f75228353fc39110890a5e9b562cc618e2d3898b
[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             "Please report bugs to " PACKAGE_BUGREPORT "\n");
164
165   exit(res);
166 }
167
168 static void
169 showVersion()
170 {
171   WRITE_MSG(1,
172             "secure-mount " VERSION " -- secure mounting of directories\n"
173             "This program is part of " PACKAGE_STRING "\n\n"
174             "Copyright (C) 2003 Enrico Scholz\n"
175             VERSION_COPYRIGHT_DISCLAIMER);
176   exit(0);
177 }
178
179 inline static bool
180 isSameObject(struct stat const *lhs,
181              struct stat const *rhs)
182 {
183   return (lhs->st_dev==rhs->st_dev &&
184           lhs->st_ino==rhs->st_ino);
185 }
186
187 static int
188 fchroot(int fd)
189 {
190   if (fchdir(fd)==-1 || chroot(".")==-1) return -1;
191   return 0;
192 }
193
194 static int
195 writeX(int fd, void const *buf, size_t len)
196 {
197   if ((size_t)(write(fd, buf, len))!=len) return -1;
198   return 0;
199 }
200
201 static int
202 writeStrX(int fd, char const *str)
203 {
204   return writeX(fd, str, strlen(str));
205 }
206
207 static inline char const *
208 getType(struct MountInfo const *mnt)
209 {
210   if (mnt->type==0)                         return "none";
211   else if (strncmp(mnt->type, "ext", 3)==0) return "ufs";
212   else                                      return mnt->type;
213 }
214
215 inline static void
216 restoreRoot(struct Options const *opt)
217 {
218   if (opt->do_chroot!=0 && fchroot(opt->cur_rootdir_fd)==-1) {
219     perror("secure-mount: fchdir(\"/\")");
220     WRITE_MSG(2, "Failed to restore root-directory; aborting\n");
221     exit(1);
222   }
223 }
224
225 static int
226 updateMtab(struct MountInfo const *mnt, struct Options const *opt)
227 {
228   int           res = -1;
229   int           fd;
230   assert(opt->mtab!=0);
231
232   if (opt->do_chroot && fchroot(opt->cur_dir_fd)==-1) {
233       perror("secure-mount: fchroot(\".\")");
234       return -1;
235   }
236
237   fd=open(opt->mtab, O_CREAT|O_APPEND|O_WRONLY, 0644);
238   
239   if (fd==-1) {
240     perror("secure-mount: open(<mtab>)");
241     goto err0;
242   }
243
244   if (flock(fd, LOCK_EX)==-1) {
245     perror("secure-mount: flock()");
246     goto err1;
247   }
248
249   if (writeStrX(fd, mnt->src)==-1 ||
250       writeStrX(fd, " ")==-1 ||
251       writeStrX(fd, mnt->dst)==-1 ||
252       writeStrX(fd, " ")==-1 ||
253       writeStrX(fd, getType(mnt))==-1 ||
254       writeStrX(fd, " ")==-1 ||
255       writeStrX(fd, mnt->data ? mnt->data : "defaults")==-1 ||
256       writeStrX(fd, " 0 0\n")==-1) {
257     perror("secure-mount: write()");
258     goto err1;
259   }
260
261   res = 0;
262
263   err1: close(fd);
264   err0:
265   restoreRoot(opt);
266   return res;
267 }
268
269 static bool
270 callExternalMount(struct MountInfo const *mnt)
271 {
272   char const *  argv[10];
273   size_t        idx = 0;
274   pid_t         pid;
275   int           status;
276   char const *  mount_prog = getenv("MOUNT");
277
278   if (mount_prog==0) mount_prog = MOUNT_PROG;
279
280   argv[idx++] = mount_prog;
281   argv[idx++] = "-n";
282   if      (mnt->flag & MS_BIND) argv[idx++] = "--bind";
283   else if (mnt->flag & MS_MOVE) argv[idx++] = "--move";
284
285   if (mnt->data &&
286       strcmp(mnt->data, "defaults")!=0) {
287     argv[idx++] = "-o";
288     argv[idx++] = mnt->data;
289   }
290
291   if (mnt->type) {
292     argv[idx++] = "-t";
293     argv[idx++] = mnt->type;
294   }
295
296   argv[idx++] = mnt->src;
297   argv[idx++] = ".";
298   argv[idx]   = 0;
299
300   pid = fork();
301   if (pid==-1) {
302     perror("secure-mount: fork()");
303     return false;
304   }
305
306   if (pid==0) {
307     execv(mount_prog, const_cast(char **)(argv));
308     PERROR_Q("secure-mount: execv", mount_prog);
309     exit(1);
310   }
311
312   if (wait4(pid, &status, 0, 0)==-1) {
313     perror("secure-mount: wait4()");
314     return false;
315   }
316
317   return (WIFEXITED(status)) && (WEXITSTATUS(status)==0);
318 }
319
320 inline static bool
321 secureChdir(char const *dir, struct Options const *opt)
322 {
323   int           dir_fd;
324   bool          res = false;
325   
326   if (opt->do_chroot!=0 && fchroot(opt->cur_dir_fd)==-1) {
327     perror("secure-mount: fchroot(\".\")");
328     return false;
329   }
330
331   if (chdir(dir)==-1) {
332     PERROR_Q("secure-mount: chdir", dir);
333     goto err;
334   }
335
336   dir_fd = open(".", O_RDONLY|O_DIRECTORY);
337   if (dir_fd==-1) {
338     perror("secure-mount: open(\".\")");
339     goto err;
340   }
341
342   restoreRoot(opt);
343   if (fchdir(dir_fd)==-1)
344     PERROR_Q("secure-mount: fchdir", dir);
345   else
346     res = true;
347   
348   close(dir_fd);
349   return res;
350
351   err:
352   restoreRoot(opt);
353   return false;
354 }
355
356 static bool
357 mountSingle(struct MountInfo const *mnt, struct Options const *opt)
358 {
359   assert(mnt->dst!=0);
360   
361   if (!secureChdir(mnt->dst, opt))
362     return false;
363
364   if (mnt->flag & (MS_BIND|MS_MOVE)) {
365     if (mount(mnt->src, ".",
366               mnt->type ? mnt->type : "",
367               mnt->flag,  mnt->data)==-1) {
368       perror("secure-mount: mount()");
369       return false;
370     }
371   }
372   else if (!callExternalMount(mnt))
373     return false;
374
375   if (!opt->ignore_mtab &&
376       updateMtab(mnt, opt)==-1) {
377     WRITE_MSG(2, "Failed to update mtab-file\n");
378       // no error
379   }
380   
381   return true;
382 }
383
384 static struct FstabOption const *
385 searchOption(char const *opt, size_t len)
386 {
387   struct FstabOption const *            i;
388   for (i=FSTAB_OPTIONS+0; i<FSTAB_OPTIONS+DIM_OF(FSTAB_OPTIONS); ++i)
389     if (strncmp(i->opt, opt, len)==0) return i;
390
391   return 0;
392 }
393
394 static bool
395 transformOptionList(struct MountInfo *info)
396 {
397   char const *                  ptr = info->data;
398
399   do {
400     char const *                pos = strchr(ptr, ',');
401     struct FstabOption const *  opt;
402     
403     if (pos==0) pos = ptr+strlen(ptr);
404     opt = searchOption(ptr, pos-ptr);
405
406     if (opt!=0) {
407       info->flag  &= ~opt->mask;
408       info->flag  |=  opt->flag;
409       info->xflag |=  opt->xflag;
410     }
411
412     if (*pos!='\0')
413       ptr = pos+1;
414     else
415       ptr = pos;
416
417   } while (*ptr!='\0');
418
419   return true;
420 }
421
422 #define MOVE_TO_NEXT_FIELD(PTR,ALLOW_EOL)               \
423   while (!isspace(*PTR) && *PTR!='\0') ++PTR;           \
424   if (!(ALLOW_EOL) && *PTR=='\0') return prFAIL;        \
425   *PTR++ = '\0';                                        \
426   while (isspace(*PTR)) ++PTR
427
428 static enum {prDOIT, prFAIL, prIGNORE}
429 parseFstabLine(struct MountInfo *info, char *buf)
430 {
431   while (isspace(*buf)) ++buf;
432   if (*buf=='#' || *buf=='\0')  return prIGNORE;
433
434   info->src  = buf;
435   MOVE_TO_NEXT_FIELD(buf, false);
436   info->dst  = buf;
437   MOVE_TO_NEXT_FIELD(buf, false);
438   info->type = buf;
439   MOVE_TO_NEXT_FIELD(buf, false);
440   info->data = buf;
441   MOVE_TO_NEXT_FIELD(buf, true);
442
443   if (strcmp(info->type, "swap")==0) return prIGNORE;
444   if (strcmp(info->type, "none")==0) info->type = 0;
445
446   info->flag   = 0;
447   info->xflag  = 0;
448   if (!transformOptionList(info)) return prFAIL;
449   if (info->xflag & XFLAG_NOAUTO) return prIGNORE;
450
451   return prDOIT;
452 }
453
454 #undef MOVE_TO_NEXT_FIELD
455
456 static bool
457 mountFstab(struct Options const *opt)
458 {
459   bool          res = false;
460   int           fd;
461   off_t         len;
462
463   assert(opt->fstab!=0);
464   fd = open(opt->fstab, O_RDONLY);
465   if (fd==-1) {
466     perror("secure-mount: open(<fstab>)");
467     goto err0;
468   }
469
470   len = lseek(fd, 0, SEEK_END);
471   if (len==-1 ||
472       lseek(fd, 0, SEEK_SET)==-1) {
473     perror("secure-mount: lseek(<fstab>)");
474     goto err1;
475   }
476
477   {
478     char        buf[len+2];
479     char        *ptr, *ptrptr;
480
481     if (read(fd, buf, len+1)!=len) {
482       perror("secure-mount: read()");
483       goto err1;
484     }
485     buf[len]   = '#';   // workaround for broken dietlibc strtok_r()
486                         // implementation
487     buf[len+1] = '\0';
488
489     ptr = strtok_r(buf, "\n", &ptrptr);
490     while (ptr) {
491       struct MountInfo  mnt;
492       char *            new_ptr = strtok_r(0, "\n", &ptrptr);
493
494       switch (parseFstabLine(&mnt, ptr)) {
495         case prFAIL     :
496           WRITE_MSG(2, "Failed to parse fstab-line beginning with '");
497           WRITE_STR(2, ptr);
498           WRITE_MSG(2, "'\n");
499           goto err1;
500
501         case prIGNORE   :  break;
502         case prDOIT     :
503           chdir("/");
504           if (!mountSingle(&mnt, opt)) {
505             WRITE_MSG(2, "Failed to mount fstab-line beginning with '");
506             WRITE_STR(2, ptr);
507             WRITE_MSG(2, "'\n");
508           }
509           break;
510         default         :
511           assert(false);
512       }
513
514       ptr = new_ptr;
515     }
516   }
517
518   res = true;
519
520   err1: close(fd);
521   err0: return res;
522 }
523
524 static void
525 initFDs(struct Options *opt)
526 {
527   opt->cur_dir_fd     = Eopen(".", O_RDONLY|O_DIRECTORY, 0);
528   opt->cur_rootdir_fd = Eopen("/", O_RDONLY|O_DIRECTORY, 0);
529
530   Efcntl(opt->cur_dir_fd,     F_SETFD, FD_CLOEXEC);
531   Efcntl(opt->cur_rootdir_fd, F_SETFD, FD_CLOEXEC);
532 }
533
534 int main(int argc, char *argv[])
535 {
536   struct MountInfo      mnt = {
537     .src         = 0,
538     .dst         = 0,
539     .type        = 0,
540     .flag        = 0,
541     .xflag       = 0,
542     .data        = 0,
543   };
544
545   struct Options        opt = {
546     .mtab           = "/etc/mtab",
547     .fstab          = "/etc/fstab",
548     .do_chroot      = 0,
549     .ignore_mtab    = false,
550     .mount_all      = false,
551     .cur_dir_fd     = -1,
552     .cur_rootdir_fd = -1
553   };
554
555   while (1) {
556     int         c = getopt_long(argc, argv, "ht:nao:", CMDLINE_OPTIONS, 0);
557     if (c==-1) break;
558     
559     switch (c) {
560       case 'h'          :  showHelp(1, argv[0], 0);
561       case 'v'          :  showVersion();
562       case 't'          :  mnt.type = optarg;         break;
563       case 'n'          :  opt.ignore_mtab = true;    break;
564       case 'a'          :  opt.mount_all   = true;    break;
565       case 'o'          :  mnt.data        = optarg;  break;
566       case OPTION_RBIND :  mnt.flag       |= MS_REC;  /*@fallthrough@*/
567       case OPTION_BIND  :  mnt.flag       |= MS_BIND; break;
568       case OPTION_MOVE  :  mnt.flag       |= MS_MOVE; break;
569       case OPTION_MTAB  :  opt.mtab        = optarg;  break;
570       case OPTION_FSTAB :  opt.fstab       = optarg;  break;
571       case OPTION_CHROOT:  opt.do_chroot   = true;    break;
572       case OPTION_SECURE:
573         WRITE_MSG(2, "secure-mount: The '--secure' option is deprecated...\n");
574         break;
575       default           :
576         WRITE_MSG(2, "Try '");
577         WRITE_STR(2, argv[0]);
578         WRITE_MSG(2, " --help\" for more information.\n");
579         return EXIT_FAILURE;
580         break;
581     }
582   }
583
584
585   if (opt.mount_all && optind<argc) {
586     WRITE_MSG(2, "Can not specify <src> and '-a' at the same time\n");
587     return EXIT_FAILURE;
588   }
589
590   initFDs(&opt);
591   signal(SIGCHLD, SIG_DFL);
592   
593   if (opt.mount_all) {
594     if (!mountFstab(&opt)) return EXIT_FAILURE;
595     else                   return EXIT_SUCCESS;
596   }
597
598   if (optind+2!=argc) {
599     WRITE_MSG(2, "Invalid <src> <dst> pair specified\n");
600     return EXIT_FAILURE;
601   }
602
603   if (mnt.data) {
604     mnt.data = strdup(mnt.data);
605     if (!transformOptionList(&mnt)) {
606       WRITE_MSG(2, "Invalid options specified\n");
607       return EXIT_FAILURE;
608     }
609   }
610     
611   mnt.src  = argv[optind++];
612   mnt.dst  = argv[optind++];
613
614   if (!mountSingle(&mnt, &opt)) return EXIT_FAILURE;
615     
616   return EXIT_SUCCESS;
617 }