gentoo: use /var/run for new /run compatibility
[util-vserver.git] / src / vcontext.c
1 // $Id$    --*- c -*--
2
3 // Copyright (C) 2004-2006 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 #ifdef HAVE_CONFIG_H
20 #  include <config.h>
21 #endif
22
23 #include "util.h"
24 #include "compat-pivot_root.h"
25 #include "lib/internal.h"
26 #include "lib_internal/jail.h"
27 #include "lib_internal/sys_personality.h"
28 #include "lib_internal/sys_unshare.h"
29
30 #include <vserver.h>
31 #include <getopt.h>
32 #include <fcntl.h>
33 #include <errno.h>
34 #include <sys/socket.h>
35 #include <sys/un.h>
36 #include <assert.h>
37 #include <signal.h>
38 #include <sys/types.h>
39 #include <pwd.h>
40 #include <grp.h>
41 #include <sys/mount.h>
42
43 #include <linux/personality.h>
44
45 #define ENSC_WRAPPERS_PREFIX    "vcontext: "
46 #define ENSC_WRAPPERS_UNISTD    1
47 #define ENSC_WRAPPERS_VSERVER   1
48 #define ENSC_WRAPPERS_FCNTL     1
49 #define ENSC_WRAPPERS_SOCKET    1
50 #define ENSC_WRAPPERS_IOSOCK    1
51 #include <wrappers.h>
52
53 #define CMD_HELP                0x1000
54 #define CMD_VERSION             0x1001
55 #define CMD_XID                 0x4000
56 #define CMD_CREATE              0x4001
57 #define CMD_MIGRATE             0x4003
58 #define CMD_INITPID             0x4002
59 #define CMD_DISCONNECT          0x4004
60 #define CMD_UID                 0x4005
61 #define CMD_CHROOT              0x4006
62 #define CMD_SILENT              0x4007
63 #define CMD_SYNCSOCK            0x4008
64 #define CMD_SYNCMSG             0x4009
65 #define CMD_MIGRATESELF         0x400a
66 #define CMD_ENDSETUP            0x400b
67 #define CMD_SILENTEXIST         0x400c
68 #define CMD_NAMESPACE           0x400d
69 #define CMD_PERSTYPE            0x400e
70 #define CMD_PERSFLAG            0x400f
71 #define CMD_VLOGIN              0x4010
72 #define CMD_PIVOT_ROOT          0x4011
73 #define CMD_CLOSE_FD            0x4012
74
75
76 #ifndef MNT_DETACH
77 #define MNT_DETACH              0x0002
78 #endif
79
80
81 struct option const
82 CMDLINE_OPTIONS[] = {
83   { "help",       no_argument,       0, CMD_HELP },
84   { "version",    no_argument,       0, CMD_VERSION },
85   { "ctx",        required_argument, 0, CMD_XID },
86   { "xid",        required_argument, 0, CMD_XID },
87   { "create",     no_argument,       0, CMD_CREATE },
88   { "migrate",    no_argument,       0, CMD_MIGRATE },
89   { "migrate-self", no_argument,        0, CMD_MIGRATESELF },
90   { "initpid",      no_argument,        0, CMD_INITPID },
91   { "endsetup",     no_argument,        0, CMD_ENDSETUP },
92   { "disconnect",   no_argument,        0, CMD_DISCONNECT },
93   { "silent",       no_argument,        0, CMD_SILENT },
94   { "silentexist",  no_argument,        0, CMD_SILENTEXIST },
95   { "uid",          required_argument,  0, CMD_UID },
96   { "chroot",       no_argument,        0, CMD_CHROOT },
97   { "namespace",    no_argument,        0, CMD_NAMESPACE },
98   { "syncsock",     required_argument,  0, CMD_SYNCSOCK },
99   { "syncmsg",      required_argument,  0, CMD_SYNCMSG },
100   { "personality-type",  required_argument, 0, CMD_PERSTYPE },
101   { "personality-flags", required_argument, 0, CMD_PERSFLAG },
102   { "vlogin",       no_argument,        0, CMD_VLOGIN },
103   { "pivot-root",   no_argument,        0, CMD_PIVOT_ROOT },
104   { "closefd",      no_argument,        0, CMD_CLOSE_FD },
105 #if 1
106   { "fakeinit",     no_argument,        0, CMD_INITPID },       // compatibility
107 #endif
108   { 0,0,0,0 },
109 };
110
111 struct Arguments {
112     bool                do_create;
113     bool                do_migrate;
114     bool                do_migrateself;
115     bool                do_disconnect;
116     bool                do_endsetup;
117     bool                is_initpid;
118     bool                is_silentexist;
119     bool                set_namespace;
120     bool                do_vlogin;
121     uint_least32_t      personality_flags;
122     uint_least32_t      personality_type;
123     int                 verbosity;
124     bool                do_chroot;
125     bool                do_pivot_root;
126     bool                do_close_fd;
127     char const *        uid;
128     xid_t               xid;
129     char const *        sync_sock;
130     char const *        sync_msg;
131 };
132
133 int             wrapper_exit_code = 255;
134
135 void do_vlogin(int argc, char *argv[], int ind);
136
137 static void
138 showHelp(int fd, char const *cmd, int res)
139 {
140   WRITE_MSG(fd, "Usage:\n    ");
141   WRITE_STR(fd, cmd);
142   WRITE_MSG(fd,
143             " --create [--xid <xid>] <opts>* [--] <program> <args>*\n    ");
144   WRITE_STR(fd, cmd);
145   WRITE_MSG(fd,
146             " [(--migrate --xid <xid>)|--migrate-self]  <opts>* [--] <program> <args>*\n"
147             "\n"
148             "<opts> can be:\n"
149             "    --chroot        ...  chroot into current directory\n"
150             "    --namespace     ...  execute namespace management operations\n"
151             "    --uid <uid>     ...  change uid\n"
152             "    --initpid       ...  set current process as general process reaper\n"
153             "                         for ctx (possible for --migrate only)\n"
154             "    --endsetup      ...  clear the setup flag; usefully for migrate only\n"
155             "    --disconnect    ...  start program in background\n"
156             "    --personality-type <type>\n"
157             "                    ...  execute <program> in the given execution domain\n"
158             "    --personality-flags <flags>+\n"
159             "                    ...  set special flags for the given execution domain\n"
160             "    --silent        ...  be silent\n"
161             "    --silentexist   ...  be silent when context exists already; usefully\n"
162             "                         for '--create' only\n"
163             "    --syncsock <file-name>\n"
164             "                    ...  before executing the program, send a message\n"
165             "                         to the socket and wait until it closes.\n"
166             "                         <file-name> must be a SOCK_STREAM unix socket\n"
167             "    --syncmsg <message>\n"
168             "                    ...  use <message> as synchronization message; by\n"
169             "                         default, 'ok' will be used\n"
170             "    --vlogin        ...  enable terminal proxy\n"
171             "    --closefd       ...  close all open file descriptors >2\n"
172             "\n"
173             "'vcontext --create' exits with code 254 iff the context exists already.\n"
174             "\n"
175             "Please report bugs to " PACKAGE_BUGREPORT "\n");
176
177   exit(res);
178 }
179
180 static void
181 showVersion()
182 {
183   WRITE_MSG(1,
184             "vcontext " VERSION " -- manages the creation of security contexts\n"
185             "This program is part of " PACKAGE_STRING "\n\n"
186             "Copyright (C) 2004-2006 Enrico Scholz\n"
187             VERSION_COPYRIGHT_DISCLAIMER);
188   exit(0);
189 }
190
191 #include "context-sync.hc"
192
193 static inline ALWAYSINLINE void
194 tellContext(xid_t ctx, bool do_it)
195 {
196   char          buf[sizeof(xid_t)*3+2];
197   size_t        l;
198
199   if (!do_it) return;
200
201   l = utilvserver_fmt_long(buf,ctx);
202
203   WRITE_MSG(1, "New security context is ");
204   Vwrite   (1, buf, l);
205   WRITE_MSG(1, "\n");
206 }
207
208 static int
209 connectExternalSync(char const *filename)
210 {
211   int                   fd;
212   struct sockaddr_un    addr;
213
214   if (filename==0) return -1;
215
216   ENSC_INIT_UNIX_SOCK(addr, filename);
217
218   fd = Esocket(PF_UNIX, SOCK_STREAM, 0);
219   Econnect(fd, &addr, sizeof(addr));
220
221   return fd;
222 }
223
224 static void
225 setFlags(struct Arguments const *args, xid_t xid)
226 {
227   struct vc_ctx_flags   flags = { 0,0 };
228
229   if (args->is_initpid)
230     flags.mask |=  VC_VXF_STATE_INIT;
231
232   if (args->do_endsetup)
233     flags.mask |=  VC_VXF_STATE_SETUP;
234
235   if (flags.mask!=0) {
236     DPRINTF("set_flags: mask=%08llx, flag=%08llx\n", flags.mask, flags.flagword);
237     Evc_set_cflags(xid, &flags);
238   }
239 }
240
241 static void
242 doExternalSync(int fd, char const *msg)
243 {
244   char          c;
245
246   if (fd==-1) return;
247
248   if (msg) EsendAll(fd, msg, strlen(msg));
249   Eshutdown(fd, SHUT_WR);
250
251   if (TEMP_FAILURE_RETRY(recv(fd, &c, 1, MSG_NOSIGNAL))!=0) {
252     WRITE_MSG(2, ENSC_WRAPPERS_PREFIX "unexpected external synchronization event\n");
253     exit(wrapper_exit_code);
254   }
255
256   Eclose(fd);
257 }
258
259 static inline ALWAYSINLINE int
260 doit(struct Arguments const *args, int argc, char *argv[])
261 {
262   int                   p[2][2];
263   pid_t                 pid = initSync(p, args->do_disconnect);
264
265   if (pid==0) {
266     xid_t                       xid;
267     int                         ext_sync_fd = connectExternalSync(args->sync_sock);
268
269     doSyncStage0(p, args->do_disconnect);
270
271     if (args->do_close_fd) {
272       int fd;
273       for (fd = 3; fd < sysconf(_SC_OPEN_MAX); fd++) {
274         if (fd == ext_sync_fd)
275           continue;
276         close(fd);
277       }
278     }
279
280     if (args->do_create) {
281       xid = vc_ctx_create(args->xid, NULL);
282       if (xid==VC_NOCTX) {
283         switch (errno) {
284           case EEXIST   :
285             if (!args->is_silentexist)
286               perror(ENSC_WRAPPERS_PREFIX "vc_ctx_create()");
287             return 254;
288           default       :
289             perror(ENSC_WRAPPERS_PREFIX "vc_ctx_create()");
290             return wrapper_exit_code;
291         }
292       }
293       tellContext(xid, args->verbosity>=1);
294     }
295     else
296       xid = args->xid;
297
298     if (args->do_chroot) {
299       Echroot(".");
300       if (args->set_namespace) {
301         if (args->do_migrateself)  Evc_set_namespace(xid, CLONE_NEWNS|CLONE_FS, 0);
302         else if (args->do_migrate) Evc_enter_namespace(xid, CLONE_NEWNS|CLONE_FS, 0);
303       }
304     }
305     else if (args->do_pivot_root) {
306       if (vc_enter_namespace(xid, CLONE_NEWNS | CLONE_FS, 1) == -1) {
307         bool existed = false;
308         if (sys_unshare(CLONE_NEWNS) == -1) {
309           perror(ENSC_WRAPPERS_PREFIX "unshare(NEWNS)");
310           return wrapper_exit_code;
311         }
312         if (mkdir("./.oldroot", 0700) == -1) {
313           if (errno == EEXIST)
314             existed = true;
315           else {
316             perror(ENSC_WRAPPERS_PREFIX "mkdir()");
317             return wrapper_exit_code;
318           }
319         }
320         if (pivot_root(".", "./.oldroot") == -1) {
321           perror(ENSC_WRAPPERS_PREFIX "pivot_root()");
322           return wrapper_exit_code;
323         }
324         if (umount2("/.oldroot", MNT_DETACH) == -1) {
325           perror(ENSC_WRAPPERS_PREFIX "umount2()");
326           return wrapper_exit_code;
327         }
328         if (!existed && rmdir("/.oldroot") == -1) {
329           perror(ENSC_WRAPPERS_PREFIX "rmdir()");
330           return wrapper_exit_code;
331         }
332         Evc_set_namespace(xid, CLONE_NEWNS | CLONE_FS, 1);
333       }
334     }
335
336     setFlags(args, xid);
337
338     if (args->do_migrate && !args->do_migrateself)
339       Evc_ctx_migrate(xid, 0);
340
341     if (args->uid != NULL) {
342       uid_t uid = 0;
343       unsigned long tmp;
344
345       if (!isNumberUnsigned(args->uid, &tmp, false)) {
346 #ifdef __dietlibc__
347         struct passwd *pw;
348         pw = getpwnam(args->uid);
349         if (pw == NULL) {
350           WRITE_MSG(2, ENSC_WRAPPERS_PREFIX "Username '");
351           WRITE_STR(2, args->uid);
352           WRITE_MSG(2, "' does not exist\n");
353           return wrapper_exit_code;
354         }
355         uid = pw->pw_uid;
356         Einitgroups(args->uid, pw->pw_gid);
357         Esetgid(pw->pw_gid);
358 #else
359         WRITE_MSG(2, ENSC_WRAPPERS_PREFIX "Uid '");
360         WRITE_STR(2, args->uid);
361         WRITE_MSG(2, "' is not a number\n");
362         return wrapper_exit_code;
363 #endif
364       }
365       else
366         uid = (uid_t) tmp;
367
368       Esetuid((uid_t) uid);
369       if (getuid()!=uid) {
370         WRITE_MSG(2, ENSC_WRAPPERS_PREFIX "Something went wrong while changing the UID\n");
371         exit(wrapper_exit_code);
372       }
373     }
374
375     if (args->personality_type!=VC_BAD_PERSONALITY &&
376         sys_personality(args->personality_type | args->personality_flags)==-1) {
377       perror(ENSC_WRAPPERS_PREFIX "personality()");
378       exit(wrapper_exit_code);
379     }
380
381     doExternalSync(ext_sync_fd, args->sync_msg);
382     doSyncStage1(p, args->do_disconnect);
383     DPRINTF("doit: pid=%u, ppid=%u\n", getpid(), getppid());
384
385     if (!args->do_vlogin)
386       execvp (argv[optind],argv+optind);
387     else
388       do_vlogin(argc, argv, optind);
389     doSyncStage2(p, args->do_disconnect);
390
391     PERROR_Q(ENSC_WRAPPERS_PREFIX "execvp", argv[optind]);
392     exit(wrapper_exit_code);
393   }
394
395   assert(args->do_disconnect);
396
397   waitOnSync(pid, p, args->xid!=VC_DYNAMIC_XID && args->do_migrate);
398   return EXIT_SUCCESS;
399 }
400
401 static uint_least32_t
402 parsePersonalityType(char const *str)
403 {
404   uint_least32_t        res = vc_str2personalitytype(str, 0);
405   if (res==VC_BAD_PERSONALITY) {
406     WRITE_MSG(2, ENSC_WRAPPERS_PREFIX "bad personality type\n");
407     exit(wrapper_exit_code);
408   }
409
410   return res;
411 }
412
413 static uint_least32_t
414 parsePersonalityFlags(char const *str)
415 {
416   struct vc_err_listparser      err;
417   uint_least32_t                res;
418
419   if (vc_list2personalityflag(str, 0, &res, &err)==-1) {
420     WRITE_MSG(2, ENSC_WRAPPERS_PREFIX "bad personality flag '");
421     Vwrite(2, err.ptr, err.len);
422     WRITE_MSG(2, "'\n");
423     exit(wrapper_exit_code);
424   }
425
426   return res;
427 }
428
429 int main (int argc, char *argv[])
430 {
431   struct Arguments              args = {
432     .do_create         = false,
433     .do_migrate        = false,
434     .do_migrateself    = false,
435     .do_disconnect     = false,
436     .do_endsetup       = false,
437     .do_vlogin         = false,
438     .do_close_fd       = false,
439     .is_initpid        = false,
440     .is_silentexist    = false,
441     .set_namespace     = false,
442     .verbosity         = 1,
443     .uid               = NULL,
444     .xid               = VC_DYNAMIC_XID,
445     .personality_type  = VC_BAD_PERSONALITY,
446     .personality_flags = 0,
447     .sync_msg          = "ok",
448   };
449
450   while (1) {
451     int         c = getopt_long(argc, argv, "+", CMDLINE_OPTIONS, 0);
452     if (c==-1) break;
453
454     switch (c) {
455       case CMD_HELP             :  showHelp(1, argv[0], 0);
456       case CMD_VERSION          :  showVersion();
457       case CMD_CREATE           :  args.do_create      = true;   break;
458       case CMD_MIGRATE          :  args.do_migrate     = true;   break;
459       case CMD_DISCONNECT       :  args.do_disconnect  = true;   break;
460       case CMD_ENDSETUP         :  args.do_endsetup    = true;   break;
461       case CMD_VLOGIN           :  args.do_vlogin      = true;   break;
462       case CMD_INITPID          :  args.is_initpid     = true;   break;
463       case CMD_CHROOT           :  args.do_chroot      = true;   break;
464       case CMD_PIVOT_ROOT       :  args.do_pivot_root  = true;   break;
465       case CMD_NAMESPACE        :  args.set_namespace  = true;   break;
466       case CMD_SILENTEXIST      :  args.is_silentexist = true;   break;
467       case CMD_CLOSE_FD         :  args.do_close_fd    = true;   break;
468       case CMD_SYNCSOCK         :  args.sync_sock      = optarg; break;
469       case CMD_SYNCMSG          :  args.sync_msg       = optarg; break;
470       case CMD_UID              :  args.uid            = optarg; break;
471       case CMD_XID              :  args.xid = Evc_xidopt2xid(optarg,true); break;
472       case CMD_SILENT           :  --args.verbosity; break;
473       case CMD_PERSTYPE         :
474         args.personality_type   = parsePersonalityType(optarg);
475         break;
476       case CMD_PERSFLAG         :
477         args.personality_flags |= parsePersonalityFlags(optarg);
478         break;
479       case CMD_MIGRATESELF      :
480         args.do_migrate     = true;
481         args.do_migrateself = true;
482         break;
483
484       default           :
485         WRITE_MSG(2, "Try '");
486         WRITE_STR(2, argv[0]);
487         WRITE_MSG(2, " --help' for more information.\n");
488         return wrapper_exit_code;
489         break;
490     }
491   }
492
493   signal(SIGCHLD, SIG_DFL);
494
495   if (args.do_migrateself)
496     args.xid = Evc_get_task_xid(0);
497
498   if (!args.do_create && !args.do_migrate)
499     WRITE_MSG(2, "Neither '--create' nor '--migrate' specified; try '--help' for more information\n");
500   else if (args.do_create  &&  args.do_migrate)
501     WRITE_MSG(2, "Can not specify '--create' and '--migrate' at the same time; try '--help' for more information\n");
502   else if (!args.do_migrate && args.is_initpid)
503     WRITE_MSG(2, "'--initpid' is possible in combination with '--migrate' only\n");
504   else if (!args.do_create && args.xid==VC_DYNAMIC_XID)
505     WRITE_MSG(2, ENSC_WRAPPERS_PREFIX "Can not migrate to an unknown context\n");
506   else if (optind>=argc)
507     WRITE_MSG(2, "No command given; use '--help' for more information.\n");
508   else
509     return doit(&args, argc, argv);
510
511   return wrapper_exit_code;
512 }