chiark / gitweb /
checkpath.c: Describe the `struct checkpath' as `query', not `context'.
[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   size_t n;
91
92   while (*path) {
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 query
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 query
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 = S_ISVTX;
295
296   /* --- Check for world-writability --- */
297
298   if ((cp->cp_what & CP_WRWORLD) &&
299       (st->st_mode & (S_IWOTH | stickyok)) == S_IWOTH) {
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 & (S_IWGRP | stickyok)) == S_IWGRP) {
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   dstr buf = DSTR_INIT;
356   int i;
357
358   /* --- Initialize stack pointer and path string --- */
359
360   sp = (/*unconst*/ struct elt *)&rootnode;
361   dstr_destroy(&d);
362
363   /* --- Try to find the current directory --- */
364
365   if (!getcwd(cwd, sizeof(cwd))) {
366     report(cp, CP_ERROR, 0, 0, "can't find current directory: %e");
367     return (CP_ERROR);
368   }
369
370   /* --- Check that the root directory is OK --- */
371
372   if (stat("/", &st)) {
373     report(cp, CP_ERROR, 0, 0, "can't stat root directory: %e");
374     return (CP_ERROR);
375   }
376
377   report(cp, CP_REPORT, 3, p, "begin scan");
378   bad |= sanity("/", &st, cp, 0);
379
380   /* --- Get the initial list of things to process --- */
381
382   ee = splitpath(p, 0);
383   if (*p != '/')
384     ee = splitpath(cwd, ee);
385
386   /* --- While there are list items which still need doing --- */
387
388   while (ee) {
389     e = ee->e_link;
390
391     /* --- Strip off simple `.' elements --- */
392
393     if (strcmp(ee->e_name, ".") == 0) {
394       xfree(ee);
395       ee = e;
396       continue;
397     }
398
399     /* --- Backtrack on `..' elements --- */
400
401     else if (strcmp(ee->e_name, "..") == 0) {
402       pop();
403       xfree(ee);
404       ee = e;
405       continue;
406     }
407
408     /* --- Everything else gets pushed on the end --- */
409
410     push(ee);
411     ee = e;
412
413     /* --- Find out what sort of a thing this is --- */
414
415     if (lstat(d.buf, &st)) {
416       report(cp, CP_ERROR, 0, d.buf, "can't stat: %e");
417       bad |= CP_ERROR;
418       break;
419     }
420
421     /* --- Handle symbolic links specially --- */
422
423     if (S_ISLNK(st.st_mode)) {
424
425       /* --- Resolve the link --- */
426
427       dstr_reset(&buf);
428       dstr_ensure(&buf, st.st_size + 1);
429       if ((i = readlink(d.buf, buf.buf, buf.sz)) < 0) {
430         report(cp, CP_ERROR, 0, d.buf, "can't readlink: %e");
431         bad |= CP_ERROR;
432         break;
433       }
434       buf.buf[i] = 0;
435       report(cp, CP_SYMLINK, 2, d.buf, "symlink -> `%s'", buf.buf);
436
437       /* --- Handle sticky parents --- *
438        *
439        * If I make a symlink in a sticky directory, I can later modify it.
440        * However, nobody else can (except the owner of the directory, and
441        * we'll already have noticed that if we care).
442        */
443
444       if ((cp->cp_what & CP_WROTHUSR) &&
445           (sp->e_link->e_flags & EF_STICKY) &&
446           st.st_uid != cp->cp_uid && st.st_uid != 0) {
447         bad |= CP_WROTHUSR;
448         report(cp, CP_WROTHUSR, 1, d.buf,
449                "symlink modifiable by user %u", st.st_uid);
450       }
451
452       /* --- Sort out what to do from here --- */
453
454       if (buf.buf[0] == '/')
455         popall();
456       else
457         pop();
458       ee = splitpath(buf.buf, ee);
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 & S_ISVTX)
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   dstr_destroy(&buf);
492   return (bad);
493 }
494
495 /* --- @checkpath_addgid@ --- *
496  *
497  * Arguments:   @struct checkpath *cp@ = pointer to block to fill in
498  *              @gid_t g@ = group id to add
499  *
500  * Returns:     Zero if successful, nonzero if the array is full.
501  *
502  * Use:         Adds the group @g@ to the structure.
503  */
504
505 int checkpath_addgid(struct checkpath *cp, gid_t g)
506 {
507   int i;
508
509   for (i = 0; i < cp->cp_gids; i++) {
510     if (cp->cp_gid[i] == g)
511       return (0);
512   }
513   if (cp->cp_gids >= N(cp->cp_gid))
514     return (-1);
515   cp->cp_gid[cp->cp_gids++] = g;
516   return (0);
517 }
518
519 /* --- @checkpath_setuid@ --- *
520  *
521  * Arguments:   @struct checkpath *cp@ = pointer to block to fill in
522  *
523  * Returns:     ---
524  *
525  * Use:         Fills in the @cp_uid@ slot of the structure with the real uid
526  *              of the current process.
527  */
528
529 void checkpath_setuid(struct checkpath *cp) { cp->cp_uid = getuid(); }
530
531 /* --- @checkpath_setgid@ --- *
532  *
533  * Arguments:   @struct checkpath *cp@ = pointer to block to fill in
534  *
535  * Returns:     Zero if successful, nonzero if the array is full.
536  *
537  * Use:         Adds the real gid of the current process to the @cp_gid@
538  *              array.
539  */
540
541 int checkpath_setgid(struct checkpath *cp)
542   { return (checkpath_addgid(cp, getgid())); }
543
544 /* --- @checkpath_setgroups@ --- *
545  *
546  * Arguments:   @struct checkpath *cp@ = pointer to block to fill in
547  *
548  * Returns:     Zero if successful, nonzero if the array is full.
549  *
550  * Use:         Adds the current process's supplementary groups to the
551  *              @cp_gid@ table.
552  */
553
554 int checkpath_setgroups(struct checkpath *cp)
555 {
556   int i, n;
557   gid_t gg[NGROUPS_MAX];
558
559   n = getgroups(N(gg), gg);
560   for (i = 0; i < n; i++) {
561     if (checkpath_addgid(cp, gg[i]))
562       return (-1);
563   }
564   return (0);
565 }
566
567 /* --- @checkpath_setids@ --- *
568  *
569  * Arguments:   @struct checkpath *cp@ = pointer to block to fill in
570  *
571  * Returns:     ---
572  *
573  * Use:         Fills in the user ids and things in the structure.  This is
574  *              equivalent to setting @cp_gids = 0@ and then calling
575  *              @_setuid@, @_setgid@ and @_setgroups@.  It can't fail.
576  */
577
578 void checkpath_setids(struct checkpath *cp)
579 {
580   cp->cp_gids = 0;
581   checkpath_setuid(cp);
582   checkpath_setgid(cp);
583   checkpath_setgroups(cp);
584 }
585
586 /*----- That's all, folks -------------------------------------------------*/