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