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