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 #define LOG_TAG "SecurityPolicy"
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;
GetSecurityLevelValue(SecurityLevel securityLevel)25 std::string SecurityPolicy::GetSecurityLevelValue(SecurityLevel securityLevel)
26 {
27     switch (securityLevel) {
28         case SecurityLevel::S1:
29             return "s1";
30         case SecurityLevel::S2:
31             return "s2";
32         case SecurityLevel::S3:
33             return "s3";
34         case SecurityLevel::S4:
35             return "s4";
36         default:
37             return "";
38     }
39 }
40 
GetFileSecurityLevel(const std::string & filePath)41 std::string SecurityPolicy::GetFileSecurityLevel(const std::string &filePath)
42 {
43     return FileManagement::ModuleSecurityLabel::SecurityLabel::GetSecurityLabel(filePath);
44 }
45 
SetSecurityLabel(const RdbStoreConfig & config)46 int SecurityPolicy::SetSecurityLabel(const RdbStoreConfig &config)
47 {
48     if (config.GetStorageMode() != StorageMode::MODE_MEMORY && config.GetSecurityLevel() != SecurityLevel::LAST) {
49         auto toSetLevel = GetSecurityLevelValue(config.GetSecurityLevel());
50         auto errCode = FileManagement::ModuleSecurityLabel::SecurityLabel::SetSecurityLabel(config.GetPath(),
51             toSetLevel) ? E_OK : E_CONFIG_INVALID_CHANGE;
52         if (errCode != E_OK) {
53             auto currentLevel = GetFileSecurityLevel(config.GetPath());
54             LOG_ERROR("Set security level from %{public}s to %{public}s, result:%{public}d, errno:%{public}d.",
55                 currentLevel.c_str(), toSetLevel.c_str(), errCode, errno);
56         }
57         return errCode;
58     }
59     return E_OK;
60 }
61 } // namespace NativeRdb
62 } // namespace OHOS