1 /*
2 * Copyright (C) 2021-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 #include "device_auth.h"
17
18 #include "alg_loader.h"
19 #include "callback_manager.h"
20 #include "channel_manager.h"
21 #include "common_defs.h"
22 #include "ext_plugin_manager.h"
23 #include "group_data_manager.h"
24 #include "dev_auth_module_manager.h"
25 #include "dev_session_mgr.h"
26 #include "group_manager.h"
27 #include "group_operation_common.h"
28 #include "hc_dev_info.h"
29 #include "hc_init_protection.h"
30 #include "hc_log.h"
31 #include "hc_time.h"
32 #include "hisysevent_common.h"
33 #include "hitrace_adapter.h"
34 #include "json_utils.h"
35 #include "key_manager.h"
36 #include "os_account_adapter.h"
37 #include "plugin_adapter.h"
38 #include "pseudonym_manager.h"
39 #include "task_manager.h"
40 #include "performance_dumper.h"
41 #include "identity_manager.h"
42 #include "group_auth_manager.h"
43 #include "account_task_manager.h"
44 #include "device_auth_common.h"
45
46 #include "identity_service.h"
47 #include "cred_session_util.h"
48 #include "credential_data_manager.h"
49 #include "identity_service_defines.h"
50 #include "cache_common_event_handler.h"
51
52 #include "mini_session_manager.h"
53 #include "huks_adapter.h"
54 #include "alg_defs.h"
55 static GroupAuthManager *g_groupAuthManager = NULL;
56 static DeviceGroupManager *g_groupManagerInstance = NULL;
57 static AccountVerifier *g_accountVerifierInstance = NULL;
58 static LightAccountVerifier *g_lightAccountVerifierInstance = NULL;
59
60 static CredManager *g_credManager = NULL;
61 static CredAuthManager *g_credAuthManager = NULL;
62
63 #define CLEAN_CRED 1
64 #define CLEAN_MODULE 2
65 #define CLEAN_CALLBACK 3
66 #define CLEAN_GROUP_MANAGER 4
67 #define CLEAN_IDENTITY_SERVICE 5
68 #define CLEAN_ALL 6
69 #define CLEAN_LIGHT_SESSION_MANAGER 7
70 #define CLEAN_DEVSESSION 8
71
72 #define RETURN_RANDOM_LEN 16
73 #define RETURN_KEY_LEN 32
74
AddOriginDataForPlugin(CJson * receivedMsg,const uint8_t * data)75 static int32_t AddOriginDataForPlugin(CJson *receivedMsg, const uint8_t *data)
76 {
77 if ((receivedMsg == NULL) || (data == NULL)) {
78 LOGE("Invalid params");
79 return HC_ERR_INVALID_PARAMS;
80 }
81 return AddStringToJson(receivedMsg, FIELD_PLUGIN_EXT_DATA, (const char *)data);
82 }
83
BuildClientAuthContext(int32_t osAccountId,int64_t requestId,const char * appId,CJson * context,char ** returnPeerUdid)84 static int32_t BuildClientAuthContext(int32_t osAccountId, int64_t requestId, const char *appId, CJson *context,
85 char **returnPeerUdid)
86 {
87 const char *peerUdid = GetPeerUdidFromJson(osAccountId, context);
88 if (peerUdid != NULL) {
89 (void)DeepCopyString(peerUdid, returnPeerUdid);
90 char *deviceId = NULL;
91 if (DeepCopyString(peerUdid, &deviceId) != HC_SUCCESS) {
92 LOGE("Failed to copy peerUdid!");
93 return HC_ERR_ALLOC_MEMORY;
94 }
95 if (AddStringToJson(context, FIELD_PEER_UDID, deviceId) != HC_SUCCESS) {
96 LOGE("add peerUdid to client auth context fail.");
97 HcFree(deviceId);
98 return HC_ERR_JSON_ADD;
99 }
100 if (AddStringToJson(context, FIELD_PEER_CONN_DEVICE_ID, deviceId) != HC_SUCCESS) {
101 LOGE("add peerConnDeviceId to client auth context fail.");
102 HcFree(deviceId);
103 return HC_ERR_JSON_ADD;
104 }
105 PRINT_SENSITIVE_DATA("PeerUdid", deviceId);
106 HcFree(deviceId);
107 }
108 if (AddBoolToJson(context, FIELD_IS_BIND, false) != HC_SUCCESS) {
109 LOGE("add isBind to context fail.");
110 return HC_ERR_JSON_ADD;
111 }
112 if (AddBoolToJson(context, FIELD_IS_CLIENT, true) != HC_SUCCESS) {
113 LOGE("add isClient to context fail.");
114 return HC_ERR_JSON_ADD;
115 }
116 if (AddIntToJson(context, FIELD_OS_ACCOUNT_ID, osAccountId) != HC_SUCCESS) {
117 LOGE("add osAccountId to context fail.");
118 return HC_ERR_JSON_ADD;
119 }
120 if (AddInt64StringToJson(context, FIELD_REQUEST_ID, requestId) != HC_SUCCESS) {
121 LOGE("add request id to client auth context fail.");
122 return HC_ERR_JSON_ADD;
123 }
124 if (AddStringToJson(context, FIELD_APP_ID, appId) != HC_SUCCESS) {
125 LOGE("add app id to client auth context fail.");
126 return HC_ERR_JSON_ADD;
127 }
128 if (AddIntToJson(context, FIELD_OPERATION_CODE, AUTH_FORM_ACCOUNT_UNRELATED) != HC_SUCCESS) {
129 LOGE("add operation code to client auth context fail.");
130 return HC_ERR_JSON_ADD;
131 }
132 return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context);
133 }
134
BuildP2PBindContext(CJson * context)135 static int32_t BuildP2PBindContext(CJson *context)
136 {
137 int32_t acquireType = -1;
138 if (GetIntFromJson(context, FIELD_ACQURIED_TYPE, &acquireType) != HC_SUCCESS) {
139 LOGE("Failed to get acquireType from reqJsonStr!");
140 return HC_ERR_JSON_FAIL;
141 }
142 if ((acquireType == P2P_BIND) && AddBoolToJson(context, FIELD_IS_DIRECT_AUTH, true) != HC_SUCCESS) {
143 LOGE("add isDirectAuth to context fail.");
144 return HC_ERR_JSON_ADD;
145 }
146 if (AddIntToJson(context, FIELD_OPERATION_CODE, acquireType) != HC_SUCCESS) {
147 LOGE("add opCode to context fail.");
148 return HC_ERR_JSON_ADD;
149 }
150 const char *serviceType = GetStringFromJson(context, FIELD_SERVICE_TYPE);
151 if (serviceType == NULL) {
152 if ((acquireType == P2P_BIND) &&
153 AddStringToJson(context, FIELD_SERVICE_TYPE, DEFAULT_SERVICE_TYPE) != HC_SUCCESS) {
154 LOGE("add serviceType to context fail.");
155 return HC_ERR_JSON_ADD;
156 }
157 }
158 return HC_SUCCESS;
159 }
160
AuthDeviceInner(int32_t osAccountId,int64_t authReqId,const char * authParams,const DeviceAuthCallback * gaCallback,char ** returnPeerUdid)161 static int32_t AuthDeviceInner(int32_t osAccountId, int64_t authReqId, const char *authParams,
162 const DeviceAuthCallback *gaCallback, char **returnPeerUdid)
163 {
164 SET_LOG_MODE(TRACE_MODE);
165 SET_TRACE_ID(authReqId);
166 ADD_PERFORM_DATA(authReqId, false, true, HcGetCurTimeInMillis());
167 osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
168 LOGI("Begin AuthDevice. [ReqId]: %" LOG_PUB PRId64 ", [OsAccountId]: %" LOG_PUB "d", authReqId, osAccountId);
169 if ((authParams == NULL) || (osAccountId == INVALID_OS_ACCOUNT) || (gaCallback == NULL)) {
170 LOGE("The input auth params is invalid!");
171 return HC_ERR_INVALID_PARAMS;
172 }
173 if (!CheckIsForegroundOsAccountId(osAccountId)) {
174 LOGE("This access is not from the foreground user, rejected it.");
175 return HC_ERR_CROSS_USER_ACCESS;
176 }
177 if (!IsOsAccountUnlocked(osAccountId)) {
178 LOGE("Os account is not unlocked!");
179 return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
180 }
181 CJson *context = CreateJsonFromString(authParams);
182 if (context == NULL) {
183 LOGE("Failed to create json from auth params!");
184 return HC_ERR_JSON_FAIL;
185 }
186 const char *appId = GetStringFromJson(context, FIELD_SERVICE_PKG_NAME);
187 if (appId == NULL) {
188 LOGE("get servicePkgName from context fail.");
189 FreeJson(context);
190 return HC_ERR_JSON_GET;
191 }
192 int32_t res = BuildClientAuthContext(osAccountId, authReqId, appId, context, returnPeerUdid);
193 if (res != HC_SUCCESS) {
194 FreeJson(context);
195 return res;
196 }
197 DEV_AUTH_REPORT_UE_CALL_EVENT_BY_PARAMS(osAccountId, authParams, appId, AUTH_DEV_EVENT);
198 SessionInitParams params = { context, *gaCallback };
199 res = OpenDevSession(authReqId, appId, ¶ms);
200 FreeJson(context);
201 if (res != HC_SUCCESS) {
202 LOGE("OpenDevSession fail. [Res]: %" LOG_PUB "d", res);
203 return res;
204 }
205 return PushStartSessionTask(authReqId);
206 }
207
AuthDevice(int32_t osAccountId,int64_t authReqId,const char * authParams,const DeviceAuthCallback * gaCallback)208 static int32_t AuthDevice(int32_t osAccountId, int64_t authReqId, const char *authParams,
209 const DeviceAuthCallback *gaCallback)
210 {
211 ReportBehaviorBeginEvent(false, true, authReqId);
212 char *peerUdid = NULL;
213 int32_t res = AuthDeviceInner(osAccountId, authReqId, authParams, gaCallback, &peerUdid);
214 ReportBehaviorBeginResultEvent(false, true, authReqId, peerUdid, res);
215 if (peerUdid != NULL) {
216 HcFree(peerUdid);
217 }
218 return res;
219 }
220
AddDeviceIdToJson(CJson * context,const char * peerUdid)221 static int32_t AddDeviceIdToJson(CJson *context, const char *peerUdid)
222 {
223 char *deviceId = NULL;
224 if (DeepCopyString(peerUdid, &deviceId) != HC_SUCCESS) {
225 LOGE("Failed to copy peerUdid!");
226 return HC_ERR_ALLOC_MEMORY;
227 }
228 if (AddStringToJson(context, FIELD_PEER_UDID, deviceId) != HC_SUCCESS) {
229 LOGE("add peerUdid to context fail.");
230 HcFree(deviceId);
231 return HC_ERR_JSON_ADD;
232 }
233 if (AddStringToJson(context, FIELD_PEER_CONN_DEVICE_ID, deviceId) != HC_SUCCESS) {
234 LOGE("add peerConnDeviceId to context fail.");
235 HcFree(deviceId);
236 return HC_ERR_JSON_ADD;
237 }
238 HcFree(deviceId);
239 return HC_SUCCESS;
240 }
241
BuildServerAuthContext(int64_t requestId,int32_t opCode,const char * appId,CJson * context,char ** returnPeerUdid)242 static int32_t BuildServerAuthContext(int64_t requestId, int32_t opCode, const char *appId, CJson *context,
243 char **returnPeerUdid)
244 {
245 int32_t res = CheckConfirmationExist(context);
246 if (res != HC_SUCCESS) {
247 return res;
248 }
249 res = AddOsAccountIdToContextIfValid(context);
250 if (res != HC_SUCCESS) {
251 return res;
252 }
253 int32_t osAccountId = ANY_OS_ACCOUNT;
254 (void)GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId);
255 const char *peerUdid = GetPeerUdidFromJson(osAccountId, context);
256 if (peerUdid == NULL) {
257 return HC_ERR_JSON_GET;
258 }
259 (void)DeepCopyString(peerUdid, returnPeerUdid);
260 PRINT_SENSITIVE_DATA("PeerUdid", peerUdid);
261 if (AddDeviceIdToJson(context, peerUdid) != HC_SUCCESS) {
262 LOGE("add deviceId to server auth context failed.");
263 return HC_ERR_JSON_ADD;
264 }
265 if (AddBoolToJson(context, FIELD_IS_BIND, false) != HC_SUCCESS) {
266 LOGE("add isBind to server auth context failed.");
267 return HC_ERR_JSON_ADD;
268 }
269 if (AddBoolToJson(context, FIELD_IS_CLIENT, false) != HC_SUCCESS) {
270 LOGE("add isClient to server auth context failed.");
271 return HC_ERR_JSON_ADD;
272 }
273 if (AddInt64StringToJson(context, FIELD_REQUEST_ID, requestId) != HC_SUCCESS) {
274 LOGE("add requestId to server auth context failed.");
275 return HC_ERR_JSON_ADD;
276 }
277 if (AddStringToJson(context, FIELD_APP_ID, appId) != HC_SUCCESS) {
278 LOGE("add appId to server auth context failed.");
279 return HC_ERR_JSON_ADD;
280 }
281 if (AddIntToJson(context, FIELD_OPERATION_CODE, opCode) != HC_SUCCESS) {
282 LOGE("add opCode to server auth context failed.");
283 return HC_ERR_JSON_ADD;
284 }
285 return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context);
286 }
287
BuildServerP2PAuthContext(int64_t requestId,int32_t opCode,const char * appId,CJson * context)288 static int32_t BuildServerP2PAuthContext(int64_t requestId, int32_t opCode, const char *appId, CJson *context)
289 {
290 int32_t res = CheckConfirmationExist(context);
291 if (res != HC_SUCCESS) {
292 return res;
293 }
294 res = AddOsAccountIdToContextIfValid(context);
295 if (res != HC_SUCCESS) {
296 return res;
297 }
298 const char *peerUdid = GetStringFromJson(context, FIELD_PEER_CONN_DEVICE_ID);
299 const char *pinCode = GetStringFromJson(context, FIELD_PIN_CODE);
300 if (peerUdid == NULL && pinCode == NULL) {
301 LOGE("need peerConnDeviceId or pinCode!");
302 return HC_ERR_JSON_GET;
303 }
304 if (peerUdid != NULL) {
305 PRINT_SENSITIVE_DATA("PeerUdid", peerUdid);
306 if (AddDeviceIdToJson(context, peerUdid) != HC_SUCCESS) {
307 LOGE("add deviceId to context fail.");
308 return HC_ERR_JSON_ADD;
309 }
310 }
311 if (AddBoolToJson(context, FIELD_IS_SINGLE_CRED, true) != HC_SUCCESS) {
312 LOGE("add isSingleCred to context fail.");
313 return HC_ERR_JSON_ADD;
314 }
315 if (AddBoolToJson(context, FIELD_IS_BIND, false) != HC_SUCCESS) {
316 LOGE("add isBind to context fail.");
317 return HC_ERR_JSON_ADD;
318 }
319 if (AddBoolToJson(context, FIELD_IS_CLIENT, false) != HC_SUCCESS) {
320 LOGE("add isClient to context fail.");
321 return HC_ERR_JSON_ADD;
322 }
323 if (AddStringToJson(context, FIELD_APP_ID, appId) != HC_SUCCESS) {
324 LOGE("add appId to context fail.");
325 return HC_ERR_JSON_ADD;
326 }
327 if (AddInt64StringToJson(context, FIELD_REQUEST_ID, requestId) != HC_SUCCESS) {
328 LOGE("add requestId to context fail.");
329 return HC_ERR_JSON_ADD;
330 }
331 if (AddIntToJson(context, FIELD_OPERATION_CODE, opCode) != HC_SUCCESS) {
332 LOGE("add opCode to context fail.");
333 return HC_ERR_JSON_ADD;
334 }
335 return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context);
336 }
337
OpenServerAuthSession(int64_t requestId,const CJson * receivedMsg,const DeviceAuthCallback * callback,char ** returnPeerUdid)338 static int32_t OpenServerAuthSession(int64_t requestId, const CJson *receivedMsg, const DeviceAuthCallback *callback,
339 char **returnPeerUdid)
340 {
341 int32_t opCode = AUTH_FORM_ACCOUNT_UNRELATED;
342 if (GetIntFromJson(receivedMsg, FIELD_AUTH_FORM, &opCode) != HC_SUCCESS) {
343 if (GetIntFromJson(receivedMsg, FIELD_OP_CODE, &opCode) != HC_SUCCESS) {
344 LOGW("Use default opCode.");
345 opCode = AUTH_FORM_INVALID_TYPE;
346 }
347 }
348 char *returnDataStr = ProcessRequestCallback(requestId, opCode, NULL, callback);
349 if (returnDataStr == NULL) {
350 LOGE("The OnRequest callback failed!");
351 return HC_ERR_REQ_REJECTED;
352 }
353 CJson *context = CreateJsonFromString(returnDataStr);
354 FreeJsonString(returnDataStr);
355 if (context == NULL) {
356 LOGE("Failed to create server auth context json from returnDataStr!");
357 return HC_ERR_JSON_FAIL;
358 }
359 const char *appId = GetStringFromJson(context, FIELD_SERVICE_PKG_NAME);
360 if (appId == NULL) {
361 LOGE("get appId from context fail.");
362 FreeJson(context);
363 return HC_ERR_JSON_GET;
364 }
365 int32_t res = BuildServerAuthContext(requestId, opCode, appId, context, returnPeerUdid);
366 if (res != HC_SUCCESS) {
367 FreeJson(context);
368 return res;
369 }
370 SessionInitParams params = { context, *callback };
371 res = OpenDevSession(requestId, appId, ¶ms);
372 FreeJson(context);
373 return res;
374 }
375
OpenServerAuthSessionForP2P(int64_t requestId,const CJson * receivedMsg,const DeviceAuthCallback * callback)376 static int32_t OpenServerAuthSessionForP2P(
377 int64_t requestId, const CJson *receivedMsg, const DeviceAuthCallback *callback)
378 {
379 int32_t opCode = P2P_BIND;
380 if (GetIntFromJson(receivedMsg, FIELD_OP_CODE, &opCode) != HC_SUCCESS) {
381 opCode = P2P_BIND;
382 LOGW("use default opCode.");
383 }
384 char *returnDataStr = ProcessRequestCallback(requestId, opCode, NULL, callback);
385 if (returnDataStr == NULL) {
386 LOGE("The OnRequest callback is fail!");
387 return HC_ERR_REQ_REJECTED;
388 }
389 CJson *context = CreateJsonFromString(returnDataStr);
390 FreeJsonString(returnDataStr);
391 if (context == NULL) {
392 LOGE("Failed to create server auth context from string!");
393 return HC_ERR_JSON_FAIL;
394 }
395 if (AddBoolToJson(context, FIELD_IS_DIRECT_AUTH, true) != HC_SUCCESS) {
396 LOGE("Failed to add isDirectAuth to context!");
397 FreeJson(context);
398 return HC_ERR_JSON_ADD;
399 }
400 const char *pkgName = GetStringFromJson(context, FIELD_SERVICE_PKG_NAME);
401 if (pkgName == NULL && AddStringToJson(context, FIELD_SERVICE_PKG_NAME, DEFAULT_PACKAGE_NAME) != HC_SUCCESS) {
402 LOGE("Failed to add default package name to server auth context!");
403 FreeJson(context);
404 return HC_ERR_JSON_ADD;
405 }
406 const char *serviceType = GetStringFromJson(context, FIELD_SERVICE_TYPE);
407 if (serviceType == NULL && AddStringToJson(context, FIELD_SERVICE_TYPE, DEFAULT_SERVICE_TYPE) != HC_SUCCESS) {
408 LOGE("Failed to add default package name to server auth context!");
409 FreeJson(context);
410 return HC_ERR_JSON_ADD;
411 }
412 const char *appId = pkgName != NULL ? pkgName : DEFAULT_PACKAGE_NAME;
413 int32_t res = BuildServerP2PAuthContext(requestId, opCode, appId, context);
414 if (res != HC_SUCCESS) {
415 FreeJson(context);
416 return res;
417 }
418 SessionInitParams params = { context, *callback };
419 res = OpenDevSession(requestId, appId, ¶ms);
420 FreeJson(context);
421 return res;
422 }
423
ProcessDataInner(int64_t authReqId,const uint8_t * data,uint32_t dataLen,const DeviceAuthCallback * gaCallback,char ** returnPeerUdid)424 static int32_t ProcessDataInner(int64_t authReqId, const uint8_t *data, uint32_t dataLen,
425 const DeviceAuthCallback *gaCallback, char **returnPeerUdid)
426 {
427 SET_LOG_MODE(TRACE_MODE);
428 SET_TRACE_ID(authReqId);
429 if (!IsSessionExist(authReqId)) {
430 ADD_PERFORM_DATA(authReqId, false, false, HcGetCurTimeInMillis());
431 } else {
432 UPDATE_PERFORM_DATA_BY_SELF_INDEX(authReqId, HcGetCurTimeInMillis());
433 }
434 LOGI("[GA] Begin ProcessData. [DataLen]: %" LOG_PUB "u, [ReqId]: %" LOG_PUB PRId64, dataLen, authReqId);
435 if ((data == NULL) || (dataLen > MAX_DATA_BUFFER_SIZE)) {
436 LOGE("Invalid input for ProcessData!");
437 return HC_ERR_INVALID_PARAMS;
438 }
439 CJson *receivedMsg = CreateJsonFromString((const char *)data);
440 if (receivedMsg == NULL) {
441 LOGE("Failed to create json from string!");
442 return HC_ERR_JSON_FAIL;
443 }
444 int32_t res;
445 if (!IsSessionExist(authReqId)) {
446 res = OpenServerAuthSession(authReqId, receivedMsg, gaCallback, returnPeerUdid);
447 if (res != HC_SUCCESS) {
448 FreeJson(receivedMsg);
449 return res;
450 }
451 }
452 if (HasAccountPlugin()) {
453 res = AddOriginDataForPlugin(receivedMsg, data);
454 if (res != HC_SUCCESS) {
455 FreeJson(receivedMsg);
456 return res;
457 }
458 }
459 res = PushProcSessionTask(authReqId, receivedMsg);
460 if (res != HC_SUCCESS) {
461 FreeJson(receivedMsg);
462 return res;
463 }
464 return HC_SUCCESS;
465 }
466
ProcessData(int64_t authReqId,const uint8_t * data,uint32_t dataLen,const DeviceAuthCallback * gaCallback)467 static int32_t ProcessData(int64_t authReqId, const uint8_t *data, uint32_t dataLen,
468 const DeviceAuthCallback *gaCallback)
469 {
470 bool isSessionExist = IsSessionExist(authReqId);
471 if (!isSessionExist) {
472 ReportBehaviorBeginEvent(false, false, authReqId);
473 }
474 char *peerUdid = NULL;
475 int32_t res = ProcessDataInner(authReqId, data, dataLen, gaCallback, &peerUdid);
476 if (!isSessionExist) {
477 ReportBehaviorBeginResultEvent(false, false, authReqId, peerUdid, res);
478 }
479 if (peerUdid != NULL) {
480 HcFree(peerUdid);
481 }
482 return res;
483 }
484
OpenServerCredSession(int64_t requestId,const CJson * receivedMsg,const DeviceAuthCallback * callback,char ** returnPeerUdid)485 static int32_t OpenServerCredSession(int64_t requestId, const CJson *receivedMsg, const DeviceAuthCallback *callback,
486 char **returnPeerUdid)
487 {
488 int32_t opCode = AUTH_FORM_ACCOUNT_UNRELATED;
489 if (GetIntFromJson(receivedMsg, FIELD_AUTH_FORM, &opCode) != HC_SUCCESS) {
490 if (GetIntFromJson(receivedMsg, FIELD_OP_CODE, &opCode) != HC_SUCCESS) {
491 opCode = AUTH_FORM_INVALID_TYPE;
492 LOGW("use default opCode.");
493 }
494 }
495 char *returnDataStr = ProcessRequestCallback(requestId, opCode, NULL, callback);
496 if (returnDataStr == NULL) {
497 LOGE("The OnRequest callback is fail!");
498 return HC_ERR_REQ_REJECTED;
499 }
500 CJson *context = CreateJsonFromString(returnDataStr);
501 FreeJsonString(returnDataStr);
502 if (context == NULL) {
503 LOGE("Failed to create context from string!");
504 return HC_ERR_JSON_FAIL;
505 }
506 if (AddIntToJson(context, FIELD_OPERATION_CODE, opCode) != HC_SUCCESS) {
507 LOGE("add opCode to context fail.");
508 FreeJson(context);
509 return HC_ERR_JSON_ADD;
510 }
511 const char *appId = NULL;
512 int32_t res = BuildServerCredContext(requestId, context, returnPeerUdid, &appId);
513 if (res != HC_SUCCESS) {
514 FreeJson(context);
515 return res;
516 }
517 SessionInitParams params = { context, *callback };
518 res = OpenDevSession(requestId, appId, ¶ms);
519 FreeJson(context);
520 return res;
521 }
522
AuthCredentialInner(int32_t osAccountId,int64_t authReqId,const char * authParams,const DeviceAuthCallback * caCallback,char ** returnPeerUdid)523 static int32_t AuthCredentialInner(int32_t osAccountId, int64_t authReqId, const char *authParams,
524 const DeviceAuthCallback *caCallback, char **returnPeerUdid)
525 {
526 SET_LOG_MODE(TRACE_MODE);
527 SET_TRACE_ID(authReqId);
528 ADD_PERFORM_DATA(authReqId, false, true, HcGetCurTimeInMillis());
529 LOGI("Begin AuthCredential. [ReqId]: %" LOG_PUB PRId64 ", [OsAccountId]: %" LOG_PUB "d", authReqId, osAccountId);
530 if (authParams == NULL || osAccountId == INVALID_OS_ACCOUNT || caCallback == NULL ||
531 returnPeerUdid == NULL) {
532 LOGE("The input auth cred params is invalid!");
533 return HC_ERR_INVALID_PARAMS;
534 }
535 if (!CheckIsForegroundOsAccountId(osAccountId)) {
536 LOGE("This access is not from the foreground user, rejected it.");
537 return HC_ERR_CROSS_USER_ACCESS;
538 }
539 if (!IsOsAccountUnlocked(osAccountId)) {
540 LOGE("Os account is not unlocked! Please unlock it first.");
541 return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED;
542 }
543 CJson *context = CreateJsonFromString(authParams);
544 if (context == NULL) {
545 LOGE("Failed to create json from string!");
546 return HC_ERR_JSON_FAIL;
547 }
548 const char *appId = NULL;
549 int32_t res = BuildClientCredContext(osAccountId, authReqId, context, &appId);
550 if (res != HC_SUCCESS) {
551 FreeJson(context);
552 return res;
553 }
554 SessionInitParams params = { context, *caCallback };
555 res = OpenDevSession(authReqId, appId, ¶ms);
556 FreeJson(context);
557 if (res != HC_SUCCESS) {
558 LOGE("OpenDevSession fail. [Res]: %" LOG_PUB "d", res);
559 return res;
560 }
561 return PushStartSessionTask(authReqId);
562 }
563
AuthCredential(int32_t osAccountId,int64_t authReqId,const char * authParams,const DeviceAuthCallback * caCallback)564 int32_t AuthCredential(int32_t osAccountId, int64_t authReqId, const char *authParams,
565 const DeviceAuthCallback *caCallback)
566 {
567 char *peerUdid = NULL;
568 int32_t res = AuthCredentialInner(osAccountId, authReqId, authParams, caCallback, &peerUdid);
569 if (peerUdid != NULL) {
570 HcFree(peerUdid);
571 }
572 return res;
573 }
574
ProcessCredDataInner(int64_t authReqId,const uint8_t * data,uint32_t dataLen,const DeviceAuthCallback * caCallback,char ** returnPeerUdid)575 static int32_t ProcessCredDataInner(int64_t authReqId, const uint8_t *data, uint32_t dataLen,
576 const DeviceAuthCallback *caCallback, char **returnPeerUdid)
577 {
578 SET_LOG_MODE(TRACE_MODE);
579 SET_TRACE_ID(authReqId);
580 if (!IsSessionExist(authReqId)) {
581 ADD_PERFORM_DATA(authReqId, false, false, HcGetCurTimeInMillis());
582 } else {
583 UPDATE_PERFORM_DATA_BY_SELF_INDEX(authReqId, HcGetCurTimeInMillis());
584 }
585 LOGI("[GA] Begin ProcessCredData. [DataLen]: %" LOG_PUB "u, [ReqId]: %" LOG_PUB PRId64, dataLen, authReqId);
586 if ((data == NULL) || (dataLen > MAX_DATA_BUFFER_SIZE)) {
587 LOGE("Invalid input for ProcessCredData!");
588 return HC_ERR_INVALID_PARAMS;
589 }
590 CJson *receivedMsg = CreateJsonFromString((const char *)data);
591 if (receivedMsg == NULL) {
592 LOGE("Failed to create json from string!");
593 return HC_ERR_JSON_CREATE;
594 }
595 int32_t res;
596 if (!IsSessionExist(authReqId)) {
597 res = OpenServerCredSession(authReqId, receivedMsg, caCallback, returnPeerUdid);
598 if (res != HC_SUCCESS) {
599 FreeJson(receivedMsg);
600 return res;
601 }
602 }
603 if (HasAccountPlugin()) {
604 res = AddOriginDataForPlugin(receivedMsg, data);
605 if (res != HC_SUCCESS) {
606 FreeJson(receivedMsg);
607 LOGE("AddOriginDataForPlugin occurred error!");
608 return res;
609 }
610 }
611 res = PushProcSessionTask(authReqId, receivedMsg);
612 if (res != HC_SUCCESS) {
613 FreeJson(receivedMsg);
614 return res;
615 }
616 return HC_SUCCESS;
617 }
618
ProcessCredData(int64_t authReqId,const uint8_t * data,uint32_t dataLen,const DeviceAuthCallback * caCallback)619 static int32_t ProcessCredData(int64_t authReqId, const uint8_t *data, uint32_t dataLen,
620 const DeviceAuthCallback *caCallback)
621 {
622 char *peerUdid = NULL;
623 int32_t res = ProcessCredDataInner(authReqId, data, dataLen, caCallback, &peerUdid);
624 if (peerUdid != NULL) {
625 HcFree(peerUdid);
626 }
627 return res;
628 }
629
CancelRequest(int64_t requestId,const char * appId)630 static void CancelRequest(int64_t requestId, const char *appId)
631 {
632 SET_LOG_MODE(TRACE_MODE);
633 SET_TRACE_ID(requestId);
634 DEV_AUTH_REPORT_UE_CALL_EVENT_BY_PARAMS(DEFAULT_OS_ACCOUNT, NULL, appId, CANCEL_REQUEST_EVENT);
635 if (appId == NULL) {
636 LOGE("Invalid app id!");
637 return;
638 }
639 LOGI("cancel request. [AppId]: %" LOG_PUB "s, [ReqId]: %" LOG_PUB PRId64, appId, requestId);
640 CancelDevSession(requestId, appId);
641 }
642
GetRealInfo(int32_t osAccountId,const char * pseudonymId,char ** realInfo)643 static int32_t GetRealInfo(int32_t osAccountId, const char *pseudonymId, char **realInfo)
644 {
645 if (pseudonymId == NULL || realInfo == NULL) {
646 LOGE("Invalid params!");
647 return HC_ERR_INVALID_PARAMS;
648 }
649 PseudonymManager *pseudonymInstance = GetPseudonymInstance();
650 if (pseudonymInstance == NULL) {
651 LOGE("not support privacy enhancement!");
652 return HC_ERR_NOT_SUPPORT;
653 }
654 return pseudonymInstance->getRealInfo(osAccountId, pseudonymId, realInfo);
655 }
656
GetPseudonymId(int32_t osAccountId,const char * indexKey,char ** pseudonymId)657 static int32_t GetPseudonymId(int32_t osAccountId, const char *indexKey, char **pseudonymId)
658 {
659 if (indexKey == NULL || pseudonymId == NULL) {
660 LOGE("Invalid params!");
661 return HC_ERR_INVALID_PARAMS;
662 }
663 PseudonymManager *pseudonymInstance = GetPseudonymInstance();
664 if (pseudonymInstance == NULL) {
665 LOGE("not support privacy enhancement!");
666 return HC_ERR_NOT_SUPPORT;
667 }
668 return pseudonymInstance->getPseudonymId(osAccountId, indexKey, pseudonymId);
669 }
670
ProcessCredential(int32_t operationCode,const char * reqJsonStr,char ** returnData)671 DEVICE_AUTH_API_PUBLIC int32_t ProcessCredential(int32_t operationCode, const char *reqJsonStr, char **returnData)
672 {
673 if (reqJsonStr == NULL || returnData == NULL) {
674 LOGE("Invalid params!");
675 return HC_ERR_INVALID_PARAMS;
676 }
677
678 const CredentialOperator *credOperator = GetCredentialOperator();
679 if (credOperator == NULL) {
680 LOGE("credOperator is null!");
681 return HC_ERR_NOT_SUPPORT;
682 }
683
684 int32_t res = HC_ERR_UNSUPPORTED_OPCODE;
685 switch (operationCode) {
686 case CRED_OP_QUERY:
687 res = credOperator->queryCredential(reqJsonStr, returnData);
688 break;
689 case CRED_OP_CREATE:
690 res = credOperator->genarateCredential(reqJsonStr, returnData);
691 break;
692 case CRED_OP_IMPORT:
693 res = credOperator->importCredential(reqJsonStr, returnData);
694 break;
695 case CRED_OP_DELETE:
696 res = credOperator->deleteCredential(reqJsonStr, returnData);
697 break;
698 default:
699 LOGE("invalid opCode: %" LOG_PUB "d", operationCode);
700 break;
701 }
702
703 return res;
704 }
705
ProcessAuthDevice(int64_t authReqId,const char * authParams,const DeviceAuthCallback * callback)706 DEVICE_AUTH_API_PUBLIC int32_t ProcessAuthDevice(
707 int64_t authReqId, const char *authParams, const DeviceAuthCallback *callback)
708 {
709 SET_LOG_MODE(TRACE_MODE);
710 SET_TRACE_ID(authReqId);
711 LOGI("[DA] Begin ProcessAuthDevice [ReqId]: %" LOG_PUB PRId64, authReqId);
712 if (authParams == NULL || HcStrlen(authParams) > MAX_DATA_BUFFER_SIZE) {
713 LOGE("Invalid input for ProcessData!");
714 return HC_ERR_INVALID_PARAMS;
715 }
716 CJson *json = CreateJsonFromString(authParams);
717 if (json == NULL) {
718 LOGE("Failed to create json from string!");
719 return HC_ERR_JSON_FAIL;
720 }
721 const char *data = GetStringFromJson(json, "data");
722 if (data == NULL) {
723 LOGE("Failed to get received data from parameter!");
724 FreeJson(json);
725 return HC_ERR_INVALID_PARAMS;
726 }
727 CJson *receivedMsg = CreateJsonFromString(data);
728 FreeJson(json);
729 if (receivedMsg == NULL) {
730 LOGE("Failed to create json from string!");
731 return HC_ERR_JSON_FAIL;
732 }
733 int32_t res;
734 if (!IsSessionExist(authReqId)) {
735 res = OpenServerAuthSessionForP2P(authReqId, receivedMsg, callback);
736 if (res != HC_SUCCESS) {
737 FreeJson(receivedMsg);
738 return res;
739 }
740 }
741 res = PushProcSessionTask(authReqId, receivedMsg);
742 if (res != HC_SUCCESS) {
743 FreeJson(receivedMsg);
744 return res;
745 }
746 return HC_SUCCESS;
747 }
748
StartAuthDevice(int64_t authReqId,const char * authParams,const DeviceAuthCallback * callback)749 DEVICE_AUTH_API_PUBLIC int32_t StartAuthDevice(
750 int64_t authReqId, const char *authParams, const DeviceAuthCallback *callback)
751 {
752 SET_LOG_MODE(TRACE_MODE);
753 SET_TRACE_ID(authReqId);
754 LOGI("StartAuthDevice. [ReqId]:%" LOG_PUB PRId64, authReqId);
755
756 if ((authParams == NULL) || (callback == NULL) || HcStrlen(authParams) > MAX_DATA_BUFFER_SIZE) {
757 LOGE("The input auth params is invalid!");
758 return HC_ERR_INVALID_PARAMS;
759 }
760 CJson *context = CreateJsonFromString(authParams);
761 if (context == NULL) {
762 LOGE("Failed to create json from string!");
763 return HC_ERR_JSON_FAIL;
764 }
765 int32_t osAccountId = INVALID_OS_ACCOUNT;
766 if (GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) {
767 LOGE("Failed to get osAccountId from json!");
768 FreeJson(context);
769 return HC_ERR_JSON_FAIL;
770 }
771 osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId);
772 if (osAccountId == INVALID_OS_ACCOUNT) {
773 FreeJson(context);
774 return HC_ERR_INVALID_PARAMS;
775 }
776 if (!CheckIsForegroundOsAccountId(osAccountId)) {
777 FreeJson(context);
778 LOGE("This access is not from the foreground user, rejected it.");
779 return HC_ERR_CROSS_USER_ACCESS;
780 }
781 int32_t res = BuildClientAuthContext(osAccountId, authReqId, DEFAULT_PACKAGE_NAME, context, NULL);
782 if (res != HC_SUCCESS) {
783 FreeJson(context);
784 return res;
785 }
786 res = BuildP2PBindContext(context);
787 if (res != HC_SUCCESS) {
788 FreeJson(context);
789 return res;
790 }
791 SessionInitParams params = { context, *callback };
792 res = OpenDevSession(authReqId, DEFAULT_PACKAGE_NAME, ¶ms);
793 FreeJson(context);
794 if (res != HC_SUCCESS) {
795 LOGE("OpenDevSession fail. [Res]: %" LOG_PUB "d", res);
796 return res;
797 }
798 return PushStartSessionTask(authReqId);
799 }
800
CancelAuthRequest(int64_t requestId,const char * authParams)801 DEVICE_AUTH_API_PUBLIC int32_t CancelAuthRequest(int64_t requestId, const char *authParams)
802 {
803 SET_LOG_MODE(TRACE_MODE);
804 SET_TRACE_ID(requestId);
805 if (authParams == NULL || HcStrlen(authParams) > MAX_DATA_BUFFER_SIZE) {
806 LOGE("Invalid authParams!");
807 return HC_ERR_INVALID_PARAMS;
808 }
809 LOGI("cancel request. [ReqId]: %" LOG_PUB PRId64, requestId);
810 CancelDevSession(requestId, DEFAULT_PACKAGE_NAME);
811 return HC_SUCCESS;
812 }
813
AllocGmAndGa(void)814 static int32_t AllocGmAndGa(void)
815 {
816 if (g_groupManagerInstance == NULL) {
817 g_groupManagerInstance = (DeviceGroupManager *)HcMalloc(sizeof(DeviceGroupManager), 0);
818 if (g_groupManagerInstance == NULL) {
819 LOGE("Failed to allocate groupManager Instance memory!");
820 return HC_ERR_ALLOC_MEMORY;
821 }
822 }
823 if (g_groupAuthManager == NULL) {
824 g_groupAuthManager = (GroupAuthManager *)HcMalloc(sizeof(GroupAuthManager), 0);
825 if (g_groupAuthManager == NULL) {
826 LOGE("Failed to allocate groupAuth Instance memory!");
827 HcFree(g_groupManagerInstance);
828 g_groupManagerInstance = NULL;
829 return HC_ERR_ALLOC_MEMORY;
830 }
831 }
832 if (g_accountVerifierInstance == NULL) {
833 g_accountVerifierInstance = (AccountVerifier *)HcMalloc(sizeof(AccountVerifier), 0);
834 if (g_accountVerifierInstance == NULL) {
835 LOGE("Failed to allocate accountVerifier Instance memory!");
836 HcFree(g_groupManagerInstance);
837 g_groupManagerInstance = NULL;
838 HcFree(g_groupAuthManager);
839 g_groupAuthManager = NULL;
840 return HC_ERR_ALLOC_MEMORY;
841 }
842 }
843 if (g_lightAccountVerifierInstance == NULL) {
844 g_lightAccountVerifierInstance = (LightAccountVerifier *)HcMalloc(sizeof(LightAccountVerifier), 0);
845 if (g_lightAccountVerifierInstance == NULL) {
846 LOGE("Failed to allocate lightAccountVerifier Instance memory!");
847 HcFree(g_groupManagerInstance);
848 g_groupManagerInstance = NULL;
849 HcFree(g_groupAuthManager);
850 g_groupAuthManager = NULL;
851 HcFree(g_accountVerifierInstance);
852 g_accountVerifierInstance = NULL;
853 return HC_ERR_ALLOC_MEMORY;
854 }
855 }
856 return HC_SUCCESS;
857 }
858
DestroyGmAndGa(void)859 static void DestroyGmAndGa(void)
860 {
861 if (g_groupAuthManager != NULL) {
862 HcFree(g_groupAuthManager);
863 g_groupAuthManager = NULL;
864 }
865 if (g_groupManagerInstance != NULL) {
866 HcFree(g_groupManagerInstance);
867 g_groupManagerInstance = NULL;
868 }
869 if (g_accountVerifierInstance != NULL) {
870 HcFree(g_accountVerifierInstance);
871 g_accountVerifierInstance = NULL;
872 }
873 if (g_lightAccountVerifierInstance != NULL) {
874 HcFree(g_lightAccountVerifierInstance);
875 g_lightAccountVerifierInstance = NULL;
876 }
877 }
878
AllocCredentialMgr(void)879 static int32_t AllocCredentialMgr(void)
880 {
881 if (g_credManager == NULL) {
882 g_credManager = (CredManager *)HcMalloc(sizeof(CredManager), 0);
883 if (g_credManager == NULL) {
884 LOGE("Failed to allocate g_credManager Instance memory!");
885 return HC_ERR_ALLOC_MEMORY;
886 }
887 }
888 return HC_SUCCESS;
889 }
890
DestroyCredentialMgr(void)891 static void DestroyCredentialMgr(void)
892 {
893 if (g_credManager != NULL) {
894 HcFree(g_credManager);
895 g_credManager = NULL;
896 }
897 }
898
AllocCa(void)899 static int32_t AllocCa(void)
900 {
901 if (g_credAuthManager == NULL) {
902 g_credAuthManager = (CredAuthManager *)HcMalloc(sizeof(CredAuthManager), 0);
903 if (g_credAuthManager == NULL) {
904 LOGE("Failed to allocate groupManager Instance memory!");
905 return HC_ERR_ALLOC_MEMORY;
906 }
907 }
908 return HC_SUCCESS;
909 }
910
DestroyCa(void)911 static void DestroyCa(void)
912 {
913 if (g_credAuthManager != NULL) {
914 HcFree(g_credAuthManager);
915 g_credAuthManager = NULL;
916 }
917 }
918
CleanAllModules(int32_t type)919 static void CleanAllModules(int32_t type)
920 {
921 switch (type) {
922 case CLEAN_ALL:
923 DestroyTaskManager();
924 // fallthrough
925 case CLEAN_DEVSESSION:
926 DestroyDevSessionManager();
927 // fallthrough
928 case CLEAN_IDENTITY_SERVICE:
929 DestroyIdentityService();
930 // fallthrough
931 case CLEAN_GROUP_MANAGER:
932 DestroyGroupManager();
933 // fallthrough
934 case CLEAN_CALLBACK:
935 DestroyCallbackManager();
936 // fallthrough
937 case CLEAN_MODULE:
938 DestroyModules();
939 // fallthrough
940 case CLEAN_CRED:
941 DestroyCredMgr();
942 // fallthrough
943 case CLEAN_LIGHT_SESSION_MANAGER:
944 DestroyLightSessionManager();
945 // fallthrough
946 default:
947 break;
948 }
949 }
950
InitAllModules(void)951 static int32_t InitAllModules(void)
952 {
953 int32_t res = GetLoaderInstance()->initAlg();
954 if (res != HC_SUCCESS) {
955 LOGE("[End]: [Service]: Failed to init algorithm module!");
956 return res;
957 }
958 do {
959 if ((res = InitCredMgr()) != HC_SUCCESS) {
960 LOGE("[End]: [Service]: Failed to init cred mgr!");
961 break;
962 }
963 if ((res = InitModules()) != HC_SUCCESS) {
964 LOGE("[End]: [Service]: Failed to init all authenticator modules!");
965 CleanAllModules(CLEAN_CRED);
966 break;
967 }
968 if ((res = InitCallbackManager()) != HC_SUCCESS) {
969 LOGE("[End]: [Service]: Failed to init callback manage module!");
970 CleanAllModules(CLEAN_MODULE);
971 break;
972 }
973 if ((res = InitGroupManager()) != HC_SUCCESS) {
974 LOGE("[End]: [Service]: Failed to init group manage module!");
975 CleanAllModules(CLEAN_CALLBACK);
976 break;
977 }
978 if ((res = InitIdentityService()) != HC_SUCCESS) {
979 LOGE("[End]: [Service]: Failed to init IS module!");
980 CleanAllModules(CLEAN_GROUP_MANAGER);
981 break;
982 }
983 if ((res = InitDevSessionManager()) != HC_SUCCESS) {
984 LOGE("[End]: [Service]: Failed to init dev session manager module!");
985 CleanAllModules(CLEAN_IDENTITY_SERVICE);
986 break;
987 }
988 (void)InitGroupAuthManager();
989 if ((res = InitTaskManager()) != HC_SUCCESS) {
990 LOGE("[End]: [Service]: Failed to init worker thread!");
991 CleanAllModules(CLEAN_DEVSESSION);
992 break;
993 }
994 if ((res = InitLightSessionManager()) != HC_SUCCESS) {
995 LOGE("[End]: [Service]: Failed to init light session manager!");
996 CleanAllModules(CLEAN_ALL);
997 break;
998 }
999 } while (0);
1000 return res;
1001 }
1002
InitPseudonymModule(void)1003 static void InitPseudonymModule(void)
1004 {
1005 PseudonymManager *manager = GetPseudonymInstance();
1006 if (manager == NULL) {
1007 LOGE("Pseudonym manager is null!");
1008 return;
1009 }
1010 manager->loadPseudonymData();
1011 }
1012
InitDeviceAuthService(void)1013 DEVICE_AUTH_API_PUBLIC int InitDeviceAuthService(void)
1014 {
1015 LOGI("[Service]: Start to init device auth service!");
1016 if (CheckInit() == FINISH_INIT) {
1017 LOGI("[End]: [Service]: Device auth service is running!");
1018 return HC_SUCCESS;
1019 }
1020 int32_t res = AllocGmAndGa();
1021 if (res != HC_SUCCESS) {
1022 return res;
1023 }
1024 res = AllocCa();
1025 if (res != HC_SUCCESS) {
1026 DestroyGmAndGa();
1027 return res;
1028 }
1029 res = AllocCredentialMgr();
1030 if (res != HC_SUCCESS) {
1031 DestroyCa();
1032 DestroyGmAndGa();
1033 return res;
1034 }
1035 InitOsAccountAdapter();
1036 res = InitAllModules();
1037 if (res != HC_SUCCESS) {
1038 DestroyCredentialMgr();
1039 DestroyCa();
1040 DestroyGmAndGa();
1041 return res;
1042 }
1043 INIT_PERFORMANCE_DUMPER();
1044 InitPseudonymModule();
1045 InitAccountTaskManager();
1046 SetInitStatus();
1047 HandleCacheCommonEvent();
1048 LOGI("[End]: [Service]: Init device auth service successfully!");
1049 return HC_SUCCESS;
1050 }
1051
DestroyDeviceAuthService(void)1052 DEVICE_AUTH_API_PUBLIC void DestroyDeviceAuthService(void)
1053 {
1054 LOGI("[Service]: Start to destroy device auth service!");
1055 if (CheckDestroy() == FINISH_DESTROY) {
1056 LOGI("[End]: [Service]: The service has not been initialized!");
1057 return;
1058 }
1059 DestroyLightSessionManager();
1060 DestroyTaskManager();
1061 DestroyDevSessionManager();
1062 DestroyIdentityService();
1063 DestroyGroupManager();
1064 DestroyGmAndGa();
1065 DestroyAccountTaskManager();
1066 DestroyCa();
1067 DestroyCredentialMgr();
1068 DestroyModules();
1069 DestroyCredMgr();
1070 DestroyChannelManager();
1071 DestroyCallbackManager();
1072 DESTROY_PERFORMANCE_DUMPER();
1073 DestroyPseudonymManager();
1074 DestroyOsAccountAdapter();
1075 SetDeInitStatus();
1076 LOGI("[End]: [Service]: Destroy device auth service successfully!");
1077 }
1078
GetGmInstance(void)1079 DEVICE_AUTH_API_PUBLIC const DeviceGroupManager *GetGmInstance(void)
1080 {
1081 if (g_groupManagerInstance == NULL) {
1082 LOGE("Service not init.");
1083 return NULL;
1084 }
1085
1086 g_groupManagerInstance->regCallback = RegCallbackImpl;
1087 g_groupManagerInstance->unRegCallback = UnRegCallbackImpl;
1088 g_groupManagerInstance->regDataChangeListener = RegListenerImpl;
1089 g_groupManagerInstance->unRegDataChangeListener = UnRegListenerImpl;
1090 g_groupManagerInstance->createGroup = CreateGroupImpl;
1091 g_groupManagerInstance->deleteGroup = DeleteGroupImpl;
1092 g_groupManagerInstance->addMemberToGroup = AddMemberToGroupImpl;
1093 g_groupManagerInstance->deleteMemberFromGroup = DeleteMemberFromGroupImpl;
1094 g_groupManagerInstance->addMultiMembersToGroup = AddMultiMembersToGroupImpl;
1095 g_groupManagerInstance->delMultiMembersFromGroup = DelMultiMembersFromGroupImpl;
1096 g_groupManagerInstance->processData = ProcessBindDataImpl;
1097 g_groupManagerInstance->getRegisterInfo = GetRegisterInfoImpl;
1098 g_groupManagerInstance->checkAccessToGroup = CheckAccessToGroupImpl;
1099 g_groupManagerInstance->getPkInfoList = GetPkInfoListImpl;
1100 g_groupManagerInstance->getGroupInfoById = GetGroupInfoByIdImpl;
1101 g_groupManagerInstance->getGroupInfo = GetGroupInfoImpl;
1102 g_groupManagerInstance->getJoinedGroups = GetJoinedGroupsImpl;
1103 g_groupManagerInstance->getRelatedGroups = GetRelatedGroupsImpl;
1104 g_groupManagerInstance->getDeviceInfoById = GetDeviceInfoByIdImpl;
1105 g_groupManagerInstance->getTrustedDevices = GetTrustedDevicesImpl;
1106 g_groupManagerInstance->isDeviceInGroup = IsDeviceInGroupImpl;
1107 g_groupManagerInstance->cancelRequest = CancelRequest;
1108 g_groupManagerInstance->destroyInfo = DestroyInfoImpl;
1109 return g_groupManagerInstance;
1110 }
1111
GetGaInstance(void)1112 DEVICE_AUTH_API_PUBLIC const GroupAuthManager *GetGaInstance(void)
1113 {
1114 if (g_groupAuthManager == NULL) {
1115 LOGE("Service not init.");
1116 return NULL;
1117 }
1118
1119 g_groupAuthManager->processData = ProcessData;
1120 g_groupAuthManager->authDevice = AuthDevice;
1121 g_groupAuthManager->cancelRequest = CancelRequest;
1122 g_groupAuthManager->getRealInfo = GetRealInfo;
1123 g_groupAuthManager->getPseudonymId = GetPseudonymId;
1124 return g_groupAuthManager;
1125 }
1126
GetSharedKeyFromOutJson(const CJson * out,DataBuff * returnSharedKey)1127 static int32_t GetSharedKeyFromOutJson(const CJson *out, DataBuff *returnSharedKey)
1128 {
1129 int sharedKeyLen = 0;
1130 if (GetIntFromJson(out, FIELD_ACCOUNT_SHARED_KEY_LEN, &sharedKeyLen) != HC_SUCCESS) {
1131 LOGE("Failed to get shared key len!");
1132 return HC_ERR_JSON_GET;
1133 }
1134 uint8_t *sharedKeyVal = (uint8_t *)HcMalloc(sharedKeyLen, 0);
1135 if (sharedKeyVal == NULL) {
1136 LOGE("Failed to alloc shared key!");
1137 return HC_ERR_ALLOC_MEMORY;
1138 }
1139 if (GetByteFromJson(out, FIELD_ACCOUNT_SHARED_KEY_VAL, sharedKeyVal, sharedKeyLen) != HC_SUCCESS) {
1140 LOGE("Failed to get shared key val!");
1141 HcFree(sharedKeyVal);
1142 return HC_ERR_JSON_GET;
1143 }
1144 returnSharedKey->data = sharedKeyVal;
1145 returnSharedKey->length = sharedKeyLen;
1146 return HC_SUCCESS;
1147 }
1148
GetRandomFromOutJson(const CJson * out,DataBuff * returnRandom)1149 static int32_t GetRandomFromOutJson(const CJson *out, DataBuff *returnRandom)
1150 {
1151 int randomLen = 0;
1152 if (GetIntFromJson(out, FIELD_ACCOUNT_RANDOM_LEN, &randomLen) != HC_SUCCESS) {
1153 LOGE("Failed to get random len!");
1154 return HC_ERR_JSON_GET;
1155 }
1156 uint8_t *randomVal = (uint8_t *)HcMalloc(randomLen, 0);
1157 if (randomVal == NULL) {
1158 LOGE("Failed to alloc random!");
1159 return HC_ERR_ALLOC_MEMORY;
1160 }
1161 if (GetByteFromJson(out, FIELD_ACCOUNT_RANDOM_VAL, randomVal, randomLen) != HC_SUCCESS) {
1162 LOGE("Failed to get random val!");
1163 HcFree(randomVal);
1164 return HC_ERR_JSON_GET;
1165 }
1166 returnRandom->data = randomVal;
1167 returnRandom->length = randomLen;
1168 return HC_SUCCESS;
1169 }
1170
DestroyDataBuff(DataBuff * data)1171 static void DestroyDataBuff(DataBuff *data)
1172 {
1173 if (data == NULL || data->data == NULL) {
1174 return;
1175 }
1176 HcFree(data->data);
1177 data->data = NULL;
1178 data->length = 0;
1179 }
1180
ConstructClientInJson(CJson * in,const char * peerPkWithSig,const char * serviceId)1181 static int32_t ConstructClientInJson(CJson *in, const char *peerPkWithSig, const char *serviceId)
1182 {
1183 if (AddStringToJson(in, FIELD_ACCOUNT_PEER_PK_WITH_SIG, peerPkWithSig) != HC_SUCCESS) {
1184 LOGE("Failed to add peer pk to json!");
1185 return HC_ERR_JSON_ADD;
1186 }
1187 if (AddStringToJson(in, FIELD_ACCOUNT_SERVICE_ID, serviceId) != HC_SUCCESS) {
1188 LOGE("Failed to add serviceId to json!");
1189 return HC_ERR_JSON_ADD;
1190 }
1191 return HC_SUCCESS;
1192 }
1193
GetClientSharedKey(const char * peerPkWithSig,const char * serviceId,DataBuff * returnSharedKey,DataBuff * returnRandom)1194 static int32_t GetClientSharedKey(const char *peerPkWithSig, const char *serviceId, DataBuff *returnSharedKey,
1195 DataBuff *returnRandom)
1196 {
1197 if (peerPkWithSig == NULL || serviceId == NULL || returnSharedKey == NULL || returnRandom == NULL) {
1198 LOGE("Invalid params!");
1199 return HC_ERR_INVALID_PARAMS;
1200 }
1201 CJson *in = CreateJson();
1202 if (in == NULL) {
1203 LOGE("Failed to create in json!");
1204 return HC_ERR_JSON_CREATE;
1205 }
1206 int32_t res = ConstructClientInJson(in, peerPkWithSig, serviceId);
1207 if (res != HC_SUCCESS) {
1208 FreeJson(in);
1209 return res;
1210 }
1211 CJson *out = CreateJson();
1212 if (out == NULL) {
1213 LOGE("Failed to create out json!");
1214 FreeJson(in);
1215 return HC_ERR_JSON_CREATE;
1216 }
1217 res = ExecuteAccountAuthCmd(DEFAULT_OS_ACCOUNT, ACCOUNT_GET_CLIENT_SHARED_KEY, in, out);
1218 FreeJson(in);
1219 if (res != HC_SUCCESS) {
1220 LOGE("Failed to get client shared key!");
1221 FreeJson(out);
1222 return res;
1223 }
1224 res = GetSharedKeyFromOutJson(out, returnSharedKey);
1225 if (res != HC_SUCCESS) {
1226 LOGE("Failed to get shared key from out json!");
1227 FreeJson(out);
1228 return res;
1229 }
1230
1231 res = GetRandomFromOutJson(out, returnRandom);
1232 FreeJson(out);
1233 if (res != HC_SUCCESS) {
1234 LOGE("Failed to get random from out json!");
1235 DestroyDataBuff(returnSharedKey);
1236 }
1237 return res;
1238 }
1239
ConstructServerInJson(CJson * in,const char * peerPkWithSig,const char * serviceId,const DataBuff * random)1240 static int32_t ConstructServerInJson(CJson *in, const char *peerPkWithSig, const char *serviceId,
1241 const DataBuff *random)
1242 {
1243 if (AddStringToJson(in, FIELD_ACCOUNT_PEER_PK_WITH_SIG, peerPkWithSig) != HC_SUCCESS) {
1244 LOGE("Failed to add peer pk to json!");
1245 return HC_ERR_JSON_ADD;
1246 }
1247 if (AddStringToJson(in, FIELD_ACCOUNT_SERVICE_ID, serviceId) != HC_SUCCESS) {
1248 LOGE("Failed to add serviceId to json!");
1249 return HC_ERR_JSON_ADD;
1250 }
1251 if (AddByteToJson(in, FIELD_ACCOUNT_RANDOM_VAL, random->data, random->length) != HC_SUCCESS) {
1252 LOGE("Failed to add random val to json!");
1253 return HC_ERR_JSON_ADD;
1254 }
1255 if (AddIntToJson(in, FIELD_ACCOUNT_RANDOM_LEN, random->length) != HC_SUCCESS) {
1256 LOGE("Failed to add random len to json!");
1257 return HC_ERR_JSON_ADD;
1258 }
1259 return HC_SUCCESS;
1260 }
1261
GetServerSharedKey(const char * peerPkWithSig,const char * serviceId,const DataBuff * random,DataBuff * returnSharedKey)1262 static int32_t GetServerSharedKey(const char *peerPkWithSig, const char *serviceId, const DataBuff *random,
1263 DataBuff *returnSharedKey)
1264 {
1265 if (peerPkWithSig == NULL || serviceId == NULL || random == NULL || random->data == NULL ||
1266 returnSharedKey == NULL) {
1267 LOGE("Invalid params!");
1268 return HC_ERR_INVALID_PARAMS;
1269 }
1270 CJson *in = CreateJson();
1271 if (in == NULL) {
1272 LOGE("Failed to create in json!");
1273 return HC_ERR_JSON_CREATE;
1274 }
1275 int32_t res = ConstructServerInJson(in, peerPkWithSig, serviceId, random);
1276 if (res != HC_SUCCESS) {
1277 FreeJson(in);
1278 return res;
1279 }
1280 CJson *out = CreateJson();
1281 if (out == NULL) {
1282 LOGE("Failed to create out json!");
1283 FreeJson(in);
1284 return HC_ERR_JSON_CREATE;
1285 }
1286 res = ExecuteAccountAuthCmd(DEFAULT_OS_ACCOUNT, ACCOUNT_GET_SERVER_SHARED_KEY, in, out);
1287 FreeJson(in);
1288 if (res != HC_SUCCESS) {
1289 LOGE("Failed to get server shared key!");
1290 FreeJson(out);
1291 return res;
1292 }
1293
1294 res = GetSharedKeyFromOutJson(out, returnSharedKey);
1295 FreeJson(out);
1296 if (res != HC_SUCCESS) {
1297 LOGE("Failed to get shared key from out json!");
1298 }
1299 return res;
1300 }
1301
GetRandomValFromOutJson(const CJson * out,DataBuff * returnRandom)1302 static int32_t GetRandomValFromOutJson(const CJson *out, DataBuff *returnRandom)
1303 {
1304 uint8_t *randomVal = (uint8_t *)HcMalloc(RETURN_RANDOM_LEN, 0);
1305 if (randomVal == NULL) {
1306 LOGE("Failed to alloc random!");
1307 return HC_ERR_ALLOC_MEMORY;
1308 }
1309 if (GetByteFromJson(out, FIELD_ACCOUNT_RANDOM_VAL, randomVal, RETURN_RANDOM_LEN) != HC_SUCCESS) {
1310 LOGE("Failed to get random val!");
1311 HcFree(randomVal);
1312 return HC_ERR_JSON_GET;
1313 }
1314 returnRandom->data = randomVal;
1315 returnRandom->length = RETURN_RANDOM_LEN;
1316 return HC_SUCCESS;
1317 }
1318
GetPeerRandomValFromOutJson(const CJson * out,DataBuff * returnRandom)1319 static int32_t GetPeerRandomValFromOutJson(const CJson *out, DataBuff *returnRandom)
1320 {
1321 uint8_t *randomVal = (uint8_t *)HcMalloc(RETURN_RANDOM_LEN, 0);
1322 if (randomVal == NULL) {
1323 LOGE("Failed to alloc random!");
1324 return HC_ERR_ALLOC_MEMORY;
1325 }
1326 if (GetByteFromJson(out, FIELD_PEER_ACCOUNT_RANDOM_VAL, randomVal, RETURN_RANDOM_LEN) != HC_SUCCESS) {
1327 LOGE("Failed to get random val!");
1328 HcFree(randomVal);
1329 return HC_ERR_JSON_GET;
1330 }
1331 returnRandom->data = randomVal;
1332 returnRandom->length = RETURN_RANDOM_LEN;
1333 return HC_SUCCESS;
1334 }
1335
LightAuthVerifySign(int32_t osAccountId,CJson * msg,CJson * out)1336 static int32_t LightAuthVerifySign(int32_t osAccountId, CJson *msg, CJson *out)
1337 {
1338 int32_t res = ExecuteAccountAuthCmd(osAccountId, LIGHT_ACCOUNT_AUTH_VERIFY_SIGN, msg, out);
1339 if (res != HC_SUCCESS) {
1340 LOGE("Verify sign failed");
1341 }
1342 return res;
1343 }
1344
StartLightAccountAuthInner(int32_t osAccountId,int64_t requestId,const char * serviceId,const DeviceAuthCallback * laCallBack,CJson * out)1345 static int32_t StartLightAccountAuthInner(int32_t osAccountId, int64_t requestId, const char *serviceId,
1346 const DeviceAuthCallback *laCallBack, CJson *out)
1347 {
1348 DataBuff clientRandom = { 0 };
1349 int32_t res = GetRandomValFromOutJson(out, &clientRandom);
1350 if (res != HC_SUCCESS) {
1351 LOGE("Failed to get random!");
1352 return res;
1353 }
1354 res = AddLightSession(requestId, osAccountId, serviceId, clientRandom);
1355 if (res != HC_SUCCESS) {
1356 LOGE("Failed to AddLightSession!");
1357 DestroyDataBuff(&clientRandom);
1358 return res;
1359 }
1360 char *returnMsg = PackJsonToString(out);
1361 if (returnMsg == NULL) {
1362 LOGE("pack out to string failed!");
1363 DestroyDataBuff(&clientRandom);
1364 return HC_ERR_JSON_FAIL;
1365 }
1366 ProcessTransmitCallback(requestId, (uint8_t *)returnMsg, HcStrlen(returnMsg) + 1, laCallBack);
1367 DestroyDataBuff(&clientRandom);
1368 FreeJsonString(returnMsg);
1369 return res;
1370 }
1371
StartLightAccountAuth(int32_t osAccountId,int64_t requestId,const char * serviceId,const DeviceAuthCallback * laCallBack)1372 static int32_t StartLightAccountAuth(int32_t osAccountId, int64_t requestId, const char *serviceId,
1373 const DeviceAuthCallback *laCallBack)
1374 {
1375 SET_LOG_MODE(TRACE_MODE);
1376 SET_TRACE_ID(requestId);
1377 LOGI("StartLightAccountAuth. [ReqId]:%" LOG_PUB PRId64, requestId);
1378 if ((serviceId == NULL) || (laCallBack == NULL) || HcStrlen(serviceId) > MAX_DATA_BUFFER_SIZE) {
1379 LOGE("The input auth params is invalid!");
1380 ProcessErrorCallback(requestId, AUTH_FORM_LIGHT_AUTH, HC_ERR_INVALID_PARAMS, NULL, laCallBack);
1381 return HC_ERR_INVALID_PARAMS;
1382 }
1383 CJson *out = CreateJson();
1384 if (out == NULL) {
1385 LOGE("Failed to create out json!");
1386 ProcessErrorCallback(requestId, AUTH_FORM_LIGHT_AUTH, HC_ERR_JSON_CREATE, NULL, laCallBack);
1387 return HC_ERR_JSON_CREATE;
1388 }
1389 int32_t res = ExecuteAccountAuthCmd(osAccountId, LIGHT_ACCOUNT_AUTH_START, NULL, out);
1390 if (res != HC_SUCCESS) {
1391 LOGE("Failed to start auth!");
1392 FreeJson(out);
1393 ProcessErrorCallback(requestId, AUTH_FORM_LIGHT_AUTH, res, NULL, laCallBack);
1394 return res;
1395 }
1396 res = StartLightAccountAuthInner(osAccountId, requestId, serviceId, laCallBack, out);
1397 if (res != HC_SUCCESS) {
1398 LOGE("Failed to start auth inner!");
1399 FreeJson(out);
1400 ProcessErrorCallback(requestId, AUTH_FORM_LIGHT_AUTH, res, NULL, laCallBack);
1401 return res;
1402 }
1403 FreeJson(out);
1404 return res;
1405 }
1406
ConstructSaltInner(DataBuff randomClientBuff,DataBuff randomServerBuff,uint8_t * hkdfSalt,uint32_t hkdfSaltLen)1407 static int32_t ConstructSaltInner(DataBuff randomClientBuff, DataBuff randomServerBuff,
1408 uint8_t *hkdfSalt, uint32_t hkdfSaltLen)
1409 {
1410 LOGI("ConstructSaltInner start");
1411 if (memcpy_s(hkdfSalt, hkdfSaltLen, randomClientBuff.data, randomClientBuff.length) != EOK) {
1412 LOGE("Copy randClient failed.");
1413 return HC_ERR_MEMORY_COPY;
1414 }
1415 if (memcpy_s(hkdfSalt + RETURN_RANDOM_LEN, hkdfSaltLen - RETURN_RANDOM_LEN,
1416 randomServerBuff.data, randomServerBuff.length) != EOK) {
1417 LOGE("Copy randomServer failed.");
1418 return HC_ERR_MEMORY_COPY;
1419 }
1420 return HC_SUCCESS;
1421 }
1422
GetRandomVal(CJson * out,uint8_t * randomVal,bool isClient,DataBuff * randomBuff)1423 static int32_t GetRandomVal(CJson *out, uint8_t *randomVal, bool isClient, DataBuff *randomBuff)
1424 {
1425 if (isClient) {
1426 randomBuff->data = randomVal;
1427 randomBuff->length = RETURN_RANDOM_LEN;
1428 } else {
1429 (void)randomVal;
1430 int32_t res = GetRandomValFromOutJson(out, randomBuff);
1431 if (res != HC_SUCCESS) {
1432 LOGE("Failed to get randomval");
1433 return res;
1434 }
1435 }
1436 return HC_SUCCESS;
1437 }
1438
ConstructSalt(CJson * out,uint8_t * randomVal,Uint8Buff * hkdfSaltBuf,bool isClient)1439 static int32_t ConstructSalt(CJson *out, uint8_t *randomVal, Uint8Buff *hkdfSaltBuf, bool isClient)
1440 {
1441 DataBuff randomBuff = { 0 };
1442 int32_t res = GetRandomVal(out, randomVal, isClient, &randomBuff);
1443 if (res != HC_SUCCESS) {
1444 LOGE("Failed to get random val");
1445 return res;
1446 }
1447 DataBuff peerRandomBuff = { 0 };
1448 res = GetPeerRandomValFromOutJson(out, &peerRandomBuff);
1449 if (res != HC_SUCCESS) {
1450 LOGE("Failed to get peer random val!");
1451 if (!isClient) {
1452 DestroyDataBuff(&randomBuff);
1453 }
1454 DestroyDataBuff(&peerRandomBuff);
1455 return res;
1456 }
1457 uint32_t hkdfSaltLen = RETURN_RANDOM_LEN + RETURN_RANDOM_LEN;
1458 uint8_t *hkdfSalt = (uint8_t *)HcMalloc(hkdfSaltLen, 0);
1459 if (hkdfSalt == NULL) {
1460 LOGE("Failed to alloc hkdfSalt");
1461 if (!isClient) {
1462 DestroyDataBuff(&randomBuff);
1463 }
1464 DestroyDataBuff(&peerRandomBuff);
1465 return HC_ERR_ALLOC_MEMORY;
1466 }
1467 if (isClient) {
1468 res = ConstructSaltInner(randomBuff, peerRandomBuff, hkdfSalt, hkdfSaltLen);
1469 } else {
1470 res = ConstructSaltInner(peerRandomBuff, randomBuff, hkdfSalt, hkdfSaltLen);
1471 }
1472 if (res != HC_SUCCESS) {
1473 LOGE("ConstructSaltInner failed!");
1474 if (!isClient) {
1475 DestroyDataBuff(&randomBuff);
1476 }
1477 DestroyDataBuff(&peerRandomBuff);
1478 HcFree(hkdfSalt);
1479 return res;
1480 }
1481 hkdfSaltBuf->val = hkdfSalt;
1482 hkdfSaltBuf->length = hkdfSaltLen;
1483 if (!isClient) {
1484 DestroyDataBuff(&randomBuff);
1485 }
1486 DestroyDataBuff(&peerRandomBuff);
1487 return res;
1488 }
1489
GetUserIdAndPeerUserId(CJson * out,const char ** userIdStr,const char ** peerUserIdStr)1490 static int32_t GetUserIdAndPeerUserId(CJson *out, const char **userIdStr, const char **peerUserIdStr)
1491 {
1492 *userIdStr = GetStringFromJson(out, FIELD_USER_ID);
1493 if (*userIdStr == NULL) {
1494 LOGE("get userIdStr from out fail.");
1495 return HC_ERR_JSON_GET;
1496 }
1497 *peerUserIdStr = GetStringFromJson(out, FIELD_PEER_USER_ID);
1498 if (*peerUserIdStr == NULL) {
1499 LOGE("get peer userIdStr from out fail.");
1500 return HC_ERR_JSON_GET;
1501 }
1502 return HC_SUCCESS;
1503 }
1504
CopyUserIdsToKeyInfo(uint8_t * keyInfo,uint32_t keyInfoLen,const char * clientUserIdStr,const char * serverUserIdStr)1505 static int32_t CopyUserIdsToKeyInfo(uint8_t *keyInfo, uint32_t keyInfoLen,
1506 const char *clientUserIdStr, const char *serverUserIdStr)
1507 {
1508 if (memcpy_s(keyInfo, keyInfoLen, clientUserIdStr, (uint32_t)HcStrlen(clientUserIdStr)) != EOK) {
1509 LOGE("Copy client userIdStr failed.");
1510 return HC_ERR_MEMORY_COPY;
1511 }
1512 if (memcpy_s(keyInfo + (uint32_t)HcStrlen(clientUserIdStr), keyInfoLen - (uint32_t)HcStrlen(clientUserIdStr),
1513 serverUserIdStr, (uint32_t)HcStrlen(serverUserIdStr)) != EOK) {
1514 LOGE("Copy server userIdStr failed.");
1515 return HC_ERR_MEMORY_COPY;
1516 }
1517 return HC_SUCCESS;
1518 }
1519
ConstructKeyInfo(CJson * out,const char * serviceId,Uint8Buff * keyInfoBuf,bool isClient)1520 static int32_t ConstructKeyInfo(CJson *out, const char *serviceId, Uint8Buff *keyInfoBuf, bool isClient)
1521 {
1522 const char *userIdStr = NULL;
1523 const char *peerUserIdStr = NULL;
1524 int32_t res = GetUserIdAndPeerUserId(out, &userIdStr, &peerUserIdStr);
1525 if (res != HC_SUCCESS) {
1526 LOGE("GetUserIdAndPeerUserId failed!");
1527 return res;
1528 }
1529 uint32_t serviceIdLen = (uint32_t)HcStrlen(serviceId);
1530 uint32_t keyInfoLen = (uint32_t)HcStrlen(userIdStr) + (uint32_t)HcStrlen(peerUserIdStr) + serviceIdLen;
1531 uint8_t *keyInfo = (uint8_t *)HcMalloc(keyInfoLen, 0);
1532 if (keyInfo == NULL) {
1533 LOGE("Failed to alloc keyInfo");
1534 return HC_ERR_ALLOC_MEMORY;
1535 }
1536 if (isClient) {
1537 res = CopyUserIdsToKeyInfo(keyInfo, keyInfoLen, userIdStr, peerUserIdStr);
1538 if (res != HC_SUCCESS) {
1539 LOGE("CopyUserIdsToKeyInfo failed!");
1540 HcFree(keyInfo);
1541 return res;
1542 }
1543 } else {
1544 res = CopyUserIdsToKeyInfo(keyInfo, keyInfoLen, peerUserIdStr, userIdStr);
1545 if (res != HC_SUCCESS) {
1546 LOGE("CopyUserIdsToKeyInfo failed!");
1547 HcFree(keyInfo);
1548 return res;
1549 }
1550 }
1551 if (memcpy_s(keyInfo + (uint32_t)HcStrlen(userIdStr) + (uint32_t)HcStrlen(peerUserIdStr),
1552 keyInfoLen - (uint32_t)HcStrlen(userIdStr) - (uint32_t)HcStrlen(peerUserIdStr),
1553 serviceId, serviceIdLen) != EOK) {
1554 LOGE("Copy serviceId failed.");
1555 HcFree(keyInfo);
1556 return HC_ERR_MEMORY_COPY;
1557 }
1558 keyInfoBuf->val = keyInfo;
1559 keyInfoBuf->length = keyInfoLen;
1560 return HC_SUCCESS;
1561 }
1562
ComputeHkdfKeyInner(int32_t osAccountId,CJson * out,Uint8Buff hkdfSaltBuf,Uint8Buff keyInfoBuf,Uint8Buff * returnKeyBuf)1563 static int32_t ComputeHkdfKeyInner(int32_t osAccountId, CJson *out,
1564 Uint8Buff hkdfSaltBuf, Uint8Buff keyInfoBuf, Uint8Buff *returnKeyBuf)
1565 {
1566 LOGI("ComputeHkdfKeyInner start");
1567 DataBuff sharedKey = {0};
1568 int32_t res = GetSharedKeyFromOutJson(out, &sharedKey);
1569 if (res != HC_SUCCESS) {
1570 LOGE("get sharedkey failed!");
1571 return res;
1572 }
1573 KeyParams keyParam = {
1574 .keyBuff = {sharedKey.data, sharedKey.length, false},
1575 .isDeStorage = false,
1576 .osAccountId = osAccountId
1577 };
1578 uint8_t *returnKey = (uint8_t *)HcMalloc(RETURN_KEY_LEN, 0);
1579 if (returnKey == NULL) {
1580 LOGE("Failed to alloc returnKey");
1581 DestroyDataBuff(&sharedKey);
1582 return HC_ERR_ALLOC_MEMORY;
1583 }
1584 returnKeyBuf->val = returnKey;
1585 returnKeyBuf->length = RETURN_KEY_LEN;
1586 res = GetLoaderInstance()->computeHkdf(&keyParam, &hkdfSaltBuf, &keyInfoBuf, returnKeyBuf);
1587 if (res != HC_SUCCESS) {
1588 LOGE("computeHkdf failed!");
1589 DestroyDataBuff(&sharedKey);
1590 HcFree(returnKey);
1591 return res;
1592 }
1593 DestroyDataBuff(&sharedKey);
1594 return res;
1595 }
1596
ComputeHkdfKeyClient(int32_t osAccountId,CJson * out,uint8_t * randomVal,const char * serviceId,Uint8Buff * returnKeyBuf)1597 static int32_t ComputeHkdfKeyClient(int32_t osAccountId, CJson *out, uint8_t *randomVal,
1598 const char *serviceId, Uint8Buff *returnKeyBuf)
1599 {
1600 Uint8Buff hkdfSaltBuf = {0};
1601 int32_t res = ConstructSalt(out, randomVal, &hkdfSaltBuf, true);
1602 if (res != HC_SUCCESS) {
1603 LOGE("ConstructSalt failed!");
1604 return res;
1605 }
1606 Uint8Buff keyInfoBuf = {0};
1607 res = ConstructKeyInfo(out, serviceId, &keyInfoBuf, true);
1608 if (res != HC_SUCCESS) {
1609 LOGE("ConstructKeyInfo failed!");
1610 HcFree(hkdfSaltBuf.val);
1611 return res;
1612 }
1613 res = ComputeHkdfKeyInner(osAccountId, out, hkdfSaltBuf, keyInfoBuf, returnKeyBuf);
1614 HcFree(hkdfSaltBuf.val);
1615 HcFree(keyInfoBuf.val);
1616 if (res != HC_SUCCESS) {
1617 LOGE("ComputeHkdfKeyInner failed!");
1618 return res;
1619 }
1620 return res;
1621 }
1622
ComputeHkdfKeyServer(int32_t osAccountId,CJson * out,uint8_t * randomVal,const char * serviceId,Uint8Buff * returnKeyBuf)1623 static int32_t ComputeHkdfKeyServer(int32_t osAccountId, CJson *out, uint8_t *randomVal,
1624 const char *serviceId, Uint8Buff *returnKeyBuf)
1625 {
1626 Uint8Buff hkdfSaltBuf = {0};
1627 int32_t res = ConstructSalt(out, randomVal, &hkdfSaltBuf, false);
1628 if (res != HC_SUCCESS) {
1629 LOGE("ConstructSalt failed!");
1630 return res;
1631 }
1632 Uint8Buff keyInfoBuf = {0};
1633 res = ConstructKeyInfo(out, serviceId, &keyInfoBuf, false);
1634 if (res != HC_SUCCESS) {
1635 LOGE("ConstructKeyInfo failed!");
1636 HcFree(hkdfSaltBuf.val);
1637 return res;
1638 }
1639 res = ComputeHkdfKeyInner(osAccountId, out, hkdfSaltBuf, keyInfoBuf, returnKeyBuf);
1640 if (res != HC_SUCCESS) {
1641 LOGE("ComputeHkdfKeyInner failed!");
1642 HcFree(hkdfSaltBuf.val);
1643 HcFree(keyInfoBuf.val);
1644 return res;
1645 }
1646 HcFree(hkdfSaltBuf.val);
1647 HcFree(keyInfoBuf.val);
1648 return res;
1649 }
1650
LightAuthOnFinish(int64_t requestId,CJson * out,const DeviceAuthCallback * laCallBack)1651 static int32_t LightAuthOnFinish(int64_t requestId, CJson *out, const DeviceAuthCallback *laCallBack)
1652 {
1653 CJson *outData = CreateJson();
1654 if (outData == NULL) {
1655 LOGE("Create outData failed!");
1656 return HC_ERR_JSON_CREATE;
1657 }
1658 const char *peerUserIdStr = GetStringFromJson(out, FIELD_PEER_USER_ID);
1659 if (peerUserIdStr == NULL) {
1660 LOGE("get peerUserIdStr from out failed!");
1661 FreeJson(outData);
1662 return HC_ERR_JSON_GET;
1663 }
1664 int32_t res = AddStringToJson(outData, FIELD_PEER_USER_ID, peerUserIdStr);
1665 if (res != HC_SUCCESS) {
1666 LOGE("add peer userid failed!");
1667 FreeJson(outData);
1668 return res;
1669 }
1670 char *returnFinishData = PackJsonToString(outData);
1671 if (returnFinishData == NULL) {
1672 LOGE("PackJsonToString failed!");
1673 FreeJson(outData);
1674 return HC_ERR_JSON_FAIL;
1675 }
1676 int32_t opCode = AUTH_FORM_LIGHT_AUTH;
1677 ProcessFinishCallback(requestId, opCode, returnFinishData, laCallBack);
1678 FreeJsonString(returnFinishData);
1679 return HC_SUCCESS;
1680 }
1681
DestroyLightSessionReturnData(LightSessionReturnData * lightSessionReturnData)1682 static void DestroyLightSessionReturnData(LightSessionReturnData *lightSessionReturnData)
1683 {
1684 if (lightSessionReturnData == NULL) {
1685 return;
1686 }
1687 if (lightSessionReturnData->serviceId != NULL) {
1688 HcFree(lightSessionReturnData->serviceId);
1689 }
1690 if (lightSessionReturnData->randomVal != NULL) {
1691 HcFree(lightSessionReturnData->randomVal);
1692 }
1693 HcFree(lightSessionReturnData);
1694 return;
1695 }
1696
ProcessLightAccountAuthClient(int64_t requestId,int32_t osAccountId,CJson * msg,const DeviceAuthCallback * laCallBack,const LightSessionReturnData * lightSessionReturnData)1697 static int32_t ProcessLightAccountAuthClient(int64_t requestId, int32_t osAccountId, CJson *msg,
1698 const DeviceAuthCallback *laCallBack, const LightSessionReturnData *lightSessionReturnData)
1699 {
1700 LOGI("ProcessLightAccountAuthClient start!");
1701 CJson *out = CreateJson();
1702 if (out == NULL) {
1703 LOGE("Failed to create out json!");
1704 return HC_ERR_JSON_CREATE;
1705 }
1706 int32_t res = ExecuteAccountAuthCmd(osAccountId, LIGHT_ACCOUNT_AUTH_PROCESS_CLIENT, msg, out);
1707 if (res != HC_SUCCESS) {
1708 LOGE("get key failed!");
1709 FreeJson(out);
1710 return res;
1711 }
1712 Uint8Buff returnKeyBuf = {0};
1713 res = ComputeHkdfKeyClient(osAccountId, out, lightSessionReturnData->randomVal,
1714 lightSessionReturnData->serviceId, &returnKeyBuf);
1715 if (res != HC_SUCCESS) {
1716 LOGE("aComputeHkdfKeyClient failed!");
1717 FreeJson(out);
1718 return res;
1719 }
1720 ProcessSessionKeyCallback(requestId, (const uint8_t *)returnKeyBuf.val, returnKeyBuf.length, laCallBack);
1721 res = LightAuthOnFinish(requestId, out, laCallBack);
1722 if (res != HC_SUCCESS) {
1723 LOGE("LightAuthOnFinish failed!");
1724 FreeJson(out);
1725 HcFree(returnKeyBuf.val);
1726 return res;
1727 }
1728 FreeJson(out);
1729 HcFree(returnKeyBuf.val);
1730 return res;
1731 }
1732
LightAuthOnTransmit(int64_t requestId,CJson * out,const DeviceAuthCallback * laCallBack)1733 static int32_t LightAuthOnTransmit(int64_t requestId, CJson *out, const DeviceAuthCallback *laCallBack)
1734 {
1735 CJson *outMsg = GetObjFromJson(out, FIELD_LIGHT_ACCOUNT_MSG);
1736 if (outMsg == NULL) {
1737 LOGE("Get outMsg from json failed!");
1738 return HC_ERR_JSON_GET;
1739 }
1740 char *returnMsg = PackJsonToString(outMsg);
1741 if (returnMsg == NULL) {
1742 LOGE("pack returnMsg to string failed");
1743 return HC_ERR_JSON_FAIL;
1744 }
1745 if (!ProcessTransmitCallback(requestId, (uint8_t *)returnMsg, HcStrlen(returnMsg) + 1, laCallBack)) {
1746 LOGE("ProcessTransmitCallback failed");
1747 FreeJsonString(returnMsg);
1748 return HC_ERR_TRANSMIT_FAIL;
1749 }
1750 FreeJsonString(returnMsg);
1751 return HC_SUCCESS;
1752 }
1753
ProcessLightAccountAuthServer(int64_t requestId,int32_t osAccountId,CJson * msg,const DeviceAuthCallback * laCallBack,const char * returnDataStr)1754 static int32_t ProcessLightAccountAuthServer(int64_t requestId, int32_t osAccountId,
1755 CJson *msg, const DeviceAuthCallback *laCallBack, const char *returnDataStr)
1756 {
1757 LOGI("ProcessLightAccountAuthServer start!");
1758 CJson *out = CreateJson();
1759 if (out == NULL) {
1760 LOGE("Failed to create out json!");
1761 return HC_ERR_JSON_CREATE;
1762 }
1763 int32_t res = ExecuteAccountAuthCmd(osAccountId, LIGHT_ACCOUNT_AUTH_PROCESS_SERVER, msg, out);
1764 if (res != HC_SUCCESS) {
1765 LOGE("get key failed!");
1766 FreeJson(out);
1767 return res;
1768 }
1769 CJson *returnDataJson = CreateJsonFromString(returnDataStr);
1770 if (returnDataJson == NULL) {
1771 LOGE("Failed to create json from returnDataStr");
1772 FreeJson(out);
1773 return HC_ERR_JSON_FAIL;
1774 }
1775 const char *serviceId = GetStringFromJson(returnDataJson, FIELD_APP_ID);
1776 if (serviceId == NULL) {
1777 LOGE("Failed to get serviceId");
1778 FreeJson(out);
1779 FreeJson(returnDataJson);
1780 return HC_ERR_JSON_FAIL;
1781 }
1782 Uint8Buff returnKeyBuf = { 0 };
1783 res = ComputeHkdfKeyServer(osAccountId, out, NULL, serviceId, &returnKeyBuf);
1784 FreeJson(returnDataJson);
1785 if (res != HC_SUCCESS) {
1786 LOGE("ComputeHkdfKeyServer failed!");
1787 FreeJson(out);
1788 return res;
1789 }
1790 ProcessSessionKeyCallback(requestId, (const uint8_t *)returnKeyBuf.val, returnKeyBuf.length, laCallBack);
1791 HcFree(returnKeyBuf.val);
1792 res = LightAuthOnTransmit(requestId, out, laCallBack);
1793 if (res != HC_SUCCESS) {
1794 LOGE("LightAuthOnTransmit failed!");
1795 FreeJson(out);
1796 return res;
1797 }
1798 res = LightAuthOnFinish(requestId, out, laCallBack);
1799 FreeJson(out);
1800 if (res != HC_SUCCESS) {
1801 LOGE("LightAuthOnTransmit failed!");
1802 return res;
1803 }
1804 return res;
1805 }
1806
ProcessLightAccountAuthInner(int32_t osAccountId,int64_t requestId,CJson * msg,CJson * out,const DeviceAuthCallback * laCallBack)1807 static int32_t ProcessLightAccountAuthInner(int32_t osAccountId, int64_t requestId,
1808 CJson *msg, CJson *out, const DeviceAuthCallback *laCallBack)
1809 {
1810 LightSessionReturnData *lightSessionReturnData =
1811 (LightSessionReturnData *)HcMalloc(sizeof(LightSessionReturnData), 0);
1812 if (lightSessionReturnData == NULL) {
1813 LOGE("Failed to alloc lightSessionReturnData");
1814 return HC_ERR_ALLOC_MEMORY;
1815 }
1816 int32_t res = QueryLightSession(requestId, osAccountId, &lightSessionReturnData->randomVal,
1817 &lightSessionReturnData->randomLen, &lightSessionReturnData->serviceId);
1818 if (res == HC_SUCCESS) { //client
1819 res = ProcessLightAccountAuthClient(requestId, osAccountId, msg, laCallBack, lightSessionReturnData);
1820 DestroyLightSessionReturnData(lightSessionReturnData);
1821 if (res != HC_SUCCESS) {
1822 LOGE("ProcessLightAccountAuthClient failed");
1823 DeleteLightSession(requestId, osAccountId);
1824 return res;
1825 }
1826 res = DeleteLightSession(requestId, osAccountId);
1827 if (res != HC_SUCCESS) {
1828 LOGE("DeleteLightSession failed");
1829 return res;
1830 }
1831 } else {
1832 DestroyLightSessionReturnData(lightSessionReturnData);
1833 char *reqParames = PackJsonToString(out);
1834 if (reqParames == NULL) {
1835 LOGE("pack out to string failed");
1836 return HC_ERR_JSON_FAIL;
1837 }
1838 int32_t opCode = AUTH_FORM_LIGHT_AUTH;
1839 char *returnDataStr = ProcessRequestCallback(requestId, opCode, reqParames, laCallBack);
1840 FreeJsonString(reqParames);
1841 if (returnDataStr == NULL) {
1842 LOGE("Onrequest callback is fail");
1843 return HC_ERR_REQ_REJECTED;
1844 }
1845 res = ProcessLightAccountAuthServer(requestId, osAccountId, msg, laCallBack, returnDataStr);
1846 FreeJsonString(returnDataStr);
1847 if (res != HC_SUCCESS) {
1848 LOGE("ProcessLightAccountAuthServer failed");
1849 return res;
1850 }
1851 }
1852 return res;
1853 }
1854
ProcessLightAccountAuth(int32_t osAccountId,int64_t requestId,DataBuff * inMsg,const DeviceAuthCallback * laCallBack)1855 static int32_t ProcessLightAccountAuth(int32_t osAccountId, int64_t requestId,
1856 DataBuff *inMsg, const DeviceAuthCallback *laCallBack)
1857 {
1858 SET_LOG_MODE(TRACE_MODE);
1859 SET_TRACE_ID(requestId);
1860
1861 CJson *out = CreateJson();
1862 if (out == NULL) {
1863 LOGE("Failed to create out json!");
1864 ProcessErrorCallback(requestId, AUTH_FORM_LIGHT_AUTH, HC_ERR_JSON_CREATE, NULL, laCallBack);
1865 return HC_ERR_JSON_CREATE;
1866 }
1867
1868 CJson *msg = CreateJsonFromString((const char*)inMsg->data);
1869 if (msg == NULL) {
1870 LOGE("Failed to CreateJsonFromString");
1871 FreeJson(out);
1872 ProcessErrorCallback(requestId, AUTH_FORM_LIGHT_AUTH, HC_ERR_JSON_CREATE, NULL, laCallBack);
1873 return HC_ERR_JSON_CREATE;
1874 }
1875
1876 int32_t res = LightAuthVerifySign(osAccountId, msg, out);
1877 if (res != HC_SUCCESS) {
1878 LOGE("LightAuthVerifySign failed");
1879 FreeJson(out);
1880 FreeJson(msg);
1881 ProcessErrorCallback(requestId, AUTH_FORM_LIGHT_AUTH, res, NULL, laCallBack);
1882 return res;
1883 }
1884 res = ProcessLightAccountAuthInner(osAccountId, requestId, msg, out, laCallBack);
1885 if (res != HC_SUCCESS) {
1886 LOGE("ProcessLightAccountAuthInner failed");
1887 FreeJson(out);
1888 FreeJson(msg);
1889 ProcessErrorCallback(requestId, AUTH_FORM_LIGHT_AUTH, res, NULL, laCallBack);
1890 return res;
1891 }
1892 FreeJson(out);
1893 FreeJson(msg);
1894 return HC_SUCCESS;
1895 }
1896
GetAccountVerifierInstance(void)1897 DEVICE_AUTH_API_PUBLIC const AccountVerifier *GetAccountVerifierInstance(void)
1898 {
1899 if (g_accountVerifierInstance == NULL) {
1900 LOGE("Account verifier instance not init!");
1901 return NULL;
1902 }
1903 g_accountVerifierInstance->getClientSharedKey = GetClientSharedKey;
1904 g_accountVerifierInstance->getServerSharedKey = GetServerSharedKey;
1905 g_accountVerifierInstance->destroyDataBuff = DestroyDataBuff;
1906 return g_accountVerifierInstance;
1907 }
1908
GetLightAccountVerifierInstance(void)1909 DEVICE_AUTH_API_PUBLIC const LightAccountVerifier *GetLightAccountVerifierInstance(void)
1910 {
1911 if (g_lightAccountVerifierInstance == NULL) {
1912 LOGE("Light account verifier instance not init!");
1913 return NULL;
1914 }
1915 g_lightAccountVerifierInstance->startLightAccountAuth = StartLightAccountAuth;
1916 g_lightAccountVerifierInstance->processLightAccountAuth = ProcessLightAccountAuth;
1917 return g_lightAccountVerifierInstance;
1918 }
1919
GetCredMgrInstance(void)1920 DEVICE_AUTH_API_PUBLIC const CredManager *GetCredMgrInstance(void)
1921 {
1922 if (g_credManager == NULL) {
1923 LOGE("Service not init");
1924 return NULL;
1925 }
1926
1927 g_credManager->addCredential = AddCredential;
1928 g_credManager->exportCredential = ExportCredential;
1929 g_credManager->queryCredentialByParams = QueryCredentialByParams;
1930 g_credManager->queryCredInfoByCredId = QueryCredInfoByCredId;
1931 g_credManager->deleteCredential = DeleteCredential;
1932 g_credManager->updateCredInfo = UpdateCredInfo;
1933 g_credManager->agreeCredential = AgreeCredential;
1934 g_credManager->registerChangeListener = RegisterChangeListener;
1935 g_credManager->unregisterChangeListener = UnregisterChangeListener;
1936 g_credManager->deleteCredByParams = DeleteCredByParams;
1937 g_credManager->batchUpdateCredentials = BatchUpdateCredentials;
1938 g_credManager->destroyInfo = DestroyInfo;
1939
1940 return g_credManager;
1941 }
1942
GetCredAuthInstance(void)1943 DEVICE_AUTH_API_PUBLIC const CredAuthManager *GetCredAuthInstance(void)
1944 {
1945 if (g_credAuthManager == NULL) {
1946 LOGE("Service not init.");
1947 return NULL;
1948 }
1949
1950 g_credAuthManager->processCredData = ProcessCredData;
1951 g_credAuthManager->authCredential = AuthCredential;
1952 return g_credAuthManager;
1953 }