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