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