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