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