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 "crypto/crypto_manager.h"
17
18 #include <random>
19
20 #include "gtest/gtest.h"
21
22 #include "access_token.h"
23 #include "accesstoken_kit.h"
24 #include "hks_api.h"
25 #include "hks_param.h"
26 #include "nativetoken_kit.h"
27 #include "token_setproc.h"
28
29 namespace OHOS::Test {
30 using namespace testing::ext;
31 using namespace OHOS::DistributedData;
32 using namespace OHOS::Security::AccessToken;
33
34 static constexpr int32_t KEY_LENGTH = 32;
35 static constexpr int32_t NONCE_SIZE = 12;
36 static constexpr int32_t INVALID_AREA = -1;
37 static constexpr int32_t TEST_USERID_NUM = 100;
38 static constexpr const char *TEST_USERID = "100";
39 static constexpr const char *TEST_BUNDLE_NAME = "test_application";
40 static constexpr const char *TEST_STORE_NAME = "test_store";
41 static constexpr const char *ROOT_KEY_ALIAS = "distributed_db_root_key";
42 static constexpr const char *PROCESS_NAME = "distributeddata";
43
44 class CryptoManagerTest : public testing::Test {
45 public:
46 static void SetUpTestCase(void);
47 static void TearDownTestCase(void);
SetUp()48 void SetUp() {}
TearDown()49 void TearDown() {}
50
51 static void SetNativeTokenIdFromProcess(const std::string &process);
52 static std::vector<uint8_t> Random(int32_t len);
53 static void DeleteRootKey(int32_t area);
54 static uint32_t GetStorageLevel(int32_t area);
55
56 static std::vector<uint8_t> randomKey;
57 static std::vector<uint8_t> vecRootKeyAlias;
58 static std::vector<uint8_t> nonce;
59 };
60
61 std::vector<uint8_t> CryptoManagerTest::randomKey;
62 std::vector<uint8_t> CryptoManagerTest::vecRootKeyAlias;
63 std::vector<uint8_t> CryptoManagerTest::nonce;
64
SetNativeTokenIdFromProcess(const std::string & process)65 void CryptoManagerTest::SetNativeTokenIdFromProcess(const std::string &process)
66 {
67 std::string dumpInfo;
68 AtmToolsParamInfo info;
69 info.processName = process;
70 AccessTokenKit::DumpTokenInfo(info, dumpInfo);
71 size_t pos = dumpInfo.find("\"tokenID\": ");
72 if (pos == std::string::npos) {
73 return;
74 }
75 pos += std::string("\"tokenID\": ").length();
76 std::string numStr;
77 while (pos < dumpInfo.length() && std::isdigit(dumpInfo[pos])) {
78 numStr += dumpInfo[pos];
79 ++pos;
80 }
81 std::istringstream iss(numStr);
82 AccessTokenID tokenID;
83 iss >> tokenID;
84 SetSelfTokenID(tokenID);
85 }
86
SetUpTestCase(void)87 void CryptoManagerTest::SetUpTestCase(void)
88 {
89 SetNativeTokenIdFromProcess(PROCESS_NAME);
90
91 randomKey = Random(KEY_LENGTH);
92 vecRootKeyAlias = std::vector<uint8_t>(ROOT_KEY_ALIAS, ROOT_KEY_ALIAS + strlen(ROOT_KEY_ALIAS));
93 nonce = Random(NONCE_SIZE);
94 }
95
TearDownTestCase(void)96 void CryptoManagerTest::TearDownTestCase(void)
97 {
98 randomKey.assign(randomKey.size(), 0);
99 nonce.assign(nonce.size(), 0);
100 DeleteRootKey(CryptoManager::Area::EL1);
101 DeleteRootKey(CryptoManager::Area::EL2);
102 DeleteRootKey(CryptoManager::Area::EL4);
103 }
104
Random(int32_t len)105 std::vector<uint8_t> CryptoManagerTest::Random(int32_t len)
106 {
107 std::random_device randomDevice;
108 std::uniform_int_distribution<int> distribution(0, std::numeric_limits<uint8_t>::max());
109 std::vector<uint8_t> key(len);
110 for (uint32_t i = 0; i < len; i++) {
111 key[i] = static_cast<uint8_t>(distribution(randomDevice));
112 }
113 return key;
114 }
115
GetStorageLevel(int32_t area)116 uint32_t CryptoManagerTest::GetStorageLevel(int32_t area)
117 {
118 if (area >= CryptoManager::Area::EL4 && area <= CryptoManager::Area::EL5) {
119 return HKS_AUTH_STORAGE_LEVEL_ECE;
120 }
121 if (area >= CryptoManager::Area::EL2 && area <= CryptoManager::Area::EL3) {
122 return HKS_AUTH_STORAGE_LEVEL_CE;
123 }
124 return HKS_AUTH_STORAGE_LEVEL_DE;
125 }
126
DeleteRootKey(int32_t area)127 void CryptoManagerTest::DeleteRootKey(int32_t area)
128 {
129 struct HksParamSet *params = nullptr;
130 if (HksInitParamSet(¶ms) != HKS_SUCCESS) {
131 return;
132 }
133 auto storageLevel = GetStorageLevel(area);
134 std::vector<HksParam> hksParam = {
135 { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_AES },
136 { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_AES_KEY_SIZE_256 },
137 { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT },
138 { .tag = HKS_TAG_DIGEST, .uint32Param = 0 },
139 { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_NONE },
140 { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_GCM },
141 { .tag = HKS_TAG_AUTH_STORAGE_LEVEL, .uint32Param = storageLevel },
142 };
143 if (storageLevel > HKS_AUTH_STORAGE_LEVEL_DE) {
144 hksParam.emplace_back(HksParam { .tag = HKS_TAG_SPECIFIC_USER_ID, .int32Param = TEST_USERID_NUM });
145 }
146 if (HksAddParams(params, hksParam.data(), hksParam.size()) != HKS_SUCCESS) {
147 HksFreeParamSet(¶ms);
148 return;
149 }
150 if (HksBuildParamSet(¶ms) != HKS_SUCCESS) {
151 HksFreeParamSet(¶ms);
152 return;
153 }
154 struct HksBlob keyName = { uint32_t(vecRootKeyAlias.size()), const_cast<uint8_t *>(vecRootKeyAlias.data()) };
155 (void)HksDeleteKey(&keyName, params);
156 HksFreeParamSet(¶ms);
157 }
158
159 /**
160 * @tc.name: GenerateRootKeyTest001
161 * @tc.desc: generate the root key of DE
162 * @tc.type: FUNC
163 */
164 HWTEST_F(CryptoManagerTest, GenerateRootKeyTest001, TestSize.Level0)
165 {
166 auto errCode = CryptoManager::GetInstance().GenerateRootKey();
167 EXPECT_EQ(errCode, CryptoManager::ErrCode::SUCCESS);
168
169 errCode = CryptoManager::GetInstance().CheckRootKey();
170 ASSERT_EQ(errCode, CryptoManager::ErrCode::SUCCESS);
171 }
172
173 /**
174 * @tc.name: EncryptAndDecryptTest001
175 * @tc.desc: encrypt random key and decrypt with EL1
176 * @tc.type: FUNC
177 */
178 HWTEST_F(CryptoManagerTest, EncryptAndDecryptTest001, TestSize.Level0)
179 {
180 auto errCode = CryptoManager::GetInstance().GenerateRootKey();
181 ASSERT_EQ(errCode, CryptoManager::ErrCode::SUCCESS);
182 CryptoManager::CryptoParams encryptParams = { .area = CryptoManager::Area::EL1, .userId = TEST_USERID };
183 auto encryptKey = CryptoManager::GetInstance().Encrypt(randomKey, encryptParams);
184 ASSERT_FALSE(encryptKey.empty());
185 ASSERT_FALSE(encryptParams.nonce.empty());
186
187 CryptoManager::CryptoParams decryptParams = { .area = CryptoManager::Area::EL1, .userId = TEST_USERID,
188 .nonce = encryptParams.nonce };
189 auto decryptKey = CryptoManager::GetInstance().Decrypt(encryptKey, decryptParams);
190 ASSERT_FALSE(decryptKey.empty());
191 for (auto i = 0; i < KEY_LENGTH; ++i) {
192 ASSERT_EQ(decryptKey[i], randomKey[i]);
193 }
194 decryptKey.assign(encryptKey.size(), 0);
195 }
196
197 /**
198 * @tc.name: EncryptAndDecryptTest002
199 * @tc.desc: encrypt random key and decrypt with EL2
200 * @tc.type: FUNC
201 */
202 HWTEST_F(CryptoManagerTest, EncryptAndDecryptTest002, TestSize.Level0)
203 {
204 CryptoManager::CryptoParams encryptParams = { .area = CryptoManager::Area::EL2, .userId = TEST_USERID };
205 auto encryptKey = CryptoManager::GetInstance().Encrypt(randomKey, encryptParams);
206 ASSERT_FALSE(encryptKey.empty());
207 ASSERT_FALSE(encryptParams.nonce.empty());
208
209 CryptoManager::CryptoParams decryptParams = { .area = CryptoManager::Area::EL2, .userId = TEST_USERID,
210 .nonce = encryptParams.nonce };
211 auto decryptKey = CryptoManager::GetInstance().Decrypt(encryptKey, decryptParams);
212 ASSERT_FALSE(decryptKey.empty());
213 for (auto i = 0; i < KEY_LENGTH; ++i) {
214 ASSERT_EQ(decryptKey[i], randomKey[i]);
215 }
216 decryptKey.assign(encryptKey.size(), 0);
217 }
218
219 /**
220 * @tc.name: EncryptAndDecryptTest003
221 * @tc.desc: encrypt random key and decrypt with EL3
222 * @tc.type: FUNC
223 */
224 HWTEST_F(CryptoManagerTest, EncryptAndDecryptTest003, TestSize.Level0)
225 {
226 CryptoManager::CryptoParams encryptParams = { .area = CryptoManager::Area::EL3, .userId = TEST_USERID };
227 auto encryptKey = CryptoManager::GetInstance().Encrypt(randomKey, encryptParams);
228 ASSERT_FALSE(encryptKey.empty());
229 ASSERT_FALSE(encryptParams.nonce.empty());
230
231 CryptoManager::CryptoParams decryptParams = { .area = CryptoManager::Area::EL3, .userId = TEST_USERID,
232 .nonce = encryptParams.nonce };
233 auto decryptKey = CryptoManager::GetInstance().Decrypt(encryptKey, decryptParams);
234 ASSERT_FALSE(decryptKey.empty());
235 for (auto i = 0; i < KEY_LENGTH; ++i) {
236 ASSERT_EQ(decryptKey[i], randomKey[i]);
237 }
238 decryptKey.assign(encryptKey.size(), 0);
239 }
240
241 /**
242 * @tc.name: EncryptAndDecryptTest004
243 * @tc.desc: encrypt random key and decrypt with EL4
244 * @tc.type: FUNC
245 */
246 HWTEST_F(CryptoManagerTest, EncryptAndDecryptTest004, TestSize.Level0)
247 {
248 CryptoManager::CryptoParams encryptParams = { .area = CryptoManager::Area::EL4, .userId = TEST_USERID };
249 auto encryptKey = CryptoManager::GetInstance().Encrypt(randomKey, encryptParams);
250 ASSERT_FALSE(encryptKey.empty());
251 ASSERT_FALSE(encryptParams.nonce.empty());
252
253 CryptoManager::CryptoParams decryptParams = { .area = CryptoManager::Area::EL4, .userId = TEST_USERID,
254 .nonce = encryptParams.nonce };
255 auto decryptKey = CryptoManager::GetInstance().Decrypt(encryptKey, decryptParams);
256 ASSERT_FALSE(decryptKey.empty());
257 for (auto i = 0; i < KEY_LENGTH; ++i) {
258 ASSERT_EQ(decryptKey[i], randomKey[i]);
259 }
260 decryptKey.assign(encryptKey.size(), 0);
261 }
262
263 /**
264 * @tc.name: EncryptAndDecryptTest005
265 * @tc.desc: encrypt random key and decrypt with INVALID_AREA
266 * @tc.type: FUNC
267 */
268 HWTEST_F(CryptoManagerTest, EncryptAndDecryptTest005, TestSize.Level0)
269 {
270 CryptoManager::CryptoParams encryptParams = { .area = INVALID_AREA, .userId = TEST_USERID };
271 auto encryptKey = CryptoManager::GetInstance().Encrypt(randomKey, encryptParams);
272 ASSERT_FALSE(encryptKey.empty());
273 ASSERT_FALSE(encryptParams.nonce.empty());
274
275 CryptoManager::CryptoParams decryptParams = { .area = encryptParams.area, .userId = TEST_USERID,
276 .nonce = encryptParams.nonce };
277 auto decryptKey = CryptoManager::GetInstance().Decrypt(encryptKey, decryptParams);
278 ASSERT_FALSE(decryptKey.empty());
279 for (auto i = 0; i < KEY_LENGTH; ++i) {
280 ASSERT_EQ(decryptKey[i], randomKey[i]);
281 }
282 decryptKey.assign(encryptKey.size(), 0);
283 }
284
285 /**
286 * @tc.name: EncryptAndDecryptTest006
287 * @tc.desc: encrypt random key and decrypt with EL1 and key alias
288 * @tc.type: FUNC
289 */
290 HWTEST_F(CryptoManagerTest, EncryptAndDecryptTest006, TestSize.Level0)
291 {
292 CryptoManager::CryptoParams encryptParams = { .area = CryptoManager::Area::EL1, .userId = TEST_USERID,
293 .keyAlias = vecRootKeyAlias };
294 auto encryptKey = CryptoManager::GetInstance().Encrypt(randomKey, encryptParams);
295 ASSERT_FALSE(encryptKey.empty());
296 ASSERT_FALSE(encryptParams.nonce.empty());
297
298 CryptoManager::CryptoParams decryptParams = { .area = encryptParams.area, .userId = TEST_USERID,
299 .keyAlias = vecRootKeyAlias, .nonce = encryptParams.nonce };
300 auto decryptKey = CryptoManager::GetInstance().Decrypt(encryptKey, decryptParams);
301 ASSERT_FALSE(decryptKey.empty());
302 for (auto i = 0; i < KEY_LENGTH; ++i) {
303 ASSERT_EQ(decryptKey[i], randomKey[i]);
304 }
305 decryptKey.assign(encryptKey.size(), 0);
306 }
307
308 /**
309 * @tc.name: EncryptAndDecryptTest007
310 * @tc.desc: encrypt random key and decrypt with EL1 and nonce value
311 * @tc.type: FUNC
312 */
313 HWTEST_F(CryptoManagerTest, EncryptAndDecryptTest007, TestSize.Level0)
314 {
315 CryptoManager::CryptoParams encryptParams = { .area = CryptoManager::Area::EL1, .userId = TEST_USERID,
316 .nonce = nonce };
317 auto encryptKey = CryptoManager::GetInstance().Encrypt(randomKey, encryptParams);
318 ASSERT_FALSE(encryptKey.empty());
319
320 CryptoManager::CryptoParams decryptParams = { .area = encryptParams.area, .userId = TEST_USERID,
321 .keyAlias = vecRootKeyAlias, .nonce = encryptParams.nonce };
322 auto decryptKey = CryptoManager::GetInstance().Decrypt(encryptKey, decryptParams);
323 ASSERT_FALSE(decryptKey.empty());
324 for (auto i = 0; i < KEY_LENGTH; ++i) {
325 ASSERT_EQ(decryptKey[i], randomKey[i]);
326 }
327 decryptKey.assign(encryptKey.size(), 0);
328 }
329
330 /**
331 * @tc.name: UpdateSecretMetaTest001
332 * @tc.desc: update meta with invalid params
333 * @tc.type: FUNC
334 */
335 HWTEST_F(CryptoManagerTest, UpdateSecretMetaTest001, TestSize.Level0)
336 {
337 std::vector<uint8_t> password;
338 StoreMetaData metaData;
339 SecretKeyMetaData secretKey;
340 CryptoManager::GetInstance().UpdateSecretMeta(password, metaData, "", secretKey);
341 ASSERT_TRUE(secretKey.sKey.empty());
342
343 secretKey.nonce = nonce;
344 secretKey.area = CryptoManager::Area::EL1;
345 CryptoManager::GetInstance().UpdateSecretMeta(randomKey, metaData, "", secretKey);
346 ASSERT_TRUE(secretKey.sKey.empty());
347 }
348
349 /**
350 * @tc.name: UpdateSecretMetaTest002
351 * @tc.desc: update meta with area EL1
352 * @tc.type: FUNC
353 */
354 HWTEST_F(CryptoManagerTest, UpdateSecretMetaTest002, TestSize.Level0)
355 {
356 auto errCode = CryptoManager::GetInstance().GenerateRootKey();
357 ASSERT_EQ(errCode, CryptoManager::ErrCode::SUCCESS);
358 SecretKeyMetaData secretKey;
359 StoreMetaData metaData;
360 metaData.bundleName = TEST_BUNDLE_NAME;
361 metaData.storeId = TEST_STORE_NAME;
362 metaData.user = TEST_USERID;
363 metaData.area = CryptoManager::Area::EL1;
364 CryptoManager::GetInstance().UpdateSecretMeta(randomKey, metaData, metaData.GetSecretKey(), secretKey);
365 ASSERT_FALSE(secretKey.sKey.empty());
366 ASSERT_FALSE(secretKey.nonce.empty());
367 ASSERT_EQ(secretKey.area, metaData.area);
368 }
369
370 /**
371 * @tc.name: UpdateSecretMetaTest003
372 * @tc.desc: update meta with area EL2
373 * @tc.type: FUNC
374 */
375 HWTEST_F(CryptoManagerTest, UpdateSecretMetaTest003, TestSize.Level0)
376 {
377 SecretKeyMetaData secretKey;
378 StoreMetaData metaData;
379 metaData.bundleName = TEST_BUNDLE_NAME;
380 metaData.storeId = TEST_STORE_NAME;
381 metaData.user = TEST_USERID;
382 metaData.area = CryptoManager::Area::EL2;
383 CryptoManager::GetInstance().UpdateSecretMeta(randomKey, metaData, metaData.GetSecretKey(), secretKey);
384 ASSERT_FALSE(secretKey.sKey.empty());
385 ASSERT_FALSE(secretKey.nonce.empty());
386 ASSERT_EQ(secretKey.area, metaData.area);
387 }
388
389 /**
390 * @tc.name: UpdateSecretMetaTest004
391 * @tc.desc: update meta with area EL3
392 * @tc.type: FUNC
393 */
394 HWTEST_F(CryptoManagerTest, UpdateSecretMetaTest004, TestSize.Level0)
395 {
396 SecretKeyMetaData secretKey;
397 StoreMetaData metaData;
398 metaData.bundleName = TEST_BUNDLE_NAME;
399 metaData.storeId = TEST_STORE_NAME;
400 metaData.user = TEST_USERID;
401 metaData.area = CryptoManager::Area::EL3;
402 CryptoManager::GetInstance().UpdateSecretMeta(randomKey, metaData, metaData.GetSecretKey(), secretKey);
403 ASSERT_FALSE(secretKey.sKey.empty());
404 ASSERT_FALSE(secretKey.nonce.empty());
405 ASSERT_EQ(secretKey.area, metaData.area);
406 }
407
408 /**
409 * @tc.name: UpdateSecretMetaTest005
410 * @tc.desc: update meta with area EL4
411 * @tc.type: FUNC
412 */
413 HWTEST_F(CryptoManagerTest, UpdateSecretMetaTest005, TestSize.Level0)
414 {
415 SecretKeyMetaData secretKey;
416 StoreMetaData metaData;
417 metaData.bundleName = TEST_BUNDLE_NAME;
418 metaData.storeId = TEST_STORE_NAME;
419 metaData.user = TEST_USERID;
420 metaData.area = CryptoManager::Area::EL4;
421 CryptoManager::GetInstance().UpdateSecretMeta(randomKey, metaData, metaData.GetSecretKey(), secretKey);
422 ASSERT_FALSE(secretKey.sKey.empty());
423 ASSERT_FALSE(secretKey.nonce.empty());
424 ASSERT_EQ(secretKey.area, metaData.area);
425 }
426 } // namespace OHOS::Test