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