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