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 permission and
13 * limitations under the License.
14 */
15
16 #include "auth_apply_key_process.h"
17
18 #include <securec.h>
19 #include <stdatomic.h>
20
21 #include "anonymizer.h"
22 #include "auth_apply_key_manager.h"
23 #include "auth_common.h"
24 #include "auth_connection.h"
25 #include "auth_hichain.h"
26 #include "auth_hichain_adapter.h"
27 #include "auth_interface.h"
28 #include "auth_log.h"
29 #include "auth_manager.h"
30 #include "bus_center_manager.h"
31 #include "device_auth.h"
32 #include "device_auth_defines.h"
33 #include "lnn_async_callback_utils.h"
34 #include "lnn_log.h"
35 #include "lnn_ohos_account_adapter.h"
36 #include "softbus_adapter_mem.h"
37 #include "softbus_error_code.h"
38 #include "softbus_json_utils.h"
39 #include "softbus_transmission_interface.h"
40
41 #define D2D_ACCOUNT_HASH "account_auth"
42 #define D2D_UDID_HASH "udid_auth"
43 #define BUSINESS_TYPE "business_type"
44 #define D2D_APPID "d2d_appid"
45 #define D2D_CLOSE_ACK "d2d_close_ack"
46 #define APPLY_KEY_MAX_INSTANCE_CNT 0x2000000
47 #define APPLY_KEY_NEGO_PROCESS_TIMEOUT (10 * 1000LL)
48 #define APPLY_KEY_SEQ_NETWORK_ID_BITS 16
49 #define SEQ_TIME_STAMP_BITS 8
50 #define SEQ_TIME_STAMP_MASK 0xFFL
51 #define APPLY_KEY_SEQ_INTEGER_BITS 7
52 #define APPLY_KEY_SEQ_INTEGER_MAX 0x0FFFFFFF
53 #define APPLY_KEY_TRANSMIT_DATA_LEN_MAX 20000
54
55 static uint32_t g_uniqueId = 0;
56 static uint64_t g_applyKeyDecayTime = 15552000000; // 180 * 24 * 60 * 60 * 1000L
57 static SoftBusList *g_applyKeyNegoList = NULL;
58 static SoftBusMutex g_applyKeyNegoListLock;
59
60 typedef struct {
61 uint32_t requestId;
62 bool isGenApplyKeySuccess;
63 int32_t reason;
64 } SyncGenApplyKeyResult;
65
66 typedef enum {
67 GEN_APPLY_KEY_STATE_WAIT = 1,
68 GEN_APPLY_KEY_STATE_START,
69 GEN_APPLY_KEY_STATE_UNKNOW,
70 } GenApplyKeyStartState;
71
72 typedef struct {
73 bool isRecvSessionKeyEvent;
74 bool isRecvFinishEvent;
75 bool isRecvCloseAckEvent;
76 } ApplyKeyNegoInfo;
77
78 typedef struct {
79 bool isServer;
80 int32_t connId;
81 uint32_t requestId;
82 uint32_t applyKeyLen;
83 uint8_t applyKey[D2D_APPLY_KEY_LEN];
84 GenApplyKeyStartState state;
85 RequestBusinessInfo info;
86 ApplyKeyNegoInfo negoInfo;
87 GenApplyKeyCallback genCb;
88 ListNode node;
89 } ApplyKeyNegoInstance;
90
RequireApplyKeyNegoListLock(void)91 static bool RequireApplyKeyNegoListLock(void)
92 {
93 if (SoftBusMutexLock(&g_applyKeyNegoListLock) != SOFTBUS_OK) {
94 AUTH_LOGE(AUTH_CONN, "ApplyKeyNegoList lock fail");
95 return false;
96 }
97 return true;
98 }
99
ReleaseApplyKeyNegoListLock(void)100 static void ReleaseApplyKeyNegoListLock(void)
101 {
102 if (SoftBusMutexUnlock(&g_applyKeyNegoListLock) != SOFTBUS_OK) {
103 AUTH_LOGE(AUTH_CONN, "ApplyKeyNegoList unlock fail");
104 }
105 }
106
InitApplyKeyNegoInstanceList(void)107 static int32_t InitApplyKeyNegoInstanceList(void)
108 {
109 if (g_applyKeyNegoList != NULL) {
110 return SOFTBUS_OK;
111 }
112 g_applyKeyNegoList = CreateSoftBusList();
113 if (g_applyKeyNegoList == NULL) {
114 AUTH_LOGE(AUTH_INIT, "applyKeynego create instance list fail");
115 return SOFTBUS_CREATE_LIST_ERR;
116 }
117 g_applyKeyNegoList->cnt = 0;
118 return SOFTBUS_OK;
119 }
120
DeInitApplyKeyNegoInstanceList(void)121 static void DeInitApplyKeyNegoInstanceList(void)
122 {
123 ApplyKeyNegoInstance *item = NULL;
124 ApplyKeyNegoInstance *nextItem = NULL;
125
126 if (g_applyKeyNegoList == NULL) {
127 AUTH_LOGE(AUTH_CONN, "g_applyKeyNegoList is null");
128 return;
129 }
130 if (!RequireApplyKeyNegoListLock()) {
131 AUTH_LOGE(AUTH_CONN, "RequireApplyKeyNegoListLock fail");
132 return;
133 }
134 LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, &g_applyKeyNegoList->list, ApplyKeyNegoInstance, node) {
135 ListDelete(&item->node);
136 (void)memset_s(item->applyKey, sizeof(item->applyKey), 0, sizeof(item->applyKey));
137 (void)memset_s(
138 item->info.peerAccountHash, sizeof(item->info.peerAccountHash), 0, sizeof(item->info.peerAccountHash));
139 SoftBusFree(item);
140 }
141 AUTH_LOGI(AUTH_CONN, "deinit applyKeynego instance");
142 ReleaseApplyKeyNegoListLock();
143 DestroySoftBusList(g_applyKeyNegoList);
144 g_applyKeyNegoList = NULL;
145 }
146
GetSameApplyKeyInstanceNum(const RequestBusinessInfo * info)147 static uint32_t GetSameApplyKeyInstanceNum(const RequestBusinessInfo *info)
148 {
149 if (g_applyKeyNegoList == NULL) {
150 AUTH_LOGE(AUTH_INIT, "applyKeynego instance is null");
151 return 0;
152 }
153
154 uint32_t num = 0;
155 ApplyKeyNegoInstance *item = NULL;
156 ApplyKeyNegoInstance *nextItem = NULL;
157 if (!RequireApplyKeyNegoListLock()) {
158 AUTH_LOGE(AUTH_CONN, "RequireApplyKeyNegoListLock fail");
159 return num;
160 }
161 LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, &g_applyKeyNegoList->list, ApplyKeyNegoInstance, node) {
162 if ((strcmp(info->accountHash, item->info.accountHash) != 0) ||
163 (strcmp(info->udidHash, item->info.udidHash) != 0) || info->type != item->info.type) {
164 continue;
165 }
166 if (item->state == GEN_APPLY_KEY_STATE_START) {
167 num++;
168 }
169 }
170 AUTH_LOGI(AUTH_CONN, "list has same aclinfo instance num=%{public}u", num);
171 ReleaseApplyKeyNegoListLock();
172 return num;
173 }
174
GetGenApplyKeyInstanceByReq(uint32_t requestId,ApplyKeyNegoInstance * instance)175 static int32_t GetGenApplyKeyInstanceByReq(uint32_t requestId, ApplyKeyNegoInstance *instance)
176 {
177 if (g_applyKeyNegoList == NULL) {
178 AUTH_LOGE(AUTH_INIT, "applyKeynego instance list is null");
179 return SOFTBUS_NO_INIT;
180 }
181 if (instance == NULL) {
182 AUTH_LOGE(AUTH_INIT, "instance is null");
183 return SOFTBUS_INVALID_PARAM;
184 }
185
186 ApplyKeyNegoInstance *item = NULL;
187 ApplyKeyNegoInstance *nextItem = NULL;
188 if (!RequireApplyKeyNegoListLock()) {
189 AUTH_LOGE(AUTH_CONN, "RequireApplyKeyNegoListLock fail");
190 return SOFTBUS_LOCK_ERR;
191 }
192 LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, &g_applyKeyNegoList->list, ApplyKeyNegoInstance, node) {
193 if (item->requestId != requestId) {
194 continue;
195 }
196 if (memcpy_s(instance, sizeof(ApplyKeyNegoInstance), item, sizeof(ApplyKeyNegoInstance)) != EOK) {
197 ReleaseApplyKeyNegoListLock();
198 AUTH_LOGE(AUTH_CONN, "applyKeynego memcpy_s instance fail, requestId=%{public}u", requestId);
199 return SOFTBUS_MEM_ERR;
200 }
201 ReleaseApplyKeyNegoListLock();
202 return SOFTBUS_OK;
203 }
204 AUTH_LOGE(AUTH_CONN, "applyKeynego req not found, requestId=%{public}u", requestId);
205 ReleaseApplyKeyNegoListLock();
206 return SOFTBUS_AUTH_APPLY_KEY_INSTANCE_NOT_FOUND;
207 }
208
GetGenApplyKeyInstanceByChannel(int32_t channelId,ApplyKeyNegoInstance * instance)209 static int32_t GetGenApplyKeyInstanceByChannel(int32_t channelId, ApplyKeyNegoInstance *instance)
210 {
211 if (g_applyKeyNegoList == NULL) {
212 AUTH_LOGE(AUTH_CONN, "g_applyKeyNegoList is null");
213 return SOFTBUS_NO_INIT;
214 }
215 if (instance == NULL) {
216 AUTH_LOGE(AUTH_CONN, "instance is null");
217 return SOFTBUS_INVALID_PARAM;
218 }
219
220 ApplyKeyNegoInstance *item = NULL;
221 ApplyKeyNegoInstance *nextItem = NULL;
222 if (!RequireApplyKeyNegoListLock()) {
223 AUTH_LOGE(AUTH_CONN, "RequireApplyKeyNegoListLock fail");
224 return SOFTBUS_LOCK_ERR;
225 }
226 LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, &g_applyKeyNegoList->list, ApplyKeyNegoInstance, node) {
227 if (item->connId != channelId) {
228 continue;
229 }
230 if (memcpy_s(instance, sizeof(ApplyKeyNegoInstance), item, sizeof(ApplyKeyNegoInstance)) != EOK) {
231 ReleaseApplyKeyNegoListLock();
232 AUTH_LOGE(AUTH_CONN, "applyKeynego memcpy_s instance fail, channelId=%{public}d", channelId);
233 return SOFTBUS_MEM_ERR;
234 }
235 ReleaseApplyKeyNegoListLock();
236 return SOFTBUS_OK;
237 }
238 ReleaseApplyKeyNegoListLock();
239 AUTH_LOGE(AUTH_CONN, "applyKeynego instance not found, channelId=%{public}d", channelId);
240 return SOFTBUS_AUTH_APPLY_KEY_INSTANCE_NOT_FOUND;
241 }
242
SetApplyKeyNegoInfoRecvSessionKey(uint32_t requestId,bool isRecv,const uint8_t * applyKey,uint32_t applyKeyLen)243 static int32_t SetApplyKeyNegoInfoRecvSessionKey(
244 uint32_t requestId, bool isRecv, const uint8_t *applyKey, uint32_t applyKeyLen)
245 {
246 if (g_applyKeyNegoList == NULL) {
247 AUTH_LOGE(AUTH_INIT, "applyKeynego instance is null");
248 return SOFTBUS_NO_INIT;
249 }
250
251 if (applyKey == NULL) {
252 AUTH_LOGE(AUTH_CONN, "applyKey is null");
253 return SOFTBUS_INVALID_PARAM;
254 }
255 ApplyKeyNegoInstance *item = NULL;
256 ApplyKeyNegoInstance *nextItem = NULL;
257 if (!RequireApplyKeyNegoListLock()) {
258 AUTH_LOGE(AUTH_CONN, "RequireApplyKeyNegoListLock fail");
259 return SOFTBUS_LOCK_ERR;
260 }
261 LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, &g_applyKeyNegoList->list, ApplyKeyNegoInstance, node) {
262 if (item->requestId == requestId) {
263 item->negoInfo.isRecvSessionKeyEvent = isRecv;
264 item->applyKeyLen = applyKeyLen;
265 if (memcpy_s(item->applyKey, sizeof(item->applyKey), applyKey, applyKeyLen) != EOK) {
266 AUTH_LOGE(AUTH_CONN, "memcpy applyKey fail");
267 ReleaseApplyKeyNegoListLock();
268 return SOFTBUS_MEM_ERR;
269 }
270 ReleaseApplyKeyNegoListLock();
271 return SOFTBUS_OK;
272 }
273 }
274 ReleaseApplyKeyNegoListLock();
275 return SOFTBUS_AUTH_APPLY_KEY_INSTANCE_NOT_FOUND;
276 }
277
SetApplyKeyNegoInfoRecvFinish(uint32_t requestId,bool isRecv,char * accountHash)278 static int32_t SetApplyKeyNegoInfoRecvFinish(uint32_t requestId, bool isRecv, char *accountHash)
279 {
280 if (g_applyKeyNegoList == NULL) {
281 AUTH_LOGE(AUTH_INIT, "applyKeynego instance is null");
282 return SOFTBUS_NO_INIT;
283 }
284
285 if (accountHash == NULL) {
286 AUTH_LOGE(AUTH_CONN, "accountHash is null");
287 return SOFTBUS_INVALID_PARAM;
288 }
289 ApplyKeyNegoInstance *item = NULL;
290 ApplyKeyNegoInstance *nextItem = NULL;
291 if (!RequireApplyKeyNegoListLock()) {
292 AUTH_LOGE(AUTH_CONN, "RequireApplyKeyNegoListLock fail");
293 return SOFTBUS_LOCK_ERR;
294 }
295 LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, &g_applyKeyNegoList->list, ApplyKeyNegoInstance, node) {
296 if (item->requestId == requestId) {
297 item->negoInfo.isRecvFinishEvent = isRecv;
298 uint64_t currentTime = SoftBusGetSysTimeMs();
299 int32_t ret = AuthInsertApplyKey(&item->info, item->applyKey, item->applyKeyLen, currentTime, accountHash);
300 if (ret != SOFTBUS_OK) {
301 AUTH_LOGE(AUTH_CONN, "insert apply key failed! ret=%{public}d", ret);
302 ReleaseApplyKeyNegoListLock();
303 return ret;
304 }
305 ReleaseApplyKeyNegoListLock();
306 return SOFTBUS_OK;
307 }
308 }
309 ReleaseApplyKeyNegoListLock();
310 return SOFTBUS_AUTH_APPLY_KEY_INSTANCE_NOT_FOUND;
311 }
312
SetApplyKeyNegoInfoRecvCloseAck(uint32_t requestId,bool isRecv)313 static int32_t SetApplyKeyNegoInfoRecvCloseAck(uint32_t requestId, bool isRecv)
314 {
315 if (g_applyKeyNegoList == NULL) {
316 AUTH_LOGE(AUTH_INIT, "applyKeynego instance is null");
317 return SOFTBUS_NO_INIT;
318 }
319
320 ApplyKeyNegoInstance *item = NULL;
321 ApplyKeyNegoInstance *nextItem = NULL;
322 if (!RequireApplyKeyNegoListLock()) {
323 AUTH_LOGE(AUTH_CONN, "RequireApplyKeyNegoListLock fail");
324 return SOFTBUS_LOCK_ERR;
325 }
326 LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, &g_applyKeyNegoList->list, ApplyKeyNegoInstance, node) {
327 if (item->requestId == requestId) {
328 item->negoInfo.isRecvCloseAckEvent = isRecv;
329 ReleaseApplyKeyNegoListLock();
330 return SOFTBUS_OK;
331 }
332 }
333 ReleaseApplyKeyNegoListLock();
334 return SOFTBUS_AUTH_APPLY_KEY_INSTANCE_NOT_FOUND;
335 }
336
SetApplyKeyStartState(uint32_t requestId,const GenApplyKeyStartState state)337 static int32_t SetApplyKeyStartState(uint32_t requestId, const GenApplyKeyStartState state)
338 {
339 if (g_applyKeyNegoList == NULL) {
340 AUTH_LOGE(AUTH_INIT, "applyKeynego instance is null");
341 return SOFTBUS_NO_INIT;
342 }
343
344 ApplyKeyNegoInstance *item = NULL;
345 ApplyKeyNegoInstance *nextItem = NULL;
346 if (!RequireApplyKeyNegoListLock()) {
347 AUTH_LOGE(AUTH_CONN, "RequireApplyKeyNegoListLock fail");
348 return SOFTBUS_LOCK_ERR;
349 }
350 LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, &g_applyKeyNegoList->list, ApplyKeyNegoInstance, node) {
351 if (item->requestId == requestId) {
352 item->state = state;
353 ReleaseApplyKeyNegoListLock();
354 return SOFTBUS_OK;
355 }
356 }
357 ReleaseApplyKeyNegoListLock();
358 return SOFTBUS_AUTH_APPLY_KEY_INSTANCE_NOT_FOUND;
359 }
360
DeleteApplyKeyNegoInstance(uint32_t requestId)361 static void DeleteApplyKeyNegoInstance(uint32_t requestId)
362 {
363 if (g_applyKeyNegoList == NULL) {
364 AUTH_LOGE(AUTH_INIT, "applyKeynego instance is null");
365 return;
366 }
367
368 ApplyKeyNegoInstance *item = NULL;
369 ApplyKeyNegoInstance *nextItem = NULL;
370 if (!RequireApplyKeyNegoListLock()) {
371 AUTH_LOGE(AUTH_CONN, "RequireApplyKeyNegoListLock fail");
372 return;
373 }
374 LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, &g_applyKeyNegoList->list, ApplyKeyNegoInstance, node) {
375 if (item->requestId != requestId) {
376 continue;
377 }
378 AUTH_LOGE(AUTH_CONN, "delete applyKeynego instance, requestId=%{public}u", requestId);
379 ListDelete(&(item->node));
380 (void)memset_s(item->applyKey, sizeof(item->applyKey), 0, sizeof(item->applyKey));
381 (void)memset_s(
382 item->info.peerAccountHash, sizeof(item->info.peerAccountHash), 0, sizeof(item->info.peerAccountHash));
383 SoftBusFree(item);
384 ReleaseApplyKeyNegoListLock();
385 return;
386 }
387 AUTH_LOGE(AUTH_CONN, "applyKeynego instance not found, requestId=%{public}u", requestId);
388 ReleaseApplyKeyNegoListLock();
389 }
390
AsyncCallGenApplyKeyResultReceived(void * para)391 static void AsyncCallGenApplyKeyResultReceived(void *para)
392 {
393 if (para == NULL) {
394 AUTH_LOGE(AUTH_CONN, "invalid param");
395 return;
396 }
397
398 SyncGenApplyKeyResult *res = (SyncGenApplyKeyResult *)para;
399 ApplyKeyNegoInstance instance;
400 (void)memset_s(&instance, sizeof(ApplyKeyNegoInstance), 0, sizeof(ApplyKeyNegoInstance));
401 int32_t ret = GetGenApplyKeyInstanceByReq(res->requestId, &instance);
402 if (ret != SOFTBUS_OK) {
403 AUTH_LOGE(AUTH_CONN, "get instance failed! ret=%{public}d", ret);
404 SoftBusFree(res);
405 return;
406 }
407 if (res->isGenApplyKeySuccess) {
408 AUTH_LOGI(AUTH_CONN, "recv genapplyKey success, requestId=%{public}u", res->requestId);
409 if (instance.genCb.onGenSuccess != NULL) {
410 AUTH_LOGI(AUTH_CONN, "onGenSuccess callback");
411 uint8_t applyKey[D2D_APPLY_KEY_LEN] = { 0 };
412 char accountHash[SHA_256_HEX_HASH_LEN] = { 0 };
413 if (GetApplyKeyByBusinessInfo(
414 &instance.info, applyKey, D2D_APPLY_KEY_LEN, accountHash, SHA_256_HEX_HASH_LEN) != SOFTBUS_OK) {
415 DeleteApplyKeyNegoInstance(instance.requestId);
416 SoftBusFree(res);
417 AUTH_LOGE(AUTH_CONN, "get apply key by instance fail");
418 return;
419 }
420 instance.genCb.onGenSuccess(instance.requestId, applyKey, D2D_APPLY_KEY_LEN);
421 }
422 DeleteApplyKeyNegoInstance(instance.requestId);
423 } else {
424 AUTH_LOGI(
425 AUTH_CONN, "recv genapplyKey fail, requestId=%{public}u, reason=%{public}d", res->requestId, res->reason);
426 if (instance.genCb.onGenFailed != NULL) {
427 AUTH_LOGI(AUTH_CONN, "onGenFailed callback");
428 instance.genCb.onGenFailed(instance.requestId, res->reason);
429 }
430 DeleteApplyKeyNegoInstance(instance.requestId);
431 }
432 SoftBusFree(res);
433 }
434
UpdateAllGenCbCallback(const RequestBusinessInfo * info,bool isSuccess,int32_t reason)435 static void UpdateAllGenCbCallback(const RequestBusinessInfo *info, bool isSuccess, int32_t reason)
436 {
437 if (g_applyKeyNegoList == NULL) {
438 AUTH_LOGE(AUTH_INIT, "applyKeynego instance is null");
439 return;
440 }
441
442 if (info == NULL) {
443 AUTH_LOGE(AUTH_INIT, "input is valid param");
444 return;
445 }
446 ApplyKeyNegoInstance *item = NULL;
447 ApplyKeyNegoInstance *nextItem = NULL;
448 if (!RequireApplyKeyNegoListLock()) {
449 AUTH_LOGE(AUTH_CONN, "RequireApplyKeyNegoListLock fail");
450 return;
451 }
452 LIST_FOR_EACH_ENTRY_SAFE(item, nextItem, &g_applyKeyNegoList->list, ApplyKeyNegoInstance, node) {
453 if ((strcmp(info->accountHash, item->info.accountHash) != 0) ||
454 (strcmp(info->udidHash, item->info.udidHash) != 0) || info->type != item->info.type) {
455 continue;
456 }
457 if (isSuccess) {
458 item->negoInfo.isRecvSessionKeyEvent = true;
459 item->negoInfo.isRecvFinishEvent = true;
460 item->negoInfo.isRecvCloseAckEvent = true;
461 }
462 SyncGenApplyKeyResult *result = (SyncGenApplyKeyResult *)SoftBusCalloc(sizeof(SyncGenApplyKeyResult));
463 if (result == NULL) {
464 ReleaseApplyKeyNegoListLock();
465 AUTH_LOGE(AUTH_CONN, "calloc result fail");
466 return;
467 }
468 result->requestId = item->requestId;
469 result->isGenApplyKeySuccess = isSuccess;
470 result->reason = reason;
471 if (LnnAsyncCallbackDelayHelper(
472 GetLooper(LOOP_TYPE_DEFAULT), AsyncCallGenApplyKeyResultReceived, (void *)result, 0) != SOFTBUS_OK) {
473 AUTH_LOGE(AUTH_CONN, "async applyKeynego success event fail");
474 SoftBusFree(result);
475 }
476 }
477 ReleaseApplyKeyNegoListLock();
478 }
479
OnGenSuccess(uint32_t requestId)480 static void OnGenSuccess(uint32_t requestId)
481 {
482 AUTH_LOGI(AUTH_CONN, "OnGenSuccess, requestId=%{public}u", requestId);
483 ApplyKeyNegoInstance instance;
484 (void)memset_s(&instance, sizeof(ApplyKeyNegoInstance), 0, sizeof(ApplyKeyNegoInstance));
485 int32_t ret = GetGenApplyKeyInstanceByReq(requestId, &instance);
486 if (ret != SOFTBUS_OK) {
487 AUTH_LOGE(AUTH_CONN, "get instance failed! ret=%{public}d", ret);
488 return;
489 }
490 if (!instance.negoInfo.isRecvSessionKeyEvent || !instance.negoInfo.isRecvFinishEvent ||
491 !instance.negoInfo.isRecvCloseAckEvent) {
492 AUTH_LOGI(AUTH_CONN,
493 "applyKeynego is not complete, recvsession=%{public}d, recvfinish=%{public}d, recvcloseack=%{public}d",
494 instance.negoInfo.isRecvSessionKeyEvent, instance.negoInfo.isRecvFinishEvent,
495 instance.negoInfo.isRecvCloseAckEvent);
496 return;
497 }
498 UpdateAllGenCbCallback(&instance.info, true, SOFTBUS_OK);
499 }
500
OnGenFailed(uint32_t requestId,int32_t reason)501 static void OnGenFailed(uint32_t requestId, int32_t reason)
502 {
503 AUTH_LOGE(AUTH_CONN, "OnGenFailed, requestId=%{public}u, reason=%{public}d", requestId, reason);
504 ApplyKeyNegoInstance instance;
505 (void)memset_s(&instance, sizeof(ApplyKeyNegoInstance), 0, sizeof(ApplyKeyNegoInstance));
506 int32_t ret = GetGenApplyKeyInstanceByReq(requestId, &instance);
507 if (ret != SOFTBUS_OK) {
508 AUTH_LOGE(AUTH_CONN, "get instance failed! ret=%{public}d", ret);
509 return;
510 }
511 UpdateAllGenCbCallback(&instance.info, false, reason);
512 }
513
GenApplyKeyTimeoutProcess(void * para)514 static void GenApplyKeyTimeoutProcess(void *para)
515 {
516 OnGenFailed((uint32_t)(uintptr_t)para, SOFTBUS_CHANNEL_AUTH_START_TIMEOUT);
517 }
518
AuthGenApplyKeyStartTimeout(uint32_t requestId)519 static void AuthGenApplyKeyStartTimeout(uint32_t requestId)
520 {
521 LnnAsyncCallbackDelayHelper(GetLooper(LOOP_TYPE_DEFAULT), GenApplyKeyTimeoutProcess, (void *)(uintptr_t)requestId,
522 APPLY_KEY_NEGO_PROCESS_TIMEOUT);
523 }
524
CreateApplyKeyNegoInstance(const RequestBusinessInfo * info,uint32_t requestId,uint32_t connId,bool isServer,const GenApplyKeyCallback * genCb)525 static int32_t CreateApplyKeyNegoInstance(const RequestBusinessInfo *info, uint32_t requestId, uint32_t connId,
526 bool isServer, const GenApplyKeyCallback *genCb)
527 {
528 if (g_applyKeyNegoList == NULL || info == NULL || genCb == NULL) {
529 AUTH_LOGE(AUTH_INIT, "applyKeynego instance is null");
530 return SOFTBUS_INVALID_PARAM;
531 }
532
533 if (!RequireApplyKeyNegoListLock()) {
534 AUTH_LOGE(AUTH_CONN, "RequireApplyKeyNegoListLock fail");
535 return SOFTBUS_LOCK_ERR;
536 }
537 ApplyKeyNegoInstance *instance = NULL;
538 instance = (ApplyKeyNegoInstance *)SoftBusCalloc(sizeof(ApplyKeyNegoInstance));
539 if (instance == NULL) {
540 AUTH_LOGE(AUTH_CONN, "malloc instance fail");
541 ReleaseApplyKeyNegoListLock();
542 return SOFTBUS_MEM_ERR;
543 }
544 instance->isServer = isServer;
545 instance->connId = connId;
546 instance->requestId = requestId;
547 instance->info = *info;
548 instance->state = GEN_APPLY_KEY_STATE_UNKNOW;
549 instance->genCb = *genCb;
550 instance->negoInfo.isRecvSessionKeyEvent = false;
551 instance->negoInfo.isRecvFinishEvent = false;
552 instance->negoInfo.isRecvCloseAckEvent = false;
553 ListInit(&instance->node);
554 ListAdd(&g_applyKeyNegoList->list, &instance->node);
555 char *anonyAccountHash = NULL;
556 Anonymize(info->accountHash, &anonyAccountHash);
557 char *anonyUdidHash = NULL;
558 Anonymize(info->udidHash, &anonyUdidHash);
559 AUTH_LOGI(AUTH_CONN,
560 "applyKeynego requestId=%{public}u, channelId=%{public}d, isServer=%{public}d, accountShortHash=%{public}s, "
561 "udidShortHash=%{public}s, type=%{public}d",
562 requestId, connId, isServer, AnonymizeWrapper(anonyAccountHash), AnonymizeWrapper(anonyUdidHash), info->type);
563 AnonymizeFree(anonyAccountHash);
564 AnonymizeFree(anonyUdidHash);
565 ReleaseApplyKeyNegoListLock();
566 AuthGenApplyKeyStartTimeout(requestId);
567 return SOFTBUS_OK;
568 }
569
PostApplyKeyData(uint32_t connId,bool toServer,const AuthDataHead * head,const uint8_t * data)570 static int32_t PostApplyKeyData(uint32_t connId, bool toServer, const AuthDataHead *head, const uint8_t *data)
571 {
572 if (head == NULL || data == NULL || GetAuthDataSize(head->len) > APPLY_KEY_TRANSMIT_DATA_LEN_MAX ||
573 ConnGetHeadSize() >= APPLY_KEY_TRANSMIT_DATA_LEN_MAX - GetAuthDataSize(head->len)) {
574 AUTH_LOGE(AUTH_CONN, "data is null");
575 return SOFTBUS_INVALID_PARAM;
576 }
577 uint32_t size = ConnGetHeadSize() + GetAuthDataSize(head->len);
578 uint8_t *buf = (uint8_t *)SoftBusCalloc(size);
579 if (buf == NULL) {
580 AUTH_LOGE(AUTH_CONN, "malloc fail");
581 return SOFTBUS_MALLOC_ERR;
582 }
583 int32_t ret = PackAuthData(head, data, buf + ConnGetHeadSize(), size - ConnGetHeadSize());
584 if (ret != SOFTBUS_OK) {
585 AUTH_LOGE(AUTH_CONN, "pack data fail=%{public}d", ret);
586 SoftBusFree(buf);
587 return ret;
588 }
589 ConnPostData connData = {
590 .module = MODULE_APPLY_KEY_CONNECTION,
591 .seq = GenSeq(!toServer),
592 .flag = CONN_HIGH,
593 .pid = 0,
594 .len = size,
595 .buf = (char *)buf,
596 };
597 AUTH_LOGI(AUTH_CONN,
598 "dataSeq=%{public}" PRId64 ", dataLen=%{public}u, "
599 "connId=%{public}u, connSeq=%{public}" PRId64 ", connLen=%{public}u}",
600 head->seq, head->len, connId, connData.seq, connData.len);
601 return ConnPostBytes(connId, &connData);
602 }
603
OnTransmitted(int64_t authSeq,const uint8_t * data,uint32_t len)604 static bool OnTransmitted(int64_t authSeq, const uint8_t *data, uint32_t len)
605 {
606 if (data == NULL || len == 0) {
607 AUTH_LOGE(AUTH_CONN, "input is invalid param");
608 return false;
609 }
610 AUTH_LOGI(AUTH_CONN, "applyKeynego OnTransmit: authSeq=%{public}" PRId64 ", len=%{public}u", authSeq, len);
611 ApplyKeyNegoInstance instance;
612 (void)memset_s(&instance, sizeof(ApplyKeyNegoInstance), 0, sizeof(ApplyKeyNegoInstance));
613 int32_t ret = GetGenApplyKeyInstanceByReq((uint32_t)authSeq, &instance);
614 if (ret != SOFTBUS_OK) {
615 AUTH_LOGE(AUTH_CONN, "get instance failed! ret=%{public}d", ret);
616 return false;
617 }
618 AuthDataHead head = {
619 .dataType = DATA_TYPE_AUTH,
620 .module = MODULE_APPLY_KEY_CONNECTION,
621 .seq = authSeq,
622 .flag = instance.isServer ? SERVER_SIDE_FLAG : CLIENT_SIDE_FLAG,
623 .len = len,
624 };
625 if (PostApplyKeyData(instance.connId, !instance.isServer, &head, data) != SOFTBUS_OK) {
626 AUTH_LOGE(AUTH_CONN, "post apply key data fail");
627 return false;
628 }
629 return true;
630 }
631
OnSessionKeyReturned(int64_t authSeq,const uint8_t * sessionKey,uint32_t sessionKeyLen)632 static void OnSessionKeyReturned(int64_t authSeq, const uint8_t *sessionKey, uint32_t sessionKeyLen)
633 {
634 AUTH_LOGI(AUTH_CONN, "applyKeynego OnSessionKeyReturned: authSeq=%{public}" PRId64 ", len=%{public}u", authSeq,
635 sessionKeyLen);
636 if (sessionKey == NULL || sessionKeyLen > D2D_APPLY_KEY_LEN) {
637 AUTH_LOGE(AUTH_CONN, "invalid sessionKey");
638 return;
639 }
640
641 ApplyKeyNegoInstance instance;
642 (void)memset_s(&instance, sizeof(ApplyKeyNegoInstance), 0, sizeof(ApplyKeyNegoInstance));
643 int32_t ret = GetGenApplyKeyInstanceByReq((uint32_t)authSeq, &instance);
644 if (ret != SOFTBUS_OK) {
645 AUTH_LOGE(AUTH_CONN, "get instance failed! ret=%{public}d", ret);
646 return;
647 }
648 if (SetApplyKeyNegoInfoRecvSessionKey(instance.requestId, true, sessionKey, sessionKeyLen) != SOFTBUS_OK) {
649 AUTH_LOGE(AUTH_CONN, "applyKeynego info not found, requestId=%{public}u", instance.requestId);
650 return;
651 }
652 }
653
GenerateAccountHash(char * accountString,char * accountHashBuf,uint32_t bufLen)654 static int32_t GenerateAccountHash(char *accountString, char *accountHashBuf, uint32_t bufLen)
655 {
656 if (accountString == NULL || accountHashBuf == NULL) {
657 AUTH_LOGE(AUTH_CONN, "invalid param");
658 return SOFTBUS_INVALID_PARAM;
659 }
660
661 uint8_t accountHash[SHA_256_HASH_LEN] = { 0 };
662 int32_t ret = SoftBusGenerateStrHash((uint8_t *)accountString, strlen(accountString), accountHash);
663 if (ret != SOFTBUS_OK) {
664 AUTH_LOGE(AUTH_FSM, "accountId hash fail, ret=%{public}d", ret);
665 return SOFTBUS_NETWORK_GENERATE_STR_HASH_ERR;
666 }
667 if (ConvertBytesToHexString(accountHashBuf, bufLen, accountHash, SHA_256_HASH_LEN) != SOFTBUS_OK) {
668 AUTH_LOGE(AUTH_FSM, "convert bytes to string fail");
669 return SOFTBUS_NETWORK_BYTES_TO_HEX_STR_ERR;
670 }
671 return SOFTBUS_OK;
672 }
673
SendApplyKeyNegoCloseAckEvent(int32_t channelId,uint32_t requestId,bool isServer)674 static int32_t SendApplyKeyNegoCloseAckEvent(int32_t channelId, uint32_t requestId, bool isServer)
675 {
676 char *msg = (char *)SoftBusCalloc(strlen(D2D_CLOSE_ACK) + 1);
677 if (msg == NULL) {
678 AUTH_LOGE(AUTH_CONN, "malloc fail");
679 return SOFTBUS_MEM_ERR;
680 }
681 if (strcpy_s(msg, strlen(D2D_CLOSE_ACK) + 1, D2D_CLOSE_ACK) != EOK) {
682 AUTH_LOGE(AUTH_CONN, "strcpy cred id fail");
683 SoftBusFree(msg);
684 return SOFTBUS_STRCPY_ERR;
685 }
686 AuthDataHead head = {
687 .dataType = DATA_TYPE_CLOSE_ACK,
688 .module = MODULE_APPLY_KEY_CONNECTION,
689 .seq = requestId,
690 .flag = isServer ? SERVER_SIDE_FLAG : CLIENT_SIDE_FLAG,
691 .len = strlen(msg),
692 };
693 if (PostApplyKeyData(channelId, false, &head, (uint8_t *)msg) != SOFTBUS_OK) {
694 AUTH_LOGE(AUTH_CONN, "post apply key data fail");
695 SoftBusFree(msg);
696 return SOFTBUS_AUTH_SEND_FAIL;
697 }
698 SoftBusFree(msg);
699 return SOFTBUS_OK;
700 }
701
CheckAccountHashWithHichain(const char * accountHash,const ApplyKeyNegoInstance * instance)702 static bool CheckAccountHashWithHichain(const char *accountHash, const ApplyKeyNegoInstance *instance)
703 {
704 if (!instance->isServer) {
705 if (strncmp(accountHash, instance->info.peerAccountHash, SHA_256_HEX_HASH_LEN) != 0) {
706 AUTH_LOGE(AUTH_CONN, "peer account hash is not target");
707 return false;
708 }
709 } else {
710 if (strncmp(accountHash, instance->info.accountHash, D2D_ACCOUNT_HASH_STR_LEN - 1) != 0) {
711 AUTH_LOGE(AUTH_CONN, "peer account short hash is not target");
712 return false;
713 }
714 }
715 return true;
716 }
717
OnFinished(int64_t authSeq,int32_t operationCode,const char * returnData)718 static void OnFinished(int64_t authSeq, int32_t operationCode, const char *returnData)
719 {
720 AUTH_LOGI(AUTH_CONN, "applyKeynego OnFinish: authSeq=%{public}" PRId64, authSeq);
721 if (returnData == NULL) {
722 AUTH_LOGE(AUTH_CONN, "invalid returnData");
723 return;
724 }
725
726 ApplyKeyNegoInstance instance;
727 char hichainReturnAccountId[SHA_256_HEX_HASH_LEN] = { 0 };
728 char hichainReturnAccountHash[SHA_256_HEX_HASH_LEN] = { 0 };
729 (void)memset_s(&instance, sizeof(ApplyKeyNegoInstance), 0, sizeof(ApplyKeyNegoInstance));
730 cJSON *msg = cJSON_ParseWithLength(returnData, strlen(returnData));
731 if (msg == NULL) {
732 AUTH_LOGE(AUTH_CONN, "cJSON_ParseWithLength fail");
733 return;
734 }
735 if (!GetJsonObjectStringItem(msg, FIELD_PEER_USER_ID, hichainReturnAccountId, SHA_256_HEX_HASH_LEN)) {
736 AUTH_LOGE(AUTH_CONN, "get json object fail");
737 cJSON_Delete(msg);
738 return;
739 }
740 cJSON_Delete(msg);
741 if (GenerateAccountHash(hichainReturnAccountId, hichainReturnAccountHash, SHA_256_HEX_HASH_LEN) != SOFTBUS_OK) {
742 AUTH_LOGE(AUTH_CONN, "convert local account hash to string fail");
743 return;
744 }
745 int32_t ret = GetGenApplyKeyInstanceByReq((uint32_t)authSeq, &instance);
746 if (ret != SOFTBUS_OK) {
747 AUTH_LOGE(AUTH_CONN, "get instance failed! ret=%{public}d", ret);
748 return;
749 }
750 if (!CheckAccountHashWithHichain(hichainReturnAccountHash, &instance)) {
751 OnGenFailed((uint32_t)authSeq, SOFTBUS_STRCMP_ERR);
752 return;
753 }
754 if (SetApplyKeyNegoInfoRecvFinish(instance.requestId, true, hichainReturnAccountHash) != SOFTBUS_OK) {
755 AUTH_LOGE(AUTH_CONN, "applyKeynego info not found, requestId=%{public}u", instance.requestId);
756 return;
757 }
758 if (instance.isServer) {
759 (void)SendApplyKeyNegoCloseAckEvent(instance.connId, instance.requestId, instance.isServer);
760 }
761 OnGenSuccess((uint32_t)authSeq);
762 }
763
OnError(int64_t authSeq,int32_t operationCode,int32_t errCode,const char * errorReturn)764 static void OnError(int64_t authSeq, int32_t operationCode, int32_t errCode, const char *errorReturn)
765 {
766 (void)operationCode;
767 uint32_t authErrCode = 0;
768 (void)GetSoftbusHichainAuthErrorCode((uint32_t)errCode, &authErrCode);
769 AUTH_LOGE(AUTH_CONN, "applyKeynego OnError: authSeq=%{public}" PRId64 ", errCode=%{public}d authErrCode=%{public}d",
770 authSeq, errCode, authErrCode);
771 ApplyKeyNegoInstance instance;
772 (void)memset_s(&instance, sizeof(ApplyKeyNegoInstance), 0, sizeof(ApplyKeyNegoInstance));
773 int32_t ret = GetGenApplyKeyInstanceByReq((uint32_t)authSeq, &instance);
774 if (ret != SOFTBUS_OK) {
775 AUTH_LOGE(AUTH_CONN, "get instance failed! ret=%{public}d", ret);
776 return;
777 }
778 OnGenFailed((uint32_t)authSeq, authErrCode);
779 }
780
OnRequest(int64_t authSeq,int operationCode,const char * reqParams)781 static char *OnRequest(int64_t authSeq, int operationCode, const char *reqParams)
782 {
783 (void)reqParams;
784 AUTH_LOGI(AUTH_CONN, "applyKeynego OnRequest: authSeq=%{public}" PRId64 ", ret=%{public}d", authSeq, operationCode);
785
786 cJSON *msg = cJSON_CreateObject();
787 if (msg == NULL) {
788 AUTH_LOGE(AUTH_CONN, "create json fail");
789 return NULL;
790 }
791 if (!AddStringToJsonObject(msg, FIELD_APP_ID, D2D_APPID)) {
792 AUTH_LOGE(AUTH_CONN, "add appid fail");
793 cJSON_Delete(msg);
794 return NULL;
795 }
796 char *msgStr = cJSON_PrintUnformatted(msg);
797 cJSON_Delete(msg);
798 if (msgStr == NULL) {
799 AUTH_LOGE(AUTH_CONN, "cJSON_PrintUnformatted fail");
800 return NULL;
801 }
802 return msgStr;
803 }
804
805 static DeviceAuthCallback g_hichainCallback = { .onTransmit = OnTransmitted,
806 .onSessionKeyReturned = OnSessionKeyReturned,
807 .onFinish = OnFinished,
808 .onError = OnError,
809 .onRequest = OnRequest };
810
ApplyKeyGetLightAccountInstance()811 static const LightAccountVerifier *ApplyKeyGetLightAccountInstance()
812 {
813 int32_t ret = InitDeviceAuthService();
814 if (ret != 0) {
815 AUTH_LOGE(AUTH_CONN, "init device auth service fail err=%{public}d", ret);
816 return NULL;
817 }
818
819 return GetLightAccountVerifierInstance();
820 }
821
ProcessAuthHichainParam(uint32_t requestId,const DeviceAuthCallback * genCb)822 static int32_t ProcessAuthHichainParam(uint32_t requestId, const DeviceAuthCallback *genCb)
823 {
824 const LightAccountVerifier *lightAccountVerifier = ApplyKeyGetLightAccountInstance();
825 AUTH_CHECK_AND_RETURN_RET_LOGE(lightAccountVerifier != NULL, SOFTBUS_AUTH_GET_LIGHT_ACCOUNT_FALI, AUTH_CONN,
826 "light account verify not initialized");
827
828 int32_t activeUserId = GetActiveOsAccountIds();
829 int32_t ret =
830 lightAccountVerifier->startLightAccountAuth(activeUserId, (int64_t)requestId, (const char *)D2D_APPID, genCb);
831 if (ret != HC_SUCCESS) {
832 uint32_t authErrCode = 0;
833 (void)GetSoftbusHichainAuthErrorCode((uint32_t)ret, &authErrCode);
834 AUTH_LOGE(AUTH_CONN,
835 "hichain identity service authenticate credential failed, err=%{public}d, authErrCode=%{public}d", ret,
836 authErrCode);
837 return authErrCode;
838 }
839 AUTH_LOGI(AUTH_CONN, "start applyKeynego auth");
840 return SOFTBUS_OK;
841 }
842
GetUdidAndAccountShortHash(char * localUdidShortHash,uint32_t udidHashLen,char * localAccountShortHash,uint32_t accountHashLen)843 static int32_t GetUdidAndAccountShortHash(
844 char *localUdidShortHash, uint32_t udidHashLen, char *localAccountShortHash, uint32_t accountHashLen)
845 {
846 if (localUdidShortHash == NULL || localAccountShortHash == NULL) {
847 AUTH_LOGE(AUTH_CONN, "invalid param");
848 return SOFTBUS_INVALID_PARAM;
849 }
850
851 char localUdid[UDID_BUF_LEN] = { 0 };
852 uint8_t hash[UDID_HASH_LEN] = { 0 };
853 uint8_t localAccountHash[SHA_256_HASH_LEN] = { 0 };
854
855 if (LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, localUdid, UDID_BUF_LEN) != SOFTBUS_OK) {
856 AUTH_LOGE(AUTH_CONN, "get local udid fail");
857 return SOFTBUS_NETWORK_GET_LOCAL_NODE_INFO_ERR;
858 }
859 if (SoftBusGenerateStrHash((unsigned char *)localUdid, strlen(localUdid), (unsigned char *)hash) != SOFTBUS_OK) {
860 AUTH_LOGE(AUTH_CONN, "generate strhash fail");
861 return SOFTBUS_NETWORK_GENERATE_STR_HASH_ERR;
862 }
863 if (ConvertBytesToHexString(localUdidShortHash, udidHashLen, hash, D2D_UDID_SHORT_HASH_LEN) !=
864 SOFTBUS_OK) {
865 AUTH_LOGE(AUTH_CONN, "convert bytes to string fail");
866 return SOFTBUS_NETWORK_BYTES_TO_HEX_STR_ERR;
867 }
868 if (LnnGetLocalByteInfo(BYTE_KEY_ACCOUNT_HASH, localAccountHash, SHA_256_HASH_LEN) != SOFTBUS_OK) {
869 AUTH_LOGE(AUTH_CONN, "get local account hash fail");
870 return SOFTBUS_NETWORK_GET_LOCAL_NODE_INFO_ERR;
871 }
872 if (ConvertBytesToHexString(localAccountShortHash, accountHashLen, localAccountHash,
873 D2D_ACCOUNT_SHORT_HASH_LEN) != SOFTBUS_OK) {
874 AUTH_LOGE(AUTH_CONN, "convert local account hash to string fail");
875 return SOFTBUS_NETWORK_BYTES_TO_HEX_STR_ERR;
876 }
877 char *anonyAccountHash = NULL;
878 Anonymize(localUdidShortHash, &anonyAccountHash);
879 char *anonyUdidHash = NULL;
880 Anonymize(localAccountShortHash, &anonyUdidHash);
881 AUTH_LOGI(AUTH_CONN, "generate accountShortHash=%{public}s, udidShortHash=%{public}s",
882 AnonymizeWrapper(anonyAccountHash), AnonymizeWrapper(anonyUdidHash));
883 AnonymizeFree(anonyAccountHash);
884 AnonymizeFree(anonyUdidHash);
885 return SOFTBUS_OK;
886 }
887
PackApplyKeyAclParam(RequestBusinessType type)888 static char *PackApplyKeyAclParam(RequestBusinessType type)
889 {
890 char localUdidShortHash[D2D_UDID_HASH_STR_LEN] = { 0 };
891 char localAccountShortHash[D2D_ACCOUNT_HASH_STR_LEN] = { 0 };
892 if (GetUdidAndAccountShortHash(
893 localUdidShortHash, D2D_UDID_HASH_STR_LEN, localAccountShortHash, D2D_ACCOUNT_HASH_STR_LEN)) {
894 AUTH_LOGE(AUTH_CONN, "generate short hash fail");
895 return NULL;
896 }
897 cJSON *msg = cJSON_CreateObject();
898 if (msg == NULL) {
899 AUTH_LOGE(AUTH_CONN, "create json fail");
900 return NULL;
901 }
902 if (!AddStringToJsonObject(msg, D2D_ACCOUNT_HASH, localAccountShortHash) ||
903 !AddStringToJsonObject(msg, D2D_UDID_HASH, localUdidShortHash) ||
904 !AddNumberToJsonObject(msg, BUSINESS_TYPE, type)) {
905 AUTH_LOGE(AUTH_CONN, "add json object fail");
906 cJSON_Delete(msg);
907 return NULL;
908 }
909 char *data = cJSON_PrintUnformatted(msg);
910 if (data == NULL) {
911 AUTH_LOGE(AUTH_CONN, "cJSON_PrintUnformatted fail");
912 }
913 cJSON_Delete(msg);
914 return data;
915 }
916
UnpackApplyKeyAclParam(const char * data,uint32_t len,RequestBusinessInfo * info)917 static int32_t UnpackApplyKeyAclParam(const char *data, uint32_t len, RequestBusinessInfo *info)
918 {
919 if (data == NULL || info == NULL) {
920 AUTH_LOGE(AUTH_CONN, "unpack applyKey info is invalid param");
921 return SOFTBUS_INVALID_PARAM;
922 }
923
924 cJSON *msg = cJSON_ParseWithLength((char *)data, len);
925 if (msg == NULL) {
926 AUTH_LOGE(AUTH_CONN, "cJSON_ParseWithLength fail");
927 return SOFTBUS_CREATE_JSON_ERR;
928 }
929 int32_t businessType = 0;
930 if (!GetJsonObjectStringItem(msg, D2D_ACCOUNT_HASH, info->accountHash, D2D_ACCOUNT_HASH_STR_LEN) ||
931 !GetJsonObjectStringItem(msg, D2D_UDID_HASH, info->udidHash, D2D_UDID_HASH_STR_LEN) ||
932 !GetJsonObjectNumberItem(msg, BUSINESS_TYPE, &businessType)) {
933 AUTH_LOGE(AUTH_CONN, "get json object fail");
934 cJSON_Delete(msg);
935 return SOFTBUS_PARSE_JSON_ERR;
936 }
937 cJSON_Delete(msg);
938 info->type = (RequestBusinessType)businessType;
939 return SOFTBUS_OK;
940 }
941
SendApplyKeyNegoDeviceId(uint32_t connId,const RequestBusinessInfo * info,uint32_t requestId)942 static int32_t SendApplyKeyNegoDeviceId(uint32_t connId, const RequestBusinessInfo *info, uint32_t requestId)
943 {
944 if (info == NULL) {
945 AUTH_LOGE(AUTH_CONN, "unpack applyKey info is invalid param");
946 return SOFTBUS_INVALID_PARAM;
947 }
948
949 char *applyKeyParams = PackApplyKeyAclParam(info->type);
950 if (applyKeyParams == NULL) {
951 AUTH_LOGE(AUTH_CONN, "generate auth param fail");
952 return SOFTBUS_CREATE_JSON_ERR;
953 }
954 AuthDataHead head = {
955 .dataType = DATA_TYPE_DEVICE_ID,
956 .module = MODULE_APPLY_KEY_CONNECTION,
957 .seq = requestId,
958 .flag = CLIENT_SIDE_FLAG,
959 .len = strlen(applyKeyParams) + 1,
960 };
961 if (PostApplyKeyData(connId, false, &head, (uint8_t *)applyKeyParams) != SOFTBUS_OK) {
962 AUTH_LOGE(AUTH_CONN, "post apply key data fail");
963 cJSON_free(applyKeyParams);
964 return SOFTBUS_AUTH_SEND_FAIL;
965 }
966 cJSON_free(applyKeyParams);
967 return SOFTBUS_OK;
968 }
969
ProcessApplyKeyNegoState(const RequestBusinessInfo * info,bool * isGreater)970 static int32_t ProcessApplyKeyNegoState(const RequestBusinessInfo *info, bool *isGreater)
971 {
972 if (info == NULL) {
973 AUTH_LOGE(AUTH_CONN, "applyKeynego info is invalid param");
974 return SOFTBUS_INVALID_PARAM;
975 }
976 char localUdidShortHash[D2D_UDID_HASH_STR_LEN] = { 0 };
977 char localAccountShortHash[D2D_ACCOUNT_HASH_STR_LEN] = { 0 };
978 if (GetUdidAndAccountShortHash(
979 localUdidShortHash, D2D_UDID_HASH_STR_LEN, localAccountShortHash, D2D_ACCOUNT_HASH_STR_LEN) != SOFTBUS_OK) {
980 AUTH_LOGE(AUTH_CONN, "get local udid and account hash fail");
981 return SOFTBUS_NETWORK_GET_NODE_INFO_ERR;
982 }
983 *isGreater = true;
984 if (strcmp(localUdidShortHash, info->udidHash) < 0) {
985 *isGreater = false;
986 AUTH_LOGW(AUTH_CONN, "peer udid is greater, wait another applyKeynego");
987 }
988 return SOFTBUS_OK;
989 }
990
StartApplyKeyHichain(uint32_t connId,const RequestBusinessInfo * info,uint32_t requestId)991 static int32_t StartApplyKeyHichain(uint32_t connId, const RequestBusinessInfo *info, uint32_t requestId)
992 {
993 if (info == NULL) {
994 AUTH_LOGE(AUTH_CONN, "applyKeynego info is invalid param");
995 return SOFTBUS_INVALID_PARAM;
996 }
997
998 bool isLocalUdidGreater = false;
999 int32_t ret = ProcessApplyKeyNegoState(info, &isLocalUdidGreater);
1000 if (ret != SOFTBUS_OK || GetSameApplyKeyInstanceNum(info) > 0) {
1001 AUTH_LOGW(AUTH_CONN, "wait another applyKeynego");
1002 return ret;
1003 }
1004 if (ret == SOFTBUS_OK && isLocalUdidGreater) {
1005 ret = SetApplyKeyStartState(requestId, GEN_APPLY_KEY_STATE_START);
1006 if (ret != SOFTBUS_OK) {
1007 AUTH_LOGE(AUTH_CONN, "get instance failed! ret=%{public}d", ret);
1008 return ret;
1009 }
1010 return ProcessAuthHichainParam(requestId, &g_hichainCallback);
1011 }
1012 return ret;
1013 }
1014
ProcessApplyKeyDeviceId(int32_t channelId,uint32_t requestId,const void * data,uint32_t dataLen)1015 static int32_t ProcessApplyKeyDeviceId(int32_t channelId, uint32_t requestId, const void *data, uint32_t dataLen)
1016 {
1017 AUTH_CHECK_AND_RETURN_RET_LOGE(data != NULL, SOFTBUS_INVALID_PARAM, AUTH_CONN, "data is null");
1018 RequestBusinessInfo info;
1019 ApplyKeyNegoInstance instance;
1020 GenApplyKeyCallback cb;
1021 (void)memset_s(&info, sizeof(RequestBusinessInfo), 0, sizeof(RequestBusinessInfo));
1022 (void)memset_s(&instance, sizeof(ApplyKeyNegoInstance), 0, sizeof(ApplyKeyNegoInstance));
1023 (void)memset_s(&cb, sizeof(GenApplyKeyCallback), 0, sizeof(GenApplyKeyCallback));
1024 bool isLocalUdidGreater = false;
1025 int32_t ret = UnpackApplyKeyAclParam((const char *)data, dataLen, &info);
1026 if (ret != SOFTBUS_OK) {
1027 AUTH_LOGE(AUTH_CONN, "UnpackApplyKeyAclParam failed! ret=%{public}d", ret);
1028 return ret;
1029 }
1030 ret = CreateApplyKeyNegoInstance(&info, requestId, channelId, true, &cb);
1031 if (ret != SOFTBUS_OK) {
1032 AUTH_LOGE(AUTH_CONN, "create new applyKeynego instance failed! ret=%{public}d", ret);
1033 return ret;
1034 }
1035 ret = ProcessApplyKeyNegoState(&info, &isLocalUdidGreater);
1036 if (ret != SOFTBUS_OK || GetSameApplyKeyInstanceNum(&info) > 0) {
1037 AUTH_LOGW(AUTH_CONN, "wait another applyKeynego");
1038 return ret;
1039 }
1040 if (ret == SOFTBUS_OK && isLocalUdidGreater) {
1041 ret = SetApplyKeyStartState(requestId, GEN_APPLY_KEY_STATE_START);
1042 if (ret != SOFTBUS_OK) {
1043 AUTH_LOGE(AUTH_CONN, "get instance failed! ret=%{public}d", ret);
1044 return ret;
1045 }
1046 return ProcessAuthHichainParam(requestId, &g_hichainCallback);
1047 }
1048 return ret;
1049 }
1050
ProcessApplyKeyData(uint32_t requestId,const uint8_t * data,uint32_t dataLen)1051 static int32_t ProcessApplyKeyData(uint32_t requestId, const uint8_t *data, uint32_t dataLen)
1052 {
1053 AUTH_LOGI(AUTH_CONN, "ProcessApplyKeyData enter: requestId=%{public}u, len=%{public}u", requestId, dataLen);
1054 ApplyKeyNegoInstance instance;
1055 (void)memset_s(&instance, sizeof(ApplyKeyNegoInstance), 0, sizeof(ApplyKeyNegoInstance));
1056 int32_t ret = GetGenApplyKeyInstanceByReq(requestId, &instance);
1057 if (ret != SOFTBUS_OK) {
1058 AUTH_LOGE(AUTH_CONN, "get instance failed! ret=%{public}d", ret);
1059 return ret;
1060 }
1061 const LightAccountVerifier *lightAccountVerifier = ApplyKeyGetLightAccountInstance();
1062 AUTH_CHECK_AND_RETURN_RET_LOGE(lightAccountVerifier != NULL, SOFTBUS_AUTH_GET_LIGHT_ACCOUNT_FALI, AUTH_CONN,
1063 "light account verify not initialized");
1064
1065 int32_t activeUserId = GetActiveOsAccountIds();
1066 DataBuff inMsg = { .data = (uint8_t *)data, .length = dataLen };
1067 int32_t hichainRet =
1068 lightAccountVerifier->processLightAccountAuth(activeUserId, (int64_t)requestId, &inMsg, &g_hichainCallback);
1069 if (hichainRet != HC_SUCCESS) {
1070 uint32_t authErrCode = 0;
1071 (void)GetSoftbusHichainAuthErrorCode((uint32_t)hichainRet, &authErrCode);
1072 AUTH_LOGE(AUTH_CONN,
1073 "hichain identity service authenticate credential failed, err=%{public}d, authErrCode=%{public}d",
1074 hichainRet, authErrCode);
1075 return authErrCode;
1076 }
1077 return SOFTBUS_OK;
1078 }
1079
ProcessApplyKeyCloseAckData(uint32_t requestId,const uint8_t * data,uint32_t dataLen)1080 static int32_t ProcessApplyKeyCloseAckData(uint32_t requestId, const uint8_t *data, uint32_t dataLen)
1081 {
1082 AUTH_LOGI(AUTH_CONN, "applykeynego close ack, requestId=%{public}u, len=%{public}u", requestId, dataLen);
1083 ApplyKeyNegoInstance instance;
1084 (void)memset_s(&instance, sizeof(ApplyKeyNegoInstance), 0, sizeof(ApplyKeyNegoInstance));
1085 int32_t ret = GetGenApplyKeyInstanceByReq(requestId, &instance);
1086 if (ret != SOFTBUS_OK) {
1087 AUTH_LOGE(AUTH_CONN, "get instance failed! ret=%{public}d", ret);
1088 return ret;
1089 }
1090 ret = SetApplyKeyNegoInfoRecvCloseAck(instance.requestId, true);
1091 if (ret != SOFTBUS_OK) {
1092 AUTH_LOGE(AUTH_CONN, "applyKeynego info not found, requestId=%{public}u", instance.requestId);
1093 return ret;
1094 }
1095 if (!instance.isServer) {
1096 (void)SendApplyKeyNegoCloseAckEvent(instance.connId, instance.requestId, instance.isServer);
1097 }
1098 OnGenSuccess(requestId);
1099 return SOFTBUS_OK;
1100 }
1101
ApplyKeyMsgHandler(int32_t channelId,uint32_t requestId,const AuthDataHead * head,const void * data,uint32_t dataLen)1102 static int32_t ApplyKeyMsgHandler(
1103 int32_t channelId, uint32_t requestId, const AuthDataHead *head, const void *data, uint32_t dataLen)
1104 {
1105 if (head == NULL || data == NULL) {
1106 AUTH_LOGE(AUTH_CONN, "param error");
1107 return SOFTBUS_INVALID_PARAM;
1108 }
1109 int32_t ret = SOFTBUS_OK;
1110 switch (head->dataType) {
1111 case DATA_TYPE_DEVICE_ID:
1112 ret = ProcessApplyKeyDeviceId(channelId, requestId, data, dataLen);
1113 break;
1114 case DATA_TYPE_AUTH:
1115 ret = ProcessApplyKeyData(requestId, (const uint8_t *)data, dataLen);
1116 break;
1117 case DATA_TYPE_CLOSE_ACK:
1118 ret = ProcessApplyKeyCloseAckData(requestId, (const uint8_t *)data, dataLen);
1119 break;
1120 default:
1121 ret = SOFTBUS_CHANNEL_AUTH_HANDLE_DATA_FAIL;
1122 break;
1123 }
1124 if (ret != SOFTBUS_OK) {
1125 OnGenFailed(requestId, ret);
1126 }
1127 AUTH_LOGI(AUTH_CONN, "exit, ret=%{public}d", ret);
1128 return ret;
1129 }
1130
OnCommConnected(uint32_t connectionId,const ConnectionInfo * info)1131 static void OnCommConnected(uint32_t connectionId, const ConnectionInfo *info)
1132 {
1133 AUTH_LOGI(AUTH_CONN, "(ignored)OnCommConnected: connectionId=%{public}u", connectionId);
1134 }
1135
OnCommDisconnected(uint32_t connectionId,const ConnectionInfo * info)1136 static void OnCommDisconnected(uint32_t connectionId, const ConnectionInfo *info)
1137 {
1138 AUTH_LOGI(AUTH_CONN, "on connect disconnected, connectionId=%{public}u", connectionId);
1139 ApplyKeyNegoInstance instance;
1140 (void)memset_s(&instance, sizeof(ApplyKeyNegoInstance), 0, sizeof(ApplyKeyNegoInstance));
1141
1142 int32_t ret = GetGenApplyKeyInstanceByChannel(connectionId, &instance);
1143 if (ret != SOFTBUS_OK) {
1144 AUTH_LOGE(AUTH_CONN, "get instance failed=%{public}d", ret);
1145 return;
1146 }
1147 DeleteApplyKeyNegoInstance(instance.requestId);
1148 }
1149
OnCommDataReceived(uint32_t connectionId,ConnModule moduleId,int64_t seq,char * data,int32_t len)1150 static void OnCommDataReceived(uint32_t connectionId, ConnModule moduleId, int64_t seq, char *data, int32_t len)
1151 {
1152 if (data == NULL || moduleId != MODULE_APPLY_KEY_CONNECTION || len <= 0) {
1153 AUTH_LOGE(AUTH_CONN, "invalid param");
1154 return;
1155 }
1156 AuthDataHead head = { 0 };
1157 const uint8_t *body = UnpackAuthData((const uint8_t *)data, (uint32_t)len, &head);
1158 if (body == NULL) {
1159 AUTH_LOGE(AUTH_CONN, "empty body");
1160 return;
1161 }
1162 int32_t ret = ApplyKeyMsgHandler(connectionId, head.seq, &head, body, head.len);
1163 AUTH_LOGI(AUTH_CONN,
1164 "ret=%{public}d, connectionId=%{public}u, module=%{public}d, seq=%{public}" PRId64 ", len=%{public}d", ret,
1165 connectionId, moduleId, head.seq, head.len);
1166 }
1167
RegisterD2DConnectListener(void)1168 static void RegisterD2DConnectListener(void)
1169 {
1170 ConnectCallback connCb = {
1171 .OnConnected = OnCommConnected,
1172 .OnDisconnected = OnCommDisconnected,
1173 .OnDataReceived = OnCommDataReceived,
1174 };
1175 int32_t ret = ConnSetConnectCallback(MODULE_APPLY_KEY_CONNECTION, &connCb);
1176 AUTH_LOGI(AUTH_CONN, "ConnSetConnectCallback, ret=%{public}d", ret);
1177 }
1178
AuthFindApplyKey(const RequestBusinessInfo * info,uint8_t * applyKey,char * accountHash,uint32_t accountHashLen)1179 int32_t AuthFindApplyKey(
1180 const RequestBusinessInfo *info, uint8_t *applyKey, char *accountHash, uint32_t accountHashLen)
1181 {
1182 if (info == NULL || applyKey == NULL || accountHash == NULL) {
1183 AUTH_LOGE(AUTH_CONN, "find apply key nego is invalid param");
1184 return SOFTBUS_INVALID_PARAM;
1185 }
1186 if (GetApplyKeyByBusinessInfo(info, applyKey, D2D_APPLY_KEY_LEN, accountHash, accountHashLen) != SOFTBUS_OK) {
1187 AUTH_LOGE(AUTH_CONN, "find apply key fail");
1188 return SOFTBUS_AUTH_APPLY_KEY_NOT_FOUND;
1189 }
1190 AUTH_LOGE(AUTH_CONN, "find apply key succ");
1191 return SOFTBUS_OK;
1192 }
1193
AuthGenApplyKey(const RequestBusinessInfo * info,uint32_t requestId,uint32_t connId,const GenApplyKeyCallback * genCb)1194 int32_t AuthGenApplyKey(
1195 const RequestBusinessInfo *info, uint32_t requestId, uint32_t connId, const GenApplyKeyCallback *genCb)
1196 {
1197 if (info == NULL || genCb == NULL) {
1198 AUTH_LOGE(AUTH_CONN, "generate apply key nego is invalid param");
1199 return SOFTBUS_INVALID_PARAM;
1200 }
1201 int32_t ret = CreateApplyKeyNegoInstance(info, requestId, connId, false, genCb);
1202 if (ret != SOFTBUS_OK) {
1203 AUTH_LOGE(AUTH_CONN, "applykey add instance fail, ret=%{public}d", ret);
1204 return ret;
1205 }
1206 ret = SendApplyKeyNegoDeviceId(connId, info, requestId);
1207 if (ret != SOFTBUS_OK) {
1208 AUTH_LOGE(AUTH_CONN, "applykey send device id fail, ret=%{public}d", ret);
1209 DeleteApplyKeyNegoInstance(requestId);
1210 return ret;
1211 }
1212 ret = StartApplyKeyHichain(connId, info, requestId);
1213 if (ret != SOFTBUS_OK) {
1214 AUTH_LOGE(AUTH_CONN, "applykey start hichain fail, ret=%{public}d", ret);
1215 DeleteApplyKeyNegoInstance(requestId);
1216 return ret;
1217 }
1218 return SOFTBUS_OK;
1219 }
1220
UpdateUniqueId(void)1221 static void UpdateUniqueId(void)
1222 {
1223 char networkId[NETWORK_ID_BUF_LEN] = { 0 };
1224 if (LnnGetLocalStrInfo(STRING_KEY_NETWORKID, networkId, sizeof(networkId)) != SOFTBUS_OK) {
1225 AUTH_LOGE(AUTH_CONN, "get local networkId fail");
1226 return;
1227 }
1228 uint8_t hashId[SHA_256_HASH_LEN] = { 0 };
1229 if (SoftBusGenerateStrHash((uint8_t *)networkId, strlen(networkId), hashId) != SOFTBUS_OK) {
1230 AUTH_LOGE(AUTH_CONN, "GenerateStrHash fail");
1231 return;
1232 }
1233 for (uint32_t i = 0; i < APPLY_KEY_SEQ_NETWORK_ID_BITS / BYTES_BIT_NUM; i++) {
1234 g_uniqueId = (g_uniqueId << BYTES_BIT_NUM) | hashId[i];
1235 }
1236 uint64_t timeStamp = SoftBusGetSysTimeMs();
1237 g_uniqueId = (g_uniqueId << SEQ_TIME_STAMP_BITS) | (SEQ_TIME_STAMP_MASK & timeStamp);
1238 }
1239
GenApplyKeySeq(void)1240 uint32_t GenApplyKeySeq(void)
1241 {
1242 static atomic_uint integer = 0;
1243 if (integer >= APPLY_KEY_SEQ_INTEGER_MAX) {
1244 integer = 0;
1245 }
1246 if (integer == 0) {
1247 UpdateUniqueId();
1248 }
1249 integer++;
1250 /* |----GreaterZero(1)----|----NetworkIdHash(16)----|----TimeStamp(8)----|----AtomicInteger(7)----| */
1251 uint32_t seq = integer;
1252 seq = (g_uniqueId << APPLY_KEY_SEQ_INTEGER_BITS) | (seq & APPLY_KEY_SEQ_INTEGER_MAX);
1253 return seq;
1254 }
1255
AuthIsApplyKeyExpired(uint64_t time)1256 bool AuthIsApplyKeyExpired(uint64_t time)
1257 {
1258 uint64_t currentTime = SoftBusGetSysTimeMs();
1259 if (currentTime < time || currentTime - time > g_applyKeyDecayTime) {
1260 AUTH_LOGE(AUTH_CONN, "apply key is expired cannot be used.");
1261 return false;
1262 }
1263 return true;
1264 }
1265
ApplyKeyNegoInit(void)1266 int32_t ApplyKeyNegoInit(void)
1267 {
1268 AUTH_LOGI(AUTH_CONN, "enter.");
1269
1270 if (SoftBusMutexInit(&g_applyKeyNegoListLock, NULL) != SOFTBUS_OK) {
1271 AUTH_LOGE(AUTH_CONN, "ApplyKeyNego mutex init fail");
1272 return SOFTBUS_LOCK_ERR;
1273 }
1274 if (InitApplyKeyNegoInstanceList() != SOFTBUS_OK) {
1275 AUTH_LOGE(AUTH_CONN, "applyKey nego instance list init err");
1276 return SOFTBUS_CREATE_LIST_ERR;
1277 }
1278 RegisterD2DConnectListener();
1279 AUTH_LOGI(AUTH_CONN, "ok");
1280 return SOFTBUS_OK;
1281 }
1282
ApplyKeyNegoDeinit(void)1283 void ApplyKeyNegoDeinit(void)
1284 {
1285 DeInitApplyKeyNegoInstanceList();
1286 SoftBusMutexDestroy(&g_applyKeyNegoListLock);
1287 }