a7abd19fa4c3c83a80a6fd43830526d1d273b4dd
[util-vserver.git] / util-vserver / src / secure-mount.c
1 // $Id$    --*- c++ -*--
2
3 // Copyright (C) 2003 Enrico Scholz <enrico.scholz@informatik.tu-chemnitz.de>
4 //  
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; version 2 of the License.
8 //  
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //  
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17
18
19   // secure-mount <general mount(8) options> [--secure] [--chroot <dir>]
20   //              [--mtab <mtabfile>] [--fstab <fstabfile>]
21   //
22   // Executes mount-operations in the given chroot-dir: it assumes sources in
23   // the current root-dir while destinations are expected in the chroot
24   // environment.  When '--secure' is given, the destination must not contain
25   // symlinks.
26
27
28 #ifdef HAVE_CONFIG_H
29 #  include <config.h>
30 #endif
31
32 #include "util.h"
33 #include "pathconfig.h"
34
35 #include <getopt.h>
36 #include <fcntl.h>
37 #include <errno.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42 #include <stdbool.h>
43 #include <sys/mount.h>
44 #include <sys/stat.h>
45 #include <sys/types.h>
46 #include <sys/file.h>
47 #include <linux/fs.h>
48 #include <assert.h>
49 #include <ctype.h>
50 #include <sys/wait.h>
51 #include <libgen.h>
52
53 #define MNTPOINT        "/etc"
54
55 struct MountInfo {
56     char const *        src;
57     char const *        dst;
58     char const *        type;
59     unsigned long       flag;
60     unsigned long       xflag;
61     char *              data;
62 };
63
64 struct Options {
65     char const *        mtab;
66     char const *        fstab;
67     char const *        rootdir;
68     bool                ignore_mtab;
69     bool                mount_all;
70     bool                is_secure;
71
72     int                 cur_rootdir_fd;
73 };
74
75 #define OPTION_BIND     1024
76 #define OPTION_MOVE     1025
77 #define OPTION_MTAB     1026
78 #define OPTION_FSTAB    1027
79 #define OPTION_CHROOT   1028
80 #define OPTION_SECURE   1029
81 #define OPTION_RBIND    1030
82
83 #define XFLAG_NOAUTO    0x01
84
85 static struct option const
86 CMDLINE_OPTIONS[] = {
87   { "help",    no_argument,       0, 'h' },
88   { "version", no_argument,       0, 'v' },
89   { "bind",    no_argument,       0, OPTION_BIND },
90   { "move",    no_argument,       0, OPTION_MOVE },
91   { "mtab",    required_argument, 0, OPTION_MTAB },
92   { "fstab",   required_argument, 0, OPTION_FSTAB },
93   { "chroot",  required_argument, 0, OPTION_CHROOT },
94   { "secure",  no_argument,       0, OPTION_SECURE },
95   { "rbind",   no_argument,       0, OPTION_RBIND },
96   { 0, 0, 0, 0 }
97 };
98
99 #ifndef MS_REC
100 #  define MS_REC        0x4000
101 #endif
102
103 static struct FstabOption {
104     char const * const  opt;
105     unsigned long const         flag;
106     unsigned long const         mask;
107     unsigned long const         xflag;
108     bool const                  is_dflt;
109 } const FSTAB_OPTIONS[] = {
110   { "defaults",   0,             (MS_RDONLY|MS_NOSUID|MS_NODEV|MS_NOEXEC|
111                                   MS_SYNCHRONOUS), 0, false },
112   { "rbind",      MS_BIND|MS_REC, MS_BIND|MS_REC,  0, false },
113   { "bind",       MS_BIND,        MS_BIND,         0, false },
114   { "move",       MS_MOVE,        MS_MOVE,         0, false },
115   { "async",      0,              MS_SYNCHRONOUS,  0, false },
116   { "sync",       MS_SYNCHRONOUS, MS_SYNCHRONOUS,  0, false },
117   { "atime",      0,              MS_NOATIME,      0, false },
118   { "noatime",    MS_NOATIME,     MS_NOATIME,      0, false },
119   { "dev",        0,              MS_NODEV,        0, false },
120   { "nodev",      MS_NODEV,       MS_NODEV,        0, false },
121   { "exec",       0,              MS_NOEXEC,       0, false },
122   { "noexec",     MS_NOEXEC,      MS_NOEXEC,       0, false },
123   { "suid",       0,              MS_NOSUID,       0, false },
124   { "nosuid",     MS_NOSUID,      MS_NOSUID,       0, false },
125   { "ro",         MS_RDONLY,      MS_RDONLY,       0, false },
126   { "rw",         0,              MS_RDONLY,       0, false },
127   
128   { "remount",    MS_REMOUNT,     MS_REMOUNT,      0, false },
129   { "users",      MS_NOEXEC|MS_NOSUID|MS_NODEV,
130                   MS_NOEXEC|MS_NOSUID|MS_NODEV,    0, false },
131   { "mandlock",   MS_MANDLOCK,    MS_MANDLOCK,     0, false },
132   { "nodiratime", MS_NODIRATIME,  MS_NODIRATIME,   0, false },
133 #ifdef MS_DIRSYNC  
134   { "dirsync",    MS_DIRSYNC,     MS_DIRSYNC,      0, false },
135 #endif
136   { "_netdev",    0,              0,               0, false },
137   { "auto",       0,              0,               0, false },
138   { "noauto",     0,              0,               XFLAG_NOAUTO, false },
139   { "user",       0,              0,               0, false },
140   { "nouser",     0,              0,               0, false },
141 };
142
143 static void
144 showHelp(int fd, char const *cmd, int res)
145 {
146   VSERVER_DECLARE_CMD(cmd);
147   
148   WRITE_MSG(fd, "Usage:  ");
149   WRITE_STR(fd, cmd);
150   WRITE_MSG(fd,
151             " [--help] [--version] [--bind] [--move] [--rbind] [-t <type>] [-n]\n"
152             "            [--mtab <filename>] [--fstab <filename>] [--chroot <dirname>] \n"
153             "            [--secure] -a|([-o <options>] [--] <src> <dst>)\n\n"
154             "Executes mount-operations in the given chroot-dir: it assumes sources in the\n"
155             "current root-dir while destinations are expected in the chroot environment.\n"
156             "When '--secure' is given, the destination must not contain symlinks.\n\n"
157             "For non-trivial mount-operations it uses the external 'mount' program which\n"
158             "can be overridden by the $MOUNT environment variable.\n\n"
159             "Please report bugs to " PACKAGE_BUGREPORT "\n");
160
161   exit(res);
162 }
163
164 static void
165 showVersion()
166 {
167   WRITE_MSG(1,
168             "secure-mount " VERSION " -- secure mounting of directories\n"
169             "This program is part of " PACKAGE_STRING "\n\n"
170             "Copyright (C) 2003 Enrico Scholz\n"
171             VERSION_COPYRIGHT_DISCLAIMER);
172   exit(0);
173 }
174
175 inline static bool
176 isSameObject(struct stat const *lhs,
177              struct stat const *rhs)
178 {
179   return (lhs->st_dev==rhs->st_dev &&
180           lhs->st_ino==rhs->st_ino);
181 }
182
183 static int
184 chdirSecure(char const *dir)
185 {
186   char          tmp[strlen(dir)+1], *ptr;
187   char const    *cur;
188
189   strcpy(tmp, dir);
190   cur = strtok_r(tmp, "/", &ptr);
191   while (cur) {
192     struct stat         pre_stat, post_stat;
193
194     if (lstat(cur, &pre_stat)==-1) return -1;
195     
196     if (!S_ISDIR(pre_stat.st_mode)) {
197       errno = ENOENT;
198       return -1;
199     }
200     if (S_ISLNK(pre_stat.st_mode)) {
201       errno = EINVAL;
202       return -1;
203     }
204
205     if (chdir(cur)==-1)            return -1;
206     if (stat(".", &post_stat)==-1) return -1;
207
208     if (!isSameObject(&pre_stat, &post_stat)) {
209       char      dir[PATH_MAX];
210       
211       WRITE_MSG(2, "Possible symlink race ATTACK at '");
212       WRITE_STR(2, getcwd(dir, sizeof(dir)));
213       WRITE_MSG(2, "'\n");
214
215       errno = EINVAL;
216       return -1;
217     }
218
219     cur = strtok_r(0, "/", &ptr);
220   }
221
222   return 0;
223 }
224
225 static int
226 verifyPosition(char const *mntpoint, char const *dir1, char const *dir2)
227 {
228   struct stat           pre_stat, post_stat;
229
230   if (stat(mntpoint, &pre_stat)==-1)       return -1;
231   if (chroot(dir1)==-1 || chdir(dir2)==-1) return -1;
232   if (stat(".", &post_stat)==-1)           return -1;
233
234   if (!isSameObject(&pre_stat, &post_stat)) {
235     char        dir[PATH_MAX];
236       
237     WRITE_MSG(2, "Possible symlink race ATTACK at '");
238     WRITE_STR(2, getcwd(dir, sizeof(dir)));
239     WRITE_MSG(2, "' within '");
240     WRITE_STR(2, dir1);
241     WRITE_STR(2, "'\n");
242
243     errno = EINVAL;
244     return -1;
245   }
246
247   return 0;
248 }
249
250 static int
251 fchroot(int fd)
252 {
253   if (fchdir(fd)==-1 || chroot(".")==-1) return -1;
254   return 0;
255 }
256
257 static int
258 writeX(int fd, void const *buf, size_t len)
259 {
260   if ((size_t)(write(fd, buf, len))!=len) return -1;
261   return 0;
262 }
263
264 static int
265 writeStrX(int fd, char const *str)
266 {
267   return writeX(fd, str, strlen(str));
268 }
269
270 static int
271 updateMtab(struct MountInfo const *mnt, struct Options const *opt)
272 {
273   int           res = -1;
274   int           fd;
275   assert(opt->mtab!=0);
276
277   if (opt->rootdir!=0 &&
278       chroot(opt->rootdir)==-1) {
279       perror("secure-mount: chroot()");
280       return -1;
281   }
282
283   fd=open(opt->mtab, O_CREAT|O_APPEND|O_WRONLY, 0644);
284   
285   if (fd==-1) perror("secure-mount: open(<mtab>)");
286   
287   if (fchroot(opt->cur_rootdir_fd)==-1) {
288     perror("secure-mount: fchroot()");
289     goto err1;
290   }
291
292   if (fd==-1) goto err0;
293
294   if (flock(fd, LOCK_EX)==-1) {
295     perror("secure-mount: flock()");
296     goto err1;
297   }
298
299
300   if (writeStrX(fd, mnt->src)==-1 ||
301       writeStrX(fd, " ")==-1 ||
302       writeStrX(fd, mnt->dst)==-1 ||
303       writeStrX(fd, " ")==-1 ||
304       writeStrX(fd, mnt->type ? mnt->type : "none")==-1 ||
305       writeStrX(fd, " ")==-1 ||
306       writeStrX(fd, mnt->data ? mnt->data : "defaults")==-1 ||
307       writeStrX(fd, " 0 0\n")==-1) {
308     perror("secure-mount: write()");
309     goto err1;
310   }
311
312   res = 0;
313
314   err1: close(fd);
315   err0: return res;
316 }
317
318 static bool
319 callExternalMount(struct MountInfo const *mnt)
320 {
321   char const *  argv[10];
322   size_t        idx = 0;
323   pid_t         pid;
324   int           status;
325   char const *  mount_prog = getenv("MOUNT");
326
327   if (mount_prog==0) mount_prog = MOUNT_PROG;
328
329   argv[idx++] = mount_prog;
330   argv[idx++] = "-n";
331   if      (mnt->flag & MS_BIND) argv[idx++] = "--bind";
332   else if (mnt->flag & MS_MOVE) argv[idx++] = "--move";
333
334   if (mnt->data &&
335       strcmp(mnt->data, "defaults")!=0) {
336     argv[idx++] = "-o";
337     argv[idx++] = mnt->data;
338   }
339
340   if (mnt->type) {
341     argv[idx++] = "-t";
342     argv[idx++] = mnt->type;
343   }
344
345   argv[idx++] = mnt->src;
346   argv[idx++] = ".";
347   argv[idx]   = 0;
348
349   pid = fork();
350   if (pid==-1) {
351     perror("secure-mount: fork()");
352     return false;
353   }
354
355   if (pid==0) {
356     execv(mount_prog, const_cast(char **)(argv));
357     PERROR_Q("secure-mount: execv", mount_prog);
358     exit(1);
359   }
360
361   if (wait4(pid, &status, 0, 0)==-1) {
362     perror("secure-mount: wait4()");
363     return false;
364   }
365
366   return (WIFEXITED(status)) && (WEXITSTATUS(status)==0);
367 }
368
369 static bool
370 mountSingle(struct MountInfo const *mnt, struct Options const *opt)
371 {
372   char const    *dir = mnt->dst;
373
374   assert(mnt->dst!=0);
375   
376   if (opt->rootdir!=0) {
377     if (chdir(opt->rootdir)==-1) {
378       PERROR_Q("secure-mount: chdir", opt->rootdir);
379       return false;
380     }
381
382     while (*dir=='/') ++dir;
383   }
384
385   if (opt->is_secure) {
386     if (chdirSecure(dir)==-1) {
387       PERROR_Q("secure-mount: chdirSecure", dir);
388       return false;
389     }
390   }
391   else {
392     if (*dir!='\0' &&
393         chdir(dir)==-1) {
394       PERROR_Q("secure-mount: chdir", dir);
395       return false;
396     }
397   }
398
399   if (mnt->flag & (MS_BIND|MS_MOVE)) {
400     if (mount(mnt->src, ".",
401               mnt->type ? mnt->type : "",
402               mnt->flag,  mnt->data)==-1) {
403       perror("secure-mount: mount()");
404       return false;
405     }
406   }
407   else {
408     if (!callExternalMount(mnt)) return false;
409   }
410
411     // Check if directories were moved between the chdirSecure() and mount(2)
412   if ((mnt->flag&MS_BIND) && opt->rootdir!=0 &&
413       (verifyPosition(mnt->src, opt->rootdir, mnt->dst)==-1 ||
414        fchroot(opt->cur_rootdir_fd)==-1)) {
415     perror("secure-mount: verifyPosition/fchroot");
416       // TODO: what is with unmounting?
417     return false;
418   }
419
420   if (!opt->ignore_mtab &&
421       updateMtab(mnt, opt)==-1) {
422     WRITE_MSG(2, "Failed to update mtab-file\n");
423       // no error
424   }
425   
426   return true;
427 }
428
429 static struct FstabOption const *
430 searchOption(char const *opt, size_t len)
431 {
432   struct FstabOption const *            i;
433   for (i=FSTAB_OPTIONS+0; i<FSTAB_OPTIONS+DIM_OF(FSTAB_OPTIONS); ++i)
434     if (strncmp(i->opt, opt, len)==0) return i;
435
436   return 0;
437 }
438
439 static bool
440 transformOptionList(struct MountInfo *info)
441 {
442   char const *                  ptr = info->data;
443
444   do {
445     char const *                pos = strchr(ptr, ',');
446     struct FstabOption const *  opt;
447     
448     if (pos==0) pos = ptr+strlen(ptr);
449     opt = searchOption(ptr, pos-ptr);
450
451     if (opt!=0) {
452       info->flag  &= ~opt->mask;
453       info->flag  |=  opt->flag;
454       info->xflag |=  opt->xflag;
455     }
456
457     if (*pos!='\0')
458       ptr = pos+1;
459     else
460       ptr = pos;
461
462   } while (*ptr!='\0');
463
464   return true;
465 }
466
467 #define MOVE_TO_NEXT_FIELD(PTR,ALLOW_EOL)               \
468   while (!isspace(*PTR) && *PTR!='\0') ++PTR;           \
469   if (!(ALLOW_EOL) && *PTR=='\0') return prFAIL;        \
470   *PTR++ = '\0';                                        \
471   while (isspace(*PTR)) ++PTR
472
473 static enum {prDOIT, prFAIL, prIGNORE}
474 parseFstabLine(struct MountInfo *info, char *buf)
475 {
476   while (isspace(*buf)) ++buf;
477   if (*buf=='#' || *buf=='\0')  return prIGNORE;
478
479   info->src  = buf;
480   MOVE_TO_NEXT_FIELD(buf, false);
481   info->dst  = buf;
482   MOVE_TO_NEXT_FIELD(buf, false);
483   info->type = buf;
484   MOVE_TO_NEXT_FIELD(buf, false);
485   info->data = buf;
486   MOVE_TO_NEXT_FIELD(buf, true);
487
488   if (strcmp(info->type, "swap")==0) return prIGNORE;
489   if (strcmp(info->type, "none")==0) info->type = 0;
490
491   info->flag   = 0;
492   info->xflag  = 0;
493   if (!transformOptionList(info)) return prFAIL;
494   if (info->xflag & XFLAG_NOAUTO) return prIGNORE;
495
496   return prDOIT;
497 }
498
499 #undef MOVE_TO_NEXT_FIELD
500
501 static bool
502 mountFstab(struct Options const *opt)
503 {
504   bool          res = false;
505   int           fd;
506   off_t         len;
507
508   assert(opt->fstab!=0);
509   fd = open(opt->fstab, O_RDONLY);
510   if (fd==-1) {
511     perror("secure-mount: open(<fstab>)");
512     goto err0;
513   }
514
515   len = lseek(fd, 0, SEEK_END);
516   if (len==-1 ||
517       lseek(fd, 0, SEEK_SET)==-1) {
518     perror("secure-mount: lseek(<fstab>)");
519     goto err1;
520   }
521
522   {
523     char        buf[len+2];
524     char        *ptr, *ptrptr;
525
526     if (read(fd, buf, len+1)!=len) {
527       perror("secure-mount: read()");
528       goto err1;
529     }
530     buf[len]   = '#';   // workaround for broken dietlibc strtok_r()
531                         // implementation
532     buf[len+1] = '\0';
533
534     ptr = strtok_r(buf, "\n", &ptrptr);
535     while (ptr) {
536       struct MountInfo  mnt;
537       char *            new_ptr = strtok_r(0, "\n", &ptrptr);
538
539       switch (parseFstabLine(&mnt, ptr)) {
540         case prFAIL     :
541           WRITE_MSG(2, "Failed to parse fstab-line beginning with '");
542           WRITE_STR(2, ptr);
543           WRITE_MSG(2, "'\n");
544           goto err1;
545
546         case prIGNORE   :  break;
547         case prDOIT     :
548           chdir("/");
549           if (!mountSingle(&mnt, opt)) {
550             WRITE_MSG(2, "Failed to mount fstab-line beginning with '");
551             WRITE_STR(2, ptr);
552             WRITE_MSG(2, "'\n");
553           }
554           break;
555         default         :
556           assert(false);
557       }
558
559       ptr = new_ptr;
560     }
561   }
562
563   res = true;
564
565   err1: close(fd);
566   err0: return res;
567 }
568
569 int main(int argc, char *argv[])
570 {
571   struct MountInfo      mnt = {
572     .src         = 0,
573     .dst         = 0,
574     .type        = 0,
575     .flag        = 0,
576     .xflag       = 0,
577     .data        = 0,
578   };
579
580   struct Options        opt = {
581     .mtab           = "/etc/mtab",
582     .fstab          = "/etc/fstab",
583     .rootdir        = 0,
584     .ignore_mtab    = false,
585     .mount_all      = false,
586     .is_secure      = false,
587     .cur_rootdir_fd = -1
588   };
589
590   opt.cur_rootdir_fd = open("/", O_RDONLY|O_DIRECTORY);
591
592   if (opt.cur_rootdir_fd==-1) {
593     perror("secure-mount: open(\"/\")");
594     return EXIT_FAILURE;
595   }
596
597   while (1) {
598     int         c = getopt_long(argc, argv, "ht:nao:", CMDLINE_OPTIONS, 0);
599     if (c==-1) break;
600     
601     switch (c) {
602       case 'h'          :  showHelp(1, argv[0], 0);
603       case 'v'          :  showVersion();
604       case 't'          :  mnt.type = optarg;         break;
605       case 'n'          :  opt.ignore_mtab = true;    break;
606       case 'a'          :  opt.mount_all   = true;    break;
607       case 'o'          :  mnt.data        = optarg;  break;
608       case OPTION_RBIND :  mnt.flag       |= MS_REC;  /*@fallthrough@*/
609       case OPTION_BIND  :  mnt.flag       |= MS_BIND; break;
610       case OPTION_MOVE  :  mnt.flag       |= MS_MOVE; break;
611       case OPTION_MTAB  :  opt.mtab        = optarg;  break;
612       case OPTION_FSTAB :  opt.fstab       = optarg;  break;
613       case OPTION_CHROOT:  opt.rootdir     = optarg;  break;
614       case OPTION_SECURE:  opt.is_secure   = true;    break;
615       default           :
616         WRITE_MSG(2, "Try '");
617         WRITE_STR(2, argv[0]);
618         WRITE_MSG(2, " --help\" for more information.\n");
619         return EXIT_FAILURE;
620         break;
621     }
622   }
623
624   if (opt.mount_all && optind<argc) {
625     WRITE_MSG(2, "Can not specify <src> and '-a' at the same time\n");
626     return EXIT_FAILURE;
627   }
628
629   if (opt.mount_all) {
630     if (!mountFstab(&opt)) return EXIT_FAILURE;
631     else                   return EXIT_SUCCESS;
632   }
633
634   if (optind+2!=argc) {
635     WRITE_MSG(2, "Invalid <src> <dst> pair specified\n");
636     return EXIT_FAILURE;
637   }
638
639   if (mnt.data) {
640     mnt.data = strdup(mnt.data);
641     if (!transformOptionList(&mnt)) {
642       WRITE_MSG(2, "Invalid options specified\n");
643       return EXIT_FAILURE;
644     }
645   }
646     
647   mnt.src  = argv[optind++];
648   mnt.dst  = argv[optind++];
649
650   if (!mountSingle(&mnt, &opt)) return EXIT_FAILURE;
651     
652   return EXIT_SUCCESS;
653 }