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