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