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