chiark / gitweb /
Use a dynamic string for reading symlinks.
[checkpath] / path.c
1 /* -*-c-*-
2  *
3  * $Id: path.c,v 1.2 1999/05/18 20:49:12 mdw Exp $
4  *
5  * Check a path for safety
6  *
7  * (c) 1999 Mark Wooding
8  */
9
10 /*----- Licensing notice --------------------------------------------------* 
11  *
12  * This file is part of chkpath.
13  *
14  * chkpath is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 2 of the License, or
17  * (at your option) any later version.
18  * 
19  * chkpath is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  * 
24  * You should have received a copy of the GNU General Public License
25  * along with chkpath; if not, write to the Free Software Foundation,
26  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27  */
28
29 /*----- Revision history --------------------------------------------------* 
30  *
31  * $Log: path.c,v $
32  * Revision 1.2  1999/05/18 20:49:12  mdw
33  * Use a dynamic string for reading symlinks.
34  *
35  * Revision 1.1.1.1  1999/04/06 20:12:07  mdw
36  * Import new project.
37  *
38  */
39
40 /*----- Header files ------------------------------------------------------*/
41
42 #include <errno.h>
43 #include <stdarg.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47
48 #include <sys/types.h>
49 #include <sys/stat.h>
50 #include <unistd.h>
51
52 #include <pwd.h>
53 #include <grp.h>
54
55 #include <mLib/alloc.h>
56 #include <mLib/dstr.h>
57
58 #include "path.h"
59
60 /*----- Data structures ---------------------------------------------------*/
61
62 /* --- An item in the directory list --- *
63  *
64  * Each directory becomes an element on a list which is manipulated in a
65  * stack-like way.
66  */
67
68 struct elt {
69   struct elt *e_link;                   /* Pointer to the next one along */
70   size_t e_offset;                      /* Offset of name in path string */
71   unsigned e_flags;                     /* Various useful flags */
72   char e_name[1];                       /* Name of the directory */
73 };
74
75 enum {
76   f_sticky = 1                          /* Directory has sticky bit set */
77 };
78
79 enum {
80   f_last = 1                            /* This is the final item to check */
81 };
82
83 /*----- Static variables --------------------------------------------------*/
84
85 static struct elt rootnode = { 0, 0, 0 }; /* Root of the list */
86 static struct elt *sp;                  /* Stack pointer for list */
87 static dstr d;                          /* Current path string */
88
89 /*----- Main code ---------------------------------------------------------*/
90
91 /* --- @splitpath@ --- *
92  *
93  * Arguments:   @const char *path@ = path string to break apart
94  *              @struct elt *tail@ = tail block to attach to end of list
95  *
96  * Returns:     Pointer to the new list head.
97  *
98  * Use:         Breaks a path string into directories and adds each one
99  *              as a node on the list, in the right order.  These can then
100  *              be pushed onto the directory stack as required.
101  */
102
103 static struct elt *splitpath(const char *path, struct elt *tail)
104 {
105   struct elt *head, **ee = &head, *e;
106
107   while (*path) {
108     size_t n;
109
110     /* --- Either a leading `/', or a doubled one --- *
111      *
112      * Either way, ignore it.
113      */
114
115     if (*path == '/') {
116       path++;
117       continue;
118     }
119
120     /* --- Skip to the next directory separator --- *
121      *
122      * Build a list element for it, and link it on.
123      */
124
125     n = strcspn(path, "/");
126     e = xmalloc(sizeof(struct elt) + n + 1);
127     memcpy(e->e_name, path, n);
128     e->e_name[n] = 0;
129     e->e_flags = 0;
130     *ee = e;
131     ee = &e->e_link;
132     path += n;
133   }
134
135   /* --- Done --- */
136
137   *ee = tail;
138   return (head);
139 }
140
141 /* --- @pop@ --- *
142  *
143  * Arguments:   ---
144  *
145  * Returns:     ---
146  *
147  * Use:         Removes the top item from the directory stack.
148  */
149
150 static void pop(void)
151 {
152   if (sp->e_link) {
153     struct elt *e = sp->e_link;
154     d.len = sp->e_offset;
155     DPUTZ(&d);
156     sp = e;
157   }
158 }
159
160 /* --- @popall@ --- *
161  *
162  * Arguments:   ---
163  *
164  * Returns:     ---
165  *
166  * Use:         Removes all the items from the directory stack.
167  */
168
169 static void popall(void)
170 {
171   while (sp->e_link)
172     pop();
173 }
174
175 /* --- @push@ --- *
176  *
177  * Arguments:   @struct elt *e@ = pointer to directory element
178  *
179  * Returns:     ---
180  *
181  * Use:         Pushes a new subdirectory onto the stack.
182  */
183
184 static void push(struct elt *e)
185 {
186   e->e_link = sp;
187   e->e_offset = d.len;
188   DPUTC(&d, '/');
189   DPUTS(&d, e->e_name);
190   sp = e;
191 }
192
193 /* --- @report@ --- *
194  *
195  * Arguments:   @struct chkpath *cp@ = pointer to context
196  *              @int what@ = what sort of report is this?
197  *              @int verbose@ = how verbose is this?
198  *              @const char *p@ = what path does it refer to?
199  *              @const char *msg@ = the message to give to the user
200  *
201  * Returns:     ---
202  *
203  * Use:         Formats and presents messages to the client.
204  */
205
206 static void report(struct chkpath *cp, int what, int verbose,
207                    const char *p, const char *msg, ...)
208 {
209   /* --- Decide whether to bin this message --- */
210
211   if (!cp->cp_report || verbose > cp->cp_verbose || !(cp->cp_what & what))
212     return;
213
214   /* --- Format the message nicely --- */
215
216   if (cp->cp_what & CP_REPORT) {
217     dstr d;
218     va_list ap;
219     const char *q = msg;
220     size_t n;
221     int e = errno;
222
223     dstr_create(&d);
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             uid_t u = (uid_t)va_arg(ap, int);
238             struct passwd *pw = getpwuid(u);
239             if (pw)
240               dstr_putf(&d, "`%s'", pw->pw_name);
241             else
242               dstr_putf(&d, "%i", (int)u);
243           } break;
244           case 'g': {
245             gid_t g = (gid_t)va_arg(ap, int);
246             struct group *gr = getgrgid(g);
247             if (gr)
248               dstr_putf(&d, "`%s'", gr->gr_name);
249             else
250               dstr_putf(&d, "%i", (int)g);
251           } break;
252           case 's': {
253             const char *s = va_arg(ap, const char *);
254             dstr_puts(&d, s);
255           } break;
256           case '%':
257             dstr_putc(&d, '%');
258             break;
259           default:
260             dstr_putc(&d, '%');
261             dstr_putc(&d, *q);
262             break;
263         }
264         q++;
265       } else {
266         n = strcspn(q, "%");
267         DPUTM(&d, q, n);
268         q += n;
269       }
270     }
271     if (verbose > 1)
272       dstr_puts(&d, " ]");
273     DPUTZ(&d);
274     cp->cp_report(what, verbose, p, d.buf, cp->cp_arg);
275     dstr_destroy(&d);
276     va_end(ap);
277   } else
278     cp->cp_report(what, verbose, p, 0, cp->cp_arg);
279 }
280
281 /* --- @sanity@ --- *
282  *
283  * Arguments:   @const char *p@ = name of directory to check
284  *              @struct stat *st@ = pointer to @stat@(2) block for it
285  *              @struct chkpath *cp@ = pointer to caller parameters
286  *              @unsigned f@ = various flags
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  */
292
293 static int sanity(const char *p, struct stat *st,
294                   struct chkpath *cp, unsigned f)
295 {
296   int bad = 0;
297   int sticky = (cp->cp_what & CP_STICKYOK) || !(f & f_last) ? 01000 : 0;
298
299   /* --- Check for world-writability --- */
300
301   if ((cp->cp_what & CP_WRWORLD) &&
302       (st->st_mode & (0002 | sticky)) == 0002) {
303     bad |= CP_WRWORLD;
304     report(cp, CP_WRWORLD, 1, p, "** world writable **");
305   }
306
307   /* --- Check for group-writability --- */
308
309   if ((cp->cp_what & (CP_WRGRP | CP_WROTHGRP)) &&
310       (st->st_mode & (0020 | sticky)) == 0020) {
311     if (cp->cp_what & CP_WRGRP) {
312       bad |= CP_WRGRP;
313       report(cp, CP_WRGRP, 1, p, "writable by group %g", st->st_gid);
314     } else {
315       int i;
316       for (i = 0; i < cp->cp_gids; i++) {
317         if (st->st_gid == cp->cp_gid[i])
318           goto good_gid;
319       }
320       bad |= CP_WROTHGRP;
321       report(cp, CP_WROTHGRP, 1, p, "writable by group %g", st->st_gid);
322     good_gid:;
323     }
324   }
325
326   /* --- Check for user-writability --- */
327
328   if ((cp->cp_what & CP_WROTHUSR) &&
329       st->st_uid != cp->cp_uid &&
330       st->st_uid != 0) {
331     bad |= CP_WROTHUSR;
332     report(cp, CP_WROTHUSR, 1, p, "owner is user %u", st->st_uid);
333   }
334
335   /* --- Done sanity check --- */
336
337   return (bad);
338 }
339
340 /* --- @path_check@ --- *
341  *
342  * Arguments:   @const char *p@ = directory name which needs checking
343  *              @struct chkpath *cp@ = caller parameters for the check
344  *
345  * Returns:     Zero if all is well, otherwise bitmask of problems.
346  *
347  * Use:         Scrutinises a directory path to see what evil things other
348  *              users could do to it.
349  */
350
351 int path_check(const char *p, struct chkpath *cp)
352 {
353   char cwd[PATH_MAX];
354   struct elt *e, *ee;
355   struct stat st;
356   int bad = 0;
357
358   /* --- Initialise stack pointer and path string --- */
359
360   sp = &rootnode;
361   dstr_destroy(&d);
362
363   /* --- Try to find the current directory --- */
364
365   if (!getcwd(cwd, sizeof(cwd))) {
366     report(cp, CP_ERROR, 0, 0, "can't find current directory: %e");
367     return (CP_ERROR);
368   }
369
370   /* --- Check that the root directory is OK --- */
371
372   if (stat("/", &st)) {
373     report(cp, CP_ERROR, 0, 0, "can't stat root directory: %e");
374     return (CP_ERROR);
375   }
376
377   report(cp, CP_REPORT, 3, p, "begin scan");
378   bad |= sanity("/", &st, cp, 0);
379
380   /* --- Get the initial list of things to process --- */
381
382   ee = splitpath(p, 0);
383   if (*p != '/')
384     ee = splitpath(cwd, ee);
385
386   /* --- While there are list items which still need doing --- */
387
388   while (ee) {
389     e = ee->e_link;
390
391     /* --- Strip off simple `.' elements --- */
392
393     if (strcmp(ee->e_name, ".") == 0) {
394       free(ee);
395       ee = e;
396       continue;
397     }
398
399     /* --- Backtrack on `..' elements --- */
400
401     else if (strcmp(ee->e_name, "..") == 0) {
402       pop();
403       free(ee);
404       ee = e;
405       continue;
406     }
407
408     /* --- Everything else gets pushed on the end --- */
409
410     push(ee);
411     ee = e;
412
413     /* --- Find out what sort of a thing this is --- */
414
415     if (lstat(d.buf, &st)) {
416       report(cp, CP_ERROR, 0, d.buf, "can't stat: %e");
417       bad |= CP_ERROR;
418       break;
419     }
420
421     /* --- Handle symbolic links specially --- */
422
423     if (S_ISLNK(st.st_mode)) {
424       dstr buf;
425       int i;
426
427       /* --- Resolve the link --- */
428
429       dstr_create(&buf);
430       dstr_ensure(&buf, st.st_size + 1);
431       if ((i = readlink(d.buf, buf.buf, buf.sz)) < 0) {
432         report(cp, CP_ERROR, 0, d.buf, "can't readlink: %e");
433         bad |= CP_ERROR;
434         break;
435       }
436       buf.buf[i] = 0;
437       report(cp, CP_SYMLINK, 2, d.buf, "symlink -> `%s'", buf.buf);
438
439       /* --- Handle sticky parents --- *
440        *
441        * If I make a symlink in a sticky directory, I can later modify it.
442        * However, nobody else can (except the owner of the directory, and
443        * we'll already have noticed that if we care).
444        */
445
446       if ((cp->cp_what & CP_WROTHUSR) &&
447           (sp->e_link->e_flags & f_sticky) &&
448           st.st_uid != cp->cp_uid && st.st_uid != 0) {
449         bad |= CP_WROTHUSR;
450         report(cp, CP_WROTHUSR, 1, d.buf,
451                "symlink modifiable by user %u", st.st_uid);
452       }
453
454       /* --- Sort out what to do from here --- */
455
456       if (buf.buf[0] == '/')
457         popall();
458       else
459         pop();
460       ee = splitpath(buf.buf, ee);
461       dstr_destroy(&buf);
462       continue;
463     }
464
465     /* --- Run the sanity check on this path element --- */
466
467     bad |= sanity(d.buf, &st, cp, ee ? 0 : f_last);
468
469     if (S_ISDIR(st.st_mode)) {
470       if (st.st_mode & 01000)
471         sp->e_flags |= f_sticky;
472       report(cp, CP_REPORT, 4, d.buf, "directory");
473       continue;
474     }
475
476     /* --- Something else I don't understand --- */
477
478     break;
479   }
480
481   /* --- Check for leftover junk --- */
482
483   if (ee) {
484     if (!(bad & CP_ERROR))
485       report(cp, CP_ERROR, 0, 0, "junk left over after reaching leaf");
486     while (ee) {
487       e = ee->e_link;
488       free(ee);
489       ee = e;
490     }
491   }
492
493   popall();
494   return (bad);
495 }
496
497 /* --- @path_setids@ --- *
498  *
499  * Arguments:   @struct chkpath *cp@ = pointer to block to fill in
500  *
501  * Returns:     Zero if OK, else @-1@.
502  *
503  * Use:         Fills in the user ids and things in the structure.
504  */
505
506 void path_setids(struct chkpath *cp)
507 {
508   int n, i;
509   gid_t g = getgid();
510
511   cp->cp_uid = getuid();
512   n = getgroups(sizeof(cp->cp_gid) / sizeof(cp->cp_gid[0]), cp->cp_gid);
513   
514   for (i = 0; i < n; i++) {
515     if (cp->cp_gid[i] == g)
516       goto gid_ok;
517   }
518   cp->cp_gid[n++] = g;
519 gid_ok:
520   cp->cp_gids = n;
521 }
522
523 /*----- That's all, folks -------------------------------------------------*/