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