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