chiark / gitweb /
checkpath.c: Rename global flags and put their definitions in constact.
[checkpath] / checkpath.c
1 /* -*-c-*-
2  *
3  * Check a path for safety
4  *
5  * (c) 1999 Mark Wooding
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of chkpath.
11  *
12  * chkpath is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * chkpath is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with chkpath; if not, write to the Free Software Foundation,
24  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25  */
26
27 /*----- Header files ------------------------------------------------------*/
28
29 #include "config.h"
30
31 #include <errno.h>
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <unistd.h>
40
41 #include <pwd.h>
42 #include <grp.h>
43
44 #include <mLib/alloc.h>
45 #include <mLib/dstr.h>
46 #include <mLib/macros.h>
47
48 #include "checkpath.h"
49
50 /*----- Data structures ---------------------------------------------------*/
51
52 /* --- An item in the directory list --- *
53  *
54  * Each directory becomes an element on a list which is manipulated in a
55  * stack-like way.
56  */
57
58 struct elt {
59   struct elt *e_link;                   /* Pointer to the next one along */
60   size_t e_offset;                      /* Offset of name in path string */
61   unsigned e_flags;                     /* Various useful flags */
62 #define EF_STICKY 1u                    /*   Directory has sticky bit set */
63   char e_name[1];                       /* Name of the directory */
64 };
65
66
67 /*----- Static variables --------------------------------------------------*/
68
69 static const struct elt rootnode = { 0, 0, 0 }; /* Root of the list */
70 static struct elt *sp;                  /* Stack pointer for list */
71 static dstr d = DSTR_INIT;              /* Current path string */
72
73 /*----- Main code ---------------------------------------------------------*/
74
75 /* --- @splitpath@ --- *
76  *
77  * Arguments:   @const char *path@ = path string to break apart
78  *              @struct elt *tail@ = tail block to attach to end of list
79  *
80  * Returns:     Pointer to the new list head.
81  *
82  * Use:         Breaks a path string into directories and adds each one
83  *              as a node on the list, in the right order.  These can then
84  *              be pushed onto the directory stack as required.
85  */
86
87 static struct elt *splitpath(const char *path, struct elt *tail)
88 {
89   struct elt *head, **ee = &head, *e;
90
91   while (*path) {
92     size_t n;
93
94     /* --- Either a leading `/', or a doubled one --- *
95      *
96      * Either way, ignore it.
97      */
98
99     if (*path == '/') {
100       path++;
101       continue;
102     }
103
104     /* --- Skip to the next directory separator --- *
105      *
106      * Build a list element for it, and link it on.
107      */
108
109     n = strcspn(path, "/");
110     e = xmalloc(sizeof(struct elt) + n + 1);
111     memcpy(e->e_name, path, n);
112     e->e_name[n] = 0;
113     e->e_flags = 0;
114     *ee = e;
115     ee = &e->e_link;
116     path += n;
117   }
118
119   /* --- Done --- */
120
121   *ee = tail;
122   return (head);
123 }
124
125 /* --- @pop@ --- *
126  *
127  * Arguments:   ---
128  *
129  * Returns:     ---
130  *
131  * Use:         Removes the top item from the directory stack.
132  */
133
134 static void pop(void)
135 {
136   if (sp->e_link) {
137     struct elt *e = sp->e_link;
138     d.len = sp->e_offset;
139     DPUTZ(&d);
140     xfree(sp); sp = e;
141   }
142 }
143
144 /* --- @popall@ --- *
145  *
146  * Arguments:   ---
147  *
148  * Returns:     ---
149  *
150  * Use:         Removes all the items from the directory stack.
151  */
152
153 static void popall(void)
154   { while (sp->e_link) pop(); }
155
156 /* --- @push@ --- *
157  *
158  * Arguments:   @struct elt *e@ = pointer to directory element
159  *
160  * Returns:     ---
161  *
162  * Use:         Pushes a new subdirectory onto the stack.
163  */
164
165 static void push(struct elt *e)
166 {
167   e->e_link = sp;
168   e->e_offset = d.len;
169   DPUTC(&d, '/');
170   DPUTS(&d, e->e_name);
171   sp = e;
172 }
173
174 /* --- @report@ --- *
175  *
176  * Arguments:   @const struct checkpath *cp@ = pointer to context
177  *              @unsigned what@ = what sort of report is this?
178  *              @int verbose@ = how verbose is this?
179  *              @const char *p@ = what path does it refer to?
180  *              @const char *msg@ = the message to give to the user
181  *
182  * Returns:     ---
183  *
184  * Use:         Formats and presents messages to the client.
185  */
186
187 static void report(const struct checkpath *cp, unsigned what, int verbose,
188                    const char *p, const char *msg, ...)
189 {
190   dstr d = DSTR_INIT;
191   va_list ap;
192   const char *q = msg;
193   const char *s;
194   size_t n;
195   int e = errno;
196   uid_t u;
197   struct passwd *pw;
198   gid_t g;
199   struct group *gr;
200
201   /* --- Decide whether to bin this message --- */
202
203   if (!cp->cp_report || verbose > cp->cp_verbose || !(cp->cp_what & what))
204     return;
205
206   /* --- If no reporting, do the easy thing --- */
207
208   if (!(cp->cp_what & CP_REPORT)) {
209     cp->cp_report(what, verbose, p, 0, cp->cp_arg);
210     return;
211   }
212
213   /* --- Format the message nicely --- */
214
215   va_start(ap, msg);
216   if (verbose > 1)
217     dstr_puts(&d, "[ ");
218   if (p)
219     dstr_putf(&d, "Path: %s: ", p);
220   while (*q) {
221     if (*q == '%') {
222       q++;
223       switch (*q) {
224         case 'e':
225           dstr_puts(&d, strerror(e));
226           break;
227         case 'u':
228           u = (uid_t)va_arg(ap, int);
229           if ((pw = getpwuid(u)) != 0)
230             dstr_putf(&d, "`%s'", pw->pw_name);
231           else
232             dstr_putf(&d, "%i", (int)u);
233           break;
234         case 'g':
235           g = (gid_t)va_arg(ap, int);
236           if ((gr = getgrgid(g)) != 0)
237             dstr_putf(&d, "`%s'", gr->gr_name);
238           else
239             dstr_putf(&d, "%i", (int)g);
240           break;
241         case 's':
242           s = va_arg(ap, const char *);
243           dstr_puts(&d, s);
244           break;
245         case '%':
246           dstr_putc(&d, '%');
247           break;
248         default:
249           dstr_putc(&d, '%');
250           dstr_putc(&d, *q);
251           break;
252       }
253       q++;
254     } else {
255       n = strcspn(q, "%");
256       DPUTM(&d, q, n);
257       q += n;
258     }
259   }
260   if (verbose > 1)
261     dstr_puts(&d, " ]");
262   DPUTZ(&d);
263   cp->cp_report(what, verbose, p, d.buf, cp->cp_arg);
264   dstr_destroy(&d);
265   va_end(ap);
266 }
267
268 /* --- @sanity@ --- *
269  *
270  * Arguments:   @const char *p@ = name of directory to check
271  *              @struct stat *st@ = pointer to @stat@(2) block for it
272  *              @const struct checkpath *cp@ = pointer to caller parameters
273  *              @unsigned f@ = various flags (@SF_...@)
274  *
275  * Returns:     Zero if everything's OK, else bitmask of problems.
276  *
277  * Use:         Performs the main load of sanity-checking on a directory.
278  *              If @SF_LAST@ is not set then sticky directories are always
279  *              acceptable.
280  */
281
282 #define SF_LAST 1u                      /* This is the final item to check */
283
284 static unsigned sanity(const char *p, struct stat *st,
285                        const struct checkpath *cp, unsigned f)
286 {
287   unsigned bad = 0;
288   int stickyok = 0;
289   int i;
290   unsigned b;
291
292   if (S_ISDIR(st->st_mode) &&
293       (!(f & SF_LAST) || (cp->cp_what & CP_STICKYOK)))
294     stickyok = 01000;
295
296   /* --- Check for world-writability --- */
297
298   if ((cp->cp_what & CP_WRWORLD) &&
299       (st->st_mode & (0002 | stickyok)) == 0002) {
300     bad |= CP_WRWORLD;
301     report(cp, CP_WRWORLD, 1, p, "** world writable **");
302   }
303
304   /* --- Check for group-writability --- */
305
306   if ((cp->cp_what & (CP_WRGRP | CP_WROTHGRP)) &&
307       (st->st_mode & (0020 | stickyok)) == 0020) {
308     b = CP_WRGRP;
309
310     if (cp->cp_what & CP_WROTHGRP) {
311       b = CP_WROTHGRP;
312       for (i = 0; i < cp->cp_gids; i++) {
313         if (st->st_gid == cp->cp_gid[i])
314           b = cp->cp_what & CP_WRGRP;
315       }
316     }
317     if (b) {
318       bad |= b;
319       report(cp, b, 1, p, "writable by %sgroup %g",
320              (b == CP_WROTHGRP) ? "other " : "", st->st_gid);
321     }
322   }
323
324   /* --- Check for user-writability --- */
325
326   if ((cp->cp_what & CP_WROTHUSR) &&
327       st->st_uid != cp->cp_uid &&
328       st->st_uid != 0) {
329     bad |= CP_WROTHUSR;
330     report(cp, CP_WROTHUSR, 1, p, "owner is user %u", st->st_uid);
331   }
332
333   /* --- Done sanity check --- */
334
335   return (bad);
336 }
337
338 /* --- @checkpath@ --- *
339  *
340  * Arguments:   @const char *p@ = directory name which needs checking
341  *              @const struct checkpath *cp@ = parameters for the check
342  *
343  * Returns:     Zero if all is well, otherwise bitmask of problems.
344  *
345  * Use:         Scrutinises a directory path to see what evil things other
346  *              users could do to it.
347  */
348
349 unsigned checkpath(const char *p, const struct checkpath *cp)
350 {
351   char cwd[PATH_MAX];
352   struct elt *e, *ee;
353   struct stat st;
354   unsigned bad = 0;
355
356   /* --- Initialize stack pointer and path string --- */
357
358   sp = (/*unconst*/ struct elt *)&rootnode;
359   dstr_destroy(&d);
360
361   /* --- Try to find the current directory --- */
362
363   if (!getcwd(cwd, sizeof(cwd))) {
364     report(cp, CP_ERROR, 0, 0, "can't find current directory: %e");
365     return (CP_ERROR);
366   }
367
368   /* --- Check that the root directory is OK --- */
369
370   if (stat("/", &st)) {
371     report(cp, CP_ERROR, 0, 0, "can't stat root directory: %e");
372     return (CP_ERROR);
373   }
374
375   report(cp, CP_REPORT, 3, p, "begin scan");
376   bad |= sanity("/", &st, cp, 0);
377
378   /* --- Get the initial list of things to process --- */
379
380   ee = splitpath(p, 0);
381   if (*p != '/')
382     ee = splitpath(cwd, ee);
383
384   /* --- While there are list items which still need doing --- */
385
386   while (ee) {
387     e = ee->e_link;
388
389     /* --- Strip off simple `.' elements --- */
390
391     if (strcmp(ee->e_name, ".") == 0) {
392       xfree(ee);
393       ee = e;
394       continue;
395     }
396
397     /* --- Backtrack on `..' elements --- */
398
399     else if (strcmp(ee->e_name, "..") == 0) {
400       pop();
401       xfree(ee);
402       ee = e;
403       continue;
404     }
405
406     /* --- Everything else gets pushed on the end --- */
407
408     push(ee);
409     ee = e;
410
411     /* --- Find out what sort of a thing this is --- */
412
413     if (lstat(d.buf, &st)) {
414       report(cp, CP_ERROR, 0, d.buf, "can't stat: %e");
415       bad |= CP_ERROR;
416       break;
417     }
418
419     /* --- Handle symbolic links specially --- */
420
421     if (S_ISLNK(st.st_mode)) {
422       dstr buf = DSTR_INIT;
423       int i;
424
425       /* --- Resolve the link --- */
426
427       dstr_ensure(&buf, st.st_size + 1);
428       if ((i = readlink(d.buf, buf.buf, buf.sz)) < 0) {
429         report(cp, CP_ERROR, 0, d.buf, "can't readlink: %e");
430         bad |= CP_ERROR;
431         break;
432       }
433       buf.buf[i] = 0;
434       report(cp, CP_SYMLINK, 2, d.buf, "symlink -> `%s'", buf.buf);
435
436       /* --- Handle sticky parents --- *
437        *
438        * If I make a symlink in a sticky directory, I can later modify it.
439        * However, nobody else can (except the owner of the directory, and
440        * we'll already have noticed that if we care).
441        */
442
443       if ((cp->cp_what & CP_WROTHUSR) &&
444           (sp->e_link->e_flags & EF_STICKY) &&
445           st.st_uid != cp->cp_uid && st.st_uid != 0) {
446         bad |= CP_WROTHUSR;
447         report(cp, CP_WROTHUSR, 1, d.buf,
448                "symlink modifiable by user %u", st.st_uid);
449       }
450
451       /* --- Sort out what to do from here --- */
452
453       if (buf.buf[0] == '/')
454         popall();
455       else
456         pop();
457       ee = splitpath(buf.buf, ee);
458       dstr_destroy(&buf);
459       continue;
460     }
461
462     /* --- Run the sanity check on this path element --- */
463
464     bad |= sanity(d.buf, &st, cp, ee ? 0 : SF_LAST);
465
466     if (S_ISDIR(st.st_mode)) {
467       if (st.st_mode & 01000)
468         sp->e_flags |= EF_STICKY;
469       report(cp, CP_REPORT, 4, d.buf, "directory");
470       continue;
471     }
472
473     /* --- Something else I don't understand --- */
474
475     break;
476   }
477
478   /* --- Check for leftover junk --- */
479
480   if (ee) {
481     if (!(bad & CP_ERROR))
482       report(cp, CP_ERROR, 0, 0, "junk left over after reaching leaf");
483     while (ee) {
484       e = ee->e_link;
485       xfree(ee);
486       ee = e;
487     }
488   }
489
490   popall();
491   return (bad);
492 }
493
494 /* --- @checkpath_addgid@ --- *
495  *
496  * Arguments:   @struct checkpath *cp@ = pointer to block to fill in
497  *              @gid_t g@ = group id to add
498  *
499  * Returns:     Zero if successful, nonzero if the array is full.
500  *
501  * Use:         Adds the group @g@ to the structure.
502  */
503
504 int checkpath_addgid(struct checkpath *cp, gid_t g)
505 {
506   int i;
507
508   for (i = 0; i < cp->cp_gids; i++) {
509     if (cp->cp_gid[i] == g)
510       return (0);
511   }
512   if (cp->cp_gids >= N(cp->cp_gid))
513     return (-1);
514   cp->cp_gid[cp->cp_gids++] = g;
515   return (0);
516 }
517
518 /* --- @checkpath_setuid@ --- *
519  *
520  * Arguments:   @struct checkpath *cp@ = pointer to block to fill in
521  *
522  * Returns:     ---
523  *
524  * Use:         Fills in the @cp_uid@ slot of the structure with the real uid
525  *              of the current process.
526  */
527
528 void checkpath_setuid(struct checkpath *cp) { cp->cp_uid = getuid(); }
529
530 /* --- @checkpath_setgid@ --- *
531  *
532  * Arguments:   @struct checkpath *cp@ = pointer to block to fill in
533  *
534  * Returns:     Zero if successful, nonzero if the array is full.
535  *
536  * Use:         Adds the real gid of the current process to the @cp_gid@
537  *              array.
538  */
539
540 int checkpath_setgid(struct checkpath *cp)
541   { return (checkpath_addgid(cp, getgid())); }
542
543 /* --- @checkpath_setgroups@ --- *
544  *
545  * Arguments:   @struct checkpath *cp@ = pointer to block to fill in
546  *
547  * Returns:     Zero if successful, nonzero if the array is full.
548  *
549  * Use:         Adds the current process's supplementary groups to the
550  *              @cp_gid@ table.
551  */
552
553 int checkpath_setgroups(struct checkpath *cp)
554 {
555   int i, n;
556   gid_t gg[NGROUPS_MAX];
557
558   n = getgroups(N(gg), gg);
559   for (i = 0; i < n; i++) {
560     if (checkpath_addgid(cp, gg[i]))
561       return (-1);
562   }
563   return (0);
564 }
565
566 /* --- @checkpath_setids@ --- *
567  *
568  * Arguments:   @struct checkpath *cp@ = pointer to block to fill in
569  *
570  * Returns:     ---
571  *
572  * Use:         Fills in the user ids and things in the structure.  This is
573  *              equivalent to setting @cp_gids = 0@ and then calling
574  *              @_setuid@, @_setgid@ and @_setgroups@.  It can't fail.
575  */
576
577 void checkpath_setids(struct checkpath *cp)
578 {
579   cp->cp_gids = 0;
580   checkpath_setuid(cp);
581   checkpath_setgid(cp);
582   checkpath_setgroups(cp);
583 }
584
585 /*----- That's all, folks -------------------------------------------------*/