• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2023 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 "cert_operation.h"
17 
18 #include "account_auth_plugin_proxy.h"
19 #include "account_related_group_auth.h"
20 #include "alg_loader.h"
21 #include "asy_token_manager.h"
22 #include "data_manager.h"
23 #include "group_auth_data_operation.h"
24 #include "group_operation_common.h"
25 #include "hc_log.h"
26 #include "hc_types.h"
27 #include "identity_common.h"
28 #include "pseudonym_manager.h"
29 #include "sym_token_manager.h"
30 
31 #define FIELD_SHARED_SECRET "sharedSecret"
32 
SetProtocolsForUidType(IdentityInfo * info)33 static int32_t SetProtocolsForUidType(IdentityInfo *info)
34 {
35 #ifdef ENABLE_ACCOUNT_AUTH_ISO
36     ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0);
37     if (entity == NULL) {
38         LOGE("Failed to alloc memory for entity!");
39         return HC_ERR_ALLOC_MEMORY;
40     }
41     entity->protocolType = ALG_ISO;
42     entity->expandProcessCmds = CMD_ADD_TRUST_DEVICE;
43     info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity);
44 #else
45     (void)info;
46 #endif
47 
48     return HC_SUCCESS;
49 }
50 
GetIdentityInfoByType(int32_t keyType,int32_t trustType,const char * groupId,IdentityInfo * info)51 static int32_t GetIdentityInfoByType(int32_t keyType, int32_t trustType, const char *groupId, IdentityInfo *info)
52 {
53     CJson *urlJson = CreateJson();
54     if (urlJson == NULL) {
55         LOGE("Failed to create url json!");
56         return HC_ERR_JSON_CREATE;
57     }
58     if (AddIntToJson(urlJson, PRESHARED_URL_CREDENTIAL_TYPE, PRE_SHARED) != HC_SUCCESS) {
59         LOGE("Failed to add credential type!");
60         FreeJson(urlJson);
61         return HC_ERR_JSON_ADD;
62     }
63     if (AddIntToJson(urlJson, PRESHARED_URL_KEY_TYPE, keyType) != HC_SUCCESS) {
64         LOGE("Failed to add key type!");
65         FreeJson(urlJson);
66         return HC_ERR_JSON_ADD;
67     }
68     if (AddIntToJson(urlJson, PRESHARED_URL_TRUST_TYPE, trustType) != HC_SUCCESS) {
69         LOGE("Failed to add trust type!");
70         FreeJson(urlJson);
71         return HC_ERR_JSON_ADD;
72     }
73     if ((trustType == TRUST_TYPE_P2P || trustType == TRUST_TYPE_UID) &&
74         AddStringToJson(urlJson, FIELD_GROUP_ID, groupId) != HC_SUCCESS) {
75         LOGE("Failed to add group id!");
76         FreeJson(urlJson);
77         return HC_ERR_JSON_ADD;
78     }
79     char *urlStr = PackJsonToString(urlJson);
80     FreeJson(urlJson);
81     if (urlStr == NULL) {
82         LOGE("Failed to pack url json to string!");
83         return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
84     }
85 
86     int32_t ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl);
87     FreeJsonString(urlStr);
88     if (ret != HC_SUCCESS) {
89         LOGE("Failed to set preSharedUrl of proof!");
90         return ret;
91     }
92 
93     ret = SetProtocolsForUidType(info);
94     if (ret != HC_SUCCESS) {
95         LOGE("Failed to set protocols!");
96         return ret;
97     }
98 
99     info->proofType = PRE_SHARED;
100     return ret;
101 }
102 
AddCertInfoToJson(const CertInfo * certInfo,CJson * out)103 int32_t AddCertInfoToJson(const CertInfo *certInfo, CJson *out)
104 {
105     if (certInfo == NULL || out == NULL) {
106         LOGE("Invalid cert info or out!");
107         return HC_ERR_INVALID_PARAMS;
108     }
109     if (AddIntToJson(out, FIELD_SIGN_ALG, certInfo->signAlg) != HC_SUCCESS) {
110         LOGE("add sign alg to json failed!");
111         return HC_ERR_JSON_ADD;
112     }
113     if (AddStringToJson(out, FIELD_PK_INFO, (const char *)certInfo->pkInfoStr.val) != HC_SUCCESS) {
114         LOGE("add pk info str to json failed!");
115         return HC_ERR_JSON_ADD;
116     }
117     if (AddByteToJson(out, FIELD_PK_INFO_SIGNATURE, certInfo->pkInfoSignature.val,
118         certInfo->pkInfoSignature.length) != HC_SUCCESS) {
119         LOGE("add pk info sign to json failed!");
120         return HC_ERR_JSON_ADD;
121     }
122     return HC_SUCCESS;
123 }
124 
GetSelfGroupEntryByPeerCert(int32_t osAccountId,const CertInfo * certInfo)125 static TrustedGroupEntry *GetSelfGroupEntryByPeerCert(int32_t osAccountId, const CertInfo *certInfo)
126 {
127     CJson *peerPkInfoJson = CreateJsonFromString((const char *)certInfo->pkInfoStr.val);
128     if (peerPkInfoJson == NULL) {
129         LOGE("Failed to create peer pkInfoJson!");
130         return NULL;
131     }
132     const char *peerUserId = GetStringFromJson(peerPkInfoJson, FIELD_USER_ID);
133     if (peerUserId == NULL) {
134         LOGE("Failed to get peer userId!");
135         FreeJson(peerPkInfoJson);
136         return NULL;
137     }
138     CJson *param = CreateJson();
139     if (param == NULL) {
140         LOGE("Failed to create query param!");
141         FreeJson(peerPkInfoJson);
142         return NULL;
143     }
144     if (AddStringToJson(param, FIELD_USER_ID, peerUserId) != HC_SUCCESS) {
145         LOGE("Failed to add peer userId to param!");
146         FreeJson(param);
147         FreeJson(peerPkInfoJson);
148         return NULL;
149     }
150     FreeJson(peerPkInfoJson);
151     BaseGroupAuth *groupAuth = GetAccountRelatedGroupAuth();
152     if (groupAuth == NULL) {
153         LOGE("Failed to get account group auth!");
154         FreeJson(param);
155         return NULL;
156     }
157     GroupEntryVec groupEntryVec = CreateGroupEntryVec();
158     QueryGroupParams queryParams = InitQueryGroupParams();
159     ((AccountRelatedGroupAuth *)groupAuth)
160         ->getAccountCandidateGroup(osAccountId, param, &queryParams, &groupEntryVec);
161     FreeJson(param);
162     if (groupEntryVec.size(&groupEntryVec) == 0) {
163         LOGE("group not found by peer user id!");
164         ClearGroupEntryVec(&groupEntryVec);
165         return NULL;
166     }
167     TrustedGroupEntry *returnEntry = DeepCopyGroupEntry(groupEntryVec.get(&groupEntryVec, 0));
168     ClearGroupEntryVec(&groupEntryVec);
169     return returnEntry;
170 }
171 
GetSelfDeviceEntryByPeerCert(int32_t osAccountId,const CertInfo * certInfo,TrustedDeviceEntry * deviceEntry)172 static int32_t GetSelfDeviceEntryByPeerCert(
173     int32_t osAccountId, const CertInfo *certInfo, TrustedDeviceEntry *deviceEntry)
174 {
175     TrustedGroupEntry *groupEntry = GetSelfGroupEntryByPeerCert(osAccountId, certInfo);
176     if (groupEntry == NULL) {
177         LOGE("Failed to get self group entry!");
178         return HC_ERR_GROUP_NOT_EXIST;
179     }
180     const char *groupId = StringGet(&groupEntry->id);
181     int32_t ret = GetSelfDeviceEntry(osAccountId, groupId, deviceEntry);
182     DestroyGroupEntry(groupEntry);
183     return ret;
184 }
185 
VerifyPeerCertInfo(const char * selfUserId,const char * selfAuthId,const CertInfo * certInfo)186 static int32_t VerifyPeerCertInfo(const char *selfUserId, const char *selfAuthId, const CertInfo *certInfo)
187 {
188     uint8_t *keyAliasValue = (uint8_t *)HcMalloc(SHA256_LEN, 0);
189     if (keyAliasValue == NULL) {
190         LOGE("Failed to alloc memory for key alias value!");
191         return HC_ERR_ALLOC_MEMORY;
192     }
193     Uint8Buff keyAlias = { .val = keyAliasValue, .length = SHA256_LEN };
194     int32_t ret = GetAccountAuthTokenManager()->generateKeyAlias(selfUserId, selfAuthId, &keyAlias, true);
195     if (ret != HC_SUCCESS) {
196         LOGE("Failed to generate server pk alias!");
197         HcFree(keyAliasValue);
198         return ret;
199     }
200     ret = GetLoaderInstance()->verify(
201         &keyAlias, &certInfo->pkInfoStr, certInfo->signAlg, &certInfo->pkInfoSignature, true);
202     HcFree(keyAliasValue);
203     if (ret != HC_SUCCESS) {
204         return HC_ERR_VERIFY_FAILED;
205     }
206     return HC_SUCCESS;
207 }
208 
GetPeerPubKeyFromCert(const CertInfo * peerCertInfo,Uint8Buff * peerPkBuff)209 static int32_t GetPeerPubKeyFromCert(const CertInfo *peerCertInfo, Uint8Buff *peerPkBuff)
210 {
211     CJson *pkInfoPeer = CreateJsonFromString((const char *)peerCertInfo->pkInfoStr.val);
212     if (pkInfoPeer == NULL) {
213         LOGE("Failed to create peer pkInfo json!");
214         return HC_ERR_JSON_CREATE;
215     }
216     const char *devicePk = GetStringFromJson(pkInfoPeer, FIELD_DEVICE_PK);
217     if (devicePk == NULL) {
218         LOGE("Failed to get peer devicePk!");
219         FreeJson(pkInfoPeer);
220         return HC_ERR_JSON_GET;
221     }
222     uint32_t pkSize = HcStrlen(devicePk) / BYTE_TO_HEX_OPER_LENGTH;
223     peerPkBuff->val = (uint8_t *)HcMalloc(pkSize, 0);
224     if (peerPkBuff->val == NULL) {
225         LOGE("Failed to alloc memory for peerPk!");
226         FreeJson(pkInfoPeer);
227         return HC_ERR_ALLOC_MEMORY;
228     }
229     if (GetByteFromJson(pkInfoPeer, FIELD_DEVICE_PK, peerPkBuff->val, pkSize) != HC_SUCCESS) {
230         LOGE("Failed to get peer public key!");
231         HcFree(peerPkBuff->val);
232         FreeJson(pkInfoPeer);
233         return HC_ERR_JSON_GET;
234     }
235     FreeJson(pkInfoPeer);
236     peerPkBuff->length = pkSize;
237     return HC_SUCCESS;
238 }
239 
GetSharedSecretForAccountInPake(const char * userId,const char * authId,const CertInfo * peerCertInfo,Uint8Buff * sharedSecret)240 static int32_t GetSharedSecretForAccountInPake(
241     const char *userId, const char *authId, const CertInfo *peerCertInfo, Uint8Buff *sharedSecret)
242 {
243     uint8_t *priAliasVal = (uint8_t *)HcMalloc(SHA256_LEN, 0);
244     if (priAliasVal == NULL) {
245         LOGE("Failed to alloc memory for self key alias!");
246         return HC_ERR_ALLOC_MEMORY;
247     }
248     Uint8Buff aliasBuff = { priAliasVal, SHA256_LEN };
249     int32_t ret = GetAccountAuthTokenManager()->generateKeyAlias(userId, authId, &aliasBuff, false);
250     if (ret != HC_SUCCESS) {
251         HcFree(priAliasVal);
252         return ret;
253     }
254     KeyBuff priAliasKeyBuff = { .key = aliasBuff.val, .keyLen = aliasBuff.length, .isAlias = true };
255     Uint8Buff peerPkBuff = { 0 };
256     ret = GetPeerPubKeyFromCert(peerCertInfo, &peerPkBuff);
257     if (ret != HC_SUCCESS) {
258         HcFree(priAliasVal);
259         return ret;
260     }
261     KeyBuff publicKeyBuff = { .key = peerPkBuff.val, .keyLen = peerPkBuff.length, .isAlias = false };
262 
263     uint32_t sharedKeyAliasLen = HcStrlen(SHARED_KEY_ALIAS) + 1;
264     sharedSecret->val = (uint8_t *)HcMalloc(sharedKeyAliasLen, 0);
265     if (sharedSecret->val == NULL) {
266         LOGE("Failed to malloc for psk alias.");
267         HcFree(priAliasVal);
268         ClearFreeUint8Buff(&peerPkBuff);
269         return HC_ERR_ALLOC_MEMORY;
270     }
271     sharedSecret->length = sharedKeyAliasLen;
272     (void)memcpy_s(sharedSecret->val, sharedKeyAliasLen, SHARED_KEY_ALIAS, sharedKeyAliasLen);
273     ret = GetLoaderInstance()->agreeSharedSecretWithStorage(
274         &priAliasKeyBuff, &publicKeyBuff, P256, P256_SHARED_SECRET_KEY_SIZE, sharedSecret);
275     HcFree(priAliasVal);
276     ClearFreeUint8Buff(&peerPkBuff);
277     if (ret != HC_SUCCESS) {
278         LOGE("Failed to agree shared secret!");
279         FreeBuffData(sharedSecret);
280     }
281     return ret;
282 }
283 
GenerateCertInfo(const Uint8Buff * pkInfoStr,const Uint8Buff * pkInfoSignature,CertInfo * certInfo)284 int32_t GenerateCertInfo(const Uint8Buff *pkInfoStr, const Uint8Buff *pkInfoSignature, CertInfo *certInfo)
285 {
286     uint32_t pkInfoLen = pkInfoStr->length;
287     certInfo->pkInfoStr.val = (uint8_t *)HcMalloc(pkInfoLen, 0);
288     if (certInfo->pkInfoStr.val == NULL) {
289         LOGE("Failed to alloc pkInfo memory!");
290         return HC_ERR_ALLOC_MEMORY;
291     }
292     if (memcpy_s(certInfo->pkInfoStr.val, pkInfoLen, pkInfoStr->val, pkInfoLen) != EOK) {
293         LOGE("Failed to copy pkInfo!");
294         FreeBuffData(&certInfo->pkInfoStr);
295         return HC_ERR_MEMORY_COPY;
296     }
297     certInfo->pkInfoStr.length = pkInfoLen;
298 
299     uint32_t signatureLen = pkInfoSignature->length;
300     certInfo->pkInfoSignature.val = (uint8_t *)HcMalloc(signatureLen, 0);
301     if (certInfo->pkInfoSignature.val == NULL) {
302         LOGE("Failed to alloc pkInfoSignature memory!");
303         FreeBuffData(&certInfo->pkInfoStr);
304         return HC_ERR_ALLOC_MEMORY;
305     }
306     if (memcpy_s(certInfo->pkInfoSignature.val, signatureLen, pkInfoSignature->val, signatureLen) != EOK) {
307         LOGE("Failed to copy pkInfoSignature!");
308         FreeBuffData(&certInfo->pkInfoStr);
309         FreeBuffData(&certInfo->pkInfoSignature);
310         return HC_ERR_MEMORY_COPY;
311     }
312     certInfo->pkInfoSignature.length = signatureLen;
313     return HC_SUCCESS;
314 }
315 
GetCertInfo(int32_t osAccountId,const char * userId,const char * authId,CertInfo * certInfo)316 static int32_t GetCertInfo(int32_t osAccountId, const char *userId, const char *authId, CertInfo *certInfo)
317 {
318     AccountToken *token = CreateAccountToken();
319     if (token == NULL) {
320         LOGE("Failed to create account token.");
321         return HC_ERR_ALLOC_MEMORY;
322     }
323     int32_t ret = GetAccountAuthTokenManager()->getToken(osAccountId, token, userId, authId);
324     if (ret != HC_SUCCESS) {
325         LOGE("Failed to get account token!");
326         DestroyAccountToken(token);
327         return ret;
328     }
329     ret = GenerateCertInfo(&token->pkInfoStr, &token->pkInfoSignature, certInfo);
330     DestroyAccountToken(token);
331     if (ret != HC_SUCCESS) {
332         LOGE("Failed to generate cert info!");
333         return ret;
334     }
335     certInfo->signAlg = P256;
336     return HC_SUCCESS;
337 }
338 
GetAccountAsymIdentityInfo(int32_t osAccountId,const char * userId,const char * authId,IdentityInfo * info,bool isNeedGeneratePdid)339 static int32_t GetAccountAsymIdentityInfo(
340     int32_t osAccountId, const char *userId, const char *authId, IdentityInfo *info, bool isNeedGeneratePdid)
341 {
342     int32_t ret = GetCertInfo(osAccountId, userId, authId, &info->proof.certInfo);
343     if (ret != HC_SUCCESS) {
344         LOGE("Failed to generate certInfo!");
345         return ret;
346     }
347 
348 #ifdef ENABLE_ACCOUNT_AUTH_EC_SPEKE
349     ProtocolEntity *ecSpekeEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0);
350     if (ecSpekeEntity == NULL) {
351         LOGE("Failed to alloc memory for ec speke entity!");
352         return HC_ERR_ALLOC_MEMORY;
353     }
354     ecSpekeEntity->protocolType = ALG_EC_SPEKE;
355     ecSpekeEntity->expandProcessCmds = CMD_ADD_TRUST_DEVICE;
356 #ifdef ENABLE_PSEUDONYM
357     if (isNeedGeneratePdid) {
358         ecSpekeEntity->expandProcessCmds |= CMD_MK_AGREE;
359     }
360 #else
361     (void)isNeedGeneratePdid;
362 #endif
363     info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&ecSpekeEntity);
364 #else
365     (void)isNeedGeneratePdid;
366 #endif
367 
368     info->proofType = CERTIFICATED;
369     return HC_SUCCESS;
370 }
371 
GetLocalDeviceType(int32_t osAccountId,const CJson * in,const char * groupId,int32_t * localDevType)372 static int32_t GetLocalDeviceType(int32_t osAccountId, const CJson *in, const char *groupId, int32_t *localDevType)
373 {
374     TrustedDeviceEntry *deviceEntry = CreateDeviceEntry();
375     if (deviceEntry == NULL) {
376         LOGE("Failed to alloc memory for deviceEntry!");
377         return HC_ERR_ALLOC_MEMORY;
378     }
379     int32_t ret = GetPeerDeviceEntry(osAccountId, in, groupId, deviceEntry);
380     if (ret != HC_SUCCESS) {
381         LOGI("Peer device not found, set local device type to accessory!");
382         *localDevType = DEVICE_TYPE_ACCESSORY;
383         DestroyDeviceEntry(deviceEntry);
384         return HC_SUCCESS;
385     }
386     if (deviceEntry->source == SELF_CREATED) {
387         LOGI("Peer device is self created, set local device type to accessory!");
388         *localDevType = DEVICE_TYPE_ACCESSORY;
389     }
390     DestroyDeviceEntry(deviceEntry);
391     return HC_SUCCESS;
392 }
393 
GenerateAuthTokenForAccessory(int32_t osAccountId,const char * groupId,Uint8Buff * authToken)394 static int32_t GenerateAuthTokenForAccessory(int32_t osAccountId, const char *groupId, Uint8Buff *authToken)
395 {
396     TrustedDeviceEntry *deviceEntry = CreateDeviceEntry();
397     if (deviceEntry == NULL) {
398         LOGE("Failed to create device entry!");
399         return HC_ERR_ALLOC_MEMORY;
400     }
401     int32_t ret = GetSelfDeviceEntry(osAccountId, groupId, deviceEntry);
402     if (ret != HC_SUCCESS) {
403         LOGE("Failed to get self device entry!");
404         DestroyDeviceEntry(deviceEntry);
405         return ret;
406     }
407     const char *userIdSelf = StringGet(&deviceEntry->userId);
408     const char *devIdSelf = StringGet(&deviceEntry->authId);
409     uint8_t keyAliasVal[SHA256_LEN] = { 0 };
410     Uint8Buff keyAlias = { keyAliasVal, SHA256_LEN };
411     ret = GetSymTokenManager()->generateKeyAlias(userIdSelf, devIdSelf, &keyAlias);
412     if (ret != HC_SUCCESS) {
413         LOGE("Failed to generate key alias for authCode!");
414         DestroyDeviceEntry(deviceEntry);
415         return ret;
416     }
417 
418     authToken->val = (uint8_t *)HcMalloc(AUTH_TOKEN_SIZE, 0);
419     if (authToken->val == NULL) {
420         LOGE("Failed to alloc memory for auth token!");
421         DestroyDeviceEntry(deviceEntry);
422         return HC_ERR_ALLOC_MEMORY;
423     }
424     authToken->length = AUTH_TOKEN_SIZE;
425     Uint8Buff userIdBuff = { (uint8_t *)userIdSelf, HcStrlen(userIdSelf) };
426     Uint8Buff challenge = { (uint8_t *)KEY_INFO_PERSISTENT_TOKEN, HcStrlen(KEY_INFO_PERSISTENT_TOKEN) };
427     ret = GetLoaderInstance()->computeHkdf(&keyAlias, &userIdBuff, &challenge, authToken, true);
428     DestroyDeviceEntry(deviceEntry);
429     if (ret != HC_SUCCESS) {
430         LOGE("Failed to computeHkdf from authCode to authToken!");
431         FreeBuffData(authToken);
432     }
433     return ret;
434 }
435 
GenerateTokenAliasForController(int32_t osAccountId,const CJson * in,const char * groupId,Uint8Buff * authTokenAlias)436 static int32_t GenerateTokenAliasForController(
437     int32_t osAccountId, const CJson *in, const char *groupId, Uint8Buff *authTokenAlias)
438 {
439     TrustedDeviceEntry *deviceEntry = CreateDeviceEntry();
440     if (deviceEntry == NULL) {
441         LOGE("Failed to create device entry!");
442         return HC_ERR_ALLOC_MEMORY;
443     }
444     int32_t ret = GetPeerDeviceEntry(osAccountId, in, groupId, deviceEntry);
445     if (ret != HC_SUCCESS) {
446         LOGE("Failed to get peer device entry!");
447         DestroyDeviceEntry(deviceEntry);
448         return ret;
449     }
450     authTokenAlias->val = (uint8_t *)HcMalloc(SHA256_LEN, 0);
451     if (authTokenAlias->val == NULL) {
452         LOGE("Failed to alloc memory for auth token alias!");
453         DestroyDeviceEntry(deviceEntry);
454         return HC_ERR_ALLOC_MEMORY;
455     }
456     authTokenAlias->length = SHA256_LEN;
457     const char *userIdPeer = StringGet(&deviceEntry->userId);
458     const char *devIdPeer = StringGet(&deviceEntry->authId);
459     ret = GetSymTokenManager()->generateKeyAlias(userIdPeer, devIdPeer, authTokenAlias);
460     DestroyDeviceEntry(deviceEntry);
461     if (ret != HC_SUCCESS) {
462         LOGE("Failed to generate key alias for authToken!");
463         FreeBuffData(authTokenAlias);
464     }
465     return ret;
466 }
467 
GenerateAuthTokenByDevType(const CJson * in,const CJson * urlJson,Uint8Buff * authToken,bool * isTokenStored)468 static int32_t GenerateAuthTokenByDevType(
469     const CJson *in, const CJson *urlJson, Uint8Buff *authToken, bool *isTokenStored)
470 {
471     int32_t osAccountId = INVALID_OS_ACCOUNT;
472     if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) {
473         LOGE("Failed to get osAccountId!");
474         return HC_ERR_JSON_GET;
475     }
476     const char *groupId = GetStringFromJson(urlJson, FIELD_GROUP_ID);
477     if (groupId == NULL) {
478         LOGE("Failed to get groupId!");
479         return HC_ERR_JSON_GET;
480     }
481     int32_t localDevType = DEVICE_TYPE_CONTROLLER;
482     int32_t ret = GetLocalDeviceType(osAccountId, in, groupId, &localDevType);
483     if (ret != HC_SUCCESS) {
484         LOGE("Failed to get local device type!");
485         return ret;
486     }
487     if (localDevType == DEVICE_TYPE_ACCESSORY) {
488         *isTokenStored = false;
489         ret = GenerateAuthTokenForAccessory(osAccountId, groupId, authToken);
490     } else {
491         ret = GenerateTokenAliasForController(osAccountId, in, groupId, authToken);
492     }
493     return ret;
494 }
495 
GetSelfAccountIdentityInfo(int32_t osAccountId,const char * groupId,IdentityInfo * info,bool isNeedGeneratePdid)496 static int32_t GetSelfAccountIdentityInfo(
497     int32_t osAccountId, const char *groupId, IdentityInfo *info, bool isNeedGeneratePdid)
498 {
499     TrustedDeviceEntry *deviceEntry = CreateDeviceEntry();
500     if (deviceEntry == NULL) {
501         LOGE("Failed to create device entry!");
502         return HC_ERR_ALLOC_MEMORY;
503     }
504     int32_t ret = GetSelfDeviceEntry(osAccountId, groupId, deviceEntry);
505     if (ret != HC_SUCCESS) {
506         LOGE("Failed to get self device entry!");
507         DestroyDeviceEntry(deviceEntry);
508         return ret;
509     }
510     if (deviceEntry->credential == SYMMETRIC_CRED) {
511         ret = GetIdentityInfoByType(KEY_TYPE_SYM, TRUST_TYPE_UID, groupId, info);
512     } else {
513         const char *userId = StringGet(&deviceEntry->userId);
514         const char *authId = StringGet(&deviceEntry->authId);
515         ret = GetAccountAsymIdentityInfo(osAccountId, userId, authId, info, isNeedGeneratePdid);
516     }
517     DestroyDeviceEntry(deviceEntry);
518     return ret;
519 }
520 
isNeedGeneratePdidByPeerCert(int32_t osAccountId,const CertInfo * certInfo)521 static bool isNeedGeneratePdidByPeerCert(int32_t osAccountId, const CertInfo *certInfo)
522 {
523 #ifdef ENABLE_PSEUDONYM
524     CJson *pkInfoJson = CreateJsonFromString((const char *)certInfo->pkInfoStr.val);
525     if (pkInfoJson == NULL) {
526         LOGE("Failed to create pkInfo json!");
527         return false;
528     }
529     const char *userId = GetStringFromJson(pkInfoJson, FIELD_USER_ID);
530     if (userId == NULL) {
531         LOGE("Failed to get userId!");
532         FreeJson(pkInfoJson);
533         return false;
534     }
535     bool isNeedGenerate = GetPseudonymInstance()->isNeedRefreshPseudonymId(osAccountId, userId);
536     FreeJson(pkInfoJson);
537     return isNeedGenerate;
538 #else
539     (void)osAccountId;
540     (void)certInfo;
541     return false;
542 #endif
543 }
544 
GetAccountRelatedCredInfo(int32_t osAccountId,const char * groupId,const char * deviceId,bool isUdid,IdentityInfo * info)545 int32_t GetAccountRelatedCredInfo(
546     int32_t osAccountId, const char *groupId, const char *deviceId, bool isUdid, IdentityInfo *info)
547 {
548     if (groupId == NULL || deviceId == NULL || info == NULL) {
549         LOGE("Invalid input params!");
550         return HC_ERR_INVALID_PARAMS;
551     }
552     TrustedDeviceEntry *deviceEntry = CreateDeviceEntry();
553     if (deviceEntry == NULL) {
554         LOGE("Failed to create device entry!");
555         return HC_ERR_ALLOC_MEMORY;
556     }
557     int32_t ret = GaGetTrustedDeviceEntryById(osAccountId, deviceId, isUdid, groupId, deviceEntry);
558     if (ret != HC_SUCCESS) {
559         LOGI("peer device not exist, get self identity info.");
560         DestroyDeviceEntry(deviceEntry);
561         return GetSelfAccountIdentityInfo(osAccountId, groupId, info, true);
562     }
563     bool isNeedGeneratePdid = false;
564 #ifdef ENABLE_PSEUDONYM
565     const char *peerUserId = StringGet(&deviceEntry->userId);
566     isNeedGeneratePdid = GetPseudonymInstance()->isNeedRefreshPseudonymId(osAccountId, peerUserId);
567 #endif
568     if (deviceEntry->source == SELF_CREATED) {
569         LOGI("peer device is from self created, get self identity info.");
570         DestroyDeviceEntry(deviceEntry);
571         return GetSelfAccountIdentityInfo(osAccountId, groupId, info, isNeedGeneratePdid);
572     }
573     int credType = deviceEntry->credential;
574     DestroyDeviceEntry(deviceEntry);
575     if (credType == SYMMETRIC_CRED) {
576         LOGI("credential type is symmetric, get sym identity info.");
577         return GetIdentityInfoByType(KEY_TYPE_SYM, TRUST_TYPE_UID, groupId, info);
578     } else {
579         LOGI("credential type is asymmetric, get self identity info.");
580         return GetSelfAccountIdentityInfo(osAccountId, groupId, info, isNeedGeneratePdid);
581     }
582 }
583 
GetSharedSecretByPeerCertFromPlugin(int32_t osAccountId,const CertInfo * peerCertInfo,Uint8Buff * sharedSecret)584 static int32_t GetSharedSecretByPeerCertFromPlugin(
585     int32_t osAccountId, const CertInfo *peerCertInfo, Uint8Buff *sharedSecret)
586 {
587     CJson *input = CreateJson();
588     if (input == NULL) {
589         LOGE("Create input params json failed!");
590         return HC_ERR_JSON_CREATE;
591     }
592     CJson *output = CreateJson();
593     if (output == NULL) {
594         LOGE("Create output results json failed!");
595         FreeJson(input);
596         return HC_ERR_JSON_CREATE;
597     }
598     int32_t res;
599     GOTO_ERR_AND_SET_RET(AddCertInfoToJson(peerCertInfo, input), res);
600     GOTO_ERR_AND_SET_RET(ExcuteCredMgrCmd(osAccountId, GET_SHARED_SECRET_BY_PEER_CERT, input, output), res);
601     res = HC_ERR_JSON_GET;
602     const char *sharedKeyAlias = GetStringFromJson(output, FIELD_SHARED_SECRET);
603     if (sharedKeyAlias == NULL) {
604         LOGE("Get alias failed!");
605         goto ERR;
606     }
607     uint32_t sharedKeyAliasLen = HcStrlen(sharedKeyAlias) + 1;
608     uint8_t *aliasVal = (uint8_t *)HcMalloc(sharedKeyAliasLen, 0);
609     GOTO_IF_CHECK_NULL(aliasVal, FIELD_SHARED_SECRET);
610     if (memcpy_s(aliasVal, sharedKeyAliasLen, sharedKeyAlias, sharedKeyAliasLen) != EOK) {
611         LOGE("parse output result set memcpy alias failed!");
612         HcFree(aliasVal);
613         aliasVal = NULL;
614         goto ERR;
615     }
616     sharedSecret->val = aliasVal;
617     sharedSecret->length = sharedKeyAliasLen;
618     res = HC_SUCCESS;
619 ERR:
620     FreeJson(input);
621     FreeJson(output);
622     return res;
623 }
624 
GetAccountAsymSharedSecret(int32_t osAccountId,const CertInfo * peerCertInfo,Uint8Buff * sharedSecret)625 int32_t GetAccountAsymSharedSecret(int32_t osAccountId, const CertInfo *peerCertInfo, Uint8Buff *sharedSecret)
626 {
627     if (peerCertInfo == NULL || sharedSecret == NULL) {
628         LOGE("Invalid input params!");
629         return HC_ERR_INVALID_PARAMS;
630     }
631     if (HasAccountAuthPlugin() == HC_SUCCESS) {
632         return GetSharedSecretByPeerCertFromPlugin(osAccountId, peerCertInfo, sharedSecret);
633     }
634     TrustedDeviceEntry *deviceEntry = CreateDeviceEntry();
635     if (deviceEntry == NULL) {
636         LOGE("Failed to create self device entry!");
637         return HC_ERR_ALLOC_MEMORY;
638     }
639     int32_t ret = GetSelfDeviceEntryByPeerCert(osAccountId, peerCertInfo, deviceEntry);
640     if (ret != HC_SUCCESS) {
641         LOGE("Failed to get self device entry!");
642         DestroyDeviceEntry(deviceEntry);
643         return ret;
644     }
645     const char *selfUserId = StringGet(&deviceEntry->userId);
646     const char *selfAuthId = StringGet(&deviceEntry->authId);
647     ret = VerifyPeerCertInfo(selfUserId, selfAuthId, peerCertInfo);
648     if (ret != HC_SUCCESS) {
649         LOGE("Failed to verify peer cert! [Res]: %d", ret);
650         DestroyDeviceEntry(deviceEntry);
651         return ret;
652     }
653     ret = GetSharedSecretForAccountInPake(selfUserId, selfAuthId, peerCertInfo, sharedSecret);
654     DestroyDeviceEntry(deviceEntry);
655     return ret;
656 }
657 
GetAccountSymSharedSecret(const CJson * in,const CJson * urlJson,Uint8Buff * sharedSecret)658 int32_t GetAccountSymSharedSecret(const CJson *in, const CJson *urlJson, Uint8Buff *sharedSecret)
659 {
660     if (in == NULL || urlJson == NULL || sharedSecret == NULL) {
661         LOGE("Invalid input params!");
662         return HC_ERR_INVALID_PARAMS;
663     }
664     bool isTokenStored = true;
665     Uint8Buff authToken = { NULL, 0 };
666     int32_t ret = GenerateAuthTokenByDevType(in, urlJson, &authToken, &isTokenStored);
667     if (ret != HC_SUCCESS) {
668         LOGE("Failed to generate auth token!");
669         return ret;
670     }
671     uint8_t seed[SEED_SIZE] = { 0 };
672     Uint8Buff seedBuff = { seed, SEED_SIZE };
673     ret = GetByteFromJson(in, FIELD_SEED, seed, SEED_SIZE);
674     if (ret != HC_SUCCESS) {
675         LOGE("Failed to get seed!");
676         FreeBuffData(&authToken);
677         return HC_ERR_JSON_GET;
678     }
679     sharedSecret->val = (uint8_t *)HcMalloc(ISO_PSK_LEN, 0);
680     if (sharedSecret->val == NULL) {
681         LOGE("Failed to alloc sharedSecret memory!");
682         FreeBuffData(&authToken);
683         return HC_ERR_ALLOC_MEMORY;
684     }
685     sharedSecret->length = ISO_PSK_LEN;
686     ret = GetLoaderInstance()->computeHmac(&authToken, &seedBuff, sharedSecret, isTokenStored);
687     FreeBuffData(&authToken);
688     if (ret != HC_SUCCESS) {
689         LOGE("ComputeHmac for psk failed, ret: %d.", ret);
690         FreeBuffData(sharedSecret);
691     }
692     return ret;
693 }
694 
GetAccountAsymCredInfo(int32_t osAccountId,const CertInfo * certInfo,IdentityInfo ** returnInfo)695 int32_t GetAccountAsymCredInfo(int32_t osAccountId, const CertInfo *certInfo, IdentityInfo **returnInfo)
696 {
697     if (certInfo == NULL || returnInfo == NULL) {
698         LOGE("Invalid input params!");
699         return HC_ERR_INVALID_PARAMS;
700     }
701     TrustedDeviceEntry *deviceEntry = CreateDeviceEntry();
702     if (deviceEntry == NULL) {
703         LOGE("Failed to create self device entry!");
704         return HC_ERR_ALLOC_MEMORY;
705     }
706     int32_t ret = GetSelfDeviceEntryByPeerCert(osAccountId, certInfo, deviceEntry);
707     if (ret != HC_SUCCESS) {
708         LOGE("Failed to get self device entry!");
709         DestroyDeviceEntry(deviceEntry);
710         return ret;
711     }
712     IdentityInfo *info = CreateIdentityInfo();
713     if (info == NULL) {
714         LOGE("Failed to create identity info!");
715         DestroyDeviceEntry(deviceEntry);
716         return HC_ERR_ALLOC_MEMORY;
717     }
718     const char *selfUserId = StringGet(&deviceEntry->userId);
719     const char *selfAuthId = StringGet(&deviceEntry->authId);
720     bool isNeedGeneratePdid = isNeedGeneratePdidByPeerCert(osAccountId, certInfo);
721     ret = GetAccountAsymIdentityInfo(osAccountId, selfUserId, selfAuthId, info, isNeedGeneratePdid);
722     DestroyDeviceEntry(deviceEntry);
723     if (ret != HC_SUCCESS) {
724         LOGE("Failed to get account asym identity info!");
725         DestroyIdentityInfo(info);
726         return ret;
727     }
728     *returnInfo = info;
729     return HC_SUCCESS;
730 }
731 
GetAccountSymCredInfoByPeerUrl(const CJson * in,const CJson * urlJson,IdentityInfo * info)732 int32_t GetAccountSymCredInfoByPeerUrl(const CJson *in, const CJson *urlJson, IdentityInfo *info)
733 {
734     if (in == NULL || urlJson == NULL || info == NULL) {
735         LOGE("Invalid input params!");
736         return HC_ERR_INVALID_PARAMS;
737     }
738     int32_t osAccountId = INVALID_OS_ACCOUNT;
739     if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) {
740         LOGE("Failed to get osAccountId!");
741         return HC_ERR_JSON_GET;
742     }
743     const char *groupId = GetStringFromJson(urlJson, FIELD_GROUP_ID);
744     if (groupId == NULL) {
745         LOGE("Failed to get group id!");
746         return HC_ERR_JSON_GET;
747     }
748     int32_t ret = CheckGroupExist(osAccountId, groupId);
749     if (ret != HC_SUCCESS) {
750         LOGE("group not exist!");
751         return ret;
752     }
753     return GetIdentityInfoByType(KEY_TYPE_SYM, TRUST_TYPE_UID, groupId, info);
754 }