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