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