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