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 */
28 smallint recurse; /* Recursive descent */
29 smallint follow_mounts;
30 /* Behavior flags determined based on setfiles vs. restorecon */
31 smallint expand_realpath; /* Expand paths via realpath */
32 smallint abort_on_error; /* Abort the file tree walk upon an error */
33 int add_assoc; /* Track inode associations for conflict detection */
34 int matchpathcon_flags; /* Flags to matchpathcon */
35 dev_t dev_id; /* Device id where target file exists */
37 struct edir excludeArray[MAX_EXCLUDES];
39 #define G (*(struct globals*)&bb_common_bufsiz1)
40 void BUG_setfiles_globals_too_big(void);
41 #define INIT_G() do { \
42 if (sizeof(G) > COMMON_BUFSIZE) \
43 BUG_setfiles_globals_too_big(); \
44 /* memset(&G, 0, sizeof(G)); - already is */ \
46 #define outfile (G.outfile )
47 #define policyfile (G.policyfile )
48 #define rootpath (G.rootpath )
49 #define rootpathlen (G.rootpathlen )
50 #define count (G.count )
51 #define excludeCtr (G.excludeCtr )
52 #define errors (G.errors )
53 #define verbose (G.verbose )
54 #define recurse (G.recurse )
55 #define follow_mounts (G.follow_mounts )
56 #define expand_realpath (G.expand_realpath )
57 #define abort_on_error (G.abort_on_error )
58 #define add_assoc (G.add_assoc )
59 #define matchpathcon_flags (G.matchpathcon_flags)
60 #define dev_id (G.dev_id )
61 #define nerr (G.nerr )
62 #define excludeArray (G.excludeArray )
64 /* Must match getopt32 string! */
80 OPT_c = (1 << 14), /* c only for setfiles */
81 OPT_R = (1 << 14), /* R only for restorecon */
83 #define FLAG_d_debug (option_mask32 & OPT_d)
84 #define FLAG_e (option_mask32 & OPT_e)
85 #define FLAG_f (option_mask32 & OPT_f)
86 #define FLAG_i_ignore_enoent (option_mask32 & OPT_i)
87 #define FLAG_l_take_log (option_mask32 & OPT_l)
88 #define FLAG_n_dry_run (option_mask32 & OPT_n)
89 #define FLAG_p_progress (option_mask32 & OPT_p)
90 #define FLAG_q_quiet (option_mask32 & OPT_q)
91 #define FLAG_r (option_mask32 & OPT_r)
92 #define FLAG_s (option_mask32 & OPT_s)
93 #define FLAG_v (option_mask32 & OPT_v)
94 #define FLAG_o (option_mask32 & OPT_o)
95 #define FLAG_F_force (option_mask32 & OPT_F)
96 #define FLAG_W_warn_no_match (option_mask32 & OPT_W)
97 #define FLAG_c (option_mask32 & OPT_c)
98 #define FLAG_R (option_mask32 & OPT_R)
101 static void qprintf(const char *fmt UNUSED_PARAM, ...)
103 /* quiet, do nothing */
106 static void inc_err(void)
109 if (nerr > 9 && !FLAG_d_debug) {
110 bb_error_msg_and_die("exiting after 10 errors");
114 static void add_exclude(const char *directory)
119 if (directory == NULL || directory[0] != '/') {
120 bb_error_msg_and_die("full path required for exclude: %s", directory);
123 if (lstat(directory, &sb)) {
124 bb_error_msg("directory \"%s\" not found, ignoring", directory);
127 if ((sb.st_mode & S_IFDIR) == 0) {
128 bb_error_msg("\"%s\" is not a directory: mode %o, ignoring",
129 directory, sb.st_mode);
132 if (excludeCtr == MAX_EXCLUDES) {
133 bb_error_msg_and_die("maximum excludes %d exceeded", MAX_EXCLUDES);
136 len = strlen(directory);
137 while (len > 1 && directory[len - 1] == '/') {
140 excludeArray[excludeCtr].directory = xstrndup(directory, len);
141 excludeArray[excludeCtr++].size = len;
144 static bool exclude(const char *file)
147 for (i = 0; i < excludeCtr; i++) {
148 if (strncmp(file, excludeArray[i].directory,
149 excludeArray[i].size) == 0) {
150 if (file[excludeArray[i].size] == '\0'
151 || file[excludeArray[i].size] == '/') {
159 static int match(const char *name, struct stat *sb, char **con)
162 char path[PATH_MAX + 1];
163 char *tmp_path = xstrdup(name);
165 if (excludeCtr > 0 && exclude(name)) {
168 ret = lstat(name, sb);
170 if (FLAG_i_ignore_enoent && errno == ENOENT) {
174 bb_error_msg("stat(%s)", name);
178 if (expand_realpath) {
179 if (S_ISLNK(sb->st_mode)) {
186 bb_error_msg("warning! %s refers to a symbolic link, not following last component", name);
188 file_sep = strrchr(tmp_path, '/');
189 if (file_sep == tmp_path) {
193 } else if (file_sep) {
195 p = realpath(tmp_path, path);
198 p = realpath("./", path);
202 if (!p || len + strlen(file_sep) + 2 > PATH_MAX) {
203 bb_perror_msg("realpath(%s) failed", name);
207 /* ensure trailing slash of directory name */
208 if (len == 0 || p[-1] != '/') {
213 if (excludeCtr > 0 && exclude(name))
218 p = realpath(name, path);
220 bb_perror_msg("realpath(%s)", name);
224 if (excludeCtr > 0 && exclude(name))
229 /* name will be what is matched in the policy */
230 if (NULL != rootpath) {
231 if (0 != strncmp(rootpath, name, rootpathlen)) {
232 bb_error_msg("%s is not located in %s",
240 if (rootpath != NULL && name[0] == '\0')
241 /* this is actually the root dir of the alt root */
242 return matchpathcon_index("/", sb->st_mode, con);
243 return matchpathcon_index(name, sb->st_mode, con);
249 /* Compare two contexts to see if their differences are "significant",
250 * or whether the only difference is in the user. */
251 static bool only_changed_user(const char *a, const char *b)
257 a = strchr(a, ':'); /* Rest of the context after the user */
261 return (strcmp(a, b) == 0);
264 static int restore(const char *file)
269 char *context = NULL;
271 bool user_only_changed = 0;
274 my_file = bb_simplify_path(file);
276 i = match(my_file, &my_sb, &newcon);
278 if (i < 0) /* No matching specification. */
281 if (FLAG_p_progress) {
283 if (count % 0x400 == 0) { /* every 1024 times */
284 count = (count % (80*0x400));
293 * Try to add an association between this inode and
294 * this specification. If there is already an association
295 * for this inode and it conflicts with this specification,
296 * then use the last matching specification.
299 j = matchpathcon_filespec_add(my_sb.st_ino, i, my_file);
304 /* There was already an association and it took precedence. */
310 printf("%s: %s matched by %s\n", applet_name, my_file, newcon);
312 /* Get the current context of the file. */
313 ret = lgetfilecon_raw(my_file, &context);
315 if (errno == ENODATA) {
316 context = NULL; /* paranoia */
318 bb_perror_msg("lgetfilecon_raw on %s", my_file);
321 user_only_changed = 0;
323 user_only_changed = only_changed_user(context, newcon);
326 * Do not relabel the file if the matching specification is
327 * <<none>> or the file is already labeled according to the
330 if ((strcmp(newcon, "<<none>>") == 0)
331 || (context && (strcmp(context, newcon) == 0) && !FLAG_F_force)) {
335 if (!FLAG_F_force && context && (is_context_customizable(context) > 0)) {
337 bb_error_msg("skipping %s. %s is customizable_types",
344 /* If we're just doing "-v", trim out any relabels where
345 * the user has changed but the role and type are the
346 * same. For "-vv", emit everything. */
347 if (verbose > 1 || !user_only_changed) {
348 bb_info_msg("%s: reset %s context %s->%s",
349 applet_name, my_file, context ? context : "", newcon);
353 if (FLAG_l_take_log && !user_only_changed) {
355 bb_info_msg("relabeling %s from %s to %s", my_file, context, newcon);
357 bb_info_msg("labeling %s to %s", my_file, newcon);
360 if (outfile && !user_only_changed)
361 fprintf(outfile, "%s\n", my_file);
364 * Do not relabel the file if -n was used.
366 if (FLAG_n_dry_run || user_only_changed)
370 * Relabel the file to the specified context.
372 ret = lsetfilecon(my_file, newcon);
374 bb_perror_msg("lsetfileconon(%s,%s)", my_file, newcon);
389 * Apply the last matching specification to a file.
390 * This function is called by recursive_action on each file during
391 * the directory traversal.
393 static int FAST_FUNC apply_spec(
396 void *userData UNUSED_PARAM,
397 int depth UNUSED_PARAM)
399 if (!follow_mounts) {
400 /* setfiles does not process across different mount points */
401 if (sb->st_dev != dev_id) {
405 errors |= restore(file);
406 if (abort_on_error && errors)
412 static int canoncon(const char *path, unsigned lineno, char **contextp)
414 static const char err_msg[] ALIGN1 = "%s: line %u has invalid context %s";
417 char *context = *contextp;
420 #if ENABLE_FEATURE_SETFILES_CHECK_OPTION
422 if (sepol_check_context(context) >= 0)
424 /* Exit immediately if we're in checking mode. */
425 bb_error_msg_and_die(err_msg, path, lineno, context);
429 if (security_canonicalize_context_raw(context, &tmpcon) < 0) {
430 if (errno != ENOENT) {
440 bb_error_msg(err_msg, path, lineno, context);
446 static int process_one(char *name)
451 rc = lstat(name, &sb);
453 if (FLAG_i_ignore_enoent && errno == ENOENT)
455 bb_perror_msg("stat(%s)", name);
460 if (S_ISDIR(sb.st_mode) && recurse) {
461 if (recursive_action(name,
466 bb_error_msg("error while labeling %s", name);
478 set_matchpathcon_printf(&qprintf);
479 matchpathcon_filespec_eval();
480 set_matchpathcon_printf(NULL);
481 matchpathcon_filespec_destroy();
491 int setfiles_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
492 int setfiles_main(int argc UNUSED_PARAM, char **argv)
496 const char *input_filename = NULL;
500 llist_t *exclude_dir = NULL;
501 char *out_filename = NULL;
505 if (applet_name[0] == 's') { /* "setfiles" */
509 * Does not expand paths via realpath,
510 * Aborts on errors during the file tree walk,
511 * Try to track inode associations for conflict detection,
512 * Does not follow mounts,
513 * Validates all file contexts at init time.
518 /* follow_mounts = 0; - already is */
519 matchpathcon_flags = MATCHPATHCON_VALIDATE | MATCHPATHCON_NOTRANS;
523 * No recursive descent unless -r/-R,
524 * Expands paths via realpath,
525 * Do not abort on errors during the file tree walk,
526 * Do not try to track inode associations for conflict detection,
528 * Does lazy validation of contexts upon use.
532 matchpathcon_flags = MATCHPATHCON_NOTRANS;
533 /* restorecon only */
537 set_matchpathcon_flags(matchpathcon_flags);
539 opt_complementary = "e::vv:v--p:p--v:v--q:q--v";
540 /* Option order must match OPT_x definitions! */
541 if (applet_name[0] == 'r') { /* restorecon */
542 flags = getopt32(argv, "de:f:ilnpqrsvo:FWR",
543 &exclude_dir, &input_filename, &out_filename, &verbose);
544 } else { /* setfiles */
545 flags = getopt32(argv, "de:f:ilnpqr:svo:FW"
546 IF_FEATURE_SETFILES_CHECK_OPTION("c:"),
547 &exclude_dir, &input_filename, &rootpath, &out_filename,
548 IF_FEATURE_SETFILES_CHECK_OPTION(&policyfile,)
553 #if ENABLE_FEATURE_SETFILES_CHECK_OPTION
554 if ((applet_name[0] == 's') && (flags & OPT_c)) {
557 policystream = xfopen_for_read(policyfile);
558 if (sepol_set_policydb_from_file(policystream) < 0) {
559 bb_error_msg_and_die("sepol_set_policydb_from_file on %s", policyfile);
561 fclose(policystream);
563 /* Only process the specified file_contexts file, not
564 any .homedirs or .local files, and do not perform
565 context translations. */
566 set_matchpathcon_flags(MATCHPATHCON_BASEONLY |
567 MATCHPATHCON_NOTRANS |
568 MATCHPATHCON_VALIDATE);
573 add_exclude(llist_pop(&exclude_dir));
577 if (NOT_LONE_CHAR(out_filename, '-')) {
578 outfile = xfopen_for_write(out_filename);
581 if (applet_name[0] == 'r') { /* restorecon */
582 if (flags & (OPT_r | OPT_R))
584 } else { /* setfiles */
586 rootpathlen = strlen(rootpath);
589 input_filename = "-";
593 if (applet_name[0] == 's') { /* setfiles */
594 /* Use our own invalid context checking function so that
595 we can support either checking against the active policy or
596 checking against a binary policy file. */
597 set_matchpathcon_canoncon(&canoncon);
601 if (!S_ISREG(sb.st_mode)) {
602 bb_error_msg_and_die("spec file %s is not a regular file", argv[0]);
604 /* Load the file contexts configuration and check it. */
605 rc = matchpathcon_init(argv[0]);
607 bb_simple_perror_msg_and_die(argv[0]);
614 if (input_filename) {
618 if (NOT_LONE_CHAR(input_filename, '-'))
619 f = xfopen_for_read(input_filename);
620 while ((len = getline(&buf, &buf_len, f)) > 0) {
622 errors |= process_one(buf);
624 if (ENABLE_FEATURE_CLEAN_UP)
625 fclose_if_not_stdin(f);
629 for (i = 0; argv[i]; i++) {
630 errors |= process_one(argv[i]);
634 if (FLAG_W_warn_no_match)
635 matchpathcon_checkmatches(argv[0]);
637 if (ENABLE_FEATURE_CLEAN_UP && outfile)