cadec83679d2984698dc44b6cba3a39666a327ea
[oweals/busybox.git] / selinux / setfiles.c
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
7 #include "libbb.h"
8 #if ENABLE_FEATURE_SETFILES_CHECK_OPTION
9 #include <sepol/sepol.h>
10 #endif
11
12 #define MAX_EXCLUDES 50
13
14 struct edir {
15         char *directory;
16         size_t size;
17 };
18
19 struct globals {
20         FILE *outfile;
21         char *policyfile;
22         char *rootpath;
23         int rootpathlen;
24         unsigned count;
25         int excludeCtr;
26         int errors;
27         int verbose; /* getopt32 uses it, has to be int */
28         //smallint force;
29         //smallint progress;
30         //smallint debug;
31         //smallint dry_run;
32         //smallint quiet;
33         //smallint ignore_enoent;
34         //smallint take_log;
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 */
44         int nerr;
45         struct edir excludeArray[MAX_EXCLUDES];
46 };
47
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 */ \
54 } while (0)
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      )
80
81 /* Must match getopt32 string! */
82 enum {
83         OPT_d = (1 << 0),
84         OPT_e = (1 << 1),
85         OPT_f = (1 << 2),
86         OPT_i = (1 << 3),
87         OPT_l = (1 << 4),
88         OPT_n = (1 << 5),
89         OPT_p = (1 << 6),
90         OPT_q = (1 << 7),
91         OPT_r = (1 << 8),
92         OPT_s = (1 << 9),
93         OPT_v = (1 << 10),
94         OPT_o = (1 << 11),
95         OPT_F = (1 << 12),
96         OPT_W = (1 << 13),
97         OPT_c = (1 << 14), /* c only for setfiles */
98         OPT_R = (1 << 14), /* R only for restorecon */
99 };
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)
116
117
118 static void qprintf(const char *fmt, ...)
119 {
120         /* quiet, do nothing */
121 }
122
123 static void inc_err(void)
124 {
125         nerr++;
126         if (nerr > 9 && !FLAG_d_debug) {
127                 bb_error_msg_and_die("exiting after 10 errors");
128         }
129 }
130
131 static int add_exclude(const char *directory)
132 {
133         struct stat sb;
134         size_t len = 0;
135
136         if (directory == NULL || directory[0] != '/') {
137                 bb_error_msg("full path required for exclude: %s", directory);
138                 return 1;
139         }
140         if (lstat(directory, &sb)) {
141                 bb_error_msg("directory \"%s\" not found, ignoring", directory);
142                 return 0;
143         }
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);
147                 return 0;
148         }
149         if (excludeCtr == MAX_EXCLUDES) {
150                 bb_error_msg("maximum excludes %d exceeded", MAX_EXCLUDES);
151                 return 1;
152         }
153
154         len = strlen(directory);
155         while (len > 1 && directory[len - 1] == '/') {
156                 len--;
157         }
158         excludeArray[excludeCtr].directory = xstrndup(directory, len);
159         excludeArray[excludeCtr++].size = len;
160
161         return 0;
162 }
163
164 static int exclude(const char *file)
165 {
166         int i = 0;
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] == '/') {
172                                 return 1;
173                         }
174                 }
175         }
176         return 0;
177 }
178
179 static int match(const char *name, struct stat *sb, char **con)
180 {
181         int ret;
182         char path[PATH_MAX + 1];
183         char *tmp_path = xstrdup(name);
184
185         if (excludeCtr > 0 && exclude(name)) {
186                 goto err;
187         }
188         ret = lstat(name, sb);
189         if (ret) {
190                 if (FLAG_i_ignore_enoent && errno == ENOENT) {
191                         free(tmp_path);
192                         return 0;
193                 }
194                 bb_error_msg("stat(%s)", name);
195                 goto err;
196         }
197
198         if (expand_realpath) {
199                 if (S_ISLNK(sb->st_mode)) {
200                         char *p = NULL;
201                         char *file_sep;
202
203                         size_t len = 0;
204
205                         if (verbose > 1)
206                                 bb_error_msg("warning! %s refers to a symbolic link, not following last component", name);
207
208                         file_sep = strrchr(tmp_path, '/');
209                         if (file_sep == tmp_path) {
210                                 file_sep++;
211                                 p[0] = '\0';
212                                 p = path;
213                         } else if (file_sep) {
214                                 *file_sep++ = '\0';
215                                 p = realpath(tmp_path, path);
216                         } else {
217                                 file_sep = tmp_path;
218                                 p = realpath("./", path);
219                         }
220                         if (p)
221                                 len = strlen(p);
222                         if (!p || len + strlen(file_sep) + 2 > PATH_MAX) {
223                                 bb_perror_msg("realpath(%s) failed", name);
224                                 goto err;
225                         }
226                         p += len;
227                         /* ensure trailing slash of directory name */
228                         if (len == 0 || p[-1] != '/') {
229                                 *p++ = '/';
230                         }
231                         strcpy(p, file_sep);
232                         name = path;
233                         if (excludeCtr > 0 && exclude(name))
234                                 goto err;
235
236                 } else {
237                         char *p;
238                         p = realpath(name, path);
239                         if (!p) {
240                                 bb_perror_msg("realpath(%s)", name);
241                                 goto err;
242                         }
243                         name = p;
244                         if (excludeCtr > 0 && exclude(name))
245                                 goto err;
246                 }
247         }
248
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",
253                                 name, rootpath);
254                         goto err;
255                 }
256                 name += rootpathlen;
257         }
258
259         free(tmp_path);
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);
264  err:
265         free(tmp_path);
266         return -1;
267 }
268
269 /* Compare two contexts to see if their differences are "significant",
270  * or whether the only difference is in the user. */
271 static int only_changed_user(const char *a, const char *b)
272 {
273         if (FLAG_F_force)
274                 return 0;
275         if (!a || !b)
276                 return 0;
277         a = strchr(a, ':'); /* Rest of the context after the user */
278         b = strchr(b, ':');
279         if (!a || !b)
280                 return 0;
281         return (strcmp(a, b) == 0);
282 }
283
284 static int restore(const char *file)
285 {
286         char *my_file = xstrdup(file);
287         char *my_file_orig = my_file;
288         struct stat my_sb;
289         int i, j, ret;
290         char *context = NULL;
291         char *newcon = NULL;
292         int user_only_changed = 0;
293         size_t len = strlen(my_file);
294         int retval = 0;
295
296         /* Skip the extra slashes at the beginning and end, if present. */
297         if (file[0] == '/' && file[1] == '/')
298                 my_file++;
299         if (len > 1 && my_file[len - 1] == '/')
300                 my_file[len - 1] = '\0';
301
302         i = match(my_file, &my_sb, &newcon);
303
304         if (i < 0) /* No matching specification. */
305                 goto out;
306
307
308         if (FLAG_p_progress) {
309                 count++;
310                 if (count % 0x400 == 0) { /* every 1024 times */
311                         count = (count % (80*0x400));
312                         if (count == 0)
313                                 fputc('\n', stdout);
314                         fputc('*', stdout);
315                         fflush(stdout);
316                 }
317         }
318
319         /*
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.
324          */
325         if (add_assoc) {
326                 j = matchpathcon_filespec_add(my_sb.st_ino, i, my_file);
327                 if (j < 0)
328                         goto err;
329
330                 if (j != i) {
331                         /* There was already an association and it took precedence. */
332                         goto out;
333                 }
334         }
335
336         if (FLAG_d_debug)
337                 printf("%s: %s matched by %s\n", applet_name, my_file, newcon);
338
339         /* Get the current context of the file. */
340         ret = lgetfilecon_raw(my_file, &context);
341         if (ret < 0) {
342                 if (errno == ENODATA) {
343                         context = NULL; /* paranoia */
344                 } else {
345                         bb_perror_msg("lgetfilecon_raw on %s", my_file);
346                         goto err;
347                 }
348                 user_only_changed = 0;
349         } else
350                 user_only_changed = only_changed_user(context, newcon);
351
352         /*
353          * Do not relabel the file if the matching specification is
354          * <<none>> or the file is already labeled according to the
355          * specification.
356          */
357         if ((strcmp(newcon, "<<none>>") == 0)
358          || (context && (strcmp(context, newcon) == 0) && !FLAG_F_force)) {
359                 goto out;
360         }
361
362         if (!FLAG_F_force && context && (is_context_customizable(context) > 0)) {
363                 if (verbose > 1) {
364                         bb_error_msg("skipping %s. %s is customizable_types",
365                                 my_file, context);
366                 }
367                 goto out;
368         }
369
370         if (verbose) {
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);
377                 }
378         }
379
380         if (FLAG_l_take_log && !user_only_changed) {
381                 if (context)
382                         bb_info_msg("relabeling %s from %s to %s", my_file, context, newcon);
383                 else
384                         bb_info_msg("labeling %s to %s", my_file, newcon);
385         }
386
387         if (outfile && !user_only_changed)
388                 fprintf(outfile, "%s\n", my_file);
389
390         /*
391          * Do not relabel the file if -n was used.
392          */
393         if (FLAG_n_dry_run || user_only_changed)
394                 goto out;
395
396         /*
397          * Relabel the file to the specified context.
398          */
399         ret = lsetfilecon(my_file, newcon);
400         if (ret) {
401                 bb_perror_msg("lsetfileconon(%s,%s)", my_file, newcon);
402                 goto err;
403         }
404
405  out:
406         freecon(context);
407         freecon(newcon);
408         free(my_file_orig);
409         return retval;
410  err:
411         retval--; /* -1 */
412         goto out;
413 }
414
415 /*
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.
419  */
420 static int apply_spec(const char *file,
421                       struct stat *sb, void *userData, int depth)
422 {
423         if (!follow_mounts) {
424                 /* setfiles does not process across different mount points */
425                 if (sb->st_dev != dev_id) {
426                         return SKIP;
427                 }
428         }
429         errors |= restore(file);
430         if (abort_on_error && errors)
431                 return FALSE;
432         return TRUE;
433 }
434
435
436 static int canoncon(const char *path, unsigned lineno, char **contextp)
437 {
438         static const char err_msg[] = "%s: line %u has invalid context %s";
439
440         char *tmpcon;
441         char *context = *contextp;
442         int invalid = 0;
443
444 #if ENABLE_FEATURE_SETFILES_CHECK_OPTION
445         if (policyfile) {
446                 if (sepol_check_context(context) >= 0)
447                         return 0;
448                 /* Exit immediately if we're in checking mode. */
449                 bb_error_msg_and_die(err_msg, path, lineno, context);
450         }
451 #endif
452
453         if (security_canonicalize_context_raw(context, &tmpcon) < 0) {
454                 if (errno != ENOENT) {
455                         invalid = 1;
456                         inc_err();
457                 }
458         } else {
459                 free(context);
460                 *contextp = tmpcon;
461         }
462
463         if (invalid) {
464                 bb_error_msg(err_msg, path, lineno, context);
465         }
466
467         return invalid;
468 }
469
470 static int process_one(char *name)
471 {
472         struct stat sb;
473         int rc;
474
475         rc = lstat(name, &sb);
476         if (rc < 0) {
477                 if (FLAG_i_ignore_enoent && errno == ENOENT)
478                         return 0;
479                 bb_perror_msg("stat(%s)", name);
480                 goto err;
481         }
482         dev_id = sb.st_dev;
483
484         if (S_ISDIR(sb.st_mode) && recurse) {
485                 if (recursive_action(name,
486                                      ACTION_RECURSE,
487                                      apply_spec,
488                                      apply_spec,
489                                      NULL, 0) != TRUE) {
490                         bb_error_msg("error while labeling %s", name);
491                         goto err;
492                 }
493         } else {
494                 rc = restore(name);
495                 if (rc)
496                         goto err;
497         }
498
499  out:
500         if (add_assoc) {
501                 if (FLAG_q_quiet)
502                         set_matchpathcon_printf(&qprintf);
503                 matchpathcon_filespec_eval();
504                 set_matchpathcon_printf(NULL);
505                 matchpathcon_filespec_destroy();
506         }
507
508         return rc;
509
510  err:
511         rc = -1;
512         goto out;
513 }
514
515 int setfiles_main(int argc, char **argv);
516 int setfiles_main(int argc, char **argv)
517 {
518         struct stat sb;
519         int rc, i = 0;
520         const char *input_filename = NULL;
521         int use_input_file = 0;
522         char *buf = NULL;
523         size_t buf_len;
524         int flags;
525         llist_t *exclude_dir = NULL;
526         char *out_filename = NULL;
527
528         INIT_G();
529
530         if (applet_name[0] == 's') { /* "setfiles" */
531                 /*
532                  * setfiles:
533                  * Recursive descent,
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.
539                  */
540                 recurse = 1;
541                 abort_on_error = 1;
542                 add_assoc = 1;
543                 /* follow_mounts = 0; - already is */
544                 matchpathcon_flags = MATCHPATHCON_VALIDATE | MATCHPATHCON_NOTRANS;
545         } else {
546                 /*
547                  * restorecon:
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,
552                  * Follows mounts,
553                  * Does lazy validation of contexts upon use.
554                  */
555                 expand_realpath = 1;
556                 follow_mounts = 1;
557                 matchpathcon_flags = MATCHPATHCON_NOTRANS;
558                 /* restorecon only */
559                 selinux_or_die();
560         }
561
562         set_matchpathcon_flags(matchpathcon_flags);
563
564         opt_complementary = "e::vv:v--p:p--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,)
574                         &verbose);
575         }
576
577 #if ENABLE_FEATURE_SETFILES_CHECK_OPTION
578         if ((applet_name[0] == 's') && (flags & OPT_c)) {
579                 FILE *policystream;
580
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);
584                 }
585                 fclose(policystream);
586
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);
593         }
594 #endif
595
596         //if (flags & OPT_d) {
597         //      debug = 1;
598         //}
599         if (flags & OPT_e) {
600                 if (exclude_dir == NULL) {
601                         bb_show_usage();
602                 }
603                 while (exclude_dir) {
604                         if (add_exclude(llist_pop(&exclude_dir)))
605                                 exit(1);
606                 }
607         }
608         //if (flags & OPT_i) {
609         //      ignore_enoent = 1;
610         //}
611         //if (flags & OPT_l) {
612         //      take_log = 1;
613         //}
614         //if (flags & OPT_F) {
615         //      force = 1;
616         //}
617         //if (flags & OPT_n) {
618         //      dry_run = 1;
619         //}
620         if (flags & OPT_o) {
621                 outfile = stdout;
622                 if (NOT_LONE_CHAR(out_filename, '-')) {
623                         outfile = xfopen(out_filename, "w");
624                 }
625         }
626         //if (flags & OPT_q) {
627         //      quiet = 1;
628         //}
629         if (applet_name[0] == 'r') { /* restorecon */
630                 if (flags & (OPT_r | OPT_R))
631                         recurse = 1;
632         } else { /* setfiles */
633                 if (flags & OPT_r)
634                         rootpathlen = strlen(rootpath);
635         }
636         if (flags & OPT_s) {
637                 use_input_file = 1;
638                 input_filename = "-";
639                 add_assoc = 0;
640         }
641         //if (flags & OPT_p) {
642         //      progress = 1;
643         //}
644         //if (flags & OPT_W) {
645         //      warn_no_match = 1;
646         //}
647
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);
653                 if (argc == 1)
654                         bb_show_usage();
655                 if (stat(argv[optind], &sb) < 0) {
656                         bb_perror_msg_and_die("%s", argv[optind]);
657                 }
658                 if (!S_ISREG(sb.st_mode)) {
659                         bb_error_msg_and_die("spec file %s is not a regular file", argv[optind]);
660                 }
661                 /* Load the file contexts configuration and check it. */
662                 rc = matchpathcon_init(argv[optind]);
663                 if (rc < 0) {
664                         bb_perror_msg_and_die("%s", argv[optind]);
665                 }
666
667                 optind++;
668
669                 if (nerr)
670                         exit(1);
671         }
672
673         if (use_input_file) {
674                 ssize_t len;
675                 FILE *f = stdin;
676
677                 if (NOT_LONE_CHAR(input_filename, '-'))
678                         f = xfopen(input_filename, "r");
679                 while ((len = getline(&buf, &buf_len, f)) > 0) {
680                         buf[len - 1] = '\0';
681                         errors |= process_one(buf);
682                 }
683                 if (ENABLE_FEATURE_CLEAN_UP)
684                         fclose_if_not_stdin(f);
685         } else {
686                 if (optind >= argc)
687                         bb_show_usage();
688                 for (i = optind; i < argc; i++) {
689                         errors |= process_one(argv[i]);
690                 }
691         }
692
693         if (FLAG_W_warn_no_match)
694                 matchpathcon_checkmatches(argv[0]);
695
696         if (ENABLE_FEATURE_CLEAN_UP && outfile)
697                 fclose(outfile);
698
699         return errors;
700 }