minor optimizations
[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 inline char const *
272 getType(struct MountInfo const *mnt)
273 {
274   if (mnt->type==0)                         return "none";
275   else if (strncmp(mnt->type, "ext", 3)==0) return "ufs";
276   else                                      return mnt->type;
277 }
278
279 static int
280 updateMtab(struct MountInfo const *mnt, struct Options const *opt)
281 {
282   int           res = -1;
283   int           fd;
284   assert(opt->mtab!=0);
285
286   if (opt->rootdir!=0 &&
287       chroot(opt->rootdir)==-1) {
288       perror("secure-mount: chroot()");
289       return -1;
290   }
291
292   fd=open(opt->mtab, O_CREAT|O_APPEND|O_WRONLY, 0644);
293   
294   if (fd==-1) perror("secure-mount: open(<mtab>)");
295   
296   if (fchroot(opt->cur_rootdir_fd)==-1) {
297     perror("secure-mount: fchroot()");
298     goto err1;
299   }
300
301   if (fd==-1) goto err0;
302
303   if (flock(fd, LOCK_EX)==-1) {
304     perror("secure-mount: flock()");
305     goto err1;
306   }
307
308
309   if (writeStrX(fd, mnt->src)==-1 ||
310       writeStrX(fd, " ")==-1 ||
311       writeStrX(fd, mnt->dst)==-1 ||
312       writeStrX(fd, " ")==-1 ||
313       writeStrX(fd, getType(mnt))==-1 ||
314       writeStrX(fd, " ")==-1 ||
315       writeStrX(fd, mnt->data ? mnt->data : "defaults")==-1 ||
316       writeStrX(fd, " 0 0\n")==-1) {
317     perror("secure-mount: write()");
318     goto err1;
319   }
320
321   res = 0;
322
323   err1: close(fd);
324   err0: return res;
325 }
326
327 static bool
328 callExternalMount(struct MountInfo const *mnt)
329 {
330   char const *  argv[10];
331   size_t        idx = 0;
332   pid_t         pid;
333   int           status;
334   char const *  mount_prog = getenv("MOUNT");
335
336   if (mount_prog==0) mount_prog = MOUNT_PROG;
337
338   argv[idx++] = mount_prog;
339   argv[idx++] = "-n";
340   if      (mnt->flag & MS_BIND) argv[idx++] = "--bind";
341   else if (mnt->flag & MS_MOVE) argv[idx++] = "--move";
342
343   if (mnt->data &&
344       strcmp(mnt->data, "defaults")!=0) {
345     argv[idx++] = "-o";
346     argv[idx++] = mnt->data;
347   }
348
349   if (mnt->type) {
350     argv[idx++] = "-t";
351     argv[idx++] = mnt->type;
352   }
353
354   argv[idx++] = mnt->src;
355   argv[idx++] = ".";
356   argv[idx]   = 0;
357
358   pid = fork();
359   if (pid==-1) {
360     perror("secure-mount: fork()");
361     return false;
362   }
363
364   if (pid==0) {
365     execv(mount_prog, const_cast(char **)(argv));
366     PERROR_Q("secure-mount: execv", mount_prog);
367     exit(1);
368   }
369
370   if (wait4(pid, &status, 0, 0)==-1) {
371     perror("secure-mount: wait4()");
372     return false;
373   }
374
375   return (WIFEXITED(status)) && (WEXITSTATUS(status)==0);
376 }
377
378 static bool
379 mountSingle(struct MountInfo const *mnt, struct Options const *opt)
380 {
381   char const    *dir = mnt->dst;
382
383   assert(mnt->dst!=0);
384   
385   if (opt->rootdir!=0) {
386     if (chdir(opt->rootdir)==-1) {
387       PERROR_Q("secure-mount: chdir", opt->rootdir);
388       return false;
389     }
390
391     while (*dir=='/') ++dir;
392   }
393
394   if (opt->is_secure) {
395     if (chdirSecure(dir)==-1) {
396       PERROR_Q("secure-mount: chdirSecure", dir);
397       return false;
398     }
399   }
400   else {
401     if (*dir!='\0' &&
402         chdir(dir)==-1) {
403       PERROR_Q("secure-mount: chdir", dir);
404       return false;
405     }
406   }
407
408   if (mnt->flag & (MS_BIND|MS_MOVE)) {
409     if (mount(mnt->src, ".",
410               mnt->type ? mnt->type : "",
411               mnt->flag,  mnt->data)==-1) {
412       perror("secure-mount: mount()");
413       return false;
414     }
415   }
416   else {
417     if (!callExternalMount(mnt)) return false;
418   }
419
420     // Check if directories were moved between the chdirSecure() and mount(2)
421   if ((mnt->flag&MS_BIND) && opt->rootdir!=0 &&
422       (verifyPosition(mnt->src, opt->rootdir, mnt->dst)==-1 ||
423        fchroot(opt->cur_rootdir_fd)==-1)) {
424     perror("secure-mount: verifyPosition/fchroot");
425       // TODO: what is with unmounting?
426     return false;
427   }
428
429   if (!opt->ignore_mtab &&
430       updateMtab(mnt, opt)==-1) {
431     WRITE_MSG(2, "Failed to update mtab-file\n");
432       // no error
433   }
434   
435   return true;
436 }
437
438 static struct FstabOption const *
439 searchOption(char const *opt, size_t len)
440 {
441   struct FstabOption const *            i;
442   for (i=FSTAB_OPTIONS+0; i<FSTAB_OPTIONS+DIM_OF(FSTAB_OPTIONS); ++i)
443     if (strncmp(i->opt, opt, len)==0) return i;
444
445   return 0;
446 }
447
448 static bool
449 transformOptionList(struct MountInfo *info)
450 {
451   char const *                  ptr = info->data;
452
453   do {
454     char const *                pos = strchr(ptr, ',');
455     struct FstabOption const *  opt;
456     
457     if (pos==0) pos = ptr+strlen(ptr);
458     opt = searchOption(ptr, pos-ptr);
459
460     if (opt!=0) {
461       info->flag  &= ~opt->mask;
462       info->flag  |=  opt->flag;
463       info->xflag |=  opt->xflag;
464     }
465
466     if (*pos!='\0')
467       ptr = pos+1;
468     else
469       ptr = pos;
470
471   } while (*ptr!='\0');
472
473   return true;
474 }
475
476 #define MOVE_TO_NEXT_FIELD(PTR,ALLOW_EOL)               \
477   while (!isspace(*PTR) && *PTR!='\0') ++PTR;           \
478   if (!(ALLOW_EOL) && *PTR=='\0') return prFAIL;        \
479   *PTR++ = '\0';                                        \
480   while (isspace(*PTR)) ++PTR
481
482 static enum {prDOIT, prFAIL, prIGNORE}
483 parseFstabLine(struct MountInfo *info, char *buf)
484 {
485   while (isspace(*buf)) ++buf;
486   if (*buf=='#' || *buf=='\0')  return prIGNORE;
487
488   info->src  = buf;
489   MOVE_TO_NEXT_FIELD(buf, false);
490   info->dst  = buf;
491   MOVE_TO_NEXT_FIELD(buf, false);
492   info->type = buf;
493   MOVE_TO_NEXT_FIELD(buf, false);
494   info->data = buf;
495   MOVE_TO_NEXT_FIELD(buf, true);
496
497   if (strcmp(info->type, "swap")==0) return prIGNORE;
498   if (strcmp(info->type, "none")==0) info->type = 0;
499
500   info->flag   = 0;
501   info->xflag  = 0;
502   if (!transformOptionList(info)) return prFAIL;
503   if (info->xflag & XFLAG_NOAUTO) return prIGNORE;
504
505   return prDOIT;
506 }
507
508 #undef MOVE_TO_NEXT_FIELD
509
510 static bool
511 mountFstab(struct Options const *opt)
512 {
513   bool          res = false;
514   int           fd;
515   off_t         len;
516
517   assert(opt->fstab!=0);
518   fd = open(opt->fstab, O_RDONLY);
519   if (fd==-1) {
520     perror("secure-mount: open(<fstab>)");
521     goto err0;
522   }
523
524   len = lseek(fd, 0, SEEK_END);
525   if (len==-1 ||
526       lseek(fd, 0, SEEK_SET)==-1) {
527     perror("secure-mount: lseek(<fstab>)");
528     goto err1;
529   }
530
531   {
532     char        buf[len+2];
533     char        *ptr, *ptrptr;
534
535     if (read(fd, buf, len+1)!=len) {
536       perror("secure-mount: read()");
537       goto err1;
538     }
539     buf[len]   = '#';   // workaround for broken dietlibc strtok_r()
540                         // implementation
541     buf[len+1] = '\0';
542
543     ptr = strtok_r(buf, "\n", &ptrptr);
544     while (ptr) {
545       struct MountInfo  mnt;
546       char *            new_ptr = strtok_r(0, "\n", &ptrptr);
547
548       switch (parseFstabLine(&mnt, ptr)) {
549         case prFAIL     :
550           WRITE_MSG(2, "Failed to parse fstab-line beginning with '");
551           WRITE_STR(2, ptr);
552           WRITE_MSG(2, "'\n");
553           goto err1;
554
555         case prIGNORE   :  break;
556         case prDOIT     :
557           chdir("/");
558           if (!mountSingle(&mnt, opt)) {
559             WRITE_MSG(2, "Failed to mount fstab-line beginning with '");
560             WRITE_STR(2, ptr);
561             WRITE_MSG(2, "'\n");
562           }
563           break;
564         default         :
565           assert(false);
566       }
567
568       ptr = new_ptr;
569     }
570   }
571
572   res = true;
573
574   err1: close(fd);
575   err0: return res;
576 }
577
578 int main(int argc, char *argv[])
579 {
580   struct MountInfo      mnt = {
581     .src         = 0,
582     .dst         = 0,
583     .type        = 0,
584     .flag        = 0,
585     .xflag       = 0,
586     .data        = 0,
587   };
588
589   struct Options        opt = {
590     .mtab           = "/etc/mtab",
591     .fstab          = "/etc/fstab",
592     .rootdir        = 0,
593     .ignore_mtab    = false,
594     .mount_all      = false,
595     .is_secure      = false,
596     .cur_rootdir_fd = -1
597   };
598
599   opt.cur_rootdir_fd = open("/", O_RDONLY|O_DIRECTORY);
600
601   if (opt.cur_rootdir_fd==-1) {
602     perror("secure-mount: open(\"/\")");
603     return EXIT_FAILURE;
604   }
605
606   signal(SIGCHLD, SIG_DFL);
607
608   while (1) {
609     int         c = getopt_long(argc, argv, "ht:nao:", CMDLINE_OPTIONS, 0);
610     if (c==-1) break;
611     
612     switch (c) {
613       case 'h'          :  showHelp(1, argv[0], 0);
614       case 'v'          :  showVersion();
615       case 't'          :  mnt.type = optarg;         break;
616       case 'n'          :  opt.ignore_mtab = true;    break;
617       case 'a'          :  opt.mount_all   = true;    break;
618       case 'o'          :  mnt.data        = optarg;  break;
619       case OPTION_RBIND :  mnt.flag       |= MS_REC;  /*@fallthrough@*/
620       case OPTION_BIND  :  mnt.flag       |= MS_BIND; break;
621       case OPTION_MOVE  :  mnt.flag       |= MS_MOVE; break;
622       case OPTION_MTAB  :  opt.mtab        = optarg;  break;
623       case OPTION_FSTAB :  opt.fstab       = optarg;  break;
624       case OPTION_CHROOT:  opt.rootdir     = optarg;  break;
625       case OPTION_SECURE:  opt.is_secure   = true;    break;
626       default           :
627         WRITE_MSG(2, "Try '");
628         WRITE_STR(2, argv[0]);
629         WRITE_MSG(2, " --help\" for more information.\n");
630         return EXIT_FAILURE;
631         break;
632     }
633   }
634
635   if (opt.mount_all && optind<argc) {
636     WRITE_MSG(2, "Can not specify <src> and '-a' at the same time\n");
637     return EXIT_FAILURE;
638   }
639
640   if (opt.mount_all) {
641     if (!mountFstab(&opt)) return EXIT_FAILURE;
642     else                   return EXIT_SUCCESS;
643   }
644
645   if (optind+2!=argc) {
646     WRITE_MSG(2, "Invalid <src> <dst> pair specified\n");
647     return EXIT_FAILURE;
648   }
649
650   if (mnt.data) {
651     mnt.data = strdup(mnt.data);
652     if (!transformOptionList(&mnt)) {
653       WRITE_MSG(2, "Invalid options specified\n");
654       return EXIT_FAILURE;
655     }
656   }
657     
658   mnt.src  = argv[optind++];
659   mnt.dst  = argv[optind++];
660
661   if (!mountSingle(&mnt, &opt)) return EXIT_FAILURE;
662     
663   return EXIT_SUCCESS;
664 }