1 /*
2 * Authors: Dan Walsh <dwalsh@redhat.com>
3 * Authors: Thomas Liu <tliu@fedoraproject.org>
4 */
5
6 #define _GNU_SOURCE
7 #include <signal.h>
8 #include <sys/fsuid.h>
9 #include <sys/stat.h>
10 #include <sys/types.h>
11 #include <sys/wait.h>
12 #include <syslog.h>
13 #include <sys/mount.h>
14 #include <glob.h>
15 #include <pwd.h>
16 #include <sched.h>
17 #include <string.h>
18 #include <stdio.h>
19 #include <regex.h>
20 #include <unistd.h>
21 #include <stdlib.h>
22 #include <cap-ng.h>
23 #include <getopt.h> /* for getopt_long() form of getopt() */
24 #include <limits.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <fcntl.h>
28
29 #include <selinux/selinux.h>
30 #include <selinux/context.h> /* for context-mangling functions */
31 #include <dirent.h>
32
33 #ifdef USE_NLS
34 #include <locale.h> /* for setlocale() */
35 #include <libintl.h> /* for gettext() */
36 #define _(msgid) gettext (msgid)
37 #else
38 #define _(msgid) (msgid)
39 #endif
40
41 #ifndef MS_REC
42 #define MS_REC 1<<14
43 #endif
44
45 #ifndef MS_SLAVE
46 #define MS_SLAVE 1<<19
47 #endif
48
49 #ifndef PACKAGE
50 #define PACKAGE "policycoreutils" /* the name of this package lang translation */
51 #endif
52
53 #define BUF_SIZE 1024
54 #define DEFAULT_PATH "/usr/bin:/bin"
55 #define USAGE_STRING _("USAGE: seunshare [ -v ] [ -C ] [ -k ] [ -t tmpdir ] [ -h homedir ] [ -r runuserdir ] [ -Z CONTEXT ] -- executable [args] ")
56
57 static int verbose = 0;
58 static int child = 0;
59
60 static capng_select_t cap_set = CAPNG_SELECT_CAPS;
61
62 /**
63 * This function will drop all capabilities.
64 */
drop_caps(void)65 static int drop_caps(void)
66 {
67 if (capng_have_capabilities(cap_set) == CAPNG_NONE)
68 return 0;
69 capng_clear(cap_set);
70 if (capng_lock() == -1 || capng_apply(cap_set) == -1) {
71 fprintf(stderr, _("Failed to drop all capabilities\n"));
72 return -1;
73 }
74 return 0;
75 }
76
77 /**
78 * This function will drop all privileges.
79 */
drop_privs(uid_t uid)80 static int drop_privs(uid_t uid)
81 {
82 if (drop_caps() == -1 || setresuid(uid, uid, uid) == -1) {
83 fprintf(stderr, _("Failed to drop privileges\n"));
84 return -1;
85 }
86 return 0;
87 }
88
89 /**
90 * If the user sends a siginto to seunshare, kill the child's session
91 */
handler(int sig)92 static void handler(int sig) {
93 if (child > 0) kill(-child,sig);
94 }
95
96 /**
97 * Take care of any signal setup.
98 */
set_signal_handles(void)99 static int set_signal_handles(void)
100 {
101 sigset_t empty;
102
103 /* Empty the signal mask in case someone is blocking a signal */
104 if (sigemptyset(&empty)) {
105 fprintf(stderr, "Unable to obtain empty signal set\n");
106 return -1;
107 }
108
109 (void)sigprocmask(SIG_SETMASK, &empty, NULL);
110
111 /* Terminate on SIGHUP */
112 if (signal(SIGHUP, SIG_DFL) == SIG_ERR) {
113 perror("Unable to set SIGHUP handler");
114 return -1;
115 }
116
117 if (signal(SIGINT, handler) == SIG_ERR) {
118 perror("Unable to set SIGINT handler");
119 return -1;
120 }
121
122 return 0;
123 }
124
125 #define status_to_retval(status,retval) do { \
126 if ((status) == -1) \
127 retval = -1; \
128 else if (WIFEXITED((status))) \
129 retval = WEXITSTATUS((status)); \
130 else if (WIFSIGNALED((status))) \
131 retval = 128 + WTERMSIG((status)); \
132 else \
133 retval = -1; \
134 } while(0)
135
136 /**
137 * Spawn external command using system() with dropped privileges.
138 * TODO: avoid system() and use exec*() instead
139 */
spawn_command(const char * cmd,uid_t uid)140 static int spawn_command(const char *cmd, uid_t uid){
141 int childpid;
142 int status = -1;
143
144 if (verbose > 1)
145 printf("spawn_command: %s\n", cmd);
146
147 childpid = fork();
148 if (childpid == -1) {
149 perror(_("Unable to fork"));
150 return status;
151 }
152
153 if (childpid == 0) {
154 if (drop_privs(uid) != 0) exit(-1);
155
156 status = system(cmd);
157 status_to_retval(status, status);
158 exit(status);
159 }
160
161 waitpid(childpid, &status, 0);
162 status_to_retval(status, status);
163 return status;
164 }
165
166 /**
167 * Check file/directory ownership, struct stat * must be passed to the
168 * functions.
169 */
check_owner_uid(uid_t uid,const char * file,struct stat * st)170 static int check_owner_uid(uid_t uid, const char *file, struct stat *st) {
171 if (S_ISLNK(st->st_mode)) {
172 fprintf(stderr, _("Error: %s must not be a symbolic link\n"), file);
173 return -1;
174 }
175 if (st->st_uid != uid) {
176 fprintf(stderr, _("Error: %s not owned by UID %d\n"), file, uid);
177 return -1;
178 }
179 return 0;
180 }
181
check_owner_gid(gid_t gid,const char * file,struct stat * st)182 static int check_owner_gid(gid_t gid, const char *file, struct stat *st) {
183 if (S_ISLNK(st->st_mode)) {
184 fprintf(stderr, _("Error: %s must not be a symbolic link\n"), file);
185 return -1;
186 }
187 if (st->st_gid != gid) {
188 fprintf(stderr, _("Error: %s not owned by GID %d\n"), file, gid);
189 return -1;
190 }
191 return 0;
192 }
193
194 #define equal_stats(one,two) \
195 ((one)->st_dev == (two)->st_dev && (one)->st_ino == (two)->st_ino && \
196 (one)->st_uid == (two)->st_uid && (one)->st_gid == (two)->st_gid && \
197 (one)->st_mode == (two)->st_mode)
198
199 /**
200 * Sanity check specified directory. Store stat info for future comparison, or
201 * compare with previously saved info to detect replaced directories.
202 * Note: This function does not perform owner checks.
203 */
verify_directory(const char * dir,struct stat * st_in,struct stat * st_out)204 static int verify_directory(const char *dir, struct stat *st_in, struct stat *st_out) {
205 struct stat sb;
206
207 if (st_out == NULL) st_out = &sb;
208
209 if (lstat(dir, st_out) == -1) {
210 fprintf(stderr, _("Failed to stat %s: %s\n"), dir, strerror(errno));
211 return -1;
212 }
213 if (! S_ISDIR(st_out->st_mode)) {
214 fprintf(stderr, _("Error: %s is not a directory: %s\n"), dir, strerror(errno));
215 return -1;
216 }
217 if (st_in && !equal_stats(st_in, st_out)) {
218 fprintf(stderr, _("Error: %s was replaced by a different directory\n"), dir);
219 return -1;
220 }
221
222 return 0;
223 }
224
225 /**
226 * This function checks to see if the shell is known in /etc/shells.
227 * If so, it returns 0. On error or illegal shell, it returns -1.
228 */
verify_shell(const char * shell_name)229 static int verify_shell(const char *shell_name)
230 {
231 int rc = -1;
232 const char *buf;
233
234 if (!(shell_name && shell_name[0]))
235 return rc;
236
237 while ((buf = getusershell()) != NULL) {
238 /* ignore comments */
239 if (*buf == '#')
240 continue;
241
242 /* check the shell skipping newline char */
243 if (!strcmp(shell_name, buf)) {
244 rc = 0;
245 break;
246 }
247 }
248 endusershell();
249 return rc;
250 }
251
252 /**
253 * Mount directory and check that we mounted the right directory.
254 */
seunshare_mount(const char * src,const char * dst,struct stat * src_st)255 static int seunshare_mount(const char *src, const char *dst, struct stat *src_st)
256 {
257 int flags = 0;
258 int is_tmp = 0;
259
260 if (verbose)
261 printf(_("Mounting %s on %s\n"), src, dst);
262
263 if (strcmp("/tmp", dst) == 0) {
264 flags = flags | MS_NODEV | MS_NOSUID | MS_NOEXEC;
265 is_tmp = 1;
266 }
267
268 /* mount directory */
269 if (mount(src, dst, NULL, MS_BIND | flags, NULL) < 0) {
270 fprintf(stderr, _("Failed to mount %s on %s: %s\n"), src, dst, strerror(errno));
271 return -1;
272 }
273
274 /* verify whether we mounted what we expected to mount */
275 if (verify_directory(dst, src_st, NULL) < 0) return -1;
276
277 /* bind mount /tmp on /var/tmp too */
278 if (is_tmp) {
279 if (verbose)
280 printf(_("Mounting /tmp on /var/tmp\n"));
281
282 if (mount("/tmp", "/var/tmp", NULL, MS_BIND | flags, NULL) < 0) {
283 fprintf(stderr, _("Failed to mount /tmp on /var/tmp: %s\n"), strerror(errno));
284 return -1;
285 }
286 }
287
288 return 0;
289
290 }
291
292 /*
293 If path is empty or ends with "/." or "/.. return -1 else return 0;
294 */
bad_path(const char * path)295 static int bad_path(const char *path) {
296 const char *ptr;
297 ptr = path;
298 while (*ptr) ptr++;
299 if (ptr == path) return -1; // ptr null
300 ptr--;
301 if (ptr != path && *ptr == '.') {
302 ptr--;
303 if (*ptr == '/') return -1; // path ends in /.
304 if (*ptr == '.') {
305 if (ptr != path) {
306 ptr--;
307 if (*ptr == '/') return -1; // path ends in /..
308 }
309 }
310 }
311 return 0;
312 }
313
rsynccmd(const char * src,const char * dst,char ** cmdbuf)314 static int rsynccmd(const char * src, const char *dst, char **cmdbuf)
315 {
316 char *buf = NULL;
317 char *newbuf = NULL;
318 glob_t fglob;
319 fglob.gl_offs = 0;
320 int flags = GLOB_PERIOD;
321 unsigned int i = 0;
322 int rc = -1;
323
324 /* match glob for all files in src dir */
325 if (asprintf(&buf, "%s/*", src) == -1) {
326 fprintf(stderr, "Out of memory\n");
327 return -1;
328 }
329
330 if (glob(buf, flags, NULL, &fglob) != 0) {
331 free(buf); buf = NULL;
332 return -1;
333 }
334
335 free(buf); buf = NULL;
336
337 for ( i=0; i < fglob.gl_pathc; i++) {
338 const char *path = fglob.gl_pathv[i];
339
340 if (bad_path(path)) continue;
341
342 if (!buf) {
343 if (asprintf(&newbuf, "\'%s\'", path) == -1) {
344 fprintf(stderr, "Out of memory\n");
345 goto err;
346 }
347 } else {
348 if (asprintf(&newbuf, "%s \'%s\'", buf, path) == -1) {
349 fprintf(stderr, "Out of memory\n");
350 goto err;
351 }
352 }
353
354 free(buf); buf = newbuf;
355 newbuf = NULL;
356 }
357
358 if (buf) {
359 if (asprintf(&newbuf, "/usr/bin/rsync -trlHDq %s '%s'", buf, dst) == -1) {
360 fprintf(stderr, "Out of memory\n");
361 goto err;
362 }
363 *cmdbuf=newbuf;
364 }
365 else {
366 *cmdbuf=NULL;
367 }
368 rc = 0;
369
370 err:
371 free(buf); buf = NULL;
372 globfree(&fglob);
373 return rc;
374 }
375
376 /**
377 * Clean up runtime temporary directory. Returns 0 if no problem was detected,
378 * >0 if some error was detected, but errors here are treated as non-fatal and
379 * left to tmpwatch to finish incomplete cleanup.
380 */
cleanup_tmpdir(const char * tmpdir,const char * src,struct passwd * pwd,int copy_content)381 static int cleanup_tmpdir(const char *tmpdir, const char *src,
382 struct passwd *pwd, int copy_content)
383 {
384 char *cmdbuf = NULL;
385 int rc = 0;
386
387 /* rsync files back */
388 if (copy_content) {
389 if (asprintf(&cmdbuf, "/usr/bin/rsync --exclude=.X11-unix -utrlHDq --delete '%s/' '%s/'", tmpdir, src) == -1) {
390 fprintf(stderr, _("Out of memory\n"));
391 cmdbuf = NULL;
392 rc++;
393 }
394 if (cmdbuf && spawn_command(cmdbuf, pwd->pw_uid) != 0) {
395 fprintf(stderr, _("Failed to copy files from the runtime temporary directory\n"));
396 rc++;
397 }
398 free(cmdbuf); cmdbuf = NULL;
399 }
400
401 /* remove files from the runtime temporary directory */
402 if (asprintf(&cmdbuf, "/bin/rm -r '%s/' 2>/dev/null", tmpdir) == -1) {
403 fprintf(stderr, _("Out of memory\n"));
404 cmdbuf = NULL;
405 rc++;
406 }
407 /* this may fail if there's root-owned file left in the runtime tmpdir */
408 if (cmdbuf && spawn_command(cmdbuf, pwd->pw_uid) != 0) rc++;
409 free(cmdbuf); cmdbuf = NULL;
410
411 /* remove runtime temporary directory */
412 if ((uid_t)setfsuid(0) != 0) {
413 /* setfsuid does not return error, but this check makes code checkers happy */
414 rc++;
415 }
416
417 if (pwd->pw_uid != 0 && rmdir(tmpdir) == -1)
418 fprintf(stderr, _("Failed to remove directory %s: %s\n"), tmpdir, strerror(errno));
419 if ((uid_t)setfsuid(pwd->pw_uid) != 0) {
420 fprintf(stderr, _("unable to switch back to user after clearing tmp dir\n"));
421 rc++;
422 }
423
424 return rc;
425 }
426
427 /**
428 * seunshare will create a tmpdir in /tmp, with root ownership. The parent
429 * process waits for it child to exit to attempt to remove the directory. If
430 * it fails to remove the directory, we will need to rely on tmpreaper/tmpwatch
431 * to clean it up.
432 */
create_tmpdir(const char * src,struct stat * src_st,struct stat * out_st,struct passwd * pwd,const char * execcon)433 static char *create_tmpdir(const char *src, struct stat *src_st,
434 struct stat *out_st, struct passwd *pwd, const char *execcon)
435 {
436 char *tmpdir = NULL;
437 char *cmdbuf = NULL;
438 int fd_t = -1, fd_s = -1;
439 struct stat tmp_st;
440 char *con = NULL;
441
442 /* get selinux context */
443 if (execcon) {
444 if ((uid_t)setfsuid(pwd->pw_uid) != 0)
445 goto err;
446
447 if ((fd_s = open(src, O_RDONLY)) < 0) {
448 fprintf(stderr, _("Failed to open directory %s: %s\n"), src, strerror(errno));
449 goto err;
450 }
451 if (fstat(fd_s, &tmp_st) == -1) {
452 fprintf(stderr, _("Failed to stat directory %s: %s\n"), src, strerror(errno));
453 goto err;
454 }
455 if (!equal_stats(src_st, &tmp_st)) {
456 fprintf(stderr, _("Error: %s was replaced by a different directory\n"), src);
457 goto err;
458 }
459 if (fgetfilecon(fd_s, &con) == -1) {
460 fprintf(stderr, _("Failed to get context of the directory %s: %s\n"), src, strerror(errno));
461 goto err;
462 }
463
464 /* ok to not reach this if there is an error */
465 if ((uid_t)setfsuid(0) != pwd->pw_uid)
466 goto err;
467 }
468
469 if (asprintf(&tmpdir, "/tmp/.sandbox-%s-XXXXXX", pwd->pw_name) == -1) {
470 fprintf(stderr, _("Out of memory\n"));
471 tmpdir = NULL;
472 goto err;
473 }
474 if (mkdtemp(tmpdir) == NULL) {
475 fprintf(stderr, _("Failed to create temporary directory: %s\n"), strerror(errno));
476 goto err;
477 }
478
479 /* temporary directory must be owned by root:user */
480 if (verify_directory(tmpdir, NULL, out_st) < 0) {
481 goto err;
482 }
483
484 if (check_owner_uid(0, tmpdir, out_st) < 0)
485 goto err;
486
487 if (check_owner_gid(getgid(), tmpdir, out_st) < 0)
488 goto err;
489
490 /* change permissions of the temporary directory */
491 if ((fd_t = open(tmpdir, O_RDONLY)) < 0) {
492 fprintf(stderr, _("Failed to open directory %s: %s\n"), tmpdir, strerror(errno));
493 goto err;
494 }
495 if (fstat(fd_t, &tmp_st) == -1) {
496 fprintf(stderr, _("Failed to stat directory %s: %s\n"), tmpdir, strerror(errno));
497 goto err;
498 }
499 if (!equal_stats(out_st, &tmp_st)) {
500 fprintf(stderr, _("Error: %s was replaced by a different directory\n"), tmpdir);
501 goto err;
502 }
503 if (fchmod(fd_t, 01770) == -1) {
504 fprintf(stderr, _("Unable to change mode on %s: %s\n"), tmpdir, strerror(errno));
505 goto err;
506 }
507 /* re-stat again to pick change mode */
508 if (fstat(fd_t, out_st) == -1) {
509 fprintf(stderr, _("Failed to stat directory %s: %s\n"), tmpdir, strerror(errno));
510 goto err;
511 }
512
513 /* copy selinux context */
514 if (execcon) {
515 if (fsetfilecon(fd_t, con) == -1) {
516 fprintf(stderr, _("Failed to set context of the directory %s: %s\n"), tmpdir, strerror(errno));
517 goto err;
518 }
519 }
520
521 if ((uid_t)setfsuid(pwd->pw_uid) != 0)
522 goto err;
523
524 if (rsynccmd(src, tmpdir, &cmdbuf) < 0) {
525 goto err;
526 }
527
528 /* ok to not reach this if there is an error */
529 if ((uid_t)setfsuid(0) != pwd->pw_uid)
530 goto err;
531
532 if (cmdbuf && spawn_command(cmdbuf, pwd->pw_uid) != 0) {
533 fprintf(stderr, _("Failed to populate runtime temporary directory\n"));
534 cleanup_tmpdir(tmpdir, src, pwd, 0);
535 goto err;
536 }
537
538 goto good;
539 err:
540 free(tmpdir); tmpdir = NULL;
541 good:
542 free(cmdbuf); cmdbuf = NULL;
543 freecon(con); con = NULL;
544 if (fd_t >= 0) close(fd_t);
545 if (fd_s >= 0) close(fd_s);
546 return tmpdir;
547 }
548
549 #define PROC_BASE "/proc"
550
551 static int
killall(const char * execcon)552 killall (const char *execcon)
553 {
554 DIR *dir;
555 char *scon;
556 struct dirent *de;
557 pid_t *pid_table, pid, self;
558 int i;
559 int pids, max_pids;
560 int running = 0;
561 self = getpid();
562 if (!(dir = opendir(PROC_BASE))) {
563 return -1;
564 }
565 max_pids = 256;
566 pid_table = malloc(max_pids * sizeof (pid_t));
567 if (!pid_table) {
568 (void)closedir(dir);
569 return -1;
570 }
571 pids = 0;
572 context_t con;
573 con = context_new(execcon);
574 const char *mcs = context_range_get(con);
575 printf("mcs=%s\n", mcs);
576 while ((de = readdir (dir)) != NULL) {
577 if (!(pid = (pid_t)atoi(de->d_name)) || pid == self)
578 continue;
579
580 if (pids == max_pids) {
581 pid_t *new_pid_table = realloc(pid_table, 2*pids*sizeof(pid_t));
582 if (!new_pid_table) {
583 free(pid_table);
584 (void)closedir(dir);
585 return -1;
586 }
587 pid_table = new_pid_table;
588 max_pids *= 2;
589 }
590 pid_table[pids++] = pid;
591 }
592
593 (void)closedir(dir);
594
595 for (i = 0; i < pids; i++) {
596 pid_t id = pid_table[i];
597
598 if (getpidcon(id, &scon) == 0) {
599
600 context_t pidcon = context_new(scon);
601 /* Attempt to kill remaining processes */
602 if (strcmp(context_range_get(pidcon), mcs) == 0)
603 kill(id, SIGKILL);
604
605 context_free(pidcon);
606 freecon(scon);
607 }
608 running++;
609 }
610
611 context_free(con);
612 free(pid_table);
613 return running;
614 }
615
main(int argc,char ** argv)616 int main(int argc, char **argv) {
617 int status = -1;
618 const char *execcon = NULL;
619
620 int clflag; /* holds codes for command line flags */
621 int kill_all = 0;
622
623 char *homedir_s = NULL; /* homedir spec'd by user in argv[] */
624 char *tmpdir_s = NULL; /* tmpdir spec'd by user in argv[] */
625 char *tmpdir_r = NULL; /* tmpdir created by seunshare */
626 char *runuserdir_s = NULL; /* /var/run/user/UID spec'd by user in argv[] */
627 char *runuserdir_r = NULL; /* /var/run/user/UID created by seunshare */
628
629 struct stat st_curhomedir;
630 struct stat st_homedir;
631 struct stat st_tmpdir_s;
632 struct stat st_tmpdir_r;
633 struct stat st_runuserdir_s;
634 struct stat st_runuserdir_r;
635
636 const struct option long_options[] = {
637 {"homedir", 1, 0, 'h'},
638 {"tmpdir", 1, 0, 't'},
639 {"runuserdir", 1, 0, 'r'},
640 {"kill", 1, 0, 'k'},
641 {"verbose", 1, 0, 'v'},
642 {"context", 1, 0, 'Z'},
643 {"capabilities", 1, 0, 'C'},
644 {NULL, 0, 0, 0}
645 };
646
647 uid_t uid = getuid();
648 /*
649 if (!uid) {
650 fprintf(stderr, _("Must not be root"));
651 return -1;
652 }
653 */
654
655 #ifdef USE_NLS
656 setlocale(LC_ALL, "");
657 bindtextdomain(PACKAGE, LOCALEDIR);
658 textdomain(PACKAGE);
659 #endif
660
661 struct passwd *pwd=getpwuid(uid);
662 if (!pwd) {
663 perror(_("getpwduid failed"));
664 return -1;
665 }
666
667 if (verify_shell(pwd->pw_shell) < 0) {
668 fprintf(stderr, _("Error: User shell is not valid\n"));
669 return -1;
670 }
671
672 while (1) {
673 clflag = getopt_long(argc, argv, "Ccvh:r:t:Z:", long_options, NULL);
674 if (clflag == -1)
675 break;
676
677 switch (clflag) {
678 case 't':
679 tmpdir_s = optarg;
680 break;
681 case 'k':
682 kill_all = 1;
683 break;
684 case 'h':
685 homedir_s = optarg;
686 break;
687 case 'r':
688 runuserdir_s = optarg;
689 break;
690 case 'v':
691 verbose++;
692 break;
693 case 'C':
694 cap_set = CAPNG_SELECT_CAPS;
695 break;
696 case 'Z':
697 execcon = optarg;
698 break;
699 default:
700 fprintf(stderr, "%s\n", USAGE_STRING);
701 return -1;
702 }
703 }
704
705 if (! homedir_s && ! tmpdir_s) {
706 fprintf(stderr, _("Error: tmpdir and/or homedir required\n %s\n"), USAGE_STRING);
707 return -1;
708 }
709
710 if (argc - optind < 1) {
711 fprintf(stderr, _("Error: executable required\n %s\n"), USAGE_STRING);
712 return -1;
713 }
714
715 if (execcon && is_selinux_enabled() != 1) {
716 fprintf(stderr, _("Error: execution context specified, but SELinux is not enabled\n"));
717 return -1;
718 }
719
720 if (set_signal_handles())
721 return -1;
722
723 /* set fsuid to ruid */
724 /* Changing fsuid is usually required when user-specified directory is
725 * on an NFS mount. It's also desired to avoid leaking info about
726 * existence of the files not accessible to the user. */
727 if (((uid_t)setfsuid(uid) != 0) && (errno != 0)) {
728 fprintf(stderr, _("Error: unable to setfsuid %m\n"));
729
730 return -1;
731 }
732
733 /* verify homedir and tmpdir */
734 if (homedir_s && (
735 verify_directory(homedir_s, NULL, &st_homedir) < 0 ||
736 check_owner_uid(uid, homedir_s, &st_homedir))) return -1;
737 if (tmpdir_s && (
738 verify_directory(tmpdir_s, NULL, &st_tmpdir_s) < 0 ||
739 check_owner_uid(uid, tmpdir_s, &st_tmpdir_s))) return -1;
740 if (runuserdir_s && (
741 verify_directory(runuserdir_s, NULL, &st_runuserdir_s) < 0 ||
742 check_owner_uid(uid, runuserdir_s, &st_runuserdir_s))) return -1;
743
744 if ((uid_t)setfsuid(0) != uid) return -1;
745
746 /* create runtime tmpdir */
747 if (tmpdir_s && (tmpdir_r = create_tmpdir(tmpdir_s, &st_tmpdir_s,
748 &st_tmpdir_r, pwd, execcon)) == NULL) {
749 fprintf(stderr, _("Failed to create runtime temporary directory\n"));
750 return -1;
751 }
752 /* create runtime runuserdir */
753 if (runuserdir_s && (runuserdir_r = create_tmpdir(runuserdir_s, &st_runuserdir_s,
754 &st_runuserdir_r, pwd, execcon)) == NULL) {
755 fprintf(stderr, _("Failed to create runtime $XDG_RUNTIME_DIR directory\n"));
756 return -1;
757 }
758
759 /* spawn child process */
760 child = fork();
761 if (child == -1) {
762 perror(_("Unable to fork"));
763 goto err;
764 }
765
766 if (child == 0) {
767 char *display = NULL;
768 char *LANG = NULL;
769 char *RUNTIME_DIR = NULL;
770 int rc = -1;
771 char *resolved_path = NULL;
772
773 if (unshare(CLONE_NEWNS) < 0) {
774 perror(_("Failed to unshare"));
775 goto childerr;
776 }
777
778 /* Remount / as SLAVE so that nothing mounted in the namespace
779 shows up in the parent */
780 if (mount("none", "/", NULL, MS_SLAVE | MS_REC , NULL) < 0) {
781 perror(_("Failed to make / a SLAVE mountpoint\n"));
782 goto childerr;
783 }
784
785 /* assume fsuid==ruid after this point */
786 if ((uid_t)setfsuid(uid) != 0) goto childerr;
787
788 resolved_path = realpath(pwd->pw_dir,NULL);
789 if (! resolved_path) goto childerr;
790
791 if (verify_directory(resolved_path, NULL, &st_curhomedir) < 0)
792 goto childerr;
793 if (check_owner_uid(uid, resolved_path, &st_curhomedir) < 0)
794 goto childerr;
795
796 if ((RUNTIME_DIR = getenv("XDG_RUNTIME_DIR")) != NULL) {
797 if ((RUNTIME_DIR = strdup(RUNTIME_DIR)) == NULL) {
798 perror(_("Out of memory"));
799 goto childerr;
800 }
801 } else {
802 if (asprintf(&RUNTIME_DIR, "/run/user/%d", uid) == -1) {
803 perror(_("Out of memory\n"));
804 goto childerr;
805 }
806 }
807
808 /* mount homedir, runuserdir and tmpdir, in this order */
809 if (runuserdir_s && seunshare_mount(runuserdir_s, RUNTIME_DIR,
810 &st_runuserdir_s) != 0) goto childerr;
811 if (homedir_s && seunshare_mount(homedir_s, resolved_path,
812 &st_homedir) != 0) goto childerr;
813 if (tmpdir_s && seunshare_mount(tmpdir_r, "/tmp",
814 &st_tmpdir_r) != 0) goto childerr;
815
816 if (drop_privs(uid) != 0) goto childerr;
817
818 /* construct a new environment */
819 if ((display = getenv("DISPLAY")) != NULL) {
820 if ((display = strdup(display)) == NULL) {
821 perror(_("Out of memory"));
822 goto childerr;
823 }
824 }
825
826 /* construct a new environment */
827 if ((LANG = getenv("LANG")) != NULL) {
828 if ((LANG = strdup(LANG)) == NULL) {
829 perror(_("Out of memory"));
830 goto childerr;
831 }
832 }
833
834 if ((rc = clearenv()) != 0) {
835 perror(_("Failed to clear environment"));
836 goto childerr;
837 }
838 if (display)
839 rc |= setenv("DISPLAY", display, 1);
840 if (LANG)
841 rc |= setenv("LANG", LANG, 1);
842 if (RUNTIME_DIR)
843 rc |= setenv("XDG_RUNTIME_DIR", RUNTIME_DIR, 1);
844 rc |= setenv("HOME", pwd->pw_dir, 1);
845 rc |= setenv("SHELL", pwd->pw_shell, 1);
846 rc |= setenv("USER", pwd->pw_name, 1);
847 rc |= setenv("LOGNAME", pwd->pw_name, 1);
848 rc |= setenv("PATH", DEFAULT_PATH, 1);
849 if (rc != 0) {
850 fprintf(stderr, _("Failed to construct environment\n"));
851 goto childerr;
852 }
853
854 if (chdir(pwd->pw_dir)) {
855 perror(_("Failed to change dir to homedir"));
856 goto childerr;
857 }
858 setsid();
859
860 /* selinux context */
861 if (execcon) {
862 /* try dyntransition, since no_new_privs can interfere
863 * with setexeccon */
864 if (setcon(execcon) != 0) {
865 /* failed; fall back to setexeccon */
866 if (setexeccon(execcon) != 0) {
867 fprintf(stderr, _("Could not set exec context to %s. %s\n"), execcon, strerror(errno));
868 goto childerr;
869 }
870 }
871 }
872
873 execv(argv[optind], argv + optind);
874 fprintf(stderr, _("Failed to execute command %s: %s\n"), argv[optind], strerror(errno));
875 childerr:
876 free(resolved_path);
877 free(display);
878 free(LANG);
879 free(RUNTIME_DIR);
880 exit(-1);
881 }
882
883 drop_caps();
884
885 /* parent waits for child exit to do the cleanup */
886 waitpid(child, &status, 0);
887 status_to_retval(status, status);
888
889 /* Make sure all child processes exit */
890 kill(-child,SIGTERM);
891
892 if (execcon && kill_all)
893 killall(execcon);
894
895 if (tmpdir_r) cleanup_tmpdir(tmpdir_r, tmpdir_s, pwd, 1);
896
897 err:
898 free(tmpdir_r);
899 return status;
900 }
901