1 /*
2 * Copyright (c) 2022-2024 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 "auth_session_fsm.h"
17
18 #include <securec.h>
19
20 #include "anonymizer.h"
21 #include "auth_attest_interface.h"
22 #include "auth_connection.h"
23 #include "auth_device_common_key.h"
24 #include "auth_hichain.h"
25 #include "auth_log.h"
26 #include "auth_manager.h"
27 #include "auth_normalize_request.h"
28 #include "auth_request.h"
29 #include "auth_pre_link.h"
30 #include "auth_session_json.h"
31 #include "auth_session_message.h"
32 #include "auth_tcp_connection.h"
33 #include "bus_center_manager.h"
34 #include "legacy/softbus_adapter_hitrace.h"
35 #include "lnn_distributed_net_ledger.h"
36 #include "lnn_event.h"
37 #include "lnn_feature_capability.h"
38 #include "softbus_adapter_bt_common.h"
39 #include "softbus_adapter_mem.h"
40 #include "softbus_base_listener.h"
41 #include "softbus_def.h"
42 #include "softbus_socket.h"
43 #include "wifi_direct_manager.h"
44
45 #define AUTH_TIMEOUT_MS (10 * 1000)
46 #define TO_AUTH_FSM(ptr) CONTAINER_OF(ptr, AuthFsm, fsm)
47 #define SHORT_UDID_HASH_LEN 8
48 #define HICHAIN_RETURN_NOT_TRUSTED (-425919748)
49 #define PTK_32_BIT_LEN 16
50
51 typedef enum {
52 FSM_MSG_RECV_DEVICE_ID,
53 FSM_MSG_RECV_AUTH_DATA,
54 FSM_MSG_RECV_TEST_AUTH_DATA,
55 FSM_MSG_SAVE_SESSION_KEY,
56 FSM_MSG_AUTH_ERROR,
57 FSM_MSG_RECV_DEVICE_INFO,
58 FSM_MSG_RECV_CLOSE_ACK,
59 FSM_MSG_AUTH_FINISH,
60 FSM_MSG_AUTH_TIMEOUT,
61 FSM_MSG_DEVICE_NOT_TRUSTED,
62 FSM_MSG_DEVICE_DISCONNECTED,
63 FSM_MSG_DEVICE_POST_DEVICEID,
64 FSM_MSG_STOP_AUTH_FSM,
65 FSM_MSG_UNKNOWN,
66 } StateMessageType;
67 typedef struct {
68 StateMessageType type;
69 char *msg;
70 } StateMsgMap;
71
72 static const StateMsgMap g_StateMsgMap[] = {
73 { FSM_MSG_RECV_DEVICE_ID, (char *)"RECV_DEVICE_ID" },
74 { FSM_MSG_RECV_AUTH_DATA, (char *)"RECV_AUTH_DATA" },
75 { FSM_MSG_RECV_TEST_AUTH_DATA, (char *)"RECV_TEST_AUTH_DATA" },
76 { FSM_MSG_SAVE_SESSION_KEY, (char *)"SAVE_SESSION_KEY" },
77 { FSM_MSG_AUTH_ERROR, (char *)"AUTH_ERROR" },
78 { FSM_MSG_RECV_DEVICE_INFO, (char *)"RECV_DEVICE_INFO" },
79 { FSM_MSG_RECV_CLOSE_ACK, (char *)"RECV_CLOSE_ACK" },
80 { FSM_MSG_AUTH_FINISH, (char *)"AUTH_FINISH" },
81 { FSM_MSG_AUTH_TIMEOUT, (char *)"AUTH_TIMEOUT" },
82 { FSM_MSG_DEVICE_NOT_TRUSTED, (char *)"DEVICE_NOT_TRUSTED" },
83 { FSM_MSG_DEVICE_DISCONNECTED, (char *)"DEVICE_DISCONNECTED" },
84 { FSM_MSG_DEVICE_POST_DEVICEID, (char *)"DEVICE_POST_DEVICEID" },
85 { FSM_MSG_STOP_AUTH_FSM, (char *)"STOP_AUTH_FSM" },
86 { FSM_MSG_UNKNOWN, (char *)"UNKNOWN MSG!!" },
87 };
88
89 typedef struct {
90 uint32_t len;
91 uint8_t data[0];
92 } MessagePara;
93
94 typedef struct {
95 int64_t param1;
96 bool param2;
97 AuthFsm *(*getFunc)(int64_t param1, bool param2);
98 } AuthFsmGetFunc;
99
100 typedef struct {
101 char localIp[IP_LEN];
102 char localBrMac[MAC_LEN];
103 char localBleMac[MAC_LEN];
104 char localUdid[UDID_BUF_LEN];
105 char localNetworkId[NETWORK_ID_BUF_LEN];
106 char localDevName[DEVICE_NAME_BUF_LEN];
107 } AuditReportDevInfo;
108
109 static ListNode g_authFsmList = { &g_authFsmList, &g_authFsmList };
110
111 static void SyncNegotiationEnter(FsmStateMachine *fsm);
112 static bool SyncNegotiationStateProcess(FsmStateMachine *fsm, int32_t msgType, void *para);
113 static void SyncDevIdStateEnter(FsmStateMachine *fsm);
114 static bool SyncDevIdStateProcess(FsmStateMachine *fsm, int32_t msgType, void *para);
115 static void DeviceAuthStateEnter(FsmStateMachine *fsm);
116 static bool DeviceAuthStateProcess(FsmStateMachine *fsm, int32_t msgType, void *para);
117 static bool SyncDevInfoStateProcess(FsmStateMachine *fsm, int32_t msgType, void *para);
118 static void AuthFsmDeinitCallback(FsmStateMachine *fsm);
119 static void HandleMsgRecvAuthTestData(AuthFsm *authFsm, const MessagePara *para);
120 static void HandleMsgSaveSessionKey(AuthFsm *authFsm, const MessagePara *para);
121
122 static FsmState g_states[STATE_NUM_MAX] = {
123 [STATE_SYNC_NEGOTIATION] = {
124 .enter = SyncNegotiationEnter,
125 .process = SyncNegotiationStateProcess,
126 .exit = NULL,
127 },
128 [STATE_SYNC_DEVICE_ID] = {
129 .enter = SyncDevIdStateEnter,
130 .process = SyncDevIdStateProcess,
131 .exit = NULL,
132 },
133 [STATE_DEVICE_AUTH] = {
134 .enter = DeviceAuthStateEnter,
135 .process = DeviceAuthStateProcess,
136 .exit = NULL,
137 },
138 [STATE_SYNC_DEVICE_INFO] = {
139 .enter = NULL,
140 .process = SyncDevInfoStateProcess,
141 .exit = NULL,
142 },
143 };
144
FsmMsgTypeToStr(int32_t type)145 static char *FsmMsgTypeToStr(int32_t type)
146 {
147 if (type < FSM_MSG_RECV_DEVICE_ID || type >= FSM_MSG_UNKNOWN) {
148 return g_StateMsgMap[FSM_MSG_UNKNOWN].msg;
149 }
150 return g_StateMsgMap[type].msg;
151 }
152
TranslateToAuthFsm(FsmStateMachine * fsm,int32_t msgType,MessagePara * para)153 static AuthFsm *TranslateToAuthFsm(FsmStateMachine *fsm, int32_t msgType, MessagePara *para)
154 {
155 if (fsm == NULL) {
156 AUTH_LOGE(AUTH_FSM, "fsm is null");
157 return NULL;
158 }
159 AuthFsm *authFsm = TO_AUTH_FSM(fsm);
160 if (authFsm == NULL) {
161 AUTH_LOGE(AUTH_FSM, "authFsm is null");
162 return NULL;
163 }
164 if (authFsm->isDead) {
165 AUTH_LOGE(AUTH_FSM, "auth fsm has dead. authSeq=%{public}" PRId64 "", authFsm->authSeq);
166 return NULL;
167 }
168 /* check para */
169 if ((msgType != FSM_MSG_AUTH_TIMEOUT && msgType != FSM_MSG_DEVICE_NOT_TRUSTED &&
170 msgType != FSM_MSG_DEVICE_DISCONNECTED && msgType != FSM_MSG_STOP_AUTH_FSM) && para == NULL) {
171 AUTH_LOGE(AUTH_FSM, "invalid msgType. msgType=%{public}d", msgType);
172 return NULL;
173 }
174 return authFsm;
175 }
176
GetNextAuthFsmId(void)177 static uint32_t GetNextAuthFsmId(void)
178 {
179 static uint32_t authFsmId = 0;
180 return ++authFsmId;
181 }
182
IsNeedExchangeNetworkId(uint32_t feature,AuthCapability capaBit)183 static bool IsNeedExchangeNetworkId(uint32_t feature, AuthCapability capaBit)
184 {
185 return ((feature & (1 << (uint32_t)capaBit)) != 0);
186 }
187
AddUdidInfo(uint32_t requestId,bool isServer,AuthConnInfo * connInfo)188 static void AddUdidInfo(uint32_t requestId, bool isServer, AuthConnInfo *connInfo)
189 {
190 if (isServer) {
191 AUTH_LOGD(AUTH_FSM, "is not client");
192 return;
193 }
194 AuthRequest request;
195 (void)memset_s(&request, sizeof(request), 0, sizeof(request));
196 if (GetAuthRequestNoLock(requestId, &request) != SOFTBUS_OK) {
197 AUTH_LOGE(AUTH_FSM, "get auth request fail");
198 return;
199 }
200 switch (connInfo->type) {
201 case AUTH_LINK_TYPE_BR:
202 case AUTH_LINK_TYPE_SESSION:
203 break;
204 case AUTH_LINK_TYPE_WIFI:
205 case AUTH_LINK_TYPE_SESSION_KEY:
206 (void)memcpy_s(connInfo->info.ipInfo.deviceIdHash, UDID_HASH_LEN, request.connInfo.info.ipInfo.deviceIdHash,
207 UDID_HASH_LEN);
208 break;
209 case AUTH_LINK_TYPE_BLE:
210 (void)memcpy_s(connInfo->info.bleInfo.deviceIdHash, UDID_HASH_LEN,
211 request.connInfo.info.bleInfo.deviceIdHash, UDID_HASH_LEN);
212 break;
213 case AUTH_LINK_TYPE_P2P:
214 case AUTH_LINK_TYPE_ENHANCED_P2P:
215 if (strcpy_s(connInfo->info.ipInfo.udid, UDID_BUF_LEN, request.connInfo.info.ipInfo.udid) != EOK) {
216 AUTH_LOGE(AUTH_FSM, "strcpy udid fail");
217 return;
218 }
219 break;
220 default:
221 AUTH_LOGE(AUTH_FSM, "error type");
222 }
223 }
224
ProcAuthFsm(uint32_t requestId,bool isServer,AuthFsm * authFsm)225 static int32_t ProcAuthFsm(uint32_t requestId, bool isServer, AuthFsm *authFsm)
226 {
227 AuthRequest request;
228 NodeInfo nodeInfo;
229 (void)memset_s(&request, sizeof(request), 0, sizeof(request));
230 (void)memset_s(&nodeInfo, sizeof(nodeInfo), 0, sizeof(nodeInfo));
231 AddUdidInfo(requestId, isServer, &authFsm->info.connInfo);
232 if (authFsm->info.connInfo.type == AUTH_LINK_TYPE_BLE) {
233 if (GetAuthRequestNoLock(requestId, &request) != SOFTBUS_OK) {
234 AUTH_LOGE(AUTH_FSM, "get auth request fail");
235 return SOFTBUS_AUTH_NOT_FOUND;
236 }
237 char udidHash[SHORT_UDID_HASH_HEX_LEN + 1] = { 0 };
238 int32_t ret = ConvertBytesToHexString(udidHash, SHORT_UDID_HASH_HEX_LEN + 1,
239 (const unsigned char *)request.connInfo.info.bleInfo.deviceIdHash, SHORT_UDID_HASH_LEN);
240 if (ret == SOFTBUS_OK && LnnRetrieveDeviceInfo((const char *)udidHash, &nodeInfo) == SOFTBUS_OK &&
241 IsNeedExchangeNetworkId(nodeInfo.authCapacity, BIT_SUPPORT_EXCHANGE_NETWORKID)) {
242 AUTH_LOGI(AUTH_FSM, "LnnRetrieveDeviceInfo success");
243 authFsm->info.idType = EXCHANGE_NETWORKID;
244 }
245 }
246 return SOFTBUS_OK;
247 }
248
FillSessionInfoModule(uint32_t requestId,AuthSessionInfo * info)249 static int32_t FillSessionInfoModule(uint32_t requestId, AuthSessionInfo *info)
250 {
251 if (!info->isServer) {
252 AuthRequest request;
253 (void)memset_s(&request, sizeof(request), 0, sizeof(request));
254 int32_t ret = GetAuthRequestNoLock(requestId, &request);
255 if (ret != SOFTBUS_OK) {
256 AUTH_LOGE(AUTH_FSM, "get auth request fail");
257 return ret;
258 }
259 info->module = request.module;
260 }
261 return SOFTBUS_OK;
262 }
263
CreateAuthFsm(int64_t authSeq,uint32_t requestId,uint64_t connId,const AuthConnInfo * connInfo,bool isServer)264 static AuthFsm *CreateAuthFsm(
265 int64_t authSeq, uint32_t requestId, uint64_t connId, const AuthConnInfo *connInfo, bool isServer)
266 {
267 AuthFsm *authFsm = (AuthFsm *)SoftBusCalloc(sizeof(AuthFsm));
268 if (authFsm == NULL) {
269 AUTH_LOGE(AUTH_FSM, "malloc AuthFsm fail");
270 return NULL;
271 }
272 authFsm->id = GetNextAuthFsmId();
273 authFsm->authSeq = authSeq;
274 authFsm->info.requestId = requestId;
275 authFsm->info.isServer = isServer;
276 authFsm->info.isConnectServer = isServer;
277 authFsm->info.connId = connId;
278 authFsm->info.connInfo = *connInfo;
279 authFsm->info.version = SOFTBUS_NEW_V2;
280 authFsm->info.idType = EXCHANGE_UDID;
281 authFsm->info.isSupportDmDeviceKey = false;
282 if (FillSessionInfoModule(requestId, &authFsm->info) != SOFTBUS_OK) {
283 AUTH_LOGE(AUTH_FSM, "fill module fail");
284 SoftBusFree(authFsm);
285 return NULL;
286 }
287 if (!isServer) {
288 if (ProcAuthFsm(requestId, isServer, authFsm) != SOFTBUS_OK) {
289 SoftBusFree(authFsm);
290 return NULL;
291 }
292 }
293 if (sprintf_s(authFsm->fsmName, sizeof(authFsm->fsmName), "AuthFsm-%u", authFsm->id) == -1) {
294 AUTH_LOGE(AUTH_FSM, "format auth fsm name fail");
295 SoftBusFree(authFsm);
296 return NULL;
297 }
298 if (LnnFsmInit(&authFsm->fsm, NULL, authFsm->fsmName, AuthFsmDeinitCallback) != SOFTBUS_OK) {
299 AUTH_LOGE(AUTH_FSM, "init fsm fail");
300 SoftBusFree(authFsm);
301 return NULL;
302 }
303 for (int32_t i = 0; i < STATE_NUM_MAX; ++i) {
304 LnnFsmAddState(&authFsm->fsm, &g_states[i]);
305 }
306 ListNodeInsert(&g_authFsmList, &authFsm->node);
307 AUTH_LOGI(AUTH_FSM,
308 "create auth fsm. authSeq=%{public}" PRId64 ", name=%{public}s, side=%{public}s, requestId=%{public}u, "
309 "" CONN_INFO, authFsm->authSeq, authFsm->fsmName, GetAuthSideStr(isServer), requestId, CONN_DATA(connId));
310 return authFsm;
311 }
312
DestroyAuthFsm(AuthFsm * authFsm)313 static void DestroyAuthFsm(AuthFsm *authFsm)
314 {
315 AUTH_LOGI(AUTH_FSM, "destroy auth. authSeq=%{public}" PRId64 ", side=%{public}s, requestId=%{public}u",
316 authFsm->authSeq, GetAuthSideStr(authFsm->info.isServer), authFsm->info.requestId);
317 ListDelete(&authFsm->node);
318 if (authFsm->info.deviceInfoData != NULL) {
319 SoftBusFree(authFsm->info.deviceInfoData);
320 authFsm->info.deviceInfoData = NULL;
321 }
322 if (authFsm->info.normalizedKey != NULL) {
323 SoftBusFree(authFsm->info.normalizedKey);
324 authFsm->info.normalizedKey = NULL;
325 }
326 SoftBusFree(authFsm);
327 }
328
AuthFsmDeinitCallback(FsmStateMachine * fsm)329 static void AuthFsmDeinitCallback(FsmStateMachine *fsm)
330 {
331 static uint32_t callCount = 0;
332 AUTH_LOGI(AUTH_FSM, "auth fsm deinit callback enter, callCount=%{public}u", callCount++);
333 if (fsm == NULL) {
334 AUTH_LOGE(AUTH_FSM, "fsm is null");
335 return;
336 }
337 if (!RequireAuthLock()) {
338 return;
339 }
340 DestroyAuthFsm(TO_AUTH_FSM(fsm));
341 ReleaseAuthLock();
342 }
343
NewMessagePara(const uint8_t * data,uint32_t len)344 static MessagePara *NewMessagePara(const uint8_t *data, uint32_t len)
345 {
346 MessagePara *para = (MessagePara *)SoftBusCalloc(sizeof(MessagePara) + len);
347 if (para == NULL) {
348 AUTH_LOGE(AUTH_FSM, "malloc ExchangeDataPara fail");
349 return NULL;
350 }
351 para->len = len;
352 if (data != NULL && len > 0 && memcpy_s(para->data, len, data, len) != EOK) {
353 AUTH_LOGE(AUTH_FSM, "copy data fail");
354 SoftBusFree(para);
355 return NULL;
356 }
357 return para;
358 }
359
FreeMessagePara(MessagePara * para)360 static void FreeMessagePara(MessagePara *para)
361 {
362 if (para != NULL) {
363 SoftBusFree(para);
364 }
365 }
366
ConvertAuthLinkTypeToHisysEvtLinkType(AuthLinkType type)367 static SoftBusLinkType ConvertAuthLinkTypeToHisysEvtLinkType(AuthLinkType type)
368 {
369 switch (type) {
370 case AUTH_LINK_TYPE_WIFI:
371 case AUTH_LINK_TYPE_SESSION_KEY:
372 return SOFTBUS_HISYSEVT_LINK_TYPE_WLAN;
373 case AUTH_LINK_TYPE_BR:
374 return SOFTBUS_HISYSEVT_LINK_TYPE_BR;
375 case AUTH_LINK_TYPE_BLE:
376 return SOFTBUS_HISYSEVT_LINK_TYPE_BLE;
377 case AUTH_LINK_TYPE_P2P:
378 return SOFTBUS_HISYSEVT_LINK_TYPE_P2P;
379 default:
380 return SOFTBUS_HISYSEVT_LINK_TYPE_BUTT;
381 }
382 }
383
DfxRecordLnnAuthEnd(AuthFsm * authFsm,uint64_t costTime,int32_t reason)384 static void DfxRecordLnnAuthEnd(AuthFsm *authFsm, uint64_t costTime, int32_t reason)
385 {
386 LnnEventExtra extra = { 0 };
387 LnnEventExtraInit(&extra);
388 extra.errcode = reason;
389 extra.authCostTime = (int32_t)costTime;
390 extra.result = (reason == SOFTBUS_OK) ? EVENT_STAGE_RESULT_OK : EVENT_STAGE_RESULT_FAILED;
391
392 if (authFsm != NULL) {
393 extra.authLinkType = authFsm->info.connInfo.type;
394 extra.authId = (int32_t)authFsm->authSeq;
395 extra.authRequestId = (int32_t)authFsm->info.requestId;
396 }
397 LNN_EVENT(EVENT_SCENE_JOIN_LNN, EVENT_STAGE_AUTH, extra);
398 }
399
ReportAuthResultEvt(AuthFsm * authFsm,int32_t result)400 static void ReportAuthResultEvt(AuthFsm *authFsm, int32_t result)
401 {
402 AUTH_LOGE(AUTH_FSM, "report auth result evt enter");
403 SoftBusLinkType linkType = ConvertAuthLinkTypeToHisysEvtLinkType(authFsm->info.connInfo.type);
404 if (linkType == SOFTBUS_HISYSEVT_LINK_TYPE_BUTT) {
405 return;
406 }
407 authFsm->statisticData.endAuthTime = (uint64_t)LnnUpTimeMs();
408 uint64_t costTime = authFsm->statisticData.endAuthTime - authFsm->statisticData.startAuthTime;
409 DfxRecordLnnAuthEnd(authFsm, costTime, result);
410 AuthFailStage stage = AUTH_STAGE_BUTT;
411
412 if (result == SOFTBUS_OK) {
413 if (SoftBusRecordAuthResult(linkType, SOFTBUS_OK, costTime, AUTH_STAGE_BUTT) != SOFTBUS_OK) {
414 AUTH_LOGE(AUTH_FSM, "report static auth result fail");
415 }
416 return;
417 } else if (result == SOFTBUS_AUTH_SYNC_DEVID_FAIL || result == SOFTBUS_AUTH_SYNC_DEVINFO_FAIL ||
418 result == SOFTBUS_AUTH_UNPACK_DEVINFO_FAIL || result == SOFTBUS_AUTH_SEND_FAIL ||
419 result == SOFTBUS_AUTH_NOT_SUPPORT_THREE_STATE) {
420 stage = AUTH_EXCHANGE_STAGE;
421 } else if (result == SOFTBUS_AUTH_DEVICE_DISCONNECTED) {
422 stage = AUTH_CONNECT_STAGE;
423 } else if (result == SOFTBUS_AUTH_HICHAIN_PROCESS_FAIL || result == SOFTBUS_AUTH_TIMEOUT ||
424 result == SOFTBUS_AUTH_HICHAIN_NOT_TRUSTED) {
425 stage = AUTH_VERIFY_STAGE;
426 } else if (result >= SOFTBUS_HICHAIN_MIN && result <= SOFTBUS_HICHAIN_MAX) {
427 stage = AUTH_VERIFY_STAGE;
428 } else {
429 AUTH_LOGE(AUTH_FSM, "unsupport result=%{public}d.", result);
430 return;
431 }
432
433 if (SoftBusRecordAuthResult(linkType, result, costTime, stage) != SOFTBUS_OK) {
434 AUTH_LOGE(AUTH_FSM, "report static auth result fail");
435 }
436 SoftBusFaultEvtInfo info;
437 (void)memset_s(&info, sizeof(SoftBusFaultEvtInfo), 0, sizeof(SoftBusFaultEvtInfo));
438 info.moduleType = MODULE_TYPE_AUTH;
439 info.linkType = linkType;
440 info.errorCode = result;
441 if (SoftBusReportBusCenterFaultEvt(&info) != SOFTBUS_OK) {
442 AUTH_LOGE(AUTH_FSM, "report buscenter fault evt fail");
443 }
444 }
445
SaveDeviceKey(AuthFsm * authFsm,int32_t keyType,AuthLinkType type)446 static void SaveDeviceKey(AuthFsm *authFsm, int32_t keyType, AuthLinkType type)
447 {
448 AuthDeviceKeyInfo deviceKey;
449 SessionKey sessionKey;
450 (void)memset_s(&deviceKey, sizeof(AuthDeviceKeyInfo), 0, sizeof(AuthDeviceKeyInfo));
451 (void)memset_s(&sessionKey, sizeof(SessionKey), 0, sizeof(SessionKey));
452 if (AuthManagerGetSessionKey(authFsm->authSeq, &authFsm->info, &sessionKey) != SOFTBUS_OK) {
453 AUTH_LOGE(AUTH_FSM, "get session key fail");
454 return;
455 }
456 if (memcpy_s(deviceKey.deviceKey, sizeof(deviceKey.deviceKey), sessionKey.value, sizeof(sessionKey.value)) != EOK) {
457 AUTH_LOGE(AUTH_FSM, "session key cpy fail");
458 (void)memset_s(&sessionKey, sizeof(SessionKey), 0, sizeof(SessionKey));
459 return;
460 }
461 deviceKey.keyLen = sessionKey.len;
462 deviceKey.keyIndex = authFsm->authSeq;
463 deviceKey.keyType = keyType;
464 deviceKey.isServerSide = authFsm->info.isServer;
465 if (AuthInsertDeviceKey(&authFsm->info.nodeInfo, &deviceKey, type) != SOFTBUS_OK) {
466 AUTH_LOGE(AUTH_FSM, "insert deviceKey fail");
467 }
468 (void)memset_s(&deviceKey, sizeof(AuthDeviceKeyInfo), 0, sizeof(AuthDeviceKeyInfo));
469 (void)memset_s(&sessionKey, sizeof(SessionKey), 0, sizeof(SessionKey));
470 }
471
GetAuthFsmByConnInfo(const AuthConnInfo * connInfo,bool isServer)472 static AuthFsm *GetAuthFsmByConnInfo(const AuthConnInfo *connInfo, bool isServer)
473 {
474 AuthFsm *item = NULL;
475 LIST_FOR_EACH_ENTRY(item, &g_authFsmList, AuthFsm, node) {
476 if (!CompareConnInfo(&item->info.connInfo, connInfo, true) || item->info.isConnectServer != isServer) {
477 continue;
478 }
479 if (item->isDead) {
480 AUTH_LOGE(AUTH_FSM, "auth fsm has dead. authSeq=%{public}" PRId64 "", item->authSeq);
481 break;
482 }
483 return item;
484 }
485 return NULL;
486 }
487
ProcessTimeoutErrorCode(AuthFsm * authFsm,int32_t * result)488 static void ProcessTimeoutErrorCode(AuthFsm *authFsm, int32_t *result)
489 {
490 AuthFsmStateIndex curState = authFsm->curState;
491 if (curState == STATE_SYNC_NEGOTIATION || curState == STATE_SYNC_DEVICE_ID) {
492 *result = SOFTBUS_AUTH_SYNC_DEVICEID_TIMEOUT;
493 } else if (curState == STATE_DEVICE_AUTH) {
494 *result = (authFsm->info.normalizedType == NORMALIZED_SUPPORT || authFsm->info.isSupportFastAuth) ?
495 SOFTBUS_AUTH_SAVE_SESSIONKEY_TIMEOUT : SOFTBUS_AUTH_HICHAIN_TIMEOUT;
496 } else if (curState == STATE_SYNC_DEVICE_INFO) {
497 *result = SOFTBUS_AUTH_SYNC_DEVICEINFO_TIMEOUT;
498 } else {
499 AUTH_LOGE(AUTH_FSM, "authFsm state error, curState=%{public}d", curState);
500 }
501 }
502
CompleteAuthSession(AuthFsm * authFsm,int32_t result)503 static void CompleteAuthSession(AuthFsm *authFsm, int32_t result)
504 {
505 SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)authFsm->authSeq);
506 AUTH_LOGI(AUTH_FSM, "auth fsm complete. authSeq=%{public}" PRId64 ", side=%{public}s, result=%{public}d",
507 authFsm->authSeq, GetAuthSideStr(authFsm->info.isServer), result);
508 ReportAuthResultEvt(authFsm, result);
509 if (result == SOFTBUS_OK) {
510 AuthManagerSetAuthFinished(authFsm->authSeq, &authFsm->info);
511 if (authFsm->info.normalizedType == NORMALIZED_KEY_ERROR) {
512 AUTH_LOGI(AUTH_FSM, "only hichain verify, save the device key");
513 SaveDeviceKey(authFsm, AUTH_LINK_TYPE_NORMALIZED, authFsm->info.connInfo.type);
514 } else if ((authFsm->info.normalizedType == NORMALIZED_NOT_SUPPORT) &&
515 (authFsm->info.connInfo.type == AUTH_LINK_TYPE_BLE) && !authFsm->info.isSupportFastAuth) {
516 AUTH_LOGI(AUTH_FSM, "save device key for fast auth");
517 SaveDeviceKey(authFsm, AUTH_LINK_TYPE_BLE, AUTH_LINK_TYPE_BLE);
518 }
519 if (!authFsm->info.isServer) {
520 NotifyNormalizeRequestSuccess(authFsm->authSeq, true);
521 }
522 // Disconnect another request and notify auth success
523 if (authFsm->info.isConnectServer && authFsm->info.peerState != AUTH_STATE_COMPATIBLE) {
524 AuthFsm *stopFsm = GetAuthFsmByConnInfo(&authFsm->info.connInfo, !authFsm->info.isConnectServer);
525 if (stopFsm != NULL) {
526 AuthNotifyAuthPassed(stopFsm->authSeq, &stopFsm->info);
527 LnnFsmPostMessage(&stopFsm->fsm, FSM_MSG_STOP_AUTH_FSM, NULL);
528 }
529 }
530 } else {
531 if (result == SOFTBUS_AUTH_TIMEOUT) {
532 ProcessTimeoutErrorCode(authFsm, &result);
533 }
534 LnnFsmRemoveMessage(&authFsm->fsm, FSM_MSG_AUTH_TIMEOUT);
535 if (!authFsm->info.isServer) {
536 NotifyNormalizeRequestFail(authFsm->authSeq, result);
537 }
538 AuthManagerSetAuthFailed(authFsm->authSeq, &authFsm->info, result);
539 }
540
541 authFsm->isDead = true;
542 LnnFsmStop(&authFsm->fsm);
543 LnnFsmDeinit(&authFsm->fsm);
544 SoftbusHitraceStop();
545 }
546
StopAuthFsm(AuthFsm * authFsm)547 static void StopAuthFsm(AuthFsm *authFsm)
548 {
549 authFsm->isDead = true;
550 LnnFsmStop(&authFsm->fsm);
551 LnnFsmDeinit(&authFsm->fsm);
552 }
553
HandleCommonMsg(AuthFsm * authFsm,int32_t msgType,MessagePara * msgPara)554 static void HandleCommonMsg(AuthFsm *authFsm, int32_t msgType, MessagePara *msgPara)
555 {
556 (void)msgPara;
557 switch (msgType) {
558 case FSM_MSG_AUTH_TIMEOUT:
559 AUTH_LOGE(AUTH_FSM, "auth fsm timeout. authSeq=%{public}" PRId64 "", authFsm->authSeq);
560 CompleteAuthSession(authFsm, SOFTBUS_AUTH_TIMEOUT);
561 HichainCancelRequest(authFsm->authSeq);
562 break;
563 case FSM_MSG_DEVICE_NOT_TRUSTED:
564 CompleteAuthSession(authFsm, SOFTBUS_AUTH_HICHAIN_NOT_TRUSTED);
565 HichainCancelRequest(authFsm->authSeq);
566 break;
567 case FSM_MSG_DEVICE_DISCONNECTED:
568 if (authFsm->info.isNodeInfoReceived && authFsm->info.isCloseAckReceived) {
569 AUTH_LOGW(AUTH_FSM,
570 "auth fsm wait for the finish event, ignore this disconnect event. authSeq=%{public}" PRId64 "",
571 authFsm->authSeq);
572 /*
573 * Note: Local hichain NOT onFinish, but remote hichain already onFinish
574 * Regard this situation as auth finish
575 */
576 CompleteAuthSession(authFsm, SOFTBUS_OK);
577 break;
578 }
579 CompleteAuthSession(authFsm, SOFTBUS_AUTH_DEVICE_DISCONNECTED);
580 HichainCancelRequest(authFsm->authSeq);
581 break;
582 case FSM_MSG_STOP_AUTH_FSM:
583 StopAuthFsm(authFsm);
584 break;
585 default:
586 AUTH_LOGE(AUTH_FSM, "auth fsm cannot handle msgType. authSeq=%{public}" PRId64 ", msgType=%{public}d",
587 authFsm->authSeq, msgType);
588 break;
589 }
590 }
591
AddConcurrentAuthRequest(AuthFsm * authFsm)592 static uint32_t AddConcurrentAuthRequest(AuthFsm *authFsm)
593 {
594 uint32_t num = 0;
595 if (strlen(authFsm->info.udidHash) == 0) {
596 AUTH_LOGE(AUTH_FSM, "udidHash is null, authSeq=%{public}" PRId64, authFsm->authSeq);
597 return num;
598 }
599 NormalizeRequest normalizeRequest = {
600 .authSeq = authFsm->authSeq,
601 .connInfo = authFsm->info.connInfo,
602 .isConnectServer = authFsm->info.isConnectServer
603 };
604 if (strcpy_s(normalizeRequest.udidHash, sizeof(normalizeRequest.udidHash), authFsm->info.udidHash) != EOK) {
605 AUTH_LOGE(AUTH_FSM, "strcpy udid hash fail. authSeq=%{public}" PRId64, authFsm->authSeq);
606 return num;
607 }
608 num = AddNormalizeRequest(&normalizeRequest);
609 char *anonyUdidHash = NULL;
610 Anonymize(normalizeRequest.udidHash, &anonyUdidHash);
611 AUTH_LOGI(AUTH_CONN, "add normalize queue, num=%{public}d, udidHash=%{public}s",
612 num, AnonymizeWrapper(anonyUdidHash));
613 AnonymizeFree(anonyUdidHash);
614 return num;
615 }
616
SyncNegotiationEnter(FsmStateMachine * fsm)617 static void SyncNegotiationEnter(FsmStateMachine *fsm)
618 {
619 if (fsm == NULL) {
620 AUTH_LOGE(AUTH_FSM, "fsm is null");
621 return;
622 }
623 AuthFsm *authFsm = TO_AUTH_FSM(fsm);
624 if (authFsm == NULL) {
625 AUTH_LOGE(AUTH_FSM, "authFsm is null");
626 return;
627 }
628 authFsm->curState = STATE_SYNC_NEGOTIATION;
629 AUTH_LOGI(AUTH_FSM, "SyncNegotiationState: auth fsm enter. authSeq=%{public}" PRId64, authFsm->authSeq);
630 if (!authFsm->info.isServer) {
631 if (PostDeviceIdMessage(authFsm->authSeq, &authFsm->info) != SOFTBUS_OK) {
632 CompleteAuthSession(authFsm, SOFTBUS_AUTH_SYNC_DEVID_FAIL);
633 }
634 }
635 }
636
HandleMsgPostDeviceId(AuthFsm * authFsm,const MessagePara * para)637 static void HandleMsgPostDeviceId(AuthFsm *authFsm, const MessagePara *para)
638 {
639 (void)para;
640 AuthSessionInfo *info = &authFsm->info;
641 if (PostDeviceIdMessage(authFsm->authSeq, info) != SOFTBUS_OK) {
642 CompleteAuthSession(authFsm, SOFTBUS_AUTH_SYNC_DEVID_FAIL);
643 return;
644 }
645 if (info->isServer) {
646 LnnFsmTransactState(&authFsm->fsm, g_states + STATE_DEVICE_AUTH);
647 }
648 }
649
SyncDevIdStateEnter(FsmStateMachine * fsm)650 static void SyncDevIdStateEnter(FsmStateMachine *fsm)
651 {
652 if (fsm == NULL) {
653 AUTH_LOGE(AUTH_FSM, "fsm is null");
654 return;
655 }
656 AuthFsm *authFsm = TO_AUTH_FSM(fsm);
657 if (authFsm == NULL) {
658 AUTH_LOGE(AUTH_FSM, "authFsm is null");
659 return;
660 }
661 authFsm->curState = STATE_SYNC_DEVICE_ID;
662 SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)authFsm->authSeq);
663 AUTH_LOGI(AUTH_FSM, "SyncDevIdState: auth fsm enter. authSeq=%{public}" PRId64 "", authFsm->authSeq);
664 if (!authFsm->info.isServer) {
665 if (authFsm->info.localState == AUTH_STATE_START) {
666 if (!AuthIsRepeatedAuthRequest(authFsm->authSeq) && AddConcurrentAuthRequest(authFsm) > 1) {
667 AUTH_LOGI(AUTH_FSM, "wait another auth, authSeq=%{public}" PRId64 "", authFsm->authSeq);
668 return;
669 }
670 }
671 if (PostDeviceIdMessage(authFsm->authSeq, &authFsm->info) != SOFTBUS_OK) {
672 CompleteAuthSession(authFsm, SOFTBUS_AUTH_SYNC_DEVID_FAIL);
673 }
674 }
675 SoftbusHitraceStop();
676 }
677
SaveLastAuthSeq(const unsigned char * udidHash,int64_t authSeq)678 static void SaveLastAuthSeq(const unsigned char *udidHash, int64_t authSeq)
679 {
680 AUTH_LOGI(AUTH_FSM, "save auth seq.authSeq=%{public}" PRId64, authSeq);
681 char hashStr[SHORT_UDID_HASH_HEX_LEN + 1] = { 0 };
682 if (ConvertBytesToHexString(
683 hashStr, SHORT_UDID_HASH_HEX_LEN + 1, udidHash, SHORT_UDID_HASH_HEX_LEN / HEXIFY_UNIT_LEN) != SOFTBUS_OK) {
684 AUTH_LOGE(AUTH_FSM, "convert udidhash to hexstr fail.");
685 return;
686 }
687 NodeInfo deviceInfo;
688 (void)memset_s(&deviceInfo, sizeof(NodeInfo), 0, sizeof(NodeInfo));
689 if (LnnRetrieveDeviceInfo(hashStr, &deviceInfo) != SOFTBUS_OK) {
690 AUTH_LOGE(AUTH_FSM, "no this device info.");
691 return;
692 }
693 deviceInfo.lastAuthSeq = authSeq;
694 if (LnnSaveRemoteDeviceInfo(&deviceInfo) != SOFTBUS_OK) {
695 AUTH_LOGE(AUTH_FSM, "save device info fail.");
696 }
697 }
698
RecoveryNormalizedDeviceKey(AuthFsm * authFsm)699 static int32_t RecoveryNormalizedDeviceKey(AuthFsm *authFsm)
700 {
701 if (authFsm->info.normalizedKey == NULL) {
702 AUTH_LOGE(AUTH_FSM, "normalizedKey is NULL, auth fail");
703 return SOFTBUS_INVALID_PARAM;
704 }
705 uint8_t hash[SHA_256_HASH_LEN] = { 0 };
706 int32_t ret = SoftBusGenerateStrHash((uint8_t *)authFsm->info.udid, strlen(authFsm->info.udid), hash);
707 if (ret != SOFTBUS_OK) {
708 AUTH_LOGE(AUTH_FSM, "generate udidHash fail");
709 return ret;
710 }
711 char udidShortHash[SHORT_UDID_HASH_HEX_LEN + 1] = { 0 };
712 if (ConvertBytesToUpperCaseHexString(udidShortHash, SHORT_UDID_HASH_HEX_LEN + 1, hash, SHORT_UDID_HASH_LEN) !=
713 SOFTBUS_OK) {
714 AUTH_LOGE(AUTH_FSM, "convert bytes to string fail");
715 return SOFTBUS_NETWORK_BYTES_TO_HEX_STR_ERR;
716 }
717 AuthUpdateNormalizeKeyIndex(udidShortHash, authFsm->info.normalizedIndex, authFsm->info.connInfo.type,
718 authFsm->info.normalizedKey, authFsm->info.isServer);
719 if (authFsm->info.connInfo.type == AUTH_LINK_TYPE_BLE) {
720 SaveLastAuthSeq(hash, authFsm->authSeq);
721 }
722 ret = AuthSessionSaveSessionKey(
723 authFsm->authSeq, authFsm->info.normalizedKey->value, authFsm->info.normalizedKey->len);
724 if (ret != SOFTBUS_OK) {
725 AUTH_LOGE(AUTH_FSM, "post save sessionKey event fail");
726 return ret;
727 }
728 return AuthSessionHandleAuthFinish(authFsm->authSeq);
729 }
730
RecoveryFastAuthKey(AuthFsm * authFsm)731 static int32_t RecoveryFastAuthKey(AuthFsm *authFsm)
732 {
733 AuthDeviceKeyInfo key = { 0 };
734 uint8_t hash[SHA_256_HASH_LEN] = { 0 };
735 int32_t ret = SoftBusGenerateStrHash((uint8_t *)authFsm->info.udid, strlen(authFsm->info.udid), hash);
736 if (ret != SOFTBUS_OK) {
737 AUTH_LOGE(AUTH_FSM, "generate udidHash fail");
738 return ret;
739 }
740 char udidShortHash[SHORT_UDID_HASH_HEX_LEN + 1] = { 0 };
741 if (ConvertBytesToUpperCaseHexString(udidShortHash, SHORT_UDID_HASH_HEX_LEN + 1, hash, SHORT_UDID_HASH_LEN) !=
742 SOFTBUS_OK) {
743 AUTH_LOGE(AUTH_FSM, "convert bytes to string fail");
744 return SOFTBUS_NETWORK_BYTES_TO_HEX_STR_ERR;
745 }
746 AuthLinkType linkType = authFsm->info.connInfo.type;
747 if (authFsm->info.connInfo.type == AUTH_LINK_TYPE_ENHANCED_P2P) {
748 // enhanced p2p reuse ble authKey
749 linkType = AUTH_LINK_TYPE_BLE;
750 }
751 if (AuthFindDeviceKey(udidShortHash, linkType, &key) != SOFTBUS_OK) {
752 AUTH_LOGE(AUTH_FSM, "find key fail, fastAuth error");
753 return SOFTBUS_AUTH_NOT_FOUND;
754 }
755 AuthUpdateKeyIndex(udidShortHash, authFsm->info.connInfo.type, authFsm->authSeq, authFsm->info.isServer);
756 authFsm->info.oldIndex = key.keyIndex;
757 ret = AuthSessionSaveSessionKey(authFsm->authSeq, key.deviceKey, key.keyLen);
758 if (ret != SOFTBUS_OK) {
759 AUTH_LOGE(AUTH_FSM, "post save sessionKey event");
760 (void)memset_s(&key, sizeof(AuthDeviceKeyInfo), 0, sizeof(AuthDeviceKeyInfo));
761 return ret;
762 }
763 (void)memset_s(&key, sizeof(AuthDeviceKeyInfo), 0, sizeof(AuthDeviceKeyInfo));
764 return AuthSessionHandleAuthFinish(authFsm->authSeq);
765 }
766
ReuseDeviceKey(AuthFsm * authFsm)767 static int32_t ReuseDeviceKey(AuthFsm *authFsm)
768 {
769 AuthDeviceKeyInfo key = { 0 };
770 AuthPreLinkNode node;
771 int32_t ret;
772 (void)memset_s(&node, sizeof(AuthPreLinkNode), 0, sizeof(AuthPreLinkNode));
773 if (FindAuthPreLinkNodeById(authFsm->info.requestId, &node) != SOFTBUS_OK) {
774 AUTH_LOGE(AUTH_FSM, "get reuse device key fail");
775 return SOFTBUS_AUTH_SESSION_KEY_NOT_FOUND;
776 }
777 if (node.keyLen == 0) {
778 AUTH_LOGE(AUTH_FSM, "get reuse device key length is 0");
779 return SOFTBUS_AUTH_SESSION_KEY_NOT_FOUND;
780 }
781 if (memcpy_s(key.deviceKey, SESSION_KEY_LENGTH, node.localDeviceKey, SESSION_KEY_LENGTH) != EOK) {
782 AUTH_LOGE(AUTH_FSM, "memcpy device key fail");
783 return SOFTBUS_MEM_ERR;
784 }
785 key.keyLen = node.keyLen;
786 ret = AuthSessionSaveSessionKey(authFsm->authSeq, key.deviceKey, key.keyLen);
787 if (ret != SOFTBUS_OK) {
788 AUTH_LOGE(AUTH_FSM, "post save sessionKey event");
789 (void)memset_s(&key, sizeof(AuthDeviceKeyInfo), 0, sizeof(AuthDeviceKeyInfo));
790 return ret;
791 }
792 (void)memset_s(&key, sizeof(AuthDeviceKeyInfo), 0, sizeof(AuthDeviceKeyInfo));
793 return SOFTBUS_OK;
794 }
795
AuditReportSetPeerDevInfo(LnnAuditExtra * lnnAuditExtra,AuthSessionInfo * info)796 static void AuditReportSetPeerDevInfo(LnnAuditExtra *lnnAuditExtra, AuthSessionInfo *info)
797 {
798 if (lnnAuditExtra == NULL || info == NULL) {
799 AUTH_LOGE(AUTH_FSM, "lnnAuditExtra or info is null");
800 return;
801 }
802 char *anonyBrMac = NULL;
803 char *anonyBleMac = NULL;
804 char *anonyIp = NULL;
805 switch (info->connInfo.type) {
806 case AUTH_LINK_TYPE_BR:
807 Anonymize(info->connInfo.info.brInfo.brMac, &anonyBrMac);
808 if (strcpy_s((char *)lnnAuditExtra->peerBrMac, BT_MAC_LEN, AnonymizeWrapper(anonyBrMac)) != EOK) {
809 AUTH_LOGE(AUTH_FSM, "BR MAC COPY ERROR");
810 }
811 AnonymizeFree(anonyBrMac);
812 break;
813 case AUTH_LINK_TYPE_BLE:
814 Anonymize(info->connInfo.info.bleInfo.bleMac, &anonyBleMac);
815 if (strcpy_s((char *)lnnAuditExtra->peerBleMac, BT_MAC_LEN, AnonymizeWrapper(anonyBleMac)) != EOK) {
816 AUTH_LOGE(AUTH_FSM, "BLE MAC COPY ERROR");
817 }
818 AnonymizeFree(anonyBleMac);
819 break;
820 case AUTH_LINK_TYPE_WIFI:
821 case AUTH_LINK_TYPE_P2P:
822 case AUTH_LINK_TYPE_ENHANCED_P2P:
823 case AUTH_LINK_TYPE_SESSION_KEY:
824 Anonymize(info->connInfo.info.ipInfo.ip, &anonyIp);
825 if (strcpy_s((char *)lnnAuditExtra->peerIp, IP_STR_MAX_LEN, AnonymizeWrapper(anonyIp)) != EOK) {
826 AUTH_LOGE(AUTH_FSM, "IP COPY ERROR");
827 }
828 AnonymizeFree(anonyIp);
829 lnnAuditExtra->peerAuthPort = info->connInfo.info.ipInfo.port;
830 break;
831 default:
832 AUTH_LOGW(AUTH_FSM, "unknow param type!");
833 break;
834 }
835 }
836
GetLocalDevReportInfo(AuditReportDevInfo * reportInfo,LnnAuditExtra * lnnAuditExtra)837 static void GetLocalDevReportInfo(AuditReportDevInfo *reportInfo, LnnAuditExtra *lnnAuditExtra)
838 {
839 (void)LnnGetLocalStrInfo(STRING_KEY_WLAN_IP, reportInfo->localIp, IP_LEN);
840 char *anonyLocalIp = NULL;
841 Anonymize(reportInfo->localIp, &anonyLocalIp);
842 if (strcpy_s((char *)lnnAuditExtra->localIp, IP_LEN, AnonymizeWrapper(anonyLocalIp)) != EOK) {
843 AUTH_LOGE(AUTH_FSM, "LOCAL IP COPY ERROR");
844 }
845 AnonymizeFree(anonyLocalIp);
846
847 (void)LnnGetLocalStrInfo(STRING_KEY_BT_MAC, reportInfo->localBrMac, MAC_LEN);
848 char *anonyLocalBrMac = NULL;
849 Anonymize(reportInfo->localBrMac, &anonyLocalBrMac);
850 if (strcpy_s((char *)lnnAuditExtra->localBrMac, MAC_LEN, AnonymizeWrapper(anonyLocalBrMac)) != EOK) {
851 AUTH_LOGE(AUTH_FSM, "LOCAL BR MAC COPY ERROR");
852 }
853 AnonymizeFree(anonyLocalBrMac);
854
855 (void)LnnGetLocalStrInfo(STRING_KEY_BLE_MAC, reportInfo->localBleMac, MAC_LEN);
856 char *anonyLocalBleMac = NULL;
857 Anonymize(reportInfo->localBleMac, &anonyLocalBleMac);
858 if (strcpy_s((char *)lnnAuditExtra->localBleMac, MAC_LEN, AnonymizeWrapper(anonyLocalBleMac)) != EOK) {
859 AUTH_LOGE(AUTH_FSM, "LOCAL BLE MAC COPY ERROR");
860 }
861 AnonymizeFree(anonyLocalBleMac);
862
863 (void)LnnGetLocalStrInfo(STRING_KEY_NETWORKID, reportInfo->localNetworkId, NETWORK_ID_BUF_LEN);
864 char *anonyLocalNetworkId = NULL;
865 Anonymize(reportInfo->localNetworkId, &anonyLocalNetworkId);
866 if (strcpy_s((char *)lnnAuditExtra->localNetworkId, NETWORK_ID_BUF_LEN, AnonymizeWrapper(anonyLocalNetworkId)) !=
867 EOK) {
868 AUTH_LOGE(AUTH_FSM, "LOCAL NETWORKID COPY ERROR");
869 }
870 AnonymizeFree(anonyLocalNetworkId);
871
872 (void)LnnGetLocalStrInfo(STRING_KEY_DEV_NAME, reportInfo->localDevName, DEVICE_NAME_BUF_LEN);
873 char *anonyLocalDevName = NULL;
874 Anonymize(reportInfo->localDevName, &anonyLocalDevName);
875 if (strcpy_s((char *)lnnAuditExtra->localDevName, DEVICE_NAME_BUF_LEN, AnonymizeWrapper(anonyLocalDevName)) !=
876 EOK) {
877 AUTH_LOGE(AUTH_FSM, "LOCAL DEVICE NAME COPY ERROR");
878 }
879 AnonymizeFree(anonyLocalDevName);
880 }
881
AuditReportSetLocalDevInfo(LnnAuditExtra * lnnAuditExtra)882 static void AuditReportSetLocalDevInfo(LnnAuditExtra *lnnAuditExtra)
883 {
884 if (lnnAuditExtra == NULL) {
885 AUTH_LOGE(AUTH_FSM, "lnnAuditExtra is null");
886 return;
887 }
888 AuditReportDevInfo reportInfo;
889 (void)memset_s(&reportInfo, sizeof(AuditReportDevInfo), 0, sizeof(AuditReportDevInfo));
890 GetLocalDevReportInfo(&reportInfo, lnnAuditExtra);
891 (void)LnnGetLocalNumInfo(NUM_KEY_AUTH_PORT, &lnnAuditExtra->localAuthPort);
892 (void)LnnGetLocalNumInfo(NUM_KEY_PROXY_PORT, &lnnAuditExtra->localProxyPort);
893 (void)LnnGetLocalNumInfo(NUM_KEY_SESSION_PORT, &lnnAuditExtra->localSessionPort);
894 (void)LnnGetLocalNumInfo(NUM_KEY_DEV_TYPE_ID, &lnnAuditExtra->localDevType);
895 char udid[UDID_BUF_LEN] = { 0 };
896 uint8_t udidHash[SHA_256_HASH_LEN] = { 0 };
897 if (LnnGetLocalStrInfo(STRING_KEY_DEV_UDID, udid, UUID_BUF_LEN) != SOFTBUS_OK) {
898 AUTH_LOGE(AUTH_FSM, "get local udid fail");
899 return;
900 }
901 int32_t ret = SoftBusGenerateStrHash((const unsigned char *)udid, strlen(udid), udidHash);
902 if (ret != SOFTBUS_OK) {
903 AUTH_LOGE(AUTH_FSM, "generate udid hash fail");
904 return;
905 }
906 if (ConvertBytesToUpperCaseHexString(reportInfo.localUdid, SHA_256_HEX_HASH_LEN, udidHash, SHA_256_HASH_LEN) !=
907 SOFTBUS_OK) {
908 AUTH_LOGE(AUTH_FSM, "convert hash to upper hex str fail");
909 }
910 char *anonyLocalUdid = NULL;
911 Anonymize(reportInfo.localUdid, &anonyLocalUdid);
912 if (strcpy_s((char *)lnnAuditExtra->localUdid, SHA_256_HEX_HASH_LEN, AnonymizeWrapper(anonyLocalUdid)) != EOK) {
913 AUTH_LOGE(AUTH_FSM, "LOCAL UDID COPY ERROR");
914 }
915 AnonymizeFree(anonyLocalUdid);
916 }
917
BuildLnnAuditEvent(LnnAuditExtra * lnnAuditExtra,AuthSessionInfo * info,int32_t result,int32_t errCode,SoftbusAuditType auditType)918 static void BuildLnnAuditEvent(
919 LnnAuditExtra *lnnAuditExtra, AuthSessionInfo *info, int32_t result, int32_t errCode, SoftbusAuditType auditType)
920 {
921 if (lnnAuditExtra == NULL || info == NULL) {
922 AUTH_LOGE(AUTH_FSM, "lnnAuditExtra or info is null");
923 return;
924 }
925 (void)AuditReportSetPeerDevInfo(lnnAuditExtra, info);
926 (void)AuditReportSetLocalDevInfo(lnnAuditExtra);
927 lnnAuditExtra->result = result;
928 lnnAuditExtra->errCode = errCode;
929 lnnAuditExtra->auditType = auditType;
930 lnnAuditExtra->connId = info->connId;
931 lnnAuditExtra->authLinkType = info->connInfo.type;
932 lnnAuditExtra->authRequestId = info->requestId;
933 (void)LnnGetAllOnlineNodeNum(&(lnnAuditExtra->onlineNum));
934 }
935
ClientSetExchangeIdType(AuthFsm * authFsm)936 static int32_t ClientSetExchangeIdType(AuthFsm *authFsm)
937 {
938 AuthSessionInfo *info = &authFsm->info;
939 if (info->idType == EXCHANGE_FAIL) {
940 AUTH_LOGE(AUTH_FSM, "fsm switch to reauth due to not find networkId");
941 info->idType = EXCHANGE_UDID;
942 LnnFsmTransactState(&authFsm->fsm, g_states + STATE_SYNC_DEVICE_ID);
943 return SOFTBUS_AUTH_NOT_FOUND;
944 }
945 return SOFTBUS_OK;
946 }
947
UpdateUdidHashIfEmpty(AuthFsm * authFsm,AuthSessionInfo * info)948 static void UpdateUdidHashIfEmpty(AuthFsm *authFsm, AuthSessionInfo *info)
949 {
950 if (info->connInfo.type == AUTH_LINK_TYPE_BLE && strlen(info->udid) != 0 &&
951 authFsm->info.connInfo.info.bleInfo.deviceIdHash[0] == '\0') {
952 char *anonyUdid = NULL;
953 Anonymize(info->udid, &anonyUdid);
954 AUTH_LOGW(AUTH_FSM, "udidhash is empty, udid=%{public}s", AnonymizeWrapper(anonyUdid));
955 AnonymizeFree(anonyUdid);
956 if (SoftBusGenerateStrHash((unsigned char *)info->udid, strlen(info->udid),
957 (unsigned char *)authFsm->info.connInfo.info.bleInfo.deviceIdHash) != SOFTBUS_OK) {
958 AUTH_LOGE(AUTH_FSM, "generate udidhash fail");
959 }
960 }
961 }
962
HandleMsgRecvDeviceId(AuthFsm * authFsm,const MessagePara * para)963 static void HandleMsgRecvDeviceId(AuthFsm *authFsm, const MessagePara *para)
964 {
965 int32_t ret = SOFTBUS_OK;
966 AuthSessionInfo *info = &authFsm->info;
967 do {
968 if (ProcessDeviceIdMessage(info, para->data, para->len) != SOFTBUS_OK) {
969 ret = SOFTBUS_AUTH_SYNC_DEVID_FAIL;
970 LnnAuditExtra lnnAuditExtra = { 0 };
971 BuildLnnAuditEvent(&lnnAuditExtra, info, AUDIT_HANDLE_MSG_FAIL_END_AUTH, ret, AUDIT_EVENT_PACKETS_ERROR);
972 LNN_AUDIT(AUDIT_SCENE_HANDLE_MSG_DEV_ID, lnnAuditExtra);
973 break;
974 }
975 UpdateUdidHashIfEmpty(authFsm, info);
976 if (info->isServer) {
977 if (PostDeviceIdMessage(authFsm->authSeq, info) != SOFTBUS_OK) {
978 ret = SOFTBUS_AUTH_SYNC_DEVID_FAIL;
979 break;
980 }
981 } else {
982 if (info->normalizedType == NORMALIZED_NOT_SUPPORT || info->peerState == AUTH_STATE_COMPATIBLE) {
983 NotifyNormalizeRequestSuccess(authFsm->authSeq, false);
984 }
985 }
986 LnnFsmTransactState(&authFsm->fsm, g_states + STATE_DEVICE_AUTH);
987 } while (false);
988
989 if (ret != SOFTBUS_OK) {
990 AUTH_LOGE(AUTH_FSM, "handle devId msg fail, ret=%{public}d", ret);
991 CompleteAuthSession(authFsm, ret);
992 }
993 }
994
HandleMsgRecvDeviceIdNego(AuthFsm * authFsm,const MessagePara * para)995 static void HandleMsgRecvDeviceIdNego(AuthFsm *authFsm, const MessagePara *para)
996 {
997 int32_t ret = SOFTBUS_OK;
998 AuthSessionInfo *info = &authFsm->info;
999 do {
1000 if (ProcessDeviceIdMessage(info, para->data, para->len) != SOFTBUS_OK) {
1001 ret = SOFTBUS_AUTH_SYNC_DEVID_FAIL;
1002 LnnAuditExtra lnnAuditExtra = { 0 };
1003 BuildLnnAuditEvent(&lnnAuditExtra, info, AUDIT_HANDLE_MSG_FAIL_END_AUTH, ret, AUDIT_EVENT_PACKETS_ERROR);
1004 LNN_AUDIT(AUDIT_SCENE_HANDLE_MSG_DEV_ID, lnnAuditExtra);
1005 break;
1006 }
1007 UpdateUdidHashIfEmpty(authFsm, info);
1008 if (UpdateLocalAuthState(authFsm->authSeq, &authFsm->info) != SOFTBUS_OK) {
1009 AUTH_LOGE(AUTH_FSM, "update auth state fail, authSeq=%{public}" PRId64, authFsm->authSeq);
1010 return;
1011 }
1012 if (info->peerState == AUTH_STATE_COMPATIBLE) {
1013 NotifyNormalizeRequestSuccess(authFsm->authSeq, false);
1014 }
1015 if (info->localState == AUTH_STATE_START) {
1016 info->isServer = false;
1017 LnnFsmTransactState(&authFsm->fsm, g_states + STATE_SYNC_DEVICE_ID);
1018 } else if (info->localState == AUTH_STATE_ACK) {
1019 info->isServer = true;
1020 ret = PostDeviceIdMessage(authFsm->authSeq, info);
1021 LnnFsmTransactState(&authFsm->fsm, g_states + STATE_DEVICE_AUTH);
1022 } else if (info->localState == AUTH_STATE_WAIT) {
1023 info->isServer = true;
1024 ret = PostDeviceIdMessage(authFsm->authSeq, info);
1025 } else if (info->localState == AUTH_STATE_COMPATIBLE) {
1026 if (info->isServer) {
1027 ret = PostDeviceIdMessage(authFsm->authSeq, info);
1028 }
1029 LnnFsmTransactState(&authFsm->fsm, g_states + STATE_DEVICE_AUTH);
1030 } else if (info->localState == AUTH_STATE_UNKNOW) {
1031 ret = PostDeviceIdMessage(authFsm->authSeq, info);
1032 } else {
1033 AUTH_LOGE(AUTH_FSM, "local auth state error");
1034 ret = SOFTBUS_AUTH_SYNC_DEVID_FAIL;
1035 }
1036 } while (false);
1037
1038 if (ret != SOFTBUS_OK) {
1039 AUTH_LOGE(AUTH_FSM, "handle devId msg fail, ret=%{public}d", ret);
1040 CompleteAuthSession(authFsm, ret);
1041 }
1042 }
1043
SyncNegotiationStateProcess(FsmStateMachine * fsm,int32_t msgType,void * para)1044 static bool SyncNegotiationStateProcess(FsmStateMachine *fsm, int32_t msgType, void *para)
1045 {
1046 MessagePara *msgPara = (MessagePara *)para;
1047 AuthFsm *authFsm = TranslateToAuthFsm(fsm, msgType, msgPara);
1048 if (authFsm == NULL) {
1049 FreeMessagePara(msgPara);
1050 return false;
1051 }
1052 SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)authFsm->authSeq);
1053 AUTH_LOGI(AUTH_FSM, "auth fsm process. authSeq=%{public}" PRId64 ", message=%{public}s", authFsm->authSeq,
1054 FsmMsgTypeToStr(msgType));
1055 switch (msgType) {
1056 case FSM_MSG_RECV_DEVICE_ID:
1057 HandleMsgRecvDeviceIdNego(authFsm, msgPara);
1058 break;
1059 case FSM_MSG_DEVICE_POST_DEVICEID:
1060 HandleMsgPostDeviceId(authFsm, msgPara);
1061 break;
1062 default:
1063 HandleCommonMsg(authFsm, msgType, msgPara);
1064 break;
1065 }
1066 FreeMessagePara(msgPara);
1067 SoftbusHitraceStop();
1068 return true;
1069 }
1070
SyncDevIdStateProcess(FsmStateMachine * fsm,int32_t msgType,void * para)1071 static bool SyncDevIdStateProcess(FsmStateMachine *fsm, int32_t msgType, void *para)
1072 {
1073 MessagePara *msgPara = (MessagePara *)para;
1074 AuthFsm *authFsm = TranslateToAuthFsm(fsm, msgType, msgPara);
1075 if (authFsm == NULL) {
1076 FreeMessagePara(msgPara);
1077 return false;
1078 }
1079 SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)authFsm->authSeq);
1080 AUTH_LOGI(AUTH_FSM, "auth fsm process. authSeq=%{public}" PRId64 ", message=%{public}s", authFsm->authSeq,
1081 FsmMsgTypeToStr(msgType));
1082 switch (msgType) {
1083 case FSM_MSG_RECV_DEVICE_ID:
1084 HandleMsgRecvDeviceId(authFsm, msgPara);
1085 break;
1086 case FSM_MSG_DEVICE_POST_DEVICEID:
1087 HandleMsgPostDeviceId(authFsm, msgPara);
1088 break;
1089 default:
1090 HandleCommonMsg(authFsm, msgType, msgPara);
1091 break;
1092 }
1093 FreeMessagePara(msgPara);
1094 SoftbusHitraceStop();
1095 return true;
1096 }
1097
HandleMsgRecvAuthData(AuthFsm * authFsm,const MessagePara * para)1098 static void HandleMsgRecvAuthData(AuthFsm *authFsm, const MessagePara *para)
1099 {
1100 int32_t ret = HichainProcessData(authFsm->authSeq, para->data, para->len);
1101 if (ret != SOFTBUS_OK) {
1102 LnnAuditExtra lnnAuditExtra = { 0 };
1103 BuildLnnAuditEvent(
1104 &lnnAuditExtra, &authFsm->info, AUDIT_HANDLE_MSG_FAIL_END_AUTH, ret, AUDIT_EVENT_PACKETS_ERROR);
1105 LNN_AUDIT(AUDIT_SCENE_HANDLE_MSG_AUTH_DATA, lnnAuditExtra);
1106 AUTH_LOGE(AUTH_FSM, "process hichain data fail");
1107 if (!authFsm->info.isAuthFinished) {
1108 CompleteAuthSession(authFsm, ret);
1109 } else {
1110 AUTH_LOGD(AUTH_FSM, "auth has finished, ignore this processing failure");
1111 }
1112 }
1113 }
1114
TrySendAuthTestInfo(int64_t authSeq,const AuthSessionInfo * info)1115 static int32_t TrySendAuthTestInfo(int64_t authSeq, const AuthSessionInfo *info)
1116 {
1117 switch (info->connInfo.type) {
1118 case AUTH_LINK_TYPE_SESSION_KEY:
1119 if (!info->isServer) {
1120 return PostAuthTestInfoMessage(authSeq, info);
1121 }
1122 return SOFTBUS_OK;
1123 default:
1124 return SOFTBUS_OK;
1125 }
1126 return SOFTBUS_AUTH_CONN_TYPE_INVALID;
1127 }
1128
SoftbusCertChainParallel(const AuthSessionInfo * info)1129 static int32_t SoftbusCertChainParallel(const AuthSessionInfo *info)
1130 {
1131 if (info == NULL || !IsSupportUDIDAbatement() || !info->isNeedPackCert) {
1132 AUTH_LOGI(AUTH_FSM, "device not support udid abatement or no need");
1133 return SOFTBUS_OK;
1134 }
1135 SoftbusCertChain *softbusCertChain = (SoftbusCertChain *)SoftBusCalloc(sizeof(SoftbusCertChain));
1136 if (softbusCertChain == NULL) {
1137 AUTH_LOGI(AUTH_FSM, "malloc gencert parallel node failed. skip");
1138 return SOFTBUS_OK;
1139 }
1140 if (AddAuthGenCertParaNode(info->requestId) != SOFTBUS_OK) {
1141 AUTH_LOGI(AUTH_FSM, "add gencert parallel node failed. skip");
1142 }
1143 if (GenerateCertificate(softbusCertChain, info) != SOFTBUS_OK) {
1144 AUTH_LOGI(AUTH_FSM, "GenerateCertificate fail");
1145 if (UpdateAuthGenCertParaNode(info->requestId, false, false, softbusCertChain) != SOFTBUS_OK) {
1146 AUTH_LOGI(AUTH_FSM, "update gencert parallel node failed. skip");
1147 }
1148 return SOFTBUS_OK;
1149 }
1150 if (UpdateAuthGenCertParaNode(info->requestId, false, true, softbusCertChain) != SOFTBUS_OK) {
1151 AUTH_LOGI(AUTH_FSM, "update gencert parallel node failed. skip");
1152 }
1153 return SOFTBUS_OK;
1154 }
1155
TrySyncDeviceInfo(int64_t authSeq,const AuthSessionInfo * info)1156 static int32_t TrySyncDeviceInfo(int64_t authSeq, const AuthSessionInfo *info)
1157 {
1158 switch (info->connInfo.type) {
1159 case AUTH_LINK_TYPE_WIFI:
1160 case AUTH_LINK_TYPE_SESSION_KEY:
1161 /* WIFI: client firstly send device info, server just reponse it. */
1162 if (!info->isServer) {
1163 return PostDeviceInfoMessage(authSeq, info);
1164 } else {
1165 return SoftbusCertChainParallel(info);
1166 }
1167 return SOFTBUS_OK;
1168 case AUTH_LINK_TYPE_BR:
1169 case AUTH_LINK_TYPE_BLE:
1170 case AUTH_LINK_TYPE_P2P:
1171 case AUTH_LINK_TYPE_ENHANCED_P2P:
1172 case AUTH_LINK_TYPE_SESSION:
1173 return PostDeviceInfoMessage(authSeq, info);
1174 default:
1175 break;
1176 }
1177 return SOFTBUS_AUTH_CONN_TYPE_INVALID;
1178 }
1179
HandleMsgAuthError(AuthFsm * authFsm,const MessagePara * para)1180 static void HandleMsgAuthError(AuthFsm *authFsm, const MessagePara *para)
1181 {
1182 int32_t result = *((int32_t *)(para->data));
1183 AUTH_LOGE(AUTH_FSM, "auth fsm handle hichain error, authSeq=%{public}" PRId64 ", reason=%{public}d",
1184 authFsm->authSeq, result);
1185 if (result == HICHAIN_RETURN_NOT_TRUSTED) {
1186 AUTH_LOGE(AUTH_FSM, "device not has trust relation, begin to offline");
1187 AuthDeviceNotTrust(authFsm->info.udid);
1188 }
1189 CompleteAuthSession(authFsm, result);
1190 }
1191
HandleMsgRecvDevInfoEarly(AuthFsm * authFsm,const MessagePara * para)1192 static void HandleMsgRecvDevInfoEarly(AuthFsm *authFsm, const MessagePara *para)
1193 {
1194 AUTH_LOGI(AUTH_FSM, "auth fsm recv device info early, save it. authSeq=%{public}" PRId64 "", authFsm->authSeq);
1195 AuthSessionInfo *info = &authFsm->info;
1196 if (info->deviceInfoData != NULL) {
1197 SoftBusFree(info->deviceInfoData);
1198 info->deviceInfoData = NULL;
1199 }
1200 info->deviceInfoData = DupMemBuffer(para->data, para->len);
1201 if (info->deviceInfoData == NULL) {
1202 AUTH_LOGE(AUTH_FSM, "dup device info fail.");
1203 return;
1204 }
1205 info->deviceInfoDataLen = para->len;
1206 }
1207
TryFinishAuthSession(AuthFsm * authFsm)1208 static void TryFinishAuthSession(AuthFsm *authFsm)
1209 {
1210 AuthSessionInfo *info = &authFsm->info;
1211 AUTH_LOGI(AUTH_FSM,
1212 "Try finish auth fsm session, authSeq=%{public}" PRId64", devInfo=%{public}d, closeAck=%{public}d, "
1213 "authFinish=%{public}d",
1214 authFsm->authSeq, info->isNodeInfoReceived, info->isCloseAckReceived, info->isAuthFinished);
1215 if (info->isNodeInfoReceived && info->isCloseAckReceived && info->isAuthFinished) {
1216 CompleteAuthSession(authFsm, SOFTBUS_OK);
1217 }
1218 }
1219
HandleMsgAuthFinish(AuthFsm * authFsm,MessagePara * para)1220 static void HandleMsgAuthFinish(AuthFsm *authFsm, MessagePara *para)
1221 {
1222 (void)para;
1223 AuthSessionInfo *info = &authFsm->info;
1224 AUTH_LOGI(AUTH_FSM,
1225 "auth fsm hichain finished, authSeq=%{public}" PRId64", devInfo=%{public}d, closeAck=%{public}d",
1226 authFsm->authSeq, info->isNodeInfoReceived, info->isCloseAckReceived);
1227 info->isAuthFinished = true;
1228 TryFinishAuthSession(authFsm);
1229 }
1230
TryRecoveryKey(AuthFsm * authFsm)1231 static int32_t TryRecoveryKey(AuthFsm *authFsm)
1232 {
1233 int32_t ret = SOFTBUS_OK;
1234 if (authFsm->info.isSupportDmDeviceKey) {
1235 AUTH_LOGI(AUTH_FSM, "reuse device key");
1236 if (ReuseDeviceKey(authFsm) != SOFTBUS_OK) {
1237 AUTH_LOGE(AUTH_FSM, "reuse device key fail");
1238 authFsm->info.isSupportDmDeviceKey = false;
1239 ret = SOFTBUS_AUTH_SYNC_DEVID_FAIL;
1240 }
1241 return ret;
1242 }
1243 if (authFsm->info.normalizedType == NORMALIZED_SUPPORT) {
1244 AUTH_LOGI(AUTH_FSM, "normalized auth succ");
1245 if (RecoveryNormalizedDeviceKey(authFsm) != SOFTBUS_OK) {
1246 AUTH_LOGE(AUTH_FSM, "normalized auth recovery device key fail");
1247 ret = SOFTBUS_AUTH_SYNC_DEVID_FAIL;
1248 }
1249 return ret;
1250 }
1251 if (authFsm->info.isSupportFastAuth) {
1252 AUTH_LOGI(AUTH_FSM, "fast auth succ");
1253 if (RecoveryFastAuthKey(authFsm) != SOFTBUS_OK) {
1254 AUTH_LOGE(AUTH_FSM, "fast auth recovery device key fail");
1255 ret = SOFTBUS_AUTH_SYNC_DEVID_FAIL;
1256 }
1257 }
1258 return ret;
1259 }
1260
ProcessClientAuthState(AuthFsm * authFsm)1261 static int32_t ProcessClientAuthState(AuthFsm *authFsm)
1262 {
1263 /* just client need start authDevice */
1264 if (ClientSetExchangeIdType(authFsm) != SOFTBUS_OK) {
1265 return SOFTBUS_OK;
1266 }
1267 char *anonyUdid = NULL;
1268 Anonymize(authFsm->info.udid, &anonyUdid);
1269 AUTH_LOGI(AUTH_FSM, "start auth send udid=%{public}s peerUserId=%{public}d", AnonymizeWrapper(anonyUdid),
1270 authFsm->info.userId);
1271 AnonymizeFree(anonyUdid);
1272 return HichainStartAuth(authFsm->authSeq, authFsm->info.udid, authFsm->info.connInfo.peerUid, authFsm->info.userId);
1273 }
1274
DeviceAuthStateEnter(FsmStateMachine * fsm)1275 static void DeviceAuthStateEnter(FsmStateMachine *fsm)
1276 {
1277 if (fsm == NULL) {
1278 AUTH_LOGE(AUTH_FSM, "fsm is null");
1279 return;
1280 }
1281 int32_t ret = SOFTBUS_OK;
1282 AuthFsm *authFsm = TO_AUTH_FSM(fsm);
1283 if (authFsm == NULL) {
1284 AUTH_LOGE(AUTH_FSM, "authFsm is null");
1285 return;
1286 }
1287 AUTH_LOGI(AUTH_FSM, "auth state enter, authSeq=%{public}" PRId64, authFsm->authSeq);
1288 authFsm->curState = STATE_DEVICE_AUTH;
1289 AuthSessionInfo *info = &authFsm->info;
1290 if (info->normalizedType == NORMALIZED_SUPPORT || info->isSupportFastAuth || info->isSupportDmDeviceKey) {
1291 ret = TryRecoveryKey(authFsm);
1292 if (ret != SOFTBUS_OK) {
1293 goto ERR_EXIT;
1294 }
1295 return;
1296 }
1297 if (!info->isServer) {
1298 ret = ProcessClientAuthState(authFsm);
1299 }
1300 if (ret != SOFTBUS_OK) {
1301 goto ERR_EXIT;
1302 }
1303 return;
1304 ERR_EXIT:
1305 AUTH_LOGE(AUTH_FSM, "auth state enter, fail ret=%{public}d", ret);
1306 CompleteAuthSession(authFsm, ret);
1307 }
1308
DeviceAuthStateProcess(FsmStateMachine * fsm,int32_t msgType,void * para)1309 static bool DeviceAuthStateProcess(FsmStateMachine *fsm, int32_t msgType, void *para)
1310 {
1311 MessagePara *msgPara = (MessagePara *)para;
1312 AuthFsm *authFsm = TranslateToAuthFsm(fsm, msgType, msgPara);
1313 if (authFsm == NULL) {
1314 FreeMessagePara(msgPara);
1315 return false;
1316 }
1317 SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)authFsm->authSeq);
1318 AUTH_LOGI(AUTH_FSM, "auth fsm process. authSeq=%{public}" PRId64 ", message=%{public}s", authFsm->authSeq,
1319 FsmMsgTypeToStr(msgType));
1320 switch (msgType) {
1321 case FSM_MSG_RECV_DEVICE_ID:
1322 HandleMsgRecvDeviceId(authFsm, msgPara);
1323 break;
1324 case FSM_MSG_RECV_AUTH_DATA:
1325 HandleMsgRecvAuthData(authFsm, msgPara);
1326 break;
1327 case FSM_MSG_RECV_TEST_AUTH_DATA:
1328 HandleMsgRecvAuthTestData(authFsm, msgPara);
1329 break;
1330 case FSM_MSG_SAVE_SESSION_KEY:
1331 HandleMsgSaveSessionKey(authFsm, msgPara);
1332 break;
1333 case FSM_MSG_AUTH_ERROR:
1334 HandleMsgAuthError(authFsm, msgPara);
1335 break;
1336 case FSM_MSG_RECV_DEVICE_INFO:
1337 HandleMsgRecvDevInfoEarly(authFsm, msgPara);
1338 break;
1339 case FSM_MSG_AUTH_FINISH:
1340 HandleMsgAuthFinish(authFsm, msgPara);
1341 break;
1342 default:
1343 HandleCommonMsg(authFsm, msgType, msgPara);
1344 break;
1345 }
1346 FreeMessagePara(msgPara);
1347 SoftbusHitraceStop();
1348 return true;
1349 }
1350
HandleCloseAckMessage(AuthFsm * authFsm,const AuthSessionInfo * info)1351 static int32_t HandleCloseAckMessage(AuthFsm *authFsm, const AuthSessionInfo *info)
1352 {
1353 if ((info->connInfo.type == AUTH_LINK_TYPE_BLE) && (SoftBusGetBrState() == BR_DISABLE) &&
1354 (info->nodeInfo.feature & 1 << BIT_SUPPORT_THREE_STATE) == 0) {
1355 AUTH_LOGE(AUTH_FSM, "peer not support three state");
1356 CompleteAuthSession(authFsm, SOFTBUS_AUTH_NOT_SUPPORT_THREE_STATE);
1357 return SOFTBUS_NETWORK_NOT_SUPPORT;
1358 }
1359 if (PostCloseAckMessage(authFsm->authSeq, info) != SOFTBUS_OK) {
1360 AUTH_LOGE(AUTH_FSM, "post close ack fail");
1361 CompleteAuthSession(authFsm, SOFTBUS_AUTH_SEND_FAIL);
1362 return SOFTBUS_AUTH_SYNC_DEVINFO_ACK_FAIL;
1363 }
1364 return SOFTBUS_OK;
1365 }
1366
GetAuthFsmByRequestId(uint64_t requestId)1367 static AuthFsm *GetAuthFsmByRequestId(uint64_t requestId)
1368 {
1369 AuthFsm *item = NULL;
1370 LIST_FOR_EACH_ENTRY(item, &g_authFsmList, AuthFsm, node) {
1371 if (item->info.requestId == requestId) {
1372 return item;
1373 }
1374 }
1375 AUTH_LOGE(AUTH_FSM, "auth fsm not found. ");
1376 return NULL;
1377 }
1378
1379
OnPtkSyncCallBack(const char * uuid,int32_t result)1380 static void OnPtkSyncCallBack(const char *uuid, int32_t result)
1381 {
1382 if (uuid == NULL) {
1383 AUTH_LOGE(AUTH_FSM, "get invalid param");
1384 return;
1385 }
1386 if (!RequireAuthLock()) {
1387 AUTH_LOGE(AUTH_FSM, "require auth lock fail");
1388 return;
1389 }
1390 AuthPreLinkNode reuseKeyNode;
1391 (void)memset_s(&reuseKeyNode, sizeof(AuthPreLinkNode), 0, sizeof(AuthPreLinkNode));
1392 if (FindAuthPreLinkNodeByUuid(uuid, &reuseKeyNode) != SOFTBUS_OK) {
1393 ReleaseAuthLock();
1394 AUTH_LOGE(AUTH_FSM, "auth reuse devicekey not found");
1395 return;
1396 }
1397 AuthFsm *authFsm = GetAuthFsmByRequestId(reuseKeyNode.requestId);
1398 AuthSessionInfo *info = &authFsm->info;
1399 if (authFsm == NULL) {
1400 ReleaseAuthLock();
1401 AUTH_LOGE(AUTH_FSM, "auth fsm not found");
1402 return;
1403 }
1404 if (result != SOFTBUS_OK) {
1405 AUTH_LOGE(AUTH_FSM, "sync ptk fail");
1406 ReleaseAuthLock();
1407 CompleteAuthSession(authFsm, SOFTBUS_AUTH_SYNC_PTK_ERR);
1408 return;
1409 }
1410 ReleaseAuthLock();
1411 DelAuthGenCertParaNodeById(reuseKeyNode.requestId);
1412 AuthManagerSetAuthPassed(authFsm->authSeq, info);
1413 TryFinishAuthSession(authFsm);
1414 }
1415
TrySyncPtkClient(AuthSessionInfo * info)1416 static void TrySyncPtkClient(AuthSessionInfo *info)
1417 {
1418 struct WifiDirectManager *wdMgr = GetWifiDirectManager();
1419 if (wdMgr == NULL) {
1420 AUTH_LOGE(AUTH_FSM, "get wifiDirect mgr fail");
1421 return;
1422 }
1423 char localPtk[PTK_DEFAULT_LEN] = { 0 };
1424 char ptk[PTK_STR_LEN] = { 0 };
1425 if (LnnGetLocalPtkByUuid(info->uuid, localPtk, PTK_DEFAULT_LEN) != SOFTBUS_OK) {
1426 AUTH_LOGE(AUTH_FSM, "get ptk by uuid fail");
1427 (void)memset_s(localPtk, PTK_DEFAULT_LEN, 0, PTK_DEFAULT_LEN);
1428 return;
1429 }
1430 if (ConvertBytesToHexString(ptk, PTK_STR_LEN, (unsigned char *)localPtk,
1431 PTK_32_BIT_LEN) != SOFTBUS_OK) {
1432 AUTH_LOGE(AUTH_FSM, "convert ptk fail");
1433 (void)memset_s(localPtk, PTK_DEFAULT_LEN, 0, PTK_DEFAULT_LEN);
1434 (void)memset_s(ptk, PTK_STR_LEN, 0, PTK_STR_LEN);
1435 }
1436 SyncPtkListener listener = OnPtkSyncCallBack;
1437 wdMgr->addSyncPtkListener(listener);
1438 if (wdMgr->savePTK(info->uuid, ptk) != SOFTBUS_OK) {
1439 AUTH_LOGE(AUTH_FSM, "client save ptk fail");
1440 (void)memset_s(localPtk, PTK_DEFAULT_LEN, 0, PTK_DEFAULT_LEN);
1441 (void)memset_s(ptk, PTK_STR_LEN, 0, PTK_STR_LEN);
1442 return;
1443 }
1444 AUTH_LOGI(AUTH_FSM, "try sync ptk");
1445 (void)memset_s(localPtk, PTK_DEFAULT_LEN, 0, PTK_DEFAULT_LEN);
1446 (void)memset_s(ptk, PTK_STR_LEN, 0, PTK_STR_LEN);
1447 if (wdMgr->syncPTK(info->uuid) != SOFTBUS_OK) {
1448 AUTH_LOGE(AUTH_FSM, "client sync ptk fail");
1449 }
1450 }
1451
TrySavePtkServer(AuthSessionInfo * info)1452 static void TrySavePtkServer(AuthSessionInfo *info)
1453 {
1454 char ptk[PTK_STR_LEN] = { 0 };
1455 struct WifiDirectManager *wdMgr = GetWifiDirectManager();
1456 if (wdMgr == NULL) {
1457 AUTH_LOGE(AUTH_FSM, "get wifiDirect mgr fail");
1458 return;
1459 }
1460 if (ConvertBytesToHexString(ptk, PTK_STR_LEN, (unsigned char *)info->nodeInfo.remotePtk,
1461 PTK_32_BIT_LEN) != SOFTBUS_OK) {
1462 AUTH_LOGE(AUTH_FSM, "client save ptk fail");
1463 (void)memset_s(ptk, PTK_STR_LEN, 0, PTK_STR_LEN);
1464 }
1465 if (wdMgr->savePTK(info->uuid, ptk) != SOFTBUS_OK) {
1466 AUTH_LOGE(AUTH_FSM, "server save ptk fail");
1467 }
1468 (void)memset_s(ptk, PTK_STR_LEN, 0, PTK_STR_LEN);
1469 }
1470
TryAddSyncPtkListenerServer(void)1471 static void TryAddSyncPtkListenerServer(void)
1472 {
1473 struct WifiDirectManager *wdMgr = GetWifiDirectManager();
1474 if (wdMgr == NULL) {
1475 AUTH_LOGE(AUTH_FSM, "get wifiDirect mgr fail");
1476 return;
1477 }
1478 AUTH_LOGI(AUTH_FSM, "wait to ptk sync");
1479 SyncPtkListener listener = OnPtkSyncCallBack;
1480 wdMgr->addSyncPtkListener(listener);
1481 }
1482
TryCompleteAuthSessionForError(AuthFsm * authFsm,AuthSessionInfo * info)1483 static void TryCompleteAuthSessionForError(AuthFsm *authFsm, AuthSessionInfo *info)
1484 {
1485 LnnAuditExtra lnnAuditExtra = { 0 };
1486 BuildLnnAuditEvent(&lnnAuditExtra, info, AUDIT_HANDLE_MSG_FAIL_END_AUTH, SOFTBUS_AUTH_UNPACK_DEVINFO_FAIL,
1487 AUDIT_EVENT_PACKETS_ERROR);
1488 LNN_AUDIT(AUDIT_SCENE_HANDLE_MSG_DEV_INFO, lnnAuditExtra);
1489 AUTH_LOGE(AUTH_FSM, "process device info msg fail");
1490 CompleteAuthSession(authFsm, SOFTBUS_AUTH_UNPACK_DEVINFO_FAIL);
1491 }
1492
ClientTryCompleteAuthSession(AuthFsm * authFsm,AuthSessionInfo * info)1493 static void ClientTryCompleteAuthSession(AuthFsm *authFsm, AuthSessionInfo *info)
1494 {
1495 LnnFsmRemoveMessage(&authFsm->fsm, FSM_MSG_AUTH_TIMEOUT);
1496 if (IsAuthPreLinkNodeExist(info->requestId)) {
1497 TrySyncPtkClient(info);
1498 return;
1499 }
1500 AuthManagerSetAuthPassed(authFsm->authSeq, info);
1501 TryFinishAuthSession(authFsm);
1502 }
1503
HandleMsgRecvDeviceInfo(AuthFsm * authFsm,const MessagePara * para)1504 static void HandleMsgRecvDeviceInfo(AuthFsm *authFsm, const MessagePara *para)
1505 {
1506 AuthSessionInfo *info = &authFsm->info;
1507 if (ProcessDeviceInfoMessage(authFsm->authSeq, info, para->data, para->len) != SOFTBUS_OK) {
1508 TryCompleteAuthSessionForError(authFsm, info);
1509 return;
1510 }
1511 info->isNodeInfoReceived = true;
1512 if (strcpy_s(info->nodeInfo.uuid, UUID_BUF_LEN, info->uuid) != EOK) {
1513 AUTH_LOGE(AUTH_FSM, "copy uuid fail.");
1514 return;
1515 }
1516 if (IsAuthPreLinkNodeExist(info->requestId)) {
1517 UpdateAuthPreLinkUuidById(info->requestId, info->uuid);
1518 }
1519 if (info->connInfo.type == AUTH_LINK_TYPE_WIFI || info->connInfo.type == AUTH_LINK_TYPE_SESSION_KEY) {
1520 info->isCloseAckReceived = true; /* WiFi auth no need close ack, set true directly */
1521 if (!info->isServer) {
1522 ClientTryCompleteAuthSession(authFsm, info);
1523 return;
1524 }
1525 if (IsAuthPreLinkNodeExist(info->requestId)) {
1526 TrySavePtkServer(info);
1527 }
1528 /* WIFI: server should response device info */
1529 if (PostDeviceInfoMessage(authFsm->authSeq, info) != SOFTBUS_OK) {
1530 AUTH_LOGE(AUTH_FSM, "server: response device info fail");
1531 CompleteAuthSession(authFsm, SOFTBUS_AUTH_SYNC_DEVINFO_FAIL);
1532 return;
1533 }
1534 LnnFsmRemoveMessage(&authFsm->fsm, FSM_MSG_AUTH_TIMEOUT);
1535 if (IsAuthPreLinkNodeExist(info->requestId)) {
1536 TryAddSyncPtkListenerServer();
1537 return;
1538 }
1539 AuthManagerSetAuthPassed(authFsm->authSeq, info);
1540 TryFinishAuthSession(authFsm);
1541 return;
1542 }
1543 if (HandleCloseAckMessage(authFsm, info) != SOFTBUS_OK) {
1544 AUTH_LOGE(AUTH_FSM, "handle close ack fail");
1545 return;
1546 }
1547 if (info->isCloseAckReceived) {
1548 LnnFsmRemoveMessage(&authFsm->fsm, FSM_MSG_AUTH_TIMEOUT);
1549 AuthManagerSetAuthPassed(authFsm->authSeq, info);
1550 TryFinishAuthSession(authFsm);
1551 }
1552 }
1553
HandleMsgRecvCloseAck(AuthFsm * authFsm,MessagePara * para)1554 static void HandleMsgRecvCloseAck(AuthFsm *authFsm, MessagePara *para)
1555 {
1556 (void)para;
1557 AuthSessionInfo *info = &authFsm->info;
1558 AUTH_LOGI(AUTH_FSM, "auth fsm recv close ack, fsm=%{public}" PRId64 ", isNodeInfoReceived=%{public}d",
1559 authFsm->authSeq, info->isNodeInfoReceived);
1560 info->isCloseAckReceived = true;
1561 if (info->isNodeInfoReceived) {
1562 LnnFsmRemoveMessage(&authFsm->fsm, FSM_MSG_AUTH_TIMEOUT);
1563 AuthManagerSetAuthPassed(authFsm->authSeq, info);
1564 } else {
1565 AUTH_LOGI(AUTH_FSM, "close ack received before device info");
1566 }
1567 TryFinishAuthSession(authFsm);
1568 }
1569
SyncDevInfoStateProcess(FsmStateMachine * fsm,int32_t msgType,void * para)1570 static bool SyncDevInfoStateProcess(FsmStateMachine *fsm, int32_t msgType, void *para)
1571 {
1572 MessagePara *msgPara = (MessagePara *)para;
1573 AuthFsm *authFsm = TranslateToAuthFsm(fsm, msgType, msgPara);
1574 if (authFsm == NULL) {
1575 FreeMessagePara(msgPara);
1576 return false;
1577 }
1578 SoftbusHitraceStart(SOFTBUS_HITRACE_ID_VALID, (uint64_t)authFsm->authSeq);
1579 AUTH_LOGI(AUTH_FSM, "auth fsm process. authSeq=%{public}" PRId64", message=%{public}s",
1580 authFsm->authSeq, FsmMsgTypeToStr(msgType));
1581 switch (msgType) {
1582 case FSM_MSG_RECV_DEVICE_INFO:
1583 HandleMsgRecvDeviceInfo(authFsm, msgPara);
1584 break;
1585 case FSM_MSG_RECV_CLOSE_ACK:
1586 HandleMsgRecvCloseAck(authFsm, msgPara);
1587 break;
1588 case FSM_MSG_RECV_AUTH_DATA:
1589 HandleMsgRecvAuthData(authFsm, msgPara);
1590 break;
1591 case FSM_MSG_AUTH_FINISH:
1592 HandleMsgAuthFinish(authFsm, msgPara);
1593 break;
1594 default:
1595 HandleCommonMsg(authFsm, msgType, msgPara);
1596 break;
1597 }
1598 FreeMessagePara(msgPara);
1599 SoftbusHitraceStop();
1600 return true;
1601 }
1602
GetAuthFsmByAuthSeq(int64_t authSeq)1603 AuthFsm *GetAuthFsmByAuthSeq(int64_t authSeq)
1604 {
1605 AuthFsm *item = NULL;
1606 LIST_FOR_EACH_ENTRY(item, &g_authFsmList, AuthFsm, node) {
1607 if (item->authSeq != authSeq) {
1608 continue;
1609 }
1610 if (item->isDead) {
1611 AUTH_LOGE(AUTH_FSM, "auth fsm has dead. authSeq=%{public}" PRId64 "", item->authSeq);
1612 break;
1613 }
1614 return item;
1615 }
1616 AUTH_LOGE(AUTH_FSM, "auth fsm not found. authSeq=%{public}" PRId64 "", authSeq);
1617 return NULL;
1618 }
1619
GetAuthFsmByConnId(uint64_t connId,bool isServer,bool isConnectSide)1620 AuthFsm *GetAuthFsmByConnId(uint64_t connId, bool isServer, bool isConnectSide)
1621 {
1622 AuthFsm *item = NULL;
1623 LIST_FOR_EACH_ENTRY(item, &g_authFsmList, AuthFsm, node) {
1624 if (isConnectSide && (item->info.connId != connId || item->info.isConnectServer != isServer)) {
1625 continue;
1626 }
1627 if (!isConnectSide && (item->info.connId != connId || item->info.isServer != isServer)) {
1628 continue;
1629 }
1630 if (item->isDead) {
1631 AUTH_LOGE(AUTH_FSM, "auth fsm has dead. authSeq=%{public}" PRId64 "", item->authSeq);
1632 break;
1633 }
1634 return item;
1635 }
1636 AUTH_LOGE(AUTH_FSM, "auth fsm not found. " CONN_INFO, CONN_DATA(connId));
1637 return NULL;
1638 }
1639
GetSessionInfoFromAuthFsm(int64_t authSeq,AuthSessionInfo * info)1640 static int32_t GetSessionInfoFromAuthFsm(int64_t authSeq, AuthSessionInfo *info)
1641 {
1642 if (!RequireAuthLock()) {
1643 return SOFTBUS_LOCK_ERR;
1644 }
1645 AuthFsm *authFsm = GetAuthFsmByAuthSeq(authSeq);
1646 if (authFsm == NULL) {
1647 AUTH_LOGE(AUTH_FSM, "auth fsm not found. authSeq=%{public}" PRId64 "", authSeq);
1648 ReleaseAuthLock();
1649 return SOFTBUS_AUTH_NOT_FOUND;
1650 }
1651 *info = authFsm->info;
1652 info->deviceInfoData = NULL;
1653 info->deviceInfoDataLen = 0;
1654 ReleaseAuthLock();
1655 return SOFTBUS_OK;
1656 }
1657
PostMessageToAuthFsm(int32_t msgType,int64_t authSeq,const uint8_t * data,uint32_t len)1658 static int32_t PostMessageToAuthFsm(int32_t msgType, int64_t authSeq, const uint8_t *data, uint32_t len)
1659 {
1660 MessagePara *para = NewMessagePara(data, len);
1661 if (para == NULL) {
1662 return SOFTBUS_MALLOC_ERR;
1663 }
1664 if (!RequireAuthLock()) {
1665 SoftBusFree(para);
1666 return SOFTBUS_LOCK_ERR;
1667 }
1668 AuthFsm *authFsm = GetAuthFsmByAuthSeq(authSeq);
1669 if (authFsm == NULL) {
1670 ReleaseAuthLock();
1671 SoftBusFree(para);
1672 return SOFTBUS_AUTH_GET_FSM_FAIL;
1673 }
1674 if (LnnFsmPostMessage(&authFsm->fsm, msgType, para) != SOFTBUS_OK) {
1675 AUTH_LOGE(AUTH_FSM, "post message to auth fsm fail");
1676 ReleaseAuthLock();
1677 SoftBusFree(para);
1678 return SOFTBUS_AUTH_SEND_FAIL;
1679 }
1680 ReleaseAuthLock();
1681 return SOFTBUS_OK;
1682 }
1683
PostMessageToAuthFsmByConnId(int32_t msgType,uint64_t connId,bool isServer,const uint8_t * data,uint32_t len)1684 static int32_t PostMessageToAuthFsmByConnId(
1685 int32_t msgType, uint64_t connId, bool isServer, const uint8_t *data, uint32_t len)
1686 {
1687 MessagePara *para = NewMessagePara(data, len);
1688 if (para == NULL) {
1689 return SOFTBUS_MALLOC_ERR;
1690 }
1691 if (!RequireAuthLock()) {
1692 SoftBusFree(para);
1693 return SOFTBUS_LOCK_ERR;
1694 }
1695 AuthFsm *authFsm = GetAuthFsmByConnId(connId, isServer, false);
1696 if (authFsm == NULL) {
1697 ReleaseAuthLock();
1698 SoftBusFree(para);
1699 return SOFTBUS_AUTH_GET_FSM_FAIL;
1700 }
1701 if (LnnFsmPostMessage(&authFsm->fsm, msgType, para) != SOFTBUS_OK) {
1702 AUTH_LOGE(AUTH_FSM, "post message to auth fsm by connId fail");
1703 ReleaseAuthLock();
1704 SoftBusFree(para);
1705 return SOFTBUS_AUTH_SEND_FAIL;
1706 }
1707 ReleaseAuthLock();
1708 return SOFTBUS_OK;
1709 }
1710
SetAuthStartTime(AuthFsm * authFsm)1711 static void SetAuthStartTime(AuthFsm *authFsm)
1712 {
1713 authFsm->statisticData.startAuthTime = (uint64_t)LnnUpTimeMs();
1714 }
1715
IsPeerSupportNegoAuth(AuthSessionInfo * info)1716 static bool IsPeerSupportNegoAuth(AuthSessionInfo *info)
1717 {
1718 char udidHash[SHORT_UDID_HASH_HEX_LEN + 1] = { 0 };
1719 if (!GetUdidShortHash(info, udidHash, SHORT_UDID_HASH_HEX_LEN + 1)) {
1720 return true;
1721 }
1722 NodeInfo nodeInfo;
1723 (void)memset_s(&nodeInfo, sizeof(nodeInfo), 0, sizeof(nodeInfo));
1724 if (LnnRetrieveDeviceInfo((const char *)udidHash, &nodeInfo) != SOFTBUS_OK) {
1725 AUTH_LOGE(AUTH_FSM, "retrive deviceInfo fail");
1726 return true;
1727 }
1728 if (IsSupportFeatureByCapaBit(nodeInfo.authCapacity, BIT_SUPPORT_NEGOTIATION_AUTH)) {
1729 return true;
1730 }
1731 return false;
1732 }
1733
GetFirstFsmState(AuthSessionInfo * info,int64_t authSeq,AuthFsmStateIndex * state)1734 static int32_t GetFirstFsmState(AuthSessionInfo *info, int64_t authSeq, AuthFsmStateIndex *state)
1735 {
1736 CHECK_NULL_PTR_RETURN_VALUE(info, SOFTBUS_INVALID_PARAM);
1737 CHECK_NULL_PTR_RETURN_VALUE(state, SOFTBUS_INVALID_PARAM);
1738 if (info->isConnectServer) {
1739 *state = STATE_SYNC_NEGOTIATION;
1740 } else {
1741 if (!IsPeerSupportNegoAuth(info)) {
1742 info->localState = AUTH_STATE_COMPATIBLE;
1743 AUTH_LOGI(AUTH_FSM, "peer not support nego, localState change, authSeq=%{public}" PRId64, authSeq);
1744 }
1745 if (info->localState == AUTH_STATE_START || info->localState == AUTH_STATE_COMPATIBLE) {
1746 *state = STATE_SYNC_DEVICE_ID;
1747 } else {
1748 *state = STATE_SYNC_NEGOTIATION;
1749 }
1750 }
1751 return SOFTBUS_OK;
1752 }
1753
AuthSessionStartAuth(const AuthParam * authParam,const AuthConnInfo * connInfo)1754 int32_t AuthSessionStartAuth(const AuthParam *authParam, const AuthConnInfo *connInfo)
1755 {
1756 AUTH_CHECK_AND_RETURN_RET_LOGE(connInfo != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "connInfo is NULL");
1757 AUTH_CHECK_AND_RETURN_RET_LOGE(authParam != NULL, SOFTBUS_INVALID_PARAM, AUTH_FSM, "authParam is NULL");
1758 if (!RequireAuthLock()) {
1759 return SOFTBUS_LOCK_ERR;
1760 }
1761 AuthFsm *authFsm =
1762 CreateAuthFsm(authParam->authSeq, authParam->requestId, authParam->connId, connInfo, authParam->isServer);
1763 if (authFsm == NULL) {
1764 ReleaseAuthLock();
1765 return SOFTBUS_MEM_ERR;
1766 }
1767 DeleteWifiConnItemByConnId(GetConnId(authParam->connId));
1768 authFsm->info.isNeedFastAuth = authParam->isFastAuth;
1769 (void)UpdateLocalAuthState(authFsm->authSeq, &authFsm->info);
1770 AuthFsmStateIndex nextState = STATE_SYNC_DEVICE_ID;
1771 if (GetFirstFsmState(&authFsm->info, authFsm->authSeq, &nextState) != SOFTBUS_OK ||
1772 LnnFsmStart(&authFsm->fsm, g_states + nextState) != SOFTBUS_OK) {
1773 AUTH_LOGE(AUTH_FSM, "start auth fsm fail. authSeq=%{public}" PRId64 "", authFsm->authSeq);
1774 DestroyAuthFsm(authFsm);
1775 ReleaseAuthLock();
1776 return SOFTBUS_AUTH_START_FSM_FAIL;
1777 }
1778 SetAuthStartTime(authFsm);
1779 LnnFsmPostMessageDelay(&authFsm->fsm, FSM_MSG_AUTH_TIMEOUT, NULL, AUTH_TIMEOUT_MS);
1780 ReleaseAuthLock();
1781 return SOFTBUS_OK;
1782 }
1783
AuthSessionProcessDevIdData(int64_t authSeq,const uint8_t * data,uint32_t len)1784 int32_t AuthSessionProcessDevIdData(int64_t authSeq, const uint8_t *data, uint32_t len)
1785 {
1786 if (data == NULL) {
1787 AUTH_LOGE(AUTH_FSM, "data is null");
1788 return SOFTBUS_INVALID_PARAM;
1789 }
1790 return PostMessageToAuthFsm(FSM_MSG_RECV_DEVICE_ID, authSeq, data, len);
1791 }
1792
AuthSessionPostAuthData(int64_t authSeq,const uint8_t * data,uint32_t len)1793 int32_t AuthSessionPostAuthData(int64_t authSeq, const uint8_t *data, uint32_t len)
1794 {
1795 AuthSessionInfo info;
1796 if (GetSessionInfoFromAuthFsm(authSeq, &info) != SOFTBUS_OK) {
1797 return SOFTBUS_AUTH_GET_SESSION_INFO_FAIL;
1798 }
1799 if (PostHichainAuthMessage(authSeq, &info, data, len) != SOFTBUS_OK) {
1800 return SOFTBUS_AUTH_SYNC_DEVID_FAIL;
1801 }
1802 return SOFTBUS_OK;
1803 }
1804
AuthSessionProcessAuthData(int64_t authSeq,const uint8_t * data,uint32_t len)1805 int32_t AuthSessionProcessAuthData(int64_t authSeq, const uint8_t *data, uint32_t len)
1806 {
1807 if (data == NULL) {
1808 AUTH_LOGE(AUTH_FSM, "data is null");
1809 return SOFTBUS_INVALID_PARAM;
1810 }
1811 return PostMessageToAuthFsm(FSM_MSG_RECV_AUTH_DATA, authSeq, data, len);
1812 }
1813
AuthSessionGetUdid(int64_t authSeq,char * udid,uint32_t size)1814 int32_t AuthSessionGetUdid(int64_t authSeq, char *udid, uint32_t size)
1815 {
1816 if (udid == NULL) {
1817 AUTH_LOGE(AUTH_FSM, "udid is null");
1818 return SOFTBUS_INVALID_PARAM;
1819 }
1820 AuthSessionInfo info = { 0 };
1821 if (GetSessionInfoFromAuthFsm(authSeq, &info) != SOFTBUS_OK) {
1822 return SOFTBUS_AUTH_GET_SESSION_INFO_FAIL;
1823 }
1824 if (memcpy_s(udid, size, info.udid, sizeof(info.udid)) != EOK) {
1825 AUTH_LOGE(AUTH_FSM, "copy udid fail");
1826 return SOFTBUS_MEM_ERR;
1827 }
1828 return SOFTBUS_OK;
1829 }
1830
AuthSessionSaveSessionKey(int64_t authSeq,const uint8_t * key,uint32_t len)1831 int32_t AuthSessionSaveSessionKey(int64_t authSeq, const uint8_t *key, uint32_t len)
1832 {
1833 if (key == NULL) {
1834 AUTH_LOGE(AUTH_FSM, "key is null");
1835 return SOFTBUS_INVALID_PARAM;
1836 }
1837 return PostMessageToAuthFsm(FSM_MSG_SAVE_SESSION_KEY, authSeq, key, len);
1838 }
1839
AuthSessionHandleAuthFinish(int64_t authSeq)1840 int32_t AuthSessionHandleAuthFinish(int64_t authSeq)
1841 {
1842 return PostMessageToAuthFsm(FSM_MSG_AUTH_FINISH, authSeq, NULL, 0);
1843 }
1844
AuthSessionHandleAuthError(int64_t authSeq,int32_t reason)1845 int32_t AuthSessionHandleAuthError(int64_t authSeq, int32_t reason)
1846 {
1847 return PostMessageToAuthFsm(FSM_MSG_AUTH_ERROR, authSeq, (uint8_t *)&reason, sizeof(reason));
1848 }
1849
AuthSessionProcessAuthTestData(int64_t authSeq,const uint8_t * data,uint32_t len)1850 int32_t AuthSessionProcessAuthTestData(int64_t authSeq, const uint8_t *data, uint32_t len)
1851 {
1852 if (data == NULL) {
1853 AUTH_LOGE(AUTH_FSM, "data is null");
1854 return SOFTBUS_INVALID_PARAM;
1855 }
1856 return PostMessageToAuthFsm(FSM_MSG_RECV_TEST_AUTH_DATA, authSeq, data, len);
1857 }
1858
AuthSessionProcessDevInfoData(int64_t authSeq,const uint8_t * data,uint32_t len)1859 int32_t AuthSessionProcessDevInfoData(int64_t authSeq, const uint8_t *data, uint32_t len)
1860 {
1861 if (data == NULL) {
1862 AUTH_LOGE(AUTH_FSM, "data is null");
1863 return SOFTBUS_INVALID_PARAM;
1864 }
1865 return PostMessageToAuthFsm(FSM_MSG_RECV_DEVICE_INFO, authSeq, data, len);
1866 }
1867
AuthSessionProcessCloseAck(int64_t authSeq,const uint8_t * data,uint32_t len)1868 int32_t AuthSessionProcessCloseAck(int64_t authSeq, const uint8_t *data, uint32_t len)
1869 {
1870 if (data == NULL) {
1871 AUTH_LOGE(AUTH_FSM, "data is null");
1872 return SOFTBUS_INVALID_PARAM;
1873 }
1874 return PostMessageToAuthFsm(FSM_MSG_RECV_CLOSE_ACK, authSeq, data, len);
1875 }
1876
AuthSessionProcessDevInfoDataByConnId(uint64_t connId,bool isServer,const uint8_t * data,uint32_t len)1877 int32_t AuthSessionProcessDevInfoDataByConnId(uint64_t connId, bool isServer, const uint8_t *data, uint32_t len)
1878 {
1879 if (data == NULL) {
1880 AUTH_LOGE(AUTH_FSM, "data is null");
1881 return SOFTBUS_INVALID_PARAM;
1882 }
1883 return PostMessageToAuthFsmByConnId(FSM_MSG_RECV_DEVICE_INFO, connId, isServer, data, len);
1884 }
1885
AuthSessionProcessCloseAckByConnId(uint64_t connId,bool isServer,const uint8_t * data,uint32_t len)1886 int32_t AuthSessionProcessCloseAckByConnId(uint64_t connId, bool isServer, const uint8_t *data, uint32_t len)
1887 {
1888 if (data == NULL) {
1889 AUTH_LOGE(AUTH_FSM, "data is null");
1890 return SOFTBUS_INVALID_PARAM;
1891 }
1892 return PostMessageToAuthFsmByConnId(FSM_MSG_RECV_CLOSE_ACK, connId, isServer, data, len);
1893 }
1894
AuthSessionProcessCancelAuthByConnId(uint64_t connId,bool isConnectServer,const uint8_t * data,uint32_t len)1895 int32_t AuthSessionProcessCancelAuthByConnId(uint64_t connId, bool isConnectServer, const uint8_t *data, uint32_t len)
1896 {
1897 if (!RequireAuthLock()) {
1898 return SOFTBUS_LOCK_ERR;
1899 }
1900 AuthFsm *authFsm = GetAuthFsmByConnId(connId, isConnectServer, true);
1901 if (authFsm == NULL) {
1902 ReleaseAuthLock();
1903 return SOFTBUS_AUTH_GET_FSM_FAIL;
1904 }
1905 if (LnnFsmPostMessage(&authFsm->fsm, FSM_MSG_DEVICE_DISCONNECTED, NULL) != SOFTBUS_OK) {
1906 AUTH_LOGE(AUTH_FSM, "post message to auth fsm by connId fail");
1907 ReleaseAuthLock();
1908 return SOFTBUS_AUTH_SEND_FAIL;
1909 }
1910 ReleaseAuthLock();
1911 return SOFTBUS_OK;
1912 }
1913
AuthSessionHandleDeviceNotTrusted(const char * udid)1914 int32_t AuthSessionHandleDeviceNotTrusted(const char *udid)
1915 {
1916 if (udid == NULL || udid[0] == '\0') {
1917 AUTH_LOGE(AUTH_FSM, "invalid udid");
1918 return SOFTBUS_INVALID_PARAM;
1919 }
1920 if (!RequireAuthLock()) {
1921 return SOFTBUS_LOCK_ERR;
1922 }
1923 AuthFsm *item = NULL;
1924 LIST_FOR_EACH_ENTRY(item, &g_authFsmList, AuthFsm, node) {
1925 if (strcmp(item->info.udid, udid) != 0) {
1926 continue;
1927 }
1928 if (item->isDead) {
1929 AUTH_LOGE(AUTH_FSM, "auth fsm has dead. authSeq=%{public}" PRId64 "", item->authSeq);
1930 continue;
1931 }
1932 LnnFsmPostMessage(&item->fsm, FSM_MSG_DEVICE_NOT_TRUSTED, NULL);
1933 }
1934 ReleaseAuthLock();
1935 return SOFTBUS_OK;
1936 }
1937
AuthSessionHandleDeviceDisconnected(uint64_t connId,bool isNeedDisconnect)1938 int32_t AuthSessionHandleDeviceDisconnected(uint64_t connId, bool isNeedDisconnect)
1939 {
1940 if (!RequireAuthLock()) {
1941 AUTH_LOGE(AUTH_FSM, "get auth lock fail");
1942 return SOFTBUS_LOCK_ERR;
1943 }
1944 AuthFsm *item = NULL;
1945 bool isDisconnected = false;
1946 LIST_FOR_EACH_ENTRY(item, &g_authFsmList, AuthFsm, node) {
1947 if (item->info.connId != connId) {
1948 continue;
1949 }
1950 if (item->isDead) {
1951 AUTH_LOGE(AUTH_FSM, "auth fsm has dead. authSeq=%{public}" PRId64 "", item->authSeq);
1952 continue;
1953 }
1954 if ((GetConnType(item->info.connId) == AUTH_LINK_TYPE_WIFI ||
1955 GetConnType(item->info.connId) == AUTH_LINK_TYPE_P2P)) {
1956 if (isNeedDisconnect) {
1957 DisconnectAuthDevice(&item->info.connId);
1958 isDisconnected = true;
1959 } else {
1960 UpdateFd(&item->info.connId, AUTH_INVALID_FD);
1961 }
1962 }
1963 LnnFsmPostMessage(&item->fsm, FSM_MSG_DEVICE_DISCONNECTED, NULL);
1964 }
1965 ReleaseAuthLock();
1966 if (isNeedDisconnect && !isDisconnected && GetConnType(connId) == AUTH_LINK_TYPE_WIFI &&
1967 IsExistWifiConnItemByConnId(GetConnId(connId))) {
1968 DeleteWifiConnItemByConnId(GetConnId(connId));
1969 DisconnectAuthDevice(&connId);
1970 }
1971 return SOFTBUS_OK;
1972 }
1973
AuthNotifyRequestVerify(int64_t authSeq)1974 int32_t AuthNotifyRequestVerify(int64_t authSeq)
1975 {
1976 return PostMessageToAuthFsm(FSM_MSG_DEVICE_POST_DEVICEID, authSeq, NULL, 0);
1977 }
1978
AuthSessionFsmExit(void)1979 void AuthSessionFsmExit(void)
1980 {
1981 HichainDestroy();
1982 if (!RequireAuthLock()) {
1983 return;
1984 }
1985 AuthFsm *item = NULL;
1986 AuthFsm *next = NULL;
1987 LIST_FOR_EACH_ENTRY_SAFE(item, next, &g_authFsmList, AuthFsm, node) {
1988 DestroyAuthFsm(item);
1989 }
1990 ListInit(&g_authFsmList);
1991 ReleaseAuthLock();
1992 }
1993
HandleMsgRecvAuthTestData(AuthFsm * authFsm,const MessagePara * para)1994 static void HandleMsgRecvAuthTestData(AuthFsm *authFsm, const MessagePara *para)
1995 {
1996 int32_t ret = SOFTBUS_OK;
1997 AuthSessionInfo *info = &authFsm->info;
1998 do {
1999 if (info->isServer) {
2000 if (PostAuthTestInfoMessage(authFsm->authSeq, info) != SOFTBUS_OK) {
2001 ret = SOFTBUS_AUTH_SYNC_DEVID_FAIL;
2002 break;
2003 }
2004 }
2005 if (ProcessAuthTestDataMessage(authFsm->authSeq, info, para->data, para->len) != SOFTBUS_OK) {
2006 ret = SOFTBUS_AUTH_SYNC_DEVID_FAIL;
2007 break;
2008 }
2009 } while (false);
2010 if (ret != SOFTBUS_OK) {
2011 RemoveAuthSessionKeyByIndex(authFsm->authSeq, authFsm->authSeq, authFsm->info.connInfo.type);
2012 if (!info->isServer) {
2013 ret = ProcessClientAuthState(authFsm);
2014 if (ret != SOFTBUS_OK) {
2015 AUTH_LOGE(AUTH_FSM, "auth fsm auth fail. authSeq=%{public}" PRId64 "", authFsm->authSeq);
2016 CompleteAuthSession(authFsm, SOFTBUS_AUTH_SYNC_DEVINFO_FAIL);
2017 }
2018 }
2019 return;
2020 }
2021 if (TrySyncDeviceInfo(authFsm->authSeq, &authFsm->info) != SOFTBUS_OK) {
2022 AUTH_LOGE(AUTH_FSM, "auth fsm sync device info fail. authSeq=%{public}" PRId64 "", authFsm->authSeq);
2023 CompleteAuthSession(authFsm, SOFTBUS_AUTH_SYNC_DEVINFO_FAIL);
2024 return;
2025 }
2026 if (authFsm->info.deviceInfoData != NULL) {
2027 AUTH_LOGE(AUTH_FSM, "auth fsm dispatch device info to next state. authSeq=%{public}" PRId64, authFsm->authSeq);
2028 (void)AuthSessionProcessDevInfoData(
2029 authFsm->authSeq, authFsm->info.deviceInfoData, authFsm->info.deviceInfoDataLen);
2030 SoftBusFree(authFsm->info.deviceInfoData);
2031 authFsm->info.deviceInfoData = NULL;
2032 }
2033 LnnFsmTransactState(&authFsm->fsm, g_states + STATE_SYNC_DEVICE_INFO);
2034 authFsm->curState = STATE_SYNC_DEVICE_INFO;
2035 AuthSessionHandleAuthFinish(authFsm->authSeq);
2036 }
2037
HandleMsgSaveSessionKey(AuthFsm * authFsm,const MessagePara * para)2038 static void HandleMsgSaveSessionKey(AuthFsm *authFsm, const MessagePara *para)
2039 {
2040 SessionKey sessionKey = { .len = para->len };
2041 if (memcpy_s(sessionKey.value, sizeof(sessionKey.value), para->data, para->len) != EOK) {
2042 AUTH_LOGE(AUTH_FSM, "copy session key fail.");
2043 (void)memset_s(&sessionKey, sizeof(sessionKey), 0, sizeof(sessionKey));
2044 return;
2045 }
2046 if (AuthManagerSetSessionKey(authFsm->authSeq, &authFsm->info, &sessionKey, true, false) != SOFTBUS_OK) {
2047 AUTH_LOGE(AUTH_FSM, "auth fsm save session key fail. authSeq=%{public}" PRId64 "", authFsm->authSeq);
2048 }
2049
2050 (void)CalcHKDF((uint8_t *)(&sessionKey.value), sessionKey.len, (uint8_t *)(&authFsm->info.sessionKeyRandomNum),
2051 sizeof(authFsm->info.sessionKeyRandomNum));
2052 (void)memset_s(&sessionKey, sizeof(sessionKey), 0, sizeof(sessionKey));
2053 if (LnnGenerateLocalPtk(authFsm->info.udid, authFsm->info.uuid) != SOFTBUS_OK) {
2054 AUTH_LOGE(AUTH_FSM, "generate ptk fail");
2055 }
2056 authFsm->info.nodeInfo.isNeedReSyncDeviceName = false;
2057 if (authFsm->info.isSupportDmDeviceKey) {
2058 if (TrySendAuthTestInfo(authFsm->authSeq, &authFsm->info) != SOFTBUS_OK) {
2059 AUTH_LOGI(AUTH_FSM, "auth fsm reuse dm device key fail. authSeq=%{public}" PRId64 "", authFsm->authSeq);
2060 if (ProcessClientAuthState(authFsm) != SOFTBUS_OK) {
2061 AUTH_LOGI(AUTH_FSM, "auth fsm sync device info fail. authSeq=%{public}" PRId64 "", authFsm->authSeq);
2062 CompleteAuthSession(authFsm, SOFTBUS_AUTH_SYNC_DEVINFO_FAIL);
2063 }
2064 }
2065 return;
2066 }
2067 if (TrySyncDeviceInfo(authFsm->authSeq, &authFsm->info) != SOFTBUS_OK) {
2068 AUTH_LOGE(AUTH_FSM, "auth fsm sync device info fail. authSeq=%{public}" PRId64 "", authFsm->authSeq);
2069 CompleteAuthSession(authFsm, SOFTBUS_AUTH_SYNC_DEVINFO_FAIL);
2070 return;
2071 }
2072 if (authFsm->info.deviceInfoData != NULL) {
2073 AUTH_LOGE(AUTH_FSM, "auth fsm dispatch device info to next state. authSeq=%{public}" PRId64, authFsm->authSeq);
2074 (void)AuthSessionProcessDevInfoData(
2075 authFsm->authSeq, authFsm->info.deviceInfoData, authFsm->info.deviceInfoDataLen);
2076 SoftBusFree(authFsm->info.deviceInfoData);
2077 authFsm->info.deviceInfoData = NULL;
2078 }
2079 LnnFsmTransactState(&authFsm->fsm, g_states + STATE_SYNC_DEVICE_INFO);
2080 authFsm->curState = STATE_SYNC_DEVICE_INFO;
2081 }
AuthSessionSetReSyncDeviceName(void)2082 void AuthSessionSetReSyncDeviceName(void)
2083 {
2084 if (!RequireAuthLock()) {
2085 AUTH_LOGE(AUTH_FSM, "get auth lock fail");
2086 return;
2087 }
2088 AuthFsm *item = NULL;
2089 AuthFsm *next = NULL;
2090 LIST_FOR_EACH_ENTRY_SAFE(item, next, &g_authFsmList, AuthFsm, node) {
2091 if (item->curState >= STATE_SYNC_DEVICE_INFO) {
2092 AUTH_LOGI(AUTH_FSM, "need resync latest device name authSeq=%{public}" PRId64, item->authSeq);
2093 item->info.nodeInfo.isNeedReSyncDeviceName = true;
2094 }
2095 }
2096 ReleaseAuthLock();
2097 }
2098