setfiles.c 15 KB

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