2 * filesystem sandbox server stub for libcaptive
3 * Copyright (C) 2003 Jan Kratochvil <project-captive@jankratochvil.net>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; exactly version 2 of June 1991 is required
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include <glib/gmessages.h>
24 #include <glib/giochannel.h>
25 #include <glib/gerror.h>
30 #include "captive/options.h"
31 #include <glib-object.h>
32 #include "captive/macros.h"
33 #include <sys/types.h>
42 #include <sys/resource.h>
43 #include <linc/linc-protocol.h> /* for linc_set_tmpdir() */
44 #include <orbit/orb-core/corba-defs.h>
47 /* Do not: #include "../../libcaptive/sandbox/split.h" * for captive_sandbox_fd_closeup(); FIXME *
48 * as it has libcaptive-dependent includes conditioned by ORBIT2.
49 * FIXME: Unify this declaration:
51 void captive_sandbox_fd_closeup(int fd_first_to_delete);
52 void captive_corba_sandbox_child(const gchar *chrooted_orbit_dir);
57 /* FIXME: We hit linc-1.0.1/src/linc-protocols.c/linc_protocol_get_sockaddr_unix()
58 * limit of socket pathname 64 characters.
59 * With CHROOT_PATH_HASHKEY_LENGTH 12 "linc-%x-%x-%x%x" still does not fit completely.
61 #define CHROOT_PATH_HASHKEY_LENGTH (12)
64 GQuark sandbox_server_main_error_quark(void)
69 r=g_quark_from_static_string("sandbox-server");
75 static gchar *optarg_setuid=CAPTIVE_SANDBOX_SETUID;
76 static gchar *optarg_setgid=CAPTIVE_SANDBOX_SETGID;
77 static gchar *optarg_chroot=CAPTIVE_SANDBOX_CHROOT;
78 static gint optarg_no_rlimit=0;
80 static const struct poptOption popt_table[]={
81 #define SANDBOX_SERVER_POPT(longname,argInfoP,argP,descripP,argDescripP) \
83 longName: (longname), \
85 argInfo: (argInfoP), \
88 descrip: (descripP), \
89 argDescrip: (argDescripP), \
92 SANDBOX_SERVER_POPT("setuid" ,POPT_ARG_STRING,&optarg_setuid,
93 N_("Username or UID to become; \"-\" for disable"),N_("UID")),
94 SANDBOX_SERVER_POPT("setgid" ,POPT_ARG_STRING,&optarg_setgid,
95 N_("Groupname or GID to become; \"-\" for disable"),N_("GID")),
96 SANDBOX_SERVER_POPT("chroot" ,POPT_ARG_STRING,&optarg_chroot,
97 N_("Pathname to directory for chroot(2); \"-\" for disable"),N_("directory")),
98 SANDBOX_SERVER_POPT("no-rlimit",POPT_ARG_NONE ,&optarg_no_rlimit,
99 N_("Disable setrlimit(2) restrictions"),NULL),
101 #undef SANDBOX_SERVER_POPT
107 static gchar *fatal_argv0;
109 static void fatal(const char *fmt,...)
113 fprintf(stderr,"%s: ",fatal_argv0);
115 vfprintf(stderr,fmt,ap);
117 fprintf(stderr,"!\nAborting!\n");
123 static void check_dir_safety(const gchar *dir)
130 fatal("Loop count >=%d during check_dir_safety(\"%s\")",depth,dir);
133 fatal("chroot path \"%s\" not absolute",dir);
134 dir=captive_printf_alloca("%s/",dir);
135 local_dir=(gchar *)captive_strdup_alloca(dir);
136 for (cs=dir;cs;cs=strchr(cs+1,'/')) {
140 /* Include the trailing '/' to resolve the root directory as "/". */
141 memcpy(local_dir,dir,cs+1-dir);
142 local_dir[cs+1-dir]=0;
143 if (lstat(local_dir,&statbuf))
144 fatal("lstat(\"%s\") of chroot path component: %m",local_dir);
145 if (S_ISLNK(statbuf.st_mode)) {
146 char linkbuf[PATH_MAX];
149 if (0>(linkbuflen=readlink(local_dir,linkbuf,sizeof(linkbuf)-1)))
150 fatal("readlink(\"%s\") of chroot path component: %m",local_dir);
151 linkbuf[linkbuflen]=0;
152 check_dir_safety(linkbuf);
153 if (stat(local_dir,&statbuf)) /* NOT lstat(2) */
154 fatal("stat(\"%s\") of chroot path component: %m",local_dir);
156 if (!S_ISDIR(statbuf.st_mode))
157 fatal("lstat/stat(\"%s\") of chroot path component is !S_ISDIR",local_dir);
158 if (statbuf.st_uid!=0)
159 fatal("lstat/stat(\"%s\") of chroot path component has UID %d !=0",local_dir,(int)statbuf.st_uid);
160 if (statbuf.st_gid!=0)
161 fatal("lstat/stat(\"%s\") of chroot path component has GID %d !=0",local_dir,(int)statbuf.st_gid);
162 if ((statbuf.st_mode&(S_IFDIR|S_ISVTX|0111)) != (S_IFDIR|0111))
163 fatal("lstat/stat(\"%s\") of chroot path component has mode 0%o !=04[01]111",local_dir,(int)statbuf.st_mode);
169 static void chrooted_unlink_recursive(const gchar *pathname)
172 struct dirent *dirent;
177 fatal("Loop count >=%d during chrooted_unlink_recursive(\"%s\")",depth,pathname);
179 /* Security: Do not allow anyone to escape the sandbox directory by symlinks. */
180 if (lstat(pathname,&statbuf))
181 fatal("Cannot lstat(\"%s\") to delete leftover sandbox files: %m",pathname);
182 if (!S_ISDIR(statbuf.st_mode)) {
183 if (unlink(pathname))
184 fatal("Cannot unlink(\"%s\") to delete leftover sandbox files: %m",pathname);
187 if (!(dir=opendir(pathname)))
188 fatal("Cannot opendir(\"%s\") to delete leftover sandbox files: %m",pathname);
189 while (errno=0,(dirent=readdir(dir))) {
192 if (!strcmp(dirent->d_name,".") || !strcmp(dirent->d_name,".."))
194 dirent_path=g_strdup_printf("%s/%s",pathname,dirent->d_name);
195 chrooted_unlink_recursive(dirent_path);
199 fatal("Cannot readdir(\"%s\") during delete of leftover sandbox files: %m",pathname);
201 fatal("Cannot closedir(\"%s\") during delete of leftover sandbox files: %m",pathname);
203 fatal("Cannot rmdir(\"%s\") during delete of leftover sandbox files: %m",pathname);
209 static void chrooted_cleanuplockeddirs(const gchar *pathname,const gchar *prefix)
212 struct dirent *dirent;
214 if (!(dir=opendir(pathname))) {
216 fatal("Cannot opendir(\"%s\") to delete leftover sandbox files: %m",pathname);
217 /* errno==ENOTDIR, a regular file */
218 if (unlink(pathname))
219 fatal("Cannot unlink(\"%s\") to delete leftover sandbox files: %m",pathname);
222 while (errno=0,(dirent=readdir(dir))) {
226 if (!strcmp(dirent->d_name,".") || !strcmp(dirent->d_name,".."))
228 if (strncmp(dirent->d_name,prefix,strlen(prefix)))
230 dirent_path=g_strdup_printf("%s/%s",pathname,dirent->d_name);
231 if (-1==(direntfd=open(dirent_path,O_RDONLY))) {
232 if (errno==ENOENT) /* It could disappear in the meantime. */
233 goto next_dirent_free_dirent_path;
234 fatal("Cannot open(\"%s\") as the child directory during delete of leftover sandbox files: %m",dirent_path);
236 if (flock(direntfd,LOCK_EX|LOCK_NB)) {
237 if (errno==EWOULDBLOCK) /* Valid directory in use. */
238 goto next_dirent_close_direntfd;
239 fatal("Cannot flock(\"%s\",LOCK_EX|LOCK_NB) child directory during delete of leftover sandbox files: %m",dirent_path);
241 chrooted_unlink_recursive(dirent_path);
242 next_dirent_close_direntfd:
244 fatal("Cannot close(\"%s\") child directory during delete of leftover sandbox files: %m",dirent_path);
245 next_dirent_free_dirent_path:
249 fatal("Cannot readdir(\"%s\") during delete of leftover sandbox files: %m",pathname);
251 fatal("Cannot closedir(\"%s\") during delete of leftover sandbox files: %m",pathname);
254 static void chrooted_createdir(const gchar *dir,uid_t uid,gid_t gid,gboolean lock)
258 for (retries=0;retries<10;retries++) {
262 if (mkdir(dir,0711)) {
264 fatal("Failed to create chroot directory \"%s\": %m",dir);
265 chrooted_unlink_recursive(dir);
267 fatal("Failed to create chroot directory \"%s\" after attempted unlink: %m",dir);
271 dirfd=open(dir,O_RDONLY);
274 fatal("Failed to open created chroot directory \"%s\" to lock it: %m",dir);
277 /* Do not use 'LOCK_NB' here as the garbage collector should release it soon. */
278 if (flock(dirfd,LOCK_EX))
279 fatal("Failed to lock created chroot directory \"%s\": %m",dir);
280 if (lstat(dir,&statbuf)) {
282 fatal("Failed to lstat(2) created chroot directory \"%s\": %m",dir);
284 fatal("Failed to close created and locked chroot directory \"%s\": %m",dir);
287 /* Leave 'dirfd' open to leave it LOCK_EX-ed. */
290 if (chown(dir,uid,gid))
291 fatal("Failed to chown(\"%s\",%d,%d): %m",dir,uid,gid);
292 if (chmod(dir,0711)) /* Just to be safe after chown(2); should be already done by mkdir(2). */
293 fatal("Failed to chmod(\"%s\",0%o): %m",dir,0711);
296 static void sandbox_server_rlimit(int resource,const gchar *resource_string,rlim_t rlim_max)
300 rlim.rlim_cur=rlim.rlim_max=rlim_max;
301 if (setrlimit(resource,&rlim))
302 fatal("setrlimit(%s,%d): %m",resource_string,(int)rlim_max);
303 if (getrlimit(resource,&rlim))
304 fatal("getrlimit(%s,%d): %m",resource_string,(int)rlim_max);
305 if (rlim.rlim_cur!=rlim_max || rlim.rlim_max!=rlim_max)
306 fatal("Unsuccessful setrlimit(%s)",resource_string);
309 static gchar *chrooted_orbit_dir;
311 static void chroot_setup(gboolean fragile)
314 const gchar *want_uid_name=NULL;
317 const gchar *chroot_pid_hashkey_dir=NULL;
320 captive_sandbox_fd_closeup(2 /* STDERR */ +1);
324 #define CLEANEMPTY(var) G_STMT_START { \
325 if ((var) && (!*(var) || *(var)=='-')) \
328 CLEANEMPTY(optarg_setgid);
329 CLEANEMPTY(optarg_setuid);
330 CLEANEMPTY(optarg_chroot);
336 want_gidl=strtol(optarg_setgid,&endptr,10);
337 if (!endptr || !*endptr) {
339 if (want_gidl<=0 || want_gid!=(gid_t)want_gidl)
340 fatal("Numeric setgid not parsable: %s",optarg_setgid);
343 struct group *want_gid_group=NULL;
344 if (!(want_gid_group=getgrnam(optarg_setgid)))
345 fatal("Unable to query setgid group name \"%s\"",optarg_setgid);
346 want_gid=want_gid_group->gr_gid;
352 struct passwd *want_uid_passwd;
353 want_uidl=strtol(optarg_setuid,&endptr,10);
354 if (!endptr || !*endptr) {
356 if (want_uidl<=0 || want_uid!=(gid_t)want_uidl)
357 fatal("Numeric setuid not parsable: %s",optarg_setuid);
360 if (!(want_uid_passwd=getpwnam(optarg_setuid)))
361 fatal("Unable to query setuid user name \"%s\"",optarg_setuid);
362 want_uid=want_uid_passwd->pw_uid;
365 fatal("Unable to detect setuid UID");
366 if (!(want_uid_passwd=getpwuid(want_uid)))
367 fatal("Unable to query name of UID %d",(int)want_uid);
368 want_uid_name=captive_strdup_alloca(want_uid_passwd->pw_name);
371 if (fragile && !optarg_chroot)
372 fatal("Fragile setuid/root environment but no --chroot set");
374 const gchar *chroot_pid_dir;
376 gchar chroot_hashkey[CHROOT_PATH_HASHKEY_LENGTH+1],*s;
379 check_dir_safety(optarg_chroot);
380 if (!(grand=g_rand_new())) /* I hope g_rand_new() is security-safe. It looks so. */
381 fatal("Cannot initialize random number generator g_rand_new()");
382 for (s=chroot_hashkey;s<chroot_hashkey+CHROOT_PATH_HASHKEY_LENGTH;s++) {
383 gi=g_rand_int_range(grand,0,10+26+26);
384 /**/ if (gi>=0 && gi<10)
386 else if (gi>=10+0 && gi<10+26)
388 else if (gi>=10+26+0 && gi<10+26+26)
390 else g_assert_not_reached();
394 if (geteuid()==0) /* Not 'fragile' as we can be native 'root'. */
395 chrooted_cleanuplockeddirs(optarg_chroot,"s-");
396 chroot_pid_dir=captive_printf_alloca("%s/s-%d",optarg_chroot,(int)getpid());
397 chrooted_createdir(chroot_pid_dir,(!optarg_setuid ? (uid_t)-1 : want_uid),(!optarg_setgid ? (gid_t)-1 : want_gid),
399 chroot_pid_hashkey_dir=captive_printf_alloca("%s/%s",chroot_pid_dir,chroot_hashkey);
400 chrooted_createdir(chroot_pid_hashkey_dir,(!optarg_setuid ? (uid_t)-1 : want_uid),(!optarg_setgid ? (gid_t)-1 : want_gid),
402 if (chroot(chroot_pid_hashkey_dir))
403 fatal("Failed to chroot(\"%s\"): %m",chroot_pid_hashkey_dir);
405 fatal("Failed to chdir(\"%s\"): %m","/");
406 /* Now it is safe to set umask(0000) as we are protected by 'chroot_hashkey'.
407 * We need it to permit our spawning parent to hardlink its sockets to us.
410 if (umask(0000)!=0000)
411 fatal("Failed to set umask(0%o): %m",0000);
412 printf("chroot_pid_hashkey_dir=%s\n",chroot_pid_hashkey_dir);
415 if (fragile && !optarg_setgid)
416 fatal("Fragile setuid/root environment but no --setgid set");
418 if (!want_gid || setgid(want_gid))
419 fatal("Failed to setgid(%d)",(!want_gid ? -1 : (int)want_gid));
420 if (setgroups(1 /* size */,&want_gid))
421 fatal("Failed to setgroups(1,[%d])",(!want_gid ? -1 : (int)want_gid));
423 if (fragile && !optarg_setuid)
424 fatal("Fragile setuid/root environment but no --setuid set");
426 if (!want_uid || setuid(want_uid))
427 fatal("Failed to setuid(%d)",(!want_uid ? -1 : (int)want_uid));
430 /* Prepare /t for /t/o-$PID directories for ORBit2
431 * and also for parent's hardlink to its /t/o-$pid directory. */
433 gchar *chrooted_orbit_dir_old,*gs,*gs2;
435 if (mkdir("/t",S_ISVTX|0777)) {
437 fatal("Failed to mkdir(\"%s\"): %m","/t");
439 if (mkdir("/etc",0700))
440 fatal("Failed to mkdir(\"%s\"): %m","/etc");
441 if (want_uid_name && want_uid && want_gid) {
443 if (!(f=fopen("/etc/passwd","w")))
444 fatal("Failed to fopen(\"%s\",\"w\"): %m","/etc/passwd");
445 if (0>fprintf(f,"%s:*:%d:%d:%s:%s:/bin/false\n",want_uid_name,(int)want_uid,(int)want_gid,want_uid_name,optarg_chroot))
446 fatal("Failed to fprintf(\"%s\"): %m","/etc/passwd");
448 fatal("Failed to fclose(\"%s\"): %m","/etc/passwd");
450 g_assert(chroot_pid_hashkey_dir!=NULL);
451 chrooted_orbit_dir=g_strdup_printf("%s/t/o-%d",chroot_pid_hashkey_dir,getpid());
452 /* Missing mkdir(2) of the last component path is intentional: */
453 for (gs=chrooted_orbit_dir;(gs2=strchr(gs,'/'));gs=gs2) {
455 if (*chrooted_orbit_dir && mkdir(chrooted_orbit_dir,S_ISVTX|0777)) {
457 fatal("Failed to mkdir(\"%s\"): %m",chrooted_orbit_dir);
461 /* Prepare '/tmp' for the initial CORBA_ORB_init() default path: */
462 if (mkdir("/tmp",S_ISVTX|0777)) {
464 fatal("Failed to mkdir(\"%s\"): %m","/tmp");
466 /* Set '0700' to prevent: Wrong permissions for ...
467 * by linc-1.0.1-1/src/linc-protocols.c/make_local_tmpdir()
469 if (mkdir(chrooted_orbit_dir,0700)) {
470 /* Do not: g_assert(errno==EEXIST);
471 * as if 'optarg_chroot' the whole chroot(2)ed directory should be ours.
473 fatal("Cannot created chrooted_orbit_dir \"%s\": %m",chrooted_orbit_dir);
475 /* Init 'orb' to pass through its linc_set_tmpdir() to not to be overriden below. */
478 CORBA_Environment ev;
481 (gchar *)captive_strdup_alloca("captive-sandbox-server"),
484 CORBA_exception_init(&ev);
485 orb=CORBA_ORB_init(&orb_argc,orb_argv,"orbit-local-orb",&ev);
486 if (orb==CORBA_OBJECT_NIL)
487 fatal("Cannot initialize CORBA ORB (CORBA_OBJECT_NIL): %m");
488 if (ev._major!=CORBA_NO_EXCEPTION)
489 fatal("Cannot initialize CORBA ORB (exception): %m");
491 chrooted_orbit_dir_old=linc_get_tmpdir(); /* returns g_strdup()ed string */
492 g_assert(chrooted_orbit_dir_old!=NULL);
493 linc_set_tmpdir(chrooted_orbit_dir);
494 if (rmdir(chrooted_orbit_dir_old))
495 fatal("Cannot remove old chrooted_orbit_dir \"%s\": %m",chrooted_orbit_dir_old);
496 g_free(chrooted_orbit_dir_old);
497 /* chmod(2) it to prevent mode limitation by
498 * active ulimit(2) of being executed by mount(8).
500 /* Set '0777' as our parent does not have 'captive' user permissions. */
501 if (chmod(chrooted_orbit_dir,S_ISVTX|0777))
502 fatal("Cannot chmod 0%o chrooted_orbit_dir \"%s\": %m",S_ISVTX|0777,chrooted_orbit_dir);
503 printf("chrooted_orbit_dir=%s\n",chrooted_orbit_dir);
506 if (fragile || !optarg_no_rlimit) {
507 #define SANDBOX_SERVER_RLIMIT(what,how) sandbox_server_rlimit((what),G_STRINGIFY(what),(how))
508 SANDBOX_SERVER_RLIMIT(RLIMIT_NPROC,0);
509 SANDBOX_SERVER_RLIMIT(RLIMIT_MEMLOCK,0);
510 SANDBOX_SERVER_RLIMIT(RLIMIT_CORE,0);
511 SANDBOX_SERVER_RLIMIT(RLIMIT_FSIZE,0);
512 SANDBOX_SERVER_RLIMIT(RLIMIT_NOFILE,6); /* >=6 */
513 /* FIXME: Why flock(dirfd,...) in chrooted_createdir() succeeds?: */
514 SANDBOX_SERVER_RLIMIT(RLIMIT_LOCKS,0);
515 #undef SANDBOX_SERVER_RLIMIT
522 if (getuid()!=want_uid)
523 fatal("getuid()=%d != want_uid=%d",(int)getuid(),(int)want_uid);
524 if (geteuid()!=want_uid)
525 fatal("geteuid()=%d != want_uid=%d",(int)geteuid(),(int)want_uid);
526 if (getgid()!=want_gid)
527 fatal("getgid()=%d != want_gid=%d",(int)getgid(),(int)want_gid);
528 if (getegid()!=want_gid)
529 fatal("getegid()=%d != want_gid=%d",(int)getegid(),(int)want_gid);
530 gid_list_size=getgroups(G_N_ELEMENTS(gid_list),gid_list);
531 for (i=0;i<gid_list_size;i++) {
532 if (gid_list[i]!=want_gid)
533 fatal("getgroups() list member @%d %d != want_gid=%d",i,(int)gid_list[i],(int)want_gid);
539 int main(int argc,char **argv)
544 struct captive_options options;
547 g_log_set_always_fatal(~(0
554 fragile=(getuid()!=geteuid() || getuid()==0 || geteuid()==0);
556 #ifndef MAINTAINER_MODE
557 if (fragile && (argc!=1 || argv[1]))
558 fatal("Arguments invalid as running in fragile setuid/root environment");
562 #endif /* MAINTAINER_MODE */
564 /* Initialize the i18n stuff */
565 setlocale(LC_ALL,"");
566 bindtextdomain(PACKAGE,LOCALEDIR);
569 /* Initialize GObject subsystem of GLib. */
572 captive_options_init(&options);
573 captive_options=&options; /* for parsing by 'CAPTIVE_POPT_INCLUDE' */
575 context=poptGetContext(
577 argc,(/*en-const*/const char **)argv, /* argc,argv */
578 popt_table, /* options */
579 POPT_CONTEXT_POSIXMEHARDER); /* flags; && !POPT_CONTEXT_KEEP_FIRST */
581 g_assert_not_reached(); /* argument recognization args_error */
584 errint=poptReadDefaultConfig(context,
587 g_assert_not_reached(); /* argument recognization args_error */
590 errint=poptGetNextOpt(context);
592 g_assert_not_reached(); /* some non-callbacked argument reached */
595 cmd_arg=poptPeekArg(context);
597 g_assert_not_reached(); /* some non-option argument reached */
600 /* 'cmd_arg'-style args gets cleared by 'poptFreeContext(context);' below */
601 poptFreeContext(context);
603 #ifdef MAINTAINER_MODE
605 #endif /* MAINTAINER_MODE */
607 captive_options=NULL; /* already parsed by 'CAPTIVE_POPT_INCLUDE' */
609 captive_corba_sandbox_child(chrooted_orbit_dir);
611 g_assert_not_reached();