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>
8 #if ENABLE_FEATURE_SETFILES_CHECK_OPTION
9 #include <sepol/sepol.h>
12 #define MAX_EXCLUDES 50
27 int verbose; /* getopt32 uses it, has to be int */
33 //smallint ignore_enoent;
35 //smallint warn_no_match;
36 smallint recurse; /* Recursive descent */
37 smallint follow_mounts;
38 /* Behavior flags determined based on setfiles vs. restorecon */
39 smallint expand_realpath; /* Expand paths via realpath */
40 smallint abort_on_error; /* Abort the file tree walk upon an error */
41 int add_assoc; /* Track inode associations for conflict detection */
42 int matchpathcon_flags; /* Flags to matchpathcon */
43 dev_t dev_id; /* Device id where target file exists */
45 struct edir excludeArray[MAX_EXCLUDES];
48 #define G (*(struct globals*)&bb_common_bufsiz1)
49 void BUG_setfiles_globals_too_big(void);
50 #define INIT_G() do { \
51 if (sizeof(G) > COMMON_BUFSIZE) \
52 BUG_setfiles_globals_too_big(); \
53 /* memset(&G, 0, sizeof(G)); - already is */ \
55 #define outfile (G.outfile )
56 #define policyfile (G.policyfile )
57 #define rootpath (G.rootpath )
58 #define rootpathlen (G.rootpathlen )
59 #define count (G.count )
60 #define excludeCtr (G.excludeCtr )
61 #define errors (G.errors )
62 #define verbose (G.verbose )
63 //#define force (G.force )
64 //#define progress (G.progress )
65 //#define debug (G.debug )
66 //#define dry_run (G.dry_run )
67 //#define quiet (G.quiet )
68 //#define ignore_enoent (G.ignore_enoent )
69 //#define take_log (G.take_log )
70 //#define warn_no_match (G.warn_no_match )
71 #define recurse (G.recurse )
72 #define follow_mounts (G.follow_mounts )
73 #define expand_realpath (G.expand_realpath )
74 #define abort_on_error (G.abort_on_error )
75 #define add_assoc (G.add_assoc )
76 #define matchpathcon_flags (G.matchpathcon_flags)
77 #define dev_id (G.dev_id )
78 #define nerr (G.nerr )
79 #define excludeArray (G.excludeArray )
81 /* Must match getopt32 string! */
97 OPT_c = (1 << 14), /* c only for setfiles */
98 OPT_R = (1 << 14), /* R only for restorecon */
100 #define FLAG_d_debug (option_mask32 & OPT_d)
101 #define FLAG_e (option_mask32 & OPT_e)
102 #define FLAG_f (option_mask32 & OPT_f)
103 #define FLAG_i_ignore_enoent (option_mask32 & OPT_i)
104 #define FLAG_l_take_log (option_mask32 & OPT_l)
105 #define FLAG_n_dry_run (option_mask32 & OPT_n)
106 #define FLAG_p_progress (option_mask32 & OPT_p)
107 #define FLAG_q_quiet (option_mask32 & OPT_q)
108 #define FLAG_r (option_mask32 & OPT_r)
109 #define FLAG_s (option_mask32 & OPT_s)
110 #define FLAG_v (option_mask32 & OPT_v)
111 #define FLAG_o (option_mask32 & OPT_o)
112 #define FLAG_F_force (option_mask32 & OPT_F)
113 #define FLAG_W_warn_no_match (option_mask32 & OPT_W)
114 #define FLAG_c (option_mask32 & OPT_c)
115 #define FLAG_R (option_mask32 & OPT_R)
118 static void qprintf(const char *fmt, ...)
120 /* quiet, do nothing */
123 static void inc_err(void)
126 if (nerr > 9 && !FLAG_d_debug) {
127 bb_error_msg_and_die("exiting after 10 errors");
131 static bool add_exclude(const char *const directory)
136 if (directory == NULL || directory[0] != '/') {
137 bb_error_msg("full path required for exclude: %s", directory);
140 if (lstat(directory, &sb)) {
141 bb_error_msg("directory \"%s\" not found, ignoring", directory);
144 if ((sb.st_mode & S_IFDIR) == 0) {
145 bb_error_msg("\"%s\" is not a directory: mode %o, ignoring",
146 directory, sb.st_mode);
149 if (excludeCtr == MAX_EXCLUDES) {
150 bb_error_msg("maximum excludes %d exceeded", MAX_EXCLUDES);
154 len = strlen(directory);
155 while (len > 1 && directory[len - 1] == '/') {
158 excludeArray[excludeCtr].directory = xstrndup(directory, len);
159 excludeArray[excludeCtr++].size = len;
164 static bool exclude(const char *file)
167 for (i = 0; i < excludeCtr; i++) {
168 if (strncmp(file, excludeArray[i].directory,
169 excludeArray[i].size) == 0) {
170 if (file[excludeArray[i].size] == '\0'
171 || file[excludeArray[i].size] == '/') {
179 static int match(const char *name, struct stat *sb, char **con)
182 char path[PATH_MAX + 1];
183 char *tmp_path = xstrdup(name);
185 if (excludeCtr > 0 && exclude(name)) {
188 ret = lstat(name, sb);
190 if (FLAG_i_ignore_enoent && errno == ENOENT) {
194 bb_error_msg("stat(%s)", name);
198 if (expand_realpath) {
199 if (S_ISLNK(sb->st_mode)) {
206 bb_error_msg("warning! %s refers to a symbolic link, not following last component", name);
208 file_sep = strrchr(tmp_path, '/');
209 if (file_sep == tmp_path) {
213 } else if (file_sep) {
215 p = realpath(tmp_path, path);
218 p = realpath("./", path);
222 if (!p || len + strlen(file_sep) + 2 > PATH_MAX) {
223 bb_perror_msg("realpath(%s) failed", name);
227 /* ensure trailing slash of directory name */
228 if (len == 0 || p[-1] != '/') {
233 if (excludeCtr > 0 && exclude(name))
238 p = realpath(name, path);
240 bb_perror_msg("realpath(%s)", name);
244 if (excludeCtr > 0 && exclude(name))
249 /* name will be what is matched in the policy */
250 if (NULL != rootpath) {
251 if (0 != strncmp(rootpath, name, rootpathlen)) {
252 bb_error_msg("%s is not located in %s",
260 if (rootpath != NULL && name[0] == '\0')
261 /* this is actually the root dir of the alt root */
262 return matchpathcon_index("/", sb->st_mode, con);
263 return matchpathcon_index(name, sb->st_mode, con);
269 /* Compare two contexts to see if their differences are "significant",
270 * or whether the only difference is in the user. */
271 static bool only_changed_user(const char *a, const char *b)
277 a = strchr(a, ':'); /* Rest of the context after the user */
281 return (strcmp(a, b) == 0);
284 static int restore(const char *file)
286 char *my_file = xstrdup(file);
287 char *my_file_orig = my_file;
290 char *context = NULL;
292 bool user_only_changed = 0;
293 size_t len = strlen(my_file);
296 /* Skip the extra slashes at the beginning and end, if present. */
297 if (file[0] == '/' && file[1] == '/')
299 if (len > 1 && my_file[len - 1] == '/')
300 my_file[len - 1] = '\0';
302 i = match(my_file, &my_sb, &newcon);
304 if (i < 0) /* No matching specification. */
308 if (FLAG_p_progress) {
310 if (count % 0x400 == 0) { /* every 1024 times */
311 count = (count % (80*0x400));
320 * Try to add an association between this inode and
321 * this specification. If there is already an association
322 * for this inode and it conflicts with this specification,
323 * then use the last matching specification.
326 j = matchpathcon_filespec_add(my_sb.st_ino, i, my_file);
331 /* There was already an association and it took precedence. */
337 printf("%s: %s matched by %s\n", applet_name, my_file, newcon);
339 /* Get the current context of the file. */
340 ret = lgetfilecon_raw(my_file, &context);
342 if (errno == ENODATA) {
343 context = NULL; /* paranoia */
345 bb_perror_msg("lgetfilecon_raw on %s", my_file);
348 user_only_changed = 0;
350 user_only_changed = only_changed_user(context, newcon);
353 * Do not relabel the file if the matching specification is
354 * <<none>> or the file is already labeled according to the
357 if ((strcmp(newcon, "<<none>>") == 0)
358 || (context && (strcmp(context, newcon) == 0) && !FLAG_F_force)) {
362 if (!FLAG_F_force && context && (is_context_customizable(context) > 0)) {
364 bb_error_msg("skipping %s. %s is customizable_types",
371 /* If we're just doing "-v", trim out any relabels where
372 * the user has changed but the role and type are the
373 * same. For "-vv", emit everything. */
374 if (verbose > 1 || !user_only_changed) {
375 bb_info_msg("%s: reset %s context %s->%s",
376 applet_name, my_file, context ?: "", newcon);
380 if (FLAG_l_take_log && !user_only_changed) {
382 bb_info_msg("relabeling %s from %s to %s", my_file, context, newcon);
384 bb_info_msg("labeling %s to %s", my_file, newcon);
387 if (outfile && !user_only_changed)
388 fprintf(outfile, "%s\n", my_file);
391 * Do not relabel the file if -n was used.
393 if (FLAG_n_dry_run || user_only_changed)
397 * Relabel the file to the specified context.
399 ret = lsetfilecon(my_file, newcon);
401 bb_perror_msg("lsetfileconon(%s,%s)", my_file, newcon);
416 * Apply the last matching specification to a file.
417 * This function is called by recursive_action on each file during
418 * the directory traversal.
420 static int apply_spec(const char *file,
421 struct stat *sb, void *userData, int depth)
423 if (!follow_mounts) {
424 /* setfiles does not process across different mount points */
425 if (sb->st_dev != dev_id) {
429 errors |= restore(file);
430 if (abort_on_error && errors)
436 static int canoncon(const char *path, unsigned lineno, char **contextp)
438 static const char err_msg[] = "%s: line %u has invalid context %s";
441 char *context = *contextp;
444 #if ENABLE_FEATURE_SETFILES_CHECK_OPTION
446 if (sepol_check_context(context) >= 0)
448 /* Exit immediately if we're in checking mode. */
449 bb_error_msg_and_die(err_msg, path, lineno, context);
453 if (security_canonicalize_context_raw(context, &tmpcon) < 0) {
454 if (errno != ENOENT) {
464 bb_error_msg(err_msg, path, lineno, context);
470 static int process_one(char *name)
475 rc = lstat(name, &sb);
477 if (FLAG_i_ignore_enoent && errno == ENOENT)
479 bb_perror_msg("stat(%s)", name);
484 if (S_ISDIR(sb.st_mode) && recurse) {
485 if (recursive_action(name,
490 bb_error_msg("error while labeling %s", name);
502 set_matchpathcon_printf(&qprintf);
503 matchpathcon_filespec_eval();
504 set_matchpathcon_printf(NULL);
505 matchpathcon_filespec_destroy();
515 int setfiles_main(int argc, char **argv);
516 int setfiles_main(int argc, char **argv)
520 const char *input_filename = NULL;
521 int use_input_file = 0;
525 llist_t *exclude_dir = NULL;
526 char *out_filename = NULL;
530 if (applet_name[0] == 's') { /* "setfiles" */
534 * Does not expand paths via realpath,
535 * Aborts on errors during the file tree walk,
536 * Try to track inode associations for conflict detection,
537 * Does not follow mounts,
538 * Validates all file contexts at init time.
543 /* follow_mounts = 0; - already is */
544 matchpathcon_flags = MATCHPATHCON_VALIDATE | MATCHPATHCON_NOTRANS;
548 * No recursive descent unless -r/-R,
549 * Expands paths via realpath,
550 * Do not abort on errors during the file tree walk,
551 * Do not try to track inode associations for conflict detection,
553 * Does lazy validation of contexts upon use.
557 matchpathcon_flags = MATCHPATHCON_NOTRANS;
558 /* restorecon only */
562 set_matchpathcon_flags(matchpathcon_flags);
564 opt_complementary = "e::vv:v--p:p--v:v--q:q--v";
565 /* Option order must match OPT_x definitions! */
566 if (applet_name[0] == 'r') { /* restorecon */
567 flags = getopt32(argc, argv, "de:f:ilnpqrsvo:FWR",
568 &exclude_dir, &input_filename, &out_filename, &verbose);
569 } else { /* setfiles */
570 flags = getopt32(argc, argv, "de:f:ilnpqr:svo:FW"
571 USE_FEATURE_SETFILES_CHECK_OPTION("c:"),
572 &exclude_dir, &input_filename, &rootpath, &out_filename,
573 USE_FEATURE_SETFILES_CHECK_OPTION(&policyfile,)
577 #if ENABLE_FEATURE_SETFILES_CHECK_OPTION
578 if ((applet_name[0] == 's') && (flags & OPT_c)) {
581 policystream = xfopen(policyfile, "r");
582 if (sepol_set_policydb_from_file(policystream) < 0) {
583 bb_error_msg_and_die("sepol_set_policydb_from_file on %s", policyfile);
585 fclose(policystream);
587 /* Only process the specified file_contexts file, not
588 any .homedirs or .local files, and do not perform
589 context translations. */
590 set_matchpathcon_flags(MATCHPATHCON_BASEONLY |
591 MATCHPATHCON_NOTRANS |
592 MATCHPATHCON_VALIDATE);
596 //if (flags & OPT_d) {
600 if (exclude_dir == NULL) {
603 while (exclude_dir) {
604 if (add_exclude(llist_pop(&exclude_dir)))
608 //if (flags & OPT_i) {
609 // ignore_enoent = 1;
611 //if (flags & OPT_l) {
614 //if (flags & OPT_F) {
617 //if (flags & OPT_n) {
622 if (NOT_LONE_CHAR(out_filename, '-')) {
623 outfile = xfopen(out_filename, "w");
626 //if (flags & OPT_q) {
629 if (applet_name[0] == 'r') { /* restorecon */
630 if (flags & (OPT_r | OPT_R))
632 } else { /* setfiles */
634 rootpathlen = strlen(rootpath);
638 input_filename = "-";
641 //if (flags & OPT_p) {
644 //if (flags & OPT_W) {
645 // warn_no_match = 1;
648 if (applet_name[0] == 's') { /* setfiles */
649 /* Use our own invalid context checking function so that
650 we can support either checking against the active policy or
651 checking against a binary policy file. */
652 set_matchpathcon_canoncon(&canoncon);
655 if (stat(argv[optind], &sb) < 0) {
656 bb_perror_msg_and_die("%s", argv[optind]);
658 if (!S_ISREG(sb.st_mode)) {
659 bb_error_msg_and_die("spec file %s is not a regular file", argv[optind]);
661 /* Load the file contexts configuration and check it. */
662 rc = matchpathcon_init(argv[optind]);
664 bb_perror_msg_and_die("%s", argv[optind]);
673 if (use_input_file) {
677 if (NOT_LONE_CHAR(input_filename, '-'))
678 f = xfopen(input_filename, "r");
679 while ((len = getline(&buf, &buf_len, f)) > 0) {
681 errors |= process_one(buf);
683 if (ENABLE_FEATURE_CLEAN_UP)
684 fclose_if_not_stdin(f);
688 for (i = optind; i < argc; i++) {
689 errors |= process_one(argv[i]);
693 if (FLAG_W_warn_no_match)
694 matchpathcon_checkmatches(argv[0]);
696 if (ENABLE_FEATURE_CLEAN_UP && outfile)