1 /*
2 * Copyright (C) 2022 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 "asy_token_manager.h"
17 #include "account_module_defines.h"
18 #include "alg_loader.h"
19 #include "common_defs.h"
20 #include "hc_dev_info.h"
21 #include "hal_error.h"
22 #include "hc_file.h"
23 #include "hc_log.h"
24 #include "hc_mutex.h"
25 #include "hc_types.h"
26 #include "string_util.h"
27
28 IMPLEMENT_HC_VECTOR(AccountTokenVec, AccountToken*, 1)
29
30 typedef struct {
31 int32_t osAccountId;
32 AccountTokenVec tokens;
33 } OsAccountTokenInfo;
34
35 DECLARE_HC_VECTOR(AccountTokenDb, OsAccountTokenInfo)
36 IMPLEMENT_HC_VECTOR(AccountTokenDb, OsAccountTokenInfo, 1)
37
38 #define MAX_DB_PATH_LEN 256
39 #define SELF_ECC_KEY_LEN 32
40
41 AccountAuthTokenManager g_asyTokenManager;
42
43 static const AlgLoader *g_algLoader = NULL;
44 static bool g_isInitial = false;
45 static AccountTokenDb g_accountTokenDb;
46 static HcMutex *g_accountDbMutex;
47
GeneratePkInfoFromJson(PkInfo * info,const CJson * pkInfoJson)48 static int32_t GeneratePkInfoFromJson(PkInfo *info, const CJson *pkInfoJson)
49 {
50 if (GetByteFromJson(pkInfoJson, FIELD_DEVICE_PK, info->devicePk.val, info->devicePk.length) != HC_SUCCESS) {
51 LOGE("get devicePk failed");
52 return HC_ERR_JSON_GET;
53 }
54 const char *devicePk = GetStringFromJson(pkInfoJson, FIELD_DEVICE_PK);
55 info->devicePk.length = HcStrlen(devicePk) / BYTE_TO_HEX_OPER_LENGTH;
56 const char *version = GetStringFromJson(pkInfoJson, FIELD_VERSION);
57 if (version == NULL) {
58 LOGE("get version failed");
59 return HC_ERR_JSON_GET;
60 }
61 if (memcpy_s(info->version.val, info->version.length, version, HcStrlen(version) + 1) != EOK) {
62 LOGE("memcpy_s version failed");
63 return HC_ERR_MEMORY_COPY;
64 }
65 info->version.length = HcStrlen(version) + 1;
66 const char *deviceId = GetStringFromJson(pkInfoJson, FIELD_DEVICE_ID);
67 if (deviceId == NULL) {
68 LOGE("get deviceId failed");
69 return HC_ERR_JSON_GET;
70 }
71 if (memcpy_s(info->deviceId.val, info->deviceId.length, deviceId, HcStrlen(deviceId) + 1) != EOK) {
72 LOGE("memcpy_s deviceId failed");
73 return HC_ERR_MEMORY_COPY;
74 }
75 info->deviceId.length = HcStrlen(deviceId) + 1;
76 const char *userId = GetStringFromJson(pkInfoJson, FIELD_USER_ID);
77 if (userId == NULL) {
78 LOGE("get userId failed");
79 return HC_ERR_JSON_GET;
80 }
81 if (memcpy_s(info->userId.val, info->userId.length, userId, HcStrlen(userId) + 1) != EOK) {
82 LOGE("memcpy_s userId failed");
83 return HC_ERR_MEMORY_COPY;
84 }
85 info->userId.length = HcStrlen(userId) + 1;
86 return HC_SUCCESS;
87 }
88
GetTokenPath(int32_t osAccountId,char * tokenPath,uint32_t pathBufferLen)89 static bool GetTokenPath(int32_t osAccountId, char *tokenPath, uint32_t pathBufferLen)
90 {
91 const char *beginPath = GetAccountStoragePath();
92 if (beginPath == NULL) {
93 LOGE("Failed to get the account storage path!");
94 return false;
95 }
96 int32_t writeByteNum;
97 if (osAccountId == DEFAULT_OS_ACCOUNT) {
98 writeByteNum = sprintf_s(tokenPath, pathBufferLen, "%s/account_data_asy.dat", beginPath);
99 } else {
100 writeByteNum = sprintf_s(tokenPath, pathBufferLen, "%s/account_data_asy%d.dat", beginPath, osAccountId);
101 }
102 if (writeByteNum <= 0) {
103 LOGE("sprintf_s fail!");
104 return false;
105 }
106 return true;
107 }
108
GenerateTokenFromJson(const CJson * tokenJson,AccountToken * token)109 static int32_t GenerateTokenFromJson(const CJson *tokenJson, AccountToken *token)
110 {
111 CJson *pkInfoJson = GetObjFromJson(tokenJson, FIELD_PK_INFO);
112 if (pkInfoJson == NULL) {
113 LOGE("Failed to get pkInfoJson");
114 return HC_ERR_JSON_GET;
115 }
116 char *pkInfoStr = PackJsonToString(pkInfoJson);
117 if (pkInfoStr == NULL) {
118 LOGE("Pack pkInfoStr failed");
119 return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
120 }
121 if (memcpy_s(token->pkInfoStr.val, token->pkInfoStr.length, pkInfoStr, HcStrlen(pkInfoStr) + 1) != EOK) {
122 LOGE("Memcpy failed for pkInfoStr");
123 FreeJsonString(pkInfoStr);
124 return HC_ERR_MEMORY_COPY;
125 }
126 token->pkInfoStr.length = HcStrlen(pkInfoStr) + 1;
127 FreeJsonString(pkInfoStr);
128 if (GetByteFromJson(tokenJson, FIELD_PK_INFO_SIGNATURE, token->pkInfoSignature.val,
129 token->pkInfoSignature.length) != HC_SUCCESS) {
130 LOGE("Get pkInfoSignature failed");
131 return HC_ERR_JSON_GET;
132 }
133 const char *signatureStr = GetStringFromJson(tokenJson, FIELD_PK_INFO_SIGNATURE);
134 token->pkInfoSignature.length = HcStrlen(signatureStr) / BYTE_TO_HEX_OPER_LENGTH;
135 if (GetByteFromJson(tokenJson, FIELD_SERVER_PK, token->serverPk.val,
136 token->serverPk.length) != HC_SUCCESS) {
137 LOGE("Get serverPk failed");
138 return HC_ERR_JSON_GET;
139 }
140 const char *serverPkStr = GetStringFromJson(tokenJson, FIELD_SERVER_PK);
141 token->serverPk.length = HcStrlen(serverPkStr) / BYTE_TO_HEX_OPER_LENGTH;
142 int32_t ret = GeneratePkInfoFromJson(&token->pkInfo, pkInfoJson);
143 if (ret != HC_SUCCESS) {
144 LOGE("Generate pkInfo failed");
145 return ret;
146 }
147 return HC_SUCCESS;
148 }
149
CreateTokensFromJson(CJson * tokensJson,AccountTokenVec * vec)150 static int32_t CreateTokensFromJson(CJson *tokensJson, AccountTokenVec *vec)
151 {
152 int32_t tokenNum = GetItemNum(tokensJson);
153 if (tokenNum <= 0) {
154 LOGE("No token found.");
155 return HC_ERR_JSON_GET;
156 }
157 int32_t ret;
158 for (int32_t i = 0; i < tokenNum; i++) {
159 CJson *tokenJson = GetItemFromArray(tokensJson, i);
160 if (tokenJson == NULL) {
161 LOGE("Token json is null");
162 ClearAccountTokenVec(vec);
163 return HC_ERR_JSON_GET;
164 }
165 AccountToken *token = CreateAccountToken();
166 if (token == NULL) {
167 LOGE("Failed to create token");
168 ClearAccountTokenVec(vec);
169 return HC_ERR_ALLOC_MEMORY;
170 }
171 ret = GenerateTokenFromJson(tokenJson, token);
172 if (ret != HC_SUCCESS) {
173 LOGE("Generate token failed");
174 DestroyAccountToken(token);
175 ClearAccountTokenVec(vec);
176 return ret;
177 }
178 if (vec->pushBackT(vec, token) == NULL) {
179 LOGE("Failed to push token to vec");
180 DestroyAccountToken(token);
181 ClearAccountTokenVec(vec);
182 return HC_ERR_MEMORY_COPY;
183 }
184 }
185 return HC_SUCCESS;
186 }
187
OpenTokenFile(int32_t osAccountId,FileHandle * file,int32_t mode)188 static int32_t OpenTokenFile(int32_t osAccountId, FileHandle *file, int32_t mode)
189 {
190 char *tokenPath = (char *)HcMalloc(MAX_DB_PATH_LEN, 0);
191 if (tokenPath == NULL) {
192 LOGE("Malloc tokenPath failed");
193 return HC_ERR_ALLOC_MEMORY;
194 }
195 if (!GetTokenPath(osAccountId, tokenPath, MAX_DB_PATH_LEN)) {
196 LOGE("Get token path failed");
197 HcFree(tokenPath);
198 return HC_ERROR;
199 }
200 int32_t ret = HcFileOpen(tokenPath, mode, file);
201 HcFree(tokenPath);
202 return ret;
203 }
204
ReadTokensFromFile(int32_t osAccountId,AccountTokenVec * vec)205 static int32_t ReadTokensFromFile(int32_t osAccountId, AccountTokenVec *vec)
206 {
207 if (vec == NULL) {
208 LOGE("Input token vec is null.");
209 return HC_ERR_NULL_PTR;
210 }
211 FileHandle file = { 0 };
212 int32_t ret = OpenTokenFile(osAccountId, &file, MODE_FILE_READ);
213 if (ret != HC_SUCCESS) {
214 LOGE("Open token file failed");
215 return ret;
216 }
217 int32_t fileSize = HcFileSize(file);
218 if (fileSize <= 0) {
219 LOGE("file size stat failed");
220 HcFileClose(file);
221 return HC_ERROR;
222 }
223 char *fileData = (char *)HcMalloc(fileSize, 0);
224 if (fileData == NULL) {
225 LOGE("Malloc file data failed");
226 HcFileClose(file);
227 return HC_ERR_ALLOC_MEMORY;
228 }
229 if (HcFileRead(file, fileData, fileSize) != fileSize) {
230 LOGE("fileData read failed");
231 HcFileClose(file);
232 HcFree(fileData);
233 return HC_ERROR;
234 }
235 HcFileClose(file);
236 CJson *readJsonFile = CreateJsonFromString(fileData);
237 HcFree(fileData);
238 if (readJsonFile == NULL) {
239 LOGE("fileData parse failed");
240 return HC_ERR_JSON_CREATE;
241 }
242 ret = CreateTokensFromJson(readJsonFile, vec);
243 FreeJson(readJsonFile);
244 if (ret != HC_SUCCESS) {
245 LOGE("Failed to create tokens from json");
246 }
247 return ret;
248 }
249
WriteTokensJsonToFile(int32_t osAccountId,CJson * tokensJson)250 static int32_t WriteTokensJsonToFile(int32_t osAccountId, CJson *tokensJson)
251 {
252 char *storeJsonString = PackJsonToString(tokensJson);
253 if (storeJsonString == NULL) {
254 LOGE("Pack stored json to string failed.");
255 return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
256 }
257 FileHandle file = { 0 };
258 int32_t ret = OpenTokenFile(osAccountId, &file, MODE_FILE_WRITE);
259 if (ret != HC_SUCCESS) {
260 LOGE("Open token file failed.");
261 FreeJsonString(storeJsonString);
262 return ret;
263 }
264 int32_t fileSize = (int32_t)(HcStrlen(storeJsonString) + 1);
265 if (HcFileWrite(file, storeJsonString, fileSize) != fileSize) {
266 LOGE("Failed to write token array to file.");
267 ret = HC_ERR_FILE;
268 }
269 FreeJsonString(storeJsonString);
270 HcFileClose(file);
271 return ret;
272 }
273
GenerateJsonFromToken(AccountToken * token,CJson * tokenJson)274 static int32_t GenerateJsonFromToken(AccountToken *token, CJson *tokenJson)
275 {
276 CJson *pkInfoJson = CreateJsonFromString((const char *)token->pkInfoStr.val);
277 if (pkInfoJson == NULL) {
278 LOGE("Failed to create pkInfoJson");
279 return HC_ERR_JSON_CREATE;
280 }
281 if (AddObjToJson(tokenJson, FIELD_PK_INFO, pkInfoJson) != HC_SUCCESS) {
282 LOGE("Add pkInfoJson to json failed");
283 FreeJson(pkInfoJson);
284 return HC_ERR_JSON_ADD;
285 }
286 FreeJson(pkInfoJson);
287 if (AddByteToJson(tokenJson, FIELD_PK_INFO_SIGNATURE, token->pkInfoSignature.val,
288 token->pkInfoSignature.length) != HC_SUCCESS) {
289 LOGE("Add pkInfoSignature to json failed");
290 return HC_ERR_JSON_ADD;
291 }
292 if (AddByteToJson(tokenJson, FIELD_SERVER_PK, token->serverPk.val,
293 token->serverPk.length) != HC_SUCCESS) {
294 LOGE("Add serverPk to json failed");
295 return HC_ERR_JSON_ADD;
296 }
297 return HC_SUCCESS;
298 }
299
SaveTokensToFile(int32_t osAccountId,const AccountTokenVec * vec)300 static int32_t SaveTokensToFile(int32_t osAccountId, const AccountTokenVec *vec)
301 {
302 CJson *storeJson = CreateJsonArray();
303 if (storeJson == NULL) {
304 LOGE("Create json failed when save tokens to file.");
305 return HC_ERR_JSON_CREATE;
306 }
307 int32_t ret;
308 uint32_t index;
309 AccountToken **token;
310 FOR_EACH_HC_VECTOR(*vec, index, token) {
311 CJson *tokenJson = CreateJson();
312 if (tokenJson == NULL) {
313 LOGE("Create token json failed.");
314 FreeJson(storeJson);
315 return HC_ERR_JSON_CREATE;
316 }
317 ret = GenerateJsonFromToken(*token, tokenJson);
318 if (ret != HC_SUCCESS) {
319 LOGE("Generate json from token failed");
320 FreeJson(tokenJson);
321 FreeJson(storeJson);
322 return ret;
323 }
324 if (AddObjToArray(storeJson, tokenJson) != HC_SUCCESS) {
325 LOGE("Add token json to array failed");
326 FreeJson(tokenJson);
327 FreeJson(storeJson);
328 return HC_ERR_JSON_ADD;
329 }
330 }
331 ret = WriteTokensJsonToFile(osAccountId, storeJson);
332 FreeJson(storeJson);
333 return ret;
334 }
335
GetVerifyAlg(const char * version)336 static Algorithm GetVerifyAlg(const char *version)
337 {
338 (void)version;
339 return P256;
340 }
341
GenerateKeyAlias(const char * userId,const char * deviceId,Uint8Buff * alias,bool isServerPkAlias)342 static int32_t GenerateKeyAlias(const char *userId, const char *deviceId, Uint8Buff *alias,
343 bool isServerPkAlias)
344 {
345 if ((userId == NULL) || (deviceId == NULL) || (alias == NULL)) {
346 LOGE("Invalid input params");
347 return HC_ERR_NULL_PTR;
348 }
349 uint32_t userIdLen = HcStrlen(userId);
350 uint32_t deviceIdLen = HcStrlen(deviceId);
351 const char *serverPkTag = "serverPk";
352 uint32_t serverPkTagLen = HcStrlen(serverPkTag);
353 uint32_t aliasStrLen;
354 if (isServerPkAlias) {
355 aliasStrLen = userIdLen + deviceIdLen + serverPkTagLen;
356 } else {
357 aliasStrLen = userIdLen + deviceIdLen;
358 }
359 uint8_t *aliasStr = (uint8_t *)HcMalloc(aliasStrLen, 0);
360 if (aliasStr == NULL) {
361 LOGE("Failed to malloc for self key aliasStr.");
362 return HC_ERR_ALLOC_MEMORY;
363 }
364 Uint8Buff aliasBuff = {
365 aliasStr,
366 aliasStrLen
367 };
368 if (memcpy_s(aliasBuff.val, aliasBuff.length, userId, userIdLen) != EOK) {
369 LOGE("Failed to copy userId.");
370 HcFree(aliasStr);
371 return HC_ERR_MEMORY_COPY;
372 }
373 if (memcpy_s(aliasBuff.val + userIdLen, aliasBuff.length - userIdLen,
374 deviceId, deviceIdLen) != EOK) {
375 LOGE("Failed to copy deviceId.");
376 HcFree(aliasStr);
377 return HC_ERR_MEMORY_COPY;
378 }
379 if (isServerPkAlias && (memcpy_s(aliasBuff.val + userIdLen + deviceIdLen,
380 aliasBuff.length - userIdLen - deviceIdLen, serverPkTag, serverPkTagLen) != EOK)) {
381 LOGE("Failed to copy serverPkTag.");
382 HcFree(aliasStr);
383 return HC_ERR_MEMORY_COPY;
384 }
385 int32_t ret = g_algLoader->sha256(&aliasBuff, alias);
386 HcFree(aliasStr);
387 if (ret != HAL_SUCCESS) {
388 LOGE("Compute alias failed");
389 }
390 return ret;
391 }
392
GenerateServerPkAlias(CJson * pkInfoJson,Uint8Buff * alias)393 static int32_t GenerateServerPkAlias(CJson *pkInfoJson, Uint8Buff *alias)
394 {
395 const char *userId = GetStringFromJson(pkInfoJson, FIELD_USER_ID);
396 if (userId == NULL) {
397 LOGE("Failed to get userId");
398 return HC_ERR_JSON_GET;
399 }
400 const char *deviceId = GetStringFromJson(pkInfoJson, FIELD_DEVICE_ID);
401 if (deviceId == NULL) {
402 LOGE("Failed to get deviceId");
403 return HC_ERR_JSON_GET;
404 }
405 return GenerateKeyAlias(userId, deviceId, alias, true);
406 }
407
ImportServerPk(const CJson * credJson,Uint8Buff * keyAlias,uint8_t * serverPk,Algorithm alg)408 static int32_t ImportServerPk(const CJson *credJson, Uint8Buff *keyAlias, uint8_t *serverPk, Algorithm alg)
409 {
410 const char *serverPkStr = GetStringFromJson(credJson, FIELD_SERVER_PK);
411 if (serverPkStr == NULL) {
412 LOGE("Failed to get serverPkStr");
413 return HC_ERR_JSON_GET;
414 }
415 uint32_t serverPkLen = HcStrlen(serverPkStr) / BYTE_TO_HEX_OPER_LENGTH;
416 Uint8Buff keyBuff = {
417 .val = serverPk,
418 .length = serverPkLen
419 };
420 int32_t authId = 0;
421 Uint8Buff authIdBuff = { (uint8_t *)&authId, sizeof(int32_t) };
422 ExtraInfo extInfo = { authIdBuff, -1, -1 };
423 return g_algLoader->importPublicKey(keyAlias, &keyBuff, alg, &extInfo);
424 }
425
VerifyPkInfoSignature(const CJson * credJson,CJson * pkInfoJson,uint8_t * signature,Uint8Buff * keyAlias,Algorithm alg)426 static int32_t VerifyPkInfoSignature(const CJson *credJson, CJson *pkInfoJson, uint8_t *signature,
427 Uint8Buff *keyAlias, Algorithm alg)
428 {
429 char *pkInfoStr = PackJsonToString(pkInfoJson);
430 if (pkInfoStr == NULL) {
431 LOGE("Failed to pack pkInfoStr");
432 return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL;
433 }
434 Uint8Buff messageBuff = {
435 .val = (uint8_t *)pkInfoStr,
436 .length = HcStrlen(pkInfoStr) + 1
437 };
438 const char *signatureStr = GetStringFromJson(credJson, FIELD_PK_INFO_SIGNATURE);
439 if (signatureStr == NULL) {
440 LOGE("Failed to get signatureStr");
441 FreeJsonString(pkInfoStr);
442 return HC_ERR_JSON_GET;
443 }
444 uint32_t signatureLen = HcStrlen(signatureStr) / BYTE_TO_HEX_OPER_LENGTH;
445 Uint8Buff signatureBuff = {
446 .val = signature,
447 .length = signatureLen
448 };
449 int32_t ret = g_algLoader->verify(keyAlias, &messageBuff, alg, &signatureBuff, true);
450 FreeJsonString(pkInfoStr);
451 return ret;
452 }
453
DoImportServerPkAndVerify(const CJson * credJson,uint8_t * signature,uint8_t * serverPk,CJson * pkInfoJson)454 static int32_t DoImportServerPkAndVerify(const CJson *credJson, uint8_t *signature, uint8_t *serverPk,
455 CJson *pkInfoJson)
456 {
457 uint8_t *keyAliasValue = (uint8_t *)HcMalloc(SHA256_LEN, 0);
458 if (keyAliasValue == NULL) {
459 LOGE("Malloc keyAliasValue failed");
460 return HC_ERR_ALLOC_MEMORY;
461 }
462 Uint8Buff keyAlias = {
463 .val = keyAliasValue,
464 .length = SHA256_LEN
465 };
466 g_accountDbMutex->lock(g_accountDbMutex);
467 int32_t ret = GenerateServerPkAlias(pkInfoJson, &keyAlias);
468 if (ret != HC_SUCCESS) {
469 LOGE("Failed to generate serverPk alias");
470 g_accountDbMutex->unlock(g_accountDbMutex);
471 HcFree(keyAliasValue);
472 return ret;
473 }
474 const char *version = GetStringFromJson(pkInfoJson, FIELD_VERSION);
475 if (version == NULL) {
476 LOGE("Failed to get version from pkInfo");
477 g_accountDbMutex->unlock(g_accountDbMutex);
478 HcFree(keyAliasValue);
479 return HC_ERR_JSON_GET;
480 }
481 Algorithm alg = GetVerifyAlg(version);
482 ret = ImportServerPk(credJson, &keyAlias, serverPk, alg);
483 if (ret != HAL_SUCCESS) {
484 LOGE("Import server public key failed");
485 g_accountDbMutex->unlock(g_accountDbMutex);
486 HcFree(keyAliasValue);
487 return ret;
488 }
489 LOGI("Import server public key success, start to verify");
490 ret = VerifyPkInfoSignature(credJson, pkInfoJson, signature, &keyAlias, alg);
491 g_accountDbMutex->unlock(g_accountDbMutex);
492 HcFree(keyAliasValue);
493 if (ret != HC_SUCCESS) {
494 LOGE("Verify pkInfoSignature failed");
495 }
496 return ret;
497 }
498
VerifySignature(const CJson * credJson)499 static int32_t VerifySignature(const CJson *credJson)
500 {
501 LOGI("start verify server message!");
502 uint8_t *signature = (uint8_t *)HcMalloc(SIGNATURE_SIZE, 0);
503 if (signature == NULL) {
504 LOGE("malloc signature fail!");
505 return HC_ERR_ALLOC_MEMORY;
506 }
507 if (GetByteFromJson(credJson, FIELD_PK_INFO_SIGNATURE, signature, SIGNATURE_SIZE) != EOK) {
508 LOGE("get pkInfoSignature fail");
509 HcFree(signature);
510 return HC_ERR_JSON_GET;
511 }
512 uint8_t *serverPk = (uint8_t *)HcMalloc(SERVER_PK_SIZE, 0);
513 if (serverPk == NULL) {
514 LOGE("malloc serverPk fail!");
515 HcFree(signature);
516 return HC_ERR_ALLOC_MEMORY;
517 }
518 if (GetByteFromJson(credJson, FIELD_SERVER_PK, serverPk, SERVER_PK_SIZE) != EOK) {
519 LOGE("get serverPk fail!");
520 HcFree(signature);
521 HcFree(serverPk);
522 return HC_ERR_JSON_GET;
523 }
524 CJson *pkInfoJson = GetObjFromJson(credJson, FIELD_PK_INFO);
525 if (pkInfoJson == NULL) {
526 LOGE("Failed to get pkInfoJson");
527 HcFree(signature);
528 HcFree(serverPk);
529 return HC_ERR_JSON_GET;
530 }
531 int32_t ret = DoImportServerPkAndVerify(credJson, signature, serverPk, pkInfoJson);
532 HcFree(signature);
533 HcFree(serverPk);
534 if (ret != HC_SUCCESS) {
535 LOGE("Verify pkInfoSignature failed");
536 } else {
537 LOGI("Verify pkInfoSignature success");
538 }
539 return ret;
540 }
541
GetTokenInfoByOsAccountId(int32_t osAccountId)542 static OsAccountTokenInfo *GetTokenInfoByOsAccountId(int32_t osAccountId)
543 {
544 uint32_t index = 0;
545 OsAccountTokenInfo *info = NULL;
546 FOR_EACH_HC_VECTOR(g_accountTokenDb, index, info) {
547 if ((info != NULL) && (info->osAccountId == osAccountId)) {
548 return info;
549 }
550 }
551 LOGI("Create a new os account database cache! [Id]: %d", osAccountId);
552 OsAccountTokenInfo newInfo;
553 newInfo.osAccountId = osAccountId;
554 newInfo.tokens = CreateAccountTokenVec();
555 OsAccountTokenInfo *returnInfo = g_accountTokenDb.pushBackT(&g_accountTokenDb, newInfo);
556 if (returnInfo == NULL) {
557 LOGE("Failed to push OsAccountTokenInfo to database!");
558 DestroyAccountTokenVec(&newInfo.tokens);
559 }
560 return returnInfo;
561 }
562
GeneratePkInfoFromInfo(const PkInfo * srcInfo,PkInfo * desInfo)563 static int32_t GeneratePkInfoFromInfo(const PkInfo *srcInfo, PkInfo *desInfo)
564 {
565 if (memcpy_s(desInfo->userId.val, desInfo->userId.length,
566 srcInfo->userId.val, srcInfo->userId.length) != EOK) {
567 LOGE("Memcpy for userId failed.");
568 return HC_ERR_MEMORY_COPY;
569 }
570 desInfo->userId.length = srcInfo->userId.length;
571 if (memcpy_s(desInfo->deviceId.val, desInfo->deviceId.length,
572 srcInfo->deviceId.val, srcInfo->deviceId.length) != EOK) {
573 LOGE("Memcpy for deviceId failed.");
574 return HC_ERR_MEMORY_COPY;
575 }
576 desInfo->deviceId.length = srcInfo->deviceId.length;
577 if (memcpy_s(desInfo->devicePk.val, desInfo->devicePk.length,
578 srcInfo->devicePk.val, srcInfo->devicePk.length) != EOK) {
579 LOGE("Memcpy for devicePk failed.");
580 return HC_ERR_MEMORY_COPY;
581 }
582 desInfo->devicePk.length = srcInfo->devicePk.length;
583 if (memcpy_s(desInfo->version.val, desInfo->version.length,
584 srcInfo->version.val, srcInfo->version.length) != EOK) {
585 LOGE("Memcpy for version failed.");
586 return HC_ERR_MEMORY_COPY;
587 }
588 desInfo->version.length = srcInfo->version.length;
589 return HC_SUCCESS;
590 }
591
SaveOsAccountTokenDb(int32_t osAccountId)592 static int32_t SaveOsAccountTokenDb(int32_t osAccountId)
593 {
594 g_accountDbMutex->lock(g_accountDbMutex);
595 OsAccountTokenInfo *info = GetTokenInfoByOsAccountId(osAccountId);
596 if (info == NULL) {
597 LOGE("Get token info by os account id failed");
598 g_accountDbMutex->unlock(g_accountDbMutex);
599 return HC_ERROR;
600 }
601 int32_t ret = SaveTokensToFile(osAccountId, &info->tokens);
602 if (ret != HC_SUCCESS) {
603 LOGE("Save tokens to file failed");
604 g_accountDbMutex->unlock(g_accountDbMutex);
605 return ret;
606 }
607 g_accountDbMutex->unlock(g_accountDbMutex);
608 LOGI("Save an os account database successfully! [Id]: %d", osAccountId);
609 return HC_SUCCESS;
610 }
611
GenerateAccountTokenFromToken(const AccountToken * token,AccountToken * returnToken)612 static bool GenerateAccountTokenFromToken(const AccountToken *token, AccountToken *returnToken)
613 {
614 if (memcpy_s(returnToken->pkInfoStr.val, returnToken->pkInfoStr.length,
615 token->pkInfoStr.val, token->pkInfoStr.length) != EOK) {
616 LOGE("Memcpy for pkInfoStr failed.");
617 return false;
618 }
619 returnToken->pkInfoStr.length = token->pkInfoStr.length;
620 if (GeneratePkInfoFromInfo(&token->pkInfo, &returnToken->pkInfo) != HC_SUCCESS) {
621 LOGE("Failed to generate pkInfo");
622 return false;
623 }
624 if (memcpy_s(returnToken->serverPk.val, returnToken->serverPk.length,
625 token->serverPk.val, token->serverPk.length) != EOK) {
626 LOGE("Memcpy for serverPk failed.");
627 return false;
628 }
629 returnToken->serverPk.length = token->serverPk.length;
630 if (memcpy_s(returnToken->pkInfoSignature.val, returnToken->pkInfoSignature.length,
631 token->pkInfoSignature.val, token->pkInfoSignature.length) != EOK) {
632 LOGE("Memcpy for pkInfoSignature failed.");
633 return false;
634 }
635 returnToken->pkInfoSignature.length = token->pkInfoSignature.length;
636 return true;
637 }
638
DeepCopyToken(const AccountToken * token)639 static AccountToken *DeepCopyToken(const AccountToken *token)
640 {
641 AccountToken *returnToken = CreateAccountToken();
642 if (returnToken == NULL) {
643 LOGE("Failed to create token");
644 return NULL;
645 }
646 if (!GenerateAccountTokenFromToken(token, returnToken)) {
647 LOGE("Generate token from exist token failed");
648 DestroyAccountToken(returnToken);
649 return NULL;
650 }
651 return returnToken;
652 }
653
QueryTokenPtrIfMatch(const AccountTokenVec * vec,const char * userId,const char * deviceId)654 static AccountToken **QueryTokenPtrIfMatch(const AccountTokenVec *vec, const char *userId, const char *deviceId)
655 {
656 if (userId == NULL || deviceId == NULL) {
657 LOGE("Invalid input param.");
658 return NULL;
659 }
660 uint32_t index;
661 AccountToken **token;
662 FOR_EACH_HC_VECTOR(*vec, index, token) {
663 if ((token == NULL) || (*token == NULL)) {
664 continue;
665 }
666 if ((strcmp(userId, (const char *)((*token)->pkInfo.userId.val)) == 0) &&
667 (strcmp(deviceId, (const char *)((*token)->pkInfo.deviceId.val)) == 0)) {
668 return token;
669 }
670 }
671 return NULL;
672 }
673
GetAccountToken(int32_t osAccountId,const char * userId,const char * deviceId)674 static AccountToken *GetAccountToken(int32_t osAccountId, const char *userId, const char *deviceId)
675 {
676 g_accountDbMutex->lock(g_accountDbMutex);
677 OsAccountTokenInfo *info = GetTokenInfoByOsAccountId(osAccountId);
678 if (info == NULL) {
679 LOGE("Failed to get token by osAccountId");
680 g_accountDbMutex->unlock(g_accountDbMutex);
681 return NULL;
682 }
683 AccountToken **token = QueryTokenPtrIfMatch(&info->tokens, userId, deviceId);
684 if ((token == NULL) || (*token == NULL)) {
685 LOGE("Query token failed");
686 g_accountDbMutex->unlock(g_accountDbMutex);
687 return NULL;
688 }
689 g_accountDbMutex->unlock(g_accountDbMutex);
690 return *token;
691 }
692
DeleteTokenInner(int32_t osAccountId,const char * userId,const char * deviceId,AccountTokenVec * deleteTokens)693 static int32_t DeleteTokenInner(int32_t osAccountId, const char *userId, const char *deviceId,
694 AccountTokenVec *deleteTokens)
695 {
696 LOGI("Start to delete tokens from database!");
697 g_accountDbMutex->lock(g_accountDbMutex);
698 OsAccountTokenInfo *info = GetTokenInfoByOsAccountId(osAccountId);
699 if (info == NULL) {
700 LOGE("Failed to get token by os account id");
701 g_accountDbMutex->unlock(g_accountDbMutex);
702 return HC_ERROR;
703 }
704 int32_t count = 0;
705 uint32_t index = 0;
706 AccountToken **token = NULL;
707 while (index < HC_VECTOR_SIZE(&info->tokens)) {
708 token = info->tokens.getp(&info->tokens, index);
709 if ((token == NULL) || (*token == NULL) ||
710 (strcmp(userId, (const char *)((*token)->pkInfo.userId.val)) != 0) ||
711 (strcmp(deviceId, (const char *)((*token)->pkInfo.deviceId.val)) != 0)) {
712 index++;
713 continue;
714 }
715 AccountToken *deleteToken = NULL;
716 HC_VECTOR_POPELEMENT(&info->tokens, &deleteToken, index);
717 count++;
718 LOGI("Delete a token from database successfully!");
719 if (deleteTokens->pushBackT(deleteTokens, deleteToken) == NULL) {
720 LOGE("Failed to push deleted token to vec");
721 DestroyAccountToken(deleteToken);
722 }
723 }
724 g_accountDbMutex->unlock(g_accountDbMutex);
725 if (count == 0) {
726 LOGE("No token deleted");
727 return HC_ERROR;
728 }
729 LOGI("Number of tokens deleted: %d", count);
730 return HC_SUCCESS;
731 }
732
GetToken(int32_t osAccountId,AccountToken * token,const char * userId,const char * deviceId)733 static int32_t GetToken(int32_t osAccountId, AccountToken *token, const char *userId, const char *deviceId)
734 {
735 if ((token == NULL) || (userId == NULL) || (deviceId == NULL)) {
736 LOGE("Invalid input params");
737 return HC_ERR_NULL_PTR;
738 }
739 AccountToken *existToken = GetAccountToken(osAccountId, userId, deviceId);
740 if (existToken == NULL) {
741 LOGE("Token not exist");
742 return HC_ERROR;
743 }
744 int32_t ret = GeneratePkInfoFromInfo(&existToken->pkInfo, &token->pkInfo);
745 if (ret != HC_SUCCESS) {
746 LOGE("Generate pkInfo failed");
747 return ret;
748 }
749 GOTO_ERR_AND_SET_RET(memcpy_s(token->pkInfoStr.val, token->pkInfoStr.length,
750 existToken->pkInfoStr.val, existToken->pkInfoStr.length), ret);
751 token->pkInfoStr.length = existToken->pkInfoStr.length;
752 GOTO_ERR_AND_SET_RET(memcpy_s(token->pkInfoSignature.val, token->pkInfoSignature.length,
753 existToken->pkInfoSignature.val, existToken->pkInfoSignature.length), ret);
754 token->pkInfoSignature.length = existToken->pkInfoSignature.length;
755 GOTO_ERR_AND_SET_RET(memcpy_s(token->serverPk.val, token->serverPk.length,
756 existToken->serverPk.val, existToken->serverPk.length), ret);
757 token->serverPk.length = existToken->serverPk.length;
758
759 ret = HC_SUCCESS;
760 LOGI("GetToken successfully!");
761 ERR:
762 return ret;
763 }
764
AddTokenInner(int32_t osAccountId,const AccountToken * token)765 static int32_t AddTokenInner(int32_t osAccountId, const AccountToken *token)
766 {
767 LOGI("Start to add a token to database!");
768 g_accountDbMutex->lock(g_accountDbMutex);
769 OsAccountTokenInfo *info = GetTokenInfoByOsAccountId(osAccountId);
770 if (info == NULL) {
771 LOGE("Failed to get token by os account id");
772 g_accountDbMutex->unlock(g_accountDbMutex);
773 return HC_ERROR;
774 }
775 AccountToken *newToken = DeepCopyToken(token);
776 if (newToken == NULL) {
777 LOGE("Deep copy token failed");
778 g_accountDbMutex->unlock(g_accountDbMutex);
779 return HC_ERR_MEMORY_COPY;
780 }
781 AccountToken **oldTokenPtr = QueryTokenPtrIfMatch(&info->tokens, (const char *)(newToken->pkInfo.userId.val),
782 (const char *)(newToken->pkInfo.deviceId.val));
783 if (oldTokenPtr != NULL) {
784 DestroyAccountToken(*oldTokenPtr);
785 *oldTokenPtr = newToken;
786 g_accountDbMutex->unlock(g_accountDbMutex);
787 LOGI("Replace an old token successfully!");
788 return HC_SUCCESS;
789 }
790 if (info->tokens.pushBackT(&info->tokens, newToken) == NULL) {
791 DestroyAccountToken(newToken);
792 g_accountDbMutex->unlock(g_accountDbMutex);
793 LOGE("Failed to push token to vec!");
794 return HC_ERR_MEMORY_COPY;
795 }
796 g_accountDbMutex->unlock(g_accountDbMutex);
797 LOGI("Add a token to database successfully!");
798 return HC_SUCCESS;
799 }
800
DoExportPkAndCompare(const char * userId,const char * deviceId,const char * devicePk,Uint8Buff * keyAlias)801 static int32_t DoExportPkAndCompare(const char *userId, const char *deviceId,
802 const char *devicePk, Uint8Buff *keyAlias)
803 {
804 g_accountDbMutex->lock(g_accountDbMutex);
805 int32_t ret = GenerateKeyAlias(userId, deviceId, keyAlias, false);
806 if (ret != HC_SUCCESS) {
807 LOGE("Generate key alias failed.");
808 g_accountDbMutex->unlock(g_accountDbMutex);
809 return ret;
810 }
811 ret = g_algLoader->checkKeyExist(keyAlias);
812 if (ret != HAL_SUCCESS) {
813 LOGE("Key pair not exist.");
814 g_accountDbMutex->unlock(g_accountDbMutex);
815 return ret;
816 }
817 uint8_t *publicKeyVal = (uint8_t *)HcMalloc(PK_SIZE, 0);
818 if (publicKeyVal == NULL) {
819 LOGE("Malloc publicKeyVal failed");
820 g_accountDbMutex->unlock(g_accountDbMutex);
821 return HC_ERR_ALLOC_MEMORY;
822 }
823 Uint8Buff publicKey = {
824 .val = publicKeyVal,
825 .length = PK_SIZE
826 };
827 ret = g_algLoader->exportPublicKey(keyAlias, &publicKey);
828 if (ret != HAL_SUCCESS) {
829 LOGE("Failed to export public key");
830 HcFree(publicKeyVal);
831 g_accountDbMutex->unlock(g_accountDbMutex);
832 return ret;
833 }
834 g_accountDbMutex->unlock(g_accountDbMutex);
835 if (strcmp((const char *)devicePk, (const char *)publicKeyVal) == 0) {
836 HcFree(publicKeyVal);
837 return HC_SUCCESS;
838 }
839 HcFree(publicKeyVal);
840 return HC_ERROR;
841 }
842
CheckDevicePk(const CJson * credJson)843 static int32_t CheckDevicePk(const CJson *credJson)
844 {
845 CJson *pkInfoJson = GetObjFromJson(credJson, FIELD_PK_INFO);
846 if (pkInfoJson == NULL) {
847 LOGE("Failed to get pkInfoJson");
848 return HC_ERR_JSON_GET;
849 }
850 const char *userId = GetStringFromJson(pkInfoJson, FIELD_USER_ID);
851 if (userId == NULL) {
852 LOGE("Failed to get userId");
853 return HC_ERR_JSON_GET;
854 }
855 const char *deviceId = GetStringFromJson(pkInfoJson, FIELD_DEVICE_ID);
856 if (deviceId == NULL) {
857 LOGE("Failed to get deviceId");
858 return HC_ERR_JSON_GET;
859 }
860 uint8_t *devicePk = (uint8_t *)HcMalloc(PK_SIZE, 0);
861 if (devicePk == NULL) {
862 LOGE("Malloc devicePk failed");
863 return HC_ERR_ALLOC_MEMORY;
864 }
865 if (GetByteFromJson(pkInfoJson, FIELD_DEVICE_PK, devicePk, PK_SIZE) != HC_SUCCESS) {
866 LOGE("Failed to get devicePk");
867 HcFree(devicePk);
868 return HC_ERR_JSON_GET;
869 }
870 uint8_t *keyAliasValue = (uint8_t *)HcMalloc(SHA256_LEN, 0);
871 if (keyAliasValue == NULL) {
872 LOGE("Malloc keyAliasValue failed");
873 HcFree(devicePk);
874 return HC_ERR_ALLOC_MEMORY;
875 }
876 Uint8Buff keyAlias = {
877 .val = keyAliasValue,
878 .length = SHA256_LEN
879 };
880 int32_t ret = DoExportPkAndCompare(userId, deviceId, (const char *)devicePk, &keyAlias);
881 HcFree(devicePk);
882 HcFree(keyAliasValue);
883 if (ret == HC_SUCCESS) {
884 LOGI("Check devicePk success");
885 } else {
886 LOGE("Check devicePk failed");
887 }
888 return ret;
889 }
890
CheckUserId(const char * userId,const CJson * in)891 static int32_t CheckUserId(const char *userId, const CJson *in)
892 {
893 CJson *pkInfoJson = GetObjFromJson(in, FIELD_PK_INFO);
894 if (pkInfoJson == NULL) {
895 LOGE("Failed to get pkInfoJson");
896 return HC_ERR_JSON_GET;
897 }
898 const char *userIdFromPk = GetStringFromJson(pkInfoJson, FIELD_USER_ID);
899 if (userIdFromPk == NULL) {
900 LOGE("Failed to get userIdFromPk");
901 return HC_ERR_JSON_GET;
902 }
903 if (strcmp(userId, userIdFromPk) == 0) {
904 return HC_SUCCESS;
905 }
906 return HC_ERROR;
907 }
908
CheckCredValidity(int32_t opCode,const CJson * in)909 static int32_t CheckCredValidity(int32_t opCode, const CJson *in)
910 {
911 const char *userId = GetStringFromJson(in, FIELD_USER_ID);
912 if (userId == NULL) {
913 LOGE("Failed to get userId");
914 return HC_ERR_JSON_GET;
915 }
916 int32_t ret = VerifySignature(in);
917 if (ret != HC_SUCCESS) {
918 LOGE("Verify server credential failed!");
919 return ret;
920 }
921 if (opCode == IMPORT_TRUSTED_CREDENTIALS) {
922 return HC_SUCCESS;
923 }
924 ret = CheckDevicePk(in);
925 if (ret != HC_SUCCESS) {
926 LOGE("Check devicePk failed!");
927 return ret;
928 }
929 ret = CheckUserId(userId, in);
930 if (ret != HC_SUCCESS) {
931 LOGE("Check userId failed!");
932 }
933 return ret;
934 }
935
AddToken(int32_t osAccountId,int32_t opCode,const CJson * in)936 static int32_t AddToken(int32_t osAccountId, int32_t opCode, const CJson *in)
937 {
938 if (in == NULL) {
939 LOGE("Input param is null!");
940 return HC_ERR_NULL_PTR;
941 }
942 int32_t ret = CheckCredValidity(opCode, in);
943 if (ret != HC_SUCCESS) {
944 LOGE("Invalid credential");
945 return ret;
946 }
947 AccountToken *token = CreateAccountToken();
948 if (token == NULL) {
949 LOGE("Failed to allocate token memory!");
950 return HC_ERR_ALLOC_MEMORY;
951 }
952 ret = GenerateTokenFromJson(in, token);
953 if (ret != HC_SUCCESS) {
954 LOGE("Failed to generate token");
955 DestroyAccountToken(token);
956 return ret;
957 }
958 ret = AddTokenInner(osAccountId, token);
959 DestroyAccountToken(token);
960 if (ret != HC_SUCCESS) {
961 LOGE("Failed to add token inner");
962 return ret;
963 }
964 ret = SaveOsAccountTokenDb(osAccountId);
965 if (ret != HC_SUCCESS) {
966 LOGE("Failed to save token to db");
967 }
968 return ret;
969 }
970
DoGenerateAndExportPk(const char * userId,const char * deviceId,Uint8Buff * keyAlias,Uint8Buff * publicKey)971 static int32_t DoGenerateAndExportPk(const char *userId, const char *deviceId,
972 Uint8Buff *keyAlias, Uint8Buff *publicKey)
973 {
974 g_accountDbMutex->lock(g_accountDbMutex);
975 int32_t ret = GenerateKeyAlias(userId, deviceId, keyAlias, false);
976 if (ret != HC_SUCCESS) {
977 LOGE("Generate key alias failed");
978 g_accountDbMutex->unlock(g_accountDbMutex);
979 return ret;
980 }
981 ret = g_algLoader->checkKeyExist(keyAlias);
982 if (ret != HAL_SUCCESS) {
983 LOGI("Key pair not exist, start to generate");
984 int32_t authId = 0;
985 Uint8Buff authIdBuff = { (uint8_t *)&authId, sizeof(int32_t) };
986 ExtraInfo extInfo = { authIdBuff, -1, -1 };
987 ret = g_algLoader->generateKeyPairWithStorage(keyAlias, SELF_ECC_KEY_LEN, P256,
988 KEY_PURPOSE_KEY_AGREE, &extInfo);
989 } else {
990 LOGI("Key pair already exists");
991 }
992 if (ret != HAL_SUCCESS) {
993 LOGE("Generate key pair failed");
994 g_accountDbMutex->unlock(g_accountDbMutex);
995 return ret;
996 }
997 ret = g_algLoader->exportPublicKey(keyAlias, publicKey);
998 g_accountDbMutex->unlock(g_accountDbMutex);
999 return ret;
1000 }
1001
GetRegisterProof(const CJson * in,CJson * out)1002 static int32_t GetRegisterProof(const CJson *in, CJson *out)
1003 {
1004 const char *userId = GetStringFromJson(in, FIELD_USER_ID);
1005 if (userId == NULL) {
1006 LOGE("Failed to get userId!");
1007 return HC_ERR_JSON_GET;
1008 }
1009 const char *version = GetStringFromJson(in, FIELD_VERSION);
1010 if (version == NULL) {
1011 LOGE("Failed to get version!");
1012 return HC_ERR_JSON_GET;
1013 }
1014 const char *deviceId = GetStringFromJson(in, FIELD_DEVICE_ID);
1015 if (deviceId == NULL) {
1016 LOGE("Failed to get deviceId!");
1017 return HC_ERR_JSON_GET;
1018 }
1019 uint8_t *keyAliasValue = (uint8_t *)HcMalloc(SHA256_LEN, 0);
1020 if (keyAliasValue == NULL) {
1021 LOGE("Malloc keyAliasValue failed");
1022 return HC_ERR_ALLOC_MEMORY;
1023 }
1024 Uint8Buff keyAlias = {
1025 .val = keyAliasValue,
1026 .length = SHA256_LEN
1027 };
1028 uint8_t *publicKeyVal = (uint8_t *)HcMalloc(PK_SIZE, 0);
1029 if (publicKeyVal == NULL) {
1030 LOGE("Malloc publicKeyVal failed");
1031 HcFree(keyAliasValue);
1032 return HC_ERR_ALLOC_MEMORY;
1033 }
1034 Uint8Buff publicKey = {
1035 .val = publicKeyVal,
1036 .length = PK_SIZE
1037 };
1038 int32_t ret = DoGenerateAndExportPk(userId, deviceId, &keyAlias, &publicKey);
1039 HcFree(keyAliasValue);
1040 if (ret != HC_SUCCESS) {
1041 LOGE("exportPublicKey failed");
1042 goto ERR;
1043 }
1044 GOTO_ERR_AND_SET_RET(AddByteToJson(out, FIELD_DEVICE_PK, publicKeyVal, publicKey.length), ret);
1045 GOTO_ERR_AND_SET_RET(AddStringToJson(out, FIELD_USER_ID, userId), ret);
1046 GOTO_ERR_AND_SET_RET(AddStringToJson(out, FIELD_DEVICE_ID, deviceId), ret);
1047 GOTO_ERR_AND_SET_RET(AddStringToJson(out, FIELD_VERSION, version), ret);
1048 LOGI("Generate register proof successfully!");
1049 ERR:
1050 HcFree(publicKeyVal);
1051 return ret;
1052 }
1053
GetAlgVersion(int32_t osAccountId,const char * userId,const char * deviceId)1054 static Algorithm GetAlgVersion(int32_t osAccountId, const char *userId, const char *deviceId)
1055 {
1056 if (userId == NULL) {
1057 LOGE("Invalid input params, return default alg.");
1058 return P256;
1059 }
1060 AccountToken *token = GetAccountToken(osAccountId, userId, deviceId);
1061 if (token == NULL) {
1062 LOGE("Token not exist, return default alg.");
1063 return P256;
1064 }
1065 return GetVerifyAlg((const char *)token->pkInfo.version.val);
1066 }
1067
DeleteKeyPair(AccountToken * token)1068 static void DeleteKeyPair(AccountToken *token)
1069 {
1070 uint8_t *keyAliasValue = (uint8_t *)HcMalloc(SHA256_LEN, 0);
1071 if (keyAliasValue == NULL) {
1072 LOGE("Malloc keyAliasValue failed");
1073 return;
1074 }
1075 Uint8Buff keyAlias = {
1076 .val = keyAliasValue,
1077 .length = SHA256_LEN
1078 };
1079 g_accountDbMutex->lock(g_accountDbMutex);
1080 if (GenerateKeyAlias((const char *)token->pkInfo.userId.val,
1081 (const char *)token->pkInfo.deviceId.val, &keyAlias, false) != HC_SUCCESS) {
1082 LOGE("Failed to generate key alias");
1083 HcFree(keyAliasValue);
1084 g_accountDbMutex->unlock(g_accountDbMutex);
1085 return;
1086 }
1087 if (g_algLoader->deleteKey(&keyAlias) != HAL_SUCCESS) {
1088 LOGE("Failed to delete key pair");
1089 } else {
1090 LOGI("Delete key pair success");
1091 }
1092 HcFree(keyAliasValue);
1093 g_accountDbMutex->unlock(g_accountDbMutex);
1094 }
1095
DeleteToken(int32_t osAccountId,const char * userId,const char * deviceId)1096 static int32_t DeleteToken(int32_t osAccountId, const char *userId, const char *deviceId)
1097 {
1098 if ((userId == NULL) || (deviceId == NULL)) {
1099 LOGE("Invalid input params!");
1100 return HC_ERR_NULL_PTR;
1101 }
1102 AccountTokenVec deleteTokens = CreateAccountTokenVec();
1103 int32_t ret = DeleteTokenInner(osAccountId, userId, deviceId, &deleteTokens);
1104 if (ret != HC_SUCCESS) {
1105 LOGE("Failed to delete token inner, account id is: %d", osAccountId);
1106 DestroyAccountTokenVec(&deleteTokens);
1107 return ret;
1108 }
1109 ret = SaveOsAccountTokenDb(osAccountId);
1110 if (ret != HC_SUCCESS) {
1111 LOGE("Failed to save token to db, account id is: %d", osAccountId);
1112 ClearAccountTokenVec(&deleteTokens);
1113 return ret;
1114 }
1115 uint32_t index;
1116 AccountToken **token;
1117 FOR_EACH_HC_VECTOR(deleteTokens, index, token) {
1118 if ((token != NULL) && (*token != NULL)) {
1119 DeleteKeyPair(*token);
1120 }
1121 }
1122 ClearAccountTokenVec(&deleteTokens);
1123 return HC_SUCCESS;
1124 }
1125
LoadOsAccountTokenDb(int32_t osAccountId)1126 static void LoadOsAccountTokenDb(int32_t osAccountId)
1127 {
1128 OsAccountTokenInfo info;
1129 info.osAccountId = osAccountId;
1130 info.tokens = CreateAccountTokenVec();
1131 if (ReadTokensFromFile(osAccountId, &info.tokens) != HC_SUCCESS) {
1132 DestroyAccountTokenVec(&info.tokens);
1133 return;
1134 }
1135 if (g_accountTokenDb.pushBackT(&g_accountTokenDb, info) == NULL) {
1136 LOGE("Failed to push osAccountInfo to database!");
1137 ClearAccountTokenVec(&info.tokens);
1138 }
1139 LOGI("Load os account db successfully! [Id]: %d", osAccountId);
1140 }
1141
LoadTokenDb(void)1142 static void LoadTokenDb(void)
1143 {
1144 StringVector dbNameVec = CreateStrVector();
1145 HcFileGetSubFileName(GetAccountStoragePath(), &dbNameVec);
1146 uint32_t index;
1147 HcString *dbName = NULL;
1148 FOR_EACH_HC_VECTOR(dbNameVec, index, dbName) {
1149 int32_t osAccountId;
1150 const char *name = StringGet(dbName);
1151 if (name == NULL) {
1152 continue;
1153 }
1154 if (strcmp(name, "account_data_asy.dat") == 0) {
1155 LoadOsAccountTokenDb(DEFAULT_OS_ACCOUNT);
1156 } else if (sscanf_s(name, "account_data_asy%d.dat", &osAccountId) == 1) {
1157 LoadOsAccountTokenDb(osAccountId);
1158 }
1159 }
1160 DestroyStrVector(&dbNameVec);
1161 }
1162
InitTokenManager(void)1163 void InitTokenManager(void)
1164 {
1165 if (g_accountDbMutex == NULL) {
1166 g_accountDbMutex = (HcMutex *)HcMalloc(sizeof(HcMutex), 0);
1167 if (g_accountDbMutex == NULL) {
1168 LOGE("Alloc account database mutex failed.");
1169 return;
1170 }
1171 if (InitHcMutex(g_accountDbMutex) != HC_SUCCESS) {
1172 LOGE("Init account mutex failed.");
1173 HcFree(g_accountDbMutex);
1174 g_accountDbMutex = NULL;
1175 return;
1176 }
1177 }
1178 g_accountDbMutex->lock(g_accountDbMutex);
1179 (void)memset_s(&g_asyTokenManager, sizeof(AccountAuthTokenManager), 0, sizeof(AccountAuthTokenManager));
1180 g_asyTokenManager.addToken = AddToken;
1181 g_asyTokenManager.getToken = GetToken;
1182 g_asyTokenManager.deleteToken = DeleteToken;
1183 g_asyTokenManager.getRegisterProof = GetRegisterProof;
1184 g_asyTokenManager.generateKeyAlias = GenerateKeyAlias;
1185 g_asyTokenManager.getAlgVersion = GetAlgVersion;
1186 if (!g_isInitial) {
1187 g_accountTokenDb = CREATE_HC_VECTOR(AccountTokenDb);
1188 g_isInitial = true;
1189 }
1190
1191 LoadTokenDb();
1192 g_algLoader = GetLoaderInstance();
1193 if (g_algLoader == NULL) {
1194 LOGE("Get loader failed.");
1195 g_accountDbMutex->unlock(g_accountDbMutex);
1196 return;
1197 }
1198 int32_t res = g_algLoader->initAlg();
1199 if (res != HAL_SUCCESS) {
1200 LOGE("Failed to init algorithm!");
1201 }
1202 g_accountDbMutex->unlock(g_accountDbMutex);
1203 }
1204
ClearAccountTokenVec(AccountTokenVec * vec)1205 void ClearAccountTokenVec(AccountTokenVec *vec)
1206 {
1207 uint32_t index;
1208 AccountToken **token;
1209 FOR_EACH_HC_VECTOR(*vec, index, token) {
1210 DestroyAccountToken(*token);
1211 }
1212 DESTROY_HC_VECTOR(AccountTokenVec, vec);
1213 }
1214
InitTokenData(AccountToken * token)1215 static void InitTokenData(AccountToken *token)
1216 {
1217 token->pkInfoStr.val = NULL;
1218 token->pkInfoSignature.val = NULL;
1219 token->serverPk.val = NULL;
1220 token->pkInfo.deviceId.val = NULL;
1221 token->pkInfo.userId.val = NULL;
1222 token->pkInfo.version.val = NULL;
1223 token->pkInfo.devicePk.val = NULL;
1224 }
1225
CreateAccountToken(void)1226 AccountToken *CreateAccountToken(void)
1227 {
1228 AccountToken *token = (AccountToken *)HcMalloc(sizeof(AccountToken), 0);
1229 if (token == NULL) {
1230 LOGE("Failed to allocate accountToken memory!");
1231 return NULL;
1232 }
1233 InitTokenData(token);
1234 token->pkInfoStr.val = (uint8_t *)HcMalloc(PUBLIC_KEY_INFO_SIZE, 0);
1235 GOTO_IF_CHECK_NULL(token->pkInfoStr.val, "pkInfoStr");
1236 token->pkInfoStr.length = PUBLIC_KEY_INFO_SIZE;
1237 token->pkInfoSignature.val = (uint8_t *)HcMalloc(SIGNATURE_SIZE, 0);
1238 GOTO_IF_CHECK_NULL(token->pkInfoSignature.val, "pkInfoSignature");
1239 token->pkInfoSignature.length = SIGNATURE_SIZE;
1240 token->serverPk.val = (uint8_t *)HcMalloc(SERVER_PK_SIZE, 0);
1241 GOTO_IF_CHECK_NULL(token->serverPk.val, "serverPk");
1242 token->serverPk.length = SERVER_PK_SIZE;
1243 token->pkInfo.deviceId.val = (uint8_t *)HcMalloc(DEV_AUTH_DEVICE_ID_SIZE, 0);
1244 GOTO_IF_CHECK_NULL(token->pkInfo.deviceId.val, "deviceId");
1245 token->pkInfo.deviceId.length = DEV_AUTH_DEVICE_ID_SIZE;
1246 token->pkInfo.userId.val = (uint8_t *)HcMalloc(DEV_AUTH_USER_ID_SIZE, 0);
1247 GOTO_IF_CHECK_NULL(token->pkInfo.userId.val, "userId");
1248 token->pkInfo.userId.length = DEV_AUTH_USER_ID_SIZE;
1249 token->pkInfo.version.val = (uint8_t *)HcMalloc(PK_VERSION_SIZE, 0);
1250 GOTO_IF_CHECK_NULL(token->pkInfo.version.val, "version");
1251 token->pkInfo.version.length = PK_VERSION_SIZE;
1252 token->pkInfo.devicePk.val = (uint8_t *)HcMalloc(PK_SIZE, 0);
1253 GOTO_IF_CHECK_NULL(token->pkInfo.devicePk.val, "devicePk");
1254 token->pkInfo.devicePk.length = PK_SIZE;
1255 return token;
1256 ERR:
1257 DestroyAccountToken(token);
1258 return NULL;
1259 }
1260
DestroyAccountToken(AccountToken * token)1261 void DestroyAccountToken(AccountToken *token)
1262 {
1263 if (token == NULL) {
1264 LOGE("Input token is null");
1265 return;
1266 }
1267 HcFree(token->pkInfoStr.val);
1268 token->pkInfoStr.length = 0;
1269 HcFree(token->pkInfoSignature.val);
1270 token->pkInfoSignature.length = 0;
1271 HcFree(token->serverPk.val);
1272 token->serverPk.length = 0;
1273 HcFree(token->pkInfo.deviceId.val);
1274 token->pkInfo.deviceId.length = 0;
1275 HcFree(token->pkInfo.userId.val);
1276 token->pkInfo.userId.length = 0;
1277 HcFree(token->pkInfo.version.val);
1278 token->pkInfo.version.length = 0;
1279 HcFree(token->pkInfo.devicePk.val);
1280 token->pkInfo.devicePk.length = 0;
1281 HcFree(token);
1282 }
1283
GetAccountAuthTokenManager(void)1284 AccountAuthTokenManager *GetAccountAuthTokenManager(void)
1285 {
1286 return &g_asyTokenManager;
1287 }
1288
DestroyTokenManager(void)1289 void DestroyTokenManager(void)
1290 {
1291 g_accountDbMutex->lock(g_accountDbMutex);
1292 g_algLoader = NULL;
1293 (void)memset_s(&g_asyTokenManager, sizeof(AccountAuthTokenManager), 0, sizeof(AccountAuthTokenManager));
1294 uint32_t index;
1295 OsAccountTokenInfo *info = NULL;
1296 FOR_EACH_HC_VECTOR(g_accountTokenDb, index, info) {
1297 ClearAccountTokenVec(&info->tokens);
1298 }
1299 DESTROY_HC_VECTOR(AccountTokenDb, &g_accountTokenDb);
1300 g_isInitial = false;
1301 g_accountDbMutex->unlock(g_accountDbMutex);
1302 if (g_accountDbMutex != NULL) {
1303 DestroyHcMutex(g_accountDbMutex);
1304 HcFree(g_accountDbMutex);
1305 g_accountDbMutex = NULL;
1306 }
1307 }