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 #include "credential_data_manager.h"
17
18 #include "common_defs.h"
19 #include "device_auth_defines.h"
20 #include "hc_dev_info.h"
21 #include "hc_file.h"
22 #include "hc_log.h"
23 #include "hc_mutex.h"
24 #include "hc_types.h"
25 #include "securec.h"
26 #include "hidump_adapter.h"
27 #include "os_account_adapter.h"
28 #include "security_label_adapter.h"
29 #include "account_task_manager.h"
30 #include "cred_listener.h"
31 #include "cred_tlv_parser.h"
32 #include "identity_service_defines.h"
33 #include "string_util.h"
34
35 typedef struct {
36 DECLARE_CRED_TLV_STRUCT(17)
37 CredTlvString credId;
38 CredTlvString deviceId;
39 CredTlvString peerUserSpaceId;
40 CredTlvUint8 subject;
41 CredTlvString userId;
42 CredTlvUint8 issuer;
43 CredTlvUint8 credType;
44 CredTlvUint8 keyFormat;
45 CredTlvUint8 algorithmType;
46 CredTlvUint8 proofType;
47 CredTlvBuffer authorizedAccountList;
48 CredTlvBuffer authorizedAppList;
49 CredTlvBuffer authorizedDeviceList;
50 CredTlvUint8 authorizedScope;
51 CredTlvString credOwner;
52 CredTlvInt32 ownerUid;
53 CredTlvString extendInfo;
54 } TlvCredentialElement;
55 DECLEAR_CRED_INIT_FUNC(TlvCredentialElement)
56 DECLARE_CRED_TLV_VECTOR(TlvCredentialVec, TlvCredentialElement)
57
58 typedef struct {
59 DECLARE_CRED_TLV_STRUCT(2)
60 CredTlvInt32 version;
61 TlvCredentialVec credentials;
62 } HCCredDataBaseV1;
63 DECLEAR_CRED_INIT_FUNC(HCCredDataBaseV1)
64
65 BEGIN_CRED_TLV_STRUCT_DEFINE(TlvCredentialElement, 0x0001)
66 CRED_TLV_MEMBER(CredTlvString, credId, 0x4001)
67 CRED_TLV_MEMBER(CredTlvString, deviceId, 0x4002)
68 CRED_TLV_MEMBER(CredTlvString, peerUserSpaceId, 0x4003)
69 CRED_TLV_MEMBER(CredTlvUint8, subject, 0x4004)
70 CRED_TLV_MEMBER(CredTlvString, userId, 0x4005)
71 CRED_TLV_MEMBER(CredTlvUint8, issuer, 0x4006)
72 CRED_TLV_MEMBER(CredTlvUint8, credType, 0x4007)
73 CRED_TLV_MEMBER(CredTlvUint8, keyFormat, 0x4008)
74 CRED_TLV_MEMBER(CredTlvUint8, algorithmType, 0x4009)
75 CRED_TLV_MEMBER(CredTlvUint8, proofType, 0x400A)
76 CRED_TLV_MEMBER(CredTlvBuffer, authorizedAccountList, 0x400B)
77 CRED_TLV_MEMBER(CredTlvBuffer, authorizedAppList, 0x400C)
78 CRED_TLV_MEMBER(CredTlvBuffer, authorizedDeviceList, 0x400D)
79 CRED_TLV_MEMBER(CredTlvUint8, authorizedScope, 0x400E)
80 CRED_TLV_MEMBER(CredTlvString, credOwner, 0x400F)
81 CRED_TLV_MEMBER(CredTlvInt32, ownerUid, 0x4010)
82 CRED_TLV_MEMBER(CredTlvString, extendInfo, 0x4011)
83 END_CRED_TLV_STRUCT_DEFINE()
84 IMPLEMENT_CRED_TLV_VECTOR(TlvCredentialVec, TlvCredentialElement, 1)
85
86 BEGIN_CRED_TLV_STRUCT_DEFINE(HCCredDataBaseV1, 0x0001)
87 CRED_TLV_MEMBER(CredTlvInt32, version, 0x6001)
88 CRED_TLV_MEMBER(TlvCredentialVec, credentials, 0x6002)
89 END_CRED_TLV_STRUCT_DEFINE()
90
91 IMPLEMENT_HC_VECTOR(CredentialVec, Credential*, 1)
92
93 typedef struct {
94 int32_t osAccountId;
95 CredentialVec credentials;
96 } OsAccountCredInfo;
97
98 DECLARE_HC_VECTOR(DevAuthCredDb, OsAccountCredInfo)
99 IMPLEMENT_HC_VECTOR(DevAuthCredDb, OsAccountCredInfo, 1)
100
101 #define MAX_DB_PATH_LEN 256
102
103 static HcMutex *g_credMutex = NULL;
104 static DevAuthCredDb g_devauthCredDb;
105 const uint8_t DEFAULT_CRED_PARAM_VAL = 0;
106
EndWithZero(HcParcel * parcel)107 static bool EndWithZero(HcParcel *parcel)
108 {
109 const char *p = GetParcelLastChar(parcel);
110 if (p == NULL) {
111 return false;
112 }
113 return (*p == '\0');
114 }
115
LoadStringVectorFromParcel(StringVector * vec,HcParcel * parcel)116 static bool LoadStringVectorFromParcel(StringVector *vec, HcParcel *parcel)
117 {
118 uint32_t strLen = 0;
119 do {
120 if (!ParcelReadUint32(parcel, &strLen)) {
121 return true;
122 }
123 if ((strLen == 0) || (strLen > MAX_STRING_LEN)) {
124 return false;
125 }
126 HcString str = CreateString();
127 ClearParcel(&str.parcel);
128 if (!ParcelReadParcel(parcel, &str.parcel, strLen, false) ||
129 !EndWithZero(&str.parcel)) {
130 DeleteString(&str);
131 return false;
132 } else {
133 if (vec->pushBack(vec, &str) == NULL) {
134 DeleteString(&str);
135 return false;
136 }
137 }
138 } while (1);
139 }
140
SaveStringVectorToParcel(const StringVector * vec,HcParcel * parcel)141 static bool SaveStringVectorToParcel(const StringVector *vec, HcParcel *parcel)
142 {
143 uint32_t index;
144 HcString *str = NULL;
145 FOR_EACH_HC_VECTOR(*vec, index, str) {
146 uint32_t len = StringLength(str) + sizeof(char);
147 if (!ParcelWriteUint32(parcel, len)) {
148 return false;
149 }
150 if (!ParcelWrite(parcel, GetParcelData(&str->parcel), GetParcelDataSize(&str->parcel))) {
151 return false;
152 }
153 }
154 return true;
155 }
156
GetOsAccountCredInfoPathCe(int32_t osAccountId,char * infoPath,uint32_t pathBufferLen)157 static bool GetOsAccountCredInfoPathCe(int32_t osAccountId, char *infoPath, uint32_t pathBufferLen)
158 {
159 const char *beginPath = GetStorageDirPathCe();
160 if (beginPath == NULL) {
161 LOGE("[CRED#DB]: Failed to get the storage path!");
162 return false;
163 }
164 if (sprintf_s(infoPath, pathBufferLen, "%s/%d/deviceauth/hccredential.dat", beginPath, osAccountId) <= 0) {
165 LOGE("[CRED#DB]: Failed to generate db file path!");
166 return false;
167 }
168 return true;
169 }
170
GetOsAccountCredInfoPathDe(int32_t osAccountId,char * infoPath,uint32_t pathBufferLen)171 static bool GetOsAccountCredInfoPathDe(int32_t osAccountId, char *infoPath, uint32_t pathBufferLen)
172 {
173 const char *beginPath = GetStorageDirPath();
174 if (beginPath == NULL) {
175 LOGE("[CRED#DB]: Failed to get the storage path dir!");
176 return false;
177 }
178 int32_t writeByteNum;
179 if (osAccountId == DEFAULT_OS_ACCOUNT) {
180 writeByteNum = sprintf_s(infoPath, pathBufferLen, "%s/hccredential.dat", beginPath);
181 } else {
182 writeByteNum = sprintf_s(infoPath, pathBufferLen, "%s/hccredential%d.dat", beginPath, osAccountId);
183 }
184 if (writeByteNum <= 0) {
185 LOGE("[CRED#DB]: sprintf_s fail!");
186 return false;
187 }
188 return true;
189 }
190
GetOsAccountCredInfoPath(int32_t osAccountId,char * infoPath,uint32_t pathBufferLen)191 static bool GetOsAccountCredInfoPath(int32_t osAccountId, char *infoPath, uint32_t pathBufferLen)
192 {
193 if (IsOsAccountSupported()) {
194 return GetOsAccountCredInfoPathCe(osAccountId, infoPath, pathBufferLen);
195 } else {
196 return GetOsAccountCredInfoPathDe(osAccountId, infoPath, pathBufferLen);
197 }
198 }
199
GenerateAuthorizedAppList(const Credential * entry,Credential * returnEntry)200 static bool GenerateAuthorizedAppList(const Credential *entry, Credential *returnEntry)
201 {
202 uint32_t index = 0;
203 HcString *authorizedApp = NULL;
204 FOR_EACH_HC_VECTOR(entry->authorizedAppList, index, authorizedApp) {
205 if (authorizedApp == NULL) {
206 continue;
207 }
208 HcString returnAuthorizedApp = CreateString();
209 if (!StringSet(&returnAuthorizedApp, *authorizedApp)) {
210 DeleteString(&returnAuthorizedApp);
211 LOGE("[CRED#DB]: Failed to copy authorizedApp!");
212 return false;
213 }
214 if (returnEntry->authorizedAppList.pushBack(&returnEntry->authorizedAppList, &returnAuthorizedApp)
215 == NULL) {
216 LOGE("[CRED#DB]: Failed to push authorizedApp to list!");
217 DeleteString(&returnAuthorizedApp);
218 return false;
219 }
220 }
221 return true;
222 }
223
GenerateCredFromCred(const Credential * entry,Credential * returnEntry)224 bool GenerateCredFromCred(const Credential *entry, Credential *returnEntry)
225 {
226 if (!StringSet(&returnEntry->credId, entry->credId)) {
227 LOGE("[CRED#DB]: Failed to copy credId!");
228 return false;
229 }
230 if (!StringSet(&returnEntry->deviceId, entry->deviceId)) {
231 LOGE("[CRED#DB]: Failed to copy deviceId!");
232 return false;
233 }
234 if (!StringSet(&returnEntry->peerUserSpaceId, entry->peerUserSpaceId)) {
235 LOGE("[CRED#DB]: Failed to copy peerUserSpaceId!");
236 return false;
237 }
238 if (!StringSet(&returnEntry->userId, entry->userId)) {
239 LOGE("[CRED#DB]: Failed to copy userId!");
240 return false;
241 }
242 if (!StringSet(&returnEntry->credOwner, entry->credOwner)) {
243 LOGE("[CRED#DB]: Failed to copy credOwner!");
244 return false;
245 }
246 if (!GenerateAuthorizedAppList(entry, returnEntry)) {
247 return false;
248 }
249 if (!StringSet(&returnEntry->extendInfo, entry->extendInfo)) {
250 LOGE("[CRED#DB]: Failed to copy extendInfo!");
251 return false;
252 }
253 returnEntry->subject = entry->subject;
254 returnEntry->authorizedScope = entry->authorizedScope;
255 returnEntry->credType = entry->credType;
256 returnEntry->issuer = entry->issuer;
257 returnEntry->keyFormat = entry->keyFormat;
258 returnEntry->algorithmType = entry->algorithmType;
259 returnEntry->proofType = entry->proofType;
260 returnEntry->ownerUid = entry->ownerUid;
261 return true;
262 }
263
GenerateCredentialFromTlv(TlvCredentialElement * credential,Credential * entry)264 static bool GenerateCredentialFromTlv(TlvCredentialElement *credential, Credential *entry)
265 {
266 if (!StringSet(&entry->credId, credential->credId.data)) {
267 LOGE("[CRED#DB]: Failed to load credId from tlv!");
268 return false;
269 }
270 if (!StringSet(&entry->deviceId, credential->deviceId.data)) {
271 LOGE("[CRED#DB]: Failed to load deviceId from tlv!");
272 return false;
273 }
274 if (!StringSet(&entry->peerUserSpaceId, credential->peerUserSpaceId.data)) {
275 LOGE("[CRED#DB]: Failed to load peerUserSpaceId from tlv!");
276 return false;
277 }
278 if (!StringSet(&entry->userId, credential->userId.data)) {
279 LOGE("[CRED#DB]: Failed to load userId from tlv!");
280 return false;
281 }
282 if (!StringSet(&entry->credOwner, credential->credOwner.data)) {
283 LOGE("[CRED#DB]: Failed to load credOwner from tlv!");
284 return false;
285 }
286 if (!LoadStringVectorFromParcel(&entry->authorizedAccountList, &credential->authorizedAccountList.data)) {
287 LOGE("[CRED#DB]: Failed to load authorizedAccountList from tlv!");
288 return false;
289 }
290 if (!LoadStringVectorFromParcel(&entry->authorizedDeviceList, &credential->authorizedDeviceList.data)) {
291 LOGE("[CRED#DB]: Failed to load authorizedDeviceList from tlv!");
292 return false;
293 }
294 if (!LoadStringVectorFromParcel(&entry->authorizedAppList, &credential->authorizedAppList.data)) {
295 LOGE("[CRED#DB]: Failed to load authorizedAppList from tlv!");
296 return false;
297 }
298 if (!StringSet(&entry->extendInfo, credential->extendInfo.data)) {
299 LOGE("[CRED#DB]: Failed to load extendInfo from tlv!");
300 return false;
301 }
302 entry->subject = credential->subject.data;
303 entry->authorizedScope = credential->authorizedScope.data;
304 entry->issuer = credential->issuer.data;
305 entry->credType = credential->credType.data;
306 entry->keyFormat = credential->keyFormat.data;
307 entry->algorithmType = credential->algorithmType.data;
308 entry->proofType = credential->proofType.data;
309 entry->ownerUid = credential->ownerUid.data;
310 return true;
311 }
312
LoadCredentials(HCCredDataBaseV1 * db,CredentialVec * vec)313 static bool LoadCredentials(HCCredDataBaseV1 *db, CredentialVec *vec)
314 {
315 uint32_t index;
316 TlvCredentialElement *credentialTlv = NULL;
317 FOR_EACH_HC_VECTOR(db->credentials.data, index, credentialTlv) {
318 if (credentialTlv == NULL) {
319 continue;
320 }
321 Credential *entry = CreateCredential();
322 if (entry == NULL) {
323 LOGE("[CRED#DB]: Failed to allocate entry memory!");
324 ClearCredentialVec(vec);
325 return false;
326 }
327 if (!GenerateCredentialFromTlv(credentialTlv, entry)) {
328 DestroyCredential(entry);
329 ClearCredentialVec(vec);
330 return false;
331 }
332 if (vec->pushBackT(vec, entry) == NULL) {
333 LOGE("[CRED#DB]: Failed to push entry to vec!");
334 DestroyCredential(entry);
335 ClearCredentialVec(vec);
336 return false;
337 }
338 }
339 return true;
340 }
341
ReadCredInfoFromParcel(HcParcel * parcel,OsAccountCredInfo * info)342 static bool ReadCredInfoFromParcel(HcParcel *parcel, OsAccountCredInfo *info)
343 {
344 bool ret = false;
345 HCCredDataBaseV1 dbv1;
346 CRED_TLV_INIT(HCCredDataBaseV1, &dbv1)
347 if (DecodeCredTlvMessage((CredTlvBase *)&dbv1, parcel, false)) {
348 if (!LoadCredentials(&dbv1, &info->credentials)) {
349 CRED_TLV_DEINIT(dbv1)
350 return false;
351 }
352 ret = true;
353 } else {
354 LOGE("[CRED#DB]: Decode Tlv Message Failed!");
355 }
356 CRED_TLV_DEINIT(dbv1)
357 return ret;
358 }
359
ReadParcelFromFile(const char * filePath,HcParcel * parcel)360 static bool ReadParcelFromFile(const char *filePath, HcParcel *parcel)
361 {
362 FileHandle file;
363 int ret = HcFileOpen(filePath, MODE_FILE_READ, &file);
364 if (ret != 0) {
365 LOGE("[CRED#DB]: Failed to open database file!");
366 return false;
367 }
368 SetSecurityLabel(filePath, SECURITY_LABEL_S2);
369 int fileSize = HcFileSize(file);
370 if (fileSize <= 0) {
371 LOGE("[CRED#DB]: The database file size is invalid!");
372 HcFileClose(file);
373 return false;
374 }
375 char *fileData = (char *)HcMalloc(fileSize, 0);
376 if (fileData == NULL) {
377 LOGE("[CRED#DB]: Failed to allocate fileData memory!");
378 HcFileClose(file);
379 return false;
380 }
381 if (HcFileRead(file, fileData, fileSize) != fileSize) {
382 LOGE("[CRED#DB]: Read file error!");
383 HcFileClose(file);
384 HcFree(fileData);
385 return false;
386 }
387 HcFileClose(file);
388 if (!ParcelWrite(parcel, fileData, fileSize)) {
389 LOGE("[CRED#DB]: parcel write error!");
390 HcFree(fileData);
391 return false;
392 }
393 HcFree(fileData);
394 return true;
395 }
396
SaveParcelToFile(const char * filePath,HcParcel * parcel)397 static bool SaveParcelToFile(const char *filePath, HcParcel *parcel)
398 {
399 FileHandle file;
400 int ret = HcFileOpen(filePath, MODE_FILE_WRITE, &file);
401 if (ret != IS_SUCCESS) {
402 LOGE("[CRED#DB]: Failed to open database file!");
403 return false;
404 }
405 SetSecurityLabel(filePath, SECURITY_LABEL_S2);
406 int fileSize = (int)GetParcelDataSize(parcel);
407 const char *fileData = GetParcelData(parcel);
408 int writeSize = HcFileWrite(file, fileData, fileSize);
409 HcFileClose(file);
410 if (writeSize == fileSize) {
411 return true;
412 } else {
413 LOGE("[CRED#DB]: write file error!");
414 return false;
415 }
416 }
417
LoadOsAccountCredDb(int32_t osAccountId)418 static void LoadOsAccountCredDb(int32_t osAccountId)
419 {
420 char filePath[MAX_DB_PATH_LEN] = { 0 };
421 if (!GetOsAccountCredInfoPath(osAccountId, filePath, MAX_DB_PATH_LEN)) {
422 LOGE("[CRED#DB]: Failed to get os account info path!");
423 return;
424 }
425 HcParcel parcel = CreateParcel(0, 0);
426 if (!ReadParcelFromFile(filePath, &parcel)) {
427 DeleteParcel(&parcel);
428 return;
429 }
430 OsAccountCredInfo info;
431 info.osAccountId = osAccountId;
432 info.credentials = CreateCredentialVec();
433 if (!ReadCredInfoFromParcel(&parcel, &info)) {
434 DestroyCredentialVec(&info.credentials);
435 DeleteParcel(&parcel);
436 return;
437 }
438 DeleteParcel(&parcel);
439 if (g_devauthCredDb.pushBackT(&g_devauthCredDb, info) == NULL) {
440 LOGE("[CRED#DB]: Failed to push osAccountCredInfo to cred database!");
441 ClearCredentialVec(&info.credentials);
442 return;
443 }
444 LOGI("[CRED#DB]: Load os account cred db successfully! [Id]: %" LOG_PUB "d", osAccountId);
445 }
446
RemoveOsAccountCredInfo(int32_t osAccountId)447 static void RemoveOsAccountCredInfo(int32_t osAccountId)
448 {
449 uint32_t index = 0;
450 OsAccountCredInfo *info = NULL;
451 FOR_EACH_HC_VECTOR(g_devauthCredDb, index, info) {
452 if (info != NULL && info->osAccountId == osAccountId) {
453 OsAccountCredInfo deleteInfo;
454 HC_VECTOR_POPELEMENT(&g_devauthCredDb, &deleteInfo, index);
455 ClearCredentialVec(&deleteInfo.credentials);
456 return;
457 }
458 }
459 }
460
OnOsAccountUnlocked(int32_t osAccountId)461 static void OnOsAccountUnlocked(int32_t osAccountId)
462 {
463 (void)LockHcMutex(g_credMutex);
464 RemoveOsAccountCredInfo(osAccountId);
465 LoadOsAccountCredDb(osAccountId);
466 UnlockHcMutex(g_credMutex);
467 }
468
OnOsAccountRemoved(int32_t osAccountId)469 static void OnOsAccountRemoved(int32_t osAccountId)
470 {
471 LOGI("[CRED#DB]: os account is removed, osAccountId: %" LOG_PUB "d", osAccountId);
472 (void)LockHcMutex(g_credMutex);
473 RemoveOsAccountCredInfo(osAccountId);
474 UnlockHcMutex(g_credMutex);
475 }
476
IsOsAccountCredDataLoaded(int32_t osAccountId)477 static bool IsOsAccountCredDataLoaded(int32_t osAccountId)
478 {
479 uint32_t index = 0;
480 OsAccountCredInfo *info = NULL;
481 FOR_EACH_HC_VECTOR(g_devauthCredDb, index, info) {
482 if (info != NULL && info->osAccountId == osAccountId) {
483 return true;
484 }
485 }
486 return false;
487 }
488
LoadDataIfNotLoaded(int32_t osAccountId)489 static void LoadDataIfNotLoaded(int32_t osAccountId)
490 {
491 if (IsOsAccountCredDataLoaded(osAccountId)) {
492 return;
493 }
494 LOGI("[CRED#DB]: data has not been loaded, load it, osAccountId: %" LOG_PUB "d", osAccountId);
495 LoadOsAccountCredDb(osAccountId);
496 }
497
GetCredInfoByOsAccountId(int32_t osAccountId)498 static OsAccountCredInfo *GetCredInfoByOsAccountId(int32_t osAccountId)
499 {
500 if (IsOsAccountSupported()) {
501 LoadDataIfNotLoaded(osAccountId);
502 }
503 uint32_t index = 0;
504 OsAccountCredInfo *info = NULL;
505 FOR_EACH_HC_VECTOR(g_devauthCredDb, index, info) {
506 if (info != NULL && info->osAccountId == osAccountId) {
507 return info;
508 }
509 }
510 LOGI("[CRED#DB]: Create a new os account database cache! [Id]: %" LOG_PUB "d", osAccountId);
511 OsAccountCredInfo newInfo;
512 newInfo.osAccountId = osAccountId;
513 newInfo.credentials = CreateCredentialVec();
514 OsAccountCredInfo *returnInfo = g_devauthCredDb.pushBackT(&g_devauthCredDb, newInfo);
515 if (returnInfo == NULL) {
516 LOGE("[CRED#DB]: Failed to push osAccountInfo to database!");
517 DestroyCredentialVec(&newInfo.credentials);
518 }
519 return returnInfo;
520 }
521
LoadDevAuthCredDb(void)522 static void LoadDevAuthCredDb(void)
523 {
524 if (IsOsAccountSupported()) {
525 return;
526 }
527 (void)LockHcMutex(g_credMutex);
528 StringVector osAccountDbNameVec = CreateStrVector();
529 HcFileGetSubFileName(GetStorageDirPath(), &osAccountDbNameVec);
530 uint32_t index;
531 HcString *dbName;
532 FOR_EACH_HC_VECTOR(osAccountDbNameVec, index, dbName) {
533 int32_t osAccountId;
534 const char *osAccountIdStr = StringGet(dbName);
535 if (osAccountIdStr == NULL) {
536 continue;
537 }
538 if (IsStrEqual(osAccountIdStr, "hccredential.dat")) {
539 LoadOsAccountCredDb(DEFAULT_OS_ACCOUNT);
540 } else if (sscanf_s(osAccountIdStr, "hccredential%d.dat", &osAccountId) == 1) {
541 LoadOsAccountCredDb(osAccountId);
542 }
543 }
544 DestroyStrVector(&osAccountDbNameVec);
545 UnlockHcMutex(g_credMutex);
546 }
547
SetCredentialElement(TlvCredentialElement * element,Credential * entry)548 static bool SetCredentialElement(TlvCredentialElement *element, Credential *entry)
549 {
550 if (!StringSet(&element->credId.data, entry->credId)) {
551 LOGE("[CRED#DB]: Failed to copy credId!");
552 return false;
553 }
554 if (!StringSet(&element->deviceId.data, entry->deviceId)) {
555 LOGE("[CRED#DB]: Failed to copy deviceId!");
556 return false;
557 }
558 if (!StringSet(&element->peerUserSpaceId.data, entry->peerUserSpaceId)) {
559 LOGE("[CRED#DB]: Failed to copy peerUserSpaceId!");
560 return false;
561 }
562 if (!StringSet(&element->userId.data, entry->userId)) {
563 LOGE("[CRED#DB]: Failed to copy userId!");
564 return false;
565 }
566 if (!StringSet(&element->credOwner.data, entry->credOwner)) {
567 LOGE("[CRED#DB]: Failed to copy credOwner!");
568 return false;
569 }
570 if (!SaveStringVectorToParcel(&entry->authorizedAccountList, &element->authorizedAccountList.data)) {
571 LOGE("[CRED#DB]: Failed to copy authorizedAccountList!");
572 return false;
573 }
574 if (!SaveStringVectorToParcel(&entry->authorizedDeviceList, &element->authorizedDeviceList.data)) {
575 LOGE("[CRED#DB]: Failed to copy authorizedDeviceList!");
576 return false;
577 }
578 if (!SaveStringVectorToParcel(&entry->authorizedAppList, &element->authorizedAppList.data)) {
579 LOGE("[CRED#DB]: Failed to copy authorizedAppList!");
580 return false;
581 }
582 if (!StringSet(&element->extendInfo.data, entry->extendInfo)) {
583 LOGE("[CRED#DB]: Failed to copy extendInfo!");
584 return false;
585 }
586 element->subject.data = entry->subject;
587 element->authorizedScope.data = entry->authorizedScope;
588 element->issuer.data = entry->issuer;
589 element->credType.data = entry->credType;
590 element->keyFormat.data = entry->keyFormat;
591 element->algorithmType.data = entry->algorithmType;
592 element->proofType.data = entry->proofType;
593 element->ownerUid.data = entry->ownerUid;
594 return true;
595 }
596
SaveCredentials(const CredentialVec * vec,HCCredDataBaseV1 * db)597 static bool SaveCredentials(const CredentialVec *vec, HCCredDataBaseV1 *db)
598 {
599 uint32_t index;
600 Credential **entry;
601 FOR_EACH_HC_VECTOR(*vec, index, entry) {
602 if (entry == NULL || *entry == NULL) {
603 continue;
604 }
605 TlvCredentialElement tmp;
606 TlvCredentialElement *element = db->credentials.data.pushBack(&db->credentials.data, &tmp);
607 if (element == NULL) {
608 return false;
609 }
610 CRED_TLV_INIT(TlvCredentialElement, element);
611 if (!SetCredentialElement(element, *entry)) {
612 CRED_TLV_DEINIT((*element));
613 return false;
614 }
615 }
616 return true;
617 }
618
SaveCredInfoToParcel(const OsAccountCredInfo * info,HcParcel * parcel)619 static bool SaveCredInfoToParcel(const OsAccountCredInfo *info, HcParcel *parcel)
620 {
621 int32_t ret = false;
622 HCCredDataBaseV1 dbv1;
623 CRED_TLV_INIT(HCCredDataBaseV1, &dbv1)
624 dbv1.version.data = 1;
625 do {
626 if (!SaveCredentials(&info->credentials, &dbv1)) {
627 break;
628 }
629 if (!EncodeCredTlvMessage((CredTlvBase *)&dbv1, parcel)) {
630 LOGE("[CRED#DB]: Encode Tlv Message failed!");
631 break;
632 }
633 ret = true;
634 } while (0);
635 CRED_TLV_DEINIT(dbv1)
636 return ret;
637 }
638
CompareStringParams(const QueryCredentialParams * params,const Credential * entry)639 static bool CompareStringParams(const QueryCredentialParams *params, const Credential *entry)
640 {
641 if ((params->deviceId != NULL) && (!IsStrEqual(params->deviceId, StringGet(&entry->deviceId)))) {
642 return false;
643 }
644 if ((params->credOwner != NULL) && (!IsStrEqual(params->credOwner, StringGet(&entry->credOwner)))) {
645 return false;
646 }
647 if ((params->userId != NULL) && (!IsStrEqual(params->userId, StringGet(&entry->userId)))) {
648 return false;
649 }
650 if ((params->credId != NULL) && (!IsStrEqual(params->credId, StringGet(&entry->credId)))) {
651 return false;
652 }
653 if ((params->peerUserSpaceId != NULL) &&
654 (!IsStrEqual(params->peerUserSpaceId, StringGet(&entry->peerUserSpaceId)))) {
655 return false;
656 }
657 return true;
658 }
659
CompareIntParams(const QueryCredentialParams * params,const Credential * entry)660 static bool CompareIntParams(const QueryCredentialParams *params, const Credential *entry)
661 {
662 if ((params->credType != DEFAULT_CRED_PARAM_VAL) && (params->credType != entry->credType)) {
663 return false;
664 }
665 if ((params->subject != DEFAULT_CRED_PARAM_VAL) && (params->subject != entry->subject)) {
666 return false;
667 }
668 if ((params->issuer != DEFAULT_CRED_PARAM_VAL) && (params->issuer != entry->issuer)) {
669 return false;
670 }
671 if ((params->ownerUid != DEFAULT_CRED_PARAM_VAL) && (params->ownerUid != entry->ownerUid)) {
672 return false;
673 }
674 if ((params->authorizedScope != DEFAULT_CRED_PARAM_VAL) && (params->authorizedScope != entry->authorizedScope)) {
675 return false;
676 }
677 if ((params->keyFormat != DEFAULT_CRED_PARAM_VAL) && (params->keyFormat != entry->keyFormat)) {
678 return false;
679 }
680 if ((params->algorithmType != DEFAULT_CRED_PARAM_VAL) && (params->algorithmType != entry->algorithmType)) {
681 return false;
682 }
683 if ((params->proofType != DEFAULT_CRED_PARAM_VAL) && (params->proofType != entry->proofType)) {
684 return false;
685 }
686 return true;
687 }
688
CompareQueryCredentialParams(const QueryCredentialParams * params,const Credential * entry)689 static bool CompareQueryCredentialParams(const QueryCredentialParams *params, const Credential *entry)
690 {
691 return CompareStringParams(params, entry) && CompareIntParams(params, entry);
692 }
693
QueryCredentialPtrIfMatch(const CredentialVec * vec,const QueryCredentialParams * params)694 static Credential **QueryCredentialPtrIfMatch(const CredentialVec *vec, const QueryCredentialParams *params)
695 {
696 uint32_t index;
697 Credential **entry;
698 FOR_EACH_HC_VECTOR(*vec, index, entry) {
699 if (entry != NULL && *entry != NULL && CompareQueryCredentialParams(params, *entry)) {
700 return entry;
701 }
702 }
703 return NULL;
704 }
705
InitQueryCredentialParams(void)706 QueryCredentialParams InitQueryCredentialParams(void)
707 {
708 QueryCredentialParams params = {
709 .credId = NULL,
710 .deviceId = NULL,
711 .subject = DEFAULT_CRED_PARAM_VAL,
712 .userId = NULL,
713 .issuer = DEFAULT_CRED_PARAM_VAL,
714 .credType = DEFAULT_CRED_PARAM_VAL,
715 .credOwner = NULL,
716 .ownerUid = DEFAULT_CRED_PARAM_VAL,
717 };
718 return params;
719 }
720
CreateCredential(void)721 Credential *CreateCredential(void)
722 {
723 Credential *ptr = (Credential *)HcMalloc(sizeof(Credential), 0);
724 if (ptr == NULL) {
725 LOGE("[CRED#DB]: Failed to allocate Credential memory!");
726 return NULL;
727 }
728 ptr->credId = CreateString();
729 ptr->deviceId = CreateString();
730 ptr->peerUserSpaceId = CreateString();
731 ptr->userId = CreateString();
732 ptr->credOwner = CreateString();
733 ptr->authorizedAccountList = CreateStrVector();
734 ptr->authorizedAppList = CreateStrVector();
735 ptr->authorizedDeviceList = CreateStrVector();
736 ptr->extendInfo = CreateString();
737 return ptr;
738 }
739
DestroyCredential(Credential * credential)740 void DestroyCredential(Credential *credential)
741 {
742 if (credential == NULL) {
743 return;
744 }
745 DeleteString(&credential->credId);
746 DeleteString(&credential->deviceId);
747 DeleteString(&credential->peerUserSpaceId);
748 DeleteString(&credential->userId);
749 DeleteString(&credential->credOwner);
750 DestroyStrVector(&credential->authorizedAccountList);
751 DestroyStrVector(&credential->authorizedAppList);
752 DestroyStrVector(&credential->authorizedDeviceList);
753 DeleteString(&credential->extendInfo);
754 HcFree(credential);
755 }
756
DeepCopyCredential(const Credential * entry)757 Credential *DeepCopyCredential(const Credential *entry)
758 {
759 Credential *returnEntry = CreateCredential();
760 if (returnEntry == NULL) {
761 return NULL;
762 }
763 if (!GenerateCredFromCred(entry, returnEntry)) {
764 DestroyCredential(returnEntry);
765 return NULL;
766 }
767 return returnEntry;
768 }
769
ClearCredentialVec(CredentialVec * vec)770 void ClearCredentialVec(CredentialVec *vec)
771 {
772 uint32_t index;
773 Credential **entry;
774 FOR_EACH_HC_VECTOR(*vec, index, entry) {
775 if (entry == NULL || *entry == NULL) {
776 continue;
777 }
778 DestroyCredential(*entry);
779 }
780 DESTROY_HC_VECTOR(CredentialVec, vec);
781 }
782
AddCredIdToReturn(const Credential * credInfo,CJson * json)783 static int32_t AddCredIdToReturn(const Credential *credInfo, CJson *json)
784 {
785 const char *credId = StringGet(&credInfo->credId);
786 if (credId == NULL) {
787 LOGE("[CRED#DB]: Failed to get credId from credInfo!");
788 return IS_ERR_NULL_PTR;
789 }
790 if (AddStringToJson(json, FIELD_CRED_ID, credId) != IS_SUCCESS) {
791 LOGE("[CRED#DB]: Failed to add credId to json!");
792 return IS_ERR_JSON_ADD;
793 }
794 PRINT_SENSITIVE_DATA("credId", credId);
795 return IS_SUCCESS;
796 }
797
AddCredTypeToReturn(const Credential * credInfo,CJson * json)798 static int32_t AddCredTypeToReturn(const Credential *credInfo, CJson *json)
799 {
800 uint8_t credType = credInfo->credType;
801 if (AddIntToJson(json, FIELD_CRED_TYPE, credType) != IS_SUCCESS) {
802 LOGE("[CRED#DB]: Failed to add credType to json!");
803 return IS_ERR_JSON_ADD;
804 }
805 LOGI("credType: %" LOG_PUB "u", credType);
806 return IS_SUCCESS;
807 }
808
AddUserIdToReturn(const Credential * credInfo,CJson * json)809 static int32_t AddUserIdToReturn(const Credential *credInfo, CJson *json)
810 {
811 const char *userId = StringGet(&credInfo->userId);
812 if (userId == NULL) {
813 LOGE("[CRED#DB]: Failed to get userId from credInfo!");
814 return IS_ERR_NULL_PTR;
815 }
816 if (AddStringToJson(json, FIELD_USER_ID, userId) != IS_SUCCESS) {
817 LOGE("[CRED#DB]: Failed to add userId to json!");
818 return IS_ERR_JSON_ADD;
819 }
820 return IS_SUCCESS;
821 }
822
AddSubjectToReturn(const Credential * credInfo,CJson * json)823 static int32_t AddSubjectToReturn(const Credential *credInfo, CJson *json)
824 {
825 uint8_t subject = credInfo->subject;
826 if (AddIntToJson(json, FIELD_SUBJECT, subject) != IS_SUCCESS) {
827 LOGE("[CRED#DB]: Failed to add subject to json!");
828 return IS_ERR_JSON_ADD;
829 }
830 return IS_SUCCESS;
831 }
832
AddIssuerToReturn(const Credential * credInfo,CJson * json)833 static int32_t AddIssuerToReturn(const Credential *credInfo, CJson *json)
834 {
835 uint8_t issuer = credInfo->issuer;
836 if (AddIntToJson(json, FIELD_ISSUER, issuer) != IS_SUCCESS) {
837 LOGE("[CRED#DB]: Failed to add issuer to json!");
838 return IS_ERR_JSON_ADD;
839 }
840 return IS_SUCCESS;
841 }
842
AddKeyFormatToReturn(const Credential * credInfo,CJson * json)843 static int32_t AddKeyFormatToReturn(const Credential *credInfo, CJson *json)
844 {
845 uint8_t keyFormat = credInfo->keyFormat;
846 if (AddIntToJson(json, FIELD_KEY_FORMAT, keyFormat) != IS_SUCCESS) {
847 LOGE("[CRED#DB]: Failed to add keyFormat to json!");
848 return IS_ERR_JSON_ADD;
849 }
850 return IS_SUCCESS;
851 }
852
AddProofTypeToReturn(const Credential * credInfo,CJson * json)853 static int32_t AddProofTypeToReturn(const Credential *credInfo, CJson *json)
854 {
855 uint8_t proofType = credInfo->proofType;
856 if (AddIntToJson(json, FIELD_PROOF_TYPE, proofType) != IS_SUCCESS) {
857 LOGE("[CRED#DB]: Failed to add proofType to json!");
858 return IS_ERR_JSON_ADD;
859 }
860 return IS_SUCCESS;
861 }
862
AddAuthorizedScopeToReturn(const Credential * credInfo,CJson * json)863 static int32_t AddAuthorizedScopeToReturn(const Credential *credInfo, CJson *json)
864 {
865 uint8_t authorizedScope = credInfo->authorizedScope;
866 if (AddIntToJson(json, FIELD_AUTHORIZED_SCOPE, authorizedScope) != IS_SUCCESS) {
867 LOGE("[CRED#DB]: Failed to add authorizedScope to json!");
868 return IS_ERR_JSON_ADD;
869 }
870 return IS_SUCCESS;
871 }
872
AddAlgorithmTypeToReturn(const Credential * credInfo,CJson * json)873 static int32_t AddAlgorithmTypeToReturn(const Credential *credInfo, CJson *json)
874 {
875 uint8_t algorithmType = credInfo->algorithmType;
876 if (AddIntToJson(json, FIELD_ALGORITHM_TYPE, algorithmType) != IS_SUCCESS) {
877 LOGE("[CRED#DB]: Failed to add algorithmType to json!");
878 return IS_ERR_JSON_ADD;
879 }
880 return IS_SUCCESS;
881 }
882
AddDeviceIdToReturn(const Credential * credInfo,CJson * json)883 static int32_t AddDeviceIdToReturn(const Credential *credInfo, CJson *json)
884 {
885 const char *deviceId = StringGet(&credInfo->deviceId);
886 if (deviceId == NULL) {
887 LOGE("[CRED#DB]: Failed to get deviceId from credInfo!");
888 return IS_ERR_NULL_PTR;
889 }
890 if (AddStringToJson(json, FIELD_DEVICE_ID, deviceId) != IS_SUCCESS) {
891 LOGE("[CRED#DB]: Failed to add deviceId to json!");
892 return IS_ERR_JSON_ADD;
893 }
894 return IS_SUCCESS;
895 }
896
AddCredOwnerToReturn(const Credential * credInfo,CJson * json)897 static int32_t AddCredOwnerToReturn(const Credential *credInfo, CJson *json)
898 {
899 const char *credOwner = StringGet(&credInfo->credOwner);
900 if (credOwner == NULL) {
901 LOGE("[CRED#DB]: Failed to get credOwner from credInfo!");
902 return IS_ERR_NULL_PTR;
903 }
904 if (AddStringToJson(json, FIELD_CRED_OWNER, credOwner) != IS_SUCCESS) {
905 LOGE("[CRED#DB]: Failed to add credOwner to json!");
906 return IS_ERR_JSON_ADD;
907 }
908 return IS_SUCCESS;
909 }
910
AddExtendInfoToReturn(const Credential * credInfo,CJson * json)911 static int32_t AddExtendInfoToReturn(const Credential *credInfo, CJson *json)
912 {
913 const char *extendInfo = StringGet(&credInfo->extendInfo);
914 if (extendInfo == NULL) {
915 LOGE("[CRED#DB]: Failed to get extendInfo from credInfo!");
916 return IS_ERR_NULL_PTR;
917 }
918 if (AddStringToJson(json, FIELD_EXTEND_INFO, extendInfo) != IS_SUCCESS) {
919 LOGE("[CRED#DB]: Failed to add extendInfo to json!");
920 return IS_ERR_JSON_ADD;
921 }
922 return IS_SUCCESS;
923 }
924
AddPeerUserSpaceIdToReturn(const Credential * credInfo,CJson * json)925 static int32_t AddPeerUserSpaceIdToReturn(const Credential *credInfo, CJson *json)
926 {
927 const char *peerUserSpaceId = StringGet(&credInfo->peerUserSpaceId);
928 if (peerUserSpaceId == NULL) {
929 LOGE("[CRED#DB]: Failed to get peerUserSpaceId from credInfo!");
930 return IS_ERR_NULL_PTR;
931 }
932 if (AddStringToJson(json, FIELD_PEER_USER_SPACE_ID, peerUserSpaceId) != IS_SUCCESS) {
933 LOGE("[CRED#DB]: Failed to add peerUserSpaceId to json!");
934 return IS_ERR_JSON_ADD;
935 }
936 return IS_SUCCESS;
937 }
938
AddAuthorizedAppListToReturn(const Credential * credInfo,CJson * json)939 static int32_t AddAuthorizedAppListToReturn(const Credential *credInfo, CJson *json)
940 {
941 CJson *arr = CreateJsonArray();
942 if (arr == NULL) {
943 LOGE("Failed to allocate json memory!");
944 return IS_ERR_JSON_CREATE;
945 }
946 uint32_t index = 0;
947 HcString *authorizedApp = NULL;
948 FOR_EACH_HC_VECTOR(credInfo->authorizedAppList, index, authorizedApp) {
949 if (authorizedApp == NULL) {
950 continue;
951 }
952 if (AddStringToArray(arr, StringGet(authorizedApp)) != IS_SUCCESS) {
953 FreeJson(arr);
954 LOGE("[CRED#DB]: Failed to add authorizedApp to json!");
955 return IS_ERR_JSON_ADD;
956 }
957 }
958 if (AddObjToJson(json, FIELD_AUTHORIZED_APP_LIST, arr) != IS_SUCCESS) {
959 FreeJson(arr);
960 LOGE("[CRED#DB]: Failed to add authorizedApp to json!");
961 return IS_ERR_JSON_ADD;
962 }
963 FreeJson(arr);
964 return IS_SUCCESS;
965 }
966
GenerateReturnCredInfo(const Credential * credential,CJson * returnJson)967 int32_t GenerateReturnCredInfo(const Credential *credential, CJson *returnJson)
968 {
969 int32_t result;
970 if (((result = AddCredIdToReturn(credential, returnJson)) != IS_SUCCESS) ||
971 ((result = AddDeviceIdToReturn(credential, returnJson)) != IS_SUCCESS) ||
972 ((result = AddPeerUserSpaceIdToReturn(credential, returnJson)) != IS_SUCCESS) ||
973 ((result = AddSubjectToReturn(credential, returnJson)) != IS_SUCCESS) ||
974 ((result = AddUserIdToReturn(credential, returnJson)) != IS_SUCCESS) ||
975 ((result = AddIssuerToReturn(credential, returnJson)) != IS_SUCCESS) ||
976 ((result = AddCredTypeToReturn(credential, returnJson)) != IS_SUCCESS) ||
977 ((result = AddKeyFormatToReturn(credential, returnJson)) != IS_SUCCESS) ||
978 ((result = AddAlgorithmTypeToReturn(credential, returnJson)) != IS_SUCCESS) ||
979 ((result = AddProofTypeToReturn(credential, returnJson)) != IS_SUCCESS) ||
980 ((result = AddCredOwnerToReturn(credential, returnJson)) != IS_SUCCESS) ||
981 ((result = AddAuthorizedAppListToReturn(credential, returnJson)) != IS_SUCCESS) ||
982 ((result = AddAuthorizedScopeToReturn(credential, returnJson)) != IS_SUCCESS) ||
983 ((result = AddExtendInfoToReturn(credential, returnJson)) != IS_SUCCESS)) {
984 return result;
985 }
986 return IS_SUCCESS;
987 }
988
GenerateCredInfoFromCredential(const Credential * entry,CJson * credInfo)989 static int32_t GenerateCredInfoFromCredential(const Credential *entry, CJson *credInfo)
990 {
991 if (AddCredTypeToReturn(entry, credInfo) != IS_SUCCESS) {
992 LOGE("add cretype to json failed.");
993 return IS_ERR_JSON_ADD;
994 }
995 if (AddDeviceIdToReturn(entry, credInfo) != IS_SUCCESS) {
996 LOGE("add deviceId to json failed.");
997 return IS_ERR_JSON_ADD;
998 }
999 if (AddUserIdToReturn(entry, credInfo) != IS_SUCCESS) {
1000 LOGE("add userId to json failed.");
1001 return IS_ERR_JSON_ADD;
1002 }
1003 if (AddSubjectToReturn(entry, credInfo) != IS_SUCCESS) {
1004 LOGE("add userId to json failed.");
1005 return IS_ERR_JSON_ADD;
1006 }
1007 return IS_SUCCESS;
1008 }
1009
GenerateCredChangedInfo(const Credential * entry,char ** returnCredInfo)1010 static int32_t GenerateCredChangedInfo(const Credential *entry, char **returnCredInfo)
1011 {
1012 CJson *credInfo = CreateJson();
1013 if (credInfo == NULL) {
1014 LOGE("create json failed.");
1015 return IS_ERR_ALLOC_MEMORY;
1016 }
1017 if (GenerateCredInfoFromCredential(entry, credInfo) != IS_SUCCESS) {
1018 FreeJson(credInfo);
1019 return IS_ERR_JSON_ADD;
1020 }
1021 char *credInfoJsonStr = PackJsonToString(credInfo);
1022 FreeJson(credInfo);
1023 if (credInfoJsonStr == NULL) {
1024 LOGE("pack credInfo json to string failed.");
1025 return IS_ERR_ALLOC_MEMORY;
1026 }
1027 *returnCredInfo = credInfoJsonStr;
1028 return IS_SUCCESS;
1029 }
1030
GenerateDeleteCredInfo(const Credential * entry,int32_t osAccountId,char ** returnCredInfo)1031 static int32_t GenerateDeleteCredInfo(const Credential *entry, int32_t osAccountId, char **returnCredInfo)
1032 {
1033 CJson *credInfo = CreateJson();
1034 if (credInfo == NULL) {
1035 LOGE("create json failed.");
1036 return IS_ERR_ALLOC_MEMORY;
1037 }
1038 int32_t ret = GenerateCredInfoFromCredential(entry, credInfo);
1039 if (ret != IS_SUCCESS) {
1040 FreeJson(credInfo);
1041 return ret;
1042 }
1043 if (AddIntToJson(credInfo, FIELD_OS_ACCOUNT_ID, osAccountId) != IS_SUCCESS) {
1044 FreeJson(credInfo);
1045 return IS_ERR_JSON_ADD;
1046 }
1047 char *credInfoJsonStr = PackJsonToString(credInfo);
1048 FreeJson(credInfo);
1049 if (credInfoJsonStr == NULL) {
1050 LOGE("pack json to string failed.");
1051 return IS_ERR_ALLOC_MEMORY;
1052 }
1053 *returnCredInfo = credInfoJsonStr;
1054 return IS_SUCCESS;
1055 }
1056
PostCredAddMsg(const Credential * entry)1057 static void PostCredAddMsg(const Credential *entry)
1058 {
1059 if (!IsCredListenerSupported()) {
1060 return;
1061 }
1062 char *returnCredInfo = NULL;
1063 if (GenerateCredChangedInfo(entry, &returnCredInfo) != IS_SUCCESS) {
1064 return;
1065 }
1066 OnCredAdd(StringGet(&entry->credId), returnCredInfo);
1067 FreeJsonString(returnCredInfo);
1068 }
1069
PostCredUpdateMsg(const Credential * entry)1070 static void PostCredUpdateMsg(const Credential *entry)
1071 {
1072 if (!IsCredListenerSupported()) {
1073 return;
1074 }
1075 char *returnCredInfo = NULL;
1076 if (GenerateCredChangedInfo(entry, &returnCredInfo) != IS_SUCCESS) {
1077 return;
1078 }
1079 OnCredUpdate(StringGet(&entry->credId), returnCredInfo);
1080 FreeJsonString(returnCredInfo);
1081 }
1082
PostCredDeleteMsg(const Credential * entry,int32_t osAccountId)1083 static void PostCredDeleteMsg(const Credential *entry, int32_t osAccountId)
1084 {
1085 if (!IsCredListenerSupported()) {
1086 return;
1087 }
1088 char *returnCredInfo = NULL;
1089 if (GenerateDeleteCredInfo(entry, osAccountId, &returnCredInfo) != IS_SUCCESS) {
1090 return;
1091 }
1092 OnCredDelete(StringGet(&entry->credId), returnCredInfo);
1093 FreeJsonString(returnCredInfo);
1094 }
1095
AddCredToDb(int32_t osAccountId,const Credential * entry)1096 int32_t AddCredToDb(int32_t osAccountId, const Credential *entry)
1097 {
1098 LOGI("[CRED#DB]: Start to add a cred to database! [OsAccountId]: %" LOG_PUB "d", osAccountId);
1099 if (entry == NULL) {
1100 LOGE("[CRED#DB]: The input entry is NULL!");
1101 return IS_ERR_NULL_PTR;
1102 }
1103 (void)LockHcMutex(g_credMutex);
1104 OsAccountCredInfo *info = GetCredInfoByOsAccountId(osAccountId);
1105 if (info == NULL) {
1106 UnlockHcMutex(g_credMutex);
1107 return IS_ERR_INVALID_PARAMS;
1108 }
1109 Credential *newEntry = DeepCopyCredential(entry);
1110 if (newEntry == NULL) {
1111 UnlockHcMutex(g_credMutex);
1112 return IS_ERR_MEMORY_COPY;
1113 }
1114 QueryCredentialParams params = InitQueryCredentialParams();
1115 params.credId = StringGet(&entry->credId);
1116 Credential **oldEntryPtr = QueryCredentialPtrIfMatch(&info->credentials, ¶ms);
1117 if (oldEntryPtr != NULL) {
1118 DestroyCredential(*oldEntryPtr);
1119 *oldEntryPtr = newEntry;
1120 PostCredUpdateMsg(newEntry);
1121 UnlockHcMutex(g_credMutex);
1122 LOGI("[CRED#DB]: Update an old credential successfully! [credType]: %" LOG_PUB "u", entry->credType);
1123 return IS_SUCCESS;
1124 }
1125 if (info->credentials.pushBackT(&info->credentials, newEntry) == NULL) {
1126 DestroyCredential(newEntry);
1127 UnlockHcMutex(g_credMutex);
1128 LOGE("[CRED#DB]: Failed to push credential to vec!");
1129 return IS_ERR_MEMORY_COPY;
1130 }
1131 PostCredAddMsg(newEntry);
1132 UnlockHcMutex(g_credMutex);
1133 LOGI("[CRED#DB]: Add a credential to database successfully! [credType]: %" LOG_PUB "u", entry->credType);
1134 return IS_SUCCESS;
1135 }
1136
DelCredential(int32_t osAccountId,const QueryCredentialParams * params)1137 int32_t DelCredential(int32_t osAccountId, const QueryCredentialParams *params)
1138 {
1139 LOGI("[CRED#DB]: Start to delete credential from database! [OsAccountId]: %" LOG_PUB "d", osAccountId);
1140 if (params == NULL) {
1141 LOGE("[CRED#DB]: The input params is NULL!");
1142 return IS_ERR_NULL_PTR;
1143 }
1144 (void)LockHcMutex(g_credMutex);
1145 OsAccountCredInfo *info = GetCredInfoByOsAccountId(osAccountId);
1146 if (info == NULL) {
1147 UnlockHcMutex(g_credMutex);
1148 return IS_ERR_INVALID_PARAMS;
1149 }
1150 int32_t count = 0;
1151 uint32_t index = 0;
1152 Credential **entry = NULL;
1153 while (index < HC_VECTOR_SIZE(&info->credentials)) {
1154 entry = info->credentials.getp(&info->credentials, index);
1155 if ((entry == NULL) || (*entry == NULL) || (!CompareQueryCredentialParams(params, *entry))) {
1156 index++;
1157 continue;
1158 }
1159 Credential *popEntry;
1160 HC_VECTOR_POPELEMENT(&info->credentials, &popEntry, index);
1161 PostCredDeleteMsg(popEntry, osAccountId);
1162 LOGI("[CRED#DB]: Delete a credential from database successfully! [credType]: %" LOG_PUB "u",
1163 popEntry->credType);
1164 DestroyCredential(popEntry);
1165 count++;
1166 }
1167 UnlockHcMutex(g_credMutex);
1168 LOGI("[CRED#DB]: Number of credentials deleted: %" LOG_PUB "d", count);
1169 return IS_SUCCESS;
1170 }
1171
QueryCredentials(int32_t osAccountId,const QueryCredentialParams * params,CredentialVec * vec)1172 int32_t QueryCredentials(int32_t osAccountId, const QueryCredentialParams *params, CredentialVec *vec)
1173 {
1174 if ((params == NULL) || (vec == NULL)) {
1175 LOGE("[CRED#DB]: The input params or vec is NULL!");
1176 return IS_ERR_NULL_PTR;
1177 }
1178 (void)LockHcMutex(g_credMutex);
1179 OsAccountCredInfo *info = GetCredInfoByOsAccountId(osAccountId);
1180 if (info == NULL) {
1181 UnlockHcMutex(g_credMutex);
1182 return IS_ERR_INVALID_PARAMS;
1183 }
1184 uint32_t index;
1185 Credential **entry;
1186 FOR_EACH_HC_VECTOR(info->credentials, index, entry) {
1187 if (entry == NULL || *entry == NULL || !CompareQueryCredentialParams(params, *entry)) {
1188 continue;
1189 }
1190 Credential *newEntry = DeepCopyCredential(*entry);
1191 if (newEntry == NULL) {
1192 continue;
1193 }
1194 if (vec->pushBackT(vec, newEntry) == NULL) {
1195 LOGE("[CRED#DB]: Failed to push entry to vec!");
1196 DestroyCredential(newEntry);
1197 }
1198 }
1199 UnlockHcMutex(g_credMutex);
1200 return IS_SUCCESS;
1201 }
1202
SaveOsAccountCredDb(int32_t osAccountId)1203 int32_t SaveOsAccountCredDb(int32_t osAccountId)
1204 {
1205 (void)LockHcMutex(g_credMutex);
1206 OsAccountCredInfo *info = GetCredInfoByOsAccountId(osAccountId);
1207 if (info == NULL) {
1208 UnlockHcMutex(g_credMutex);
1209 return IS_ERR_INVALID_PARAMS;
1210 }
1211 HcParcel parcel = CreateParcel(0, 0);
1212 if (!SaveCredInfoToParcel(info, &parcel)) {
1213 DeleteParcel(&parcel);
1214 UnlockHcMutex(g_credMutex);
1215 return IS_ERR_MEMORY_COPY;
1216 }
1217 char filePath[MAX_DB_PATH_LEN] = { 0 };
1218 if (!GetOsAccountCredInfoPath(osAccountId, filePath, MAX_DB_PATH_LEN)) {
1219 DeleteParcel(&parcel);
1220 UnlockHcMutex(g_credMutex);
1221 return IS_ERR_CONVERT_FAILED;
1222 }
1223 if (!SaveParcelToFile(filePath, &parcel)) {
1224 DeleteParcel(&parcel);
1225 UnlockHcMutex(g_credMutex);
1226 return IS_ERR_MEMORY_COPY;
1227 }
1228 DeleteParcel(&parcel);
1229 UnlockHcMutex(g_credMutex);
1230 LOGI("[CRED#DB]: Save an os account cred database successfully! [Id]: %" LOG_PUB "d", osAccountId);
1231 return IS_SUCCESS;
1232 }
1233
1234 #ifdef DEV_AUTH_HIVIEW_ENABLE
DumpCredential(int fd,const Credential * credential)1235 static void DumpCredential(int fd, const Credential *credential)
1236 {
1237 dprintf(fd, "||--------------------------Credential--------------------------| |\n");
1238 dprintf(fd, "||%-16s = %-43.8s| |\n", "credId", StringGet(&credential->credId));
1239 dprintf(fd, "||%-16s = %-43.8s| |\n", "deviceId", StringGet(&credential->deviceId));
1240 dprintf(fd, "||%-16s = %-43.8s| |\n", "peerUserSpaceId", StringGet(&credential->peerUserSpaceId));
1241 dprintf(fd, "||%-16s = %-43d| |\n", "subject", credential->subject);
1242 dprintf(fd, "||%-16s = %-43.8s| |\n", "userId", StringGet(&credential->userId));
1243 dprintf(fd, "||%-16s = %-43d| |\n", "issuer", credential->issuer);
1244 dprintf(fd, "||%-16s = %-43d| |\n", "credType", credential->credType);
1245 dprintf(fd, "||%-16s = %-43d| |\n", "keyFormat", credential->keyFormat);
1246 dprintf(fd, "||%-16s = %-43d| |\n", "algorithmType", credential->algorithmType);
1247 dprintf(fd, "||%-16s = %-43d| |\n", "proofType", credential->proofType);
1248 uint32_t index = 0;
1249 HcString *authorizedApp = NULL;
1250 FOR_EACH_HC_VECTOR(credential->authorizedAppList, index, authorizedApp) {
1251 if (authorizedApp == NULL) {
1252 continue;
1253 }
1254 dprintf(fd, "||%-16s %d = %-43.8s| |\n", "app", index, StringGet(authorizedApp));
1255 }
1256 dprintf(fd, "||%-16s = %-43d| |\n", "authorizedScope", credential->authorizedScope);
1257 dprintf(fd, "||%-16s = %-43.8s| |\n", "credOwner", StringGet(&credential->credOwner));
1258 dprintf(fd, "||%-16s = %-43.8s| |\n", "extendInfo", StringGet(&credential->extendInfo));
1259 dprintf(fd, "||--------------------------Credential--------------------------| |\n");
1260 }
1261
DumpDb(int fd,const OsAccountCredInfo * db)1262 static void DumpDb(int fd, const OsAccountCredInfo *db)
1263 {
1264 const CredentialVec *credentials = &db->credentials;
1265 dprintf(fd, "|----------------------------------CRED-DataBase-----------------------------------|\n");
1266 dprintf(fd, "|%-13s = %-66d|\n", "osAccountId", db->osAccountId);
1267 dprintf(fd, "|%-13s = %-66d|\n", "credentialNum", credentials->size(credentials));
1268 uint32_t index;
1269 Credential **credential;
1270 FOR_EACH_HC_VECTOR(*credentials, index, credential) {
1271 if (credential == NULL || *credential == NULL) {
1272 continue;
1273 }
1274 DumpCredential(fd, *credential);
1275 }
1276 dprintf(fd, "|----------------------------------CRED-DataBase-----------------------------------|\n");
1277 }
1278
LoadAllAccountsData(void)1279 static void LoadAllAccountsData(void)
1280 {
1281 int32_t *accountIds = NULL;
1282 uint32_t size = 0;
1283 int32_t ret = GetAllOsAccountIds(&accountIds, &size);
1284 if (ret != IS_SUCCESS) {
1285 LOGE("[CRED#DB]: Failed to get all os account ids, [res]: %" LOG_PUB "d", ret);
1286 return;
1287 }
1288 for (uint32_t index = 0; index < size; index++) {
1289 LoadDataIfNotLoaded(accountIds[index]);
1290 }
1291 HcFree(accountIds);
1292 }
1293
DevAuthDataBaseDump(int fd)1294 static void DevAuthDataBaseDump(int fd)
1295 {
1296 if (g_credMutex == NULL) {
1297 LOGE("[CRED#DB]: Init mutex failed");
1298 return;
1299 }
1300 (void)LockHcMutex(g_credMutex);
1301 if (IsOsAccountSupported()) {
1302 LoadAllAccountsData();
1303 }
1304 uint32_t index;
1305 OsAccountCredInfo *info;
1306 FOR_EACH_HC_VECTOR(g_devauthCredDb, index, info) {
1307 if (info == NULL) {
1308 continue;
1309 }
1310 DumpDb(fd, info);
1311 }
1312 UnlockHcMutex(g_credMutex);
1313 }
1314 #endif
1315
InitCredDatabase(void)1316 int32_t InitCredDatabase(void)
1317 {
1318 if (g_credMutex == NULL) {
1319 g_credMutex = (HcMutex *)HcMalloc(sizeof(HcMutex), 0);
1320 if (g_credMutex == NULL) {
1321 LOGE("[CRED#DB]: Alloc cred databaseMutex failed");
1322 return IS_ERR_ALLOC_MEMORY;
1323 }
1324 if (InitHcMutex(g_credMutex, false) != IS_SUCCESS) {
1325 LOGE("[CRED#DB]: Init mutex failed");
1326 HcFree(g_credMutex);
1327 g_credMutex = NULL;
1328 return IS_ERR_INIT_FAILED;
1329 }
1330 }
1331 g_devauthCredDb = CREATE_HC_VECTOR(DevAuthCredDb);
1332 AddOsAccountEventCallback(CRED_DATA_CALLBACK, OnOsAccountUnlocked, OnOsAccountRemoved);
1333 LoadDevAuthCredDb();
1334 DEV_AUTH_REG_CRED_DUMP_FUNC(DevAuthDataBaseDump);
1335 return IS_SUCCESS;
1336 }
1337
DestroyCredDatabase(void)1338 void DestroyCredDatabase(void)
1339 {
1340 RemoveOsAccountEventCallback(CRED_DATA_CALLBACK);
1341 (void)LockHcMutex(g_credMutex);
1342 uint32_t index;
1343 OsAccountCredInfo *info;
1344 FOR_EACH_HC_VECTOR(g_devauthCredDb, index, info) {
1345 if (info == NULL) {
1346 continue;
1347 }
1348 ClearCredentialVec(&info->credentials);
1349 }
1350 DESTROY_HC_VECTOR(DevAuthCredDb, &g_devauthCredDb);
1351 UnlockHcMutex(g_credMutex);
1352 DestroyHcMutex(g_credMutex);
1353 HcFree(g_credMutex);
1354 g_credMutex = NULL;
1355 }