00102daa315b44781a25d24d25bec94e661b471f
[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 "busybox.h"
16 #include <unistd.h>
17 #include <string.h>
18 #include <assert.h>
19
20 #if ENABLE_SHOW_USAGE && !ENABLE_FEATURE_COMPRESS_USAGE
21 static const char usage_messages[] =
22 #define MAKE_USAGE
23 #include "usage.h"
24 #include "applets.h"
25 ;
26 #undef MAKE_USAGE
27 #else
28 #define usage_messages 0
29 #endif /* ENABLE_SHOW_USAGE */
30
31 #undef APPLET
32 #undef APPLET_NOUSAGE
33 #undef PROTOTYPES
34 #include "applets.h"
35
36 static struct BB_applet *applet_using;
37
38 /* The -1 arises because of the {0,NULL,0,-1} entry above. */
39 const size_t NUM_APPLETS = (sizeof (applets) / sizeof (struct BB_applet) - 1);
40
41
42 #ifdef CONFIG_FEATURE_SUID_CONFIG
43
44 #include <ctype.h>
45
46 #define CONFIG_FILE "/etc/busybox.conf"
47
48 /* applets [] is const, so we have to define this "override" structure */
49 static struct BB_suid_config
50 {
51         struct BB_applet *m_applet;
52
53         uid_t m_uid;
54         gid_t m_gid;
55         mode_t m_mode;
56
57         struct BB_suid_config *m_next;
58 } *suid_config;
59
60 static int suid_cfg_readable;
61
62 /* check if u is member of group g */
63 static int ingroup(uid_t u, gid_t g)
64 {
65         struct group *grp = getgrgid(g);
66
67         if (grp) {
68                 char **mem;
69
70                 for (mem = grp->gr_mem; *mem; mem++) {
71                         struct passwd *pwd = getpwnam(*mem);
72
73                         if (pwd && (pwd->pw_uid == u))
74                                 return 1;
75                 }
76         }
77         return 0;
78 }
79
80 /* This should probably be a libbb routine.  In that case,
81  * I'd probably rename it to something like bb_trimmed_slice.
82  */
83 static char *get_trimmed_slice(char *s, char *e)
84 {
85         /* First, consider the value at e to be nul and back up until we
86          * reach a non-space char.  Set the char after that (possibly at
87          * the original e) to nul. */
88         while (e-- > s) {
89                 if (!isspace(*e)) {
90                         break;
91                 }
92         }
93         e[1] = 0;
94
95         /* Next, advance past all leading space and return a ptr to the
96          * first non-space char; possibly the terminating nul. */
97         return skip_whitespace(s);
98 }
99
100
101 #define parse_error(x)  { err=x; goto pe_label; }
102
103 /* Don't depend on the tools to combine strings. */
104 static const char config_file[] = CONFIG_FILE;
105
106 /* There are 4 chars + 1 nul for each of user/group/other. */
107 static const char mode_chars[] = "Ssx-\0Ssx-\0Ttx-";
108
109 /* We don't supply a value for the nul, so an index adjustment is
110  * necessary below.  Also, we use unsigned short here to save some
111  * space even though these are really mode_t values. */
112 static const unsigned short mode_mask[] = {
113         /*  SST         sst                 xxx   --- */
114         S_ISUID,    S_ISUID|S_IXUSR,    S_IXUSR,    0,  /* user */
115         S_ISGID,    S_ISGID|S_IXGRP,    S_IXGRP,    0,  /* group */
116         0,          S_IXOTH,            S_IXOTH,    0   /* other */
117 };
118
119 static void parse_config_file(void)
120 {
121         struct BB_suid_config *sct_head;
122         struct BB_suid_config *sct;
123         struct BB_applet *applet;
124         FILE *f;
125         char *err;
126         char *s;
127         char *e;
128         int i, lc, section;
129         char buffer[256];
130         struct stat st;
131
132         assert(!suid_config);           /* Should be set to NULL by bss init. */
133
134         if ((stat(config_file, &st) != 0)                       /* No config file? */
135                 || !S_ISREG(st.st_mode)                                 /* Not a regular file? */
136                 || (st.st_uid != 0)                                             /* Not owned by root? */
137                 || (st.st_mode & (S_IWGRP | S_IWOTH))   /* Writable by non-root? */
138                 || !(f = fopen(config_file, "r"))               /* Can not open? */
139                 ) {
140                 return;
141         }
142
143         suid_cfg_readable = 1;
144         sct_head = NULL;
145         section = lc = 0;
146
147         do {
148                 s = buffer;
149
150                 if (!fgets(s, sizeof(buffer), f)) { /* Are we done? */
151                         if (ferror(f)) {   /* Make sure it wasn't a read error. */
152                                 parse_error("reading");
153                         }
154                         fclose(f);
155                         suid_config = sct_head; /* Success, so set the pointer. */
156                         return;
157                 }
158
159                 lc++;                                   /* Got a (partial) line. */
160
161                 /* If a line is too long for our buffer, we consider it an error.
162                  * The following test does mistreat one corner case though.
163                  * If the final line of the file does not end with a newline and
164                  * yet exactly fills the buffer, it will be treated as too long
165                  * even though there isn't really a problem.  But it isn't really
166                  * worth adding code to deal with such an unlikely situation, and
167                  * we do err on the side of caution.  Besides, the line would be
168                  * too long if it did end with a newline. */
169                 if (!strchr(s, '\n') && !feof(f)) {
170                         parse_error("line too long");
171                 }
172
173                 /* Trim leading and trailing whitespace, ignoring comments, and
174                  * check if the resulting string is empty. */
175                 if (!*(s = get_trimmed_slice(s, strchrnul(s, '#')))) {
176                         continue;
177                 }
178
179                 /* Check for a section header. */
180
181                 if (*s == '[') {
182                         /* Unlike the old code, we ignore leading and trailing
183                          * whitespace for the section name.  We also require that
184                          * there are no stray characters after the closing bracket. */
185                         if (!(e = strchr(s, ']'))       /* Missing right bracket? */
186                                 || e[1]                                 /* Trailing characters? */
187                                 || !*(s = get_trimmed_slice(s+1, e)) /* Missing name? */
188                                 ) {
189                                 parse_error("section header");
190                         }
191                         /* Right now we only have one section so just check it.
192                          * If more sections are added in the future, please don't
193                          * resort to cascading ifs with multiple strcasecmp calls.
194                          * That kind of bloated code is all too common.  A loop
195                          * and a string table would be a better choice unless the
196                          * number of sections is very small. */
197                         if (strcasecmp(s, "SUID") == 0) {
198                                 section = 1;
199                                 continue;
200                         }
201                         section = -1;   /* Unknown section so set to skip. */
202                         continue;
203                 }
204
205                 /* Process sections. */
206
207                 if (section == 1) {             /* SUID */
208                         /* Since we trimmed leading and trailing space above, we're
209                          * now looking for strings of the form
210                          *    <key>[::space::]*=[::space::]*<value>
211                          * where both key and value could contain inner whitespace. */
212
213                         /* First get the key (an applet name in our case). */
214                         if (!!(e = strchr(s, '='))) {
215                                 s = get_trimmed_slice(s, e);
216                         }
217                         if (!e || !*s) {        /* Missing '=' or empty key. */
218                                 parse_error("keyword");
219                         }
220
221                         /* Ok, we have an applet name.  Process the rhs if this
222                          * applet is currently built in and ignore it otherwise.
223                          * Note: This can hide config file bugs which only pop
224                          * up when the busybox configuration is changed. */
225                         if ((applet = find_applet_by_name(s))) {
226                                 /* Note: We currently don't check for duplicates!
227                                  * The last config line for each applet will be the
228                                  * one used since we insert at the head of the list.
229                                  * I suppose this could be considered a feature. */
230                                 sct = xmalloc(sizeof(struct BB_suid_config));
231                                 sct->m_applet = applet;
232                                 sct->m_mode = 0;
233                                 sct->m_next = sct_head;
234                                 sct_head = sct;
235
236                                 /* Get the specified mode. */
237
238                                 e = skip_whitespace(e+1);
239
240                                 for (i=0 ; i < 3 ; i++) {
241                                         const char *q;
242                                         if (!*(q = strchrnul(mode_chars + 5*i, *e++))) {
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                                 {
263                                         char *e2;
264
265                                         sct->m_uid = strtoul(s, &e2, 10);
266                                         if (*e2 || (s == e2)) {
267                                                 struct passwd *pwd = getpwnam(s);
268                                                 if (!pwd) {
269                                                         parse_error("user");
270                                                 }
271                                                 sct->m_uid = pwd->pw_uid;
272                                         }
273
274                                         sct->m_gid = strtoul(e, &e2, 10);
275                                         if (*e2 || (e == e2)) {
276                                                 struct group *grp;
277                                                 if (!(grp = getgrnam(e))) {
278                                                         parse_error("group");
279                                                 }
280                                                 sct->m_gid = grp->gr_gid;
281                                         }
282                                 }
283                         }
284                         continue;
285                 }
286
287                 /* Unknown sections are ignored. */
288
289                 /* Encountering configuration lines prior to seeing a
290                  * section header is treated as an error.  This is how
291                  * the old code worked, but it may not be desirable.
292                  * We may want to simply ignore such lines in case they
293                  * are used in some future version of busybox. */
294                 if (!section) {
295                         parse_error("keyword outside section");
296                 }
297
298         } while (1);
299
300  pe_label:
301         fprintf(stderr, "Parse error in %s, line %d: %s\n",
302                         config_file, lc, err);
303
304         fclose(f);
305         /* Release any allocated memory before returning. */
306         while (sct_head) {
307                 sct = sct_head->m_next;
308                 free(sct_head);
309                 sct_head = sct;
310         }
311         return;
312 }
313
314 #else
315 #define parse_config_file()
316 #endif /* CONFIG_FEATURE_SUID_CONFIG */
317
318 #ifdef CONFIG_FEATURE_SUID
319 static void check_suid(struct BB_applet *applet)
320 {
321         uid_t ruid = getuid();               /* real [ug]id */
322         uid_t rgid = getgid();
323
324 #ifdef CONFIG_FEATURE_SUID_CONFIG
325         if (suid_cfg_readable) {
326                 struct BB_suid_config *sct;
327
328                 for (sct = suid_config; sct; sct = sct->m_next) {
329                         if (sct->m_applet == applet)
330                                 break;
331                 }
332                 if (sct) {
333                         mode_t m = sct->m_mode;
334
335                         if (sct->m_uid == ruid)       /* same uid */
336                                 m >>= 6;
337                         else if ((sct->m_gid == rgid) || ingroup(ruid, sct->m_gid))  /* same group / in group */
338                                 m >>= 3;
339
340                         if (!(m & S_IXOTH))           /* is x bit not set ? */
341                                 bb_error_msg_and_die ("You have no permission to run this applet!");
342
343                         if ((sct->m_mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {     /* *both* have to be set for sgid */
344                                 xsetgid(sct->m_gid);
345                         } else xsetgid(rgid);                /* no sgid -> drop */
346
347                         if (sct->m_mode & S_ISUID) xsetuid(sct->m_uid);
348                         else xsetuid(ruid);                  /* no suid -> drop */
349                 } else {
350                         /* default: drop all privileges */
351                         xsetgid(rgid);
352                         xsetuid(ruid);
353                 }
354                 return;
355         } else {
356 #ifndef CONFIG_FEATURE_SUID_CONFIG_QUIET
357                 static int onetime = 0;
358
359                 if (!onetime) {
360                         onetime = 1;
361                         fprintf(stderr, "Using fallback suid method\n");
362                 }
363 #endif
364         }
365 #endif
366
367         if (applet->need_suid == _BB_SUID_ALWAYS) {
368                 if (geteuid()) bb_error_msg_and_die("Applet requires root privileges!");
369         } else if (applet->need_suid == _BB_SUID_NEVER) {
370                 xsetgid(rgid);                          /* drop all privileges */
371                 xsetuid(ruid);
372         }
373 }
374 #else
375 #define check_suid(x)
376 #endif /* CONFIG_FEATURE_SUID */
377
378
379
380 #ifdef CONFIG_FEATURE_COMPRESS_USAGE
381
382 #include "usage_compressed.h"
383 #include "unarchive.h"
384
385 static const char *unpack_usage_messages(void)
386 {
387         int input[2], output[2], pid;
388         char *buf;
389
390         if(pipe(input) < 0 || pipe(output) < 0)
391                 exit(1);
392
393         pid = fork();
394         switch (pid) {
395         case -1: /* error */
396                 exit(1);
397         case 0: /* child */
398                 close(input[1]);
399                 close(output[0]);
400                 uncompressStream(input[0], output[1]);
401                 exit(0);
402         }
403         /* parent */
404
405         close(input[0]);
406         close(output[1]);
407         pid = fork();
408         switch (pid) {
409         case -1: /* error */
410                 exit(1);
411         case 0: /* child */
412                 full_write(input[1], packed_usage, sizeof(packed_usage));
413                 exit(0);
414         }
415         /* parent */
416         close(input[1]);
417
418         buf = xmalloc(SIZEOF_usage_messages);
419         full_read(output[0], buf, SIZEOF_usage_messages);
420         return buf;
421 }
422
423 #else
424 #define unpack_usage_messages() usage_messages
425 #endif /* ENABLE_FEATURE_COMPRESS_USAGE */
426
427 void bb_show_usage(void)
428 {
429         if (ENABLE_SHOW_USAGE) {
430                 const char *format_string;
431                 const char *usage_string = unpack_usage_messages();
432                 int i;
433
434                 for (i = applet_using - applets; i > 0;)
435                         if (!*usage_string++) --i;
436
437                 format_string = "%s\n\nUsage: %s %s\n\n";
438                 if (*usage_string == '\b')
439                         format_string = "%s\n\nNo help available.\n\n";
440                 fprintf (stderr, format_string, bb_msg_full_version,
441                         applet_using->name, usage_string);
442         }
443
444         exit(xfunc_error_retval);
445 }
446
447 static int applet_name_compare(const void *name, const void *vapplet)
448 {
449         const struct BB_applet *applet = vapplet;
450
451         return strcmp(name, applet->name);
452 }
453
454 extern const size_t NUM_APPLETS;
455
456 struct BB_applet *find_applet_by_name(const char *name)
457 {
458         return bsearch(name, applets, NUM_APPLETS, sizeof(struct BB_applet),
459                                 applet_name_compare);
460 }
461
462 void run_applet_by_name(const char *name, int argc, char **argv)
463 {
464         if (ENABLE_FEATURE_SUID_CONFIG) parse_config_file();
465
466         if (!strncmp(name, "busybox", 7)) busybox_main(argc, argv);
467         /* Do a binary search to find the applet entry given the name. */
468         applet_using = find_applet_by_name(name);
469         if (applet_using) {
470                 applet_name = applet_using->name;
471                 if(argc==2 && !strcmp(argv[1], "--help")) bb_show_usage();
472                 if(ENABLE_FEATURE_SUID) check_suid(applet_using);
473                 exit((*(applet_using->main))(argc, argv));
474         }
475 }