1 /*
2  * Copyright (c) 2020-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *    http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef _CUT_AUTHENTICATE_
17 
18 #include "hks_rkc.h"
19 
20 #include "hks_crypto_hal.h"
21 #include "hks_get_udid.h"
22 #include "hks_log.h"
23 #include "hks_mem.h"
24 #include "hks_param.h"
25 #include "hks_template.h"
26 
27 #ifdef HKS_ENABLE_UPGRADE_RKC_DERIVE_ALG
28 #include "hks_rkc_v1.h"
29 #endif
30 
31 /* the configuration of root key component */
32 static struct HksRkcCfg g_hksRkcCfg = {
33     .state = HKS_RKC_STATE_INVALID,
34     .rkVersion = HKS_RKC_VER,
35     .mkVersion = HKS_MK_VER,
36     .storageType = HKS_RKC_STORAGE_FILE_SYS,
37     .rkCreatedTime = { 0, 0, 0, 0, 0, 0 },
38     .rkExpiredTime = { 0, 0, 0, 0, 0, 0 },
39     .ksfAttrRkc = {{ NULL, NULL }},
40     .ksfAttrMk = {{ NULL, NULL }},
41     .rmkIter = HKS_RKC_RMK_ITER,
42     .rmkHashAlg = HKS_RKC_RMK_HMAC_SHA256,
43     .mkMask = {0},
44     .mkEncryptAlg = HKS_RKC_MK_CRYPT_ALG_AES256_GCM,
45     .reserve = {0}
46 };
47 
GetGlobalKsfAttrRkc(void)48 const struct HksKsfAttr *GetGlobalKsfAttrRkc(void)
49 {
50     return &g_hksRkcCfg.ksfAttrRkc;
51 }
52 
GetGlobalKsfAttrMk(void)53 const struct HksKsfAttr *GetGlobalKsfAttrMk(void)
54 {
55     return &g_hksRkcCfg.ksfAttrMk;
56 }
57 
58 /* the data of main key */
59 struct HksRkcMk g_hksRkcMk = { false, { 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, {0} };
60 
61 /* the additional data of main key. 'H', 'K', 'S', 'R', 'K', 'C', 'M', 'K' */
62 const uint8_t g_hksRkcMkAddData[HKS_RKC_MK_ADD_DATA_LEN] = { 0x48, 0x4B, 0x53, 0x52, 0x4B, 0x43, 0x4D, 0x4B };
63 
ReadAllKsfRkc(struct HksKsfDataRkcWithVer * validKsfData)64 static int32_t ReadAllKsfRkc(struct HksKsfDataRkcWithVer *validKsfData)
65 {
66     /* Read all rkc ksf */
67     int32_t readRet[HKS_KSF_NUM] = { 0 };
68     struct HksKsfDataRkcWithVer allRkcData[HKS_KSF_NUM] = { 0 };
69     for (uint32_t i = 0; i < HKS_KSF_NUM; ++i) {
70         readRet[i] = HksReadKsfRkc(g_hksRkcCfg.ksfAttrRkc.name[i], &(allRkcData[i]));
71     }
72 
73     int32_t validIndex = 0;
74     for (; validIndex < HKS_KSF_NUM; validIndex++) {
75         if (readRet[validIndex] == HKS_SUCCESS) {
76             break;
77         }
78     }
79     if (validIndex == HKS_KSF_NUM) {
80         return HKS_ERROR_INVALID_KEY_FILE;
81     }
82 
83     for (uint32_t i = 0; i < HKS_KSF_NUM; i++) {
84         if (readRet[i] != HKS_SUCCESS) {
85             int32_t ret = HksWriteKsfRkc(g_hksRkcCfg.ksfAttrRkc.name[i], &allRkcData[validIndex]);
86             HKS_IF_NOT_SUCC_LOGE(ret, "rewrite rkc ksf failed! ret = 0x%" LOG_PUBLIC "X", ret)
87         }
88     }
89 
90     (void)memcpy_s(validKsfData, sizeof(struct HksKsfDataRkcWithVer),
91         &allRkcData[validIndex], sizeof(struct HksKsfDataRkcWithVer));
92     return HKS_SUCCESS;
93 }
94 
ReadAllKsfMk(struct HksKsfDataMkWithVer * validKsfData)95 static int32_t ReadAllKsfMk(struct HksKsfDataMkWithVer *validKsfData)
96 {
97     /* Read all ksf */
98     int32_t readRet[HKS_KSF_NUM] = { 0 };
99     struct HksKsfDataMkWithVer allMkData[HKS_KSF_NUM] = { 0 };
100     for (uint32_t i = 0; i < HKS_KSF_NUM; ++i) {
101         readRet[i] = HksReadKsfMk(g_hksRkcCfg.ksfAttrMk.name[i], &(allMkData[i]));
102     }
103 
104     int32_t validIndex = 0;
105     for (; validIndex < HKS_KSF_NUM; validIndex++) {
106         if (readRet[validIndex] == HKS_SUCCESS) {
107             break;
108         }
109     }
110     if (validIndex == HKS_KSF_NUM) {
111         return HKS_ERROR_INVALID_KEY_FILE;
112     }
113 
114     for (uint32_t i = 0; i < HKS_KSF_NUM; i++) {
115         if (readRet[i] != HKS_SUCCESS) {
116             int32_t ret = HksWriteKsfMk(g_hksRkcCfg.ksfAttrMk.name[i], &allMkData[validIndex]);
117             HKS_IF_NOT_SUCC_LOGE(ret, "rewrite mk ksf failed! ret = 0x%" LOG_PUBLIC "X", ret)
118         }
119     }
120 
121     (void)memcpy_s(validKsfData, sizeof(struct HksKsfDataMkWithVer),
122         &allMkData[validIndex], sizeof(struct HksKsfDataMkWithVer));
123     return HKS_SUCCESS;
124 }
125 
RkcGetRmkRawKey(const struct HksKsfDataRkc * ksfDataRkc,struct HksBlob * rawKey)126 static int32_t RkcGetRmkRawKey(const struct HksKsfDataRkc *ksfDataRkc, struct HksBlob *rawKey)
127 {
128     uint8_t udid[HKS_HARDWARE_UDID_LEN] = {0};
129     int32_t ret = HksGetHardwareUdid(udid, HKS_HARDWARE_UDID_LEN);
130     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "Get hardware udid failed! ret = 0x%" LOG_PUBLIC "X", ret)
131 
132     /* materials xor */
133     for (uint32_t i = 0; i < HKS_RKC_MATERIAL_LEN; ++i) {
134         rawKey->data[i] = ksfDataRkc->rkMaterial1[i] ^ ksfDataRkc->rkMaterial2[i] ^ udid[i];
135     }
136 
137     (void)memset_s(udid, HKS_HARDWARE_UDID_LEN, 0, HKS_HARDWARE_UDID_LEN);
138     return HKS_SUCCESS;
139 }
140 
RkcDigestToHks(const uint32_t rkcDigest)141 uint32_t RkcDigestToHks(const uint32_t rkcDigest)
142 {
143     if (rkcDigest == HKS_RKC_RMK_HMAC_SHA256) {
144         return HKS_DIGEST_SHA256;
145     }
146 
147     /* if digest is invalid, will use default digest */
148     return HKS_DIGEST_SHA256;
149 }
150 
RkcHkdfHmac(const uint32_t hashAlg,const struct HksBlob * rawKey,const struct HksBlob * salt,const uint32_t iterNum,struct HksBlob * dk)151 static int32_t RkcHkdfHmac(const uint32_t hashAlg, const struct HksBlob *rawKey,
152     const struct HksBlob *salt, const uint32_t iterNum, struct HksBlob *dk)
153 {
154     struct HksKeyDerivationParam derParam = {
155         .salt = *salt,
156         .iterations = iterNum,
157         .digestAlg = RkcDigestToHks(hashAlg),
158     };
159     const struct HksKeySpec derivationSpec = { HKS_ALG_HKDF, dk->size, &derParam };
160     int32_t ret = HksCryptoHalDeriveKey(rawKey, &derivationSpec, dk);
161     HKS_IF_NOT_SUCC_LOGE(ret, "Crypto hal derive key failed! ret = 0x%" LOG_PUBLIC "X", ret)
162 
163     return ret;
164 }
165 
RkcDeriveRmk(const struct HksKsfDataRkc * ksfDataRkc,struct HksBlob * rmk)166 static int32_t RkcDeriveRmk(const struct HksKsfDataRkc *ksfDataRkc, struct HksBlob *rmk)
167 {
168     struct HksBlob rawKey;
169     rawKey.data = (uint8_t *)HksMalloc(HKS_RKC_RAW_KEY_LEN);
170     HKS_IF_NULL_LOGE_RETURN(rawKey.data, HKS_ERROR_MALLOC_FAIL, "Malloc rawKey failed!")
171 
172     rawKey.size = HKS_RKC_RAW_KEY_LEN;
173     (void)memset_s(rawKey.data, rawKey.size, 0, rawKey.size);
174 
175     int32_t ret;
176     do {
177         /* get the raw key */
178         ret = RkcGetRmkRawKey(ksfDataRkc, &rawKey);
179         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Get rmk raw key failed! ret = 0x%" LOG_PUBLIC "X", ret)
180 
181         /* HKDF-HMAC */
182         const struct HksBlob salt = { HKS_RKC_SALT_LEN, (uint8_t *)(ksfDataRkc->rmkSalt) };
183         ret = RkcHkdfHmac(ksfDataRkc->rmkHashAlg, &rawKey, &salt, ksfDataRkc->rmkIter, rmk);
184         HKS_IF_NOT_SUCC_LOGE(ret, "HKDF failed! ret = 0x%" LOG_PUBLIC "X", ret)
185     } while (0);
186 
187     (void)memset_s(rawKey.data, rawKey.size, 0, rawKey.size);
188     HKS_FREE_BLOB(rawKey);
189     return ret;
190 }
191 
RkcRecoverRkTime(struct HksTime createdTime,struct HksTime expiredTime)192 void RkcRecoverRkTime(struct HksTime createdTime, struct HksTime expiredTime)
193 {
194     g_hksRkcCfg.rkCreatedTime = createdTime;
195     g_hksRkcCfg.rkExpiredTime = expiredTime;
196 }
197 
RkcRecoverMkTime(struct HksTime createdTime,struct HksTime expiredTime)198 void RkcRecoverMkTime(struct HksTime createdTime, struct HksTime expiredTime)
199 {
200     g_hksRkcMk.mkCreatedTime = createdTime;
201     g_hksRkcMk.mkExpiredTime = expiredTime;
202 }
203 
RkcMakeRandomMaterial(struct HksKsfDataRkc * ksfDataRkc)204 static int32_t RkcMakeRandomMaterial(struct HksKsfDataRkc *ksfDataRkc)
205 {
206     /* two random number */
207     struct HksBlob random1 = { HKS_RKC_MATERIAL_LEN, ksfDataRkc->rkMaterial1 };
208     struct HksBlob random2 = { HKS_RKC_MATERIAL_LEN, ksfDataRkc->rkMaterial2 };
209 
210     int32_t ret;
211     /* Generate 32 * 2 random number: R1 + R2 and fill material */
212     ret = HksCryptoHalFillPrivRandom(&random1);
213     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "Generate random1 failed! ret = 0x%" LOG_PUBLIC "X", ret)
214     ret = HksCryptoHalFillPrivRandom(&random2);
215     if (ret != HKS_SUCCESS) {
216         HKS_LOG_E("Generate random2 failed! ret = 0x%" LOG_PUBLIC "X", ret);
217         (void)memset_s(random1.data, HKS_RKC_MATERIAL_LEN, 0, HKS_RKC_MATERIAL_LEN);
218     }
219     return ret;
220 }
221 
InitMkCryptUsageSpec(uint8_t * iv,const uint32_t ivSize,struct HksUsageSpec * usageSpec)222 static int32_t InitMkCryptUsageSpec(uint8_t *iv, const uint32_t ivSize, struct HksUsageSpec *usageSpec)
223 {
224     usageSpec->mode = HKS_MODE_GCM;
225     usageSpec->padding = HKS_PADDING_NONE;
226     usageSpec->digest = HKS_DIGEST_NONE;
227     usageSpec->algType = HKS_ALG_AES;
228 
229     struct HksAeadParam *aeadParam = (struct HksAeadParam *)usageSpec->algParam;
230     aeadParam->aad.size = HKS_RKC_MK_ADD_DATA_LEN;
231     aeadParam->aad.data = (uint8_t *)&g_hksRkcMkAddData;
232     aeadParam->nonce.size = ivSize;
233     aeadParam->nonce.data = iv;
234     aeadParam->payloadLen = HKS_RKC_RMK_EK_LEN;
235 
236     return HKS_SUCCESS;
237 }
238 
ExecuteMkCrypt(const struct HksKsfDataMk * ksfDataMk,const struct HksBlob * rmk,struct HksBlob * plainText,struct HksBlob * cipherText,const bool encrypt)239 int32_t ExecuteMkCrypt(const struct HksKsfDataMk *ksfDataMk, const struct HksBlob *rmk,
240     struct HksBlob *plainText, struct HksBlob *cipherText, const bool encrypt)
241 {
242     struct HksAeadParam aeadParam;
243     (void)memset_s(&aeadParam, sizeof(aeadParam), 0, sizeof(aeadParam));
244     struct HksUsageSpec usageSpec = { .algParam = (void *)(&aeadParam) };
245     int32_t ret = InitMkCryptUsageSpec((uint8_t *)ksfDataMk->mkIv, HKS_RKC_MK_IV_LEN, &usageSpec);
246     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "Init mk crypt usageSpec failed! ret = 0x%" LOG_PUBLIC "X", ret)
247 
248     const struct HksBlob key = { HKS_RKC_RMK_EK_LEN, rmk->data };
249     if (encrypt) {
250         aeadParam.tagLenEnc = HKS_AE_TAG_LEN;
251         struct HksBlob tag = { HKS_AE_TAG_LEN, cipherText->data + key.size };
252         ret = HksCryptoHalEncrypt(&key, &usageSpec, plainText, cipherText, &tag);
253     } else {
254         aeadParam.tagDec.size = HKS_AE_TAG_LEN;
255         aeadParam.tagDec.data = cipherText->data + cipherText->size - HKS_AE_TAG_LEN;
256         cipherText->size -= HKS_AE_TAG_LEN; /* the decrypt len should remove the tag len */
257         ret = HksCryptoHalDecrypt(&key, &usageSpec, cipherText, plainText);
258     }
259     if (ret != HKS_SUCCESS) {
260         HKS_LOG_E("Crypto mk failed! ret = 0x%" LOG_PUBLIC "X", ret);
261         ret = HKS_ERROR_CRYPTO_ENGINE_ERROR; /* need return this error code for hichian call refresh func */
262     }
263 
264     return ret;
265 }
266 
RkcMkCrypt(const struct HksKsfDataRkc * ksfDataRkc,const struct HksKsfDataMk * ksfDataMk,struct HksBlob * plainText,struct HksBlob * cipherText,const bool encrypt)267 int32_t RkcMkCrypt(const struct HksKsfDataRkc *ksfDataRkc, const struct HksKsfDataMk *ksfDataMk,
268     struct HksBlob *plainText, struct HksBlob *cipherText, const bool encrypt)
269 {
270     struct HksBlob rmk;
271     rmk.data = (uint8_t *)HksMalloc(HKS_RKC_RMK_LEN);
272     HKS_IF_NULL_LOGE_RETURN(rmk.data, HKS_ERROR_MALLOC_FAIL, "Malloc rmk failed!")
273 
274     rmk.size = HKS_RKC_RMK_LEN;
275     (void)memset_s(rmk.data, rmk.size, 0, rmk.size);
276 
277     int32_t ret;
278     do {
279         ret = RkcDeriveRmk(ksfDataRkc, &rmk);
280         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Derive rmk failed! ret = 0x%" LOG_PUBLIC "X", ret)
281 
282         ret = ExecuteMkCrypt(ksfDataMk, &rmk, plainText, cipherText, encrypt);
283         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Crypto mk failed! ret = 0x%" LOG_PUBLIC "X", ret)
284     } while (0);
285 
286     /* the data of root key should be cleared after use */
287     (void)memset_s(rmk.data, rmk.size, 0, rmk.size);
288     HKS_FREE_BLOB(rmk);
289     return ret;
290 }
291 
RkcMaskMk(const struct HksBlob * mk)292 int32_t RkcMaskMk(const struct HksBlob *mk)
293 {
294     struct HksBlob mkMaskBlob = { HKS_RKC_MK_LEN, g_hksRkcCfg.mkMask };
295     int32_t ret = HksCryptoHalFillPrivRandom(&mkMaskBlob);
296     HKS_IF_NOT_SUCC_LOGE_RETURN(ret, ret, "Generate mk mask failed! ret = 0x%" LOG_PUBLIC "X", ret)
297 
298     for (uint32_t i = 0; i < HKS_RKC_MK_LEN; ++i) {
299         g_hksRkcMk.mkWithMask[i] = mk->data[i] ^ g_hksRkcCfg.mkMask[i];
300     }
301 
302     g_hksRkcMk.valid = true;
303     return ret;
304 }
305 
RkcMakeMk(struct HksKsfDataRkc * ksfDataRkc,struct HksKsfDataMk * ksfDataMk)306 static int32_t RkcMakeMk(struct HksKsfDataRkc *ksfDataRkc, struct HksKsfDataMk *ksfDataMk)
307 {
308     struct HksBlob mk;
309     mk.data = (uint8_t *)HksMalloc(HKS_RKC_MK_LEN);
310     HKS_IF_NULL_LOGE_RETURN(mk.data, HKS_ERROR_MALLOC_FAIL, "Malloc mk failed!")
311 
312     mk.size = HKS_RKC_MK_LEN;
313 
314     int32_t ret;
315     do {
316         /* generate main key */
317         ret = HksCryptoHalFillPrivRandom(&mk);
318         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Generate mk failed! ret = 0x%" LOG_PUBLIC "X", ret)
319 
320         /* generate the IV of main key */
321         struct HksBlob mkIvBlob = { HKS_RKC_MK_IV_LEN, ksfDataMk->mkIv };
322         ret = HksCryptoHalFillPrivRandom(&mkIvBlob);
323         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Generate mkIv failed! ret = 0x%" LOG_PUBLIC "X", ret)
324 
325         struct HksBlob cipherTextBlob = { HKS_RKC_MK_CIPHER_TEXT_LEN, ksfDataMk->mkCiphertext };
326         ret = RkcMkCrypt(ksfDataRkc, ksfDataMk, &mk, &cipherTextBlob, true); /* true: encrypt */
327         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Encrypt mk failed! ret = 0x%" LOG_PUBLIC "X", ret)
328 
329         /* the main key in memory should be masked */
330         ret = RkcMaskMk(&mk);
331     } while (0);
332 
333     (void)memset_s(mk.data, mk.size, 0, mk.size);
334     HKS_FREE_BLOB(mk);
335     return ret;
336 }
337 
CloneNewStr(const char * srcStr,const uint32_t strLenMax)338 static char *CloneNewStr(const char *srcStr, const uint32_t strLenMax)
339 {
340     HKS_IF_NULL_LOGE_RETURN(srcStr, NULL, "Invalid input string!")
341 
342     const uint32_t strLen = strlen(srcStr);
343     if ((strLen == 0) || (strLen > strLenMax)) {
344         HKS_LOG_E("Invalid input string! len = 0x%" LOG_PUBLIC "X, maxLen = 0x%" LOG_PUBLIC "X", strLen, strLenMax);
345         return NULL;
346     }
347 
348     char *newBuf = (char *)HksMalloc(strLen + 1); /* 1: end char */
349     HKS_IF_NULL_LOGE_RETURN(newBuf, NULL, "Malloc new buffer failed!")
350 
351     if (memcpy_s(newBuf, strLen, srcStr, strLen) != EOK) {
352         HKS_LOG_E("Memcpy new buffer failed!");
353         HKS_FREE(newBuf);
354         return NULL;
355     }
356     newBuf[strLen] = '\0';
357 
358     return newBuf;
359 }
360 
InitKsfAttr(const struct HksKsfAttr * ksfAttr,uint8_t ksfType)361 int32_t InitKsfAttr(const struct HksKsfAttr *ksfAttr, uint8_t ksfType)
362 {
363     int32_t initRet = HKS_SUCCESS;
364 
365     /* clone keystore filename from parameter. */
366     for (uint8_t i = 0; i < HKS_KSF_NUM; ++i) {
367         char *fileName = CloneNewStr(ksfAttr->name[i], HKS_KSF_NAME_LEN_MAX);
368         /* the memory will be freed by HksCfgDestroy() */
369         if (fileName == NULL) {
370             initRet = HKS_ERROR_MALLOC_FAIL;
371             break;
372         }
373 
374         if (ksfType == HKS_KSF_TYPE_RKC) {
375             g_hksRkcCfg.ksfAttrRkc.name[i] = fileName;
376         } else {
377             g_hksRkcCfg.ksfAttrMk.name[i] = fileName;
378         }
379     }
380 
381     if (initRet != HKS_SUCCESS) {
382         HksCfgClearMem();
383     }
384     return initRet;
385 }
386 
UpgradeMkIfNeeded(uint32_t mkVersion,const struct HksBlob * mk)387 static int32_t UpgradeMkIfNeeded(uint32_t mkVersion, const struct HksBlob *mk)
388 {
389     if (mkVersion == HKS_MK_VER) {
390         return HKS_SUCCESS; // no need upgrade
391     }
392     // reserved function for future upgrade, e.g. version 2->3
393     (void)mk;
394     return HKS_SUCCESS;
395 }
396 
RkcLoadKsf(void)397 static int32_t RkcLoadKsf(void)
398 {
399     int32_t ret;
400     struct HksKsfDataRkcWithVer *validKsfDataRkcWithVer =
401         (struct HksKsfDataRkcWithVer *)HksMalloc(sizeof(struct HksKsfDataRkcWithVer));
402     struct HksKsfDataMkWithVer *validKsfDataMkWithVer =
403         (struct HksKsfDataMkWithVer *)HksMalloc(sizeof(struct HksKsfDataRkcWithVer));
404     do {
405         if (validKsfDataRkcWithVer == NULL || validKsfDataMkWithVer == NULL) {
406             ret = HKS_ERROR_MALLOC_FAIL;
407             break;
408         }
409 
410         ret = ReadAllKsfMk(validKsfDataMkWithVer);
411         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "All mk ksf file are invalid! ret = 0x%" LOG_PUBLIC "X", ret)
412 
413         RkcRecoverMkTime(validKsfDataMkWithVer->ksfDataMk.mkCreatedTime,
414             validKsfDataMkWithVer->ksfDataMk.mkExpiredTime);
415 
416         /* Initialize the attribute of rkc keystore file */
417         struct HksKsfAttr ksfAttrRkc = {{ "rinfo1_v2.data", "rinfo2_v2.data" }};
418         ret = InitKsfAttr(&ksfAttrRkc, HKS_KSF_TYPE_RKC);
419         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Init attribute of rkc keystore file failed! ret = 0x%" LOG_PUBLIC "X", ret)
420 
421         ret = ReadAllKsfRkc(validKsfDataRkcWithVer);
422         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "All rkc ksf file are invalid! ret = 0x%" LOG_PUBLIC "X", ret)
423 
424         RkcRecoverRkTime(validKsfDataRkcWithVer->ksfDataRkc.rkCreatedTime,
425             validKsfDataRkcWithVer->ksfDataRkc.rkExpiredTime);
426 
427         // decrypt main key
428         struct HksBlob tempMkBlob = { HKS_RKC_MK_LEN, g_hksRkcMk.mkWithMask };
429         struct HksBlob mkCipherText = { HKS_RKC_MK_CIPHER_TEXT_LEN, validKsfDataMkWithVer->ksfDataMk.mkCiphertext };
430         ret = RkcMkCrypt(&(validKsfDataRkcWithVer->ksfDataRkc), &(validKsfDataMkWithVer->ksfDataMk),
431             &tempMkBlob, &mkCipherText, false); /* false: decrypt */
432         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Main key decrypt failed! ret = 0x%" LOG_PUBLIC "X", ret)
433 
434         /* the main key in memory should be masked */
435         ret = RkcMaskMk(&tempMkBlob);
436         HKS_IF_NOT_SUCC_BREAK(ret);
437 
438         ret = UpgradeMkIfNeeded(validKsfDataMkWithVer->mkVersion, &tempMkBlob);
439     } while (0);
440 
441     HKS_MEMSET_FREE_PTR(validKsfDataRkcWithVer, sizeof(struct HksKsfDataRkcWithVer));
442     HKS_MEMSET_FREE_PTR(validKsfDataMkWithVer, sizeof(struct HksKsfDataMkWithVer));
443     return ret;
444 }
445 
FillKsfDataRkcWithVer(struct HksKsfDataRkcWithVer * ksfDataRkcWithVer)446 int32_t FillKsfDataRkcWithVer(struct HksKsfDataRkcWithVer *ksfDataRkcWithVer)
447 {
448     HKS_IF_NULL_LOGE_RETURN(ksfDataRkcWithVer, HKS_ERROR_INVALID_ARGUMENT, "Invalid rkc ksf");
449 
450     (void)memset_s(ksfDataRkcWithVer, sizeof(struct HksKsfDataRkcWithVer), 0, sizeof(struct HksKsfDataRkcWithVer));
451     ksfDataRkcWithVer->rkVersion = g_hksRkcCfg.rkVersion;
452     ksfDataRkcWithVer->ksfDataRkc.rmkIter = g_hksRkcCfg.rmkIter;
453     ksfDataRkcWithVer->ksfDataRkc.rmkHashAlg = g_hksRkcCfg.rmkHashAlg;
454     int32_t ret;
455     do {
456         /* Two material are generated by random number. */
457         ret = RkcMakeRandomMaterial(&(ksfDataRkcWithVer->ksfDataRkc));
458         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Generate material failed! ret = 0x%" LOG_PUBLIC "X", ret)
459 
460         /* The salt value is generated by random number. */
461         struct HksBlob salt = { HKS_RKC_SALT_LEN, ksfDataRkcWithVer->ksfDataRkc.rmkSalt };
462         ret = HksCryptoHalFillPrivRandom(&salt);
463         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Generate salt failed! ret = 0x%" LOG_PUBLIC "X", ret)
464     } while (0);
465 
466     if (ret != HKS_SUCCESS) {
467         (void)memset_s(ksfDataRkcWithVer, sizeof(struct HksKsfDataRkcWithVer), 0, sizeof(struct HksKsfDataRkcWithVer));
468     }
469     return ret;
470 }
471 
FillKsfDataMkWithVer(struct HksKsfDataMkWithVer * ksfDataMkWithVer)472 void FillKsfDataMkWithVer(struct HksKsfDataMkWithVer *ksfDataMkWithVer)
473 {
474     (void)memset_s(ksfDataMkWithVer, sizeof(struct HksKsfDataMkWithVer), 0, sizeof(struct HksKsfDataMkWithVer));
475     ksfDataMkWithVer->mkVersion = g_hksRkcCfg.mkVersion;
476     ksfDataMkWithVer->ksfDataMk.mkEncryptAlg = g_hksRkcCfg.mkEncryptAlg;
477 }
478 
RkcWriteAllKsf(const struct HksKsfDataRkcWithVer * ksfDataRkcWithVer,const struct HksKsfDataMkWithVer * ksfDataMkWithVer)479 int32_t RkcWriteAllKsf(const struct HksKsfDataRkcWithVer *ksfDataRkcWithVer,
480     const struct HksKsfDataMkWithVer *ksfDataMkWithVer)
481 {
482     bool isSuccess = false;
483     int32_t ret;
484     for (uint32_t i = 0; i < HKS_KSF_NUM; ++i) {
485         ret = HksWriteKsfRkc(g_hksRkcCfg.ksfAttrRkc.name[i], ksfDataRkcWithVer);
486         HKS_IF_NOT_SUCC_LOGE_RETURN(ret, HKS_ERROR_WRITE_FILE_FAIL, "make mk failed! ret = 0x%" LOG_PUBLIC "X", ret)
487     }
488     for (uint32_t i = 0; i < HKS_KSF_NUM; ++i) {
489         ret = HksWriteKsfMk(g_hksRkcCfg.ksfAttrMk.name[i], ksfDataMkWithVer);
490         if (ret == HKS_SUCCESS) {
491             isSuccess = true;
492         }
493     }
494 
495     /* If all keystore file were written fail, return error code, otherwise, return success code. */
496     return (isSuccess ? HKS_SUCCESS : HKS_ERROR_WRITE_FILE_FAIL);
497 }
498 
RkcCreateKsf(void)499 static int32_t RkcCreateKsf(void)
500 {
501     int32_t ret;
502     struct HksKsfDataRkcWithVer *newKsfDataRkcWithVer =
503         (struct HksKsfDataRkcWithVer *)HksMalloc(sizeof(struct HksKsfDataRkcWithVer));
504     struct HksKsfDataMkWithVer *newKsfDataMkWithVer =
505         (struct HksKsfDataMkWithVer *)HksMalloc(sizeof(struct HksKsfDataMkWithVer));
506     do {
507         if (newKsfDataRkcWithVer == NULL || newKsfDataMkWithVer == NULL) {
508             HKS_LOG_E("Malloc rkc or mk ksf data failed!");
509             ret = HKS_ERROR_INSUFFICIENT_MEMORY;
510             break;
511         }
512 
513         FillKsfDataMkWithVer(newKsfDataMkWithVer);
514         ret = FillKsfDataRkcWithVer(newKsfDataRkcWithVer);
515         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Fill rkc data failed")
516 
517         /* make main key. */
518         ret = RkcMakeMk(&(newKsfDataRkcWithVer->ksfDataRkc), &(newKsfDataMkWithVer->ksfDataMk));
519         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "make mk failed! ret = 0x%" LOG_PUBLIC "X", ret)
520 
521         /* Initialize rkc keystore file name (mk already done in HksRkcInit) */
522         struct HksKsfAttr ksfAttrRkc = {{ "rinfo1_v2.data", "rinfo2_v2.data" }};
523         ret = InitKsfAttr(&ksfAttrRkc, HKS_KSF_TYPE_RKC);
524         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Init attribute of rkc keystore file failed! ret = 0x%" LOG_PUBLIC "X", ret)
525 
526         /* Write the root key component and the main key data into all keystore files */
527         ret = RkcWriteAllKsf(newKsfDataRkcWithVer, newKsfDataMkWithVer);
528         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Write rkc & mk ksf failed! ret = 0x%" LOG_PUBLIC "X", ret)
529     } while (0);
530 
531     /* the data of root & main key should be cleared after use */
532     HKS_MEMSET_FREE_PTR(newKsfDataRkcWithVer, sizeof(struct HksKsfDataRkcWithVer));
533     HKS_MEMSET_FREE_PTR(newKsfDataMkWithVer, sizeof(struct HksKsfDataMkWithVer));
534     return ret;
535 }
536 
HksRkcInit(void)537 int32_t HksRkcInit(void)
538 {
539     if (g_hksRkcCfg.state == HKS_RKC_STATE_VALID) {
540         HKS_LOG_I("Hks rkc is running!");
541         return HKS_SUCCESS;
542     }
543 
544     int32_t ret;
545     do {
546         /* Initialize the attribute of mk keystore file */
547         struct HksKsfAttr ksfAttrMk = {{ "minfo1_v2.data", "minfo2_v2.data" }};
548         ret = InitKsfAttr(&ksfAttrMk, HKS_KSF_TYPE_MK);
549         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "Init attribute of mk keystore file failed! ret = 0x%" LOG_PUBLIC "X", ret)
550 
551         if (KsfExist(HKS_KSF_TYPE_MK)) {
552             ret = RkcLoadKsf();
553         } else {
554             /* Initialize the attribute of rkc keystore file */
555             struct HksKsfAttr ksfAttrRkcV1 = {{ "info1.data", "info2.data" }};
556             ret = InitKsfAttr(&ksfAttrRkcV1, HKS_KSF_TYPE_RKC);
557             HKS_IF_NOT_SUCC_LOGE_BREAK(ret,
558                 "Init attribute of rkc keystore file failed! ret = 0x%" LOG_PUBLIC "X", ret)
559 #ifdef HKS_ENABLE_UPGRADE_RKC_DERIVE_ALG
560             if (KsfExist(HKS_KSF_TYPE_RKC)) { // mk ksf not exists, rkc ksf exists => version 1
561                 ret = UpgradeV1ToV2();
562             } else { // latest version
563 #endif
564                 ret = RkcCreateKsf();
565 #ifdef HKS_ENABLE_UPGRADE_RKC_DERIVE_ALG
566             }
567 #endif
568         }
569     } while (0);
570 
571     if (ret != HKS_SUCCESS) {
572         HksCfgDestroy();
573         HksMkDestroy();
574         return ret;
575     }
576 
577     g_hksRkcCfg.state = HKS_RKC_STATE_VALID;
578     return HKS_SUCCESS;
579 }
580 
HksCfgDestroy(void)581 void HksCfgDestroy(void)
582 {
583     g_hksRkcCfg.state = HKS_RKC_STATE_INVALID;
584     HksCfgClearMem();
585 }
586 
HksMkDestroy(void)587 void HksMkDestroy(void)
588 {
589     HksMkClearMem();
590 }
591 
HksCfgClearMem(void)592 void HksCfgClearMem(void)
593 {
594     for (uint32_t i = 0; i < HKS_KSF_NUM; ++i) {
595         HKS_FREE(g_hksRkcCfg.ksfAttrRkc.name[i]);
596         HKS_FREE(g_hksRkcCfg.ksfAttrMk.name[i]);
597     }
598 
599     (void)memset_s(&g_hksRkcCfg, sizeof(g_hksRkcCfg), 0, sizeof(g_hksRkcCfg));
600 }
601 
HksMkClearMem(void)602 void HksMkClearMem(void)
603 {
604     (void)memset_s(&g_hksRkcMk, sizeof(g_hksRkcMk), 0, sizeof(g_hksRkcMk));
605 }
606 
HksRkcGetMainKey(struct HksBlob * mainKey)607 int32_t HksRkcGetMainKey(struct HksBlob *mainKey)
608 {
609     if (!g_hksRkcMk.valid) {
610         HKS_LOG_E("Main key is invalid now, initialization is required before Getting main key!");
611         return HKS_FAILURE;
612     }
613 
614     if (mainKey->size != HKS_RKC_MK_LEN) {
615         HKS_LOG_E("Invalid mainKey size! size = 0x%" LOG_PUBLIC "X", mainKey->size);
616         return HKS_ERROR_INVALID_ARGUMENT;
617     }
618 
619     /* remove mask */
620     for (uint32_t i = 0; i < HKS_RKC_MK_LEN; ++i) {
621         mainKey->data[i] = g_hksRkcMk.mkWithMask[i] ^ g_hksRkcCfg.mkMask[i];
622     }
623 
624     return HKS_SUCCESS;
625 }
626 
HksRkcBuildParamSet(struct HksParamSet ** paramSetOut)627 int32_t HksRkcBuildParamSet(struct HksParamSet **paramSetOut)
628 {
629     int32_t ret;
630     struct HksParamSet *paramSet = NULL;
631     do {
632         ret = HksInitParamSet(&paramSet);
633         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HksInitParamSet failed")
634 
635         struct HksParam storageLevelParam;
636         storageLevelParam.tag = HKS_TAG_AUTH_STORAGE_LEVEL;
637         storageLevelParam.uint32Param = HKS_AUTH_STORAGE_LEVEL_DE;
638         ret = HksAddParams(paramSet, &storageLevelParam, 1);
639         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HksAddParams failed")
640 
641         ret = HksBuildParamSet(&paramSet);
642         HKS_IF_NOT_SUCC_LOGE_BREAK(ret, "HksBuildParamSet failed")
643         *paramSetOut = paramSet;
644         return HKS_SUCCESS;
645     } while (0);
646     HksFreeParamSet(&paramSet);
647     return ret;
648 }
649 #endif /* _CUT_AUTHENTICATE_ */
650