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