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