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