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 "security_policy.h"
17
18 #include "logger.h"
19 #include "rdb_errno.h"
20 #include "security_label.h"
21
22 namespace OHOS {
23 namespace NativeRdb {
24 using namespace OHOS::Rdb;
25
SetFileSecurityLevel(const std::string & filePath,const std::string & securityLevel)26 int SecurityPolicy::SetFileSecurityLevel(const std::string &filePath, const std::string &securityLevel)
27 {
28 bool result = FileManagement::ModuleSecurityLabel::SecurityLabel::SetSecurityLabel(filePath, securityLevel);
29 LOG_INFO("Set database securityLabel:%{public}s, result:%{public}d.", securityLevel.c_str(), result);
30 return result ? E_OK : E_ERROR;
31 }
32
GetSecurityLevelValue(SecurityLevel securityLevel)33 std::string SecurityPolicy::GetSecurityLevelValue(SecurityLevel securityLevel)
34 {
35 switch (securityLevel) {
36 case SecurityLevel::S1:
37 return "s1";
38 case SecurityLevel::S2:
39 return "s2";
40 case SecurityLevel::S3:
41 return "s3";
42 case SecurityLevel::S4:
43 return "s4";
44 default:
45 return "";
46 }
47 }
48
GetFileSecurityLevel(const std::string & filePath)49 std::string SecurityPolicy::GetFileSecurityLevel(const std::string &filePath)
50 {
51 return FileManagement::ModuleSecurityLabel::SecurityLabel::GetSecurityLabel(filePath);
52 }
53
SetSecurityLabel(const RdbStoreConfig & config)54 int SecurityPolicy::SetSecurityLabel(const RdbStoreConfig &config)
55 {
56 if (config.GetStorageMode() != StorageMode::MODE_MEMORY && config.GetSecurityLevel() != SecurityLevel::LAST) {
57 std::string currentLevel = GetFileSecurityLevel(config.GetPath());
58 std::string toSetLevel = GetSecurityLevelValue(config.GetSecurityLevel());
59 LOG_INFO("Security level current is %{public}s to %{public}s.", currentLevel.c_str(), toSetLevel.c_str());
60 if (currentLevel.empty()) {
61 return SetFileSecurityLevel(config.GetPath(), toSetLevel);
62 }
63 return currentLevel == toSetLevel ? E_OK : E_ERROR;
64 }
65 return E_OK;
66 }
67 } // namespace NativeRdb
68 } // namespace OHOS