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 <orbit/orb-core/corba-defs.h>
45 #ifdef HAVE_ORBIT_LINK
46 char *link_get_tmpdir(void);
47 void link_set_tmpdir(const char *dir);
49 #include <linc/linc-protocol.h> /* for linc_set_tmpdir() */
53 /* Do not: #include "../../libcaptive/sandbox/split.h" * for captive_sandbox_fd_closeup(); FIXME *
54 * as it has libcaptive-dependent includes conditioned by ORBIT2.
55 * FIXME: Unify this declaration:
57 void captive_sandbox_fd_closeup(int fd_first_to_delete);
58 void captive_corba_sandbox_child(const gchar *chrooted_orbit_dir);
63 /* FIXME: We hit linc-1.0.1/src/linc-protocols.c/linc_protocol_get_sockaddr_unix()
64 * limit of socket pathname 64 characters.
65 * With CHROOT_PATH_HASHKEY_LENGTH 12 "linc-%x-%x-%x%x" still does not fit completely.
67 #define CHROOT_PATH_HASHKEY_LENGTH (12)
70 GQuark sandbox_server_main_error_quark(void)
75 r=g_quark_from_static_string("sandbox-server");
81 static gchar *optarg_setuid=CAPTIVE_SANDBOX_SETUID;
82 static gchar *optarg_setgid=CAPTIVE_SANDBOX_SETGID;
83 static gchar *optarg_chroot=CAPTIVE_SANDBOX_CHROOT;
84 static gint optarg_no_rlimit=0;
86 static const struct poptOption popt_table[]={
87 #define SANDBOX_SERVER_POPT(longname,argInfoP,argP,descripP,argDescripP) \
89 longName: (longname), \
91 argInfo: (argInfoP), \
94 descrip: (descripP), \
95 argDescrip: (argDescripP), \
98 SANDBOX_SERVER_POPT("setuid" ,POPT_ARG_STRING,&optarg_setuid,
99 N_("Username or UID to become; \"-\" for disable"),N_("UID")),
100 SANDBOX_SERVER_POPT("setgid" ,POPT_ARG_STRING,&optarg_setgid,
101 N_("Groupname or GID to become; \"-\" for disable"),N_("GID")),
102 SANDBOX_SERVER_POPT("chroot" ,POPT_ARG_STRING,&optarg_chroot,
103 N_("Pathname to directory for chroot(2); \"-\" for disable"),N_("directory")),
104 SANDBOX_SERVER_POPT("no-rlimit",POPT_ARG_NONE ,&optarg_no_rlimit,
105 N_("Disable setrlimit(2) restrictions"),NULL),
107 #undef SANDBOX_SERVER_POPT
113 static gchar *fatal_argv0;
115 static void fatal(const char *fmt,...)
119 fprintf(stderr,"%s: ",fatal_argv0);
121 vfprintf(stderr,fmt,ap);
123 fprintf(stderr,"!\nAborting!\n");
129 static void check_dir_safety(const gchar *dir)
136 fatal("Loop count >=%d during check_dir_safety(\"%s\")",depth,dir);
139 fatal("chroot path \"%s\" not absolute",dir);
140 dir=captive_printf_alloca("%s/",dir);
141 local_dir=(gchar *)captive_strdup_alloca(dir);
142 for (cs=dir;cs;cs=strchr(cs+1,'/')) {
146 /* Include the trailing '/' to resolve the root directory as "/". */
147 memcpy(local_dir,dir,cs+1-dir);
148 local_dir[cs+1-dir]=0;
149 if (lstat(local_dir,&statbuf))
150 fatal("lstat(\"%s\") of chroot path component: %m",local_dir);
151 if (S_ISLNK(statbuf.st_mode)) {
152 char linkbuf[PATH_MAX];
155 if (0>(linkbuflen=readlink(local_dir,linkbuf,sizeof(linkbuf)-1)))
156 fatal("readlink(\"%s\") of chroot path component: %m",local_dir);
157 linkbuf[linkbuflen]=0;
158 check_dir_safety(linkbuf);
159 if (stat(local_dir,&statbuf)) /* NOT lstat(2) */
160 fatal("stat(\"%s\") of chroot path component: %m",local_dir);
162 if (!S_ISDIR(statbuf.st_mode))
163 fatal("lstat/stat(\"%s\") of chroot path component is !S_ISDIR",local_dir);
164 if (statbuf.st_uid!=0)
165 fatal("lstat/stat(\"%s\") of chroot path component has UID %d !=0",local_dir,(int)statbuf.st_uid);
166 if (statbuf.st_gid!=0)
167 fatal("lstat/stat(\"%s\") of chroot path component has GID %d !=0",local_dir,(int)statbuf.st_gid);
168 if ((statbuf.st_mode&(S_IFDIR|S_ISVTX|0111)) != (S_IFDIR|0111))
169 fatal("lstat/stat(\"%s\") of chroot path component has mode 0%o !=04[01]111",local_dir,(int)statbuf.st_mode);
175 static void chrooted_unlink_recursive(const gchar *pathname)
178 struct dirent *dirent;
183 fatal("Loop count >=%d during chrooted_unlink_recursive(\"%s\")",depth,pathname);
185 /* Security: Do not allow anyone to escape the sandbox directory by symlinks. */
186 if (lstat(pathname,&statbuf))
187 fatal("Cannot lstat(\"%s\") to delete leftover sandbox files: %m",pathname);
188 if (!S_ISDIR(statbuf.st_mode)) {
189 if (unlink(pathname))
190 fatal("Cannot unlink(\"%s\") to delete leftover sandbox files: %m",pathname);
193 if (!(dir=opendir(pathname)))
194 fatal("Cannot opendir(\"%s\") to delete leftover sandbox files: %m",pathname);
195 while (errno=0,(dirent=readdir(dir))) {
198 if (!strcmp(dirent->d_name,".") || !strcmp(dirent->d_name,".."))
200 dirent_path=g_strdup_printf("%s/%s",pathname,dirent->d_name);
201 chrooted_unlink_recursive(dirent_path);
205 fatal("Cannot readdir(\"%s\") during delete of leftover sandbox files: %m",pathname);
207 fatal("Cannot closedir(\"%s\") during delete of leftover sandbox files: %m",pathname);
209 fatal("Cannot rmdir(\"%s\") during delete of leftover sandbox files: %m",pathname);
215 static void chrooted_cleanuplockeddirs(const gchar *pathname,const gchar *prefix)
218 struct dirent *dirent;
220 if (!(dir=opendir(pathname))) {
222 fatal("Cannot opendir(\"%s\") to delete leftover sandbox files: %m",pathname);
223 /* errno==ENOTDIR, a regular file */
224 if (unlink(pathname))
225 fatal("Cannot unlink(\"%s\") to delete leftover sandbox files: %m",pathname);
228 while (errno=0,(dirent=readdir(dir))) {
232 if (!strcmp(dirent->d_name,".") || !strcmp(dirent->d_name,".."))
234 if (strncmp(dirent->d_name,prefix,strlen(prefix)))
236 dirent_path=g_strdup_printf("%s/%s",pathname,dirent->d_name);
237 if (-1==(direntfd=open(dirent_path,O_RDONLY))) {
238 if (errno==ENOENT) /* It could disappear in the meantime. */
239 goto next_dirent_free_dirent_path;
240 fatal("Cannot open(\"%s\") as the child directory during delete of leftover sandbox files: %m",dirent_path);
242 if (flock(direntfd,LOCK_EX|LOCK_NB)) {
243 if (errno==EWOULDBLOCK) /* Valid directory in use. */
244 goto next_dirent_close_direntfd;
245 fatal("Cannot flock(\"%s\",LOCK_EX|LOCK_NB) child directory during delete of leftover sandbox files: %m",dirent_path);
247 chrooted_unlink_recursive(dirent_path);
248 next_dirent_close_direntfd:
250 fatal("Cannot close(\"%s\") child directory during delete of leftover sandbox files: %m",dirent_path);
251 next_dirent_free_dirent_path:
255 fatal("Cannot readdir(\"%s\") during delete of leftover sandbox files: %m",pathname);
257 fatal("Cannot closedir(\"%s\") during delete of leftover sandbox files: %m",pathname);
260 static void chrooted_createdir(const gchar *dir,uid_t uid,gid_t gid,gboolean lock)
264 for (retries=0;retries<10;retries++) {
268 if (mkdir(dir,0711)) {
270 fatal("Failed to create chroot directory \"%s\": %m",dir);
271 chrooted_unlink_recursive(dir);
273 fatal("Failed to create chroot directory \"%s\" after attempted unlink: %m",dir);
277 dirfd=open(dir,O_RDONLY);
280 fatal("Failed to open created chroot directory \"%s\" to lock it: %m",dir);
283 /* Do not use 'LOCK_NB' here as the garbage collector should release it soon. */
284 if (flock(dirfd,LOCK_EX))
285 fatal("Failed to lock created chroot directory \"%s\": %m",dir);
286 if (lstat(dir,&statbuf)) {
288 fatal("Failed to lstat(2) created chroot directory \"%s\": %m",dir);
290 fatal("Failed to close created and locked chroot directory \"%s\": %m",dir);
293 /* Leave 'dirfd' open to leave it LOCK_EX-ed. */
296 if (chown(dir,uid,gid))
297 fatal("Failed to chown(\"%s\",%d,%d): %m",dir,uid,gid);
298 if (chmod(dir,0711)) /* Just to be safe after chown(2); should be already done by mkdir(2). */
299 fatal("Failed to chmod(\"%s\",0%o): %m",dir,0711);
302 static void sandbox_server_rlimit(int resource,const gchar *resource_string,rlim_t rlim_max)
306 rlim.rlim_cur=rlim.rlim_max=rlim_max;
307 if (setrlimit(resource,&rlim))
308 fatal("setrlimit(%s,%d): %m",resource_string,(int)rlim_max);
309 if (getrlimit(resource,&rlim))
310 fatal("getrlimit(%s,%d): %m",resource_string,(int)rlim_max);
311 if (rlim.rlim_cur!=rlim_max || rlim.rlim_max!=rlim_max)
312 fatal("Unsuccessful setrlimit(%s)",resource_string);
315 static gchar *chrooted_orbit_dir;
317 static void chroot_setup(gboolean fragile)
320 const gchar *want_uid_name=NULL;
323 const gchar *chroot_pid_hashkey_dir=NULL;
326 captive_sandbox_fd_closeup(2 /* STDERR */ +1);
330 #define CLEANEMPTY(var) G_STMT_START { \
331 if ((var) && (!*(var) || *(var)=='-')) \
334 CLEANEMPTY(optarg_setgid);
335 CLEANEMPTY(optarg_setuid);
336 CLEANEMPTY(optarg_chroot);
342 want_gidl=strtol(optarg_setgid,&endptr,10);
343 if (!endptr || !*endptr) {
345 if (want_gidl<=0 || want_gid!=(gid_t)want_gidl)
346 fatal("Numeric setgid not parsable: %s",optarg_setgid);
349 struct group *want_gid_group=NULL;
350 if (!(want_gid_group=getgrnam(optarg_setgid)))
351 fatal("Unable to query setgid group name \"%s\"",optarg_setgid);
352 want_gid=want_gid_group->gr_gid;
358 struct passwd *want_uid_passwd;
359 want_uidl=strtol(optarg_setuid,&endptr,10);
360 if (!endptr || !*endptr) {
362 if (want_uidl<=0 || want_uid!=(gid_t)want_uidl)
363 fatal("Numeric setuid not parsable: %s",optarg_setuid);
366 if (!(want_uid_passwd=getpwnam(optarg_setuid)))
367 fatal("Unable to query setuid user name \"%s\"",optarg_setuid);
368 want_uid=want_uid_passwd->pw_uid;
371 fatal("Unable to detect setuid UID");
372 if (!(want_uid_passwd=getpwuid(want_uid)))
373 fatal("Unable to query name of UID %d",(int)want_uid);
374 want_uid_name=captive_strdup_alloca(want_uid_passwd->pw_name);
377 /* Prevent: GLib-WARNING **: getpwuid_r(): failed due to unknown user id (42)
378 * Try to invoke GLib g_get_any_init() before possible chroot(2) below.
385 if (fragile && !optarg_chroot)
386 fatal("Fragile setuid/root environment but no --chroot set");
388 const gchar *chroot_pid_dir;
390 gchar chroot_hashkey[CHROOT_PATH_HASHKEY_LENGTH+1],*s;
393 check_dir_safety(optarg_chroot);
394 if (!(grand=g_rand_new())) /* I hope g_rand_new() is security-safe. It looks so. */
395 fatal("Cannot initialize random number generator g_rand_new()");
396 for (s=chroot_hashkey;s<chroot_hashkey+CHROOT_PATH_HASHKEY_LENGTH;s++) {
397 gi=g_rand_int_range(grand,0,10+26+26);
398 /**/ if (gi>=0 && gi<10)
400 else if (gi>=10+0 && gi<10+26)
402 else if (gi>=10+26+0 && gi<10+26+26)
404 else g_assert_not_reached();
408 if (geteuid()==0) /* Not 'fragile' as we can be native 'root'. */
409 chrooted_cleanuplockeddirs(optarg_chroot,"s-");
410 chroot_pid_dir=captive_printf_alloca("%s/s-%d",optarg_chroot,(int)getpid());
411 chrooted_createdir(chroot_pid_dir,(!optarg_setuid ? (uid_t)-1 : want_uid),(!optarg_setgid ? (gid_t)-1 : want_gid),
413 chroot_pid_hashkey_dir=captive_printf_alloca("%s/%s",chroot_pid_dir,chroot_hashkey);
414 chrooted_createdir(chroot_pid_hashkey_dir,(!optarg_setuid ? (uid_t)-1 : want_uid),(!optarg_setgid ? (gid_t)-1 : want_gid),
416 if (chroot(chroot_pid_hashkey_dir))
417 fatal("Failed to chroot(\"%s\"): %m",chroot_pid_hashkey_dir);
419 fatal("Failed to chdir(\"%s\"): %m","/");
420 /* Now it is safe to set umask(0000) as we are protected by 'chroot_hashkey'.
421 * We need it to permit our spawning parent to hardlink its sockets to us.
424 if (umask(0000)!=0000)
425 fatal("Failed to set umask(0%o): %m",0000);
426 printf("chroot_pid_hashkey_dir=%s\n",chroot_pid_hashkey_dir);
429 if (fragile && !optarg_setgid)
430 fatal("Fragile setuid/root environment but no --setgid set");
432 if (!want_gid || setgid(want_gid))
433 fatal("Failed to setgid(%d)",(!want_gid ? -1 : (int)want_gid));
434 if (setgroups(1 /* size */,&want_gid))
435 fatal("Failed to setgroups(1,[%d])",(!want_gid ? -1 : (int)want_gid));
437 if (fragile && !optarg_setuid)
438 fatal("Fragile setuid/root environment but no --setuid set");
440 if (!want_uid || setuid(want_uid))
441 fatal("Failed to setuid(%d)",(!want_uid ? -1 : (int)want_uid));
444 /* Prepare /t for /t/o-$PID directories for ORBit2
445 * and also for parent's hardlink to its /t/o-$pid directory. */
447 gchar *chrooted_orbit_dir_old,*gs,*gs2;
449 if (mkdir("/t",S_ISVTX|0777)) {
451 fatal("Failed to mkdir(\"%s\"): %m","/t");
453 if (mkdir("/etc",0700))
454 fatal("Failed to mkdir(\"%s\"): %m","/etc");
455 if (want_uid_name && want_uid && want_gid) {
457 if (!(f=fopen("/etc/passwd","w")))
458 fatal("Failed to fopen(\"%s\",\"w\"): %m","/etc/passwd");
459 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))
460 fatal("Failed to fprintf(\"%s\"): %m","/etc/passwd");
462 fatal("Failed to fclose(\"%s\"): %m","/etc/passwd");
464 g_assert(chroot_pid_hashkey_dir!=NULL);
465 chrooted_orbit_dir=g_strdup_printf("%s/t/o-%d",chroot_pid_hashkey_dir,getpid());
466 /* Missing mkdir(2) of the last component path is intentional: */
467 for (gs=chrooted_orbit_dir;(gs2=strchr(gs,'/'));gs=gs2) {
469 if (*chrooted_orbit_dir && mkdir(chrooted_orbit_dir,S_ISVTX|0777)) {
471 fatal("Failed to mkdir(\"%s\"): %m",chrooted_orbit_dir);
475 /* Prepare '/tmp' for the initial CORBA_ORB_init() default path: */
476 if (mkdir("/tmp",S_ISVTX|0777)) {
478 fatal("Failed to mkdir(\"%s\"): %m","/tmp");
480 /* Set '0700' to prevent: Wrong permissions for ...
481 * by linc-1.0.1-1/src/linc-protocols.c/make_local_tmpdir()
483 if (mkdir(chrooted_orbit_dir,0700)) {
484 /* Do not: g_assert(errno==EEXIST);
485 * as if 'optarg_chroot' the whole chroot(2)ed directory should be ours.
487 fatal("Cannot created chrooted_orbit_dir \"%s\": %m",chrooted_orbit_dir);
489 /* Init 'orb' to pass through its linc_set_tmpdir() to not to be overriden below. */
492 CORBA_Environment ev;
495 (gchar *)captive_strdup_alloca("captive-sandbox-server"),
498 CORBA_exception_init(&ev);
499 orb=CORBA_ORB_init(&orb_argc,orb_argv,"orbit-local-orb",&ev);
500 if (orb==CORBA_OBJECT_NIL)
501 fatal("Cannot initialize CORBA ORB (CORBA_OBJECT_NIL): %m");
502 if (ev._major!=CORBA_NO_EXCEPTION)
503 fatal("Cannot initialize CORBA ORB (exception): %m");
505 #ifdef HAVE_ORBIT_LINK
506 chrooted_orbit_dir_old=link_get_tmpdir(); /* returns g_strdup()ed string */
508 chrooted_orbit_dir_old=linc_get_tmpdir(); /* returns g_strdup()ed string */
510 g_assert(chrooted_orbit_dir_old!=NULL);
511 #ifdef HAVE_ORBIT_LINK
512 link_set_tmpdir(chrooted_orbit_dir);
514 linc_set_tmpdir(chrooted_orbit_dir);
516 if (!*chrooted_orbit_dir_old)
517 fatal("Cannot detect chrooted_orbit_dir: --with-orbit-line incompatible with ORBit2 version");
518 if (rmdir(chrooted_orbit_dir_old))
519 fatal("Cannot remove old chrooted_orbit_dir \"%s\": %m",chrooted_orbit_dir_old);
520 g_free(chrooted_orbit_dir_old);
521 /* chmod(2) it to prevent mode limitation by
522 * active ulimit(2) of being executed by mount(8).
524 /* Set '0777' as our parent does not have 'captive' user permissions. */
525 if (chmod(chrooted_orbit_dir,S_ISVTX|0777))
526 fatal("Cannot chmod 0%o chrooted_orbit_dir \"%s\": %m",S_ISVTX|0777,chrooted_orbit_dir);
527 printf("chrooted_orbit_dir=%s\n",chrooted_orbit_dir);
530 if (fragile || !optarg_no_rlimit) {
531 #define SANDBOX_SERVER_RLIMIT(what,how) sandbox_server_rlimit((what),G_STRINGIFY(what),(how))
532 SANDBOX_SERVER_RLIMIT(RLIMIT_NPROC,0);
533 SANDBOX_SERVER_RLIMIT(RLIMIT_MEMLOCK,0);
534 SANDBOX_SERVER_RLIMIT(RLIMIT_CORE,0);
535 SANDBOX_SERVER_RLIMIT(RLIMIT_FSIZE,0);
536 SANDBOX_SERVER_RLIMIT(RLIMIT_NOFILE,16); /* >=6; newer ORBit2/link require >6 */
537 /* FIXME: Why flock(dirfd,...) in chrooted_createdir() succeeds?: */
538 SANDBOX_SERVER_RLIMIT(RLIMIT_LOCKS,0);
539 #undef SANDBOX_SERVER_RLIMIT
546 if (getuid()!=want_uid)
547 fatal("getuid()=%d != want_uid=%d",(int)getuid(),(int)want_uid);
548 if (geteuid()!=want_uid)
549 fatal("geteuid()=%d != want_uid=%d",(int)geteuid(),(int)want_uid);
550 if (getgid()!=want_gid)
551 fatal("getgid()=%d != want_gid=%d",(int)getgid(),(int)want_gid);
552 if (getegid()!=want_gid)
553 fatal("getegid()=%d != want_gid=%d",(int)getegid(),(int)want_gid);
554 gid_list_size=getgroups(G_N_ELEMENTS(gid_list),gid_list);
555 for (i=0;i<gid_list_size;i++) {
556 if (gid_list[i]!=want_gid)
557 fatal("getgroups() list member @%d %d != want_gid=%d",i,(int)gid_list[i],(int)want_gid);
563 int main(int argc,char **argv)
568 struct captive_options options;
571 g_log_set_always_fatal(~(0
578 fragile=(getuid()!=geteuid() || getuid()==0 || geteuid()==0);
580 #ifndef MAINTAINER_MODE
581 if (fragile && (argc!=1 || argv[1]))
582 fatal("Arguments invalid as running in fragile setuid/root environment");
586 #endif /* MAINTAINER_MODE */
588 /* Initialize the i18n stuff */
589 setlocale(LC_ALL,"");
590 bindtextdomain(PACKAGE,LOCALEDIR);
593 /* Initialize GObject subsystem of GLib. */
596 captive_options_init(&options);
597 captive_options=&options; /* for parsing by 'CAPTIVE_POPT_INCLUDE' */
599 context=poptGetContext(
601 argc,(/*en-const*/const char **)argv, /* argc,argv */
602 popt_table, /* options */
603 POPT_CONTEXT_POSIXMEHARDER); /* flags; && !POPT_CONTEXT_KEEP_FIRST */
605 g_assert_not_reached(); /* argument recognization args_error */
608 errint=poptReadDefaultConfig(context,
611 g_assert_not_reached(); /* argument recognization args_error */
614 errint=poptGetNextOpt(context);
616 g_assert_not_reached(); /* some non-callbacked argument reached */
619 cmd_arg=poptPeekArg(context);
621 g_assert_not_reached(); /* some non-option argument reached */
624 /* 'cmd_arg'-style args gets cleared by 'poptFreeContext(context);' below */
625 poptFreeContext(context);
627 #ifdef MAINTAINER_MODE
629 #endif /* MAINTAINER_MODE */
631 captive_options=NULL; /* already parsed by 'CAPTIVE_POPT_INCLUDE' */
633 captive_corba_sandbox_child(chrooted_orbit_dir);
635 g_assert_not_reached();