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