3
0

setfiles.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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 ATTRIBUTE_UNUSED, ...)
  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. bb_putchar('\n');
  259. bb_putchar('*');
  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(
  353. const char *file,
  354. struct stat *sb,
  355. void *userData ATTRIBUTE_UNUSED,
  356. int depth ATTRIBUTE_UNUSED)
  357. {
  358. if (!follow_mounts) {
  359. /* setfiles does not process across different mount points */
  360. if (sb->st_dev != dev_id) {
  361. return SKIP;
  362. }
  363. }
  364. errors |= restore(file);
  365. if (abort_on_error && errors)
  366. return FALSE;
  367. return TRUE;
  368. }
  369. static int canoncon(const char *path, unsigned lineno, char **contextp)
  370. {
  371. static const char err_msg[] ALIGN1 = "%s: line %u has invalid context %s";
  372. char *tmpcon;
  373. char *context = *contextp;
  374. int invalid = 0;
  375. #if ENABLE_FEATURE_SETFILES_CHECK_OPTION
  376. if (policyfile) {
  377. if (sepol_check_context(context) >= 0)
  378. return 0;
  379. /* Exit immediately if we're in checking mode. */
  380. bb_error_msg_and_die(err_msg, path, lineno, context);
  381. }
  382. #endif
  383. if (security_canonicalize_context_raw(context, &tmpcon) < 0) {
  384. if (errno != ENOENT) {
  385. invalid = 1;
  386. inc_err();
  387. }
  388. } else {
  389. free(context);
  390. *contextp = tmpcon;
  391. }
  392. if (invalid) {
  393. bb_error_msg(err_msg, path, lineno, context);
  394. }
  395. return invalid;
  396. }
  397. static int process_one(char *name)
  398. {
  399. struct stat sb;
  400. int rc;
  401. rc = lstat(name, &sb);
  402. if (rc < 0) {
  403. if (FLAG_i_ignore_enoent && errno == ENOENT)
  404. return 0;
  405. bb_perror_msg("stat(%s)", name);
  406. goto err;
  407. }
  408. dev_id = sb.st_dev;
  409. if (S_ISDIR(sb.st_mode) && recurse) {
  410. if (recursive_action(name,
  411. ACTION_RECURSE,
  412. apply_spec,
  413. apply_spec,
  414. NULL, 0) != TRUE) {
  415. bb_error_msg("error while labeling %s", name);
  416. goto err;
  417. }
  418. } else {
  419. rc = restore(name);
  420. if (rc)
  421. goto err;
  422. }
  423. out:
  424. if (add_assoc) {
  425. if (FLAG_q_quiet)
  426. set_matchpathcon_printf(&qprintf);
  427. matchpathcon_filespec_eval();
  428. set_matchpathcon_printf(NULL);
  429. matchpathcon_filespec_destroy();
  430. }
  431. return rc;
  432. err:
  433. rc = -1;
  434. goto out;
  435. }
  436. int setfiles_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  437. int setfiles_main(int argc, char **argv)
  438. {
  439. struct stat sb;
  440. int rc, i = 0;
  441. const char *input_filename = NULL;
  442. char *buf = NULL;
  443. size_t buf_len;
  444. int flags;
  445. llist_t *exclude_dir = NULL;
  446. char *out_filename = NULL;
  447. INIT_G();
  448. if (applet_name[0] == 's') { /* "setfiles" */
  449. /*
  450. * setfiles:
  451. * Recursive descent,
  452. * Does not expand paths via realpath,
  453. * Aborts on errors during the file tree walk,
  454. * Try to track inode associations for conflict detection,
  455. * Does not follow mounts,
  456. * Validates all file contexts at init time.
  457. */
  458. recurse = 1;
  459. abort_on_error = 1;
  460. add_assoc = 1;
  461. /* follow_mounts = 0; - already is */
  462. matchpathcon_flags = MATCHPATHCON_VALIDATE | MATCHPATHCON_NOTRANS;
  463. } else {
  464. /*
  465. * restorecon:
  466. * No recursive descent unless -r/-R,
  467. * Expands paths via realpath,
  468. * Do not abort on errors during the file tree walk,
  469. * Do not try to track inode associations for conflict detection,
  470. * Follows mounts,
  471. * Does lazy validation of contexts upon use.
  472. */
  473. expand_realpath = 1;
  474. follow_mounts = 1;
  475. matchpathcon_flags = MATCHPATHCON_NOTRANS;
  476. /* restorecon only */
  477. selinux_or_die();
  478. }
  479. set_matchpathcon_flags(matchpathcon_flags);
  480. opt_complementary = "e::vv:v--p:p--v:v--q:q--v";
  481. /* Option order must match OPT_x definitions! */
  482. if (applet_name[0] == 'r') { /* restorecon */
  483. flags = getopt32(argv, "de:f:ilnpqrsvo:FWR",
  484. &exclude_dir, &input_filename, &out_filename, &verbose);
  485. } else { /* setfiles */
  486. flags = getopt32(argv, "de:f:ilnpqr:svo:FW"
  487. USE_FEATURE_SETFILES_CHECK_OPTION("c:"),
  488. &exclude_dir, &input_filename, &rootpath, &out_filename,
  489. USE_FEATURE_SETFILES_CHECK_OPTION(&policyfile,)
  490. &verbose);
  491. }
  492. #if ENABLE_FEATURE_SETFILES_CHECK_OPTION
  493. if ((applet_name[0] == 's') && (flags & OPT_c)) {
  494. FILE *policystream;
  495. policystream = xfopen(policyfile, "r");
  496. if (sepol_set_policydb_from_file(policystream) < 0) {
  497. bb_error_msg_and_die("sepol_set_policydb_from_file on %s", policyfile);
  498. }
  499. fclose(policystream);
  500. /* Only process the specified file_contexts file, not
  501. any .homedirs or .local files, and do not perform
  502. context translations. */
  503. set_matchpathcon_flags(MATCHPATHCON_BASEONLY |
  504. MATCHPATHCON_NOTRANS |
  505. MATCHPATHCON_VALIDATE);
  506. }
  507. #endif
  508. while (exclude_dir)
  509. add_exclude(llist_pop(&exclude_dir));
  510. if (flags & OPT_o) {
  511. outfile = stdout;
  512. if (NOT_LONE_CHAR(out_filename, '-')) {
  513. outfile = xfopen(out_filename, "w");
  514. }
  515. }
  516. if (applet_name[0] == 'r') { /* restorecon */
  517. if (flags & (OPT_r | OPT_R))
  518. recurse = 1;
  519. } else { /* setfiles */
  520. if (flags & OPT_r)
  521. rootpathlen = strlen(rootpath);
  522. }
  523. if (flags & OPT_s) {
  524. input_filename = "-";
  525. add_assoc = 0;
  526. }
  527. if (applet_name[0] == 's') { /* setfiles */
  528. /* Use our own invalid context checking function so that
  529. we can support either checking against the active policy or
  530. checking against a binary policy file. */
  531. set_matchpathcon_canoncon(&canoncon);
  532. if (argc == 1)
  533. bb_show_usage();
  534. if (stat(argv[optind], &sb) < 0) {
  535. bb_simple_perror_msg_and_die(argv[optind]);
  536. }
  537. if (!S_ISREG(sb.st_mode)) {
  538. bb_error_msg_and_die("spec file %s is not a regular file", argv[optind]);
  539. }
  540. /* Load the file contexts configuration and check it. */
  541. rc = matchpathcon_init(argv[optind]);
  542. if (rc < 0) {
  543. bb_simple_perror_msg_and_die(argv[optind]);
  544. }
  545. optind++;
  546. if (nerr)
  547. exit(1);
  548. }
  549. if (input_filename) {
  550. ssize_t len;
  551. FILE *f = stdin;
  552. if (NOT_LONE_CHAR(input_filename, '-'))
  553. f = xfopen(input_filename, "r");
  554. while ((len = getline(&buf, &buf_len, f)) > 0) {
  555. buf[len - 1] = '\0';
  556. errors |= process_one(buf);
  557. }
  558. if (ENABLE_FEATURE_CLEAN_UP)
  559. fclose_if_not_stdin(f);
  560. } else {
  561. if (optind >= argc)
  562. bb_show_usage();
  563. for (i = optind; i < argc; i++) {
  564. errors |= process_one(argv[i]);
  565. }
  566. }
  567. if (FLAG_W_warn_no_match)
  568. matchpathcon_checkmatches(argv[0]);
  569. if (ENABLE_FEATURE_CLEAN_UP && outfile)
  570. fclose(outfile);
  571. return errors;
  572. }