1 #ifndef _SELABEL_FILE_H_
2 #define _SELABEL_FILE_H_
3
4 #include <errno.h>
5 #include <pthread.h>
6 #include <string.h>
7
8 #include <sys/stat.h>
9 #include <sys/xattr.h>
10
11 /*
12 * regex.h/c were introduced to hold all dependencies on the regular
13 * expression back-end when we started supporting PCRE2. regex.h defines a
14 * minimal interface required by libselinux, so that the remaining code
15 * can be agnostic about the underlying implementation.
16 */
17 #include "regex.h"
18
19 #include "callbacks.h"
20 #include "label_internal.h"
21 #include "selinux_internal.h"
22
23 #define SELINUX_MAGIC_COMPILED_FCONTEXT 0xf97cff8a
24
25 /* Version specific changes */
26 #define SELINUX_COMPILED_FCONTEXT_NOPCRE_VERS 1
27 #define SELINUX_COMPILED_FCONTEXT_PCRE_VERS 2
28 #define SELINUX_COMPILED_FCONTEXT_MODE 3
29 #define SELINUX_COMPILED_FCONTEXT_PREFIX_LEN 4
30 #define SELINUX_COMPILED_FCONTEXT_REGEX_ARCH 5
31
32 #define SELINUX_COMPILED_FCONTEXT_MAX_VERS \
33 SELINUX_COMPILED_FCONTEXT_REGEX_ARCH
34
35 /* Required selinux_restorecon and selabel_get_digests_all_partial_matches() */
36 #define RESTORECON_PARTIAL_MATCH_DIGEST "security.sehash"
37
38 struct selabel_sub {
39 char *src;
40 int slen;
41 char *dst;
42 struct selabel_sub *next;
43 };
44
45 /* A file security context specification. */
46 struct spec {
47 struct selabel_lookup_rec lr; /* holds contexts for lookup result */
48 char *regex_str; /* regular expression string for diagnostics */
49 char *type_str; /* type string for diagnostic messages */
50 struct regex_data * regex; /* backend dependent regular expression data */
51 bool regex_compiled; /* bool to indicate if the regex is compiled */
52 pthread_mutex_t regex_lock; /* lock for lazy compilation of regex */
53 mode_t mode; /* mode format value */
54 int matches; /* number of matching pathnames */
55 int stem_id; /* indicates which stem-compression item */
56 char hasMetaChars; /* regular expression has meta-chars */
57 char from_mmap; /* this spec is from an mmap of the data */
58 size_t prefix_len; /* length of fixed path prefix */
59 };
60
61 /* A regular expression stem */
62 struct stem {
63 char *buf;
64 int len;
65 char from_mmap;
66 };
67
68 /* Where we map the file in during selabel_open() */
69 struct mmap_area {
70 void *addr; /* Start addr + len used to release memory at close */
71 size_t len;
72 void *next_addr; /* Incremented by next_entry() */
73 size_t next_len; /* Decremented by next_entry() */
74 struct mmap_area *next;
75 };
76
77 /* Our stored configuration */
78 struct saved_data {
79 /*
80 * The array of specifications, initially in the same order as in
81 * the specification file. Sorting occurs based on hasMetaChars.
82 */
83 struct spec *spec_arr;
84 unsigned int nspec;
85 unsigned int alloc_specs;
86
87 /*
88 * The array of regular expression stems.
89 */
90 struct stem *stem_arr;
91 int num_stems;
92 int alloc_stems;
93 struct mmap_area *mmap_areas;
94
95 /* substitution support */
96 struct selabel_sub *dist_subs;
97 struct selabel_sub *subs;
98 };
99
string_to_mode(char * mode)100 static inline mode_t string_to_mode(char *mode)
101 {
102 size_t len;
103
104 if (!mode)
105 return 0;
106 len = strlen(mode);
107 if (mode[0] != '-' || len != 2)
108 return -1;
109 switch (mode[1]) {
110 case 'b':
111 return S_IFBLK;
112 case 'c':
113 return S_IFCHR;
114 case 'd':
115 return S_IFDIR;
116 case 'p':
117 return S_IFIFO;
118 case 'l':
119 return S_IFLNK;
120 case 's':
121 return S_IFSOCK;
122 case '-':
123 return S_IFREG;
124 default:
125 return -1;
126 }
127 /* impossible to get here */
128 return 0;
129 }
130
grow_specs(struct saved_data * data)131 static inline int grow_specs(struct saved_data *data)
132 {
133 struct spec *specs;
134 size_t new_specs, total_specs;
135
136 if (data->nspec < data->alloc_specs)
137 return 0;
138
139 new_specs = data->nspec + 16;
140 total_specs = data->nspec + new_specs;
141
142 specs = realloc(data->spec_arr, total_specs * sizeof(*specs));
143 if (!specs) {
144 perror("realloc");
145 return -1;
146 }
147
148 /* blank the new entries */
149 memset(&specs[data->nspec], 0, new_specs * sizeof(*specs));
150
151 data->spec_arr = specs;
152 data->alloc_specs = total_specs;
153 return 0;
154 }
155
156 /* Determine if the regular expression specification has any meta characters. */
spec_hasMetaChars(struct spec * spec)157 static inline void spec_hasMetaChars(struct spec *spec)
158 {
159 char *c;
160 int len;
161 char *end;
162
163 c = spec->regex_str;
164 len = strlen(spec->regex_str);
165 end = c + len;
166
167 spec->hasMetaChars = 0;
168 spec->prefix_len = len;
169
170 /* Look at each character in the RE specification string for a
171 * meta character. Return when any meta character reached. */
172 while (c < end) {
173 switch (*c) {
174 case '.':
175 case '^':
176 case '$':
177 case '?':
178 case '*':
179 case '+':
180 case '|':
181 case '[':
182 case '(':
183 case '{':
184 spec->hasMetaChars = 1;
185 spec->prefix_len = c - spec->regex_str;
186 return;
187 case '\\': /* skip the next character */
188 c++;
189 break;
190 default:
191 break;
192
193 }
194 c++;
195 }
196 }
197
198 /* Move exact pathname specifications to the end. */
sort_specs(struct saved_data * data)199 static inline int sort_specs(struct saved_data *data)
200 {
201 struct spec *spec_copy;
202 struct spec spec;
203 unsigned int i;
204 int front, back;
205 size_t len = sizeof(*spec_copy);
206
207 spec_copy = malloc(len * data->nspec);
208 if (!spec_copy)
209 return -1;
210
211 /* first move the exact pathnames to the back */
212 front = 0;
213 back = data->nspec - 1;
214 for (i = 0; i < data->nspec; i++) {
215 if (data->spec_arr[i].hasMetaChars)
216 memcpy(&spec_copy[front++], &data->spec_arr[i], len);
217 else
218 memcpy(&spec_copy[back--], &data->spec_arr[i], len);
219 }
220
221 /*
222 * now the exact pathnames are at the end, but they are in the reverse
223 * order. Since 'front' is now the first of the 'exact' we can run
224 * that part of the array switching the front and back element.
225 */
226 back = data->nspec - 1;
227 while (front < back) {
228 /* save the front */
229 memcpy(&spec, &spec_copy[front], len);
230 /* move the back to the front */
231 memcpy(&spec_copy[front], &spec_copy[back], len);
232 /* put the old front in the back */
233 memcpy(&spec_copy[back], &spec, len);
234 front++;
235 back--;
236 }
237
238 free(data->spec_arr);
239 data->spec_arr = spec_copy;
240
241 return 0;
242 }
243
244 /* Return the length of the text that can be considered the stem, returns 0
245 * if there is no identifiable stem */
get_stem_from_spec(const char * const buf)246 static inline int get_stem_from_spec(const char *const buf)
247 {
248 const char *tmp = strchr(buf + 1, '/');
249 const char *ind;
250
251 if (!tmp)
252 return 0;
253
254 for (ind = buf; ind < tmp; ind++) {
255 if (strchr(".^$?*+|[({", (int)*ind))
256 return 0;
257 }
258 return tmp - buf;
259 }
260
261 /*
262 * return the stemid given a string and a length
263 */
find_stem(struct saved_data * data,const char * buf,int stem_len)264 static inline int find_stem(struct saved_data *data, const char *buf,
265 int stem_len)
266 {
267 int i;
268
269 for (i = 0; i < data->num_stems; i++) {
270 if (stem_len == data->stem_arr[i].len &&
271 !strncmp(buf, data->stem_arr[i].buf, stem_len))
272 return i;
273 }
274
275 return -1;
276 }
277
278 /* returns the index of the new stored object */
store_stem(struct saved_data * data,char * buf,int stem_len)279 static inline int store_stem(struct saved_data *data, char *buf, int stem_len)
280 {
281 int num = data->num_stems;
282
283 if (data->alloc_stems == num) {
284 struct stem *tmp_arr;
285 int alloc_stems = data->alloc_stems * 2 + 16;
286 tmp_arr = realloc(data->stem_arr,
287 sizeof(*tmp_arr) * alloc_stems);
288 if (!tmp_arr) {
289 free(buf);
290 return -1;
291 }
292 data->alloc_stems = alloc_stems;
293 data->stem_arr = tmp_arr;
294 }
295 data->stem_arr[num].len = stem_len;
296 data->stem_arr[num].buf = buf;
297 data->stem_arr[num].from_mmap = 0;
298 data->num_stems++;
299
300 return num;
301 }
302
303 /* find the stem of a file spec, returns the index into stem_arr for a new
304 * or existing stem, (or -1 if there is no possible stem - IE for a file in
305 * the root directory or a regex that is too complex for us). */
find_stem_from_spec(struct saved_data * data,const char * buf)306 static inline int find_stem_from_spec(struct saved_data *data, const char *buf)
307 {
308 int stem_len = get_stem_from_spec(buf);
309 int stemid;
310 char *stem;
311
312 if (!stem_len)
313 return -1;
314
315 stemid = find_stem(data, buf, stem_len);
316 if (stemid >= 0)
317 return stemid;
318
319 /* not found, allocate a new one */
320 stem = strndup(buf, stem_len);
321 if (!stem)
322 return -1;
323
324 return store_stem(data, stem, stem_len);
325 }
326
327 /* This will always check for buffer over-runs and either read the next entry
328 * if buf != NULL or skip over the entry (as these areas are mapped in the
329 * current buffer). */
next_entry(void * buf,struct mmap_area * fp,size_t bytes)330 static inline int next_entry(void *buf, struct mmap_area *fp, size_t bytes)
331 {
332 if (bytes > fp->next_len)
333 return -1;
334
335 if (buf)
336 memcpy(buf, fp->next_addr, bytes);
337
338 fp->next_addr = (char *)fp->next_addr + bytes;
339 fp->next_len -= bytes;
340 return 0;
341 }
342
compile_regex(struct spec * spec,const char ** errbuf)343 static inline int compile_regex(struct spec *spec, const char **errbuf)
344 {
345 char *reg_buf, *anchored_regex, *cp;
346 struct regex_error_data error_data;
347 static char regex_error_format_buffer[256];
348 size_t len;
349 int rc;
350 bool regex_compiled;
351
352 /* We really want pthread_once() here, but since its
353 * init_routine does not take a parameter, it's not possible
354 * to use, so we generate the same effect with atomics and a
355 * mutex */
356 #ifdef __ATOMIC_RELAXED
357 regex_compiled =
358 __atomic_load_n(&spec->regex_compiled, __ATOMIC_ACQUIRE);
359 #else
360 /* GCC <4.7 */
361 __sync_synchronize();
362 regex_compiled = spec->regex_compiled;
363 #endif
364 if (regex_compiled) {
365 return 0; /* already done */
366 }
367
368 __pthread_mutex_lock(&spec->regex_lock);
369 /* Check if another thread compiled the regex while we waited
370 * on the mutex */
371 #ifdef __ATOMIC_RELAXED
372 regex_compiled =
373 __atomic_load_n(&spec->regex_compiled, __ATOMIC_ACQUIRE);
374 #else
375 /* GCC <4.7 */
376 __sync_synchronize();
377 regex_compiled = spec->regex_compiled;
378 #endif
379 if (regex_compiled) {
380 __pthread_mutex_unlock(&spec->regex_lock);
381 return 0;
382 }
383
384 reg_buf = spec->regex_str;
385 /* Anchor the regular expression. */
386 len = strlen(reg_buf);
387 cp = anchored_regex = malloc(len + 3);
388 if (!anchored_regex) {
389 if (errbuf)
390 *errbuf = "out of memory";
391 __pthread_mutex_unlock(&spec->regex_lock);
392 return -1;
393 }
394
395 /* Create ^...$ regexp. */
396 *cp++ = '^';
397 memcpy(cp, reg_buf, len);
398 cp += len;
399 *cp++ = '$';
400 *cp = '\0';
401
402 /* Compile the regular expression. */
403 rc = regex_prepare_data(&spec->regex, anchored_regex, &error_data);
404 free(anchored_regex);
405 if (rc < 0) {
406 if (errbuf) {
407 regex_format_error(&error_data,
408 regex_error_format_buffer,
409 sizeof(regex_error_format_buffer));
410 *errbuf = ®ex_error_format_buffer[0];
411 }
412 __pthread_mutex_unlock(&spec->regex_lock);
413 return -1;
414 }
415
416 /* Done. */
417 #ifdef __ATOMIC_RELAXED
418 __atomic_store_n(&spec->regex_compiled, true, __ATOMIC_RELEASE);
419 #else
420 /* GCC <4.7 */
421 spec->regex_compiled = true;
422 __sync_synchronize();
423 #endif
424 __pthread_mutex_unlock(&spec->regex_lock);
425 return 0;
426 }
427
428 /* This service is used by label_file.c process_file() and
429 * utils/sefcontext_compile.c */
process_line(struct selabel_handle * rec,const char * path,const char * prefix,char * line_buf,unsigned lineno)430 static inline int process_line(struct selabel_handle *rec,
431 const char *path, const char *prefix,
432 char *line_buf, unsigned lineno)
433 {
434 int items, len, rc;
435 char *regex = NULL, *type = NULL, *context = NULL;
436 struct saved_data *data = (struct saved_data *)rec->data;
437 struct spec *spec_arr;
438 unsigned int nspec = data->nspec;
439 const char *errbuf = NULL;
440
441 items = read_spec_entries(line_buf, &errbuf, 3, ®ex, &type, &context);
442 if (items < 0) {
443 rc = errno;
444 selinux_log(SELINUX_ERROR,
445 "%s: line %u error due to: %s\n", path,
446 lineno, errbuf ?: strerror(errno));
447 errno = rc;
448 return -1;
449 }
450
451 if (items == 0)
452 return items;
453
454 if (items < 2) {
455 COMPAT_LOG(SELINUX_ERROR,
456 "%s: line %u is missing fields\n", path,
457 lineno);
458 if (items == 1)
459 free(regex);
460 errno = EINVAL;
461 return -1;
462 } else if (items == 2) {
463 /* The type field is optional. */
464 context = type;
465 type = 0;
466 }
467
468 len = get_stem_from_spec(regex);
469 if (len && prefix && strncmp(prefix, regex, len)) {
470 /* Stem of regex does not match requested prefix, discard. */
471 free(regex);
472 free(type);
473 free(context);
474 return 0;
475 }
476
477 rc = grow_specs(data);
478 if (rc)
479 return rc;
480
481 spec_arr = data->spec_arr;
482
483 /* process and store the specification in spec. */
484 spec_arr[nspec].stem_id = find_stem_from_spec(data, regex);
485 spec_arr[nspec].regex_str = regex;
486 __pthread_mutex_init(&spec_arr[nspec].regex_lock, NULL);
487 spec_arr[nspec].regex_compiled = false;
488
489 spec_arr[nspec].type_str = type;
490 spec_arr[nspec].mode = 0;
491
492 spec_arr[nspec].lr.ctx_raw = context;
493 spec_arr[nspec].lr.lineno = lineno;
494
495 /*
496 * bump data->nspecs to cause closef() to cover it in its free
497 * but do not bump nspec since it's used below.
498 */
499 data->nspec++;
500
501 if (rec->validating
502 && compile_regex(&spec_arr[nspec], &errbuf)) {
503 COMPAT_LOG(SELINUX_ERROR,
504 "%s: line %u has invalid regex %s: %s\n",
505 path, lineno, regex, errbuf);
506 errno = EINVAL;
507 return -1;
508 }
509
510 if (type) {
511 mode_t mode = string_to_mode(type);
512
513 if (mode == (mode_t)-1) {
514 COMPAT_LOG(SELINUX_ERROR,
515 "%s: line %u has invalid file type %s\n",
516 path, lineno, type);
517 errno = EINVAL;
518 return -1;
519 }
520 spec_arr[nspec].mode = mode;
521 }
522
523 /* Determine if specification has
524 * any meta characters in the RE */
525 spec_hasMetaChars(&spec_arr[nspec]);
526
527 if (strcmp(context, "<<none>>") && rec->validating)
528 return compat_validate(rec, &spec_arr[nspec].lr, path, lineno);
529
530 return 0;
531 }
532
533 #endif /* _SELABEL_FILE_H_ */
534