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