• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "key_manager.h"
17 
18 #include <string>
19 
20 #include "directory_ex.h"
21 #include "file_ex.h"
22 #include "fscrypt_key_v1.h"
23 #include "fscrypt_key_v2.h"
24 #include "libfscrypt/fscrypt_control.h"
25 #include "libfscrypt/key_control.h"
26 #include "parameter.h"
27 #include "storage_service_constant.h"
28 #include "storage_service_errno.h"
29 #include "storage_service_log.h"
30 
31 namespace OHOS {
32 namespace StorageDaemon {
33 const UserAuth NULL_KEY_AUTH = {};
34 const std::string FSCRYPT_USER_EL1_PUBLIC = std::string() + "/data/service/el1/public";
35 const std::string SERVICE_STORAGE_DAEMON_DIR = FSCRYPT_USER_EL1_PUBLIC + "/storage_daemon";
36 const std::string FSCRYPT_EL_DIR = SERVICE_STORAGE_DAEMON_DIR + "/sd";
37 const std::string USER_EL1_DIR = FSCRYPT_EL_DIR + "/el1";
38 const std::string USER_EL2_DIR = FSCRYPT_EL_DIR + "/el2";
39 
GetBaseKey(const std::string & dir)40 std::shared_ptr<BaseKey> KeyManager::GetBaseKey(const std::string& dir)
41 {
42     uint8_t versionFromPolicy = GetFscryptVersionFromPolicy();
43     uint8_t kernelSupportVersion = KeyCtrlGetFscryptVersion(MNT_DATA.c_str());
44     if (kernelSupportVersion == FSCRYPT_INVALID) {
45         LOGE("kernel not support fscrypt");
46         return nullptr;
47     }
48     if ((versionFromPolicy == kernelSupportVersion) && (kernelSupportVersion == FSCRYPT_V2)) {
49         return std::dynamic_pointer_cast<BaseKey>(std::make_shared<FscryptKeyV2>(dir));
50     }
51     if (versionFromPolicy != kernelSupportVersion) {
52         LOGE("version from policy %{public}u not same as version from kernel %{public}u", versionFromPolicy,
53              kernelSupportVersion);
54     }
55     return std::dynamic_pointer_cast<BaseKey>(std::make_shared<FscryptKeyV1>(dir));
56 }
57 
GenerateAndInstallDeviceKey(const std::string & dir)58 int KeyManager::GenerateAndInstallDeviceKey(const std::string &dir)
59 {
60     LOGI("enter");
61     globalEl1Key_ = GetBaseKey(dir);
62     if (globalEl1Key_ == nullptr) {
63         return -EOPNOTSUPP;
64     }
65 
66     if (globalEl1Key_->InitKey() == false) {
67         globalEl1Key_ = nullptr;
68         LOGE("global security key init failed");
69         return -EFAULT;
70     }
71 
72     if (globalEl1Key_->StoreKey(NULL_KEY_AUTH) == false) {
73         globalEl1Key_->ClearKey();
74         globalEl1Key_ = nullptr;
75         LOGE("global security key store failed");
76         return -EFAULT;
77     }
78 
79     if (globalEl1Key_->ActiveKey(FIRST_CREATE_KEY) == false) {
80         globalEl1Key_->ClearKey();
81         globalEl1Key_ = nullptr;
82         LOGE("global security key active failed");
83         return -EFAULT;
84     }
85 
86     (void)globalEl1Key_->UpdateKey();
87     hasGlobalDeviceKey_ = true;
88     LOGI("key create success");
89     return 0;
90 }
91 
RestoreDeviceKey(const std::string & dir)92 int KeyManager::RestoreDeviceKey(const std::string &dir)
93 {
94     LOGI("enter");
95     if (globalEl1Key_ != nullptr) {
96         LOGD("device key has existed");
97         return 0;
98     }
99 
100     globalEl1Key_ = GetBaseKey(dir);
101     if (globalEl1Key_ == nullptr) {
102         return -EOPNOTSUPP;
103     }
104 
105     if (globalEl1Key_->InitKey() == false) {
106         globalEl1Key_ = nullptr;
107         LOGE("global security key init failed");
108         return -EFAULT;
109     }
110 
111     if (globalEl1Key_->RestoreKey(NULL_KEY_AUTH) == false) {
112         globalEl1Key_ = nullptr;
113         LOGE("global security key restore failed");
114         return -EFAULT;
115     }
116 
117     if (globalEl1Key_->ActiveKey(RETRIEVE_KEY) == false) {
118         globalEl1Key_ = nullptr;
119         LOGE("global security key active failed");
120         return -EFAULT;
121     }
122     hasGlobalDeviceKey_ = true;
123     LOGI("key restore success");
124 
125     return 0;
126 }
127 
InitGlobalDeviceKey(void)128 int KeyManager::InitGlobalDeviceKey(void)
129 {
130     LOGI("enter");
131     int ret = InitFscryptPolicy();
132     if (ret < 0) {
133         LOGE("fscrypt init failed, fscrypt will not be enabled");
134         return ret;
135     }
136 
137     std::lock_guard<std::mutex> lock(keyMutex_);
138     if (hasGlobalDeviceKey_ || globalEl1Key_ != nullptr) {
139         LOGD("glabal device el1 have existed");
140         return 0;
141     }
142 
143     ret = MkDir(STORAGE_DAEMON_DIR, 0700); // para.0700: root only
144     if (ret && errno != EEXIST) {
145         LOGE("create storage daemon dir error");
146         return ret;
147     }
148     ret = MkDir(DEVICE_EL1_DIR, 0700);
149     if (ret) {
150         if (errno != EEXIST) {
151             LOGE("make device el1 dir error");
152             return ret;
153         }
154         UpgradeKeys({{0, DEVICE_EL1_DIR}});
155         return RestoreDeviceKey(DEVICE_EL1_DIR);
156     }
157 
158     return GenerateAndInstallDeviceKey(DEVICE_EL1_DIR);
159 }
160 
GenerateAndInstallUserKey(uint32_t userId,const std::string & dir,const UserAuth & auth,KeyType type)161 int KeyManager::GenerateAndInstallUserKey(uint32_t userId, const std::string &dir, const UserAuth &auth, KeyType type)
162 {
163     LOGI("enter");
164     if (HasElkey(userId, type)) {
165         LOGD("The user %{public}u el %{public}u have existed", userId, type);
166         return 0;
167     }
168 
169     auto elKey = GetBaseKey(dir);
170     if (elKey == nullptr) {
171         return -EOPNOTSUPP;
172     }
173 
174     if (elKey->InitKey() == false) {
175         LOGE("user security key init failed");
176         return -EFAULT;
177     }
178 
179     if (elKey->StoreKey(auth) == false) {
180         elKey->ClearKey();
181         LOGE("user security key store failed");
182         return -EFAULT;
183     }
184 
185     if (elKey->ActiveKey(FIRST_CREATE_KEY) == false) {
186         elKey->ClearKey();
187         LOGE("user security key active failed");
188         return -EFAULT;
189     }
190 
191     (void)elKey->UpdateKey();
192     if (type == EL1_KEY) {
193         userEl1Key_[userId] = elKey;
194     } else if (type == EL2_KEY) {
195         userEl2Key_[userId] = elKey;
196     }
197     LOGI("key create success");
198 
199     return 0;
200 }
201 
RestoreUserKey(uint32_t userId,const std::string & dir,const UserAuth & auth,KeyType type)202 int KeyManager::RestoreUserKey(uint32_t userId, const std::string &dir, const UserAuth &auth, KeyType type)
203 {
204     LOGI("enter");
205     if (HasElkey(userId, type)) {
206         LOGD("The user %{public}u el %{public}u have existed", userId, type);
207         return 0;
208     }
209 
210     auto elKey = GetBaseKey(dir);
211     if (elKey == nullptr) {
212         return -EOPNOTSUPP;
213     }
214 
215     if (elKey->InitKey() == false) {
216         LOGE("user security key init failed");
217         return -EFAULT;
218     }
219 
220     if (elKey->RestoreKey(auth) == false) {
221         LOGE("user security key restore failed");
222         return -EFAULT;
223     }
224 
225     if (elKey->ActiveKey(RETRIEVE_KEY) == false) {
226         LOGE("user security key active failed");
227         return -EFAULT;
228     }
229 
230     if (type == EL1_KEY) {
231         userEl1Key_[userId] = elKey;
232     } else if (type == EL2_KEY) {
233         userEl2Key_[userId] = elKey;
234     }
235     LOGI("key restore success");
236 
237     return 0;
238 }
239 
HasElkey(uint32_t userId,KeyType type)240 bool KeyManager::HasElkey(uint32_t userId, KeyType type)
241 {
242     LOGI("enter");
243     if (type == EL1_KEY) {
244         if (userEl1Key_.find(userId) != userEl1Key_.end()) {
245             LOGD("user el1 key has existed");
246             return true;
247         }
248     } else if (type == EL2_KEY) {
249         if (userEl2Key_.find(userId) != userEl2Key_.end()) {
250             LOGD("user el2 key has existed");
251             return true;
252         }
253     } else {
254         LOGE("key type error");
255     }
256 
257     return false;
258 }
259 
LoadAllUsersEl1Key(void)260 int KeyManager::LoadAllUsersEl1Key(void)
261 {
262     LOGI("enter");
263     std::vector<FileList> dirInfo;
264     ReadDigitDir(USER_EL2_DIR, dirInfo);
265     UpgradeKeys(dirInfo);
266     dirInfo.clear();
267     ReadDigitDir(USER_EL1_DIR, dirInfo);
268     UpgradeKeys(dirInfo);
269     for (auto item : dirInfo) {
270         if (RestoreUserKey(item.userId, item.path, NULL_KEY_AUTH, EL1_KEY) != 0) {
271             LOGE("user %{public}u el1 key restore error", item.userId);
272         }
273     }
274 
275     return 0;
276 }
277 
InitUserElkeyStorageDir(void)278 int KeyManager::InitUserElkeyStorageDir(void)
279 {
280     int ret = MkDir(SERVICE_STORAGE_DAEMON_DIR, 0700);
281     if (ret && errno != EEXIST) {
282         LOGE("make service storage daemon dir error");
283         return ret;
284     }
285 
286     ret = MkDir(FSCRYPT_EL_DIR, 0700);
287     if (ret && errno != EEXIST) {
288         LOGE("make service storage daemon dir error");
289         return ret;
290     }
291 
292     ret = MkDir(USER_EL1_DIR, 0700);
293     if (ret && errno != EEXIST) {
294         LOGE("make el1 storage dir error");
295         return ret;
296     }
297     ret = MkDir(USER_EL2_DIR, 0700);
298     if (ret && errno != EEXIST) {
299         LOGE("make el2 storage dir error");
300         return ret;
301     }
302 
303     return 0;
304 }
305 
InitGlobalUserKeys(void)306 int KeyManager::InitGlobalUserKeys(void)
307 {
308     LOGI("enter");
309     if (!KeyCtrlHasFscryptSyspara()) {
310         return 0;
311     }
312     std::lock_guard<std::mutex> lock(keyMutex_);
313     int ret = InitUserElkeyStorageDir();
314     if (ret) {
315         LOGE("Init user el storage dir failed");
316         return ret;
317     }
318 
319     std::string globalUserEl1Path = USER_EL1_DIR + "/" + std::to_string(GLOBAL_USER_ID);
320     if (IsDir(globalUserEl1Path)) {
321         ret = RestoreUserKey(GLOBAL_USER_ID, globalUserEl1Path, NULL_KEY_AUTH, EL1_KEY);
322         if (ret != 0) {
323             LOGE("Restore el1 failed");
324             return ret;
325         }
326     } else {
327         ret = GenerateAndInstallUserKey(GLOBAL_USER_ID, globalUserEl1Path, NULL_KEY_AUTH, EL1_KEY);
328         if (ret != 0) {
329             LOGE("Generate el1 failed");
330             return ret;
331         }
332     }
333 
334     ret = LoadAllUsersEl1Key();
335     if (ret) {
336         LOGE("Load all users el1 failed");
337         return ret;
338     }
339     LOGI("Init global user key success");
340 
341     return 0;
342 }
343 
GenerateUserKeys(unsigned int user,uint32_t flags)344 int KeyManager::GenerateUserKeys(unsigned int user, uint32_t flags)
345 {
346     LOGI("start, user:%{public}u", user);
347     if (!KeyCtrlHasFscryptSyspara()) {
348         return 0;
349     }
350 
351     std::lock_guard<std::mutex> lock(keyMutex_);
352     if ((!IsDir(USER_EL1_DIR)) || (!IsDir(USER_EL2_DIR))) {
353         LOGD("El storage dir is not existed");
354         return -ENOENT;
355     }
356 
357     std::string el1Path = USER_EL1_DIR + "/" + std::to_string(user);
358     std::string el2Path = USER_EL2_DIR + "/" + std::to_string(user);
359     if (IsDir(el1Path) || IsDir(el2Path)) {
360             LOGE("user %{public}d el key have existed, create error", user);
361             return -EEXIST;
362     }
363     int ret = GenerateAndInstallUserKey(user, el1Path, NULL_KEY_AUTH, EL1_KEY);
364     if (ret) {
365         LOGE("user el1 create error");
366         return ret;
367     }
368 
369     ret = GenerateAndInstallUserKey(user, el2Path, NULL_KEY_AUTH, EL2_KEY);
370     if (ret) {
371         DoDeleteUserKeys(user);
372         LOGE("user el2 create error");
373         return ret;
374     }
375     LOGI("Create user el success");
376 
377     return 0;
378 }
379 
DoDeleteUserKeys(unsigned int user)380 int KeyManager::DoDeleteUserKeys(unsigned int user)
381 {
382     int ret = 0;
383     std::string elPath;
384     auto it = userEl1Key_.find(user);
385     if (it != userEl1Key_.end()) {
386         auto elKey = it->second;
387         elKey->ClearKey();
388         userEl1Key_.erase(user);
389     } else {
390         elPath = USER_EL1_DIR + "/" + std::to_string(user);
391         std::shared_ptr<BaseKey> elKey = GetBaseKey(elPath);
392         if (elKey == nullptr) {
393             LOGE("Malloc el1 Basekey memory failed");
394             return -ENOMEM;
395         }
396         if (!elKey->ClearKey()) {
397             LOGE("Delete el1 key failed");
398             ret = -EFAULT;
399         }
400     }
401 
402     it = userEl2Key_.find(user);
403     if (it != userEl2Key_.end()) {
404         auto elKey = it->second;
405         elKey->ClearKey();
406         userEl2Key_.erase(user);
407     } else {
408         elPath = USER_EL2_DIR + "/" + std::to_string(user);
409         std::shared_ptr<BaseKey> elKey = GetBaseKey(elPath);
410         if (elKey == nullptr) {
411             LOGE("Malloc el2 Basekey memory failed");
412             return -ENOMEM;
413         }
414         if (!elKey->ClearKey()) {
415             LOGE("Delete el2 key failed");
416             ret = -EFAULT;
417         }
418     }
419 
420     return ret;
421 }
422 
DeleteUserKeys(unsigned int user)423 int KeyManager::DeleteUserKeys(unsigned int user)
424 {
425     LOGI("start, user:%{public}d", user);
426     if (!KeyCtrlHasFscryptSyspara()) {
427         return 0;
428     }
429 
430     std::lock_guard<std::mutex> lock(keyMutex_);
431     int ret = DoDeleteUserKeys(user);
432     LOGI("delete user key end");
433 
434     return ret;
435 }
436 
UpdateUserAuth(unsigned int user,uint64_t secureUid,const std::vector<uint8_t> & token,const std::vector<uint8_t> & oldSecret,const std::vector<uint8_t> & newSecret)437 int KeyManager::UpdateUserAuth(unsigned int user, uint64_t secureUid,
438                                const std::vector<uint8_t> &token,
439                                const std::vector<uint8_t> &oldSecret,
440                                const std::vector<uint8_t> &newSecret)
441 {
442     LOGI("start, user:%{public}d", user);
443     if (!KeyCtrlHasFscryptSyspara()) {
444         return 0;
445     }
446 
447     std::lock_guard<std::mutex> lock(keyMutex_);
448     if (userEl2Key_.find(user) == userEl2Key_.end()) {
449         LOGE("Have not found user %{public}u el2 key", user);
450         return -ENOENT;
451     }
452 
453     auto item = userEl2Key_[user];
454     UserAuth auth = {token, oldSecret, secureUid};
455     if ((item->RestoreKey(auth) == false) && (item->RestoreKey(NULL_KEY_AUTH) == false)) {
456         LOGE("Restore key error");
457         return -EFAULT;
458     }
459 
460     auth.secret = newSecret;
461     if (item->StoreKey(auth) == false) {
462         LOGE("Store key error");
463         return -EFAULT;
464     }
465     item->keyInfo_.key.Clear();
466 
467     return 0;
468 }
469 
ActiveUserKey(unsigned int user,const std::vector<uint8_t> & token,const std::vector<uint8_t> & secret)470 int KeyManager::ActiveUserKey(unsigned int user, const std::vector<uint8_t> &token,
471                               const std::vector<uint8_t> &secret)
472 {
473     LOGI("start");
474     if (!KeyCtrlHasFscryptSyspara()) {
475         return 0;
476     }
477 
478     std::lock_guard<std::mutex> lock(keyMutex_);
479     if (userEl2Key_.find(user) != userEl2Key_.end()) {
480         LOGE("The user %{public}u el2 have been actived", user);
481         return 0;
482     }
483     std::string keyDir = USER_EL2_DIR + "/" + std::to_string(user);
484     if (!IsDir(keyDir)) {
485         LOGE("Have not found user %{public}u el2", user);
486         return -ENOENT;
487     }
488 
489     std::shared_ptr<BaseKey> elKey = GetBaseKey(keyDir);
490     if (elKey == nullptr) {
491         LOGE("elKey failed");
492         return -EOPNOTSUPP;
493     }
494     if (elKey->InitKey() == false) {
495         LOGE("Init el failed");
496         return -EFAULT;
497     }
498     UserAuth auth = {token, secret};
499     if ((elKey->RestoreKey(auth) == false) && (elKey->RestoreKey(NULL_KEY_AUTH) == false)) {
500         LOGE("Restore el failed");
501         return -EFAULT;
502     }
503     if (elKey->ActiveKey(RETRIEVE_KEY) == false) {
504         LOGE("Active user %{public}u key failed", user);
505         return -EFAULT;
506     }
507 
508     userEl2Key_[user] = elKey;
509     LOGI("Active user %{public}u el2 success", user);
510 
511     return 0;
512 }
513 
InActiveUserKey(unsigned int user)514 int KeyManager::InActiveUserKey(unsigned int user)
515 {
516     LOGI("start");
517     if (!KeyCtrlHasFscryptSyspara()) {
518         return 0;
519     }
520 
521     std::lock_guard<std::mutex> lock(keyMutex_);
522     if (userEl2Key_.find(user) == userEl2Key_.end()) {
523         LOGE("Have not found user %{public}u el2", user);
524         return -ENOENT;
525     }
526     auto elKey = userEl2Key_[user];
527     if (elKey->InactiveKey(USER_LOGOUT) == false) {
528         LOGE("Clear user %{public}u key failed", user);
529         return -EFAULT;
530     }
531 
532     userEl2Key_.erase(user);
533     LOGI("Inactive user %{public}u el2 success", user);
534 
535     return 0;
536 }
537 
SetDirectoryElPolicy(unsigned int user,KeyType type,const std::vector<FileList> & vec)538 int KeyManager::SetDirectoryElPolicy(unsigned int user, KeyType type,
539                                      const std::vector<FileList> &vec)
540 {
541     LOGI("start");
542     if (!KeyCtrlHasFscryptSyspara()) {
543         return 0;
544     }
545 
546     std::string keyPath;
547     std::lock_guard<std::mutex> lock(keyMutex_);
548     if (type == EL1_KEY) {
549         if (userEl1Key_.find(user) == userEl1Key_.end()) {
550             LOGD("Have not found user %{public}u el1 key, not enable el1", user);
551             return -ENOENT;
552         }
553         keyPath = userEl1Key_[user]->GetDir();
554     } else if (type == EL2_KEY) {
555         if (userEl2Key_.find(user) == userEl2Key_.end()) {
556             LOGD("Have not found user %{public}u el2 key, not enable el2", user);
557             return -ENOENT;
558         }
559         keyPath = userEl2Key_[user]->GetDir();
560     } else {
561         LOGD("Not specify el flags, no need to crypt");
562         return 0;
563     }
564 
565     for (auto item : vec) {
566         if (LoadAndSetPolicy(keyPath.c_str(), item.path.c_str()) != 0) {
567             LOGE("Set directory el policy error!");
568             return -EFAULT;
569         }
570     }
571     LOGI("Set user %{public}u el policy success", user);
572 
573     return 0;
574 }
575 
UpdateKeyContext(uint32_t userId)576 int KeyManager::UpdateKeyContext(uint32_t userId)
577 {
578     LOGI("start");
579     if (!KeyCtrlHasFscryptSyspara()) {
580         return 0;
581     }
582 
583     std::lock_guard<std::mutex> lock(keyMutex_);
584     if (userEl2Key_.find(userId) == userEl2Key_.end()) {
585         LOGE("Have not found user %{public}u el2", userId);
586         return -ENOENT;
587     }
588     auto elKey = userEl2Key_[userId];
589     if (!elKey->UpdateKey()) {
590         LOGE("Basekey update newest context failed");
591         return -EFAULT;
592     }
593     LOGI("Basekey update key context success");
594 
595     return 0;
596 }
597 
UpgradeKeys(const std::vector<FileList> & dirInfo)598 int KeyManager::UpgradeKeys(const std::vector<FileList> &dirInfo)
599 {
600     for (const auto &it : dirInfo) {
601         std::shared_ptr<BaseKey> elKey = GetBaseKey(it.path);
602         if (elKey == nullptr) {
603             LOGE("elKel feiled");
604             continue;
605         }
606         elKey->UpgradeKeys();
607     }
608     return 0;
609 }
610 } // namespace StorageDaemon
611 } // namespace OHOS
612