implemented '--rbind'
[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       flags;
60     char *              data;
61     bool                noauto;
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 static struct option const
84 CMDLINE_OPTIONS[] = {
85   { "help",    no_argument,       0, 'h' },
86   { "version", no_argument,       0, 'v' },
87   { "bind",    no_argument,       0, OPTION_BIND },
88   { "move",    no_argument,       0, OPTION_MOVE },
89   { "mtab",    required_argument, 0, OPTION_MTAB },
90   { "fstab",   required_argument, 0, OPTION_FSTAB },
91   { "chroot",  required_argument, 0, OPTION_CHROOT },
92   { "secure",  no_argument,       0, OPTION_SECURE },
93   { "rbind",   no_argument,       0, OPTION_RBIND },
94   { 0, 0, 0, 0 }
95 };
96
97 static struct FstabOptions {
98     char const * const  opt;
99     unsigned long const or_flag;
100     unsigned long const and_flag;
101     bool const          is_dflt;
102 } const FSTAB_OPTIONS[] = {
103   { "bind",       MS_BIND,        ~0, false },
104   { "move",       MS_MOVE,        ~0, false },
105 #if 0
106   { "noatime",    MS_NOATIME,     ~0, false },
107   { "mandlock",   MS_MANDLOCK,    ~0, false },
108   { "nodev",      MS_NODEV,       ~0, false },
109   { "nodiratime", MS_NODIRATIME,  ~0, false },
110   { "noexec",     MS_NOEXEC,      ~0, false },
111   { "nosuid",     MS_NOSUID,      ~0, false },
112   { "rdonly",     MS_RDONLY,      ~0, false },
113   { "remount",    MS_REMOUNT,     ~0, false },
114   { "sync",       MS_SYNCHRONOUS, ~0, false },
115 #ifdef MS_DIRSYNC  
116   { "dirsync",    MS_DIRSYNC,     ~0, false },
117 #endif
118 #endif
119   { "", 0, 0, false }
120 };
121
122 static void
123 showHelp(int fd, char const *cmd, int res)
124 {
125   VSERVER_DECLARE_CMD(cmd);
126   
127   WRITE_MSG(fd, "Usage:  ");
128   WRITE_STR(fd, cmd);
129   WRITE_MSG(fd,
130             " [--help] [--version] [--bind] [--move] [--rbind] [-t <type>] [-n]\n"
131             "            [--mtab <filename>] [--fstab <filename>] [--chroot <dirname>] \n"
132             "            [--secure] -a|([-o <options>] [--] <src> <dst>)\n\n"
133             "Executes mount-operations in the given chroot-dir: it assumes sources in the\n"
134             "current root-dir while destinations are expected in the chroot environment.\n"
135             "When '--secure' is given, the destination must not contain symlinks.\n\n"
136             "For non-trivial mount-operations it uses the external 'mount' program which\n"
137             "can be overridden by the $MOUNT environment variable.\n\n"
138             "Please report bugs to " PACKAGE_BUGREPORT "\n");
139
140   exit(res);
141 }
142
143 static void
144 showVersion()
145 {
146   WRITE_MSG(1,
147             "secure-mount " VERSION " -- secure mounting of directories\n"
148             "This program is part of " PACKAGE_STRING "\n\n"
149             "Copyright (C) 2003 Enrico Scholz\n"
150             VERSION_COPYRIGHT_DISCLAIMER);
151   exit(0);
152 }
153
154 inline static bool
155 isSameObject(struct stat const *lhs,
156              struct stat const *rhs)
157 {
158   return (lhs->st_dev==rhs->st_dev &&
159           lhs->st_ino==rhs->st_ino);
160 }
161
162 static int
163 chdirSecure(char const *dir)
164 {
165   char          tmp[strlen(dir)+1], *ptr;
166   char const    *cur;
167
168   strcpy(tmp, dir);
169   cur = strtok_r(tmp, "/", &ptr);
170   while (cur) {
171     struct stat         pre_stat, post_stat;
172
173     if (lstat(cur, &pre_stat)==-1) return -1;
174     
175     if (!S_ISDIR(pre_stat.st_mode)) {
176       errno = ENOENT;
177       return -1;
178     }
179     if (S_ISLNK(pre_stat.st_mode)) {
180       errno = EINVAL;
181       return -1;
182     }
183
184     if (chdir(cur)==-1)            return -1;
185     if (stat(".", &post_stat)==-1) return -1;
186
187     if (!isSameObject(&pre_stat, &post_stat)) {
188       char      dir[PATH_MAX];
189       
190       WRITE_MSG(2, "Possible symlink race ATTACK at '");
191       WRITE_STR(2, getcwd(dir, sizeof(dir)));
192       WRITE_MSG(2, "'\n");
193
194       errno = EINVAL;
195       return -1;
196     }
197
198     cur = strtok_r(0, "/", &ptr);
199   }
200
201   return 0;
202 }
203
204 static int
205 verifyPosition(char const *mntpoint, char const *dir1, char const *dir2)
206 {
207   struct stat           pre_stat, post_stat;
208
209   if (stat(mntpoint, &pre_stat)==-1)       return -1;
210   if (chroot(dir1)==-1 || chdir(dir2)==-1) return -1;
211   if (stat(".", &post_stat)==-1)           return -1;
212
213   if (!isSameObject(&pre_stat, &post_stat)) {
214     char        dir[PATH_MAX];
215       
216     WRITE_MSG(2, "Possible symlink race ATTACK at '");
217     WRITE_STR(2, getcwd(dir, sizeof(dir)));
218     WRITE_MSG(2, "' within '");
219     WRITE_STR(2, dir1);
220     WRITE_STR(2, "'\n");
221
222     errno = EINVAL;
223     return -1;
224   }
225
226   return 0;
227 }
228
229 static int
230 fchroot(int fd)
231 {
232   if (fchdir(fd)==-1 || chroot(".")==-1) return -1;
233   return 0;
234 }
235
236 static int
237 writeX(int fd, void const *buf, size_t len)
238 {
239   if ((size_t)(write(fd, buf, len))!=len) return -1;
240   return 0;
241 }
242
243 static int
244 writeStrX(int fd, char const *str)
245 {
246   return writeX(fd, str, strlen(str));
247 }
248
249 static int
250 updateMtab(struct MountInfo const *mnt, struct Options const *opt)
251 {
252   int           res = -1;
253   int           fd;
254   assert(opt->mtab!=0);
255
256   if (opt->rootdir!=0 &&
257       chroot(opt->rootdir)==-1) {
258       perror("chroot()");
259       return -1;
260   }
261
262   fd=open(opt->mtab, O_CREAT|O_APPEND|O_WRONLY, 0644);
263   
264   if (fd==-1) perror("open()");
265   
266   if (fchroot(opt->cur_rootdir_fd)==-1) {
267     perror("fchroot()");
268     goto err1;
269   }
270
271   if (fd==-1) goto err0;
272
273   if (flock(fd, LOCK_EX)==-1) {
274     perror("flock()");
275     goto err1;
276   }
277
278
279   if (writeStrX(fd, mnt->src)==-1 ||
280       writeStrX(fd, " ")==-1 ||
281       writeStrX(fd, mnt->dst)==-1 ||
282       writeStrX(fd, " ")==-1 ||
283       writeStrX(fd, mnt->type ? mnt->type : "none")==-1 ||
284       writeStrX(fd, " ")==-1 ||
285       writeStrX(fd, mnt->data ? mnt->data : "defaults")==-1 ||
286       writeStrX(fd, " 0 0\n")==-1) {
287     perror("write()");
288     goto err1;
289   }
290
291   res = 0;
292
293   err1: close(fd);
294   err0: return res;
295 }
296
297 static bool
298 callExternalMount(struct MountInfo const *mnt)
299 {
300   char const *  argv[10];
301   size_t        idx = 0;
302   pid_t         pid;
303   int           status;
304   char const *  mount_prog = getenv("MOUNT");
305
306   if (mount_prog==0) mount_prog = MOUNT_PROG;
307
308   argv[idx++] = mount_prog;
309   argv[idx++] = "-n";
310   if      (mnt->flags & MS_BIND) argv[idx++] = "--bind";
311   else if (mnt->flags & MS_MOVE) argv[idx++] = "--move";
312
313   if (mnt->data &&
314       strcmp(mnt->data, "defaults")!=0) {
315     argv[idx++] = "-o";
316     argv[idx++] = mnt->data;
317   }
318
319   if (mnt->type) {
320     argv[idx++] = "-t";
321     argv[idx++] = mnt->type;
322   }
323
324   argv[idx++] = mnt->src;
325   argv[idx++] = ".";
326   argv[idx]   = 0;
327
328   pid = fork();
329   if (pid==-1) {
330     perror("fork()");
331     return false;
332   }
333
334   if (pid==0) {
335     execv(mount_prog, const_cast(char **)(argv));
336     perror("execv()");
337     exit(1);
338   }
339
340   if (wait4(pid, &status, 0, 0)==-1) {
341     perror("wait4()");
342     return false;
343   }
344
345   return (WIFEXITED(status)) && (WEXITSTATUS(status)==0);
346 }
347
348 static bool
349 mountSingle(struct MountInfo const *mnt, struct Options const *opt)
350 {
351   char const    *dir = mnt->dst;
352
353   assert(mnt->dst!=0);
354   
355   if (opt->rootdir!=0) {
356     if (chdir(opt->rootdir)==-1) {
357       perror("chdir()");
358       return false;
359     }
360
361     while (*dir=='/') ++dir;
362   }
363
364   if (opt->is_secure) {
365     if (chdirSecure(dir)==-1) {
366       perror("chdirSecure()");
367       return false;
368     }
369   }
370   else {
371     if (*dir!='\0' &&
372         chdir(dir)==-1) {
373       perror("chdir()");
374       return false;
375     }
376   }
377
378   if (mnt->flags&MS_BIND) {
379     if (mount(mnt->src, ".",
380               mnt->type ? mnt->type : "",
381               mnt->flags, mnt->data)==-1) {
382       perror("mount()");
383       return false;
384     }
385   }
386   else {
387     if (!callExternalMount(mnt)) return false;
388   }
389
390     // Check if directories were moved between the chdirSecure() and mount(2)
391   if ((mnt->flags&MS_BIND) && opt->rootdir!=0 &&
392       (verifyPosition(mnt->src, opt->rootdir, mnt->dst)==-1 ||
393        fchroot(opt->cur_rootdir_fd)==-1)) {
394     perror("verifyPosition/fchroot");
395       // TODO: what is with unmounting?
396     return false;
397   }
398
399   if (!opt->ignore_mtab &&
400       updateMtab(mnt, opt)==-1) {
401     WRITE_MSG(2, "Failed to update mtab-file\n");
402       // no error
403   }
404   
405   return true;
406 }
407
408 static bool
409 searchAndRemoveOption(char *buf, char const *needle)
410 {
411   char          *pos = strstr(buf, needle);
412   size_t        len  = strlen(needle);
413
414   if (pos==0)                          return false;
415   if (pos>buf && pos[-1]!=',')         return false;
416   if (pos[len]!=',' && pos[len]!='\0') return false;
417
418   if (pos>buf || pos[len]!='\0') ++len;
419   if (pos>buf) --pos;
420
421   memmove(pos, pos+len, strlen(pos+len));
422   return true;
423 }
424
425 static bool
426 transformOptionList(struct MountInfo *info)
427 {
428   struct FstabOptions const *   flag;
429     
430   for (flag=FSTAB_OPTIONS; flag->opt[0]!='\0'; ++flag) {
431     if (searchAndRemoveOption(info->data, flag->opt) || flag->is_dflt) {
432       info->flags &= flag->and_flag;
433       info->flags |= flag->or_flag;
434     }
435   }
436
437   if (searchAndRemoveOption(info->data, "noauto"))
438     info->noauto = true;
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->flags  = 0;
468   info->noauto = false;
469   if (!transformOptionList(info)) return prFAIL;
470   if (info->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("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("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("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 int main(int argc, char *argv[])
546 {
547   struct MountInfo      mnt = {
548     .src         = 0,
549     .dst         = 0,
550     .type        = 0,
551     .flags       = 0,
552     .data        = 0,
553     .noauto      = false
554   };
555
556   struct Options        opt = {
557     .mtab           = "/etc/mtab",
558     .fstab          = "/etc/fstab",
559     .rootdir        = 0,
560     .ignore_mtab    = false,
561     .mount_all      = false,
562     .is_secure      = false,
563     .cur_rootdir_fd = -1
564   };
565
566   opt.cur_rootdir_fd = open("/", O_RDONLY|O_DIRECTORY);
567
568   if (opt.cur_rootdir_fd==-1) {
569     perror("open(\"/\")");
570     return EXIT_FAILURE;
571   }
572
573   while (1) {
574     int         c = getopt_long(argc, argv, "ht:nao:", CMDLINE_OPTIONS, 0);
575     if (c==-1) break;
576     
577     switch (c) {
578       case 'h'          :  showHelp(1, argv[0], 0);
579       case 'v'          :  showVersion();
580       case 't'          :  mnt.type = optarg;         break;
581       case 'n'          :  opt.ignore_mtab = true;    break;
582       case 'a'          :  opt.mount_all   = true;    break;
583       case 'o'          :  mnt.data        = optarg;  break;
584       case OPTION_RBIND :  mnt.flags      |= MS_REC;  /*@fallthrough@*/
585       case OPTION_BIND  :  mnt.flags      |= MS_BIND; break;
586       case OPTION_MOVE  :  mnt.flags      |= MS_MOVE; break;
587       case OPTION_MTAB  :  opt.mtab        = optarg;  break;
588       case OPTION_FSTAB :  opt.fstab       = optarg;  break;
589       case OPTION_CHROOT:  opt.rootdir     = optarg;  break;
590       case OPTION_SECURE:  opt.is_secure   = true;    break;
591       default           :
592         WRITE_MSG(2, "Try '");
593         WRITE_STR(2, argv[0]);
594         WRITE_MSG(2, " --help\" for more information.\n");
595         return EXIT_FAILURE;
596         break;
597     }
598   }
599
600   if (opt.mount_all && optind<argc) {
601     WRITE_MSG(2, "Can not specify <src> and '-a' at the same time\n");
602     return EXIT_FAILURE;
603   }
604
605   if (opt.mount_all) {
606     if (!mountFstab(&opt)) return EXIT_FAILURE;
607     else                   return EXIT_SUCCESS;
608   }
609
610   if (optind+2!=argc) {
611     WRITE_MSG(2, "Invalid <src> <dst> pair specified\n");
612     return EXIT_FAILURE;
613   }
614
615   if (mnt.data) {
616     mnt.data = strdup(mnt.data);
617     if (!transformOptionList(&mnt)) {
618       WRITE_MSG(2, "Invalid options specified\n");
619       return EXIT_FAILURE;
620     }
621   }
622     
623   mnt.src  = argv[optind++];
624   mnt.dst  = argv[optind++];
625
626   if (!mountSingle(&mnt, &opt)) return EXIT_FAILURE;
627     
628   return EXIT_SUCCESS;
629 }