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