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