1 /*
2 * Copyright (C) 2023-2025 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_label_adapter.h"
17
18 #include <sys/xattr.h>
19 #include "device_auth_defines.h"
20 #include "hc_types.h"
21 #include "hc_log.h"
22 #include "string_util.h"
23
24 #define SECURITY_LABEL_XATTR_KEY "user.security"
25
GetSecurityLabel(const char * filePath,char ** returnLabel)26 static int32_t GetSecurityLabel(const char *filePath, char **returnLabel)
27 {
28 int32_t labelSize = getxattr(filePath, SECURITY_LABEL_XATTR_KEY, NULL, 0);
29 if (labelSize <= 0 || errno == ENOTSUP) {
30 LOGE("Failed to get security label size, labelSize: %" LOG_PUB "d, [errno]: %" LOG_PUB "d", labelSize, errno);
31 return HC_ERROR;
32 }
33 char *label = (char *)HcMalloc(labelSize + 1, 0);
34 if (label == NULL) {
35 LOGE("Failed to alloc memory for label!");
36 return HC_ERR_ALLOC_MEMORY;
37 }
38 labelSize = getxattr(filePath, SECURITY_LABEL_XATTR_KEY, label, labelSize);
39 if (labelSize <= 0 || errno == ENOTSUP) {
40 LOGE("Failed to get security label, labelSize: %" LOG_PUB "d, [errno]: %" LOG_PUB "d", labelSize, errno);
41 HcFree(label);
42 return HC_ERROR;
43 }
44 *returnLabel = label;
45 return HC_SUCCESS;
46 }
47
IsSetLabelNeeded(const char * filePath,const char * labelToSet)48 static bool IsSetLabelNeeded(const char *filePath, const char *labelToSet)
49 {
50 char *existLabel = NULL;
51 if (GetSecurityLabel(filePath, &existLabel) != HC_SUCCESS) {
52 return true;
53 }
54 if (!IsStrEqual(existLabel, labelToSet)) {
55 LOGI("Incorrect security level, need to reset.");
56 HcFree(existLabel);
57 return true;
58 }
59 HcFree(existLabel);
60 return false;
61 }
62
SetSecurityLabel(const char * filePath,const char * labelToSet)63 void SetSecurityLabel(const char *filePath, const char *labelToSet)
64 {
65 if (!IsSetLabelNeeded(filePath, labelToSet)) {
66 return;
67 }
68 int32_t res = setxattr(filePath, SECURITY_LABEL_XATTR_KEY, labelToSet,
69 HcStrlen(labelToSet), 0);
70 LOGI("Set security label [Res]: %" LOG_PUB "d", res);
71 }