• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-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 #ifndef FOUNDATION_FILEMANAGEMENT_FILEAPI_INTERFACES_INNERKITS_SECURITY_LABEL_H
17 #define FOUNDATION_FILEMANAGEMENT_FILEAPI_INTERFACES_INNERKITS_SECURITY_LABEL_H
18 
19 #include <cerrno>
20 #include <memory>
21 #include <set>
22 #include <string>
23 #include <sys/xattr.h>
24 
25 namespace OHOS {
26 namespace DistributedFS {
27 namespace ModuleSecurityLabel {
28 const char XATTR_KEY[] = {"user.security"};
29 const std::string DEFAULT_DATA_LEVEL = "s3";
30 const std::set<std::string> DATA_LEVEL = {"s0", "s1", "s2", "s3", "s4"};
31 class SecurityLabel {
32 public:
SetSecurityLabel(const std::string & path,const std::string & dataLevel)33     static bool SetSecurityLabel(const std::string &path, const std::string &dataLevel)
34     {
35         if (DATA_LEVEL.count(dataLevel) != 1) {
36             return false;
37         }
38         if (setxattr(path.c_str(), XATTR_KEY, dataLevel.c_str(), dataLevel.size(), 0) < 0) {
39             return false;
40         }
41         return true;
42     }
43 
GetSecurityLabel(const std::string & path)44     static std::string GetSecurityLabel(const std::string &path)
45     {
46         auto xattrValueSize = getxattr(path.c_str(), XATTR_KEY, nullptr, 0);
47         if (xattrValueSize == -1 || errno == ENOTSUP) {
48             return "";
49         }
50         if (xattrValueSize <= 0) {
51             return DEFAULT_DATA_LEVEL;
52         }
53         std::unique_ptr<char[]> xattrValue = std::make_unique<char[]>((long)xattrValueSize + 1);
54         if (xattrValue == nullptr) {
55             return "";
56         }
57 
58         xattrValueSize = getxattr(path.c_str(), XATTR_KEY, xattrValue.get(), xattrValueSize);
59         if (xattrValueSize == -1 || errno == ENOTSUP) {
60             return "";
61         }
62         if (xattrValueSize <= 0) {
63             return DEFAULT_DATA_LEVEL;
64         }
65         return std::string(xattrValue.get());
66     }
67 };
68 } // namespace ModuleSecurityLabel
69 } // namespace FileIO
70 } // namespace OHOS
71 #endif