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