• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022-2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "key_manager.h"
17 
18 #include <fcntl.h>
19 #include <future>
20 #include "directory_ex.h"
21 #include "file_ex.h"
22 #include "fscrypt_key_v1.h"
23 #include "fscrypt_key_v2.h"
24 #include "iam_client.h"
25 #include "libfscrypt/fscrypt_control.h"
26 #include "recover_manager.h"
27 #include "storage_service_errno.h"
28 #include "storage_service_log.h"
29 #include "user/user_manager.h"
30 #include "utils/storage_radar.h"
31 #ifdef EL5_FILEKEY_MANAGER
32 #include "el5_filekey_manager_kit.h"
33 #endif
34 #ifdef EL5_FILEKEY_MANAGER
35 using namespace OHOS::Security::AccessToken;
36 #endif
37 
38 using namespace OHOS::StorageService;
39 namespace OHOS {
40 namespace StorageDaemon {
41 const UserAuth NULL_KEY_AUTH = {};
42 constexpr const char *DEFAULT_NEED_RESTORE_VERSION = "1";
43 constexpr const char *DEFAULT_NEED_RESTORE_UPDATE_VERSION = "3";
44 constexpr const char *UECE_PATH = "/dev/fbex_uece";
45 constexpr const char *DATA_DIR = "data/app/";
46 constexpr const char *SERVICE_DIR = "data/service/";
47 constexpr const char *ENCRYPT_VERSION_DIR = "/latest/encrypted";
48 constexpr const char *SEC_DISCARD_DIR = "/latest/sec_discard";
49 constexpr const char *SHIELD_DIR = "/latest/shield";
50 constexpr const char *DESC_DIR = "/key_desc";
51 constexpr const char *EL2_ENCRYPT_TMP_FILE = "/el2_tmp";
52 constexpr uint32_t KEY_RECOVERY_USER_ID = 300;
53 
54 constexpr const char *SERVICE_STORAGE_DAEMON_DIR = "/data/service/el1/public/storage_daemon";
55 constexpr const char *FSCRYPT_EL_DIR = "/data/service/el1/public/storage_daemon/sd";
56 constexpr uint32_t RECOVERY_TOKEN_CHALLENGE_LENG = 32;
57 
58 constexpr int LOCK_STATUS_START = 0;
59 constexpr int LOCK_STATUS_END = 1;
60 constexpr uint8_t RETRIEVE_KEY = 0x0;
61 constexpr uint8_t FIRST_CREATE_KEY = 0x6c;
62 constexpr uint8_t USER_LOGOUT = 0x0;
63 constexpr uint32_t USER_ADD_AUTH = 0x0;
64 constexpr uint32_t USER_CHANGE_AUTH = 0x1;
65 
66 constexpr uint32_t FILE_ENCRY_ERROR_UECE_AUTH_STATUS_WRONG = 0xFBE30034;
67 
68 #ifdef EL5_FILEKEY_MANAGER
69 constexpr int32_t WAIT_THREAD_TIMEOUT_MS = 500;
70 #endif
71 
IsEncryption()72 static bool IsEncryption()
73 {
74 #ifdef SUPPORT_RECOVERY_KEY_SERVICE
75     static bool isEncryption = RecoveryManager::GetInstance().IsEncryptionEnabled();
76     return isEncryption;
77 #endif
78     return true;
79 }
GetBaseKey(const std::string & dir)80 std::shared_ptr<BaseKey> KeyManager::GetBaseKey(const std::string& dir)
81 {
82     uint8_t versionFromPolicy = GetFscryptVersionFromPolicy();
83     uint8_t kernelSupportVersion = KeyCtrlGetFscryptVersion(MNT_DATA);
84     if (kernelSupportVersion != FSCRYPT_V1 && kernelSupportVersion != FSCRYPT_V2) {
85         LOGE("kernel not support fscrypt, ret is %{public}d, errno is %{public}d.", kernelSupportVersion, errno);
86         return nullptr;
87     }
88     if ((versionFromPolicy == kernelSupportVersion) && (kernelSupportVersion == FSCRYPT_V2)) {
89         return std::dynamic_pointer_cast<BaseKey>(std::make_shared<FscryptKeyV2>(dir));
90     }
91     if (versionFromPolicy != kernelSupportVersion) {
92         LOGE("version from policy %{public}u not same as version from kernel %{public}u", versionFromPolicy,
93              kernelSupportVersion);
94     }
95     return std::dynamic_pointer_cast<BaseKey>(std::make_shared<FscryptKeyV1>(dir));
96 }
97 
GenerateAndInstallDeviceKey(const std::string & dir)98 int KeyManager::GenerateAndInstallDeviceKey(const std::string &dir)
99 {
100     LOGW("enter");
101     if (!KeyCtrlHasFscryptSyspara() || !IsEncryption()) {
102         LOGW("FscryptSyspara has not or encryption not enabled");
103         return E_OK;
104     }
105     globalEl1Key_ = GetBaseKey(dir);
106     if (globalEl1Key_ == nullptr) {
107         StorageRadar::ReportUserKeyResult("GenerateAndInstallDeviceKey", 0, E_GLOBAL_KEY_NULLPTR, "EL1", "");
108         return E_GLOBAL_KEY_NULLPTR;
109     }
110 
111     if (globalEl1Key_->InitKey(true) == false) {
112         globalEl1Key_ = nullptr;
113         LOGE("global security key init failed");
114         StorageRadar::ReportUserKeyResult("GenerateAndInstallDeviceKey", 0, E_GLOBAL_KEY_INIT_ERROR, "EL1", "");
115         return E_GLOBAL_KEY_INIT_ERROR;
116     }
117     auto ret = globalEl1Key_->StoreKey(NULL_KEY_AUTH);
118     if (ret != E_OK) {
119         globalEl1Key_->ClearKey();
120         globalEl1Key_ = nullptr;
121         LOGE("global security key store failed");
122         StorageRadar::ReportUserKeyResult("GenerateAndInstallDeviceKey", 0, E_GLOBAL_KEY_STORE_ERROR, "EL1", "");
123         return E_GLOBAL_KEY_STORE_ERROR;
124     }
125 
126     if (globalEl1Key_->ActiveKey({}, FIRST_CREATE_KEY) != E_OK) {
127         globalEl1Key_->ClearKey();
128         globalEl1Key_ = nullptr;
129         LOGE("global security key active failed");
130         StorageRadar::ReportUserKeyResult("GenerateAndInstallDeviceKey", 0, E_GLOBAL_KEY_ACTIVE_ERROR, "EL1", "");
131         return E_GLOBAL_KEY_ACTIVE_ERROR;
132     }
133 
134     if (globalEl1Key_->UpdateKey() != E_OK) {
135         StorageRadar::ReportUserKeyResult("GenerateAndInstallDeviceKey", 0, E_GLOBAL_KEY_UPDATE_ERROR, "EL1", "");
136     }
137     hasGlobalDeviceKey_ = true;
138     LOGW("key create success");
139     return 0;
140 }
141 
RestoreDeviceKey(const std::string & dir)142 int KeyManager::RestoreDeviceKey(const std::string &dir)
143 {
144     LOGI("enter");
145     if (globalEl1Key_ != nullptr) {
146         LOGI("device key has existed");
147         return 0;
148     }
149 
150     globalEl1Key_ = GetBaseKey(dir);
151     if (globalEl1Key_ == nullptr) {
152         StorageRadar::ReportUserKeyResult("RestoreDeviceKey", 0, E_GLOBAL_KEY_NULLPTR, "EL1", "");
153         return E_GLOBAL_KEY_NULLPTR;
154     }
155 
156     if (globalEl1Key_->InitKey(false) == false) {
157         globalEl1Key_ = nullptr;
158         LOGE("global security key init failed");
159         StorageRadar::ReportUserKeyResult("RestoreDeviceKey", 0, E_GLOBAL_KEY_INIT_ERROR, "EL1", "");
160         return E_GLOBAL_KEY_INIT_ERROR;
161     }
162 
163     auto ret = globalEl1Key_->RestoreKey(NULL_KEY_AUTH);
164     if (ret != E_OK) {
165         globalEl1Key_ = nullptr;
166         LOGE("global security key restore failed");
167         StorageRadar::ReportUserKeyResult("RestoreDeviceKey", 0, E_GLOBAL_KEY_STORE_ERROR, "EL1", "");
168         return E_GLOBAL_KEY_STORE_ERROR;
169     }
170 
171     if (globalEl1Key_->ActiveKey({}, RETRIEVE_KEY) != E_OK) {
172         globalEl1Key_ = nullptr;
173         LOGE("global security key active failed");
174         StorageRadar::ReportUserKeyResult("RestoreDeviceKey", 0, E_GLOBAL_KEY_ACTIVE_ERROR, "EL1", "");
175         return E_GLOBAL_KEY_ACTIVE_ERROR;
176     }
177     hasGlobalDeviceKey_ = true;
178     LOGI("key restore success");
179 
180     return 0;
181 }
182 
InitGlobalDeviceKey(void)183 int KeyManager::InitGlobalDeviceKey(void)
184 {
185     LOGW("enter");
186     int ret = InitFscryptPolicy();
187     if (ret < 0) {
188         LOGE("fscrypt init failed, fscrypt will not be enabled");
189         StorageRadar::ReportUserKeyResult("InitGlobalDeviceKey::InitFscryptPolicy", 0, ret, "EL1", "");
190         return ret;
191     }
192 
193     std::lock_guard<std::mutex> lock(keyMutex_);
194     if (hasGlobalDeviceKey_ || globalEl1Key_ != nullptr) {
195         LOGI("glabal device el1 have existed");
196         return 0;
197     }
198 
199     ret = MkDir(STORAGE_DAEMON_DIR, S_IRWXU); // para.0700: root only
200     if (ret && errno != EEXIST) {
201         LOGE("create storage daemon dir error");
202         StorageRadar::ReportUserKeyResult("InitGlobalDeviceKey::MkDir", 0, ret, "EL1",
203             std::string("errno = ") + std::to_string(errno) + ", path = " + STORAGE_DAEMON_DIR);
204         return ret;
205     }
206     std::error_code errCode;
207     if (std::filesystem::exists(DEVICE_EL1_DIR, errCode) && !std::filesystem::is_empty(DEVICE_EL1_DIR)) {
208         UpgradeKeys({{0, DEVICE_EL1_DIR}});
209         return RestoreDeviceKey(DEVICE_EL1_DIR);
210     }
211     ret = MkDir(DEVICE_EL1_DIR, S_IRWXU);
212     if (ret && errno != EEXIST) {
213         LOGE("create device el1 key dir = (/data/service/el0/storage_daemon/sd) error");
214         StorageRadar::ReportUserKeyResult("InitGlobalDeviceKey::MkDir", 0, ret, "EL1",
215             std::string("errno = ") + std::to_string(errno) + ", path = " + DEVICE_EL1_DIR);
216         return ret;
217     }
218 
219     return GenerateAndInstallDeviceKey(DEVICE_EL1_DIR);
220 }
221 
GenerateAndInstallUserKey(uint32_t userId,const std::string & dir,const UserAuth & auth,KeyType type)222 int KeyManager::GenerateAndInstallUserKey(uint32_t userId, const std::string &dir, const UserAuth &auth, KeyType type)
223 {
224     LOGW("enter");
225     if (HasElkey(userId, type)) {
226         return 0;
227     }
228     auto elKey = GetBaseKey(dir);
229     if (elKey == nullptr) {
230         return E_GLOBAL_KEY_NULLPTR;
231     }
232     if (type == EL5_KEY) {
233         return GenerateAndInstallEl5Key(userId, dir, auth);
234     }
235     if (elKey->InitKey(true) == false) {
236         LOGE("user security key init failed");
237         return E_ELX_KEY_INIT_ERROR;
238     }
239     auto ret = elKey->StoreKey(auth);
240     if (ret != E_OK) {
241         elKey->ClearKey();
242         LOGE("user security key store failed");
243         return E_ELX_KEY_STORE_ERROR;
244     }
245     // Generate hashkey for encrypt public directory
246     elKey->GenerateHashKey();
247     if (elKey->ActiveKey(auth.token, FIRST_CREATE_KEY) != E_OK) {
248         elKey->ClearKey();
249         LOGE("user security key active failed");
250         return E_ELX_KEY_ACTIVE_ERROR;
251     }
252     (void)elKey->UpdateKey();
253     if (type >= EL1_KEY && type < EL5_KEY) {
254         SaveUserElKey(userId, type, elKey);
255     }
256     LOGI("key create success");
257     return 0;
258 }
259 
GenerateAndInstallEl5Key(uint32_t userId,const std::string & dir,const UserAuth & auth)260 int KeyManager::GenerateAndInstallEl5Key(uint32_t userId, const std::string &dir, const UserAuth &auth)
261 {
262     LOGI("enter");
263     auto elKey = GetBaseKey(dir);
264     if (elKey == nullptr) {
265         return E_GLOBAL_KEY_NULLPTR;
266     }
267     bool isNeedEncryptClassE = true;
268     saveESecretStatus[userId] = true;
269     auto ret = elKey->AddClassE(isNeedEncryptClassE, saveESecretStatus[userId], FIRST_CREATE_KEY);
270     if (ret != E_OK) {
271         elKey->ClearKey();
272         LOGE("user %{public}u el5 create error, error=%{public}d", userId, ret);
273         return E_EL5_ADD_CLASS_ERROR;
274     }
275     std::string keyDir = GetKeyDirByUserAndType(userId, EL5_KEY);
276     if (keyDir == "") {
277         return E_KEY_TYPE_INVALID;
278     }
279     if (!saveESecretStatus[userId]) {
280         OHOS::ForceRemoveDirectory(keyDir);
281     }
282     saveESecretStatus[userId] = (!auth.secret.IsEmpty() && !auth.token.IsEmpty());
283     if (isNeedEncryptClassE) {
284         if (!auth.secret.IsEmpty() && !auth.token.IsEmpty()) {
285             auto ret = elKey->EncryptClassE(auth, saveESecretStatus[userId], userId, USER_ADD_AUTH);
286             if (ret != E_OK) {
287                 elKey->ClearKey();
288                 LOGE("user %{public}u el5 create error", userId);
289                 return E_EL5_ENCRYPT_CLASS_ERROR;
290             }
291         }
292     } else {
293         bool eBufferStatue = false;
294         if (elKey->DecryptClassE(auth, saveESecretStatus[userId], eBufferStatue, userId, false) != E_OK) {
295             LOGE("user %{public}u decrypt error", userId);
296         }
297     }
298     SaveUserElKey(userId, EL5_KEY, elKey);
299     return 0;
300 }
301 
RestoreUserKey(uint32_t userId,const std::string & dir,const UserAuth & auth,KeyType type)302 int KeyManager::RestoreUserKey(uint32_t userId, const std::string &dir, const UserAuth &auth, KeyType type)
303 {
304     LOGI("enter");
305     if (HasElkey(userId, type)) {
306         return E_OK;
307     }
308 
309     auto elKey = GetBaseKey(dir);
310     if (elKey == nullptr) {
311         return E_GLOBAL_KEY_NULLPTR;
312     }
313 
314     if (elKey->InitKey(false) == false) {
315         LOGE("user security key init failed");
316         return E_ELX_KEY_INIT_ERROR;
317     }
318 
319     auto ret = elKey->RestoreKey(auth);
320     if (ret != E_OK) {
321         LOGE("user security key restore failed");
322         return E_ELX_KEY_STORE_ERROR;
323     }
324 
325     if (elKey->ActiveKey(auth.token, RETRIEVE_KEY) != E_OK) {
326         LOGE("user security key active failed");
327         return E_ELX_KEY_ACTIVE_ERROR;
328     }
329 
330     SaveUserElKey(userId, type, elKey);
331     LOGI("key restore success");
332 
333     return E_OK;
334 }
335 
336 #ifdef USER_CRYPTO_MIGRATE_KEY
ClearAppCloneUserNeedRestore(unsigned int userId,std::string elNeedRestorePath)337 int32_t KeyManager::ClearAppCloneUserNeedRestore(unsigned int userId, std::string elNeedRestorePath)
338 {
339     LOGI("enter");
340     if (userId < StorageService::START_APP_CLONE_USER_ID || userId >= StorageService::MAX_APP_CLONE_USER_ID) {
341         LOGI("Clear userId %{public}d out of range", userId);
342         return E_USERID_RANGE;
343     }
344 
345     LOGE("User %{public}d is app clone user, do delete elx need_restore.", userId);
346     std::error_code errCode;
347     if (!std::filesystem::exists(elNeedRestorePath, errCode)) {
348         LOGI("need_restore don't exist, not need to delete.");
349     }
350     (void)remove(elNeedRestorePath.c_str());
351     LOGI("Complete delete need_restore.");
352     return E_OK;
353 }
354 #endif
355 
HasElkey(uint32_t userId,KeyType type)356 bool KeyManager::HasElkey(uint32_t userId, KeyType type)
357 {
358     if (userElKeys_.find(userId) != userElKeys_.end()) {
359         if (userElKeys_[userId].find(type) != userElKeys_[userId].end()) {
360             LOGI("The user %{public}u el %{public}u have existed", userId, type);
361             return true;
362         }
363     }
364     LOGE("Have not found user %{public}u key, type %{public}u", userId, type);
365     return false;
366 }
367 
IsNeedClearKeyFile(std::string file)368 bool KeyManager::IsNeedClearKeyFile(std::string file)
369 {
370     LOGI("enter:");
371     std::error_code errCode;
372     if (!std::filesystem::exists(file, errCode)) {
373         LOGE("file not exist, file is %{private}s", file.c_str());
374         return false;
375     }
376 
377     std::string version;
378     if (!OHOS::LoadStringFromFile(file, version)) {
379         LOGE("LoadStringFromFile return fail, file is %{private}s", file.c_str());
380         return false;
381     }
382 
383     if (version != DEFAULT_NEED_RESTORE_VERSION && version != DEFAULT_NEED_RESTORE_UPDATE_VERSION) {
384         LOGE("need to clear, file is %{private}s, version is %{public}s.", file.c_str(), version.c_str());
385         return true;
386     }
387     LOGE("no need to clear, file is %{private}s, version is %{public}s", file.c_str(), version.c_str());
388     return false;
389 }
390 
ProcUpgradeKey(const std::vector<FileList> & dirInfo)391 void KeyManager::ProcUpgradeKey(const std::vector<FileList> &dirInfo)
392 {
393     LOGI("enter:");
394     for (const auto &it : dirInfo) {
395         std::string needRestorePath = it.path + "/latest/need_restore";
396         if (IsNeedClearKeyFile(needRestorePath)) {
397             bool ret = RmDirRecurse(it.path);
398             if (!ret) {
399                 LOGE("remove key dir fail, result is %{public}d, dir %{private}s", ret, it.path.c_str());
400             }
401         }
402     }
403 }
404 
LoadAllUsersEl1Key(void)405 int KeyManager::LoadAllUsersEl1Key(void)
406 {
407     LOGI("enter");
408     int ret = E_OK;
409     std::vector<FileList> dirInfo;
410     ReadDigitDir(USER_EL2_DIR, dirInfo);
411     UpgradeKeys(dirInfo);
412     dirInfo.clear();
413     ReadDigitDir(USER_EL1_DIR, dirInfo);
414     UpgradeKeys(dirInfo);
415     for (auto &item : dirInfo) {
416         ret = RestoreUserKey(item.userId, item.path, NULL_KEY_AUTH, EL1_KEY);
417         if (ret != E_OK) {
418             LOGE("user %{public}u el1 key restore error", item.userId);
419             StorageRadar::ReportUserKeyResult("LoadAllUsersEl1Key::RestoreUserKey", item.userId,
420                 ret, "EL1", "user el1 path = " + item.path);
421         }
422     }
423 
424     /* only for el3/el4 upgrade scene */
425     dirInfo.clear();
426     ReadDigitDir(USER_EL3_DIR, dirInfo);
427     ProcUpgradeKey(dirInfo);
428     dirInfo.clear();
429     ReadDigitDir(USER_EL4_DIR, dirInfo);
430     ProcUpgradeKey(dirInfo);
431     dirInfo.clear();
432     ReadDigitDir(USER_EL5_DIR, dirInfo);
433     ProcUpgradeKey(dirInfo);
434     return ret;
435 }
436 
InitUserElkeyStorageDir(void)437 int KeyManager::InitUserElkeyStorageDir(void)
438 {
439     int ret = MkDir(SERVICE_STORAGE_DAEMON_DIR, S_IRWXU);
440     if (ret && errno != EEXIST) {
441         LOGE("make service storage daemon dir error");
442         return ret;
443     }
444 
445     ret = MkDir(FSCRYPT_EL_DIR, S_IRWXU);
446     if (ret && errno != EEXIST) {
447         LOGE("make service storage daemon dir error");
448         return ret;
449     }
450 
451     ret = MkDir(USER_EL1_DIR, S_IRWXU);
452     if (ret && errno != EEXIST) {
453         LOGE("make el1 storage dir error");
454         return ret;
455     }
456     ret = MkDir(USER_EL2_DIR, S_IRWXU);
457     if (ret && errno != EEXIST) {
458         LOGE("make el2 storage dir error");
459         return ret;
460     }
461     // 0700 means create el3 permissions
462     ret = MkDir(USER_EL3_DIR, S_IRWXU);
463     if (ret && errno != EEXIST) {
464         LOGE("make el3 storage dir error");
465         return ret;
466     }
467     // 0700 means create el4 permissions
468     ret = MkDir(USER_EL4_DIR, S_IRWXU);
469     if (ret && errno != EEXIST) {
470         LOGE("make el4 storage dir error");
471         return ret;
472     }
473     // 0700 means create el5 permissions
474     ret = MkDir(USER_EL5_DIR, S_IRWXU);
475     if (ret && errno != EEXIST) {
476         LOGE("make el5 storage dir error");
477         return ret;
478     }
479     return 0;
480 }
481 
InitGlobalUserKeys(void)482 int KeyManager::InitGlobalUserKeys(void)
483 {
484     LOGW("enter");
485     if (!KeyCtrlHasFscryptSyspara() || !IsEncryption()) {
486         LOGW("FscryptSyspara has not or encryption not enabled");
487         return 0;
488     }
489     std::lock_guard<std::mutex> lock(keyMutex_);
490     int ret = InitUserElkeyStorageDir();
491     if (ret) {
492         LOGE("Init user el storage dir failed");
493         StorageRadar::ReportUserKeyResult("InitGlobalUserKeys::InitUserElkeyStorageDir", GLOBAL_USER_ID,
494             ret, "EL1", "");
495         return ret;
496     }
497 
498     std::string globalUserEl1Path = std::string(USER_EL1_DIR) + "/" + std::to_string(GLOBAL_USER_ID);
499     if (IsDir(globalUserEl1Path)) {
500         ret = RestoreUserKey(GLOBAL_USER_ID, globalUserEl1Path, NULL_KEY_AUTH, EL1_KEY);
501         if (ret != 0) {
502             LOGE("Restore el1 failed");
503             StorageRadar::ReportUserKeyResult("InitGlobalUserKeys::RestoreUserKey", GLOBAL_USER_ID,
504                 ret, "EL1", "global user el1 path = " + globalUserEl1Path);
505             return ret;
506         }
507     } else {
508         ret = GenerateAndInstallUserKey(GLOBAL_USER_ID, globalUserEl1Path, NULL_KEY_AUTH, EL1_KEY);
509         if (ret != 0) {
510             LOGE("Generate el1 failed");
511             StorageRadar::ReportUserKeyResult("InitGlobalUserKeys::GenerateAndInstallUserKey", GLOBAL_USER_ID,
512                 ret, "EL1", "global user el1 path = " + globalUserEl1Path);
513             return ret;
514         }
515     }
516 
517     ret = LoadAllUsersEl1Key();
518     if (ret) {
519         LOGE("Load all users el1 failed");
520         return ret;
521     }
522     LOGW("Init global user key success");
523 
524     return 0;
525 }
526 
GenerateUserKeys(unsigned int user,uint32_t flags)527 int KeyManager::GenerateUserKeys(unsigned int user, uint32_t flags)
528 {
529     LOGW("start, user:%{public}u", user);
530     if (!KeyCtrlHasFscryptSyspara() || !IsEncryption()) {
531         LOGW("FscryptSyspara has not or encryption not enabled");
532         return 0;
533     }
534     if ((!IsDir(USER_EL1_DIR)) || (!IsDir(USER_EL2_DIR)) || (!IsDir(USER_EL3_DIR)) ||
535         (!IsDir(USER_EL4_DIR)) || (!IsDir(USER_EL5_DIR))) {
536         LOGI("El storage dir is not existed");
537         return -ENOENT;
538     }
539     int ret = GenerateElxAndInstallUserKey(user);
540     if (ret != E_OK) {
541         LOGE("Generate ELX failed!");
542         return ret;
543     }
544     LOGW("Create user el success");
545     return ret;
546 }
547 
GenerateElxAndInstallUserKey(unsigned int user)548 int KeyManager::GenerateElxAndInstallUserKey(unsigned int user)
549 {
550     std::string el1Path = std::string(USER_EL1_DIR) + "/" + std::to_string(user);
551     std::string el2Path = std::string(USER_EL2_DIR) + "/" + std::to_string(user);
552     std::string el3Path = std::string(USER_EL3_DIR) + "/" + std::to_string(user);
553     std::string el4Path = std::string(USER_EL4_DIR) + "/" + std::to_string(user);
554     std::string el5Path = std::string(USER_EL5_DIR) + "/" + std::to_string(user);
555     if (IsDir(el1Path) || IsDir(el2Path) || IsDir(el3Path) || IsDir(el4Path) || IsDir(el5Path)) {
556         return CheckAndFixUserKeyDirectory(user);
557     }
558     std::lock_guard<std::mutex> lock(keyMutex_);
559     int ret = GenerateAndInstallUserKey(user, el1Path, NULL_KEY_AUTH, EL1_KEY);
560     if (ret) {
561         LOGE("user el1 create error");
562         StorageRadar::ReportUserKeyResult("GenerateElxAndInstallUserKey", user, ret, "EL1", "el1Path = " + el1Path);
563         return ret;
564     }
565 
566     ret = GenerateAndInstallUserKey(user, el2Path, NULL_KEY_AUTH, EL2_KEY);
567     if (ret) {
568         DoDeleteUserKeys(user);
569         LOGE("user el2 create error");
570         StorageRadar::ReportUserKeyResult("GenerateElxAndInstallUserKey", user, ret, "EL2", "el2Path = " + el2Path);
571         return ret;
572     }
573     ret = GenerateAndInstallUserKey(user, el3Path, NULL_KEY_AUTH, EL3_KEY);
574     if (ret) {
575         DoDeleteUserKeys(user);
576         LOGE("user el3 create error");
577         StorageRadar::ReportUserKeyResult("GenerateElxAndInstallUserKey", user, ret, "EL3", "el3Path = " + el3Path);
578         return ret;
579     }
580     ret = GenerateAndInstallUserKey(user, el4Path, NULL_KEY_AUTH, EL4_KEY);
581     if (ret) {
582         DoDeleteUserKeys(user);
583         LOGE("user el4 create error");
584         StorageRadar::ReportUserKeyResult("GenerateElxAndInstallUserKey", user, ret, "EL4", "el4Path = " + el4Path);
585         return ret;
586     }
587     ret = GenerateAndInstallUserKey(user, el5Path, NULL_KEY_AUTH, EL5_KEY);
588     if (ret) {
589         DoDeleteUserKeys(user);
590         LOGE("user el5 create error");
591         StorageRadar::ReportUserKeyResult("GenerateElxAndInstallUserKey", user, ret, "EL5", "el5Path = " + el5Path);
592         return ret;
593     }
594     saveLockScreenStatus[user] = true;
595     return ret;
596 }
597 
CheckAndFixUserKeyDirectory(unsigned int user)598 int KeyManager::CheckAndFixUserKeyDirectory(unsigned int user)
599 {
600     std::string el1NeedRestorePath = std::string(USER_EL1_DIR) + "/" + std::to_string(user) + RESTORE_DIR;
601     std::error_code errCode;
602     if (std::filesystem::exists(el1NeedRestorePath, errCode)) {
603         LOGE("el1 need_restore file is existed, upgrade scene not support.");
604         return -EEXIST;
605     }
606     int ret = GenerateIntegrityDirs(user, EL1_KEY);
607     if (ret != -EEXIST) {
608         LOGE("GenerateIntegrityDirs el1 failed.");
609         StorageRadar::ReportUserKeyResult("GenerateIntegrityDirs", user, ret, "EL1", "");
610     }
611     ret = GenerateIntegrityDirs(user, EL2_KEY);
612     if (ret != -EEXIST) {
613         LOGE("GenerateIntegrityDirs el2 failed.");
614         StorageRadar::ReportUserKeyResult("GenerateIntegrityDirs", user, ret, "EL2", "");
615     }
616     return ret;
617 }
618 
GenerateIntegrityDirs(int32_t userId,KeyType type)619 int KeyManager::GenerateIntegrityDirs(int32_t userId, KeyType type)
620 {
621     std::string dirType = (type == EL1_KEY) ? EL1 : EL2;
622     std::string userDir = std::string(FSCRYPT_EL_DIR) + "/" + dirType;
623     uint32_t flag_type = (type == EL1_KEY) ? IStorageDaemonEnum::CRYPTO_FLAG_EL1 : IStorageDaemonEnum::CRYPTO_FLAG_EL2;
624     std::string versionElx = userDir + "/" + std::to_string(userId) + FSCRYPT_VERSION_DIR;
625     std::string encryptElx = userDir + "/" + std::to_string(userId) + ENCRYPT_VERSION_DIR;
626     std::string discardElx = userDir + "/" + std::to_string(userId) + SEC_DISCARD_DIR;
627     std::string shieldElx = userDir + "/" + std::to_string(userId) + SHIELD_DIR;
628     std::error_code errCode;
629     if (!std::filesystem::exists(versionElx, errCode) || !std::filesystem::exists(encryptElx, errCode) ||
630         !std::filesystem::exists(shieldElx, errCode) || !std::filesystem::exists(discardElx, errCode) ||
631         !IsWorkDirExist(dirType, userId)) {
632         LOGE("user %{public}d el %{public}d is not integrity. create error", userId, type);
633         std::string extraData =
634             "dir is not Integrity , userId =" + std::to_string(userId) + ", type = " + std::to_string(type);
635         StorageRadar::ReportUserKeyResult("GenerateIntegrityDirs", userId, E_DIR_INTEGRITY_ERR, dirType,
636                                           extraData);
637         int ret = DoDeleteUserCeEceSeceKeys(userId, userDir, type);
638         if (ret != E_OK) {
639             LOGE("Delete userId=%{public}d el %{public}d key failed", userId, type);
640         }
641 
642         ret = GenerateUserKeyByType(userId, type, {}, {});
643         if (ret != E_OK) {
644             LOGE("upgrade scene:generate user key fail, userId %{public}d, KeyType %{public}d", userId, type);
645             return ret;
646         }
647 
648         LOGI("try to destory dir first, user %{public}d, Type %{public}d", userId, type);
649         (void)UserManager::GetInstance().DestroyUserDirs(userId, flag_type);
650         ret = UserManager::GetInstance().PrepareUserDirs(userId, flag_type);
651         if (ret != E_OK) {
652             LOGE("upgrade scene:prepare user dirs fail, userId %{public}d, type %{public}d", userId, type);
653             return ret;
654         }
655     }
656     LOGI("userId=%{public}d el %{public}d directory is existed, no need fix.", userId, type);
657     return -EEXIST;
658 }
659 
IsWorkDirExist(std::string type,int32_t userId)660 bool KeyManager::IsWorkDirExist(std::string type, int32_t userId)
661 {
662     std::string dataDir = std::string(DATA_DIR) + type + "/" + std::to_string(userId);
663     std::string serviceDir = std::string(SERVICE_DIR) + type + "/" + std::to_string(userId);
664     std::error_code errCode;
665     bool isExist = std::filesystem::exists(dataDir, errCode) && std::filesystem::exists(serviceDir, errCode);
666     return isExist;
667 }
668 
GenerateUserKeyByType(unsigned int user,KeyType type,const std::vector<uint8_t> & token,const std::vector<uint8_t> & secret)669 int KeyManager::GenerateUserKeyByType(unsigned int user, KeyType type,
670                                       const std::vector<uint8_t> &token,
671                                       const std::vector<uint8_t> &secret)
672 {
673     LOGI("start, user:%{public}u, type %{public}u", user, type);
674     if (!KeyCtrlHasFscryptSyspara() || !IsEncryption()) {
675         LOGW("FscryptSyspara has not or encryption not enabled");
676         return 0;
677     }
678 
679     std::lock_guard<std::mutex> lock(keyMutex_);
680     std::string elPath = GetKeyDirByType(type);
681     if (!IsDir(elPath)) {
682         LOGI("El storage dir is not existed");
683         return -ENOENT;
684     }
685 
686     std::string elUserKeyPath = elPath + + "/" + std::to_string(user);
687     if (IsDir(elUserKeyPath)) {
688         LOGE("user %{public}d el key have existed, create error", user);
689         return -EEXIST;
690     }
691     uint64_t secureUid = { 0 };
692     if (!secret.empty() && !token.empty()) {
693         IamClient::GetInstance().GetSecureUid(user, secureUid);
694         LOGE("token is exist, get secure uid");
695     }
696     UserAuth auth = { .token = token, .secret = secret, .secureUid = secureUid };
697     int ret = GenerateAndInstallUserKey(user, elUserKeyPath, auth, type);
698     if (ret) {
699         LOGE("user el create error, user %{public}u, type %{public}u", user, type);
700         StorageRadar::ReportUserKeyResult("GenerateUserKeyByType::GenerateAndInstallUserKey",
701             user, ret, std::to_string(type), "user key path = " + elUserKeyPath);
702         return ret;
703     }
704     LOGI("Create user el success, user %{public}u, type %{public}u", user, type);
705 
706     return 0;
707 }
708 
DeleteElKey(unsigned int user,KeyType type)709 void KeyManager::DeleteElKey(unsigned int user, KeyType type)
710 {
711     if (userElKeys_.find(user) == userElKeys_.end()) {
712         LOGE("The user %{public}u not existed", user);
713         return;
714     }
715     if (userElKeys_[user].find(type) == userElKeys_[user].end()) {
716         LOGE("The el%{public}u not existed", type);
717         return;
718     }
719     userElKeys_[user].erase(type);
720     if (userElKeys_[user].empty()) {
721         userElKeys_.erase(user);
722     }
723 }
724 
DoDeleteUserCeEceSeceKeys(unsigned int user,const std::string userDir,KeyType type)725 int KeyManager::DoDeleteUserCeEceSeceKeys(unsigned int user, const std::string userDir, KeyType type)
726 {
727     LOGI("enter, userDir is %{public}s", userDir.c_str());
728     int ret = 0;
729 #ifdef USER_CRYPTO_MIGRATE_KEY
730     if (userDir == USER_EL1_DIR) {
731         std::string elNeedRestorePath = std::string(USER_EL1_DIR) + "/" + std::to_string(user) + RESTORE_DIR;
732         (void)ClearAppCloneUserNeedRestore(user, elNeedRestorePath);
733     }
734 #endif
735     if (HasElkey(user, type)) {
736         auto elKey = userElKeys_[user][type];
737         if (!elKey->ClearKey()) {
738             LOGE("clear key failed");
739             ret = E_CLEAR_KEY_FAILED;
740         }
741         DeleteElKey(user, type);
742         saveLockScreenStatus.erase(user);
743     } else {
744         std::string elPath = userDir + "/" + std::to_string(user);
745         std::shared_ptr<BaseKey> elKey = GetBaseKey(elPath);
746         if (elKey == nullptr) {
747             LOGE("Malloc el1 Basekey memory failed");
748             return E_PARAMS_NULLPTR_ERR;
749         }
750         if (!elKey->ClearKey()) {
751             LOGE("clear key failed");
752             ret = E_CLEAR_KEY_FAILED;
753         }
754     }
755     LOGI("end, ret is %{public}d", ret);
756     return ret;
757 }
758 
DoDeleteUserKeys(unsigned int user)759 int KeyManager::DoDeleteUserKeys(unsigned int user)
760 {
761     int errCode = 0;
762     KeyType types[] = { EL1_KEY, EL2_KEY, EL3_KEY, EL4_KEY, EL5_KEY };
763     constexpr const char *USER_DIRS[] = {
764         USER_EL1_DIR,
765         USER_EL2_DIR,
766         USER_EL3_DIR,
767         USER_EL4_DIR,
768         USER_EL5_DIR
769     };
770     int size = sizeof(types) / sizeof(types[0]);
771     std::string el("El");
772     const std::string elxPath("elx path=");
773     for (int i = 0; i < size; ++i) {
774         if (types[i] == EL5_KEY && IsUeceSupportWithErrno() == ENOENT) {
775             continue;
776         }
777         int deleteRet = DoDeleteUserCeEceSeceKeys(user, GetKeyDirByType(types[i]), types[i]);
778         if (deleteRet != 0) {
779             LOGE("Delete el%{public}d key failed", i + 1);
780             errCode = deleteRet;
781             StorageRadar::ReportUserKeyResult("DoDeleteUserKeys", user, errCode,
782                 "El" + std::to_string(i + 1), elxPath + USER_DIRS[i]);
783         }
784     }
785     return errCode;
786 }
787 
DeleteUserKeys(unsigned int user)788 int KeyManager::DeleteUserKeys(unsigned int user)
789 {
790     LOGI("start, user:%{public}d", user);
791     if (!KeyCtrlHasFscryptSyspara() || !IsEncryption()) {
792         LOGW("FscryptSyspara has not or encryption not enabled");
793         return 0;
794     }
795 
796     std::lock_guard<std::mutex> lock(keyMutex_);
797     int ret = DoDeleteUserKeys(user);
798     LOGI("delete user key end, ret is %{public}d", ret);
799 
800     auto userTask = userLockScreenTask_.find(user);
801     if (userTask != userLockScreenTask_.end()) {
802         userLockScreenTask_.erase(userTask);
803         LOGI("Delete user %{public}u, erase user task", user);
804     }
805     return ret;
806 }
807 
BuildSecretStatus(struct UserTokenSecret & userTokenSecret)808 std::string BuildSecretStatus(struct UserTokenSecret &userTokenSecret)
809 {
810     std::string isOldEmy = userTokenSecret.oldSecret.empty() ? "true" : "false";
811     std::string isNewEmy = userTokenSecret.newSecret.empty() ? "true" : "false";
812     return "oldSecret isEmpty = " + isOldEmy + ", newSecret isEmpty = " + isNewEmy;
813 }
814 
BuildTimeInfo(int64_t start,int64_t end)815 std::string BuildTimeInfo(int64_t start, int64_t end)
816 {
817     std::string duration = std::to_string(end - start);
818     return " start: " + std::to_string(start) + " ,end: " + std::to_string(end) + " ,duration: " + duration;
819 }
820 
821 #ifdef USER_CRYPTO_MIGRATE_KEY
UpdateUserAuth(unsigned int user,struct UserTokenSecret & userTokenSecret,bool needGenerateShield)822 int KeyManager::UpdateUserAuth(unsigned int user, struct UserTokenSecret &userTokenSecret,
823                                bool needGenerateShield)
824 #else
825 int KeyManager::UpdateUserAuth(unsigned int user, struct UserTokenSecret &userTokenSecret)
826 #endif
827 {
828     std::lock_guard<std::mutex> lock(keyMutex_);
829     std::string secretInfo = BuildSecretStatus(userTokenSecret);
830     std::string queryTime = BuildTimeInfo(getLockStatusTime_[LOCK_STATUS_START], getLockStatusTime_[LOCK_STATUS_END]);
831     int64_t startTime = StorageService::StorageRadar::RecordCurrentTime();
832 
833     LOGW("enter, param status: user=%{public}d, token=%{public}d, oldSec=%{public}d, newSec=%{public}d", user,
834         userTokenSecret.token.empty(), userTokenSecret.oldSecret.empty(), userTokenSecret.newSecret.empty());
835     int ret = UpdateESecret(user, userTokenSecret);
836     if (ret != 0) {
837         LOGE("user %{public}u UpdateESecret fail", user);
838         queryTime += " UpdateUserAuth: " + BuildTimeInfo(startTime, StorageService::StorageRadar::RecordCurrentTime());
839         StorageRadar::ReportUpdateUserAuth("UpdateESecret", user, ret, "EL5", secretInfo + queryTime);
840         return ret;
841     }
842 #ifdef USER_CRYPTO_MIGRATE_KEY
843     ret = UpdateCeEceSeceUserAuth(user, userTokenSecret, EL2_KEY, needGenerateShield);
844     if (ret != 0) {
845         LOGE("user %{public}u UpdateUserAuth el2 key fail", user);
846         queryTime += " UpdateUserAuth: " + BuildTimeInfo(startTime, StorageService::StorageRadar::RecordCurrentTime());
847         StorageRadar::ReportUpdateUserAuth("UpdateCeEceSeceUserAuth_Migrate", user, ret, "EL2", secretInfo + queryTime);
848         return ret;
849     }
850     ret = UpdateCeEceSeceUserAuth(user, userTokenSecret, EL3_KEY, needGenerateShield);
851     if (ret != 0) {
852         LOGE("user %{public}u UpdateUserAuth el3 key fail", user);
853         queryTime += " UpdateUserAuth: " + BuildTimeInfo(startTime, StorageService::StorageRadar::RecordCurrentTime());
854         StorageRadar::ReportUpdateUserAuth("UpdateCeEceSeceUserAuth_Migrate", user, ret, "EL3", secretInfo + queryTime);
855         return ret;
856     }
857     ret = UpdateCeEceSeceUserAuth(user, userTokenSecret, EL4_KEY, needGenerateShield);
858     if (ret != 0) {
859         LOGE("user %{public}u UpdateUserAuth el4 key fail", user);
860         queryTime += " UpdateUserAuth: " + BuildTimeInfo(startTime, StorageService::StorageRadar::RecordCurrentTime());
861         StorageRadar::ReportUpdateUserAuth("UpdateCeEceSeceUserAuth_Migrate", user, ret, "EL4", secretInfo + queryTime);
862         return ret;
863     }
864 #else
865     ret = UpdateCeEceSeceUserAuth(user, userTokenSecret, EL2_KEY);
866     if (ret != 0) {
867         LOGE("user %{public}u UpdateUserAuth el2 key fail", user);
868         queryTime += " UpdateUserAuth: " + BuildTimeInfo(startTime, StorageService::StorageRadar::RecordCurrentTime());
869         StorageRadar::ReportUpdateUserAuth("UpdateCeEceSeceUserAuth", user, ret, "EL2", secretInfo + queryTime);
870         return ret;
871     }
872     ret = UpdateCeEceSeceUserAuth(user, userTokenSecret, EL3_KEY);
873     if (ret != 0) {
874         LOGE("user %{public}u UpdateUserAuth el3 key fail", user);
875         queryTime += " UpdateUserAuth: " + BuildTimeInfo(startTime, StorageService::StorageRadar::RecordCurrentTime());
876         StorageRadar::ReportUpdateUserAuth("UpdateCeEceSeceUserAuth", user, ret, "EL3", secretInfo + queryTime);
877         return ret;
878     }
879     ret = UpdateCeEceSeceUserAuth(user, userTokenSecret, EL4_KEY);
880     if (ret != 0) {
881         LOGE("user %{public}u UpdateUserAuth el4 key fail", user);
882         queryTime += " UpdateUserAuth: " + BuildTimeInfo(startTime, StorageService::StorageRadar::RecordCurrentTime());
883         StorageRadar::ReportUpdateUserAuth("UpdateCeEceSeceUserAuth", user, ret, "EL4", secretInfo + queryTime);
884         return ret;
885     }
886 #endif
887     return ret;
888 }
889 
UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> & authToken,const std::vector<uint8_t> & newSecret,uint64_t secureUid,uint32_t userId,const std::vector<std::vector<uint8_t>> & plainText)890 int32_t KeyManager::UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> &authToken,
891     const std::vector<uint8_t> &newSecret, uint64_t secureUid, uint32_t userId,
892     const std::vector<std::vector<uint8_t>> &plainText)
893 {
894     LOGI("enter UpdateUseAuthWithRecoveryKey start, user:%{public}d", userId);
895     std::string el2Path = std::string(USER_EL2_DIR) + "/" + std::to_string(userId);
896     std::string el3Path = std::string(USER_EL3_DIR) + "/" + std::to_string(userId);
897     std::string el4Path = std::string(USER_EL4_DIR) + "/" + std::to_string(userId);
898     std::vector<std::string> elKeyDirs = {el2Path, el3Path, el4Path};
899 
900     uint32_t i = 0;
901     for (const auto &elxKeyDir : elKeyDirs) {
902         if (!IsDir(elxKeyDir)) {
903             LOGE("Have not found type %{public}s", elxKeyDir.c_str());
904             return E_KEY_TYPE_INVALID;
905         }
906         std::shared_ptr<BaseKey> elxKey = GetBaseKey(elxKeyDir);
907         if (elxKey == nullptr) {
908             LOGE("load elx key failed , key path is %{public}s", elxKeyDir.c_str());
909             return E_PARAMS_NULLPTR_ERR;
910         }
911 
912         if (plainText.size() < elKeyDirs.size()) {
913             LOGE("plain text size error");
914             return E_PARAMS_INVALID;
915         }
916         KeyBlob originKey(plainText[i]);
917         elxKey->SetOriginKey(originKey);
918         i++;
919         auto ret = elxKey->StoreKey({authToken, newSecret, secureUid});
920         if (ret != E_OK) {
921             LOGE("Store key error");
922             return E_ELX_KEY_STORE_ERROR;
923         }
924     }
925     if (IsUeceSupport()) {
926         std::shared_ptr<BaseKey> el5Key = GetBaseKey(std::string(USER_EL5_DIR) + "/" + std::to_string(userId));
927         if (!el5Key) {
928             return E_PARAMS_NULLPTR_ERR;
929         }
930         bool tempUeceSupport = true;
931         UserAuth userAuth = {.token = authToken, .secret = newSecret, .secureUid = secureUid};
932         auto ret = el5Key->EncryptClassE(userAuth, tempUeceSupport, userId, USER_ADD_AUTH);
933         if (ret != E_OK) {
934             el5Key->ClearKey();
935             LOGE("user %{public}u Encrypt E fail", userId);
936             return E_EL5_ENCRYPT_CLASS_ERROR;
937         }
938         ret = el5Key->LockUece(tempUeceSupport);
939         if (ret != E_OK) {
940             LOGE("lock user %{public}u key failed !", userId);
941         }
942     }
943     return E_OK;
944 }
945 
UpdateESecret(unsigned int user,struct UserTokenSecret & tokenSecret)946 int KeyManager::UpdateESecret(unsigned int user, struct UserTokenSecret &tokenSecret)
947 {
948     LOGW("UpdateESecret enter");
949     if (!KeyCtrlHasFscryptSyspara() || !IsEncryption()) {
950         LOGW("FscryptSyspara has not or encryption not enabled");
951         return E_OK;
952     }
953     std::shared_ptr<BaseKey> el5Key = GetUserElKey(user, EL5_KEY);
954     std::string el5Path = std::string(USER_EL5_DIR) + "/" + std::to_string(user);
955     if (IsUeceSupport() && el5Key == nullptr) {
956         if (!MkDirRecurse(el5Path, S_IRWXU)) {
957             LOGE("MkDirRecurse %{public}u failed!", user);
958             return E_CREATE_DIR_RECURSIVE_FAILED;
959         }
960         LOGI("MkDirRecurse %{public}u success!", user);
961         el5Key = GetUserElKey(user, EL5_KEY);
962     }
963     if (el5Key == nullptr) {
964         LOGE("Have not found user %{public}u el key", user);
965         return E_PARAMS_NULLPTR_ERR;
966     }
967     if (tokenSecret.newSecret.empty()) {
968         return DoChangerPinCodeClassE(user, el5Key);
969     }
970     if (!tokenSecret.newSecret.empty() && !tokenSecret.oldSecret.empty()) {
971         saveESecretStatus[user] = true;
972         auto ret = el5Key->ChangePinCodeClassE(saveESecretStatus[user], user);
973         if (ret != E_OK) {
974             LOGE("user %{public}u ChangePinCodeClassE fail, error=%{public}d", user, ret);
975             return E_EL5_UPDATE_CLASS_ERROR;
976         }
977         return 0;
978     }
979     uint32_t status = tokenSecret.oldSecret.empty() ? USER_ADD_AUTH : USER_CHANGE_AUTH;
980     LOGI("UpdateESecret status is %{public}u", status);
981     UserAuth auth = { .token = tokenSecret.token, .secret = tokenSecret.newSecret, .secureUid = tokenSecret.secureUid };
982     saveESecretStatus[user] = true;
983     auto ret = el5Key->EncryptClassE(auth, saveESecretStatus[user], user, status);
984     if (static_cast<uint32_t>(ret) == FILE_ENCRY_ERROR_UECE_AUTH_STATUS_WRONG) {
985         LOGE("user= %{public}d, error=FILE_ENCRY_ERROR_UECE_AUTH_STATUS_WRONG, no need to add again", user);
986     } else if (ret != E_OK) {
987         LOGE("user %{public}u EncryptClassE fail", user);
988         return E_EL5_ENCRYPT_CLASS_ERROR;
989     }
990     el5Key->ClearKeyInfo();
991     LOGW("saveESecretStatus is %{public}u", saveESecretStatus[user]);
992     return 0;
993 }
994 
DoChangerPinCodeClassE(unsigned int user,std::shared_ptr<BaseKey> & el5Key)995 int KeyManager::DoChangerPinCodeClassE(unsigned int user, std::shared_ptr<BaseKey> &el5Key)
996 {
997     auto ret = el5Key->DeleteClassEPinCode(user);
998     if (ret != E_OK) {
999         LOGE("user %{public}u DeleteClassE fail, error=%{public}d", user, ret);
1000         return E_EL5_DELETE_CLASS_ERROR;
1001     }
1002     saveESecretStatus[user] = false;
1003     return 0;
1004 }
1005 
1006 #ifdef USER_CRYPTO_MIGRATE_KEY
UpdateCeEceSeceUserAuth(unsigned int user,struct UserTokenSecret & userTokenSecret,KeyType type,bool needGenerateShield)1007 int KeyManager::UpdateCeEceSeceUserAuth(unsigned int user,
1008                                         struct UserTokenSecret &userTokenSecret,
1009                                         KeyType type, bool needGenerateShield)
1010 #else
1011 int KeyManager::UpdateCeEceSeceUserAuth(unsigned int user,
1012                                         struct UserTokenSecret &userTokenSecret,
1013                                         KeyType type)
1014 #endif
1015 {
1016     LOGW("start, user:%{public}d", user);
1017     if (!KeyCtrlHasFscryptSyspara() || !IsEncryption()) {
1018         LOGW("FscryptSyspara has not or encryption not enabled");
1019         return E_OK;
1020     }
1021     std::shared_ptr<BaseKey> item = GetUserElKey(user, type);
1022     if (item == nullptr) {
1023         LOGE("Have not found user %{public}u el key", user);
1024         return E_PARAMS_NULLPTR_ERR;
1025     }
1026 
1027     UserAuth auth = { {}, userTokenSecret.oldSecret, userTokenSecret.secureUid };
1028     UserAuth auth_newSec = { userTokenSecret.token, userTokenSecret.newSecret, userTokenSecret.secureUid };
1029     LOGW("param status token:%{public}d, oldSec:%{public}d, newSec:%{public}d", userTokenSecret.token.empty(),
1030         userTokenSecret.oldSecret.empty(), userTokenSecret.newSecret.empty());
1031     if (!userTokenSecret.oldSecret.empty()) {
1032         KeyBlob token(userTokenSecret.token);
1033         auth.token = std::move(token);
1034     }
1035     if ((item->RestoreKey(auth) != E_OK) && (item->RestoreKey(NULL_KEY_AUTH) != E_OK) &&
1036         (item->RestoreKey(auth_newSec) != E_OK)) {
1037         LOGE("Restore key error");
1038         return E_RESTORE_KEY_FAILED;
1039     }
1040     if (!userTokenSecret.newSecret.empty()) {
1041         KeyBlob token(userTokenSecret.token);
1042         KeyBlob newSecret(userTokenSecret.newSecret);
1043         auth.token = std::move(token);
1044         auth.secret = std::move(newSecret);
1045     } else {
1046         auth.token.Clear();
1047         auth.secret.Clear();
1048     }
1049 #ifdef USER_CRYPTO_MIGRATE_KEY
1050     auto ret = item->StoreKey(auth, needGenerateShield);
1051 #else
1052     auto ret = item->StoreKey(auth);
1053 #endif
1054     if (ret != E_OK) {
1055         LOGE("Store key error");
1056         return E_ELX_KEY_STORE_ERROR;
1057     }
1058 
1059     // Generate hashkey for encrypt public directory
1060     item->GenerateHashKey();
1061     item->ClearKeyInfo();
1062     userPinProtect[user] = !userTokenSecret.newSecret.empty();
1063     return 0;
1064 }
1065 
CheckNeedRestoreVersion(unsigned int user,KeyType type)1066 int KeyManager::CheckNeedRestoreVersion(unsigned int user, KeyType type)
1067 {
1068     std::error_code errCode;
1069     std::string restore_version;
1070     std::string need_restore_path = GetKeyDirByUserAndType(user, type) + RESTORE_DIR;
1071     (void)OHOS::LoadStringFromFile(need_restore_path, restore_version);
1072     if (std::filesystem::exists(need_restore_path, errCode) &&
1073         restore_version == DEFAULT_NEED_RESTORE_UPDATE_VERSION && !IsAppCloneUser(user)) {
1074         LOGI("NEED_RESTORE path exist: %{public}s, errcode: %{public}d", need_restore_path.c_str(), errCode.value());
1075         return type == EL5_KEY ? -ENONET : -EFAULT;
1076     }
1077     return E_OK;
1078 }
1079 
GetKeyDirByUserAndType(unsigned int user,KeyType type)1080 std::string KeyManager::GetKeyDirByUserAndType(unsigned int user, KeyType type)
1081 {
1082     std::string keyDir = "";
1083     switch (type) {
1084         case EL1_KEY:
1085             keyDir = std::string(USER_EL1_DIR) + "/" + std::to_string(user);
1086             break;
1087         case EL2_KEY:
1088             keyDir = std::string(USER_EL2_DIR) + "/" + std::to_string(user);
1089             break;
1090         case EL3_KEY:
1091             keyDir = std::string(USER_EL3_DIR) + "/" + std::to_string(user);
1092             break;
1093         case EL4_KEY:
1094             keyDir = std::string(USER_EL4_DIR) + "/" + std::to_string(user);
1095             break;
1096         case EL5_KEY:
1097             keyDir = std::string(USER_EL5_DIR) + "/" + std::to_string(user);
1098             break;
1099         default:
1100             LOGE("GetKeyDirByUserAndType type %{public}u is invalid", type);
1101             break;
1102     }
1103     return keyDir;
1104 }
1105 
GetNatoNeedRestorePath(uint32_t userId,KeyType type)1106 std::string KeyManager::GetNatoNeedRestorePath(uint32_t userId, KeyType type)
1107 {
1108     std::string keyDir = "";
1109     switch (type) {
1110         case EL2_KEY:
1111             keyDir = std::string(NATO_EL2_DIR) + "/" + std::to_string(userId);
1112             break;
1113         case EL3_KEY:
1114             keyDir = std::string(NATO_EL3_DIR) + "/" + std::to_string(userId);
1115             break;
1116         case EL4_KEY:
1117             keyDir = std::string(NATO_EL4_DIR) + "/" + std::to_string(userId);
1118             break;
1119         default:
1120             LOGE("GetNatoNeedRestorePath type %{public}u is invalid", type);
1121             break;
1122     }
1123     return keyDir;
1124 }
1125 
GetKeyDirByType(KeyType type)1126 std::string KeyManager::GetKeyDirByType(KeyType type)
1127 {
1128     std::string keyDir = "";
1129     switch (type) {
1130         case EL1_KEY:
1131             keyDir = USER_EL1_DIR;
1132             break;
1133         case EL2_KEY:
1134             keyDir = USER_EL2_DIR;
1135             break;
1136         case EL3_KEY:
1137             keyDir = USER_EL3_DIR;
1138             break;
1139         case EL4_KEY:
1140             keyDir = USER_EL4_DIR;
1141             break;
1142         case EL5_KEY:
1143             keyDir = USER_EL5_DIR;
1144             break;
1145         default:
1146             LOGE("GetKeyDirByType type %{public}u is invalid", type);
1147             break;
1148     }
1149     return keyDir;
1150 }
1151 
SaveUserElKey(unsigned int user,KeyType type,std::shared_ptr<BaseKey> elKey)1152 void KeyManager::SaveUserElKey(unsigned int user, KeyType type, std::shared_ptr<BaseKey> elKey)
1153 {
1154     if (type >= EL1_KEY && type <= EL5_KEY) {
1155         userElKeys_[user][type] = elKey;
1156     } else {
1157         LOGE("Save el key failed,type:%{public}d", type);
1158     }
1159 }
1160 
GetUserElKey(unsigned int user,KeyType type)1161 std::shared_ptr<BaseKey> KeyManager::GetUserElKey(unsigned int user, KeyType type)
1162 {
1163     bool isNeedGenerateBaseKey = false;
1164     std::shared_ptr<BaseKey> elKey = nullptr;
1165     if (!HasElkey(user, type)) {
1166         std::string keyDir = GetKeyDirByUserAndType(user, type);
1167         if (!IsDir(keyDir)) {
1168             LOGE("Have not found user %{public}u el, %{public}u type", user, type);
1169             return nullptr;
1170         }
1171         elKey = GetBaseKey(keyDir);
1172         if (elKey == nullptr) {
1173             LOGE("BaseKey memory failed");
1174             return nullptr;
1175         }
1176         isNeedGenerateBaseKey = true;
1177         LOGI("Generate new baseKey type: %{public}u", type);
1178     }
1179     if (isNeedGenerateBaseKey) {
1180         SaveUserElKey(user, type, elKey);
1181     }
1182     return userElKeys_[user][type];
1183 }
1184 
ActiveCeSceSeceUserKey(unsigned int user,KeyType type,const std::vector<uint8_t> & token,const std::vector<uint8_t> & secret)1185 int KeyManager::ActiveCeSceSeceUserKey(unsigned int user,
1186                                        KeyType type,
1187                                        const std::vector<uint8_t> &token,
1188                                        const std::vector<uint8_t> &secret)
1189 {
1190     if (!KeyCtrlHasFscryptSyspara() || !IsEncryption()) {
1191         LOGW("FscryptSyspara has not or encryption not enabled");
1192         return 0;
1193     }
1194     int ret = CheckNeedRestoreVersion(user, type);
1195     if (ret == -EFAULT || ret == -ENOENT) {
1196         return ret;
1197     }
1198     if (CheckUserPinProtect(user, token, secret) != E_OK) {
1199         LOGE("IAM & Storage mismatch, wait user input pin.");
1200         return E_CHECK_USER_PIN_PROTECT_ERR;
1201     }
1202     std::lock_guard<std::mutex> lock(keyMutex_);
1203     if (HasElkey(user, type) && HashElxActived(user, type)) {
1204         return 0;
1205     }
1206     std::shared_ptr<DelayHandler> userDelayHandler;
1207     if (GetUserDelayHandler(user, userDelayHandler)) {
1208         userDelayHandler->CancelDelayTask();
1209     }
1210     std::string keyDir = GetKeyDirByUserAndType(user, type);
1211     if (keyDir == "") {
1212         return E_KEY_TYPE_INVALID;
1213     }
1214     if (!CheckDir(type, keyDir, user)) {
1215         return -ENOENT;
1216     }
1217     std::shared_ptr<BaseKey> elKey = GetBaseKey(keyDir);
1218     if (elKey == nullptr) {
1219         LOGE("elKey failed");
1220         return -EOPNOTSUPP;
1221     }
1222     if (type == EL5_KEY) {
1223         return ActiveUece(user, elKey, token, secret);
1224     }
1225     if (ActiveElXUserKey(user, token, type, secret, elKey) != 0) {
1226         LOGE("ActiveElXUserKey failed");
1227         return E_ELX_KEY_ACTIVE_ERROR;
1228     }
1229     SaveUserElKey(user, type, elKey);
1230     userPinProtect[user] = !secret.empty();
1231     saveLockScreenStatus[user] = true;
1232     LOGI("Active user %{public}u el success, saveLockScreenStatus is %{public}d", user, saveLockScreenStatus[user]);
1233     return 0;
1234 }
1235 
ActiveElxUserKey4Nato(unsigned int user,KeyType type,const KeyBlob & authToken)1236 int KeyManager::ActiveElxUserKey4Nato(unsigned int user, KeyType type, const KeyBlob &authToken)
1237 {
1238     LOGW("Active Elx user key for nato for userId=%{public}d, keyType=%{public}u", user, type);
1239     if (!KeyCtrlHasFscryptSyspara() || !IsEncryption()) {
1240         LOGW("FscryptSyspara has not or encryption not enabled");
1241         return E_OK;
1242     }
1243     std::lock_guard<std::mutex> lock(keyMutex_);
1244     std::string keyDir = GetNatoNeedRestorePath(user, type);
1245     if (keyDir == "") {
1246         return E_KEY_TYPE_INVALID;
1247     }
1248     if (!CheckDir(type, keyDir, user)) {
1249         return E_NATO_CHECK_KEY_DIR_ERROR;
1250     }
1251     std::shared_ptr<BaseKey> elKey = GetBaseKey(keyDir);
1252     if (elKey == nullptr) {
1253         LOGE("GetBaseKey nato for userId=%{public}d el%{public}u failed.", user, type);
1254         return E_PARAMS_NULLPTR_ERR;
1255     }
1256     if (!elKey->InitKey(false)) {
1257         LOGE("InitKey nato for userId=%{public}d el%{public}u failed.", user, type);
1258         return E_NATO_INIT_USER_KEY_ERROR;
1259     }
1260     if (elKey->RestoreKey4Nato(keyDir, type) != E_OK) {
1261         LOGE("RestoreKey nato for userId=%{public}d el%{public}u failed.", user, type);
1262         return E_NATO_RESTORE_USER_KEY_ERROR;
1263     }
1264     if (elKey->ActiveKey(authToken, RETRIEVE_KEY) != E_OK) {
1265         LOGE("ActiveKey nato for userId=%{public}d el%{public}u failed.", user, type);
1266         return E_NATO_ACTIVE_EL4_KEY_ERROR;
1267     }
1268     LOGW("Active Elx user key for nato for userId=%{public}d, keyType=%{public}u success.", user, type);
1269     return E_OK;
1270 }
1271 
ActiveUece(unsigned int user,std::shared_ptr<BaseKey> elKey,const std::vector<uint8_t> & token,const std::vector<uint8_t> & secret)1272 int KeyManager::ActiveUece(unsigned int user,
1273                            std::shared_ptr<BaseKey> elKey,
1274                            const std::vector<uint8_t> &token,
1275                            const std::vector<uint8_t> &secret)
1276 {
1277     if (ActiveUeceUserKey(user, token, secret, elKey) != 0) {
1278         LOGE("ActiveUeceUserKey failed");
1279         return E_ELX_KEY_ACTIVE_ERROR;
1280     }
1281     return 0;
1282 }
1283 
CheckDir(KeyType type,std::string keyDir,unsigned int user)1284 bool KeyManager::CheckDir(KeyType type, std::string keyDir, unsigned int user)
1285 {
1286     if ((type != EL5_KEY) && !IsDir(keyDir)) {
1287         LOGE("Have not found user %{public}u el", user);
1288         return false;
1289     }
1290     if ((type == EL5_KEY) && CheckAndDeleteEmptyEl5Directory(keyDir, user) != 0) {
1291         return false;
1292     }
1293     return true;
1294 }
1295 
HashElxActived(unsigned int user,KeyType type)1296 bool KeyManager::HashElxActived(unsigned int user, KeyType type)
1297 {
1298     if (HasElkey(user, type)) {
1299         auto elKey = userElKeys_[user][type];
1300         if (elKey == nullptr) {
1301             LOGI("The ElKey is nullptr: %{public}d", elKey == nullptr);
1302             return false;
1303         }
1304 
1305         if (!elKey->KeyDescIsEmpty()) {
1306             LOGI("user el%{public}u key desc has existed", type);
1307             return true;
1308         }
1309     }
1310     return false;
1311 }
1312 
IsAppCloneUser(unsigned int user)1313 bool KeyManager::IsAppCloneUser(unsigned int user)
1314 {
1315     return user >= START_APP_CLONE_USER_ID && user <= MAX_APP_CLONE_USER_ID;
1316 }
1317 
CheckAndDeleteEmptyEl5Directory(std::string keyDir,unsigned int user)1318 int KeyManager::CheckAndDeleteEmptyEl5Directory(std::string keyDir, unsigned int user)
1319 {
1320     std::string keyUeceDir = std::string(UECE_DIR) + "/" + std::to_string(user);
1321     if (!IsDir(keyDir) || !IsDir(keyUeceDir)) {
1322         LOGE("Have not found dir %{public}u el5", user);
1323         return -ENOENT;
1324     }
1325 
1326     if (IsDir(keyDir) && std::filesystem::is_empty(keyDir)) {
1327         OHOS::ForceRemoveDirectory(keyDir);
1328         LOGE("Have removed key dir %{public}u el5", user);
1329         return -ENOENT;
1330     }
1331     return 0;
1332 }
1333 
GetUserDelayHandler(uint32_t userId,std::shared_ptr<DelayHandler> & delayHandler)1334 bool KeyManager::GetUserDelayHandler(uint32_t userId, std::shared_ptr<DelayHandler> &delayHandler)
1335 {
1336     LOGI("enter");
1337     auto iterTask = userLockScreenTask_.find(userId);
1338     if (iterTask == userLockScreenTask_.end()) {
1339         userLockScreenTask_[userId] = std::make_shared<DelayHandler>(userId);
1340     }
1341     delayHandler = userLockScreenTask_[userId];
1342     if (delayHandler == nullptr) {
1343         LOGE("user %{public}d delayHandler is nullptr !", userId);
1344         return false;
1345     }
1346     return true;
1347 }
1348 
ActiveUeceUserKey(unsigned int user,const std::vector<uint8_t> & token,const std::vector<uint8_t> & secret,std::shared_ptr<BaseKey> elKey)1349 int KeyManager::ActiveUeceUserKey(unsigned int user,
1350                                   const std::vector<uint8_t> &token,
1351                                   const std::vector<uint8_t> &secret, std::shared_ptr<BaseKey> elKey)
1352 {
1353     saveESecretStatus[user] = !secret.empty();
1354     LOGW("userId %{public}u, token empty %{public}d sec empty %{public}d", user, token.empty(), secret.empty());
1355     SaveUserElKey(user, EL5_KEY, elKey);
1356     UserAuth auth = { .token = token, .secret = secret };
1357     bool eBufferStatue = false;
1358     auto ret = elKey->DecryptClassE(auth, saveESecretStatus[user], eBufferStatue, user, true);
1359     if (ret != E_OK) {
1360         LOGE("Unlock user %{public}u E_Class failed", user);
1361         return E_EL5_DELETE_CLASS_ERROR;
1362     }
1363 
1364     if (!token.empty() && !secret.empty() && eBufferStatue) {
1365         if (TryToFixUeceKey(user, token, secret) != E_OK) {
1366             LOGE("TryToFixUeceKey el5 failed !");
1367             return E_TRY_TO_FIX_USER_KEY_ERR;
1368         }
1369     }
1370     LOGW("ActiveCeSceSeceUserKey user %{public}u, saveESecretStatus %{public}d", user, saveESecretStatus[user]);
1371     return 0;
1372 }
1373 
ActiveElXUserKey(unsigned int user,const std::vector<uint8_t> & token,KeyType keyType,const std::vector<uint8_t> & secret,std::shared_ptr<BaseKey> elKey)1374 int KeyManager::ActiveElXUserKey(unsigned int user,
1375                                  const std::vector<uint8_t> &token, KeyType keyType,
1376                                  const std::vector<uint8_t> &secret, std::shared_ptr<BaseKey> elKey)
1377 {
1378     if (elKey->InitKey(false) == false) {
1379         LOGE("Init el failed");
1380         return E_ELX_KEY_INIT_ERROR;
1381     }
1382     UserAuth auth = { token, secret };
1383     auto keyResult = elKey->RestoreKey(auth);
1384     bool noKeyResult = (keyResult != E_OK) && (elKey->RestoreKey(NULL_KEY_AUTH) == E_OK);
1385     // key and no-key situation all failed, include upgrade situation, return err
1386     if (keyResult != E_OK && !noKeyResult) {
1387         LOGE("Restore el failed, type: %{public}u", keyType);
1388         return E_RESTORE_KEY_FAILED;
1389     }
1390     // if device has pwd and decrypt success, continue.otherwise try no pwd and fix situation.
1391     if (keyResult != E_OK && noKeyResult) {
1392         if (TryToFixUserCeEceSeceKey(user, keyType, token, secret) != E_OK) {
1393             LOGE("TryToFixUserCeEceSeceKey elx failed, type %{public}u", keyType);
1394             return E_TRY_TO_FIX_USER_KEY_ERR;
1395         }
1396     }
1397     std::string NEED_UPDATE_PATH = GetKeyDirByUserAndType(user, keyType) + PATH_LATEST + SUFFIX_NEED_UPDATE;
1398     std::string NEED_RESTORE_PATH = GetKeyDirByUserAndType(user, keyType) + PATH_LATEST + SUFFIX_NEED_RESTORE;
1399     if (!FileExists(NEED_RESTORE_PATH) && !FileExists(NEED_UPDATE_PATH)) {
1400         auto ret = elKey->StoreKey(auth);
1401         if (ret != E_OK) {
1402             LOGE("Store el failed");
1403             return E_ELX_KEY_STORE_ERROR;
1404         }
1405     }
1406     // Generate hashkey for encrypt public directory
1407     elKey->GenerateHashKey();
1408     if (elKey->ActiveKey(auth.token, RETRIEVE_KEY) != E_OK) {
1409         LOGE("Active user %{public}u key failed", user);
1410         return E_ELX_KEY_ACTIVE_ERROR;
1411     }
1412     return 0;
1413 }
1414 
UnlockUserScreen(uint32_t user,const std::vector<uint8_t> & token,const std::vector<uint8_t> & secret)1415 int KeyManager::UnlockUserScreen(uint32_t user, const std::vector<uint8_t> &token, const std::vector<uint8_t> &secret)
1416 {
1417     LOGI("start");
1418     int64_t startTime = StorageService::StorageRadar::RecordCurrentTime();
1419     userPinProtect[user] = !secret.empty() || !token.empty();
1420     std::shared_ptr<DelayHandler> userDelayHandler;
1421     if (GetUserDelayHandler(user, userDelayHandler)) {
1422         userDelayHandler->CancelDelayTask();
1423     }
1424     auto iter = saveLockScreenStatus.find(user);
1425     if (iter == saveLockScreenStatus.end()) {
1426         saveLockScreenStatus.insert(std::make_pair(user, false));
1427     }
1428     if (!IsUserCeDecrypt(user)) {
1429         LOGE("user ce does not decrypt, skip");
1430         return 0;
1431     }
1432     if (!KeyCtrlHasFscryptSyspara() || !IsEncryption()) {
1433         saveLockScreenStatus[user] = true;
1434         LOGI("saveLockScreenStatus is %{public}d", saveLockScreenStatus[user]);
1435         return 0;
1436     }
1437     std::lock_guard<std::mutex> lock(keyMutex_);
1438     std::string tokenEmy = token.empty() ? "true" : "false";
1439     std::string secretEmy = secret.empty() ? "true" : "false";
1440     std::string queryTime = BuildTimeInfo(getLockStatusTime_[LOCK_STATUS_START], getLockStatusTime_[LOCK_STATUS_END]);
1441     std::string extraData = "token isEmpty = " + tokenEmy + ", secret isEmpty = " + secretEmy + queryTime;
1442     int ret = 0;
1443     if ((ret = UnlockEceSece(user, token, secret)) != E_OK) {
1444         extraData += " UnlockScreen: " + BuildTimeInfo(startTime, StorageService::StorageRadar::RecordCurrentTime());
1445         StorageRadar::ReportUpdateUserAuth("UnlockUserScreen::UnlockEceSece", user, ret, "EL4", extraData);
1446         return ret;
1447     }
1448     if ((ret = UnlockUece(user, token, secret)) != E_OK) {
1449         extraData += " UnlockScreen: " + BuildTimeInfo(startTime, StorageService::StorageRadar::RecordCurrentTime());
1450         StorageRadar::ReportUpdateUserAuth("UnlockUserScreen::UnlockUece", user, ret, "EL5", extraData);
1451         return ret;
1452     }
1453     saveLockScreenStatus[user] = true;
1454     LOGW("UnlockUserScreen user %{public}u el3 and el4 success and saveLockScreenStatus is %{public}d", user,
1455          saveLockScreenStatus[user]);
1456     return 0;
1457 }
1458 
UnlockEceSece(uint32_t user,const std::vector<uint8_t> & token,const std::vector<uint8_t> & secret)1459 int32_t KeyManager::UnlockEceSece(uint32_t user,
1460                                   const std::vector<uint8_t> &token,
1461                                   const std::vector<uint8_t> &secret)
1462 {
1463     auto el4Key = GetUserElKey(user, EL4_KEY);
1464     if (el4Key == nullptr) {
1465         saveLockScreenStatus[user] = true;
1466         LOGE("The user %{public}u not been actived and saveLockScreenStatus is %{public}d", user,
1467              saveLockScreenStatus[user]);
1468         return E_NON_EXIST;
1469     }
1470     if (el4Key->RestoreKey({ token, secret }, false) != E_OK && el4Key->RestoreKey(NULL_KEY_AUTH, false) != E_OK) {
1471         LOGE("Restore user %{public}u el4 key failed", user);
1472         return E_RESTORE_KEY_FAILED;
1473     }
1474     int32_t ret = el4Key->UnlockUserScreen(token, user, FSCRYPT_SDP_ECE_CLASS);
1475     if (ret != E_OK) {
1476         LOGE("UnlockUserScreen user %{public}u el4 key failed", user);
1477         return E_UNLOCK_SCREEN_FAILED;
1478     }
1479     LOGI("DecryptClassE user %{public}u saveESecretStatus %{public}d", user, saveESecretStatus[user]);
1480     return E_OK;
1481 }
1482 
UnlockUece(uint32_t user,const std::vector<uint8_t> & token,const std::vector<uint8_t> & secret)1483 int32_t KeyManager::UnlockUece(uint32_t user,
1484                                const std::vector<uint8_t> &token,
1485                                const std::vector<uint8_t> &secret)
1486 {
1487     UserAuth auth = {.token = token, .secret = secret};
1488     saveESecretStatus[user] = !auth.token.IsEmpty();
1489     auto el5Key = GetUserElKey(user, EL5_KEY);
1490     bool eBufferStatue = false;
1491     if (el5Key != nullptr) {
1492         auto ret = el5Key->DecryptClassE(auth, saveESecretStatus[user], eBufferStatue, user, false);
1493         if (ret != E_OK) {
1494             LOGE("Unlock user %{public}u uece failed", user);
1495             return ret;
1496         }
1497     }
1498     return E_OK;
1499 }
1500 
GetLockScreenStatus(uint32_t user,bool & lockScreenStatus)1501 int KeyManager::GetLockScreenStatus(uint32_t user, bool &lockScreenStatus)
1502 {
1503     getLockStatusTime_[LOCK_STATUS_START] = StorageService::StorageRadar::RecordCurrentTime();
1504     LOGI("start");
1505     std::lock_guard<std::mutex> lock(keyMutex_);
1506     auto iter = saveLockScreenStatus.find(user);
1507     lockScreenStatus = (iter == saveLockScreenStatus.end()) ? false: iter->second;
1508     LOGW("lockScreenStatus is %{public}d", lockScreenStatus);
1509     getLockStatusTime_[LOCK_STATUS_END] = StorageService::StorageRadar::RecordCurrentTime();
1510     return 0;
1511 }
1512 
GenerateAppkey(uint32_t userId,uint32_t hashId,std::string & keyId,bool needReSet)1513 int KeyManager::GenerateAppkey(uint32_t userId, uint32_t hashId, std::string &keyId, bool needReSet)
1514 {
1515     if (!IsUeceSupport() || !IsEncryption()) {
1516         LOGI("Not support uece or encryption not enabled!");
1517         return -ENOTSUP;
1518     }
1519     LOGI("enter");
1520     std::lock_guard<std::mutex> lock(keyMutex_);
1521     if (needReSet) {
1522         return GenerateAppkeyWithRecover(userId, hashId, keyId);
1523     }
1524 
1525     if (userId == KEY_RECOVERY_USER_ID) {
1526         LOGI("GenerateAppKey when RecoverKey");
1527         auto el5Key = GetBaseKey(GetKeyDirByUserAndType(userId, EL5_KEY));
1528         if (el5Key == nullptr) {
1529             LOGE("el5Key is nullptr");
1530             return E_PARAMS_NULLPTR_ERR;
1531         }
1532         auto ret = el5Key->GenerateAppkey(userId, hashId, keyId);
1533         if (ret != E_OK) {
1534             LOGE("Failed to generate Appkey2, error=%{public}d", ret);
1535             return E_EL5_GENERATE_APP_KEY_ERR;
1536         }
1537         return 0;
1538     }
1539     auto el5Key = GetBaseKey(GetKeyDirByUserAndType(userId, EL5_KEY));
1540     if (el5Key == nullptr) {
1541         LOGE("el5Key is nullptr");
1542         return E_PARAMS_NULLPTR_ERR;
1543     }
1544     auto ret = el5Key->GenerateAppkey(userId, hashId, keyId);
1545     if (ret != E_OK) {
1546         LOGE("Failed to generate Appkey2 error=%{public}d", ret);
1547         return E_EL5_GENERATE_APP_KEY_ERR;
1548     }
1549 
1550     return 0;
1551 }
1552 
GenerateAppkeyWithRecover(uint32_t userId,uint32_t hashId,std::string & keyId)1553 int KeyManager::GenerateAppkeyWithRecover(uint32_t userId, uint32_t hashId, std::string &keyId)
1554 {
1555     LOGI("GenerateAppkey needReSet");
1556     std::string el5Path = std::string(MAINTAIN_USER_EL5_DIR) + "/" + std::to_string(userId);
1557     auto el5Key = GetBaseKey(el5Path);
1558     if (el5Key == nullptr) {
1559         LOGE("el5Key is nullptr");
1560         return E_PARAMS_NULLPTR_ERR;
1561     }
1562     auto ret = el5Key->GenerateAppkey(userId, hashId, keyId);
1563     if (ret != E_OK) {
1564         LOGE("Failed to generate Appkey2 error=%{public}d", ret);
1565         return E_EL5_GENERATE_APP_KEY_WITH_RECOVERY_ERR;
1566     }
1567     ret = el5Key->DeleteClassEPinCode(userId);
1568     if (ret != E_OK) {
1569         LOGE("GenerateAppkey DeleteClassEPinCode failed");
1570         return E_EL5_DELETE_CLASS_WITH_RECOVERY_ERR;
1571     }
1572     saveESecretStatus[userId] = false;
1573     return 0;
1574 }
1575 
DeleteAppkey(uint32_t userId,const std::string keyId)1576 int KeyManager::DeleteAppkey(uint32_t userId, const std::string keyId)
1577 {
1578     if (!IsUeceSupport() || !IsEncryption()) {
1579         LOGI("Not support uece or encryption not enabled!");
1580         return -ENOTSUP;
1581     }
1582     std::lock_guard<std::mutex> lock(keyMutex_);
1583     auto el5Key = GetBaseKey(GetKeyDirByUserAndType(userId, EL5_KEY));
1584     if (el5Key == nullptr) {
1585         LOGE("el5Key is nullptr");
1586         return E_PARAMS_NULLPTR_ERR;
1587     }
1588     if (el5Key->DeleteAppkey(keyId) != E_OK) {
1589         LOGE("Failed to delete Appkey2");
1590         return E_EL5_DELETE_APP_KEY_ERR;
1591     }
1592     return 0;
1593 }
1594 
CreateRecoverKey(uint32_t userId,uint32_t userType,const std::vector<uint8_t> & token,const std::vector<uint8_t> & secret)1595 int KeyManager::CreateRecoverKey(uint32_t userId, uint32_t userType, const std::vector<uint8_t> &token,
1596                                  const std::vector<uint8_t> &secret)
1597 {
1598     LOGI("enter");
1599     std::string globalUserEl1Path = std::string(USER_EL1_DIR) + "/" + std::to_string(GLOBAL_USER_ID);
1600     std::string el1Path = std::string(USER_EL1_DIR) + "/" + std::to_string(userId);
1601     std::string el2Path = std::string(USER_EL2_DIR) + "/" + std::to_string(userId);
1602     std::string el3Path = std::string(USER_EL3_DIR) + "/" + std::to_string(userId);
1603     std::string el4Path = std::string(USER_EL4_DIR) + "/" + std::to_string(userId);
1604     std::vector<std::string> elKeyDirs = { DEVICE_EL1_DIR, globalUserEl1Path, el1Path, el2Path, el3Path, el4Path };
1605     std::vector<KeyBlob> originKeys;
1606     for (const auto &elxKeyDir : elKeyDirs) {
1607         if (!IsDir(elxKeyDir)) {
1608             LOGE("Have not found type %{public}s el", elxKeyDir.c_str());
1609             return E_KEY_TYPE_INVALID;
1610         }
1611         std::shared_ptr<BaseKey> elxKey = GetBaseKey(elxKeyDir);
1612         if (elxKey == nullptr) {
1613             LOGE("load elx key failed , key path is %{public}s", elxKeyDir.c_str());
1614             return E_PARAMS_NULLPTR_ERR;
1615         }
1616         UserAuth auth = { token, secret };
1617         if (secret.empty() && token.size() == RECOVERY_TOKEN_CHALLENGE_LENG) {
1618             LOGW("secret is empty, use none token.");
1619             auth = { {}, {}};
1620         }
1621         if ((elxKey->RestoreKey(auth, false) != E_OK) && (elxKey->RestoreKey(NULL_KEY_AUTH, false) != E_OK)) {
1622             LOGE("Restore el failed");
1623             return E_RESTORE_KEY_FAILED;
1624         }
1625         KeyBlob originKey;
1626         if (!elxKey->GetOriginKey(originKey)) {
1627             LOGE("get origin key failed !");
1628             return -ENOENT;
1629         }
1630         originKeys.push_back(std::move(originKey));
1631     }
1632     int ret = RecoveryManager::GetInstance().CreateRecoverKey(userId, userType, token, secret, originKeys);
1633     if (ret != E_OK) {
1634         LOGE("Create recovery key failed !");
1635         return ret;
1636     }
1637     originKeys.clear();
1638     return E_OK;
1639 }
1640 
SetRecoverKey(const std::vector<uint8_t> & key)1641 int KeyManager::SetRecoverKey(const std::vector<uint8_t> &key)
1642 {
1643     LOGI("enter");
1644     std::vector<KeyBlob> originIvs;
1645     if (RecoveryManager::GetInstance().SetRecoverKey(key) != E_OK) {
1646         LOGE("Set recovery key filed !");
1647         return E_SET_RECOVERY_KEY_ERR;
1648     }
1649     return E_OK;
1650 }
1651 
ResetSecretWithRecoveryKey(uint32_t userId,uint32_t rkType,const std::vector<uint8_t> & key)1652 int32_t KeyManager::ResetSecretWithRecoveryKey(uint32_t userId, uint32_t rkType, const std::vector<uint8_t> &key)
1653 {
1654     LOGI("enter");
1655 #ifdef RECOVER_KEY_TEE_ENVIRONMENT
1656     std::vector<KeyBlob> originIvs;
1657     auto ret = RecoveryManager::GetInstance().ResetSecretWithRecoveryKey(userId, rkType, key, originIvs);
1658     if (ret != E_OK) {
1659         LOGE("ResetSecretWithRecoveryKey filed !");
1660         return E_RESET_SECRET_WITH_RECOVERY_KEY_ERR;
1661     }
1662 
1663     LOGI("enter UpdateUseAuthWithRecoveryKey start, user:%{public}d", userId);
1664     std::string globalUserEl1Path = std::string(MAINTAIN_USER_EL1_DIR) + "/" + std::to_string(GLOBAL_USER_ID);
1665     std::string el1Path = std::string(MAINTAIN_USER_EL1_DIR) + "/" + std::to_string(userId);
1666     std::string el2Path = std::string(MAINTAIN_USER_EL2_DIR) + "/" + std::to_string(userId);
1667     std::string el3Path = std::string(MAINTAIN_USER_EL3_DIR) + "/" + std::to_string(userId);
1668     std::string el4Path = std::string(MAINTAIN_USER_EL4_DIR) + "/" + std::to_string(userId);
1669     std::vector<std::string> elKeyDirs = {MAINTAIN_DEVICE_EL1_DIR, globalUserEl1Path,
1670                                           el1Path, el2Path, el3Path, el4Path};
1671 
1672     if (originIvs.size() < elKeyDirs.size()) {
1673         LOGE("plain text size error");
1674         return E_PARAMS_INVALID;
1675     }
1676 
1677     uint32_t i = 0;
1678     for (const auto &elxKeyDir : elKeyDirs) {
1679         if (!IsDir(elxKeyDir)) {
1680             LOGE("Have not found type %{public}s", elxKeyDir.c_str());
1681             return E_KEY_TYPE_INVALID;
1682         }
1683         std::shared_ptr<BaseKey> elxKey = GetBaseKey(elxKeyDir);
1684         if (elxKey == nullptr) {
1685             LOGE("load elx key failed , key path is %{public}s", elxKeyDir.c_str());
1686             return E_PARAMS_NULLPTR_ERR;
1687         }
1688 
1689         elxKey->SetOriginKey(originIvs[i]);
1690         i++;
1691         auto ret = elxKey->StoreKey(NULL_KEY_AUTH);
1692         if (ret != E_OK) {
1693             LOGE("Store key error");
1694             return E_ELX_KEY_STORE_ERROR;
1695         }
1696     }
1697 #endif
1698     return E_OK;
1699 }
1700 
UnlockUserAppKeys(uint32_t userId,bool needGetAllAppKey)1701 int KeyManager::UnlockUserAppKeys(uint32_t userId, bool needGetAllAppKey)
1702 {
1703     if (!IsUeceSupport() || !IsEncryption()) {
1704         LOGI("E type is not support or encryption not enabled");
1705         return E_OK;
1706     }
1707 #ifdef EL5_FILEKEY_MANAGER
1708     int ret = E_OK;
1709     std::vector<std::pair<int, std::string>> keyInfo;
1710     std::vector<std::pair<std::string, bool>> loadInfos;
1711     auto startTime = StorageService::StorageRadar::RecordCurrentTime();
1712     if (needGetAllAppKey) {
1713         ret = El5FilekeyManagerKit::GetUserAllAppKey(userId, keyInfo);
1714         if (ret != 0) {
1715             LOGE("get user all app keys fail.");
1716             StorageRadar::ReportEl5KeyMgrResult("UnlockUserAppKeys::GetUserAllAppKey", ret, userId);
1717             return ret;
1718         }
1719         LOGI("get user all app keys success.");
1720     } else {
1721         ret = El5FilekeyManagerKit::GetUserAppKey(userId, keyInfo);
1722         if (ret != 0) {
1723             LOGE("get User Appkeys fail.");
1724             StorageRadar::ReportEl5KeyMgrResult("UnlockUserAppKeys::GetUserAppKey", ret, userId);
1725             return ret;
1726         }
1727         LOGI("get User Appkeys success.");
1728     }
1729     auto delay = StorageService::StorageRadar::ReportDuration("GET USER APP KEYS",
1730         startTime, StorageService::DELAY_TIME_THRESH_HIGH, userId);
1731     LOGI("SD_DURATION: GET USER APP KEYS: delay time = %{public}s", delay.c_str());
1732     startTime = StorageService::StorageRadar::RecordCurrentTime();
1733     ret = GenerateAndLoadAppKeyInfo(userId, keyInfo);
1734     delay = StorageService::StorageRadar::ReportDuration("GEN&LOAD APP KEY INFO",
1735         startTime, StorageService::DELAY_TIME_THRESH_HIGH, userId);
1736     LOGI("SD_DURATION: GEN&LOAD APP KEY INFO: delay time = %{public}s", delay.c_str());
1737     if (ret != E_OK) {
1738         LOGE("UnlockUserAppKeys fail.");
1739         return ret;
1740     }
1741 #endif
1742     LOGI("UnlockUserAppKeys success!");
1743     return E_OK;
1744 }
1745 
1746 #ifdef EL5_FILEKEY_MANAGER
GenerateAndLoadAppKeyInfo(uint32_t userId,const std::vector<std::pair<int,std::string>> & keyInfo)1747 int KeyManager::GenerateAndLoadAppKeyInfo(uint32_t userId, const std::vector<std::pair<int, std::string>> &keyInfo)
1748 {
1749     std::vector<std::pair<std::string, bool>> loadInfos;
1750     if (keyInfo.size() == 0) {
1751         LOGE("The keyInfo is empty!");
1752         return E_OK;
1753     }
1754     if (!HasElkey(userId, EL5_KEY)) {
1755         return -ENOENT;
1756     }
1757     auto elKey = userElKeys_[userId][EL5_KEY];
1758     std::string keyId;
1759     for (auto keyInfoAppUid :keyInfo) {
1760         auto startTime = StorageService::StorageRadar::RecordCurrentTime();
1761         if (elKey->GenerateAppkey(userId, keyInfoAppUid.first, keyId) != E_OK) {
1762             LOGE("Failed to Generate Appkey2!");
1763             loadInfos.push_back(std::make_pair(keyInfoAppUid.second, false));
1764             continue;
1765         }
1766         auto delay = StorageService::StorageRadar::ReportDuration("GENERATE APP KEY",
1767             startTime, StorageService::DELAY_TIME_THRESH_HIGH, userId);
1768         LOGI("SD_DURATION: GENERATE APPKEY, delay time = %{public}s", delay.c_str());
1769         if (keyInfoAppUid.second != keyId) {
1770             LOGE("The keyId check fails!");
1771             loadInfos.push_back(std::make_pair(keyInfoAppUid.second, false));
1772             continue;
1773         }
1774         loadInfos.push_back(std::make_pair(keyInfoAppUid.second, true));
1775     }
1776     auto startTime = StorageService::StorageRadar::RecordCurrentTime();
1777     int ret = El5FilekeyManagerKit::ChangeUserAppkeysLoadInfo(userId, loadInfos);
1778     if (ret != 0) {
1779         LOGE("Change User Appkeys LoadInfo fail.");
1780         StorageRadar::ReportEl5KeyMgrResult("GenerateAndLoadAppKeyInfo::ChangeUserAppkeysLoadInfo", ret, userId);
1781         return ret;
1782     }
1783     auto delay = StorageService::StorageRadar::ReportDuration("CHANGE USER APP KEYS LOAD INFO",
1784         startTime, StorageService::DELAY_TIME_THRESH_HIGH, userId);
1785     LOGI("SD_DURATION: CHANGE USER APP KEYS LOAD INFO: delay time = %{public}s", delay.c_str());
1786     return E_OK;
1787 }
1788 #endif
1789 
InActiveUserKey(unsigned int user)1790 int KeyManager::InActiveUserKey(unsigned int user)
1791 {
1792     LOGI("start");
1793     if (!KeyCtrlHasFscryptSyspara() || !IsEncryption()) {
1794         LOGW("FscryptSyspara has not or encryption not enabled");
1795         return 0;
1796     }
1797     std::lock_guard<std::mutex> lock(keyMutex_);
1798     KeyType types[] = { EL2_KEY, EL3_KEY, EL4_KEY, EL5_KEY };
1799     int ret = 0;
1800     for (KeyType type : types) {
1801         ret = InactiveUserElKey(user, type);
1802         if (ret != E_OK) {
1803             LOGE("Inactive user El%{public}d key failed", type);
1804             StorageRadar::ReportUserKeyResult("InactiveUserElKey", user, ret, "EL" + std::to_string(type), "");
1805             return ret;
1806         }
1807     }
1808     auto userTask = userLockScreenTask_.find(user);
1809     if (userTask != userLockScreenTask_.end()) {
1810         userLockScreenTask_.erase(userTask);
1811         LOGI("InActive user %{public}u, erase user task", user);
1812     }
1813     return 0;
1814 }
1815 
InactiveUserElKey(unsigned int user,KeyType type)1816 int KeyManager::InactiveUserElKey(unsigned int user, KeyType type)
1817 {
1818     std::shared_ptr<BaseKey> elKey;
1819     if (!HasElkey(user, type)) {
1820         LOGE("Have not found user %{public}u type %{public}u", user, type);
1821         std::string keyDir = GetKeyDirByUserAndType(user, type);
1822         if (type != EL5_KEY && !IsDir(keyDir)) {
1823             LOGE("have not found user %{public}u, type %{public}u", user, type);
1824             return E_PARAMS_INVALID;
1825         }
1826         elKey = GetBaseKey(keyDir);
1827     } else {
1828         elKey = userElKeys_[user][type];
1829     }
1830     if (elKey == nullptr) {
1831         LOGE("BaseKey memory failed");
1832         return E_PARAMS_INVALID;
1833     }
1834     if (elKey->InactiveKey(USER_LOGOUT) != E_OK) {
1835         LOGE("Clear user %{public}u key failed", user);
1836         return E_ELX_KEY_INACTIVE_ERROR;
1837     }
1838     LOGI("remove elx desc");
1839     auto elx = elKey->GetKeyDir();
1840     if (!elx.empty() && elx != "el1") {
1841         std::string descElx = std::string(FSCRYPT_EL_DIR) + "/" + elx + "/" + std::to_string(user) + DESC_DIR;
1842         (void)remove(descElx.c_str());
1843         LOGI("remove desc success.");
1844     }
1845     DeleteElKey(user, type);
1846     LOGI("Inactive user %{public}u elX success", user);
1847     return 0;
1848 }
1849 
LockUserScreen(uint32_t user)1850 int KeyManager::LockUserScreen(uint32_t user)
1851 {
1852     LOGI("start");
1853     std::lock_guard<std::mutex> lock(keyMutex_);
1854     std::error_code errCode;
1855     if (!IsUserCeDecrypt(user) || std::filesystem::exists(GetNatoNeedRestorePath(user, EL4_KEY), errCode)) {
1856         LOGE("user ce does not decrypt, skip");
1857         return 0;
1858     }
1859 
1860     auto iter = userPinProtect.find(user);
1861     if (iter == userPinProtect.end() || iter->second == false) {
1862         if (!IamClient::GetInstance().HasPinProtect(user)) {
1863             LOGI("Has no pin protect, saveLockScreenStatus is %{public}d", saveLockScreenStatus[user]);
1864             return 0;
1865         }
1866         userPinProtect.erase(user);
1867         userPinProtect.insert(std::make_pair(user, true));
1868         LOGI("User is %{public}u ,Lock screen, SaveLockScreenStatus is %{public}d", user, saveLockScreenStatus[user]);
1869     }
1870     iter = saveLockScreenStatus.find(user);
1871     if (iter == saveLockScreenStatus.end()) {
1872         saveLockScreenStatus.insert(std::make_pair(user, false));
1873         LOGI("User is %{public}u ,Insert LockScreenStatus, SaveLockScreenStatus is %{public}d", user,
1874              saveLockScreenStatus[user]);
1875     }
1876     if (!KeyCtrlHasFscryptSyspara() || !IsEncryption()) {
1877         saveLockScreenStatus[user] = false;
1878         LOGI("KeyCtrlHasFscryptSyspara is false, saveLockScreenStatus is %{public}d",
1879             saveLockScreenStatus[user]);
1880         return 0;
1881     }
1882     auto el5Key = GetUserElKey(user, EL5_KEY);
1883     saveESecretStatus[user] = true;
1884     if (el5Key != nullptr && el5Key->LockUece(saveESecretStatus[user]) != E_OK) {
1885         LOGE("lock user %{public}u el5 key failed !", user);
1886     }
1887     auto el4Key = GetUserElKey(user, EL4_KEY);
1888     if (el4Key == nullptr) {
1889         LOGE("Have not found user %{public}u el3 or el4", user);
1890         StorageRadar::ReportUpdateUserAuth("LockUserScreen::GetUserElKey", user, E_NON_EXIST, "EL4", "not found key");
1891         return E_NON_EXIST;
1892     }
1893     std::shared_ptr<DelayHandler> userDelayHandler;
1894     if (GetUserDelayHandler(user, userDelayHandler)) {
1895         userDelayHandler->StartDelayTask(el4Key);
1896     }
1897 
1898     saveLockScreenStatus[user] = false;
1899     LOGI("LockUserScreen user %{public}u el3 and el4 success, saveLockScreenStatus is %{public}d",
1900         user, saveLockScreenStatus[user]);
1901     return 0;
1902 }
1903 
SetDirectoryElPolicy(unsigned int user,KeyType type,const std::vector<FileList> & vec)1904 int KeyManager::SetDirectoryElPolicy(unsigned int user, KeyType type, const std::vector<FileList> &vec)
1905 {
1906     LOGI("start");
1907     if (!KeyCtrlHasFscryptSyspara() || !IsEncryption()) {
1908         LOGW("FscryptSyspara has not or encryption not enabled");
1909         return 0;
1910     }
1911     std::string keyPath;
1912     std::string eceSeceKeyPath;
1913     std::lock_guard<std::mutex> lock(keyMutex_);
1914     if (type == EL1_KEY) {
1915         int ret = getElxKeyPath(user, EL1_KEY, keyPath);
1916         if (ret != E_OK) {
1917             return ret;
1918         }
1919     } else if (type == EL2_KEY || type == EL3_KEY || type == EL4_KEY || type == EL5_KEY) {
1920         int ret = getElxKeyPath(user, EL2_KEY, keyPath);
1921         if (ret != E_OK) {
1922             return ret;
1923         }
1924     } else {
1925         LOGE("Not specify el flags, no need to crypt");
1926         return 0;
1927     }
1928     if (getElxKeyPath(user, type, eceSeceKeyPath) != 0) {
1929         LOGE("method getEceSeceKeyPath fail");
1930         return -ENOENT;
1931     }
1932     for (auto item : vec) {
1933         int ret = LoadAndSetPolicy(keyPath.c_str(), item.path.c_str());
1934         if (ret != 0) {
1935             LOGE("Set directory el policy error, ret: %{public}d, path:%{public}s", ret, item.path.c_str());
1936             return E_LOAD_AND_SET_POLICY_ERR;
1937         }
1938     }
1939     if (type == EL3_KEY || type == EL4_KEY) {
1940         for (auto item : vec) {
1941             if (LoadAndSetEceAndSecePolicy(eceSeceKeyPath.c_str(), item.path.c_str(), static_cast<int>(type)) != 0) {
1942                 LOGE("Set directory el policy error!");
1943                 return E_LOAD_AND_SET_ECE_POLICY_ERR;
1944             }
1945         }
1946     }
1947     LOGW("Set user %{public}u el policy success", user);
1948     return 0;
1949 }
1950 
getElxKeyPath(unsigned int user,KeyType type,std::string & elxKeyPath)1951 int KeyManager::getElxKeyPath(unsigned int user, KeyType type, std::string &elxKeyPath)
1952 {
1953     std::string natoPath = GetNatoNeedRestorePath(user, type);
1954     std::error_code errCode;
1955     if (std::filesystem::exists(natoPath, errCode)) {
1956         LOGW("type=%{public}d NATO path is exist.", type);
1957         elxKeyPath = natoPath;
1958         return E_OK;
1959     }
1960     if (!HasElkey(user, type) && type != EL5_KEY) {
1961         return -ENOENT;
1962     }
1963     if (type >= EL1_KEY && type <= EL4_KEY) {
1964         elxKeyPath = userElKeys_[user][type]->GetDir();
1965     }
1966     return E_OK;
1967 }
1968 
UpdateCeEceSeceKeyContext(uint32_t userId,KeyType type)1969 int KeyManager::UpdateCeEceSeceKeyContext(uint32_t userId, KeyType type)
1970 {
1971     LOGI("start");
1972     if (!KeyCtrlHasFscryptSyspara() || !IsEncryption()) {
1973         LOGW("FscryptSyspara has not or encryption not enabled");
1974         return 0;
1975     }
1976     std::lock_guard<std::mutex> lock(keyMutex_);
1977     if (HasElkey(userId, type) == false) {
1978         return E_PARAMS_INVALID;
1979     }
1980     std::shared_ptr<BaseKey> elKey = GetUserElKey(userId, type);
1981     if (elKey == nullptr) {
1982         LOGE("Have not found user %{public}u, type el%{public}u", userId, type);
1983         return -ENOENT;
1984     }
1985     auto ret = elKey->UpdateKey();
1986     if (ret != E_OK) {
1987         LOGE("Basekey update newest context failed");
1988         return E_ELX_KEY_UPDATE_ERROR;
1989     }
1990     return 0;
1991 }
1992 
UpdateKeyContext(uint32_t userId,bool needRemoveTmpKey)1993 int KeyManager::UpdateKeyContext(uint32_t userId, bool needRemoveTmpKey)
1994 {
1995     LOGI("UpdateKeyContext enter");
1996     int ret = UpdateCeEceSeceKeyContext(userId, EL2_KEY);
1997     if (ret != 0) {
1998         LOGE("Basekey update EL2 newest context failed");
1999         StorageRadar::ReportUpdateUserAuth("UpdateKeyContext::UpdateCeEceSeceKeyContext", userId, ret, "EL2", "");
2000         return ret;
2001     }
2002     ret = UpdateCeEceSeceKeyContext(userId, EL3_KEY);
2003     if (ret != 0) {
2004         LOGE("Basekey update EL3 newest context failed");
2005         StorageRadar::ReportUpdateUserAuth("UpdateKeyContext::UpdateCeEceSeceKeyContext", userId, ret, "EL3", "");
2006         return ret;
2007     }
2008     ret = UpdateCeEceSeceKeyContext(userId, EL4_KEY);
2009     if (ret != 0) {
2010         LOGE("Basekey update EL4 newest context failed");
2011         StorageRadar::ReportUpdateUserAuth("UpdateKeyContext::UpdateCeEceSeceKeyContext", userId, ret, "EL4", "");
2012         return ret;
2013     }
2014     if (IsUeceSupport()) {
2015         ret = UpdateClassEBackUp(userId);
2016         if (ret != 0) {
2017             LOGE("Inform FBE do update class E backup failed, ret=%{public}d", ret);
2018             return ret;
2019         }
2020         if (saveESecretStatus[userId]) {
2021             ret = UpdateCeEceSeceKeyContext(userId, EL5_KEY);
2022         }
2023     }
2024     if (ret != 0 && ((userId < START_APP_CLONE_USER_ID || userId > MAX_APP_CLONE_USER_ID))) {
2025         LOGE("Basekey update EL5 newest context failed");
2026         StorageRadar::ReportUpdateUserAuth("UpdateKeyContext::UpdateCeEceSeceKeyContext", userId, ret, "EL5", "");
2027         return ret;
2028     }
2029     LOGI("Basekey update key context success");
2030     return 0;
2031 }
2032 
IsUeceSupport()2033 bool KeyManager::IsUeceSupport()
2034 {
2035     FILE *f = fopen(UECE_PATH, "r+");
2036     if (f == nullptr) {
2037         if (errno == ENOENT) {
2038             LOGE("uece does not support !");
2039         }
2040         LOGE("open uece failed, errno : %{public}d", errno);
2041         return false;
2042     }
2043     int fd = fileno(f);
2044     if (fd < 0) {
2045         if (errno == ENOENT) {
2046             LOGE("uece does not support !");
2047         }
2048         LOGE("open uece failed, errno : %{public}d", errno);
2049         (void)fclose(f);
2050         return false;
2051     }
2052     (void)fclose(f);
2053     LOGI("uece is support.");
2054     return true;
2055 }
2056 
UpdateClassEBackUp(uint32_t userId)2057 int KeyManager::UpdateClassEBackUp(uint32_t userId)
2058 {
2059     auto startTime = StorageService::StorageRadar::RecordCurrentTime();
2060     auto el5Key = GetUserElKey(userId, EL5_KEY);
2061     if (el5Key == nullptr) {
2062         LOGE("Have not found user %{public}u el5 Key", userId);
2063         return E_NON_EXIST;
2064     }
2065     auto ret = el5Key->UpdateClassEBackUp(userId);
2066     auto delay = StorageService::StorageRadar::ReportDuration("FBE:UpdateClassEBackUp",
2067         startTime, StorageService::DEFAULT_DELAY_TIME_THRESH, userId);
2068     LOGI("SD_DURATION: FBEX: UPDATE CLASS E BACKUP: user=%{public}u, delay=%{public}s", userId, delay.c_str());
2069     return ret;
2070 }
2071 
IsUeceSupportWithErrno()2072 int KeyManager::IsUeceSupportWithErrno()
2073 {
2074     int fd = open(UECE_PATH, O_RDWR);
2075     if (fd < 0) {
2076         if (errno == ENOENT) {
2077             LOGE("uece does not support !");
2078             return ENOENT;
2079         }
2080         LOGE("open uece failed, errno : %{public}d", errno);
2081         return errno;
2082     }
2083     close(fd);
2084     LOGI("uece is support.");
2085     return E_OK;
2086 }
2087 
UpgradeKeys(const std::vector<FileList> & dirInfo)2088 int KeyManager::UpgradeKeys(const std::vector<FileList> &dirInfo)
2089 {
2090     for (const auto &it : dirInfo) {
2091         std::shared_ptr<BaseKey> elKey = GetBaseKey(it.path);
2092         if (elKey == nullptr) {
2093             LOGE("Basekey memory failed");
2094             continue;
2095         }
2096         elKey->UpgradeKeys();
2097     }
2098     return 0;
2099 }
2100 
GetFileEncryptStatus(uint32_t userId,bool & isEncrypted,bool needCheckDirMount)2101 int KeyManager::GetFileEncryptStatus(uint32_t userId, bool &isEncrypted, bool needCheckDirMount)
2102 {
2103     LOGI("Begin check encrypted status, userId is %{public}d, needCheckDirMount is %{public}d",
2104          userId, needCheckDirMount);
2105     isEncrypted = true;
2106     const char rootPath[] = "/data/app/el2/";
2107     const char basePath[] = "/base";
2108     size_t allPathSize = strlen(rootPath) + strlen(basePath) + 1 + USER_ID_SIZE_VALUE;
2109     char *path = reinterpret_cast<char *>(malloc(sizeof(char) * (allPathSize)));
2110     if (path == nullptr) {
2111         LOGE("Failed to malloce path.");
2112         return E_MEMORY_OPERATION_ERR;
2113     }
2114     int len = sprintf_s(path, allPathSize, "%s%u%s", rootPath, userId, basePath);
2115     if (len <= 0 || (size_t)len >= allPathSize) {
2116         free(path);
2117         LOGE("Failed to get base path");
2118         return E_PARAMS_INVALID;
2119     }
2120     if (access(path, F_OK) != 0) {
2121         free(path);
2122         LOGE("Can not access el2 dir, user %{public}d el2 is encrypted.", userId);
2123         return E_OK;
2124     }
2125     std::string el2Path(path);
2126     if (!SaveStringToFile(el2Path + EL2_ENCRYPT_TMP_FILE, " ")) {
2127         free(path);
2128         LOGE("Can not save el2 file, user %{public}d el2 is encrypted.", userId);
2129         return E_OK;
2130     }
2131     free(path);
2132     int ret = remove((el2Path + EL2_ENCRYPT_TMP_FILE).c_str());
2133     LOGE("remove ret = %{public}d", ret);
2134     if (needCheckDirMount && !MountManager::GetInstance().CheckMountFileByUser(userId)) {
2135         LOGI("The virturalDir is not exists.");
2136         return E_OK;
2137     }
2138     isEncrypted = false;
2139     LOGI("This is decrypted status");
2140     return E_OK;
2141 }
2142 
IsUserCeDecrypt(uint32_t userId)2143 bool KeyManager::IsUserCeDecrypt(uint32_t userId)
2144 {
2145     bool isCeEncrypt = false;
2146     int ret = GetFileEncryptStatus(userId, isCeEncrypt);
2147     if (ret != E_OK || isCeEncrypt) {
2148         LOGE("User %{public}d el2 has not decrypt.", userId);
2149         return false;
2150     }
2151     LOGI("User %{public}d el2 decrypted.", userId);
2152     return true;
2153 }
2154 
CheckUserPinProtect(unsigned int userId,const std::vector<uint8_t> & token,const std::vector<uint8_t> & secret)2155 int KeyManager::CheckUserPinProtect(unsigned int userId,
2156                                     const std::vector<uint8_t> &token,
2157                                     const std::vector<uint8_t> &secret)
2158 {
2159     LOGI("enter CheckUserPinProtect");
2160     std::error_code errCode;
2161     std::string restorePath = std::string(USER_EL2_DIR) + "/" + std::to_string(userId) + RESTORE_DIR;
2162     if (!std::filesystem::exists(restorePath, errCode)) {
2163         LOGI("Do not check pin code.");
2164         return E_OK;
2165     }
2166     // judge if device has PIN protect
2167     if ((token.empty() && secret.empty()) && IamClient::GetInstance().HasPinProtect(userId)) {
2168         LOGE("User %{public}d has pin code protect.", userId);
2169         return E_ERR;
2170     }
2171     return E_OK;
2172 }
2173 
TryToFixUserCeEceSeceKey(unsigned int userId,KeyType keyType,const std::vector<uint8_t> & token,const std::vector<uint8_t> & secret)2174 int KeyManager::TryToFixUserCeEceSeceKey(unsigned int userId,
2175                                          KeyType keyType,
2176                                          const std::vector<uint8_t> &token,
2177                                          const std::vector<uint8_t> &secret)
2178 {
2179     LOGI("enter TryToFixUserCeEceSeceKey");
2180     keyMutex_.unlock();
2181     if (!IamClient::GetInstance().HasPinProtect(userId)) {
2182         LOGE("User %{public}d has no pin code protect.", userId);
2183         return E_OK;
2184     }
2185 
2186     uint64_t secureUid = { 0 };
2187     if (!secret.empty() && !token.empty()) {
2188         IamClient::GetInstance().GetSecureUid(userId, secureUid);
2189         LOGE("Pin code is exist, get secure uid.");
2190     }
2191     UserAuth auth = { .token = token, .secret = secret, .secureUid = secureUid };
2192     UserTokenSecret userTokenSecret = { .token = token, .oldSecret = {}, .newSecret = secret, .secureUid = secureUid };
2193 
2194     int ret = E_OK;
2195 #ifdef USER_CRYPTO_MIGRATE_KEY
2196     ret = UpdateCeEceSeceUserAuth(userId, userTokenSecret, keyType, false);
2197 #else
2198     ret = UpdateCeEceSeceUserAuth(userId, userTokenSecret, keyType);
2199 #endif
2200     if (ret != E_OK) {
2201         LOGE("try to fix elx key failed !");
2202         return ret;
2203     }
2204     ret = UpdateCeEceSeceKeyContext(userId, keyType);
2205     if (ret != E_OK) {
2206         LOGE("try to fix elx key context failed !");
2207         StorageRadar::ReportUpdateUserAuth("TryToFixUserCeEceSeceKey::UpdateCeEceSeceKeyContext",
2208             userId, ret, std::to_string(keyType), "");
2209         return ret;
2210     }
2211     return E_OK;
2212 }
2213 
TryToFixUeceKey(unsigned int userId,const std::vector<uint8_t> & token,const std::vector<uint8_t> & secret)2214 int KeyManager::TryToFixUeceKey(unsigned int userId,
2215                                 const std::vector<uint8_t> &token,
2216                                 const std::vector<uint8_t> &secret)
2217 {
2218     LOGI("enter TryToFixUeceKey");
2219     keyMutex_.unlock();
2220     if (!IamClient::GetInstance().HasPinProtect(userId)) {
2221         LOGE("User %{public}d has no pin code protect.", userId);
2222         return E_OK;
2223     }
2224 
2225     uint64_t secureUid = { 0 };
2226     if (!secret.empty() && !token.empty()) {
2227         IamClient::GetInstance().GetSecureUid(userId, secureUid);
2228         LOGE("Pin code is exist, get secure uid.");
2229     }
2230     UserAuth auth = { .token=token, .secret=secret, .secureUid = secureUid };
2231     UserTokenSecret tokenSecret = { .token = token, .oldSecret = { }, .newSecret = secret, .secureUid = secureUid};
2232 
2233     int ret = UpdateESecret(userId, tokenSecret);
2234     if (ret != E_OK) {
2235         LOGE("try to fix elx key failed !");
2236         return ret;
2237     }
2238     ret = UpdateCeEceSeceKeyContext(userId, EL5_KEY);
2239     if (ret != E_OK) {
2240         LOGE("try to fix elx key context failed !");
2241         StorageRadar::ReportUpdateUserAuth("TryToFixUeceKey::UpdateCeEceSeceKeyContext", userId, ret, "EL5", "");
2242         return ret;
2243     }
2244     return E_OK;
2245 }
2246 
2247 #ifdef USER_CRYPTO_MIGRATE_KEY
RestoreUserKey(uint32_t userId,KeyType type)2248 int KeyManager::RestoreUserKey(uint32_t userId, KeyType type)
2249 {
2250     LOGI("start, user is %{public}u , type is %{public}d", userId, type);
2251     std::string dir = GetKeyDirByUserAndType(userId, type);
2252     if (dir == "") {
2253         LOGE("type is invalid, %{public}u", type);
2254         return E_PARAMS_INVALID;
2255     }
2256 
2257     if (!IsDir(dir)) {
2258         LOGE("dir not exist");
2259         return -ENOENT;
2260     }
2261     int32_t ret = RestoreUserKey(userId, dir, NULL_KEY_AUTH, type);
2262     if (ret == 0 && type != EL1_KEY) {
2263         saveLockScreenStatus[userId] = true;
2264         LOGI("User is %{public}u , saveLockScreenStatus is %{public}d", userId, saveLockScreenStatus[userId]);
2265     }
2266     return ret;
2267 }
2268 #endif
2269 
2270 #ifdef EL5_FILEKEY_MANAGER
RegisterUeceActivationCallback(const sptr<StorageManager::IUeceActivationCallback> & ueceCallback)2271 int KeyManager::RegisterUeceActivationCallback(const sptr<StorageManager::IUeceActivationCallback> &ueceCallback)
2272 {
2273     std::lock_guard<std::mutex> lock(ueceMutex_);
2274     if (ueceCallback == nullptr) {
2275         LOGE("callback is nullptr");
2276         return E_PARAMS_INVALID;
2277     }
2278     if (ueceCallback_ != nullptr) {
2279         LOGI("El5FileMgr already registered callback, renew");
2280         ueceCallback_ = ueceCallback;
2281         return E_OK;
2282     }
2283     ueceCallback_ = ueceCallback;
2284     LOGI("El5FileMgr register callback");
2285     return E_OK;
2286 }
2287 
UnregisterUeceActivationCallback()2288 int KeyManager::UnregisterUeceActivationCallback()
2289 {
2290     std::lock_guard<std::mutex> lock(ueceMutex_);
2291     if (ueceCallback_ == nullptr) {
2292         LOGI("El5FileMgr already unregistered callback");
2293         return E_OK;
2294     }
2295     ueceCallback_ = nullptr;
2296     LOGI("Unregister callback");
2297     return E_OK;
2298 }
2299 #endif
2300 
NotifyUeceActivation(uint32_t userId,int32_t resultCode,bool needGetAllAppKey)2301 int KeyManager::NotifyUeceActivation(uint32_t userId, int32_t resultCode, bool needGetAllAppKey)
2302 {
2303 #ifdef EL5_FILEKEY_MANAGER
2304     if (ueceCallback_ == nullptr) {
2305         LOGE("el5 activation callback invalid");
2306         return E_OK;
2307     }
2308     std::promise<int32_t> promise;
2309     std::future<int32_t> future = promise.get_future();
2310     auto startTime = StorageService::StorageRadar::RecordCurrentTime();
2311     std::thread callbackThread ([this, userId, resultCode, needGetAllAppKey, p = std::move(promise)]() mutable {
2312         int32_t retValue = E_OK;
2313         LOGI("ready for callback, El5 activation result = %{public}d, userId=%{public}u, needGetAllAppKey=%{public}d",
2314             resultCode, userId, needGetAllAppKey);
2315         ueceCallback_->OnEl5Activation(resultCode, userId, needGetAllAppKey, retValue);
2316         p.set_value(retValue);
2317     });
2318 
2319     if (future.wait_for(std::chrono::milliseconds(WAIT_THREAD_TIMEOUT_MS)) == std::future_status::timeout) {
2320         LOGE("el5 activation callback timed out");
2321         callbackThread.detach();
2322         return E_OK;
2323     }
2324 
2325     auto delay = StorageService::StorageRadar::ReportDuration("UNLOCK USER APP KEYS",
2326         startTime, StorageService::DELAY_TIME_THRESH_HIGH, userId);
2327     LOGI("SD_DURATION: UNLOCK USER APP KEYS CB: delay time = %{public}s, isAllAppKey=%{public}d",
2328         delay.c_str(), needGetAllAppKey);
2329 
2330     int32_t ret = future.get();
2331     LOGI("Unlock App Keys ret= %{public}d", ret);
2332     callbackThread.join();
2333     if (resultCode != E_OK || ret == E_PARAMS_INVALID) {
2334         return E_OK;
2335     }
2336     return ret;
2337 # else
2338     LOGD("EL5_FILEKEY_MANAGER is not supported");
2339     return E_OK;
2340 #endif
2341 }
2342 } // namespace StorageDaemon
2343 } // namespace OHOS
2344