use new ensc_wrappers/ headers
[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(255);
195   }
196 }
197
198 static inline void
199 setFlags(char const *str, uint32_t *flags)
200 {
201   for (;;) {
202     char const  *ptr = strchr(str, ',');
203     size_t      cnt  = ptr ? (size_t)(ptr-str) : strlen(str);
204     
205     if      (strncmp(str, "lock",     cnt)==0) *flags |= S_CTX_INFO_LOCK;
206     else if (strncmp(str, "sched",    cnt)==0) *flags |= S_CTX_INFO_SCHED;
207     else if (strncmp(str, "nproc",    cnt)==0) *flags |= S_CTX_INFO_NPROC;
208     else if (strncmp(str, "private",  cnt)==0) *flags |= S_CTX_INFO_PRIVATE;
209     else if (strncmp(str, "fakeinit", cnt)==0) *flags |= S_CTX_INFO_INIT;
210     else if (strncmp(str, "hideinfo", cnt)==0) *flags |= S_CTX_INFO_HIDEINFO;
211     else if (strncmp(str, "ulimit",   cnt)==0) *flags |= S_CTX_INFO_ULIMIT;
212     else {
213       WRITE_MSG(2, "Unknown flag '");
214       write(2, str, cnt);
215       WRITE_MSG(2, "'\n");
216       exit(255);
217     }
218
219     
220     if (ptr==0) break;
221     str = ptr+1;
222   }
223 }
224
225 static inline ALWAYSINLINE void
226 setHostname(char const *name)
227 {
228   if (name == NULL) return;
229   
230   if (sethostname(name, strlen(name))==-1) {
231     perror("sethostname()");
232     exit(255);
233   }
234   if (!global_args->do_silent) {
235     WRITE_MSG(1, "Host name is now ");
236     WRITE_STR(1, name);
237     WRITE_MSG(1, "\n");
238   }
239 }
240
241 static inline ALWAYSINLINE void
242 setDomainname(char const *name)
243 {
244   if (name == NULL) return;
245   
246   if (setdomainname(name, strlen(name))==-1) {
247     perror("setdomainname()");
248     exit(255);
249   }
250   if (!global_args->do_silent) {
251     WRITE_MSG(1, "Domain name is now ");
252     WRITE_STR(1, name);
253     WRITE_MSG(1, "\n");
254   }
255 }
256
257 static inline ALWAYSINLINE void
258 tellContext(xid_t ctx)
259 {
260   char          buf[sizeof(xid_t)*3+2];
261   size_t        l;
262
263   if (global_args->do_silent) return;
264
265   l = utilvserver_fmt_long(buf,ctx);
266
267   WRITE_MSG(2, "New security context is ");
268   write(2, buf, l);
269   WRITE_MSG(2, "\n");
270 }
271
272 static inline ALWAYSINLINE int
273 initSync(int p[2])
274 {
275   if (!global_args->do_disconnect) return 0;
276
277   Epipe(p);
278   fcntl(p[1], F_SETFD, FD_CLOEXEC);
279   return Efork();
280 }
281
282 static inline ALWAYSINLINE void
283 doSyncStage1(int p[2])
284 {
285   int   fd;
286
287   if (!global_args->do_disconnect) return;
288   
289   fd = Eopen("/dev/null", O_RDONLY, 0);
290   Esetsid();
291   Edup2(fd, 0);
292   Eclose(p[0]);
293   if (fd!=0) Eclose(fd);
294   Ewrite(p[1], ".", 1);
295 }
296
297 static inline ALWAYSINLINE void
298 doSyncStage2(int p[2])
299 {
300   if (!global_args->do_disconnect) return;
301
302   Ewrite(p[1], "X", 1);
303 }
304
305 static void
306 waitOnSync(pid_t pid, int p[2])
307 {
308   int           c;
309   size_t        l;
310
311   assert(global_args->do_disconnect);
312   assert(pid!=0);
313
314   Eclose(p[1]);
315   l = Eread(p[0], &c, 1);
316   if (l!=1) exitLikeProcess(pid);
317   l = Eread(p[0], &c, 1);
318   if (l!=0) exitLikeProcess(pid);
319 }
320
321 int main (int argc, char *argv[])
322 {
323   struct Arguments args = {
324     .nbctx         = 0,
325     .do_disconnect = false,
326     .do_silent     = false,
327     .flags         = 0,
328     .remove_caps   = 0,
329     .add_caps      = 0,
330     .hostname      = 0,
331     .domainname    = 0
332   };
333   xid_t         newctx;
334   int           xflags;
335   int           p[2];
336   pid_t         pid;
337   
338   global_args = &args;
339   
340   while (1) {
341     int         c = getopt_long(argc, argv, "+", CMDLINE_OPTIONS, 0);
342     if (c==-1) break;
343
344     switch (c) {
345       case CMD_HELP             :  showHelp(1, argv[0], 0);
346       case CMD_VERSION          :  showVersion();
347       case CMD_DISCONNECT       :  args.do_disconnect = true;   break;
348       case CMD_SILENT           :  args.do_silent     = true;   break;
349       case CMD_DOMAINNAME       :  args.domainname    = optarg; break;
350       case CMD_HOSTNAME         :  args.hostname      = optarg; break;
351         
352       case CMD_CAP              :
353         setCap(optarg, &args.add_caps, &args.remove_caps);
354         break;
355       case CMD_SECURE           :
356         args.remove_caps |= vc_get_securecaps();
357         break;
358       case CMD_FLAG             :
359         setFlags(optarg, &args.flags);
360         break;
361       case CMD_CTX              :
362         if (args.nbctx>0)
363           WRITE_MSG(2, "WARNING: More than one ctx not supported by this version\n");
364         if (args.nbctx>=DIM_OF(args.ctxs)) {
365           WRITE_MSG(2, "Too many contexts given\n");
366           exit(255);
367         }
368         args.ctxs[args.nbctx++] = atoi(optarg);
369         break;
370
371           
372       default           :
373         WRITE_MSG(2, "Try '");
374         WRITE_STR(2, argv[0]);
375         WRITE_MSG(2, " --help\" for more information.\n");
376         return 255;
377         break;
378     }
379   }
380
381   if (optind>=argc) {
382     WRITE_MSG(2, "No command given; use '--help' for more information.\n");
383     exit(255);
384   }
385   
386   if (args.domainname && strcmp(args.domainname, "none")==0)
387     args.domainname = "";
388     
389   if (args.nbctx == 0)
390     args.ctxs[args.nbctx++] = VC_RANDCTX;
391     
392   xflags = args.flags & 16;
393
394   newctx            = Evc_new_s_context(args.ctxs[0],0,args.flags&~16);
395   args.remove_caps &= (~args.add_caps);
396   setHostname(args.hostname);
397   setDomainname(args.domainname);
398
399   pid = initSync(p);
400   
401   if (pid==0) {
402     if (args.remove_caps!=0 || xflags!=0)
403       Evc_new_s_context (VC_SAMECTX,args.remove_caps,xflags);
404     tellContext(args.ctxs[0]==VC_RANDCTX ? newctx : args.ctxs[0]);
405
406     doSyncStage1(p);
407     execvp (argv[optind],argv+optind);
408     doSyncStage2(p);
409
410     perror("execvp()");
411     exit(255);
412   }
413
414   waitOnSync(pid, p);
415   return EXIT_SUCCESS;
416 }
417
418 #ifdef ENSC_TESTSUITE
419 #define FLAG_TEST(STR,EXP) \
420   {                        \
421     uint32_t    flag=0;    \
422     setFlags(STR, &flag);  \
423     assert(flag==(EXP));   \
424   }
425
426 #define CAP_TEST(STR,EXP_ADD,EXP_DEL)           \
427   {                                             \
428     uint32_t    add=0,del=0;                    \
429     setCap(STR, &add, &del);                    \
430     assert(add==(EXP_ADD));                     \
431     assert(del==(EXP_DEL));                     \
432   }
433
434 void
435 test()
436 {
437   FLAG_TEST("lock",       1);
438   FLAG_TEST("lock,sched", 3);
439
440   CAP_TEST("CHOWN",      1, 0);
441   CAP_TEST("CAP_CHOWN",  1, 0);
442   CAP_TEST("!CHOWN",     0, 1);
443   CAP_TEST("!CAP_CHOWN", 0, 1);
444 }
445 #endif