• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022-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 #include "key_manager.h"
17 
18 #include <filesystem>
19 #include <string>
20 
21 #include "base_key.h"
22 #include "common_timer_errors.h"
23 #include "directory_ex.h"
24 #include "file_ex.h"
25 #include "fscrypt_key_v1.h"
26 #include "fscrypt_key_v2.h"
27 #include "libfscrypt/fscrypt_control.h"
28 #include "libfscrypt/key_control.h"
29 #include "parameter.h"
30 #include "storage_service_constant.h"
31 #include "storage_service_errno.h"
32 #include "storage_service_log.h"
33 
34 namespace OHOS {
35 namespace StorageDaemon {
36 const UserAuth NULL_KEY_AUTH = {};
37 const std::string DEFAULT_NEED_RESTORE_VERSION = "1";
38 
GetBaseKey(const std::string & dir)39 std::shared_ptr<BaseKey> KeyManager::GetBaseKey(const std::string& dir)
40 {
41     uint8_t versionFromPolicy = GetFscryptVersionFromPolicy();
42     uint8_t kernelSupportVersion = KeyCtrlGetFscryptVersion(MNT_DATA.c_str());
43     if (kernelSupportVersion == FSCRYPT_INVALID) {
44         LOGE("kernel not support fscrypt");
45         return nullptr;
46     }
47     if ((versionFromPolicy == kernelSupportVersion) && (kernelSupportVersion == FSCRYPT_V2)) {
48         return std::dynamic_pointer_cast<BaseKey>(std::make_shared<FscryptKeyV2>(dir));
49     }
50     if (versionFromPolicy != kernelSupportVersion) {
51         LOGE("version from policy %{public}u not same as version from kernel %{public}u", versionFromPolicy,
52              kernelSupportVersion);
53     }
54     return std::dynamic_pointer_cast<BaseKey>(std::make_shared<FscryptKeyV1>(dir));
55 }
56 
GenerateAndInstallDeviceKey(const std::string & dir)57 int KeyManager::GenerateAndInstallDeviceKey(const std::string &dir)
58 {
59     LOGI("enter");
60     globalEl1Key_ = GetBaseKey(dir);
61     if (globalEl1Key_ == nullptr) {
62         return -EOPNOTSUPP;
63     }
64 
65     if (globalEl1Key_->InitKey() == false) {
66         globalEl1Key_ = nullptr;
67         LOGE("global security key init failed");
68         return -EFAULT;
69     }
70 
71     if (globalEl1Key_->StoreKey(NULL_KEY_AUTH) == false) {
72         globalEl1Key_->ClearKey();
73         globalEl1Key_ = nullptr;
74         LOGE("global security key store failed");
75         return -EFAULT;
76     }
77 
78     if (globalEl1Key_->ActiveKey(FIRST_CREATE_KEY) == false) {
79         globalEl1Key_->ClearKey();
80         globalEl1Key_ = nullptr;
81         LOGE("global security key active failed");
82         return -EFAULT;
83     }
84 
85     (void)globalEl1Key_->UpdateKey();
86     hasGlobalDeviceKey_ = true;
87     LOGI("key create success");
88     return 0;
89 }
90 
RestoreDeviceKey(const std::string & dir)91 int KeyManager::RestoreDeviceKey(const std::string &dir)
92 {
93     LOGI("enter");
94     if (globalEl1Key_ != nullptr) {
95         LOGD("device key has existed");
96         return 0;
97     }
98 
99     globalEl1Key_ = GetBaseKey(dir);
100     if (globalEl1Key_ == nullptr) {
101         return -EOPNOTSUPP;
102     }
103 
104     if (globalEl1Key_->InitKey() == false) {
105         globalEl1Key_ = nullptr;
106         LOGE("global security key init failed");
107         return -EFAULT;
108     }
109 
110     if (globalEl1Key_->RestoreKey(NULL_KEY_AUTH) == false) {
111         globalEl1Key_ = nullptr;
112         LOGE("global security key restore failed");
113         return -EFAULT;
114     }
115 
116     if (globalEl1Key_->ActiveKey(RETRIEVE_KEY) == false) {
117         globalEl1Key_ = nullptr;
118         LOGE("global security key active failed");
119         return -EFAULT;
120     }
121     hasGlobalDeviceKey_ = true;
122     LOGI("key restore success");
123 
124     return 0;
125 }
126 
InitGlobalDeviceKey(void)127 int KeyManager::InitGlobalDeviceKey(void)
128 {
129     LOGI("enter");
130     int ret = InitFscryptPolicy();
131     if (ret < 0) {
132         LOGE("fscrypt init failed, fscrypt will not be enabled");
133         return ret;
134     }
135 
136     std::lock_guard<std::mutex> lock(keyMutex_);
137     if (hasGlobalDeviceKey_ || globalEl1Key_ != nullptr) {
138         LOGD("glabal device el1 have existed");
139         return 0;
140     }
141 
142     ret = MkDir(STORAGE_DAEMON_DIR, 0700); // para.0700: root only
143     if (ret && errno != EEXIST) {
144         LOGE("create storage daemon dir error");
145         return ret;
146     }
147     ret = MkDir(DEVICE_EL1_DIR, 0700);
148     if (ret) {
149         if (errno != EEXIST) {
150             LOGE("make device el1 dir error");
151             return ret;
152         }
153         UpgradeKeys({{0, DEVICE_EL1_DIR}});
154         return RestoreDeviceKey(DEVICE_EL1_DIR);
155     }
156 
157     return GenerateAndInstallDeviceKey(DEVICE_EL1_DIR);
158 }
159 
GenerateAndInstallUserKey(uint32_t userId,const std::string & dir,const UserAuth & auth,KeyType type)160 int KeyManager::GenerateAndInstallUserKey(uint32_t userId, const std::string &dir, const UserAuth &auth, KeyType type)
161 {
162     LOGI("enter");
163     if (HasElkey(userId, type)) {
164         LOGD("The user %{public}u el %{public}u have existed", userId, type);
165         return 0;
166     }
167 
168     auto elKey = GetBaseKey(dir);
169     if (elKey == nullptr) {
170         return -EOPNOTSUPP;
171     }
172 
173     if (elKey->InitKey() == false) {
174         LOGE("user security key init failed");
175         return -EFAULT;
176     }
177 
178     if (elKey->StoreKey(auth) == false) {
179         elKey->ClearKey();
180         LOGE("user security key store failed");
181         return -EFAULT;
182     }
183 
184     if (elKey->ActiveKey(FIRST_CREATE_KEY) == false) {
185         elKey->ClearKey();
186         LOGE("user security key active failed");
187         return -EFAULT;
188     }
189 
190     (void)elKey->UpdateKey();
191     if (type == EL1_KEY) {
192         userEl1Key_[userId] = elKey;
193     } else if (type == EL2_KEY) {
194         userEl2Key_[userId] = elKey;
195     } else if (type == EL3_KEY) {
196         userEl3Key_[userId] = elKey;
197     } else if (type == EL4_KEY) {
198         userEl4Key_[userId] = elKey;
199     }
200     LOGI("key create success");
201 
202     return 0;
203 }
204 
RestoreUserKey(uint32_t userId,const std::string & dir,const UserAuth & auth,KeyType type)205 int KeyManager::RestoreUserKey(uint32_t userId, const std::string &dir, const UserAuth &auth, KeyType type)
206 {
207     LOGI("enter");
208     if (HasElkey(userId, type)) {
209         LOGD("The user %{public}u el %{public}u have existed", userId, type);
210         return 0;
211     }
212 
213     auto elKey = GetBaseKey(dir);
214     if (elKey == nullptr) {
215         return -EOPNOTSUPP;
216     }
217 
218     if (elKey->InitKey() == false) {
219         LOGE("user security key init failed");
220         return -EFAULT;
221     }
222 
223     if (elKey->RestoreKey(auth) == false) {
224         LOGE("user security key restore failed");
225         return -EFAULT;
226     }
227 
228     if (elKey->ActiveKey(RETRIEVE_KEY) == false) {
229         LOGE("user security key active failed");
230         return -EFAULT;
231     }
232 
233     if (type == EL1_KEY) {
234         userEl1Key_[userId] = elKey;
235     } else if (type == EL2_KEY) {
236         userEl2Key_[userId] = elKey;
237     } else if (type == EL3_KEY) {
238         userEl3Key_[userId] = elKey;
239     } else if (type == EL4_KEY) {
240         userEl4Key_[userId] = elKey;
241     }
242     LOGI("key restore success");
243 
244     return 0;
245 }
246 
HasElkey(uint32_t userId,KeyType type)247 bool KeyManager::HasElkey(uint32_t userId, KeyType type)
248 {
249     LOGI("enter");
250     if (type == EL1_KEY) {
251         if (userEl1Key_.find(userId) != userEl1Key_.end()) {
252             LOGD("user el1 key has existed");
253             return true;
254         }
255     } else if (type == EL2_KEY) {
256         if (userEl2Key_.find(userId) != userEl2Key_.end()) {
257             LOGD("user el2 key has existed");
258             return true;
259         }
260     } else if (type == EL3_KEY) {
261         if (userEl3Key_.find(userId) != userEl3Key_.end()) {
262             LOGD("user el3 key has existed");
263             return true;
264         }
265     } else if (type == EL4_KEY) {
266         if (userEl4Key_.find(userId) != userEl4Key_.end()) {
267             LOGD("user el4 key has existed");
268             return true;
269         }
270     } else {
271         LOGE("key type error");
272     }
273 
274     return false;
275 }
276 
IsNeedClearKeyFile(std::string file)277 bool KeyManager::IsNeedClearKeyFile(std::string file)
278 {
279     LOGI("enter:");
280     if (!std::filesystem::exists(file)) {
281         LOGE("file not exist, file is %{private}s", file.c_str());
282         return false;
283     }
284 
285     std::string version;
286     if (!OHOS::LoadStringFromFile(file, version)) {
287         LOGE("LoadStringFromFile return fail, file is %{private}s", file.c_str());
288         return false;
289     }
290 
291     if (version != DEFAULT_NEED_RESTORE_VERSION) {
292         LOGE("need to clear, file is %{private}s, version is %{public}s.", file.c_str(), version.c_str());
293         return true;
294     }
295     LOGE("no need to clear, file is %{private}s, version is %{public}s", file.c_str(), version.c_str());
296     return false;
297 }
298 
ProcUpgradeKey(const std::vector<FileList> & dirInfo)299 void KeyManager::ProcUpgradeKey(const std::vector<FileList> &dirInfo)
300 {
301     LOGI("enter:");
302     for (const auto &it : dirInfo) {
303         std::string needRestorePath = it.path + "/latest/need_restore";
304         if (IsNeedClearKeyFile(needRestorePath)) {
305             bool ret = RmDirRecurse(it.path);
306             if (!ret) {
307                 LOGE("remove key dir fail, result is %{public}d, dir %{private}s", ret, it.path.c_str());
308             }
309         }
310     }
311 }
312 
LoadAllUsersEl1Key(void)313 int KeyManager::LoadAllUsersEl1Key(void)
314 {
315     LOGI("enter");
316     std::vector<FileList> dirInfo;
317     ReadDigitDir(USER_EL2_DIR, dirInfo);
318     UpgradeKeys(dirInfo);
319     dirInfo.clear();
320     ReadDigitDir(USER_EL1_DIR, dirInfo);
321     UpgradeKeys(dirInfo);
322     for (auto item : dirInfo) {
323         if (RestoreUserKey(item.userId, item.path, NULL_KEY_AUTH, EL1_KEY) != 0) {
324             LOGE("user %{public}u el1 key restore error", item.userId);
325         }
326     }
327 
328     /* only for el3/el4 upgrade scene */
329     dirInfo.clear();
330     ReadDigitDir(USER_EL3_DIR, dirInfo);
331     ProcUpgradeKey(dirInfo);
332     dirInfo.clear();
333     ReadDigitDir(USER_EL4_DIR, dirInfo);
334     ProcUpgradeKey(dirInfo);
335     return 0;
336 }
337 
InitUserElkeyStorageDir(void)338 int KeyManager::InitUserElkeyStorageDir(void)
339 {
340     int ret = MkDir(SERVICE_STORAGE_DAEMON_DIR, 0700);
341     if (ret && errno != EEXIST) {
342         LOGE("make service storage daemon dir error");
343         return ret;
344     }
345 
346     ret = MkDir(FSCRYPT_EL_DIR, 0700);
347     if (ret && errno != EEXIST) {
348         LOGE("make service storage daemon dir error");
349         return ret;
350     }
351 
352     ret = MkDir(USER_EL1_DIR, 0700);
353     if (ret && errno != EEXIST) {
354         LOGE("make el1 storage dir error");
355         return ret;
356     }
357     ret = MkDir(USER_EL2_DIR, 0700);
358     if (ret && errno != EEXIST) {
359         LOGE("make el2 storage dir error");
360         return ret;
361     }
362     // 0700 means create el3 permissions
363     ret = MkDir(USER_EL3_DIR, 0700);
364     if (ret && errno != EEXIST) {
365         LOGE("make el3 storage dir error");
366         return ret;
367     }
368     // 0700 means create el4 permissions
369     ret = MkDir(USER_EL4_DIR, 0700);
370     if (ret && errno != EEXIST) {
371         LOGE("make el4 storage dir error");
372         return ret;
373     }
374 
375     return 0;
376 }
377 
InitGlobalUserKeys(void)378 int KeyManager::InitGlobalUserKeys(void)
379 {
380     LOGI("enter");
381     if (!KeyCtrlHasFscryptSyspara()) {
382         return 0;
383     }
384     std::lock_guard<std::mutex> lock(keyMutex_);
385     int ret = InitUserElkeyStorageDir();
386     if (ret) {
387         LOGE("Init user el storage dir failed");
388         return ret;
389     }
390 
391     std::string globalUserEl1Path = USER_EL1_DIR + "/" + std::to_string(GLOBAL_USER_ID);
392     if (IsDir(globalUserEl1Path)) {
393         ret = RestoreUserKey(GLOBAL_USER_ID, globalUserEl1Path, NULL_KEY_AUTH, EL1_KEY);
394         if (ret != 0) {
395             LOGE("Restore el1 failed");
396             return ret;
397         }
398     } else {
399         ret = GenerateAndInstallUserKey(GLOBAL_USER_ID, globalUserEl1Path, NULL_KEY_AUTH, EL1_KEY);
400         if (ret != 0) {
401             LOGE("Generate el1 failed");
402             return ret;
403         }
404     }
405 
406     ret = LoadAllUsersEl1Key();
407     if (ret) {
408         LOGE("Load all users el1 failed");
409         return ret;
410     }
411     LOGI("Init global user key success");
412 
413     return 0;
414 }
415 
GenerateUserKeys(unsigned int user,uint32_t flags)416 int KeyManager::GenerateUserKeys(unsigned int user, uint32_t flags)
417 {
418     LOGI("start, user:%{public}u", user);
419     if (!KeyCtrlHasFscryptSyspara()) {
420         return 0;
421     }
422 
423     std::lock_guard<std::mutex> lock(keyMutex_);
424     if ((!IsDir(USER_EL1_DIR)) || (!IsDir(USER_EL2_DIR)) || (!IsDir(USER_EL3_DIR)) || (!IsDir(USER_EL4_DIR))) {
425         LOGD("El storage dir is not existed");
426         return -ENOENT;
427     }
428 
429     std::string el1Path = USER_EL1_DIR + "/" + std::to_string(user);
430     std::string el2Path = USER_EL2_DIR + "/" + std::to_string(user);
431     std::string el3Path = USER_EL3_DIR + "/" + std::to_string(user);
432     std::string el4Path = USER_EL4_DIR + "/" + std::to_string(user);
433     if (IsDir(el1Path) || IsDir(el2Path) || IsDir(el3Path) || IsDir(el4Path)) {
434         LOGE("user %{public}d el key have existed, create error", user);
435         return -EEXIST;
436     }
437     int ret = GenerateAndInstallUserKey(user, el1Path, NULL_KEY_AUTH, EL1_KEY);
438     if (ret) {
439         LOGE("user el1 create error");
440         return ret;
441     }
442 
443     ret = GenerateAndInstallUserKey(user, el2Path, NULL_KEY_AUTH, EL2_KEY);
444     if (ret) {
445         DoDeleteUserKeys(user);
446         LOGE("user el2 create error");
447         return ret;
448     }
449     ret = GenerateAndInstallUserKey(user, el3Path, NULL_KEY_AUTH, EL3_KEY);
450     if (ret) {
451         DoDeleteUserKeys(user);
452         LOGE("user el3 create error");
453         return ret;
454     }
455     ret = GenerateAndInstallUserKey(user, el4Path, NULL_KEY_AUTH, EL4_KEY);
456     if (ret) {
457         DoDeleteUserKeys(user);
458         LOGE("user el4 create error");
459         return ret;
460     }
461     LOGI("Create user el success");
462 
463     return 0;
464 }
465 
GenerateUserKeyByType(unsigned int user,KeyType type,const std::vector<uint8_t> & token,const std::vector<uint8_t> & secret)466 int KeyManager::GenerateUserKeyByType(unsigned int user, KeyType type,
467                                       const std::vector<uint8_t> &token,
468                                       const std::vector<uint8_t> &secret)
469 {
470     LOGI("start, user:%{public}u, type %{public}u", user, type);
471     if (!KeyCtrlHasFscryptSyspara()) {
472         return 0;
473     }
474 
475     std::lock_guard<std::mutex> lock(keyMutex_);
476     std::string elPath = GetKeyDirByType(type);
477     if (!IsDir(elPath)) {
478         LOGI("El storage dir is not existed");
479         return -ENOENT;
480     }
481 
482     std::string elUserKeyPath = elPath + + "/" + std::to_string(user);
483     if (IsDir(elUserKeyPath)) {
484         LOGE("user %{public}d el key have existed, create error", user);
485         return -EEXIST;
486     }
487     UserAuth auth = {.token = token, .secret = secret, .secureUid = 0};
488     int ret = GenerateAndInstallUserKey(user, elUserKeyPath, auth, type);
489     if (ret) {
490         LOGE("user el create error, user %{public}u, type %{public}u", user, type);
491         return ret;
492     }
493     LOGI("Create user el success, user %{public}u, type %{public}u", user, type);
494 
495     return 0;
496 }
497 
DoDeleteUserCeEceSeceKeys(unsigned int user,const std::string USER_DIR,std::map<unsigned int,std::shared_ptr<BaseKey>> & userElKey_)498 int KeyManager::DoDeleteUserCeEceSeceKeys(unsigned int user,
499                                           const std::string USER_DIR,
500                                           std::map<unsigned int, std::shared_ptr<BaseKey>> &userElKey_)
501 {
502     int ret = 0;
503     std::string elPath;
504     auto it = userElKey_.find(user);
505     if (it != userElKey_.end()) {
506         auto elKey = it->second;
507         elKey->ClearKey();
508         userElKey_.erase(user);
509         saveLockScreenStatus.erase(user);
510     } else {
511         elPath = USER_DIR + "/" + std::to_string(user);
512         std::shared_ptr<BaseKey> elKey = GetBaseKey(elPath);
513         if (elKey == nullptr) {
514             LOGE("Malloc el1 Basekey memory failed");
515             return -ENOMEM;
516         }
517         if (!elKey->ClearKey()) {
518             LOGE("Delete el1 key failed");
519             ret = -EFAULT;
520         }
521     }
522     return ret;
523 }
524 
DoDeleteUserKeys(unsigned int user)525 int KeyManager::DoDeleteUserKeys(unsigned int user)
526 {
527     int ret = 0;
528     std::string elPath;
529     ret = DoDeleteUserCeEceSeceKeys(user, USER_EL1_DIR, userEl1Key_);
530     if (ret != 0) {
531         LOGE("Delete el1 key failed");
532         ret = -EFAULT;
533     }
534     ret = DoDeleteUserCeEceSeceKeys(user, USER_EL2_DIR, userEl2Key_);
535     if (ret != 0) {
536         LOGE("Delete el2 key failed");
537         ret = -EFAULT;
538     }
539     ret = DoDeleteUserCeEceSeceKeys(user, USER_EL3_DIR, userEl3Key_);
540     if (ret != 0) {
541         LOGE("Delete el3 key failed");
542         ret = -EFAULT;
543     }
544     ret = DoDeleteUserCeEceSeceKeys(user, USER_EL4_DIR, userEl4Key_);
545     if (ret != 0) {
546         LOGE("Delete el4 key failed");
547         ret = -EFAULT;
548     }
549     return ret;
550 }
551 
DeleteUserKeys(unsigned int user)552 int KeyManager::DeleteUserKeys(unsigned int user)
553 {
554     LOGI("start, user:%{public}d", user);
555     if (!KeyCtrlHasFscryptSyspara()) {
556         return 0;
557     }
558 
559     std::lock_guard<std::mutex> lock(keyMutex_);
560     int ret = DoDeleteUserKeys(user);
561     LOGI("delete user key end");
562 
563     return ret;
564 }
565 
566 #ifdef USER_CRYPTO_MIGRATE_KEY
UpdateUserAuth(unsigned int user,struct UserTokenSecret & userTokenSecret,bool needGenerateShield)567 int KeyManager::UpdateUserAuth(unsigned int user, struct UserTokenSecret &userTokenSecret,
568                                bool needGenerateShield)
569 #else
570 int KeyManager::UpdateUserAuth(unsigned int user, struct UserTokenSecret &userTokenSecret)
571 #endif
572 {
573 #ifdef USER_CRYPTO_MIGRATE_KEY
574     int ret = UpdateCeEceSeceUserAuth(user, userTokenSecret, EL2_KEY, needGenerateShield);
575     if (ret != 0) {
576         LOGE("user %{public}u UpdateUserAuth el2 key fail", user);
577         return ret;
578     }
579     ret = UpdateCeEceSeceUserAuth(user, userTokenSecret, EL3_KEY, needGenerateShield);
580     if (ret != 0) {
581         LOGE("user %{public}u UpdateUserAuth el3 key fail", user);
582         return ret;
583     }
584     ret = UpdateCeEceSeceUserAuth(user, userTokenSecret, EL4_KEY, needGenerateShield);
585     if (ret != 0) {
586         LOGE("user %{public}u UpdateUserAuth el4 key fail", user);
587         return ret;
588     }
589 #else
590     int ret = UpdateCeEceSeceUserAuth(user, userTokenSecret, EL2_KEY);
591     if (ret != 0) {
592         LOGE("user %{public}u UpdateUserAuth el2 key fail", user);
593         return ret;
594     }
595     ret = UpdateCeEceSeceUserAuth(user, userTokenSecret, EL3_KEY);
596     if (ret != 0) {
597         LOGE("user %{public}u UpdateUserAuth el3 key fail", user);
598         return ret;
599     }
600     ret = UpdateCeEceSeceUserAuth(user, userTokenSecret, EL4_KEY);
601     if (ret != 0) {
602         LOGE("user %{public}u UpdateUserAuth el4 key fail", user);
603         return ret;
604     }
605 #endif
606 
607     return ret;
608 }
609 
610 #ifdef USER_CRYPTO_MIGRATE_KEY
UpdateCeEceSeceUserAuth(unsigned int user,struct UserTokenSecret & userTokenSecret,KeyType type,bool needGenerateShield)611 int KeyManager::UpdateCeEceSeceUserAuth(unsigned int user,
612                                         struct UserTokenSecret &userTokenSecret,
613                                         KeyType type, bool needGenerateShield)
614 #else
615 int KeyManager::UpdateCeEceSeceUserAuth(unsigned int user,
616                                         struct UserTokenSecret &userTokenSecret,
617                                         KeyType type)
618 #endif
619 {
620     LOGI("start, user:%{public}d", user);
621     if (!KeyCtrlHasFscryptSyspara()) {
622         return 0;
623     }
624     std::lock_guard<std::mutex> lock(keyMutex_);
625     std::shared_ptr<BaseKey> item = GetUserElKey(user, type);
626     if (item == nullptr) {
627         LOGE("Have not found user %{public}u el key", user);
628         return -ENOENT;
629     }
630 
631     UserAuth auth = {userTokenSecret.token, userTokenSecret.oldSecret, userTokenSecret.secureUid};
632     if ((item->RestoreKey(auth) == false) && (item->RestoreKey(NULL_KEY_AUTH) == false)) {
633         LOGE("Restore key error");
634         return -EFAULT;
635     }
636 
637     auth.secret = userTokenSecret.newSecret;
638 #ifdef USER_CRYPTO_MIGRATE_KEY
639     if (item->StoreKey(auth, needGenerateShield) == false) {
640 #else
641     if (item->StoreKey(auth) == false) {
642 #endif
643         LOGE("Store key error");
644         return -EFAULT;
645     }
646 
647     userPinProtect[user] = !userTokenSecret.newSecret.empty();
648     return 0;
649 }
650 
651 int KeyManager::ActiveUserKey(unsigned int user, const std::vector<uint8_t> &token,
652                               const std::vector<uint8_t> &secret)
653 {
654     LOGI("start");
655     if (!KeyCtrlHasFscryptSyspara()) {
656         return 0;
657     }
658 
659     if (ActiveCeSceSeceUserKey(user, EL2_KEY, token, secret) != 0) {
660         LOGI("Active user %{public}u el2 fail", user);
661         return -EFAULT;
662     }
663     if (ActiveCeSceSeceUserKey(user, EL3_KEY, token, secret) != 0) {
664         LOGI("Active user %{public}u el3 fail", user);
665         return -EFAULT;
666     }
667     if (ActiveCeSceSeceUserKey(user, EL4_KEY, token, secret) != 0) {
668         LOGI("Active user %{public}u el4 fail", user);
669         return -EFAULT;
670     }
671     return 0;
672 }
673 
674 std::string KeyManager::GetKeyDirByUserAndType(unsigned int user, KeyType type)
675 {
676     std::string keyDir = "";
677     switch (type) {
678         case EL1_KEY:
679             keyDir = USER_EL1_DIR + "/" + std::to_string(user);
680             break;
681         case EL2_KEY:
682             keyDir = USER_EL2_DIR + "/" + std::to_string(user);
683             break;
684         case EL3_KEY:
685             keyDir = USER_EL3_DIR + "/" + std::to_string(user);
686             break;
687         case EL4_KEY:
688             keyDir = USER_EL4_DIR + "/" + std::to_string(user);
689             break;
690         default:
691             LOGE("GetKeyDirByUserAndType type %{public}u is invalid", type);
692             break;
693     }
694     return keyDir;
695 }
696 
697 std::string KeyManager::GetKeyDirByType(KeyType type)
698 {
699     std::string keyDir = "";
700     switch (type) {
701         case EL1_KEY:
702             keyDir = USER_EL1_DIR;
703             break;
704         case EL2_KEY:
705             keyDir = USER_EL2_DIR;
706             break;
707         case EL3_KEY:
708             keyDir = USER_EL3_DIR;
709             break;
710         case EL4_KEY:
711             keyDir = USER_EL4_DIR;
712             break;
713         default:
714             LOGE("GetKeyDirByType type %{public}u is invalid", type);
715             break;
716     }
717     return keyDir;
718 }
719 
720 void KeyManager::SaveUserElKey(unsigned int user, KeyType type, std::shared_ptr<BaseKey> elKey)
721 {
722     switch (type) {
723         case EL1_KEY:
724             userEl1Key_[user] = elKey;
725             break;
726         case EL2_KEY:
727             userEl2Key_[user] = elKey;
728             break;
729         case EL3_KEY:
730             userEl3Key_[user] = elKey;
731             break;
732         case EL4_KEY:
733             userEl4Key_[user] = elKey;
734             break;
735         default:
736             LOGE("SaveUserElKey type %{public}u is invalid", type);
737     }
738 }
739 
740 std::shared_ptr<BaseKey> KeyManager::GetUserElKey(unsigned int user, KeyType type)
741 {
742     if (HasElkey(user, type) != true) {
743         LOGE("Have not found user %{public}u key, type %{public}u", user, type);
744         return nullptr;
745     }
746 
747     switch (type) {
748         case EL1_KEY:
749             return userEl1Key_[user];
750         case EL2_KEY:
751             return userEl2Key_[user];
752         case EL3_KEY:
753             return userEl3Key_[user];
754         case EL4_KEY:
755             return userEl4Key_[user];
756         default:
757             LOGE("GetUserElKey type %{public}u is invalid", type);
758             return nullptr;
759     }
760 }
761 
762 int KeyManager::ActiveCeSceSeceUserKey(unsigned int user, KeyType type,
763                                        const std::vector<uint8_t> &token,
764                                        const std::vector<uint8_t> &secret)
765 {
766     if (!KeyCtrlHasFscryptSyspara()) {
767         return 0;
768     }
769     std::lock_guard<std::mutex> lock(keyMutex_);
770     if (HasElkey(user, type)) {
771         LOGE("The user %{public}u el have been actived, key type is %{public}u", user, type);
772         return 0;
773     }
774     std::string keyDir = GetKeyDirByUserAndType(user, type);
775     if (keyDir == "") {
776         return E_KEY_TYPE_INVAL;
777     }
778     if (!IsDir(keyDir)) {
779         LOGE("Have not found user %{public}u el", user);
780         return -ENOENT;
781     }
782 
783     std::shared_ptr<BaseKey> elKey = GetBaseKey(keyDir);
784     if (elKey == nullptr) {
785         LOGE("elKey failed");
786         return -EOPNOTSUPP;
787     }
788     if (elKey->InitKey() == false) {
789         LOGE("Init el failed");
790         return -EFAULT;
791     }
792     UserAuth auth = {token, secret};
793     if ((elKey->RestoreKey(auth) == false) && (elKey->RestoreKey(NULL_KEY_AUTH) == false)) {
794         LOGE("Restore el failed");
795         return -EFAULT;
796     }
797     std::string NEED_UPDATE_PATH = keyDir + PATH_LATEST + SUFFIX_NEED_UPDATE;
798     if (!FileExists(NEED_UPDATE_PATH) && (elKey->StoreKey(auth) == false)) {
799         LOGE("Store el failed");
800         return -EFAULT;
801     }
802     if (elKey->ActiveKey(RETRIEVE_KEY) == false) {
803         LOGE("Active user %{public}u key failed", user);
804         return -EFAULT;
805     }
806 
807     SaveUserElKey(user, type, elKey);
808     if (secret.empty()) {
809         userPinProtect.insert(std::make_pair(user, false));
810     } else {
811         userPinProtect.insert(std::make_pair(user, true));
812     }
813     LOGI("Active user %{public}u el success", user);
814     saveLockScreenStatus.insert(std::make_pair(user, true));
815     return 0;
816 }
817 
818 int KeyManager::UnlockUserScreen(uint32_t user)
819 {
820     LOGI("start");
821     auto iter = saveLockScreenStatus.find(user);
822     if (iter == saveLockScreenStatus.end()) {
823         saveLockScreenStatus.insert(std::make_pair(user, false));
824     }
825     if (!KeyCtrlHasFscryptSyspara()) {
826         saveLockScreenStatus[user] = true;
827         LOGI("saveLockScreenStatus is %{public}d", saveLockScreenStatus[user]);
828         return 0;
829     }
830     std::lock_guard<std::mutex> lock(keyMutex_);
831     if (userEl4Key_.find(user) == userEl4Key_.end()) {
832         saveLockScreenStatus[user] = true;
833         LOGE("The user %{public}u not been actived and saveLockScreenStatus is %{public}d", user,
834              saveLockScreenStatus[user]);
835         return 0;
836     }
837     auto el4Key = userEl4Key_[user];
838     if (!el4Key->UnlockUserScreen(user, FSCRYPT_SDP_ECE_CLASS)) {
839         LOGE("UnlockUserScreen user %{public}u el4 key failed", user);
840         return -EFAULT;
841     }
842     saveLockScreenStatus[user] = true;
843     LOGI("UnlockUserScreen user %{public}u el3 and el4 success and saveLockScreenStatus is %{public}d", user,
844          saveLockScreenStatus[user]);
845     return 0;
846 }
847 
848 int KeyManager::GetLockScreenStatus(uint32_t user, bool &lockScreenStatus)
849 {
850     LOGI("start");
851     std::lock_guard<std::mutex> lock(keyMutex_);
852     auto iter = saveLockScreenStatus.find(user);
853     lockScreenStatus = (iter == saveLockScreenStatus.end()) ? false: iter->second;
854     LOGI("lockScreenStatus is %{public}d", lockScreenStatus);
855     return 0;
856 }
857 
858 int KeyManager::InActiveUserKey(unsigned int user)
859 {
860     LOGI("start");
861     if (!KeyCtrlHasFscryptSyspara()) {
862         return 0;
863     }
864     std::lock_guard<std::mutex> lock(keyMutex_);
865     if (userEl2Key_.find(user) == userEl2Key_.end()) {
866         LOGE("Have not found user %{public}u el2", user);
867         return -ENOENT;
868     }
869     auto elKey = userEl2Key_[user];
870     if (elKey->InactiveKey(USER_LOGOUT) == false) {
871         LOGE("Clear user %{public}u key failed", user);
872         return -EFAULT;
873     }
874     userEl2Key_.erase(user);
875     LOGI("Inactive user %{public}u el2 success", user);
876 
877     if (userEl3Key_.find(user) == userEl3Key_.end()) {
878         LOGE("Have not found user %{public}u el3", user);
879         return -ENOENT;
880     }
881     elKey = userEl3Key_[user];
882     if (elKey->InactiveKey(USER_LOGOUT) == false) {
883         LOGE("Clear user %{public}u key failed", user);
884         return -EFAULT;
885     }
886     userEl3Key_.erase(user);
887     LOGI("Inactive user %{public}u el3 success", user);
888 
889     if (userEl4Key_.find(user) == userEl4Key_.end()) {
890         LOGE("Have not found user %{public}u el4", user);
891         return -ENOENT;
892     }
893     elKey = userEl4Key_[user];
894     if (elKey->InactiveKey(USER_LOGOUT) == false) {
895         LOGE("Clear user %{public}u key failed", user);
896         return -EFAULT;
897     }
898     userEl4Key_.erase(user);
899     LOGI("Inactive user %{public}u el3 success", user);
900 
901     return 0;
902 }
903 
904 int KeyManager::LockUserScreen(uint32_t user)
905 {
906     LOGI("start");
907     std::lock_guard<std::mutex> lock(keyMutex_);
908     auto iter = userPinProtect.find(user);
909     if (iter == userPinProtect.end() || iter->second == false) {
910         LOGI("saveLockScreenStatus is %{public}d", saveLockScreenStatus[user]);
911         return 0;
912     }
913     iter = saveLockScreenStatus.find(user);
914     if (iter == saveLockScreenStatus.end()) {
915         saveLockScreenStatus.insert(std::make_pair(user, false));
916     }
917     if (!KeyCtrlHasFscryptSyspara()) {
918         saveLockScreenStatus[user] = false;
919         LOGI("saveLockScreenStatus is %{public}d", saveLockScreenStatus[user]);
920         return 0;
921     }
922     if (userEl4Key_.find(user) == userEl4Key_.end()) {
923         LOGE("Have not found user %{public}u el3 or el4", user);
924         return -ENOENT;
925     }
926     auto elKey = userEl4Key_[user];
927     if (!elKey->LockUserScreen(user, FSCRYPT_SDP_ECE_CLASS)) {
928         LOGE("Clear user %{public}u key failed", user);
929         return -EFAULT;
930     }
931     LOGI("LockUserScreen user %{public}u el3 and el4 success", user);
932     saveLockScreenStatus[user] = false;
933     LOGI("saveLockScreenStatus is %{public}d", saveLockScreenStatus[user]);
934     return 0;
935 }
936 
937 int KeyManager::SetDirectoryElPolicy(unsigned int user, KeyType type, const std::vector<FileList> &vec)
938 {
939     LOGI("start");
940     if (!KeyCtrlHasFscryptSyspara()) {
941         return 0;
942     }
943     std::string keyPath;
944     std::string eceSeceKeyPath;
945     std::lock_guard<std::mutex> lock(keyMutex_);
946     if (type == EL1_KEY) {
947         if (userEl1Key_.find(user) == userEl1Key_.end()) {
948             LOGE("Have not found user %{public}u el1 key, not enable el1", user);
949             return -ENOENT;
950         }
951         keyPath = userEl1Key_[user]->GetDir();
952     } else if (type == EL2_KEY || type == EL3_KEY || type == EL4_KEY) {
953         if (userEl2Key_.find(user) == userEl2Key_.end()) {
954             LOGE("Have not found user %{public}u el2 key, not enable el2", user);
955             return -ENOENT;
956         }
957         keyPath = userEl2Key_[user]->GetDir();
958     } else {
959         LOGE("Not specify el flags, no need to crypt");
960         return 0;
961     }
962     if (getEceSeceKeyPath(user, type, eceSeceKeyPath) != 0) {
963         LOGE("method getEceSeceKeyPath fail");
964         return -ENOENT;
965     }
966     for (auto item : vec) {
967         int ret = LoadAndSetPolicy(keyPath.c_str(), item.path.c_str());
968         if (ret != 0) {
969             LOGE("Set directory el policy error, ret: %{public}d", ret);
970             return -EFAULT;
971         }
972     }
973     if (type == EL3_KEY || type == EL4_KEY) {
974         for (auto item : vec) {
975             if (LoadAndSetEceAndSecePolicy(eceSeceKeyPath.c_str(), item.path.c_str(), static_cast<int>(type)) != 0) {
976                 LOGE("Set directory el policy error!");
977                 return -EFAULT;
978             }
979         }
980     }
981     LOGI("Set user %{public}u el policy success", user);
982     return 0;
983 }
984 
985 int KeyManager::getEceSeceKeyPath(unsigned int user, KeyType type, std::string &eceSeceKeyPath)
986 {
987     if (type == EL3_KEY) {
988         if (userEl3Key_.find(user) == userEl3Key_.end()) {
989             LOGD("Have not found user %{public}u el3 key, not enable el3", user);
990             return -ENOENT;
991         }
992         eceSeceKeyPath = userEl3Key_[user]->GetDir();
993     }
994     if (type == EL4_KEY) {
995         if (userEl4Key_.find(user) == userEl4Key_.end()) {
996             LOGD("Have not found user %{public}u el4 key, not enable el4", user);
997             return -ENOENT;
998         }
999         eceSeceKeyPath = userEl4Key_[user]->GetDir();
1000     }
1001     return 0;
1002 }
1003 
1004 int KeyManager::UpdateCeEceSeceKeyContext(uint32_t userId, KeyType type)
1005 {
1006     LOGI("start");
1007     if (!KeyCtrlHasFscryptSyspara()) {
1008         return 0;
1009     }
1010     std::lock_guard<std::mutex> lock(keyMutex_);
1011     if (HasElkey(userId, type) == false) {
1012         LOGE("Have not found user %{public}u el%{public}u", userId, type);
1013         return -ENOENT;
1014     }
1015     std::shared_ptr<BaseKey> elKey = GetUserElKey(userId, type);
1016     if (elKey == nullptr) {
1017         LOGE("Have not found user %{public}u, type el%{public}u", userId, type);
1018         return -ENOENT;
1019     }
1020     if (!elKey->UpdateKey()) {
1021         LOGE("Basekey update newest context failed");
1022         return -EFAULT;
1023     }
1024     return 0;
1025 }
1026 
1027 int KeyManager::UpdateKeyContext(uint32_t userId)
1028 {
1029     LOGI("UpdateKeyContext enter");
1030     int ret = UpdateCeEceSeceKeyContext(userId, EL2_KEY);
1031     if (ret != 0) {
1032         LOGE("Basekey update EL2 newest context failed");
1033         return ret;
1034     }
1035     ret = UpdateCeEceSeceKeyContext(userId, EL3_KEY);
1036     if (ret != 0) {
1037         LOGE("Basekey update EL3 newest context failed");
1038         return ret;
1039     }
1040     ret = UpdateCeEceSeceKeyContext(userId, EL4_KEY);
1041     if (ret != 0) {
1042         LOGE("Basekey update EL4 newest context failed");
1043         return ret;
1044     }
1045     LOGI("Basekey update key context success");
1046     return 0;
1047 }
1048 
1049 int KeyManager::UpgradeKeys(const std::vector<FileList> &dirInfo)
1050 {
1051     for (const auto &it : dirInfo) {
1052         std::shared_ptr<BaseKey> elKey = GetBaseKey(it.path);
1053         if (elKey == nullptr) {
1054             LOGE("elKel feiled");
1055             continue;
1056         }
1057         elKey->UpgradeKeys();
1058     }
1059     return 0;
1060 }
1061 
1062 #ifdef USER_CRYPTO_MIGRATE_KEY
1063 int KeyManager::RestoreUserKey(uint32_t userId, KeyType type)
1064 {
1065     LOGI("start, user is %{public}u , type is %{public}d", userId, type);
1066     std::string dir = GetKeyDirByUserAndType(userId, type);
1067     if (dir == "") {
1068         LOGE("type is invalid, %{public}u", type);
1069         return -EFAULT;
1070     }
1071 
1072     if (!IsDir(dir)) {
1073         LOGE("dir not exist");
1074         return -ENOENT;
1075     }
1076     return RestoreUserKey(userId, dir, NULL_KEY_AUTH, type);
1077 }
1078 #endif
1079 } // namespace StorageDaemon
1080 } // namespace OHOS
1081