added support for new migrate feature
[util-vserver.git] / util-vserver / src / chcontext.c
1 // $Id$
2
3 // Copyright (C) 2003,2004 Enrico Scholz <enrico.scholz@informatik.tu-chemnitz.de>
4 // based on chcontext.cc by Jacques Gelinas
5 //  
6 // This program is free software; you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation; either version 2, or (at your option)
9 // any later version.
10 //  
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 // GNU General Public License for more details.
15 //  
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19
20 /*
21         chcontext is a wrapper to user the new_s_context system call. It
22         does little more than mapping command line option to the system call
23         arguments.
24 */
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 #include "util.h"
30 #include "vserver.h"
31 #include "internal.h"
32
33 #include <stdio.h>
34 #include <unistd.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <errno.h>
38 #include <getopt.h>
39 #include <assert.h>
40 #include <fcntl.h>
41 #include <libgen.h>
42
43 #define ENSC_WRAPPERS_PREFIX    "chcontext: "
44 #define ENSC_WRAPPERS_VSERVER   1
45 #define ENSC_WRAPPERS_UNISTD    1
46 #define ENSC_WRAPPERS_FCNTL     1
47 #include <wrappers.h>
48
49 #define CMD_HELP        0x1000
50 #define CMD_VERSION     0x1001
51 #define CMD_CAP         0x4000
52 #define CMD_CTX         0x4001
53 #define CMD_DISCONNECT  0x4002
54 #define CMD_DOMAINNAME  0x4003
55 #define CMD_FLAG        0x4004
56 #define CMD_HOSTNAME    0x4005
57 #define CMD_SECURE      0x4006
58 #define CMD_SILENT      0x4007
59
60 int wrapper_exit_code   = 255;
61
62 struct option const
63 CMDLINE_OPTIONS[] = {
64   { "help",     no_argument,  0, CMD_HELP },
65   { "version",  no_argument,  0, CMD_VERSION },
66   { "cap",        required_argument,  0, CMD_CAP },
67   { "ctx",        required_argument,  0, CMD_CTX },
68   { "disconnect", no_argument,        0, CMD_DISCONNECT },
69   { "domainname", required_argument,  0, CMD_DOMAINNAME },
70   { "flag",       required_argument,  0, CMD_FLAG },
71   { "hostname",   required_argument,  0, CMD_HOSTNAME },
72   { "secure",     no_argument,        0, CMD_SECURE },
73   { "silent",     no_argument,        0, CMD_SILENT },
74   { 0,0,0,0 }
75 };
76
77 struct Arguments {
78     size_t              nbctx;
79     xid_t               ctxs[16];
80     bool                do_disconnect;
81     bool                do_silent;
82     unsigned int        flags;
83     uint32_t            remove_caps;
84     uint32_t            add_caps;
85     char const *        hostname;
86     char const *        domainname;
87 };
88
89 static struct Arguments const *         global_args = 0;
90
91 static void
92 showHelp(int fd, char const *cmd, int res)
93 {
94   VSERVER_DECLARE_CMD(cmd);
95   
96   WRITE_MSG(fd, "Usage: ");
97   WRITE_STR(fd, cmd);
98   WRITE_MSG(fd,
99             " [--cap [!]<cap_name>] [--secure] [--ctx <num>] [--disconnect]\n"
100             "       [--domainname <name>] [--hostname <name>] [--flag <flags>+]\n"
101             "       [--silent] [--] command arguments ...\n"
102             "\n"
103             "chcontext allocate a new security context and executes\n"
104             "a command in that context.\n"
105             "By default, a new/unused context is allocated\n"
106             "\n"
107             "--cap CAP_NAME\n"
108             "    Add a capability from the command. This option may be\n"
109             "    repeated several time.\n"
110             "    See /usr/include/linux/capability.h\n"
111             "    In general, this option is used with the --secure option\n"
112             "    --secure removes most critical capabilities and --cap\n"
113             "    adds specific ones.\n"
114             "\n"
115
116             "--cap !CAP_NAME\n"
117             "    Remove a capability from the command. This option may be\n"
118             "    repeated several time.\n"
119             "    See /usr/include/linux/capability.h\n"
120             "\n"
121             "--ctx num\n"
122             "    Select the context. On root in context 0 is allowed to\n"
123             "    select a specific context.\n"
124             "    Context number 1 is special. It can see all processes\n"
125             "    in any contexts, but can't kill them though.\n"
126             "    Option --ctx may be repeated several times to specify up to 16 contexts.\n"
127
128             "--disconnect\n"
129             "    Start the command in background and make the process\n"
130             "    a child of process 1.\n"
131
132             "--domainname new_domainname\n"
133             "    Set the domainname (NIS) in the new security context.\n"
134             "    Use \"none\" to unset the domain name.\n"
135
136             "--flag\n"
137             "    Set one flag in the new or current security context. The following\n"
138             "    flags are supported. The option may be used several time.\n"
139             "\n"
140             "        fakeinit: The new process will believe it is process number 1.\n"
141             "                  Useful to run a real /sbin/init in a vserver.\n"
142             "        lock:     The new process is trapped and can't use chcontext anymore.\n"
143             "        sched:    The new process and its children will share a common \n"
144             "                  execution priority.\n"
145             "        nproc:    Limit the number of process in the vserver according to\n"
146             "                  ulimit setting. Normally, ulimit is a per user thing.\n"
147             "                  With this flag, it becomes a per vserver thing.\n"
148             "        private:  No one can join this security context once created.\n"
149             "        ulimit:   Apply the current ulimit to the whole context\n"
150
151             "--hostname new_hostname\n"
152             "    Set the hostname in the new security context\n"
153             "    This is need because if you create a less privileged\n"
154             "    security context, it may be unable to change its hostname\n"
155
156             "--secure\n"
157             "    Remove all the capabilities to make a virtual server trustable\n"
158
159             "--silent\n"
160             "    Do not print the allocated context number.\n"
161             "\n"
162             "Please report bugs to " PACKAGE_BUGREPORT "\n");
163
164   exit(res);
165 }
166
167 static void
168 showVersion()
169 {
170   WRITE_MSG(1,
171             "chcontext-compat " VERSION " -- allocates/enters a security context\n"
172             "This program is part of " PACKAGE_STRING "\n\n"
173             "Copyright (C) 2003,2004 Enrico Scholz\n"
174             VERSION_COPYRIGHT_DISCLAIMER);
175   exit(0);
176 }
177
178 static inline void
179 setCap(char const *str, uint32_t *add_caps, uint32_t *remove_caps)
180 {
181   uint32_t      *cap;
182   int           bit;
183   
184   if (str[0] != '!')
185     cap = add_caps;
186   else {
187     cap = remove_caps;
188     str++;
189   }
190         
191   bit = vc_text2cap(str);
192         
193   if (bit!=-1) *cap |= (1<<bit);
194   else {
195     WRITE_MSG(2, "Unknown capability '");
196     WRITE_STR(2, str);
197     WRITE_MSG(2, "'\n");
198     exit(wrapper_exit_code);
199   }
200 }
201
202 static inline void
203 setFlags(char const *str, uint32_t *flags)
204 {
205   char const            *err_ptr;
206   size_t                err_len;
207   
208   *flags = vc_list2flag_compat(str, 0, &err_ptr, &err_len);
209
210   if (err_ptr!=0) {
211     WRITE_MSG(2, "Unknown flag '");
212     write(2, err_ptr, err_len);
213     WRITE_MSG(2, "'\n");
214     exit(wrapper_exit_code);
215   }
216 }
217
218 static inline ALWAYSINLINE void
219 setHostname(char const *name)
220 {
221   if (name == NULL) return;
222   
223   if (sethostname(name, strlen(name))==-1) {
224     perror("chcontext: sethostname()");
225     exit(255);
226   }
227   if (!global_args->do_silent) {
228     WRITE_MSG(1, "Host name is now ");
229     WRITE_STR(1, name);
230     WRITE_MSG(1, "\n");
231   }
232 }
233
234 static inline ALWAYSINLINE void
235 setDomainname(char const *name)
236 {
237   if (name == NULL) return;
238   
239   if (setdomainname(name, strlen(name))==-1) {
240     perror("chcontext: setdomainname()");
241     exit(255);
242   }
243   if (!global_args->do_silent) {
244     WRITE_MSG(1, "Domain name is now ");
245     WRITE_STR(1, name);
246     WRITE_MSG(1, "\n");
247   }
248 }
249
250 static inline ALWAYSINLINE void
251 tellContext(xid_t ctx)
252 {
253   char          buf[sizeof(xid_t)*3+2];
254   size_t        l;
255
256   if (global_args->do_silent) return;
257
258   l = utilvserver_fmt_long(buf,ctx);
259
260   WRITE_MSG(2, "New security context is ");
261   write(2, buf, l);
262   WRITE_MSG(2, "\n");
263 }
264
265 static inline ALWAYSINLINE int
266 initSync(int p[2])
267 {
268   if (!global_args->do_disconnect) return 0;
269
270   Epipe(p);
271   fcntl(p[1], F_SETFD, FD_CLOEXEC);
272   return Efork();
273 }
274
275 static inline ALWAYSINLINE void
276 doSyncStage1(int p[2])
277 {
278   int   fd;
279
280   if (!global_args->do_disconnect) return;
281   
282   fd = Eopen("/dev/null", O_RDONLY, 0);
283   Esetsid();
284   Edup2(fd, 0);
285   Eclose(p[0]);
286   if (fd!=0) Eclose(fd);
287   Ewrite(p[1], ".", 1);
288 }
289
290 static inline ALWAYSINLINE void
291 doSyncStage2(int p[2])
292 {
293   if (!global_args->do_disconnect) return;
294
295   Ewrite(p[1], "X", 1);
296 }
297
298 static void
299 waitOnSync(pid_t pid, int p[2])
300 {
301   int           c;
302   size_t        l;
303
304   assert(global_args->do_disconnect);
305   assert(pid!=0);
306
307   Eclose(p[1]);
308   l = Eread(p[0], &c, 1);
309   if (l!=1) exitLikeProcess(pid);
310   l = Eread(p[0], &c, 1);
311   if (l!=0) exitLikeProcess(pid);
312 }
313
314 int main (int argc, char *argv[])
315 {
316   struct Arguments args = {
317     .nbctx         = 0,
318     .do_disconnect = false,
319     .do_silent     = false,
320     .flags         = 0,
321     .remove_caps   = 0,
322     .add_caps      = 0,
323     .hostname      = 0,
324     .domainname    = 0
325   };
326   xid_t         newctx;
327   int           xflags;
328   int           p[2];
329   pid_t         pid;
330   
331   global_args = &args;
332   
333   while (1) {
334     int         c = getopt_long(argc, argv, "+", CMDLINE_OPTIONS, 0);
335     if (c==-1) break;
336
337     switch (c) {
338       case CMD_HELP             :  showHelp(1, argv[0], 0);
339       case CMD_VERSION          :  showVersion();
340       case CMD_DISCONNECT       :  args.do_disconnect = true;   break;
341       case CMD_SILENT           :  args.do_silent     = true;   break;
342       case CMD_DOMAINNAME       :  args.domainname    = optarg; break;
343       case CMD_HOSTNAME         :  args.hostname      = optarg; break;
344         
345       case CMD_CAP              :
346         setCap(optarg, &args.add_caps, &args.remove_caps);
347         break;
348       case CMD_SECURE           :
349         args.remove_caps |= vc_get_securecaps();
350         break;
351       case CMD_FLAG             :
352         setFlags(optarg, &args.flags);
353         break;
354       case CMD_CTX              :
355         if (args.nbctx>0)
356           WRITE_MSG(2, "WARNING: More than one ctx not supported by this version\n");
357         if (args.nbctx>=DIM_OF(args.ctxs)) {
358           WRITE_MSG(2, "Too many contexts given\n");
359           exit(255);
360         }
361         args.ctxs[args.nbctx++] = atoi(optarg);
362         break;
363
364           
365       default           :
366         WRITE_MSG(2, "Try '");
367         WRITE_STR(2, argv[0]);
368         WRITE_MSG(2, " --help\" for more information.\n");
369         return 255;
370         break;
371     }
372   }
373
374   if (optind>=argc) {
375     WRITE_MSG(2, "No command given; use '--help' for more information.\n");
376     exit(255);
377   }
378   
379   if (args.domainname && strcmp(args.domainname, "none")==0)
380     args.domainname = "";
381     
382   if (args.nbctx == 0)
383     args.ctxs[args.nbctx++] = VC_DYNAMIC_XID;
384     
385   xflags      = args.flags & S_CTX_INFO_INIT;
386   args.flags &= ~S_CTX_INFO_INIT;
387
388   pid = initSync(p);
389   if (pid==0) {
390     newctx            = Evc_new_s_context(args.ctxs[0],0,args.flags);
391     args.remove_caps &= (~args.add_caps);
392     setHostname(args.hostname);
393     setDomainname(args.domainname);
394
395     if (args.remove_caps!=0 || xflags!=0)
396       Evc_new_s_context (VC_SAMECTX,args.remove_caps,xflags);
397     tellContext(args.ctxs[0]==VC_DYNAMIC_XID ? newctx : args.ctxs[0]);
398
399     doSyncStage1(p);
400     execvp (argv[optind],argv+optind);
401     doSyncStage2(p);
402
403     PERROR_Q("chcontext: execvp", argv[optind]);
404     exit(255);
405   }
406
407   waitOnSync(pid, p);
408   return EXIT_SUCCESS;
409 }
410
411 #ifdef ENSC_TESTSUITE
412 #define FLAG_TEST(STR,EXP) \
413   {                        \
414     uint32_t    flag=0;    \
415     setFlags(STR, &flag);  \
416     assert(flag==(EXP));   \
417   }
418
419 #define CAP_TEST(STR,EXP_ADD,EXP_DEL)           \
420   {                                             \
421     uint32_t    add=0,del=0;                    \
422     setCap(STR, &add, &del);                    \
423     assert(add==(EXP_ADD));                     \
424     assert(del==(EXP_DEL));                     \
425   }
426
427 void
428 test()
429 {
430   FLAG_TEST("lock",       1);
431   FLAG_TEST("lock,sched", 3);
432
433   CAP_TEST("CHOWN",      1, 0);
434   CAP_TEST("CAP_CHOWN",  1, 0);
435   CAP_TEST("!CHOWN",     0, 1);
436   CAP_TEST("!CAP_CHOWN", 0, 1);
437 }
438 #endif