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 SECURITY_LABEL_H 17 #define 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 FileManagement { 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 #ifdef IOS_PLATFORM 39 if (setxattr(path.c_str(), XATTR_KEY, dataLevel.c_str(), dataLevel.size(), 0, 0) < 0) { 40 #else 41 if (setxattr(path.c_str(), XATTR_KEY, dataLevel.c_str(), dataLevel.size(), 0) < 0) { 42 #endif 43 return false; 44 } 45 return true; 46 } 47 48 static std::string GetSecurityLabel(const std::string &path) 49 { 50 #ifdef IOS_PLATFORM 51 auto xattrValueSize = getxattr(path.c_str(), XATTR_KEY, nullptr, 0, 0, 0); 52 #else 53 auto xattrValueSize = getxattr(path.c_str(), XATTR_KEY, nullptr, 0); 54 #endif 55 if (xattrValueSize == -1 || errno == ENOTSUP) { 56 return ""; 57 } 58 if (xattrValueSize <= 0) { 59 return DEFAULT_DATA_LEVEL; 60 } 61 std::unique_ptr<char[]> xattrValue = std::make_unique<char[]>((long)xattrValueSize + 1); 62 if (xattrValue == nullptr) { 63 return ""; 64 } 65 #ifdef IOS_PLATFORM 66 xattrValueSize = getxattr(path.c_str(), XATTR_KEY, xattrValue.get(), xattrValueSize, 0, 0); 67 #else 68 xattrValueSize = getxattr(path.c_str(), XATTR_KEY, xattrValue.get(), xattrValueSize); 69 #endif 70 if (xattrValueSize == -1 || errno == ENOTSUP) { 71 return ""; 72 } 73 if (xattrValueSize <= 0) { 74 return DEFAULT_DATA_LEVEL; 75 } 76 return std::string(xattrValue.get()); 77 } 78 }; 79 } // namespace ModuleSecurityLabel 80 } // namespace FileManagement 81 } // namespace OHOS 82 #endif