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