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