applets.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) tons of folks. Tracking down who wrote what
  6. * isn't something I'm going to worry about... If you wrote something
  7. * here, please feel free to acknowledge your work.
  8. *
  9. * Based in part on code from sash, Copyright (c) 1999 by David I. Bell
  10. * Permission has been granted to redistribute this code under the GPL.
  11. *
  12. * Licensed under GPLv2 or later, see file License in this tarball for details.
  13. */
  14. #include <assert.h>
  15. #include "busybox.h"
  16. /* Apparently uclibc defines __GLIBC__ (compat trick?). Oh well. */
  17. #if ENABLE_STATIC && defined(__GLIBC__) && !defined(__UCLIBC__)
  18. #warning Static linking against glibc produces buggy executables
  19. #warning (glibc does not cope well with ld --gc-sections).
  20. #warning See sources.redhat.com/bugzilla/show_bug.cgi?id=3400
  21. #warning Note that glibc is unsuitable for static linking anyway.
  22. #warning If you still want to do it, remove -Wl,--gc-sections
  23. #warning from top-level Makefile and remove this warning.
  24. #error Aborting compilation.
  25. #endif
  26. /* Declare <applet>_main() */
  27. #define PROTOTYPES
  28. #include "applets.h"
  29. #undef PROTOTYPES
  30. #if ENABLE_SHOW_USAGE && !ENABLE_FEATURE_COMPRESS_USAGE
  31. /* Define usage_messages[] */
  32. static const char usage_messages[] ALIGN1 = ""
  33. #define MAKE_USAGE
  34. #include "usage.h"
  35. #include "applets.h"
  36. ;
  37. #undef MAKE_USAGE
  38. #else
  39. #define usage_messages 0
  40. #endif /* SHOW_USAGE */
  41. /* Define struct bb_applet applets[] */
  42. #include "applets.h"
  43. /* The -1 arises because of the {0,NULL,0,-1} entry. */
  44. #if ENABLE_FEATURE_SH_STANDALONE
  45. const unsigned short NUM_APPLETS = ARRAY_SIZE(applets);
  46. #endif
  47. const struct bb_applet *current_applet;
  48. const char *applet_name ATTRIBUTE_EXTERNALLY_VISIBLE;
  49. #if !BB_MMU
  50. bool re_execed;
  51. #endif
  52. USE_FEATURE_SUID(static uid_t ruid;) /* real uid */
  53. #if ENABLE_FEATURE_SUID_CONFIG
  54. /* applets[] is const, so we have to define this "override" structure */
  55. static struct BB_suid_config {
  56. const struct bb_applet *m_applet;
  57. uid_t m_uid;
  58. gid_t m_gid;
  59. mode_t m_mode;
  60. struct BB_suid_config *m_next;
  61. } *suid_config;
  62. static bool suid_cfg_readable;
  63. /* check if u is member of group g */
  64. static int ingroup(uid_t u, gid_t g)
  65. {
  66. struct group *grp = getgrgid(g);
  67. if (grp) {
  68. char **mem;
  69. for (mem = grp->gr_mem; *mem; mem++) {
  70. struct passwd *pwd = getpwnam(*mem);
  71. if (pwd && (pwd->pw_uid == u))
  72. return 1;
  73. }
  74. }
  75. return 0;
  76. }
  77. /* This should probably be a libbb routine. In that case,
  78. * I'd probably rename it to something like bb_trimmed_slice.
  79. */
  80. static char *get_trimmed_slice(char *s, char *e)
  81. {
  82. /* First, consider the value at e to be nul and back up until we
  83. * reach a non-space char. Set the char after that (possibly at
  84. * the original e) to nul. */
  85. while (e-- > s) {
  86. if (!isspace(*e)) {
  87. break;
  88. }
  89. }
  90. e[1] = '\0';
  91. /* Next, advance past all leading space and return a ptr to the
  92. * first non-space char; possibly the terminating nul. */
  93. return skip_whitespace(s);
  94. }
  95. /* Don't depend on the tools to combine strings. */
  96. static const char config_file[] ALIGN1 = "/etc/busybox.conf";
  97. /* We don't supply a value for the nul, so an index adjustment is
  98. * necessary below. Also, we use unsigned short here to save some
  99. * space even though these are really mode_t values. */
  100. static const unsigned short mode_mask[] ALIGN2 = {
  101. /* SST sst xxx --- */
  102. S_ISUID, S_ISUID|S_IXUSR, S_IXUSR, 0, /* user */
  103. S_ISGID, S_ISGID|S_IXGRP, S_IXGRP, 0, /* group */
  104. 0, S_IXOTH, S_IXOTH, 0 /* other */
  105. };
  106. #define parse_error(x) do { errmsg = x; goto pe_label; } while (0)
  107. static void parse_config_file(void)
  108. {
  109. struct BB_suid_config *sct_head;
  110. struct BB_suid_config *sct;
  111. const struct bb_applet *applet;
  112. FILE *f;
  113. const char *errmsg;
  114. char *s;
  115. char *e;
  116. int i;
  117. unsigned lc;
  118. smallint section;
  119. char buffer[256];
  120. struct stat st;
  121. assert(!suid_config); /* Should be set to NULL by bss init. */
  122. ruid = getuid();
  123. if (ruid == 0) /* run by root - don't need to even read config file */
  124. return;
  125. if ((stat(config_file, &st) != 0) /* No config file? */
  126. || !S_ISREG(st.st_mode) /* Not a regular file? */
  127. || (st.st_uid != 0) /* Not owned by root? */
  128. || (st.st_mode & (S_IWGRP | S_IWOTH)) /* Writable by non-root? */
  129. || !(f = fopen(config_file, "r")) /* Cannot open? */
  130. ) {
  131. return;
  132. }
  133. suid_cfg_readable = 1;
  134. sct_head = NULL;
  135. section = lc = 0;
  136. while (1) {
  137. s = buffer;
  138. if (!fgets(s, sizeof(buffer), f)) { /* Are we done? */
  139. if (ferror(f)) { /* Make sure it wasn't a read error. */
  140. parse_error("reading");
  141. }
  142. fclose(f);
  143. suid_config = sct_head; /* Success, so set the pointer. */
  144. return;
  145. }
  146. lc++; /* Got a (partial) line. */
  147. /* If a line is too long for our buffer, we consider it an error.
  148. * The following test does mistreat one corner case though.
  149. * If the final line of the file does not end with a newline and
  150. * yet exactly fills the buffer, it will be treated as too long
  151. * even though there isn't really a problem. But it isn't really
  152. * worth adding code to deal with such an unlikely situation, and
  153. * we do err on the side of caution. Besides, the line would be
  154. * too long if it did end with a newline. */
  155. if (!strchr(s, '\n') && !feof(f)) {
  156. parse_error("line too long");
  157. }
  158. /* Trim leading and trailing whitespace, ignoring comments, and
  159. * check if the resulting string is empty. */
  160. s = get_trimmed_slice(s, strchrnul(s, '#'));
  161. if (!*s) {
  162. continue;
  163. }
  164. /* Check for a section header. */
  165. if (*s == '[') {
  166. /* Unlike the old code, we ignore leading and trailing
  167. * whitespace for the section name. We also require that
  168. * there are no stray characters after the closing bracket. */
  169. e = strchr(s, ']');
  170. if (!e /* Missing right bracket? */
  171. || e[1] /* Trailing characters? */
  172. || !*(s = get_trimmed_slice(s+1, e)) /* Missing name? */
  173. ) {
  174. parse_error("section header");
  175. }
  176. /* Right now we only have one section so just check it.
  177. * If more sections are added in the future, please don't
  178. * resort to cascading ifs with multiple strcasecmp calls.
  179. * That kind of bloated code is all too common. A loop
  180. * and a string table would be a better choice unless the
  181. * number of sections is very small. */
  182. if (strcasecmp(s, "SUID") == 0) {
  183. section = 1;
  184. continue;
  185. }
  186. section = -1; /* Unknown section so set to skip. */
  187. continue;
  188. }
  189. /* Process sections. */
  190. if (section == 1) { /* SUID */
  191. /* Since we trimmed leading and trailing space above, we're
  192. * now looking for strings of the form
  193. * <key>[::space::]*=[::space::]*<value>
  194. * where both key and value could contain inner whitespace. */
  195. /* First get the key (an applet name in our case). */
  196. e = strchr(s, '=');
  197. if (e) {
  198. s = get_trimmed_slice(s, e);
  199. }
  200. if (!e || !*s) { /* Missing '=' or empty key. */
  201. parse_error("keyword");
  202. }
  203. /* Ok, we have an applet name. Process the rhs if this
  204. * applet is currently built in and ignore it otherwise.
  205. * Note: this can hide config file bugs which only pop
  206. * up when the busybox configuration is changed. */
  207. applet = find_applet_by_name(s);
  208. if (applet) {
  209. /* Note: We currently don't check for duplicates!
  210. * The last config line for each applet will be the
  211. * one used since we insert at the head of the list.
  212. * I suppose this could be considered a feature. */
  213. sct = xmalloc(sizeof(struct BB_suid_config));
  214. sct->m_applet = applet;
  215. sct->m_mode = 0;
  216. sct->m_next = sct_head;
  217. sct_head = sct;
  218. /* Get the specified mode. */
  219. e = skip_whitespace(e+1);
  220. for (i = 0; i < 3; i++) {
  221. /* There are 4 chars + 1 nul for each of user/group/other. */
  222. static const char mode_chars[] ALIGN1 = "Ssx-\0" "Ssx-\0" "Ttx-";
  223. const char *q;
  224. q = strchrnul(mode_chars + 5*i, *e++);
  225. if (!*q) {
  226. parse_error("mode");
  227. }
  228. /* Adjust by -i to account for nul. */
  229. sct->m_mode |= mode_mask[(q - mode_chars) - i];
  230. }
  231. /* Now get the the user/group info. */
  232. s = skip_whitespace(e);
  233. /* Note: we require whitespace between the mode and the
  234. * user/group info. */
  235. if ((s == e) || !(e = strchr(s, '.'))) {
  236. parse_error("<uid>.<gid>");
  237. }
  238. *e++ = '\0';
  239. /* We can't use get_ug_id here since it would exit()
  240. * if a uid or gid was not found. Oh well... */
  241. sct->m_uid = bb_strtoul(s, NULL, 10);
  242. if (errno) {
  243. struct passwd *pwd = getpwnam(s);
  244. if (!pwd) {
  245. parse_error("user");
  246. }
  247. sct->m_uid = pwd->pw_uid;
  248. }
  249. sct->m_gid = bb_strtoul(e, NULL, 10);
  250. if (errno) {
  251. struct group *grp;
  252. grp = getgrnam(e);
  253. if (!grp) {
  254. parse_error("group");
  255. }
  256. sct->m_gid = grp->gr_gid;
  257. }
  258. }
  259. continue;
  260. }
  261. /* Unknown sections are ignored. */
  262. /* Encountering configuration lines prior to seeing a
  263. * section header is treated as an error. This is how
  264. * the old code worked, but it may not be desirable.
  265. * We may want to simply ignore such lines in case they
  266. * are used in some future version of busybox. */
  267. if (!section) {
  268. parse_error("keyword outside section");
  269. }
  270. } /* while (1) */
  271. pe_label:
  272. fprintf(stderr, "Parse error in %s, line %d: %s\n",
  273. config_file, lc, errmsg);
  274. fclose(f);
  275. /* Release any allocated memory before returning. */
  276. while (sct_head) {
  277. sct = sct_head->m_next;
  278. free(sct_head);
  279. sct_head = sct;
  280. }
  281. }
  282. #else
  283. static inline void parse_config_file(void)
  284. {
  285. USE_FEATURE_SUID(ruid = getuid();)
  286. }
  287. #endif /* FEATURE_SUID_CONFIG */
  288. #if ENABLE_FEATURE_SUID
  289. static void check_suid(const struct bb_applet *applet)
  290. {
  291. gid_t rgid; /* real gid */
  292. if (ruid == 0) /* set by parse_config_file() */
  293. return; /* run by root - no need to check more */
  294. rgid = getgid();
  295. #if ENABLE_FEATURE_SUID_CONFIG
  296. if (suid_cfg_readable) {
  297. uid_t uid;
  298. struct BB_suid_config *sct;
  299. mode_t m;
  300. for (sct = suid_config; sct; sct = sct->m_next) {
  301. if (sct->m_applet == applet)
  302. goto found;
  303. }
  304. /* default: drop all privileges */
  305. xsetgid(rgid);
  306. xsetuid(ruid);
  307. return;
  308. found:
  309. m = sct->m_mode;
  310. if (sct->m_uid == ruid)
  311. /* same uid */
  312. m >>= 6;
  313. else if ((sct->m_gid == rgid) || ingroup(ruid, sct->m_gid))
  314. /* same group / in group */
  315. m >>= 3;
  316. if (!(m & S_IXOTH)) /* is x bit not set ? */
  317. bb_error_msg_and_die("you have no permission to run this applet!");
  318. /* _both_ sgid and group_exec have to be set for setegid */
  319. if ((sct->m_mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
  320. rgid = sct->m_gid;
  321. /* else (no setegid) we will set egid = rgid */
  322. /* We set effective AND saved ids. If saved-id is not set
  323. * like we do below, seteiud(0) can still later succeed! */
  324. if (setresgid(-1, rgid, rgid))
  325. bb_perror_msg_and_die("setresgid");
  326. /* do we have to set effective uid? */
  327. uid = ruid;
  328. if (sct->m_mode & S_ISUID)
  329. uid = sct->m_uid;
  330. /* else (no seteuid) we will set euid = ruid */
  331. if (setresuid(-1, uid, uid))
  332. bb_perror_msg_and_die("setresuid");
  333. return;
  334. }
  335. #if !ENABLE_FEATURE_SUID_CONFIG_QUIET
  336. {
  337. static bool onetime = 0;
  338. if (!onetime) {
  339. onetime = 1;
  340. fprintf(stderr, "Using fallback suid method\n");
  341. }
  342. }
  343. #endif
  344. #endif
  345. if (applet->need_suid == _BB_SUID_ALWAYS) {
  346. /* Real uid is not 0. If euid isn't 0 too, suid bit
  347. * is most probably not set on our executable */
  348. if (geteuid())
  349. bb_error_msg_and_die("applet requires root privileges!");
  350. } else if (applet->need_suid == _BB_SUID_NEVER) {
  351. xsetgid(rgid); /* drop all privileges */
  352. xsetuid(ruid);
  353. }
  354. }
  355. #else
  356. #define check_suid(x) ((void)0)
  357. #endif /* FEATURE_SUID */
  358. #if ENABLE_FEATURE_COMPRESS_USAGE
  359. #include "usage_compressed.h"
  360. #include "unarchive.h"
  361. static const char *unpack_usage_messages(void)
  362. {
  363. char *outbuf = NULL;
  364. bunzip_data *bd;
  365. int i;
  366. i = start_bunzip(&bd,
  367. /* src_fd: */ -1,
  368. /* inbuf: */ packed_usage,
  369. /* len: */ sizeof(packed_usage));
  370. /* read_bunzip can longjmp to start_bunzip, and ultimately
  371. * end up here with i != 0 on read data errors! Not trivial */
  372. if (!i) {
  373. /* Cannot use xmalloc: will leak bd in NOFORK case! */
  374. outbuf = malloc_or_warn(SIZEOF_usage_messages);
  375. if (outbuf)
  376. read_bunzip(bd, outbuf, SIZEOF_usage_messages);
  377. }
  378. dealloc_bunzip(bd);
  379. return outbuf;
  380. }
  381. #define dealloc_usage_messages(s) free(s)
  382. #else
  383. #define unpack_usage_messages() usage_messages
  384. #define dealloc_usage_messages(s) ((void)(s))
  385. #endif /* FEATURE_COMPRESS_USAGE */
  386. void bb_show_usage(void)
  387. {
  388. if (ENABLE_SHOW_USAGE) {
  389. const char *format_string;
  390. const char *p;
  391. const char *usage_string = p = unpack_usage_messages();
  392. int i;
  393. i = current_applet - applets;
  394. while (i) {
  395. while (*p++) continue;
  396. i--;
  397. }
  398. fprintf(stderr, "%s multi-call binary\n", bb_banner);
  399. format_string = "\nUsage: %s %s\n\n";
  400. if (*p == '\b')
  401. format_string = "\nNo help available.\n\n";
  402. fprintf(stderr, format_string, applet_name, p);
  403. dealloc_usage_messages((char*)usage_string);
  404. }
  405. xfunc_die();
  406. }
  407. static int applet_name_compare(const void *name, const void *vapplet)
  408. {
  409. const struct bb_applet *applet = vapplet;
  410. return strcmp(name, applet->name);
  411. }
  412. const struct bb_applet *find_applet_by_name(const char *name)
  413. {
  414. /* Do a binary search to find the applet entry given the name. */
  415. return bsearch(name, applets, ARRAY_SIZE(applets)-1, sizeof(applets[0]),
  416. applet_name_compare);
  417. }
  418. #if ENABLE_FEATURE_INSTALLER
  419. /* create (sym)links for each applet */
  420. static void install_links(const char *busybox, int use_symbolic_links)
  421. {
  422. /* directory table
  423. * this should be consistent w/ the enum,
  424. * busybox.h::bb_install_loc_t, or else... */
  425. static const char usr_bin [] ALIGN1 = "/usr/bin";
  426. static const char usr_sbin[] ALIGN1 = "/usr/sbin";
  427. static const char *const install_dir[] = {
  428. &usr_bin [8], /* "", equivalent to "/" for concat_path_file() */
  429. &usr_bin [4], /* "/bin" */
  430. &usr_sbin[4], /* "/sbin" */
  431. usr_bin,
  432. usr_sbin
  433. };
  434. int (*lf)(const char *, const char *) = link;
  435. char *fpc;
  436. int i;
  437. int rc;
  438. if (use_symbolic_links)
  439. lf = symlink;
  440. for (i = 0; applets[i].name != NULL; i++) {
  441. fpc = concat_path_file(
  442. install_dir[applets[i].install_loc],
  443. applets[i].name);
  444. rc = lf(busybox, fpc);
  445. if (rc != 0 && errno != EEXIST) {
  446. bb_perror_msg("%s", fpc);
  447. }
  448. free(fpc);
  449. }
  450. }
  451. #else
  452. #define install_links(x,y) ((void)0)
  453. #endif /* FEATURE_INSTALLER */
  454. /* If we were called as "busybox..." */
  455. static int busybox_main(char **argv)
  456. {
  457. if (!argv[1]) {
  458. /* Called without arguments */
  459. const struct bb_applet *a;
  460. int col, output_width;
  461. help:
  462. output_width = 80;
  463. if (ENABLE_FEATURE_AUTOWIDTH) {
  464. /* Obtain the terminal width */
  465. get_terminal_width_height(0, &output_width, NULL);
  466. }
  467. /* leading tab and room to wrap */
  468. output_width -= sizeof("start-stop-daemon, ") + 8;
  469. printf("%s multi-call binary\n", bb_banner); /* reuse const string... */
  470. printf("Copyright (C) 1998-2006  Erik Andersen, Rob Landley, and others.\n"
  471. "Licensed under GPLv2.  See source distribution for full notice.\n"
  472. "\n"
  473. "Usage: busybox [function] [arguments]...\n"
  474. " or: [function] [arguments]...\n"
  475. "\n"
  476. "\tBusyBox is a multi-call binary that combines many common Unix\n"
  477. "\tutilities into a single executable. Most people will create a\n"
  478. "\tlink to busybox for each function they wish to use and BusyBox\n"
  479. "\twill act like whatever it was invoked as!\n"
  480. "\nCurrently defined functions:\n");
  481. col = 0;
  482. a = applets;
  483. while (a->name) {
  484. if (col > output_width) {
  485. puts(",");
  486. col = 0;
  487. }
  488. col += printf("%s%s", (col ? ", " : "\t"), a->name);
  489. a++;
  490. }
  491. puts("\n");
  492. return 0;
  493. }
  494. if (ENABLE_FEATURE_INSTALLER && strcmp(argv[1], "--install") == 0) {
  495. const char *busybox;
  496. busybox = xmalloc_readlink(bb_busybox_exec_path);
  497. if (!busybox)
  498. busybox = bb_busybox_exec_path;
  499. /* -s makes symlinks */
  500. install_links(busybox, argv[2] && strcmp(argv[2], "-s") == 0);
  501. return 0;
  502. }
  503. if (strcmp(argv[1], "--help") == 0) {
  504. /* "busybox --help [<applet>]" */
  505. if (!argv[2])
  506. goto help;
  507. /* convert to "<applet> --help" */
  508. argv[0] = argv[2];
  509. argv[2] = NULL;
  510. } else {
  511. /* "busybox <applet> arg1 arg2 ..." */
  512. argv++;
  513. }
  514. /* we want "<argv[0]>: applet not found", not "busybox: ..." */
  515. applet_name = argv[0];
  516. run_applet_and_exit(argv[0], argv);
  517. bb_error_msg_and_die("applet not found");
  518. }
  519. void run_current_applet_and_exit(char **argv)
  520. {
  521. int argc = 1;
  522. while (argv[argc])
  523. argc++;
  524. /* Reinit some shared global data */
  525. optind = 1;
  526. xfunc_error_retval = EXIT_FAILURE;
  527. applet_name = current_applet->name;
  528. if (argc == 2 && !strcmp(argv[1], "--help"))
  529. bb_show_usage();
  530. if (ENABLE_FEATURE_SUID)
  531. check_suid(current_applet);
  532. exit(current_applet->main(argc, argv));
  533. }
  534. void run_applet_and_exit(const char *name, char **argv)
  535. {
  536. current_applet = find_applet_by_name(name);
  537. if (current_applet)
  538. run_current_applet_and_exit(argv);
  539. if (!strncmp(name, "busybox", 7))
  540. exit(busybox_main(argv));
  541. }
  542. #ifdef __GLIBC__
  543. /* Make it reside in R/W memory: */
  544. int *const bb_errno __attribute__ ((section (".data")));
  545. #endif
  546. int main(int argc, char **argv)
  547. {
  548. #ifdef __GLIBC__
  549. (*(int **)&bb_errno) = __errno_location();
  550. #endif
  551. #if !BB_MMU
  552. /* NOMMU re-exec trick sets high-order bit in first byte of name */
  553. if (argv[0][0] & 0x80) {
  554. re_execed = 1;
  555. argv[0][0] &= 0x7f;
  556. }
  557. #endif
  558. applet_name = argv[0];
  559. if (applet_name[0] == '-')
  560. applet_name++;
  561. applet_name = bb_basename(applet_name);
  562. parse_config_file(); /* ...maybe, if FEATURE_SUID_CONFIG */
  563. /* Set locale for everybody except 'init' */
  564. if (ENABLE_LOCALE_SUPPORT && getpid() != 1)
  565. setlocale(LC_ALL, "");
  566. run_applet_and_exit(applet_name, argv);
  567. bb_error_msg_and_die("applet not found");
  568. }