1 /*
2 * Copyright (c) 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 #include <errno.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <stdbool.h>
20
21 #include "app_allow_config.h"
22 #include "callbacks.h"
23 #include "ignore_path.h"
24
25
26 #define SYSTEM_APP_ALLOW_CONFIG_PATH "/system/etc/selinux/app_allow_cfg"
27 static char **g_app_allow_config = NULL;
28 static size_t g_line_count = 0;
29
insert_line_to_app_allow_config(const char * line)30 static bool insert_line_to_app_allow_config(const char *line)
31 {
32 if (strlen(line) == 0) {
33 return false;
34 }
35
36 char **new_list = (char **)malloc((g_line_count + 1) * sizeof(char *));
37 if (new_list == NULL) {
38 selinux_log(SELINUX_ERROR, "Failed to malloc, line: %s\n", line);
39 return false;
40 }
41
42 if (g_app_allow_config != NULL) {
43 for (size_t i = 0; i < g_line_count; i++) {
44 new_list[i] = g_app_allow_config[i];
45 free(g_app_allow_config[i]);
46 }
47 free(g_app_allow_config);
48 }
49
50 g_app_allow_config = new_list;
51 g_app_allow_config[g_line_count] = strdup(line);
52 if (g_app_allow_config[g_line_count] == NULL) {
53 for (size_t i = 0; i < g_line_count; i++) {
54 free(new_list[i]);
55 }
56 free(new_list);
57 selinux_log(SELINUX_ERROR, "Failed to strdup, line: %s\n", line);
58 return false;
59 }
60
61 return true;
62 }
63
load_app_allow_config()64 void load_app_allow_config()
65 {
66 FILE *file = fopen(SYSTEM_APP_ALLOW_CONFIG_PATH, "r");
67 if (file == NULL) {
68 selinux_log(SELINUX_ERROR, "Failed to open file, %s\n", SYSTEM_APP_ALLOW_CONFIG_PATH);
69 return;
70 }
71
72 char *line = NULL;
73 size_t len = 0;
74 while (getline(&line, &len, file) != -1) {
75 len = trim_newline(line);
76 if (len > 0 && line[len -1] == '/') {
77 line[len - 1] = '\0';
78 }
79
80 if (!insert_line_to_app_allow_config(line)) {
81 selinux_log(SELINUX_ERROR, "Failed to insert app_allow_config line: %s\n", line);
82 continue;
83 }
84 g_line_count++;
85 }
86
87 free(line);
88 if (fclose(file) != 0) {
89 selinux_log(SELINUX_ERROR, "Failed to close file app_allow_config, err: %s\n", strerror(errno));
90 }
91 }
92
is_in_app_allow_config(const char * pathname)93 bool is_in_app_allow_config(const char *pathname)
94 {
95 for (size_t i = 0; i < g_line_count; i++) {
96 if (strcmp(g_app_allow_config[i], pathname) == 0 ||
97 strstr(pathname, g_app_allow_config[i]) != NULL) {
98 return true;
99 }
100 }
101
102 return false;
103 }
104