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