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