• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *    http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 
17 #include "identity_operation.h"
18 
19 #include "alg_defs.h"
20 #include "alg_loader.h"
21 #include "clib_error.h"
22 #include "cred_listener.h"
23 #include "device_auth.h"
24 #include "device_auth_defines.h"
25 #include "hal_error.h"
26 #include "hc_log.h"
27 #include "hc_time.h"
28 #include "identity_service_defines.h"
29 #include "permission_adapter.h"
30 #include "hisysevent_common.h"
31 #include "string_util.h"
32 
GetCredentialById(int32_t osAccountId,const char * credId,Credential ** returnEntry)33 int32_t GetCredentialById(int32_t osAccountId, const char *credId, Credential **returnEntry)
34 {
35     if (credId == NULL) {
36         LOGE("The input credId is NULL!");
37         return IS_ERR_INVALID_PARAMS;
38     }
39     uint32_t index;
40     CredentialVec credentialVec = CreateCredentialVec();
41     QueryCredentialParams params = InitQueryCredentialParams();
42     params.credId = credId;
43     int32_t ret = QueryCredentials(osAccountId, &params, &credentialVec);
44     if (ret != IS_SUCCESS) {
45         LOGE("Failed to query credentials!");
46         ClearCredentialVec(&credentialVec);
47         return ret;
48     }
49     Credential **credential = NULL;
50     FOR_EACH_HC_VECTOR(credentialVec, index, credential) {
51         *returnEntry = DeepCopyCredential(*credential);
52         ClearCredentialVec(&credentialVec);
53         if (*returnEntry == NULL) {
54             LOGE("Failed to copy credential!");
55             return IS_ERR_ALLOC_MEMORY;
56         }
57         return IS_SUCCESS;
58     }
59     ClearCredentialVec(&credentialVec);
60     LOGI("This credId does not exist!");
61     return IS_ERR_LOCAL_CRED_NOT_EXIST;
62 }
63 
Int64ToString(int64_t num,char ** result)64 static int32_t Int64ToString(int64_t num, char **result)
65 {
66     const int bufferSize = MAX_INT64_SIZE + 1;
67     char *tempStr = (char *)HcMalloc(bufferSize, 0);
68     if (tempStr == NULL) {
69         LOGE("Failed to allocate memory!");
70         return IS_ERR_ALLOC_MEMORY;
71     }
72     if (sprintf_s(tempStr, bufferSize, "%" PRId64, num) < 0) {
73         LOGE("Failed to convert int64 to string!");
74         HcFree(tempStr);
75         return IS_ERR_CONVERT_FAILED;
76     }
77     *result = tempStr;
78     return IS_SUCCESS;
79 }
80 
CombineBaseCredId(const char * credentialOwner,const char * deviceId,char ** baseCredIdStr)81 static int32_t CombineBaseCredId(const char *credentialOwner, const char *deviceId, char **baseCredIdStr)
82 {
83     if (credentialOwner == NULL || deviceId == NULL) {
84         LOGE("Invalid input parameters!");
85         return IS_ERR_INVALID_PARAMS;
86     }
87     char *timeStr = NULL;
88     int32_t ret = Int64ToString(HcGetCurTimeInMillis(), &timeStr);
89     if (ret != IS_SUCCESS) {
90         LOGE("Failed to convert time to string!");
91         return ret;
92     }
93     size_t totalLength = HcStrlen(credentialOwner) + HcStrlen(deviceId) + HcStrlen(timeStr) + 1;
94     char *tempCredId = (char *)HcMalloc(totalLength, 0);
95     if (tempCredId == NULL) {
96         LOGE("Failed to allocate memory for tempCredId!");
97         HcFree(timeStr);
98         return IS_ERR_ALLOC_MEMORY;
99     }
100 
101     if (strcpy_s(tempCredId, totalLength, credentialOwner) != EOK) {
102         LOGE("Failed to copy credentialOwner to tempCredId!");
103         HcFree(timeStr);
104         HcFree(tempCredId);
105         return IS_ERR_CONVERT_FAILED;
106     }
107     if (strcat_s(tempCredId, totalLength, deviceId) != EOK) {
108         LOGE("Failed to concatenate deviceId to tempCredId!");
109         HcFree(timeStr);
110         HcFree(tempCredId);
111         return IS_ERR_CONVERT_FAILED;
112     }
113     if (strcat_s(tempCredId, totalLength, timeStr) != EOK) {
114         LOGE("Failed to concatenate timeStr to tempCredId!");
115         HcFree(timeStr);
116         HcFree(tempCredId);
117         return IS_ERR_CONVERT_FAILED;
118     }
119     HcFree(timeStr);
120     *baseCredIdStr = tempCredId;
121     return IS_SUCCESS;
122 }
123 
Uint8BuffToString(Uint8Buff * byte,char ** str)124 static int32_t Uint8BuffToString(Uint8Buff *byte, char **str)
125 {
126     uint32_t strLen = byte->length * BYTE_TO_HEX_OPER_LENGTH + 1;
127     char *tempStr = (char *)HcMalloc(strLen, 0);
128     if (tempStr == NULL) {
129         LOGE("Failed to malloc tempStr");
130         return IS_ERR_ALLOC_MEMORY;
131     }
132     int32_t ret = ByteToHexString(byte->val, byte->length, tempStr, strLen);
133     if (ret != IS_SUCCESS) {
134         LOGE("Failed to convert byte to hex string");
135         HcFree(tempStr);
136         return ret;
137     }
138     *str = tempStr;
139     return IS_SUCCESS;
140 }
141 
Sha256BaseCredId(const char * baseCredIdStr,Uint8Buff * credIdByte,char ** credIdStr)142 static int32_t Sha256BaseCredId(const char *baseCredIdStr, Uint8Buff *credIdByte, char **credIdStr)
143 {
144     Uint8Buff returnCredIdByte = { NULL, SHA256_LEN };
145     returnCredIdByte.val = (uint8_t *)HcMalloc(SHA256_LEN, 0);
146     if (returnCredIdByte.val == NULL) {
147         LOGE("Failed to malloc memory for returnCredIdByte");
148         return IS_ERR_ALLOC_MEMORY;
149     }
150 
151     Uint8Buff baseCredIdBuff = { (uint8_t *)baseCredIdStr, (uint32_t)HcStrlen(baseCredIdStr) };
152     int32_t ret = GetLoaderInstance()->sha256(&baseCredIdBuff, &returnCredIdByte);
153     if (ret == HAL_ERR_HUKS) {
154         LOGE("Huks sha256 error");
155         HcFree(returnCredIdByte.val);
156         return IS_ERR_HUKS_SHA256_FAILED;
157     }
158     if (ret != IS_SUCCESS) {
159         LOGE("Failed to sha256 credId, ret = %" LOG_PUB "d", ret);
160         HcFree(returnCredIdByte.val);
161         return ret;
162     }
163 
164     char *returnCredIdStr = NULL;
165     ret = Uint8BuffToString(&returnCredIdByte, &returnCredIdStr);
166     if (ret != IS_SUCCESS) {
167         LOGE("Failed to convert credIdByte to credIdStr, ret = %" LOG_PUB "d", ret);
168         HcFree(returnCredIdByte.val);
169         return ret;
170     }
171     *credIdStr = returnCredIdStr;
172     credIdByte->val = returnCredIdByte.val;
173     credIdByte->length = SHA256_LEN;
174     return IS_SUCCESS;
175 }
176 
GenerateCredIdInner(const char * credentialOwner,const char * deviceId,Uint8Buff * credIdByte,char ** credIdStr)177 static int32_t GenerateCredIdInner(const char *credentialOwner, const char *deviceId,
178     Uint8Buff *credIdByte, char **credIdStr)
179 {
180     char *baseCredIdStr = NULL;
181     int32_t ret = CombineBaseCredId(credentialOwner, deviceId, &baseCredIdStr);
182     if (ret != IS_SUCCESS) {
183         LOGE("Failed to combine credId!");
184         return ret;
185     }
186 
187     ret = Sha256BaseCredId(baseCredIdStr, credIdByte, credIdStr);
188     HcFree(baseCredIdStr);
189     return ret;
190 }
191 
IsCredIdExist(int32_t osAccountId,const char * credIdStr)192 static bool IsCredIdExist(int32_t osAccountId, const char *credIdStr)
193 {
194     Credential *existedCredential = NULL;
195     int32_t ret = GetCredentialById(osAccountId, credIdStr, &existedCredential);
196     DestroyCredential(existedCredential);
197 
198     return ret == IS_SUCCESS;
199 }
200 
UseImportedCredId(int32_t osAccountId,Credential * credential,Uint8Buff * credIdByte)201 static int32_t UseImportedCredId(int32_t osAccountId, Credential *credential, Uint8Buff *credIdByte)
202 {
203     if (IsCredIdExist(osAccountId, StringGet(&credential->credId))) {
204         LOGE("Imported credId existed");
205         return IS_ERR_IMPORTED_CRED_ID_EXISTED;
206     }
207     LOGI("Imported credId not existed in DB, use imported credId");
208 
209     uint32_t credIdByteLen = HcStrlen(StringGet(&credential->credId)) / BYTE_TO_HEX_OPER_LENGTH;
210     credIdByte->length = credIdByteLen;
211     uint8_t *returnCredIdByteVal = (uint8_t *)HcMalloc(credIdByteLen, 0);
212     if (returnCredIdByteVal == NULL) {
213         LOGE("Failed to malloc memory for credIdByte");
214         return IS_ERR_ALLOC_MEMORY;
215     }
216 
217     int32_t ret = HexStringToByte(StringGet(&credential->credId), returnCredIdByteVal, credIdByte->length);
218     if (ret != IS_SUCCESS) {
219         LOGE("Failed to convert credId to byte, ret = %" LOG_PUB "d", ret);
220         HcFree(returnCredIdByteVal);
221         return IS_ERR_INVALID_HEX_STRING;
222     }
223     credIdByte->val = returnCredIdByteVal;
224     return IS_SUCCESS;
225 }
226 
GenerateUniqueCredId(int32_t osAccountId,Credential * credential,Uint8Buff * credIdByte,char ** credIdStr)227 static int32_t GenerateUniqueCredId(int32_t osAccountId,
228     Credential *credential, Uint8Buff *credIdByte, char **credIdStr)
229 {
230     char *returnCredId = NULL;
231     const char *credOwner = StringGet(&credential->credOwner);
232     const char *deviceId = StringGet(&credential->deviceId);
233     int32_t ret = GenerateCredIdInner(credOwner, deviceId, credIdByte, &returnCredId);
234     if (ret != IS_SUCCESS) {
235         return ret;
236     }
237     if (IsCredIdExist(osAccountId, returnCredId)) {
238         LOGW("CredId already exists, regenerate credId");
239         HcFree(returnCredId);
240         returnCredId = NULL;
241         ret = GenerateCredIdInner(credOwner, deviceId, credIdByte, &returnCredId);
242         if (ret != IS_SUCCESS) {
243             return ret;
244         }
245     }
246     *credIdStr = returnCredId;
247     return IS_SUCCESS;
248 }
249 
GenerateCredId(int32_t osAccountId,Credential * credential,Uint8Buff * credIdByte)250 int32_t GenerateCredId(int32_t osAccountId, Credential *credential, Uint8Buff *credIdByte)
251 {
252     if (HcStrlen(StringGet(&credential->credId)) > 0) {
253         return UseImportedCredId(osAccountId, credential, credIdByte); // credId is set by user
254     }
255 
256     char *credIdStr = NULL;
257     int32_t ret = GenerateUniqueCredId(osAccountId, credential, credIdByte, &credIdStr);
258     if (ret != IS_SUCCESS) {
259         return ret;
260     }
261 
262     if (!StringSetPointer(&credential->credId, credIdStr)) {
263         LOGE("Failed to set credId");
264         HcFree(credIdByte->val);
265         HcFree(credIdStr);
266         return IS_ERR_MEMORY_COPY;
267     }
268     HcFree(credIdStr);
269     LOGI("Generate credId success");
270     return IS_SUCCESS;
271 }
272 
CheckOutMaxCredSize(int32_t osAccountId,const char * credOwner)273 static int32_t CheckOutMaxCredSize(int32_t osAccountId, const char *credOwner)
274 {
275     QueryCredentialParams queryParams = InitQueryCredentialParams();
276     queryParams.credOwner = credOwner;
277     CredentialVec credentialVec = CreateCredentialVec();
278     int32_t ret = QueryCredentials(osAccountId, &queryParams, &credentialVec);
279     if (ret != IS_SUCCESS) {
280         LOGE("Failed to query credentials");
281         ClearCredentialVec(&credentialVec);
282         return ret;
283     }
284     if (credentialVec.size(&credentialVec) > MAX_CRED_SIZE) {
285         LOGE("The number of credentials exceeds the maximum limit");
286         ClearCredentialVec(&credentialVec);
287         return IS_ERR_BEYOND_LIMIT;
288     }
289     ClearCredentialVec(&credentialVec);
290     return IS_SUCCESS;
291 }
292 
GetAlgoFromCred(uint8_t algorithmType)293 static Algorithm GetAlgoFromCred(uint8_t algorithmType)
294 {
295     switch (algorithmType) {
296         case ALGO_TYPE_P256:
297             return P256;
298         case ALGO_TYPE_ED25519:
299             return ED25519;
300         default:
301             return AES;
302     }
303 }
304 
GenerateKeyValue(int32_t osAccountId,Credential * credential,KeyParams keyParams,Algorithm algo,ExtraInfo exInfo)305 static int32_t GenerateKeyValue(int32_t osAccountId,
306     Credential *credential, KeyParams keyParams, Algorithm algo, ExtraInfo exInfo)
307 {
308     Uint8Buff keyAlias = { keyParams.keyBuff.key, keyParams.keyBuff.keyLen };
309     if (GetLoaderInstance()->checkKeyExist(&keyAlias, false, osAccountId) != HAL_ERR_KEY_NOT_EXIST) {
310         LOGI("The keyValue corresponding to the credId already exists in HUKS, no need to generate.");
311         return IS_SUCCESS;
312     }
313     LOGI("The keyValue corresponding to the credId does not exist in HUKS, generate keyValue.");
314     uint32_t keyLen = (credential->algorithmType == ALGO_TYPE_AES_128) ? AES_128_KEY_LEN : ALGO_KEY_LEN;
315     int32_t ret = GetLoaderInstance()->generateKeyPairWithStorage(&keyParams, keyLen, algo,
316         KEY_PURPOSE_KEY_AGREE, &exInfo);
317     if (ret == HAL_ERR_HUKS) {
318         LOGE("Huks generateKeyPair failed!");
319         return IS_ERR_HUKS_GENERATE_KEY_FAILED;
320     }
321     if (ret != IS_SUCCESS) {
322         LOGE("Failed to generate key pair!");
323         return ret;
324     }
325     LOGI("Generate key pair success!");
326     return IS_SUCCESS;
327 }
328 
ImportKeyValue(KeyParams keyParams,Uint8Buff * keyValue,Algorithm algo,ExtraInfo exInfo,uint8_t subject)329 static int32_t ImportKeyValue(KeyParams keyParams,
330     Uint8Buff *keyValue, Algorithm algo, ExtraInfo exInfo, uint8_t subject)
331 {
332     int32_t ret;
333 
334     if (algo == AES) {
335         KeyPurpose keyPurpose = subject == SUBJECT_MASTER_CONTROLLER ? KEY_PURPOSE_MAC : KEY_PURPOSE_DERIVE;
336         ret = GetLoaderInstance()->importSymmetricKey(&keyParams, keyValue, keyPurpose, &exInfo);
337     } else {
338         ret = GetLoaderInstance()->importPublicKey(&keyParams, keyValue, algo, &exInfo);
339     }
340 
341     if (ret == HAL_ERR_HUKS) {
342         LOGE("Huks import key failed!");
343         return IS_ERR_HUKS_IMPORT_KEY_FAILED;
344     }
345     if (ret != IS_SUCCESS) {
346         LOGE("Failed to import key pair!");
347         return ret;
348     }
349     LOGI("Import key pair success!");
350     return IS_SUCCESS;
351 }
352 
AddKeyValueToHuks(int32_t osAccountId,Uint8Buff * credIdByte,Credential * credential,uint8_t method,Uint8Buff * keyValue)353 int32_t AddKeyValueToHuks(int32_t osAccountId, Uint8Buff *credIdByte, Credential *credential, uint8_t method,
354     Uint8Buff *keyValue)
355 {
356     if (credential->credType == ACCOUNT_SHARED && keyValue->val == NULL) {
357         return IS_SUCCESS;
358     }
359     if (credential->ownerUid == DEV_AUTH_UID) {
360         return IS_SUCCESS;
361     }
362     KeyParams keyParams = { { credIdByte->val, credIdByte->length, true }, false, osAccountId };
363     int32_t authId = 0;
364     Uint8Buff authIdBuff = { (uint8_t *)&authId, sizeof(int32_t) };
365     ExtraInfo exInfo = { authIdBuff, DEFAULT_EX_INFO_VAL, DEFAULT_EX_INFO_VAL };
366     Algorithm algo = GetAlgoFromCred(credential->algorithmType);
367     switch (method) {
368         case METHOD_GENERATE:
369             return GenerateKeyValue(osAccountId, credential, keyParams, algo, exInfo);
370         case METHOD_IMPORT:
371             return ImportKeyValue(keyParams, keyValue, algo, exInfo, credential->subject);
372         default:
373             return IS_ERR_INVALID_PARAMS;
374     }
375 }
376 
GetValidKeyAlias(int32_t osAccountId,const char * credId,Uint8Buff * credIdHashBuff)377 int32_t GetValidKeyAlias(int32_t osAccountId, const char *credId, Uint8Buff *credIdHashBuff)
378 {
379     uint32_t credIdByteLen = HcStrlen(credId) / BYTE_TO_HEX_OPER_LENGTH;
380     Uint8Buff returnCredIdByte = { NULL, credIdByteLen };
381     returnCredIdByte.val = (uint8_t *)HcMalloc(credIdByteLen, 0);
382     if (returnCredIdByte.val == NULL) {
383         LOGE("Failed to malloc credIdByteLen");
384         return IS_ERR_ALLOC_MEMORY;
385     }
386     int32_t ret = HexStringToByte(credId, returnCredIdByte.val, returnCredIdByte.length);
387     if (ret != IS_SUCCESS) {
388         LOGE("Failed to convert credId to byte, invalid credId, ret = %" LOG_PUB "d", ret);
389         HcFree(returnCredIdByte.val);
390         return IS_ERR_INVALID_HEX_STRING;
391     }
392 
393     ret = GetLoaderInstance()->checkKeyExist(&returnCredIdByte, false, osAccountId);
394     if (ret != IS_SUCCESS) {
395         HcFree(returnCredIdByte.val);
396         return ret;
397     }
398     credIdHashBuff->val = returnCredIdByte.val;
399     credIdHashBuff->length = credIdByteLen;
400     return IS_SUCCESS;
401 }
402 
AddCredAndSaveDb(int32_t osAccountId,Credential * credential)403 int32_t AddCredAndSaveDb(int32_t osAccountId, Credential *credential)
404 {
405     int32_t ret = AddCredToDb(osAccountId, credential);
406     if (ret != IS_SUCCESS) {
407         LOGE("Failed to add credential to database");
408         return ret;
409     }
410     ret = SaveOsAccountCredDb(osAccountId);
411     if (ret != IS_SUCCESS) {
412         LOGE("Failed to save CredDb, ret: %" LOG_PUB "d", ret);
413         return ret;
414     }
415     return IS_SUCCESS;
416 }
417 
418 
IsValueInArray(uint8_t value,uint8_t * array,uint32_t length)419 static bool IsValueInArray(uint8_t value, uint8_t *array, uint32_t length)
420 {
421     for (uint32_t i = 0; i < length; i++) {
422         if (array[i] == value) {
423             return true;
424         }
425     }
426     return false;
427 }
428 
SetVectorFromList(StringVector * dataVector,CJson * dataList)429 static int32_t SetVectorFromList(StringVector *dataVector, CJson *dataList)
430 {
431     int32_t dataListNum = GetItemNum(dataList);
432     for (int32_t i = 0; i < dataListNum; i++) {
433         CJson *item = GetItemFromArray(dataList, i);
434         if (item == NULL) {
435             LOGE("item is null.");
436             return IS_ERR_JSON_GET;
437         }
438         const char *data = GetStringValue(item);
439         if (data == NULL) {
440             LOGE("the data of list is null.");
441             return IS_ERR_JSON_GET;
442         }
443         HcString strData = CreateString();
444         if (!StringSetPointer(&strData, data)) {
445             LOGE("Failed to set strData!");
446             DeleteString(&strData);
447             return IS_ERR_MEMORY_COPY;
448         }
449         if (dataVector->pushBackT(dataVector, strData) == NULL) {
450             LOGE("Failed to push strData to vector!");
451             DeleteString(&strData);
452             return IS_ERR_MEMORY_COPY;
453         }
454     }
455     return IS_SUCCESS;
456 }
457 
SetMethodFromJson(CJson * json,uint8_t * method)458 static int32_t SetMethodFromJson(CJson *json, uint8_t *method)
459 {
460     int32_t methodInt32 = DEFAULT_VAL;
461     if (GetIntFromJson(json, FIELD_METHOD, &methodInt32) != IS_SUCCESS) {
462         LOGE("Failed to get method from credReqParam");
463         return IS_ERR_JSON_GET;
464     }
465     *method = (uint8_t)methodInt32;
466 
467     uint8_t methodRange[] = { METHOD_GENERATE, METHOD_IMPORT };
468     uint32_t length = sizeof(methodRange) / sizeof(methodRange[0]);
469     if (!IsValueInArray(*method, methodRange, length)) {
470         LOGE("method is invalid.");
471         return IS_ERR_INVALID_PARAMS;
472     }
473     return IS_SUCCESS;
474 }
475 
SetCredType(Credential * credential,CJson * json)476 static int32_t SetCredType(Credential *credential, CJson *json)
477 {
478     if (GetUint8FromJson(json, FIELD_CRED_TYPE, &credential->credType) != IS_SUCCESS) {
479         LOGE("Failed to get credential type from credReqParam");
480         return IS_ERR_JSON_GET;
481     }
482 
483     uint8_t credTypeRange[] = { ACCOUNT_RELATED, ACCOUNT_UNRELATED, ACCOUNT_SHARED };
484     uint32_t length = sizeof(credTypeRange) / sizeof(credTypeRange[0]);
485     if (!IsValueInArray(credential->credType, credTypeRange, length)) {
486         LOGE("credential type is invalid.");
487         return IS_ERR_INVALID_PARAMS;
488     }
489     return IS_SUCCESS;
490 }
491 
SetKeyFormat(Credential * credential,CJson * json,uint8_t method)492 static int32_t SetKeyFormat(Credential *credential, CJson *json, uint8_t method)
493 {
494     if (GetUint8FromJson(json, FIELD_KEY_FORMAT, &credential->keyFormat) != IS_SUCCESS) {
495         LOGE("Failed to get key format from credReqParam");
496         return IS_ERR_JSON_GET;
497     }
498     uint8_t keyFormatRange[] = { SYMMETRIC_KEY, ASYMMETRIC_PUB_KEY, ASYMMETRIC_KEY, X509_CERT};
499     uint32_t length = sizeof(keyFormatRange) / sizeof(keyFormatRange[0]);
500     if (!IsValueInArray(credential->keyFormat, keyFormatRange, length)) {
501         LOGE("key format is invalid.");
502         return IS_ERR_INVALID_PARAMS;
503     }
504     if (credential->keyFormat == SYMMETRIC_KEY && method != METHOD_IMPORT) {
505         LOGE("Symmetric key is only supported for import");
506         return IS_ERR_INVALID_PARAMS;
507     }
508     if (credential->keyFormat == ASYMMETRIC_PUB_KEY && method != METHOD_IMPORT) {
509         LOGE("Asymmetric public key is only supported for import");
510         return IS_ERR_INVALID_PARAMS;
511     }
512     if (credential->keyFormat == ASYMMETRIC_KEY && method != METHOD_GENERATE) {
513         LOGE("Asymmetric key is only supported for generate");
514         return IS_ERR_INVALID_PARAMS;
515     }
516     return IS_SUCCESS;
517 }
518 
SetAuthorizedScope(Credential * credential,CJson * json)519 static int32_t SetAuthorizedScope(Credential *credential, CJson *json)
520 {
521     if (GetUint8FromJson(json, FIELD_AUTHORIZED_SCOPE, &credential->authorizedScope) != IS_SUCCESS) {
522         LOGE("Failed to get authorizedScope from credReqParam");
523         return IS_ERR_JSON_GET;
524     }
525     uint8_t scopeRange[] = { SCOPE_DEVICE, SCOPE_USER, SCOPE_APP };
526     uint32_t length = sizeof(scopeRange) / sizeof(scopeRange[0]);
527     if (!IsValueInArray(credential->authorizedScope, scopeRange, length)) {
528         LOGE("Invalid authorizedScope");
529         return IS_ERR_INVALID_PARAMS;
530     }
531     return IS_SUCCESS;
532 }
533 
SetAlgorithmType(Credential * credential,CJson * json)534 static int32_t SetAlgorithmType(Credential *credential, CJson *json)
535 {
536     if (GetUint8FromJson(json, FIELD_ALGORITHM_TYPE, &credential->algorithmType) != IS_SUCCESS) {
537         LOGE("Failed to get algorithm type from credReqParam");
538         return IS_ERR_JSON_GET;
539     }
540     uint8_t algorithmTypeRange[] = { ALGO_TYPE_AES_256, ALGO_TYPE_P256, ALGO_TYPE_ED25519 };
541     uint32_t length = sizeof(algorithmTypeRange) / sizeof(algorithmTypeRange[0]);
542     if (!IsValueInArray(credential->algorithmType, algorithmTypeRange, length)) {
543         LOGE("Invalid algorithm type");
544         return IS_ERR_INVALID_PARAMS;
545     }
546     return IS_SUCCESS;
547 }
548 
SetSubject(Credential * credential,CJson * json)549 static int32_t SetSubject(Credential *credential, CJson *json)
550 {
551     if (GetUint8FromJson(json, FIELD_SUBJECT, &credential->subject) != IS_SUCCESS) {
552         LOGE("Failed to get subject from credReqParam");
553         return IS_ERR_JSON_GET;
554     }
555     uint8_t subjectRange[] = { SUBJECT_MASTER_CONTROLLER, SUBJECT_ACCESSORY_DEVICE };
556     uint32_t length = sizeof(subjectRange) / sizeof(subjectRange[0]);
557     if (!IsValueInArray(credential->subject, subjectRange, length)) {
558         LOGE("Invalid subject");
559         return IS_ERR_INVALID_PARAMS;
560     }
561     return IS_SUCCESS;
562 }
563 
SetIssuer(Credential * credential,CJson * json)564 static int32_t SetIssuer(Credential *credential, CJson *json)
565 {
566     if (GetUint8FromJson(json, FIELD_ISSUER, &credential->issuer) != IS_SUCCESS) {
567         LOGW("Failed to get issuer from credReqParam");
568     }
569     if (credential->credType == ACCOUNT_UNRELATED) {
570         return IS_SUCCESS;
571     }
572     uint8_t issuerRange[] = { SYSTEM_ACCOUNT, APP_ACCOUNT, DOMANIN_ACCOUNT };
573     uint32_t length = sizeof(issuerRange) / sizeof(issuerRange[0]);
574     if (credential->issuer == DEFAULT_VAL || !IsValueInArray(credential->issuer, issuerRange, length)) {
575         LOGE("Invalid issuer");
576         return IS_ERR_INVALID_PARAMS;
577     }
578     return IS_SUCCESS;
579 }
580 
SetDeviceId(Credential * credential,CJson * json)581 static int32_t SetDeviceId(Credential *credential, CJson *json)
582 {
583     const char *deviceId = GetStringFromJson(json, FIELD_DEVICE_ID);
584     if (deviceId == NULL || IsStrEqual(deviceId, "")) {
585         LOGE("Failed to get deviceId from credReqParam");
586         return IS_ERR_JSON_GET;
587     }
588     if (!StringSetPointer(&credential->deviceId, deviceId)) {
589         LOGE("Failed to set deviceId");
590         return IS_ERR_MEMORY_COPY;
591     }
592     return IS_SUCCESS;
593 }
594 
SetCredOwner(Credential * credential,CJson * json)595 static int32_t SetCredOwner(Credential *credential, CJson *json)
596 {
597     const char *credOwner = GetStringFromJson(json, FIELD_CRED_OWNER);
598     if (credOwner == NULL || IsStrEqual(credOwner, "")) {
599         LOGE("Failed to get credOwner from credReqParam");
600         return IS_ERR_JSON_GET;
601     }
602     if (!StringSetPointer(&credential->credOwner, credOwner)) {
603         LOGE("Failed to set credOwner");
604         return IS_ERR_MEMORY_COPY;
605     }
606     return IS_SUCCESS;
607 }
608 
SetProofType(Credential * credential,CJson * json)609 static int32_t SetProofType(Credential *credential, CJson *json)
610 {
611     if (GetUint8FromJson(json, FIELD_PROOF_TYPE, &credential->proofType) != IS_SUCCESS) {
612         LOGE("Failed to get proofType from credReqParam");
613         return IS_ERR_JSON_GET;
614     }
615     uint8_t proofTypeRange[] = { PROOF_TYPE_PSK, PROOF_TYPE_PKI };
616     uint32_t length = sizeof(proofTypeRange) / sizeof(proofTypeRange[0]);
617     if (!IsValueInArray(credential->proofType, proofTypeRange, length)) {
618         LOGE("Invalid proofType");
619         return IS_ERR_INVALID_PARAMS;
620     }
621     return IS_SUCCESS;
622 }
623 
SetUserId(Credential * credential,CJson * json)624 static int32_t SetUserId(Credential *credential, CJson *json)
625 {
626     const char *userId = GetStringFromJson(json, FIELD_USER_ID);
627     if (credential->credType == ACCOUNT_RELATED && (userId == NULL || IsStrEqual(userId, ""))) {
628         LOGE("Invalid params, when credType is account, userId is NULL");
629         return IS_ERR_INVALID_PARAMS;
630     }
631     if (userId == NULL) {
632         return IS_SUCCESS;
633     }
634     if (!StringSetPointer(&credential->userId, userId)) {
635         LOGW("Failed to set userId");
636     }
637 
638     return IS_SUCCESS;
639 }
640 
SetKeyValueFromJson(CJson * json,Credential * credential,uint8_t method,Uint8Buff * keyValue)641 static int32_t SetKeyValueFromJson(CJson *json, Credential *credential, uint8_t method, Uint8Buff *keyValue)
642 {
643     const char *keyValueStr = GetStringFromJson(json, FIELD_KEY_VALUE);
644     if (credential->credType == ACCOUNT_SHARED && keyValueStr == NULL) {
645         return IS_SUCCESS;
646     }
647     if (method == METHOD_GENERATE) {
648         if (HcStrlen(keyValueStr) > 0) {
649             LOGE("Invalid params, when method is generate, keyValue should not be passed in");
650             return IS_ERR_KEYVALUE_METHOD_CONFLICT;
651         }
652         return IS_SUCCESS;
653     }
654     if (keyValueStr == NULL || HcStrlen(keyValueStr) <= 0) {
655         LOGE("Invalid params, when method is imoprt, keyValue is NULL");
656         return IS_ERR_INVALID_PARAMS;
657     }
658     uint32_t keyValueLen = HcStrlen(keyValueStr) / BYTE_TO_HEX_OPER_LENGTH;
659     keyValue->length = keyValueLen;
660     uint8_t *returnKeyVal = (uint8_t *)HcMalloc(keyValueLen, 0);
661     if (returnKeyVal == NULL) {
662         LOGE("Failed to malloc memory for keyValue");
663         return IS_ERR_ALLOC_MEMORY;
664     }
665     if (GetByteFromJson(json, FIELD_KEY_VALUE, returnKeyVal, keyValue->length) != IS_SUCCESS) {
666         LOGE("set keyValue fail.");
667         HcFree(returnKeyVal);
668         return IS_ERR_JSON_GET;
669     }
670     keyValue->val = returnKeyVal;
671     return IS_SUCCESS;
672 }
673 
SetPeerUserSpaceId(Credential * credential,CJson * json,uint8_t method)674 static int32_t SetPeerUserSpaceId(Credential *credential, CJson *json, uint8_t method)
675 {
676     const char *peerUserSpaceId = GetStringFromJson(json, FIELD_PEER_USER_SPACE_ID);
677     if (credential->credType == ACCOUNT_UNRELATED && method == METHOD_IMPORT &&
678         (peerUserSpaceId == NULL || IsStrEqual(peerUserSpaceId, ""))) {
679         LOGE("Invalid params, when credType is not account and method is import, peer osaccount id is NULL");
680         return IS_ERR_INVALID_PARAMS;
681     }
682     if (peerUserSpaceId == NULL) {
683         return IS_SUCCESS;
684     }
685     if (!StringSetPointer(&credential->peerUserSpaceId, peerUserSpaceId)) {
686         LOGW("Failed to set peerUserSpaceId");
687     }
688     return IS_SUCCESS;
689 }
690 
SetAppList(Credential * credential,CJson * json)691 static int32_t SetAppList(Credential *credential, CJson *json)
692 {
693     CJson *appList = GetObjFromJson(json, FIELD_AUTHORIZED_APP_LIST);
694     if (appList == NULL) {
695         if (credential->authorizedScope == SCOPE_APP) {
696             LOGE("when authorizedScope is APP, authorizedAppList is required");
697             return IS_ERR_INVALID_PARAMS;
698         }
699         return IS_SUCCESS;
700     }
701 
702     int32_t ret = SetVectorFromList(&credential->authorizedAppList, appList);
703     if (ret != IS_SUCCESS) {
704         LOGE("Failed to set authorized app list from credReqParam");
705         return ret;
706     }
707     return IS_SUCCESS;
708 }
709 
SetExtendInfo(Credential * credential,CJson * json)710 static int32_t SetExtendInfo(Credential *credential, CJson *json)
711 {
712     const char *extendInfo = GetStringFromJson(json, FIELD_EXTEND_INFO);
713     if (extendInfo == NULL || IsStrEqual(extendInfo, "")) {
714         LOGW("Failed to get extendInfo from credReqParam");
715     }
716     if (extendInfo == NULL) {
717         LOGW("Failed to get extendInfo from credReqParam");
718         return IS_SUCCESS;
719     }
720     if (!StringSetPointer(&credential->extendInfo, extendInfo)) {
721         LOGW("Failed to set extendInfo!");
722     }
723     return IS_SUCCESS;
724 }
725 
SetCredIdFromJson(Credential * credential,CJson * json)726 static int32_t SetCredIdFromJson(Credential *credential, CJson *json)
727 {
728     const char *credIdStr = GetStringFromJson(json, FIELD_CRED_ID);
729     if (credIdStr == NULL || HcStrlen(credIdStr) == 0) {
730         LOGI("No imported credId in credReqParam, credId will be generated by IS.");
731         return IS_SUCCESS;
732     }
733     if (!StringSetPointer(&credential->credId, credIdStr)) {
734         LOGE("Failed to set credId");
735         return IS_ERR_ALLOC_MEMORY;
736     }
737     return IS_SUCCESS;
738 }
739 
SetRequiredField(Credential * credential,CJson * json,uint8_t * method)740 static int32_t SetRequiredField(Credential *credential, CJson *json, uint8_t *method)
741 {
742     int32_t ret = SetMethodFromJson(json, method);
743     if (ret != IS_SUCCESS) {
744         return ret;
745     }
746 
747     ret = SetCredType(credential, json);
748     if (ret != IS_SUCCESS) {
749         return ret;
750     }
751 
752     ret = SetKeyFormat(credential, json, *method);
753     if (ret != IS_SUCCESS) {
754         return ret;
755     }
756 
757     ret = SetAuthorizedScope(credential, json);
758     if (ret != IS_SUCCESS) {
759         return ret;
760     }
761 
762     ret = SetAlgorithmType(credential, json);
763     if (ret != IS_SUCCESS) {
764         return ret;
765     }
766 
767     ret = SetSubject(credential, json);
768     if (ret != IS_SUCCESS) {
769         return ret;
770     }
771 
772     ret = SetDeviceId(credential, json);
773     if (ret != IS_SUCCESS) {
774         return ret;
775     }
776 
777     ret = SetCredOwner(credential, json);
778     if (ret != IS_SUCCESS) {
779         return ret;
780     }
781 
782     ret = SetProofType(credential, json);
783     if (ret != IS_SUCCESS) {
784         return ret;
785     }
786     credential->ownerUid = GetCallingUid();
787     LOGI("UID: %" LOG_PUB "d", credential->ownerUid);
788     return IS_SUCCESS;
789 }
790 
SetSpecialRequiredField(Credential * credential,CJson * json,uint8_t * method,Uint8Buff * keyValue)791 static int32_t SetSpecialRequiredField(Credential *credential, CJson *json, uint8_t *method, Uint8Buff *keyValue)
792 {
793     int32_t ret = SetUserId(credential, json);
794     if (ret != IS_SUCCESS) {
795         return ret;
796     }
797 
798     ret = SetIssuer(credential, json);
799     if (ret != IS_SUCCESS) {
800         return ret;
801     }
802 
803     ret = SetKeyValueFromJson(json, credential, *method, keyValue);
804     if (ret != IS_SUCCESS) {
805         return ret;
806     }
807 
808     ret = SetPeerUserSpaceId(credential, json, *method);
809     if (ret != IS_SUCCESS) {
810         HcFree(keyValue->val);
811         return ret;
812     }
813 
814     ret = SetAppList(credential, json);
815     if (ret != IS_SUCCESS) {
816         HcFree(keyValue->val);
817         return ret;
818     }
819     return IS_SUCCESS;
820 }
821 
SetOptionalField(Credential * credential,CJson * json)822 static int32_t SetOptionalField(Credential *credential, CJson *json)
823 {
824     int32_t ret = SetExtendInfo(credential, json);
825     if (ret != IS_SUCCESS) {
826         return ret;
827     }
828 
829     return SetCredIdFromJson(credential, json);
830 }
831 
CheckAndSetCredInfo(int32_t osAccountId,Credential * credential,CJson * json,uint8_t * method,Uint8Buff * keyValue)832 int32_t CheckAndSetCredInfo(int32_t osAccountId,
833     Credential *credential, CJson *json, uint8_t *method, Uint8Buff *keyValue)
834 {
835     int32_t ret = SetRequiredField(credential, json, method);
836     if (ret != IS_SUCCESS) {
837         return ret;
838     }
839 
840     ret = SetSpecialRequiredField(credential, json, method, keyValue);
841     if (ret != IS_SUCCESS) {
842         return ret;
843     }
844 
845     ret = SetOptionalField(credential, json);
846     if (ret != IS_SUCCESS) {
847         HcFree(keyValue->val);
848         return ret;
849     }
850 
851     ret = CheckOutMaxCredSize(osAccountId, StringGet(&credential->credOwner));
852     if (ret != IS_SUCCESS) {
853         HcFree(keyValue->val);
854     }
855     return ret;
856 }
857 
SetQueryParamsFromJson(QueryCredentialParams * queryParams,CJson * json)858 int32_t SetQueryParamsFromJson(QueryCredentialParams *queryParams, CJson *json)
859 {
860     queryParams->credId = GetStringFromJson(json, FIELD_CRED_ID);
861     queryParams->deviceId = GetStringFromJson(json, FIELD_DEVICE_ID);
862     queryParams->peerUserSpaceId = GetStringFromJson(json, FIELD_PEER_USER_SPACE_ID);
863     queryParams->userId = GetStringFromJson(json, FIELD_USER_ID);
864     queryParams->credOwner = GetStringFromJson(json, FIELD_CRED_OWNER);
865 
866     if (GetUint8FromJson(json, FIELD_SUBJECT, &queryParams->subject) == IS_SUCCESS) {
867         LOGI("Set query params: subject");
868     }
869     if (GetUint8FromJson(json, FIELD_ISSUER, &queryParams->issuer) == IS_SUCCESS) {
870         LOGI("Set query params: issuer");
871     }
872     if (GetUint8FromJson(json, FIELD_CRED_TYPE, &queryParams->credType) == IS_SUCCESS) {
873         LOGI("Set query params: credType");
874     }
875     if (GetUint8FromJson(json, FIELD_KEY_FORMAT, &queryParams->keyFormat) == IS_SUCCESS) {
876         LOGI("Set query params: keyFormat");
877     }
878     if (GetUint8FromJson(json, FIELD_ALGORITHM_TYPE, &queryParams->algorithmType) == IS_SUCCESS) {
879         LOGI("Set query params: algorithmType");
880     }
881     if (GetUint8FromJson(json, FIELD_PROOF_TYPE, &queryParams->proofType) == IS_SUCCESS) {
882         LOGI("Set query params: proofType");
883     }
884     if (GetUint8FromJson(json, FIELD_AUTHORIZED_SCOPE, &queryParams->authorizedScope) == IS_SUCCESS) {
885         LOGI("Set query params: authorizedScope");
886     }
887     return IS_SUCCESS;
888 }
889 
IsOriginalStrHashMatch(const char * originalStr,const char * subHashedStr)890 static int32_t IsOriginalStrHashMatch(const char *originalStr, const char *subHashedStr)
891 {
892     Uint8Buff originalStrBuffer = { (uint8_t *)originalStr, (uint32_t)HcStrlen(originalStr) };
893     uint8_t hashedStrBytes[SHA256_LEN] = { 0 };
894     Uint8Buff hashedStrBuffer = { hashedStrBytes, sizeof(hashedStrBytes) };
895     int32_t result = GetLoaderInstance()->sha256(&originalStrBuffer, &hashedStrBuffer);
896     if (result != IS_SUCCESS) {
897         LOGE("sha256 failed, ret:%" LOG_PUB "d", result);
898         return result;
899     }
900     uint32_t hashedStrHexLength = SHA256_LEN * BYTE_TO_HEX_OPER_LENGTH + 1;
901     char *hashedStrHex = (char *)HcMalloc(hashedStrHexLength, 0);
902     if (hashedStrHex == NULL) {
903         LOGE("malloc hashedStrHex string failed");
904         return IS_ERR_ALLOC_MEMORY;
905     }
906     result = ByteToHexString(hashedStrBytes, SHA256_LEN, hashedStrHex, hashedStrHexLength);
907     if (result != IS_SUCCESS) {
908         LOGE("Byte to hexString failed, ret:%" LOG_PUB "d", result);
909         HcFree(hashedStrHex);
910         return result;
911     }
912     char *upperSubHashedStr = NULL;
913     result = ToUpperCase(subHashedStr, &upperSubHashedStr);
914     if (result != IS_SUCCESS) {
915         LOGE("Failed to convert the input sub hashed string to upper case!");
916         HcFree(hashedStrHex);
917         return result;
918     }
919     if (strstr((const char *)hashedStrHex, upperSubHashedStr) != NULL) {
920         LOGI("Original string hash is match!");
921         HcFree(hashedStrHex);
922         HcFree(upperSubHashedStr);
923         return IS_SUCCESS;
924     }
925     HcFree(hashedStrHex);
926     HcFree(upperSubHashedStr);
927     return IS_ERROR;
928 }
929 
IsCredHashMatch(Credential * credential,CJson * reqJson)930 bool IsCredHashMatch(Credential *credential, CJson *reqJson)
931 {
932     const char *deviceIdHash = GetStringFromJson(reqJson, FIELD_DEVICE_ID_HASH);
933     if (deviceIdHash != NULL &&
934         IsOriginalStrHashMatch(StringGet(&credential->deviceId), deviceIdHash) != IS_SUCCESS) {
935         return false;
936     }
937 
938     const char *userIdHash = GetStringFromJson(reqJson, FIELD_USER_ID_HASH);
939     if (userIdHash != NULL &&
940         IsOriginalStrHashMatch(StringGet(&credential->userId), userIdHash) != IS_SUCCESS) {
941         return false;
942     }
943 
944     return true;
945 }
946 
CheckCredKeyExist(int32_t osAccountId,const Credential * credential,const char * credId)947 static int32_t CheckCredKeyExist(int32_t osAccountId, const Credential *credential, const char *credId)
948 {
949     // ACCOUNT_SHARED type dose not need check key
950     if (credential->credType == ACCOUNT_SHARED || credential->ownerUid == DEV_AUTH_UID) {
951         return HC_SUCCESS;
952     }
953     uint32_t credIdByteLen = HcStrlen(credId) / BYTE_TO_HEX_OPER_LENGTH;
954     Uint8Buff credIdByte = { NULL, credIdByteLen };
955     credIdByte.val = (uint8_t *)HcMalloc(credIdByteLen, 0);
956     if (credIdByte.val == NULL) {
957         LOGE("Failed to malloc credIdByteLen");
958         return IS_ERR_ALLOC_MEMORY;
959     }
960     int32_t ret = HexStringToByte(credId, credIdByte.val, credIdByte.length);
961     if (ret != IS_SUCCESS) {
962         LOGE("Failed to convert credId to byte, invalid credId, ret = %" LOG_PUB "d", ret);
963         HcFree(credIdByte.val);
964         return IS_ERR_INVALID_HEX_STRING;
965     }
966     ret = GetLoaderInstance()->checkKeyExist(&credIdByte, false, osAccountId);
967     HcFree(credIdByte.val);
968     switch (ret) {
969         // delete invaild credId
970         case HAL_ERR_KEY_NOT_EXIST:
971             LOGE("Huks key not exist!");
972             DelCredById(osAccountId, credId);
973             break;
974         case HAL_ERR_HUKS:
975             LOGE("Failed to check key exist in huks");
976             break;
977         case IS_SUCCESS:
978             break;
979         default:
980             LOGE("CheckKeyExist failed");
981             break;
982     }
983     return ret;
984 }
985 
GetCredIdsFromCredVec(int32_t osAccountId,CJson * reqJson,CredentialVec * credentialVec,CJson * credIdJson)986 int32_t GetCredIdsFromCredVec(int32_t osAccountId, CJson *reqJson, CredentialVec *credentialVec, CJson *credIdJson)
987 {
988     uint32_t index;
989     int32_t ret;
990     Credential **ptr;
991     FOR_EACH_HC_VECTOR(*credentialVec, index, ptr) {
992         if (*ptr == NULL) {
993             continue;
994         }
995         Credential *credential = (Credential *)(*ptr);
996         const char *credId = StringGet(&credential->credId);
997         if (CheckCredKeyExist(osAccountId, credential, credId) != IS_SUCCESS) {
998             LOGE("CredKey not Exist!");
999             continue;
1000         }
1001         if (!IsCredHashMatch(credential, reqJson)) {
1002             continue;
1003         }
1004 
1005         ret = AddStringToArray(credIdJson, credId);
1006         if (ret != IS_SUCCESS) {
1007             LOGE("Failed to add credId to json");
1008             return IS_ERR_JSON_ADD;
1009         }
1010         PRINT_SENSITIVE_DATA("credId", credId);
1011     }
1012     LOGI("credIdList size is: %" LOG_PUB "d", GetItemNum(credIdJson));
1013     return IS_SUCCESS;
1014 }
1015 
UpdateExtendInfo(Credential * credential,const char * extendInfo)1016 static int32_t UpdateExtendInfo(Credential *credential, const char *extendInfo)
1017 {
1018     if (!StringSetPointer(&credential->extendInfo, extendInfo)) {
1019         LOGE("Failed to update extendInfo");
1020         return IS_ERR_MEMORY_COPY;
1021     }
1022     return IS_SUCCESS;
1023 }
1024 
UpdateAppList(Credential * credential,CJson * appList)1025 static int32_t UpdateAppList(Credential *credential, CJson *appList)
1026 {
1027     DestroyStrVector(&credential->authorizedAppList);
1028     credential->authorizedAppList = CreateStrVector();
1029     int32_t ret = SetVectorFromList(&credential->authorizedAppList, appList);
1030     if (ret != IS_SUCCESS) {
1031         LOGE("Failed to update authorizedAppList");
1032         return ret;
1033     }
1034     return IS_SUCCESS;
1035 }
1036 
UpdateInfoFromJson(Credential * credential,CJson * json)1037 int32_t UpdateInfoFromJson(Credential *credential, CJson *json)
1038 {
1039     const char *extendInfo = GetStringFromJson(json, FIELD_EXTEND_INFO);
1040     CJson *appList = GetObjFromJson(json, FIELD_AUTHORIZED_APP_LIST);
1041 
1042     if (extendInfo == NULL && appList == NULL) {
1043         LOGE("Failed to set update info: no valid field");
1044         return IS_ERR_INVALID_PARAMS;
1045     }
1046 
1047     int32_t ret;
1048 
1049     if (extendInfo != NULL) {
1050         ret = UpdateExtendInfo(credential, extendInfo);
1051         if (ret != IS_SUCCESS) {
1052             return ret;
1053         }
1054     }
1055 
1056     if (appList != NULL) {
1057         ret = UpdateAppList(credential, appList);
1058     }
1059 
1060     return ret;
1061 }
1062 
DelCredById(int32_t osAccountId,const char * credId)1063 int32_t DelCredById(int32_t osAccountId, const char *credId)
1064 {
1065     QueryCredentialParams delParams = InitQueryCredentialParams();
1066     delParams.credId = credId;
1067     int32_t ret = DelCredential(osAccountId, &delParams);
1068     if (ret != IS_SUCCESS) {
1069         LOGE("Failed to delete credential, ret: %" LOG_PUB "d", ret);
1070         return ret;
1071     }
1072     ret = SaveOsAccountCredDb(osAccountId);
1073     if (ret != IS_SUCCESS) {
1074         LOGE("Failed to save CredDb, ret: %" LOG_PUB "d", ret);
1075         return ret;
1076     }
1077     return IS_SUCCESS;
1078 }
1079 
AddKeyValueToReturn(Uint8Buff keyValue,char ** returnData)1080 int32_t AddKeyValueToReturn(Uint8Buff keyValue, char **returnData)
1081 {
1082     CJson *keyValueJson = CreateJson();
1083     if (keyValueJson == NULL) {
1084         LOGE("Failed to create keyValueJson");
1085         return IS_ERR_JSON_CREATE;
1086     }
1087     int32_t ret = AddByteToJson(keyValueJson, FIELD_KEY_VALUE, keyValue.val, keyValue.length);
1088     if (ret != IS_SUCCESS) {
1089         LOGE("Failed to add key value to json");
1090         FreeJson(keyValueJson);
1091         return IS_ERR_JSON_ADD;
1092     }
1093     *returnData = PackJsonToString(keyValueJson);
1094     FreeJson(keyValueJson);
1095     if (*returnData == NULL) {
1096         LOGE("Failed to pack key value json to string");
1097         return IS_ERR_PACKAGE_JSON_TO_STRING_FAIL;
1098     }
1099     return IS_SUCCESS;
1100 }
1101 
GenerateReturnEmptyArrayStr(char ** returnVec)1102 int32_t GenerateReturnEmptyArrayStr(char **returnVec)
1103 {
1104     CJson *json = CreateJsonArray();
1105     if (json == NULL) {
1106         LOGE("Failed to allocate json memory!");
1107         return IS_ERR_JSON_CREATE;
1108     }
1109     *returnVec = PackJsonToString(json);
1110     FreeJson(json);
1111     if (*returnVec == NULL) {
1112         LOGE("Failed to convert json to string!");
1113         return IS_ERR_PACKAGE_JSON_TO_STRING_FAIL;
1114     }
1115     return IS_SUCCESS;
1116 }
1117 
CheckOwnerUidPermission(Credential * credential)1118 int32_t CheckOwnerUidPermission(Credential *credential)
1119 {
1120     int32_t currentUid = GetCallingUid();
1121     if (currentUid != credential->ownerUid) {
1122         LOGE("currentUid is not the same as the ownerUid of the credential");
1123         return IS_ERR_OWNER_UID;
1124     }
1125     return IS_SUCCESS;
1126 }
1127 
GenerateCredKeyAlias(const char * credId,const char * deviceId,Uint8Buff * alias)1128 int32_t GenerateCredKeyAlias(const char *credId, const char *deviceId, Uint8Buff *alias)
1129 {
1130     if ((credId == NULL) || (deviceId == NULL) || (alias == NULL)) {
1131         LOGE("Invalid input params");
1132         return IS_ERR_NULL_PTR;
1133     }
1134     uint32_t credIdLen = HcStrlen(credId);
1135     uint32_t deviceIdLen = HcStrlen(deviceId);
1136     uint32_t aliasStrLen = credIdLen + deviceIdLen + 1;
1137     uint8_t *aliasStr = (uint8_t *)HcMalloc(aliasStrLen, 0);
1138     if (aliasStr == NULL) {
1139         LOGE("Failed to malloc for key aliasStr.");
1140         return IS_ERR_ALLOC_MEMORY;
1141     }
1142     Uint8Buff aliasBuff = {
1143         aliasStr,
1144         aliasStrLen
1145     };
1146     if (memcpy_s(aliasBuff.val, aliasBuff.length, credId, credIdLen) != EOK) {
1147         LOGE("Failed to copy credId.");
1148         HcFree(aliasStr);
1149         return IS_ERR_MEMORY_COPY;
1150     }
1151     if (memcpy_s(aliasBuff.val + credIdLen, deviceIdLen,
1152         deviceId, deviceIdLen) != EOK) {
1153         LOGE("Failed to copy deviceId.");
1154         HcFree(aliasStr);
1155         return IS_ERR_MEMORY_COPY;
1156     }
1157     int32_t ret = GetLoaderInstance()->sha256(&aliasBuff, alias);
1158     HcFree(aliasStr);
1159     if (ret != HAL_SUCCESS) {
1160         LOGE("Compute alias failed");
1161     }
1162     return ret;
1163 }
1164 
ComputeAndSavePskInner(int32_t osAccountId,uint8_t credAlgo,const Uint8Buff * selfKeyAlias,const Uint8Buff * peerKeyAlias,Uint8Buff * sharedKeyAlias)1165 static int32_t ComputeAndSavePskInner(int32_t osAccountId, uint8_t credAlgo, const Uint8Buff *selfKeyAlias,
1166     const Uint8Buff *peerKeyAlias, Uint8Buff *sharedKeyAlias)
1167 {
1168     KeyParams selfKeyParams = { { selfKeyAlias->val, selfKeyAlias->length, true }, false, osAccountId };
1169     uint8_t peerPubKeyVal[KEY_VALUE_MAX_LENGTH] = { 0 };
1170     Uint8Buff peerPubKeyBuff = { peerPubKeyVal, KEY_VALUE_MAX_LENGTH };
1171     KeyParams keyParams = { { peerKeyAlias->val, peerKeyAlias->length, true }, false, osAccountId };
1172     int32_t res = GetLoaderInstance()->exportPublicKey(&keyParams, &peerPubKeyBuff);
1173     if (res != IS_SUCCESS) {
1174         LOGE("Failed to export peer public key!");
1175         return res;
1176     }
1177     KeyBuff peerKeyBuff = { peerPubKeyBuff.val, peerPubKeyBuff.length, false };
1178     Algorithm algo = GetAlgoFromCred(credAlgo);
1179     res = GetLoaderInstance()->agreeSharedSecretWithStorage(&selfKeyParams, &peerKeyBuff, algo,
1180         PSK_LEN, sharedKeyAlias);
1181     if (res != IS_SUCCESS) {
1182         ReportRadarEvent(res);
1183         LOGE("Agree psk failed.");
1184     }
1185     return res;
1186 }
1187 
SetAgreeCredInfo(int32_t osAccountId,CJson * reqJson,Credential * agreeCredential,Uint8Buff * keyValue,Uint8Buff * agreeCredIdByte)1188 int32_t SetAgreeCredInfo(int32_t osAccountId, CJson *reqJson,
1189     Credential *agreeCredential, Uint8Buff *keyValue, Uint8Buff *agreeCredIdByte)
1190 {
1191     if (AddIntToJson(reqJson, FIELD_METHOD, METHOD_IMPORT) != IS_SUCCESS) {
1192         LOGE("Failed to add method to json!");
1193         return IS_ERR_JSON_ADD;
1194     }
1195     uint8_t method = DEFAULT_VAL;
1196     int32_t ret = CheckAndSetCredInfo(osAccountId, agreeCredential, reqJson, &method, keyValue);
1197     if (ret != IS_SUCCESS) {
1198         return ret;
1199     }
1200     if ((ret = GenerateCredId(osAccountId, agreeCredential, agreeCredIdByte)) != IS_SUCCESS) {
1201         HcFree(keyValue->val);
1202         return ret;
1203     }
1204     return IS_SUCCESS;
1205 }
1206 
ImportAgreeKeyValue(int32_t osAccountId,Credential * agreeCredential,Uint8Buff * keyValue,Uint8Buff * peerKeyAlias)1207 int32_t ImportAgreeKeyValue(int32_t osAccountId, Credential *agreeCredential, Uint8Buff *keyValue,
1208     Uint8Buff *peerKeyAlias)
1209 {
1210     int32_t ret = GenerateCredKeyAlias(
1211         StringGet(&agreeCredential->credId), StringGet(&agreeCredential->deviceId), peerKeyAlias);
1212     if (ret != IS_SUCCESS) {
1213         LOGE("Failed to generate peer key alias!");
1214         return ret;
1215     }
1216     ret = AddKeyValueToHuks(osAccountId, peerKeyAlias, agreeCredential, METHOD_IMPORT, keyValue);
1217     if (ret != IS_SUCCESS) {
1218         LOGE("Failed to add peer key value to huks!");
1219         return ret;
1220     }
1221     return IS_SUCCESS;
1222 }
1223 
CheckAndDelInvalidCred(int32_t osAccountId,const char * selfCredId,Uint8Buff * selfCredIdByte)1224 int32_t CheckAndDelInvalidCred(int32_t osAccountId, const char *selfCredId, Uint8Buff *selfCredIdByte)
1225 {
1226     int32_t ret = GetValidKeyAlias(osAccountId, selfCredId, selfCredIdByte);
1227     if (ret == HAL_ERR_KEY_NOT_EXIST) {
1228         LOGE("Huks key not exist!");
1229         DelCredById(osAccountId, selfCredId);
1230         return IS_ERR_HUKS_KEY_NOT_EXIST;
1231     }
1232     if (ret == HAL_ERR_HUKS) {
1233         LOGE("Huks check key exist failed");
1234         return IS_ERR_HUKS_CHECK_KEY_EXIST_FAILED;
1235     }
1236     if (ret != IS_SUCCESS) {
1237         LOGE("Failed to check key exist in HUKS");
1238         return ret;
1239     }
1240     return IS_SUCCESS;
1241 }
1242 
ComputePskAndDelInvalidKey(int32_t osAccountId,uint8_t credAlgo,Uint8Buff * selfCredIdByte,Uint8Buff * peerKeyAlias,Uint8Buff * agreeCredIdByte)1243 int32_t ComputePskAndDelInvalidKey(int32_t osAccountId, uint8_t credAlgo, Uint8Buff *selfCredIdByte,
1244     Uint8Buff *peerKeyAlias, Uint8Buff *agreeCredIdByte)
1245 {
1246     int32_t ret = ComputeAndSavePskInner(osAccountId, credAlgo, selfCredIdByte, peerKeyAlias, agreeCredIdByte);
1247     if (ret != IS_SUCCESS) {
1248         LOGE("Failed to compute and save psk!");
1249         return ret;
1250     }
1251     ret = GetLoaderInstance()->deleteKey(peerKeyAlias, false, osAccountId);
1252     if (ret != IS_SUCCESS) {
1253         LOGE("Failed to delete key from HUKS");
1254         return ret;
1255     }
1256     return IS_SUCCESS;
1257 }
1258 
SetRequiredParamsFromJson(QueryCredentialParams * queryParams,CJson * baseInfoJson)1259 int32_t SetRequiredParamsFromJson(QueryCredentialParams *queryParams, CJson *baseInfoJson)
1260 {
1261     if (GetUint8FromJson(baseInfoJson, FIELD_CRED_TYPE, &(queryParams->credType)) != IS_SUCCESS) {
1262         LOGE("Failed to set query params: credType");
1263         return IS_ERR_JSON_GET;
1264     }
1265     if (queryParams->credType != ACCOUNT_SHARED) {
1266         LOGE("Not support for credType %" LOG_PUB "d, only support for ACCOUNT_SHARED", queryParams->credType);
1267         return IS_ERR_NOT_SUPPORT;
1268     }
1269     const char *credOwner = GetStringFromJson(baseInfoJson, FIELD_CRED_OWNER);
1270     if (credOwner == NULL || IsStrEqual(credOwner, "")) {
1271         LOGE("Failed to set query params: credOwner");
1272         return IS_ERR_JSON_GET;
1273     }
1274     queryParams->credOwner = credOwner;
1275     return IS_SUCCESS;
1276 }
1277 
SetUpdateToQueryParams(CJson * json,QueryCredentialParams * queryParams)1278 int32_t SetUpdateToQueryParams(CJson *json, QueryCredentialParams *queryParams)
1279 {
1280     const char *userId = GetStringFromJson(json, FIELD_USER_ID);
1281     if (userId == NULL || IsStrEqual(userId, "")) {
1282         LOGE("Failed to set query params: userId");
1283         return IS_ERR_JSON_GET;
1284     }
1285     queryParams->userId = userId;
1286     const char *deviceId = GetStringFromJson(json, FIELD_DEVICE_ID);
1287     if (deviceId == NULL || IsStrEqual(deviceId, "")) {
1288         LOGE("Failed to set query params: deviceId");
1289         return IS_ERR_JSON_GET;
1290     }
1291     queryParams->deviceId = deviceId;
1292     return IS_SUCCESS;
1293 }
1294 
EraseCredIdInVec(const char * credId,CredentialVec * credVec)1295 static int32_t EraseCredIdInVec(const char *credId, CredentialVec *credVec)
1296 {
1297     uint32_t index = 0;
1298     Credential **item;
1299     while (index < credVec->size(credVec)) {
1300         item = credVec->getp(credVec, index);
1301         if (item == NULL || *item == NULL) {
1302             index++;
1303             continue;
1304         }
1305         const char *itemCredId = StringGet(&(*item)->credId);
1306         if (itemCredId != NULL && IsStrEqual(credId, itemCredId)) {
1307             credVec->eraseElement(credVec, item, index);
1308             return IS_SUCCESS;
1309         }
1310         index++;
1311     }
1312     return IS_ERROR;
1313 }
1314 
AddUpdateInfoToJson(QueryCredentialParams * queryParams,CJson * baseInfoJson)1315 int32_t AddUpdateInfoToJson(QueryCredentialParams *queryParams, CJson *baseInfoJson)
1316 {
1317     if (AddStringToJson(baseInfoJson, FIELD_USER_ID, queryParams->userId) != IS_SUCCESS) {
1318         LOGE("add userId to baseInfoJson fail.");
1319         return IS_ERR_JSON_ADD;
1320     }
1321     if (AddStringToJson(baseInfoJson, FIELD_DEVICE_ID, queryParams->deviceId) != IS_SUCCESS) {
1322         LOGE("add deviceId to baseInfoJson fail.");
1323         return IS_ERR_JSON_ADD;
1324     }
1325     if (AddIntToJson(baseInfoJson, FIELD_METHOD, METHOD_IMPORT) != IS_SUCCESS) {
1326         LOGE("Failed to add method to baseInfoJson!");
1327         return IS_ERR_JSON_ADD;
1328     }
1329     return IS_SUCCESS;
1330 }
1331 
EraseUpdateCredIdInSelfVec(CredentialVec * updateCredVec,CredentialVec * selfCredVec)1332 int32_t EraseUpdateCredIdInSelfVec(CredentialVec *updateCredVec, CredentialVec *selfCredVec)
1333 {
1334     Credential **cred = updateCredVec->getp(updateCredVec, 0);
1335     if (cred == NULL || *cred == NULL) {
1336         LOGE("Failed to get first cred");
1337         return IS_ERR_NULL_PTR;
1338     }
1339     const char *updateCredId = StringGet(&(*cred)->credId);
1340     if (updateCredId == NULL) {
1341         LOGE("Failed to get updateCredId");
1342         return IS_ERR_NULL_PTR;
1343     }
1344     return EraseCredIdInVec(updateCredId, selfCredVec);
1345 }
1346 
GetQueryJsonStr(CJson * baseInfoJson,char ** queryJsonStr)1347 int32_t GetQueryJsonStr(CJson *baseInfoJson, char **queryJsonStr)
1348 {
1349     const char *credOwner = GetStringFromJson(baseInfoJson, FIELD_CRED_OWNER);
1350     if (credOwner == NULL) {
1351         LOGE("Failed to get credOwner");
1352         return IS_ERR_INVALID_PARAMS;
1353     }
1354     CJson *queryJson = CreateJson();
1355     if (queryJson == NULL) {
1356         LOGE("Failed to create queryJson");
1357         return IS_ERR_JSON_CREATE;
1358     }
1359     if (AddStringToJson(queryJson, FIELD_CRED_OWNER, credOwner)) {
1360         FreeJson(queryJson);
1361         return IS_ERR_JSON_ADD;
1362     }
1363     *queryJsonStr = PackJsonToString(queryJson);
1364     FreeJson(queryJson);
1365     if (*queryJsonStr == NULL) {
1366         LOGE("Failed to pack queryJson to string");
1367         return IS_ERR_PACKAGE_JSON_TO_STRING_FAIL;
1368     }
1369     return IS_SUCCESS;
1370 }
1371 
GetUpdateCredVec(int32_t osAccountId,CJson * updateInfo,QueryCredentialParams * queryParams,CredentialVec * updateCredVec)1372 int32_t GetUpdateCredVec(int32_t osAccountId, CJson *updateInfo,
1373     QueryCredentialParams *queryParams, CredentialVec *updateCredVec)
1374 {
1375     int32_t ret = SetUpdateToQueryParams(updateInfo, queryParams);
1376     if (ret != IS_SUCCESS) {
1377         LOGE("Failed to set updateLists to query params");
1378         return ret;
1379     }
1380     return QueryCredentials(osAccountId, queryParams, updateCredVec);
1381 }
1382