blob: 964a1e436238e9cffaebd07e1f1a3faa3b65d45f [file] [log] [blame]
Tom Cherryfd44b9f2017-11-08 14:01:00 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include "contexts_split.h"
30
31#include <ctype.h>
32#include <stdlib.h>
33#include <string.h>
34#include <sys/mman.h>
35#include <sys/stat.h>
36
37#include <async_safe/log.h>
38
39#include "context_node.h"
40#include "system_property_globals.h"
41
42class ContextListNode : public ContextNode {
43 public:
44 ContextListNode(ContextListNode* next, const char* context)
45 : ContextNode(strdup(context)), next(next) {
46 }
47
48 ~ContextListNode() {
49 free(const_cast<char*>(context()));
50 }
51
52 ContextListNode* next;
53};
54
55struct PrefixNode {
56 PrefixNode(struct PrefixNode* next, const char* prefix, ContextListNode* context)
57 : prefix(strdup(prefix)), prefix_len(strlen(prefix)), context(context), next(next) {
58 }
59 ~PrefixNode() {
60 free(prefix);
61 }
62 char* prefix;
63 const size_t prefix_len;
64 ContextListNode* context;
65 PrefixNode* next;
66};
67
68template <typename List, typename... Args>
69static inline void ListAdd(List** list, Args... args) {
70 *list = new List(*list, args...);
71}
72
73static void ListAddAfterLen(PrefixNode** list, const char* prefix, ContextListNode* context) {
74 size_t prefix_len = strlen(prefix);
75
76 auto next_list = list;
77
78 while (*next_list) {
79 if ((*next_list)->prefix_len < prefix_len || (*next_list)->prefix[0] == '*') {
80 ListAdd(next_list, prefix, context);
81 return;
82 }
83 next_list = &(*next_list)->next;
84 }
85 ListAdd(next_list, prefix, context);
86}
87
88template <typename List, typename Func>
89static void ListForEach(List* list, Func func) {
90 while (list) {
91 func(list);
92 list = list->next;
93 }
94}
95
96template <typename List, typename Func>
97static List* ListFind(List* list, Func func) {
98 while (list) {
99 if (func(list)) {
100 return list;
101 }
102 list = list->next;
103 }
104 return nullptr;
105}
106
107template <typename List>
108static void ListFree(List** list) {
109 while (*list) {
110 auto old_list = *list;
111 *list = old_list->next;
112 delete old_list;
113 }
114}
115
116// The below two functions are duplicated from label_support.c in libselinux.
117// TODO: Find a location suitable for these functions such that both libc and
118// libselinux can share a common source file.
119
120// The read_spec_entries and read_spec_entry functions may be used to
121// replace sscanf to read entries from spec files. The file and
122// property services now use these.
123
124// Read an entry from a spec file (e.g. file_contexts)
125static inline int read_spec_entry(char** entry, char** ptr, int* len) {
126 *entry = nullptr;
127 char* tmp_buf = nullptr;
128
129 while (isspace(**ptr) && **ptr != '\0') (*ptr)++;
130
131 tmp_buf = *ptr;
132 *len = 0;
133
134 while (!isspace(**ptr) && **ptr != '\0') {
135 (*ptr)++;
136 (*len)++;
137 }
138
139 if (*len) {
140 *entry = strndup(tmp_buf, *len);
141 if (!*entry) return -1;
142 }
143
144 return 0;
145}
146
147// line_buf - Buffer containing the spec entries .
148// num_args - The number of spec parameter entries to process.
149// ... - A 'char **spec_entry' for each parameter.
150// returns - The number of items processed.
151//
152// This function calls read_spec_entry() to do the actual string processing.
153static int read_spec_entries(char* line_buf, int num_args, ...) {
154 char **spec_entry, *buf_p;
155 int len, rc, items, entry_len = 0;
156 va_list ap;
157
158 len = strlen(line_buf);
159 if (line_buf[len - 1] == '\n')
160 line_buf[len - 1] = '\0';
161 else
162 // Handle case if line not \n terminated by bumping
163 // the len for the check below (as the line is NUL
164 // terminated by getline(3))
165 len++;
166
167 buf_p = line_buf;
168 while (isspace(*buf_p)) buf_p++;
169
170 // Skip comment lines and empty lines.
171 if (*buf_p == '#' || *buf_p == '\0') return 0;
172
173 // Process the spec file entries
174 va_start(ap, num_args);
175
176 items = 0;
177 while (items < num_args) {
178 spec_entry = va_arg(ap, char**);
179
180 if (len - 1 == buf_p - line_buf) {
181 va_end(ap);
182 return items;
183 }
184
185 rc = read_spec_entry(spec_entry, &buf_p, &entry_len);
186 if (rc < 0) {
187 va_end(ap);
188 return rc;
189 }
190 if (entry_len) items++;
191 }
192 va_end(ap);
193 return items;
194}
195
196static bool MapSystemPropertyArea(bool access_rw, bool* fsetxattr_failed) {
197 char filename[PROP_FILENAME_MAX];
198 int len = async_safe_format_buffer(filename, sizeof(filename), "%s/properties_serial",
199 property_filename);
200 if (len < 0 || len > PROP_FILENAME_MAX) {
201 __system_property_area__ = nullptr;
202 return false;
203 }
204
205 if (access_rw) {
206 __system_property_area__ =
207 prop_area::map_prop_area_rw(filename, "u:object_r:properties_serial:s0", fsetxattr_failed);
208 } else {
209 __system_property_area__ = prop_area::map_prop_area(filename);
210 }
211 return __system_property_area__;
212}
213
214bool ContextsSplit::InitializePropertiesFromFile(const char* filename) {
215 FILE* file = fopen(filename, "re");
216 if (!file) {
217 return false;
218 }
219
220 char* buffer = nullptr;
221 size_t line_len;
222 char* prop_prefix = nullptr;
223 char* context = nullptr;
224
225 while (getline(&buffer, &line_len, file) > 0) {
226 int items = read_spec_entries(buffer, 2, &prop_prefix, &context);
227 if (items <= 0) {
228 continue;
229 }
230 if (items == 1) {
231 free(prop_prefix);
232 continue;
233 }
234
235 // init uses ctl.* properties as an IPC mechanism and does not write them
236 // to a property file, therefore we do not need to create property files
237 // to store them.
238 if (!strncmp(prop_prefix, "ctl.", 4)) {
239 free(prop_prefix);
240 free(context);
241 continue;
242 }
243
244 auto old_context = ListFind(
245 contexts_, [context](ContextListNode* l) { return !strcmp(l->context(), context); });
246 if (old_context) {
247 ListAddAfterLen(&prefixes_, prop_prefix, old_context);
248 } else {
249 ListAdd(&contexts_, context);
250 ListAddAfterLen(&prefixes_, prop_prefix, contexts_);
251 }
252 free(prop_prefix);
253 free(context);
254 }
255
256 free(buffer);
257 fclose(file);
258
259 return true;
260}
261
262bool ContextsSplit::InitializeProperties() {
263 // If we do find /property_contexts, then this is being
264 // run as part of the OTA updater on older release that had
265 // /property_contexts - b/34370523
266 if (InitializePropertiesFromFile("/property_contexts")) {
267 return true;
268 }
269
270 // Use property_contexts from /system & /vendor, fall back to those from /
271 if (access("/system/etc/selinux/plat_property_contexts", R_OK) != -1) {
272 if (!InitializePropertiesFromFile("/system/etc/selinux/plat_property_contexts")) {
273 return false;
274 }
275 // Don't check for failure here, so we always have a sane list of properties.
276 // E.g. In case of recovery, the vendor partition will not have mounted and we
277 // still need the system / platform properties to function.
278 InitializePropertiesFromFile("/vendor/etc/selinux/nonplat_property_contexts");
279 } else {
280 if (!InitializePropertiesFromFile("/plat_property_contexts")) {
281 return false;
282 }
283 InitializePropertiesFromFile("/nonplat_property_contexts");
284 }
285
286 return true;
287}
288
289bool ContextsSplit::Initialize(bool writable) {
290 if (!InitializeProperties()) {
291 return false;
292 }
293
294 if (writable) {
295 mkdir(property_filename, S_IRWXU | S_IXGRP | S_IXOTH);
296 bool open_failed = false;
297 bool fsetxattr_failed = false;
298 ListForEach(contexts_, [&fsetxattr_failed, &open_failed](ContextListNode* l) {
299 if (!l->Open(true, &fsetxattr_failed)) {
300 open_failed = true;
301 }
302 });
303 if (open_failed || !MapSystemPropertyArea(true, &fsetxattr_failed)) {
304 FreeAndUnmap();
305 return false;
306 }
307
308 return !fsetxattr_failed;
309 } else {
310 if (!MapSystemPropertyArea(false, nullptr)) {
311 FreeAndUnmap();
312 return false;
313 }
314 }
315 return true;
316}
317
318prop_area* ContextsSplit::GetPropAreaForName(const char* name) {
319 auto entry = ListFind(prefixes_, [name](PrefixNode* l) {
320 return l->prefix[0] == '*' || !strncmp(l->prefix, name, l->prefix_len);
321 });
322 if (!entry) {
323 return nullptr;
324 }
325
326 auto cnode = entry->context;
327 if (!cnode->pa()) {
328 // We explicitly do not check no_access_ in this case because unlike the
329 // case of foreach(), we want to generate an selinux audit for each
330 // non-permitted property access in this function.
331 cnode->Open(false, nullptr);
332 }
333 return cnode->pa();
334}
335
336void ContextsSplit::ForEach(void (*propfn)(const prop_info* pi, void* cookie), void* cookie) {
337 ListForEach(contexts_, [propfn, cookie](ContextListNode* l) {
338 if (l->CheckAccessAndOpen()) {
339 l->pa()->foreach (propfn, cookie);
340 }
341 });
342}
343
344void ContextsSplit::ResetAccess() {
345 ListForEach(contexts_, [](ContextListNode* l) { l->ResetAccess(); });
346}
347
348void ContextsSplit::FreeAndUnmap() {
349 ListFree(&prefixes_);
350 ListFree(&contexts_);
351 if (__system_property_area__) {
352 munmap(__system_property_area__, pa_size);
353 __system_property_area__ = nullptr;
354 }
355}