summaryrefslogtreecommitdiff
path: root/selinux/setfiles.c (plain)
blob: 4fc307f550d7c712b3f738ea9d723e048a0c6b66
1/*
2 setfiles: based on policycoreutils 2.0.19
3 policycoreutils was released under GPL 2.
4 Port to BusyBox (c) 2007 by Yuichi Nakamura <ynakam@hitachisoft.jp>
5*/
6//config:config SETFILES
7//config: bool "setfiles"
8//config: default n
9//config: depends on SELINUX
10//config: help
11//config: Enable support to modify to relabel files.
12//config: Notice: If you built libselinux with -D_FILE_OFFSET_BITS=64,
13//config: (It is default in libselinux's Makefile), you _must_ enable
14//config: CONFIG_LFS.
15//config:
16//config:config FEATURE_SETFILES_CHECK_OPTION
17//config: bool "Enable check option"
18//config: default n
19//config: depends on SETFILES
20//config: help
21//config: Support "-c" option (check the validity of the contexts against
22//config: the specified binary policy) for setfiles. Requires libsepol.
23//config:
24//config:config RESTORECON
25//config: bool "restorecon"
26//config: default n
27//config: depends on SELINUX
28//config: help
29//config: Enable support to relabel files. The feature is almost
30//config: the same as setfiles, but usage is a little different.
31
32//applet:IF_SETFILES(APPLET(setfiles, BB_DIR_SBIN, BB_SUID_DROP))
33//applet:IF_RESTORECON(APPLET_ODDNAME(restorecon, setfiles, BB_DIR_SBIN, BB_SUID_DROP, restorecon))
34
35//kbuild:lib-$(CONFIG_SETFILES) += setfiles.o
36//kbuild:lib-$(CONFIG_RESTORECON) += setfiles.o
37
38//usage:#define setfiles_trivial_usage
39//usage: "[-dnpqsvW] [-e DIR]... [-o FILE] [-r alt_root_path]"
40//usage: IF_FEATURE_SETFILES_CHECK_OPTION(
41//usage: " [-c policyfile] spec_file"
42//usage: )
43//usage: " pathname"
44//usage:#define setfiles_full_usage "\n\n"
45//usage: "Reset file contexts under pathname according to spec_file\n"
46//usage: IF_FEATURE_SETFILES_CHECK_OPTION(
47//usage: "\n -c FILE Check the validity of the contexts against the specified binary policy"
48//usage: )
49//usage: "\n -d Show which specification matched each file"
50//usage: "\n -l Log changes in file labels to syslog"
51//TODO: log to syslog is not yet implemented, it goes to stdout only now
52//usage: "\n -n Don't change any file labels"
53//usage: "\n -q Suppress warnings"
54//usage: "\n -r DIR Use an alternate root path"
55//usage: "\n -e DIR Exclude DIR"
56//usage: "\n -F Force reset of context to match file_context for customizable files"
57//usage: "\n -o FILE Save list of files with incorrect context"
58//usage: "\n -s Take a list of files from stdin (instead of command line)"
59//usage: "\n -v Show changes in file labels, if type or role are changing"
60//usage: "\n -vv Show changes in file labels, if type, role, or user are changing"
61//usage: "\n -W Display warnings about entries that had no matching files"
62//usage:
63//usage:#define restorecon_trivial_usage
64//usage: "[-iFnRv] [-e EXCLUDEDIR]... [-o FILE] [-f FILE]"
65//usage:#define restorecon_full_usage "\n\n"
66//usage: "Reset security contexts of files in pathname\n"
67//usage: "\n -i Ignore files that don't exist"
68//usage: "\n -f FILE File with list of files to process"
69//usage: "\n -e DIR Directory to exclude"
70//usage: "\n -R,-r Recurse"
71//usage: "\n -n Don't change any file labels"
72//usage: "\n -o FILE Save list of files with incorrect context"
73//usage: "\n -v Verbose"
74//usage: "\n -vv Show changed labels"
75//usage: "\n -F Force reset of context to match file_context"
76//usage: "\n for customizable files, or the user section,"
77//usage: "\n if it has changed"
78
79#include "libbb.h"
80#if ENABLE_FEATURE_SETFILES_CHECK_OPTION
81#include <sepol/sepol.h>
82#endif
83
84#define MAX_EXCLUDES 50
85
86struct edir {
87 char *directory;
88 size_t size;
89};
90
91struct globals {
92 FILE *outfile;
93 char *policyfile;
94 char *rootpath;
95 int rootpathlen;
96 unsigned count;
97 int excludeCtr;
98 int errors;
99 int verbose; /* getopt32 uses it, has to be int */
100 smallint recurse; /* Recursive descent */
101 smallint follow_mounts;
102 /* Behavior flags determined based on setfiles vs. restorecon */
103 smallint expand_realpath; /* Expand paths via realpath */
104 smallint abort_on_error; /* Abort the file tree walk upon an error */
105 int add_assoc; /* Track inode associations for conflict detection */
106 int matchpathcon_flags; /* Flags to matchpathcon */
107 dev_t dev_id; /* Device id where target file exists */
108 int nerr;
109 struct edir excludeArray[MAX_EXCLUDES];
110} FIX_ALIASING;
111#define G (*(struct globals*)bb_common_bufsiz1)
112void BUG_setfiles_globals_too_big(void);
113#define INIT_G() do { \
114 setup_common_bufsiz(); \
115 if (sizeof(G) > COMMON_BUFSIZE) \
116 BUG_setfiles_globals_too_big(); \
117 /* memset(&G, 0, sizeof(G)); - already is */ \
118} while (0)
119#define outfile (G.outfile )
120#define policyfile (G.policyfile )
121#define rootpath (G.rootpath )
122#define rootpathlen (G.rootpathlen )
123#define count (G.count )
124#define excludeCtr (G.excludeCtr )
125#define errors (G.errors )
126#define verbose (G.verbose )
127#define recurse (G.recurse )
128#define follow_mounts (G.follow_mounts )
129#define expand_realpath (G.expand_realpath )
130#define abort_on_error (G.abort_on_error )
131#define add_assoc (G.add_assoc )
132#define matchpathcon_flags (G.matchpathcon_flags)
133#define dev_id (G.dev_id )
134#define nerr (G.nerr )
135#define excludeArray (G.excludeArray )
136
137/* Must match getopt32 string! */
138enum {
139 OPT_d = (1 << 0),
140 OPT_e = (1 << 1),
141 OPT_f = (1 << 2),
142 OPT_i = (1 << 3),
143 OPT_l = (1 << 4),
144 OPT_n = (1 << 5),
145 OPT_p = (1 << 6),
146 OPT_q = (1 << 7),
147 OPT_r = (1 << 8),
148 OPT_s = (1 << 9),
149 OPT_v = (1 << 10),
150 OPT_o = (1 << 11),
151 OPT_F = (1 << 12),
152 OPT_W = (1 << 13),
153 OPT_c = (1 << 14), /* c only for setfiles */
154 OPT_R = (1 << 14), /* R only for restorecon */
155};
156#define FLAG_d_debug (option_mask32 & OPT_d)
157#define FLAG_e (option_mask32 & OPT_e)
158#define FLAG_f (option_mask32 & OPT_f)
159#define FLAG_i_ignore_enoent (option_mask32 & OPT_i)
160#define FLAG_l_take_log (option_mask32 & OPT_l)
161#define FLAG_n_dry_run (option_mask32 & OPT_n)
162#define FLAG_p_progress (option_mask32 & OPT_p)
163#define FLAG_q_quiet (option_mask32 & OPT_q)
164#define FLAG_r (option_mask32 & OPT_r)
165#define FLAG_s (option_mask32 & OPT_s)
166#define FLAG_v (option_mask32 & OPT_v)
167#define FLAG_o (option_mask32 & OPT_o)
168#define FLAG_F_force (option_mask32 & OPT_F)
169#define FLAG_W_warn_no_match (option_mask32 & OPT_W)
170#define FLAG_c (option_mask32 & OPT_c)
171#define FLAG_R (option_mask32 & OPT_R)
172
173
174static void qprintf(const char *fmt UNUSED_PARAM, ...)
175{
176 /* quiet, do nothing */
177}
178
179static void inc_err(void)
180{
181 nerr++;
182 if (nerr > 9 && !FLAG_d_debug) {
183 bb_error_msg_and_die("exiting after 10 errors");
184 }
185}
186
187static void add_exclude(const char *directory)
188{
189 struct stat sb;
190 size_t len;
191
192 if (directory == NULL || directory[0] != '/') {
193 bb_error_msg_and_die("full path required for exclude: %s", directory);
194 }
195 if (lstat(directory, &sb)) {
196 bb_error_msg("directory \"%s\" not found, ignoring", directory);
197 return;
198 }
199 if ((sb.st_mode & S_IFDIR) == 0) {
200 bb_error_msg("\"%s\" is not a directory: mode %o, ignoring",
201 directory, sb.st_mode);
202 return;
203 }
204 if (excludeCtr == MAX_EXCLUDES) {
205 bb_error_msg_and_die("maximum excludes %d exceeded", MAX_EXCLUDES);
206 }
207
208 len = strlen(directory);
209 while (len > 1 && directory[len - 1] == '/') {
210 len--;
211 }
212 excludeArray[excludeCtr].directory = xstrndup(directory, len);
213 excludeArray[excludeCtr++].size = len;
214}
215
216static bool exclude(const char *file)
217{
218 int i = 0;
219 for (i = 0; i < excludeCtr; i++) {
220 if (strncmp(file, excludeArray[i].directory,
221 excludeArray[i].size) == 0) {
222 if (file[excludeArray[i].size] == '\0'
223 || file[excludeArray[i].size] == '/') {
224 return 1;
225 }
226 }
227 }
228 return 0;
229}
230
231static int match(const char *name, struct stat *sb, char **con)
232{
233 int ret;
234 char path[PATH_MAX + 1];
235 char *tmp_path = xstrdup(name);
236
237 if (excludeCtr > 0 && exclude(name)) {
238 goto err;
239 }
240 ret = lstat(name, sb);
241 if (ret) {
242 if (FLAG_i_ignore_enoent && errno == ENOENT) {
243 free(tmp_path);
244 return 0;
245 }
246 bb_error_msg("stat(%s)", name);
247 goto err;
248 }
249
250 if (expand_realpath) {
251 if (S_ISLNK(sb->st_mode)) {
252 char *p = NULL;
253 char *file_sep;
254
255 size_t len = 0;
256
257 if (verbose > 1)
258 bb_error_msg("warning! %s refers to a symbolic link, not following last component", name);
259
260 file_sep = strrchr(tmp_path, '/');
261 if (file_sep == tmp_path) {
262 file_sep++;
263 path[0] = '\0';
264 p = path;
265 } else if (file_sep) {
266 *file_sep++ = '\0';
267 p = realpath(tmp_path, path);
268 } else {
269 file_sep = tmp_path;
270 p = realpath("./", path);
271 }
272 if (p)
273 len = strlen(p);
274 if (!p || len + strlen(file_sep) + 2 > PATH_MAX) {
275 bb_perror_msg("realpath(%s) failed", name);
276 goto err;
277 }
278 p += len;
279 /* ensure trailing slash of directory name */
280 if (len == 0 || p[-1] != '/') {
281 *p++ = '/';
282 }
283 strcpy(p, file_sep);
284 name = path;
285 if (excludeCtr > 0 && exclude(name))
286 goto err;
287 } else {
288 char *p;
289 p = realpath(name, path);
290 if (!p) {
291 bb_perror_msg("realpath(%s)", name);
292 goto err;
293 }
294 name = p;
295 if (excludeCtr > 0 && exclude(name))
296 goto err;
297 }
298 }
299
300 /* name will be what is matched in the policy */
301 if (NULL != rootpath) {
302 if (0 != strncmp(rootpath, name, rootpathlen)) {
303 bb_error_msg("%s is not located in %s",
304 name, rootpath);
305 goto err;
306 }
307 name += rootpathlen;
308 }
309
310 free(tmp_path);
311 if (rootpath != NULL && name[0] == '\0')
312 /* this is actually the root dir of the alt root */
313 return matchpathcon_index("/", sb->st_mode, con);
314 return matchpathcon_index(name, sb->st_mode, con);
315 err:
316 free(tmp_path);
317 return -1;
318}
319
320/* Compare two contexts to see if their differences are "significant",
321 * or whether the only difference is in the user. */
322static bool only_changed_user(const char *a, const char *b)
323{
324 if (FLAG_F_force)
325 return 0;
326 if (!a || !b)
327 return 0;
328 a = strchr(a, ':'); /* Rest of the context after the user */
329 b = strchr(b, ':');
330 if (!a || !b)
331 return 0;
332 return (strcmp(a, b) == 0);
333}
334
335static int restore(const char *file)
336{
337 char *my_file;
338 struct stat my_sb;
339 int i, j, ret;
340 char *context = NULL;
341 char *newcon = NULL;
342 bool user_only_changed = 0;
343 int retval = 0;
344
345 my_file = bb_simplify_path(file);
346
347 i = match(my_file, &my_sb, &newcon);
348
349 if (i < 0) /* No matching specification. */
350 goto out;
351
352 if (FLAG_p_progress) {
353 count++;
354 if (count % 0x400 == 0) { /* every 1024 times */
355 count = (count % (80*0x400));
356 if (count == 0)
357 bb_putchar('\n');
358 bb_putchar('*');
359 fflush_all();
360 }
361 }
362
363 /*
364 * Try to add an association between this inode and
365 * this specification. If there is already an association
366 * for this inode and it conflicts with this specification,
367 * then use the last matching specification.
368 */
369 if (add_assoc) {
370 j = matchpathcon_filespec_add(my_sb.st_ino, i, my_file);
371 if (j < 0)
372 goto err;
373
374 if (j != i) {
375 /* There was already an association and it took precedence. */
376 goto out;
377 }
378 }
379
380 if (FLAG_d_debug)
381 printf("%s: %s matched by %s\n", applet_name, my_file, newcon);
382
383 /* Get the current context of the file. */
384 ret = lgetfilecon_raw(my_file, &context);
385 if (ret < 0) {
386 if (errno == ENODATA) {
387 context = NULL; /* paranoia */
388 } else {
389 bb_perror_msg("lgetfilecon_raw on %s", my_file);
390 goto err;
391 }
392 user_only_changed = 0;
393 } else
394 user_only_changed = only_changed_user(context, newcon);
395
396 /*
397 * Do not relabel the file if the matching specification is
398 * <<none>> or the file is already labeled according to the
399 * specification.
400 */
401 if ((strcmp(newcon, "<<none>>") == 0)
402 || (context && (strcmp(context, newcon) == 0) && !FLAG_F_force)) {
403 goto out;
404 }
405
406 if (!FLAG_F_force && context && (is_context_customizable(context) > 0)) {
407 if (verbose > 1) {
408 bb_error_msg("skipping %s. %s is customizable_types",
409 my_file, context);
410 }
411 goto out;
412 }
413
414 if (verbose) {
415 /* If we're just doing "-v", trim out any relabels where
416 * the user has changed but the role and type are the
417 * same. For "-vv", emit everything. */
418 if (verbose > 1 || !user_only_changed) {
419 printf("%s: reset %s context %s->%s\n",
420 applet_name, my_file, context ? context : "", newcon);
421 }
422 }
423
424 if (FLAG_l_take_log && !user_only_changed) {
425 if (context)
426 printf("relabeling %s from %s to %s\n", my_file, context, newcon);
427 else
428 printf("labeling %s to %s\n", my_file, newcon);
429 }
430
431 if (outfile && !user_only_changed)
432 fprintf(outfile, "%s\n", my_file);
433
434 /*
435 * Do not relabel the file if -n was used.
436 */
437 if (FLAG_n_dry_run || user_only_changed)
438 goto out;
439
440 /*
441 * Relabel the file to the specified context.
442 */
443 ret = lsetfilecon(my_file, newcon);
444 if (ret) {
445 bb_perror_msg("lsetfileconon(%s,%s)", my_file, newcon);
446 goto err;
447 }
448
449 out:
450 freecon(context);
451 freecon(newcon);
452 free(my_file);
453 return retval;
454 err:
455 retval--; /* -1 */
456 goto out;
457}
458
459/*
460 * Apply the last matching specification to a file.
461 * This function is called by recursive_action on each file during
462 * the directory traversal.
463 */
464static int FAST_FUNC apply_spec(
465 const char *file,
466 struct stat *sb,
467 void *userData UNUSED_PARAM,
468 int depth UNUSED_PARAM)
469{
470 if (!follow_mounts) {
471 /* setfiles does not process across different mount points */
472 if (sb->st_dev != dev_id) {
473 return SKIP;
474 }
475 }
476 errors |= restore(file);
477 if (abort_on_error && errors)
478 return FALSE;
479 return TRUE;
480}
481
482
483static int canoncon(const char *path, unsigned lineno, char **contextp)
484{
485 static const char err_msg[] ALIGN1 = "%s: line %u has invalid context %s";
486
487 char *tmpcon;
488 char *context = *contextp;
489 int invalid = 0;
490
491#if ENABLE_FEATURE_SETFILES_CHECK_OPTION
492 if (policyfile) {
493 if (sepol_check_context(context) >= 0)
494 return 0;
495 /* Exit immediately if we're in checking mode. */
496 bb_error_msg_and_die(err_msg, path, lineno, context);
497 }
498#endif
499
500 if (security_canonicalize_context_raw(context, &tmpcon) < 0) {
501 if (errno != ENOENT) {
502 invalid = 1;
503 inc_err();
504 }
505 } else {
506 free(context);
507 *contextp = tmpcon;
508 }
509
510 if (invalid) {
511 bb_error_msg(err_msg, path, lineno, context);
512 }
513
514 return invalid;
515}
516
517static int process_one(char *name)
518{
519 struct stat sb;
520 int rc;
521
522 rc = lstat(name, &sb);
523 if (rc < 0) {
524 if (FLAG_i_ignore_enoent && errno == ENOENT)
525 return 0;
526 bb_perror_msg("stat(%s)", name);
527 goto err;
528 }
529 dev_id = sb.st_dev;
530
531 if (S_ISDIR(sb.st_mode) && recurse) {
532 if (recursive_action(name,
533 ACTION_RECURSE,
534 apply_spec,
535 apply_spec,
536 NULL, 0) != TRUE
537 ) {
538 bb_error_msg("error while labeling %s", name);
539 goto err;
540 }
541 } else {
542 rc = restore(name);
543 if (rc)
544 goto err;
545 }
546
547 out:
548 if (add_assoc) {
549 if (FLAG_q_quiet)
550 set_matchpathcon_printf(&qprintf);
551 matchpathcon_filespec_eval();
552 set_matchpathcon_printf(NULL);
553 matchpathcon_filespec_destroy();
554 }
555
556 return rc;
557
558 err:
559 rc = -1;
560 goto out;
561}
562
563int setfiles_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
564int setfiles_main(int argc UNUSED_PARAM, char **argv)
565{
566 struct stat sb;
567 int rc, i = 0;
568 const char *input_filename = NULL;
569 char *buf = NULL;
570 size_t buf_len;
571 int flags;
572 llist_t *exclude_dir = NULL;
573 char *out_filename = NULL;
574
575 INIT_G();
576
577 if (applet_name[0] == 's') { /* "setfiles" */
578 /*
579 * setfiles:
580 * Recursive descent,
581 * Does not expand paths via realpath,
582 * Aborts on errors during the file tree walk,
583 * Try to track inode associations for conflict detection,
584 * Does not follow mounts,
585 * Validates all file contexts at init time.
586 */
587 recurse = 1;
588 abort_on_error = 1;
589 add_assoc = 1;
590 /* follow_mounts = 0; - already is */
591 matchpathcon_flags = MATCHPATHCON_VALIDATE | MATCHPATHCON_NOTRANS;
592 } else {
593 /*
594 * restorecon:
595 * No recursive descent unless -r/-R,
596 * Expands paths via realpath,
597 * Do not abort on errors during the file tree walk,
598 * Do not try to track inode associations for conflict detection,
599 * Follows mounts,
600 * Does lazy validation of contexts upon use.
601 */
602 expand_realpath = 1;
603 follow_mounts = 1;
604 matchpathcon_flags = MATCHPATHCON_NOTRANS;
605 /* restorecon only */
606 selinux_or_die();
607 }
608
609 set_matchpathcon_flags(matchpathcon_flags);
610
611 opt_complementary = "vv:v--p:p--v:v--q:q--v";
612 /* Option order must match OPT_x definitions! */
613 if (applet_name[0] == 'r') { /* restorecon */
614 flags = getopt32(argv, "de:*f:ilnpqrsvo:FWR",
615 &exclude_dir, &input_filename, &out_filename, &verbose);
616 } else { /* setfiles */
617 flags = getopt32(argv, "de:*f:ilnpqr:svo:FW"
618 IF_FEATURE_SETFILES_CHECK_OPTION("c:"),
619 &exclude_dir, &input_filename, &rootpath, &out_filename,
620 IF_FEATURE_SETFILES_CHECK_OPTION(&policyfile,)
621 &verbose);
622 }
623 argv += optind;
624
625#if ENABLE_FEATURE_SETFILES_CHECK_OPTION
626 if ((applet_name[0] == 's') && (flags & OPT_c)) {
627 FILE *policystream;
628
629 policystream = xfopen_for_read(policyfile);
630 if (sepol_set_policydb_from_file(policystream) < 0) {
631 bb_error_msg_and_die("sepol_set_policydb_from_file on %s", policyfile);
632 }
633 fclose(policystream);
634
635 /* Only process the specified file_contexts file, not
636 * any .homedirs or .local files, and do not perform
637 * context translations. */
638 set_matchpathcon_flags(MATCHPATHCON_BASEONLY |
639 MATCHPATHCON_NOTRANS |
640 MATCHPATHCON_VALIDATE);
641 }
642#endif
643
644 while (exclude_dir)
645 add_exclude(llist_pop(&exclude_dir));
646
647 if (flags & OPT_o) {
648 outfile = stdout;
649 if (NOT_LONE_CHAR(out_filename, '-')) {
650 outfile = xfopen_for_write(out_filename);
651 }
652 }
653 if (applet_name[0] == 'r') { /* restorecon */
654 if (flags & (OPT_r | OPT_R))
655 recurse = 1;
656 } else { /* setfiles */
657 if (flags & OPT_r)
658 rootpathlen = strlen(rootpath);
659 }
660 if (flags & OPT_s) {
661 input_filename = "-";
662 add_assoc = 0;
663 }
664
665 if (applet_name[0] == 's') { /* setfiles */
666 /* Use our own invalid context checking function so that
667 * we can support either checking against the active policy or
668 * checking against a binary policy file. */
669 set_matchpathcon_canoncon(&canoncon);
670 if (!argv[0])
671 bb_show_usage();
672 xstat(argv[0], &sb);
673 if (!S_ISREG(sb.st_mode)) {
674 bb_error_msg_and_die("spec file %s is not a regular file", argv[0]);
675 }
676 /* Load the file contexts configuration and check it. */
677 rc = matchpathcon_init(argv[0]);
678 if (rc < 0) {
679 bb_simple_perror_msg_and_die(argv[0]);
680 }
681 if (nerr)
682 exit(EXIT_FAILURE);
683 argv++;
684 }
685
686 if (input_filename) {
687 ssize_t len;
688 FILE *f = stdin;
689
690 if (NOT_LONE_CHAR(input_filename, '-'))
691 f = xfopen_for_read(input_filename);
692 while ((len = getline(&buf, &buf_len, f)) > 0) {
693 buf[len - 1] = '\0';
694 errors |= process_one(buf);
695 }
696 if (ENABLE_FEATURE_CLEAN_UP)
697 fclose_if_not_stdin(f);
698 } else {
699 if (!argv[0])
700 bb_show_usage();
701 for (i = 0; argv[i]; i++) {
702 errors |= process_one(argv[i]);
703 }
704 }
705
706 if (FLAG_W_warn_no_match)
707 matchpathcon_checkmatches(argv[0]);
708
709 if (ENABLE_FEATURE_CLEAN_UP && outfile)
710 fclose(outfile);
711
712 return errors;
713}
714