]> git.ipfire.org Git - people/ms/systemd.git/blob - execute.c
cgroup: if we are already in our own cgroup, then reuse it
[people/ms/systemd.git] / execute.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
2
3 /***
4 This file is part of systemd.
5
6 Copyright 2010 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <assert.h>
23 #include <dirent.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <unistd.h>
27 #include <string.h>
28 #include <signal.h>
29 #include <sys/socket.h>
30 #include <sys/un.h>
31 #include <sys/prctl.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <grp.h>
36 #include <pwd.h>
37
38 #include "execute.h"
39 #include "strv.h"
40 #include "macro.h"
41 #include "util.h"
42 #include "log.h"
43 #include "ioprio.h"
44 #include "securebits.h"
45 #include "cgroup.h"
46
47 /* This assumes there is a 'tty' group */
48 #define TTY_MODE 0620
49
50 static int shift_fds(int fds[], unsigned n_fds) {
51 int start, restart_from;
52
53 if (n_fds <= 0)
54 return 0;
55
56 /* Modifies the fds array! (sorts it) */
57
58 assert(fds);
59
60 start = 0;
61 for (;;) {
62 int i;
63
64 restart_from = -1;
65
66 for (i = start; i < (int) n_fds; i++) {
67 int nfd;
68
69 /* Already at right index? */
70 if (fds[i] == i+3)
71 continue;
72
73 if ((nfd = fcntl(fds[i], F_DUPFD, i+3)) < 0)
74 return -errno;
75
76 close_nointr_nofail(fds[i]);
77 fds[i] = nfd;
78
79 /* Hmm, the fd we wanted isn't free? Then
80 * let's remember that and try again from here*/
81 if (nfd != i+3 && restart_from < 0)
82 restart_from = i;
83 }
84
85 if (restart_from < 0)
86 break;
87
88 start = restart_from;
89 }
90
91 return 0;
92 }
93
94 static int flags_fds(const int fds[], unsigned n_fds, bool nonblock) {
95 unsigned i;
96 int r;
97
98 if (n_fds <= 0)
99 return 0;
100
101 assert(fds);
102
103 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
104
105 for (i = 0; i < n_fds; i++) {
106
107 if ((r = fd_nonblock(fds[i], nonblock)) < 0)
108 return r;
109
110 /* We unconditionally drop FD_CLOEXEC from the fds,
111 * since after all we want to pass these fds to our
112 * children */
113
114 if ((r = fd_cloexec(fds[i], false)) < 0)
115 return r;
116 }
117
118 return 0;
119 }
120
121 static const char *tty_path(const ExecContext *context) {
122 assert(context);
123
124 if (context->tty_path)
125 return context->tty_path;
126
127 return "/dev/console";
128 }
129
130 static int open_null_as(int flags, int nfd) {
131 int fd, r;
132
133 assert(nfd >= 0);
134
135 if ((fd = open("/dev/null", flags|O_NOCTTY)) < 0)
136 return -errno;
137
138 if (fd != nfd) {
139 r = dup2(fd, nfd) < 0 ? -errno : nfd;
140 close_nointr_nofail(fd);
141 } else
142 r = nfd;
143
144 return r;
145 }
146
147 static int connect_logger_as(const ExecContext *context, ExecOutput output, const char *ident, int nfd) {
148 int fd, r;
149 union {
150 struct sockaddr sa;
151 struct sockaddr_un un;
152 } sa;
153
154 assert(context);
155 assert(output < _EXEC_OUTPUT_MAX);
156 assert(ident);
157 assert(nfd >= 0);
158
159 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
160 return -errno;
161
162 zero(sa);
163 sa.sa.sa_family = AF_UNIX;
164 strncpy(sa.un.sun_path+1, LOGGER_SOCKET, sizeof(sa.un.sun_path)-1);
165
166 if (connect(fd, &sa.sa, sizeof(sa)) < 0) {
167 close_nointr_nofail(fd);
168 return -errno;
169 }
170
171 if (shutdown(fd, SHUT_RD) < 0) {
172 close_nointr_nofail(fd);
173 return -errno;
174 }
175
176 /* We speak a very simple protocol between log server
177 * and client: one line for the log destination (kmsg
178 * or syslog), followed by the priority field,
179 * followed by the process name. Since we replaced
180 * stdin/stderr we simple use stdio to write to
181 * it. Note that we use stderr, to minimize buffer
182 * flushing issues. */
183
184 dprintf(fd,
185 "%s\n"
186 "%i\n"
187 "%s\n",
188 output == EXEC_OUTPUT_KERNEL ? "kmsg" : "syslog",
189 context->syslog_priority,
190 context->syslog_identifier ? context->syslog_identifier : ident);
191
192 if (fd != nfd) {
193 r = dup2(fd, nfd) < 0 ? -errno : nfd;
194 close_nointr_nofail(fd);
195 } else
196 r = nfd;
197
198 return r;
199 }
200 static int open_terminal_as(const char *path, mode_t mode, int nfd) {
201 int fd, r;
202
203 assert(path);
204 assert(nfd >= 0);
205
206 if ((fd = open_terminal(path, mode | O_NOCTTY)) < 0)
207 return fd;
208
209 if (fd != nfd) {
210 r = dup2(fd, nfd) < 0 ? -errno : nfd;
211 close_nointr_nofail(fd);
212 } else
213 r = nfd;
214
215 return r;
216 }
217
218 static bool is_terminal_input(ExecInput i) {
219 return
220 i == EXEC_INPUT_TTY ||
221 i == EXEC_INPUT_TTY_FORCE ||
222 i == EXEC_INPUT_TTY_FAIL;
223 }
224
225 static int fixup_input(const ExecContext *context, int socket_fd) {
226 assert(context);
227
228 if (socket_fd < 0 && context->std_input == EXEC_INPUT_SOCKET)
229 return EXEC_INPUT_NULL;
230
231 return context->std_input;
232 }
233
234 static int fixup_output(const ExecContext *context, int socket_fd) {
235 assert(context);
236
237 if (socket_fd < 0 && context->std_output == EXEC_OUTPUT_SOCKET)
238 return EXEC_OUTPUT_INHERIT;
239
240 return context->std_output;
241 }
242
243 static int fixup_error(const ExecContext *context, int socket_fd) {
244 assert(context);
245
246 if (socket_fd < 0 && context->std_error == EXEC_OUTPUT_SOCKET)
247 return EXEC_OUTPUT_INHERIT;
248
249 return context->std_error;
250 }
251
252 static int setup_input(const ExecContext *context, int socket_fd) {
253 ExecInput i;
254
255 assert(context);
256
257 i = fixup_input(context, socket_fd);
258
259 switch (i) {
260
261 case EXEC_INPUT_NULL:
262 return open_null_as(O_RDONLY, STDIN_FILENO);
263
264 case EXEC_INPUT_TTY:
265 case EXEC_INPUT_TTY_FORCE:
266 case EXEC_INPUT_TTY_FAIL: {
267 int fd, r;
268
269 if ((fd = acquire_terminal(
270 tty_path(context),
271 i == EXEC_INPUT_TTY_FAIL,
272 i == EXEC_INPUT_TTY_FORCE)) < 0)
273 return fd;
274
275 if (fd != STDIN_FILENO) {
276 r = dup2(fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
277 close_nointr_nofail(fd);
278 } else
279 r = STDIN_FILENO;
280
281 return r;
282 }
283
284 case EXEC_INPUT_SOCKET:
285 return dup2(socket_fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
286
287 default:
288 assert_not_reached("Unknown input type");
289 }
290 }
291
292 static int setup_output(const ExecContext *context, int socket_fd, const char *ident) {
293 ExecOutput o;
294 ExecInput i;
295
296 assert(context);
297 assert(ident);
298
299 i = fixup_input(context, socket_fd);
300 o = fixup_output(context, socket_fd);
301
302 /* This expects the input is already set up */
303
304 switch (o) {
305
306 case EXEC_OUTPUT_INHERIT:
307
308 /* If the input is connected to a terminal, inherit that... */
309 if (is_terminal_input(i) || i == EXEC_INPUT_SOCKET)
310 return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
311
312 return STDIN_FILENO;
313
314 case EXEC_OUTPUT_NULL:
315 return open_null_as(O_WRONLY, STDOUT_FILENO);
316
317 case EXEC_OUTPUT_TTY:
318 if (is_terminal_input(i))
319 return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
320
321 /* We don't reset the terminal if this is just about output */
322 return open_terminal_as(tty_path(context), O_WRONLY, STDOUT_FILENO);
323
324 case EXEC_OUTPUT_SYSLOG:
325 case EXEC_OUTPUT_KERNEL:
326 return connect_logger_as(context, o, ident, STDOUT_FILENO);
327
328 case EXEC_OUTPUT_SOCKET:
329 assert(socket_fd >= 0);
330 return dup2(socket_fd, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
331
332 default:
333 assert_not_reached("Unknown output type");
334 }
335 }
336
337 static int setup_error(const ExecContext *context, int socket_fd, const char *ident) {
338 ExecOutput o, e;
339 ExecInput i;
340
341 assert(context);
342 assert(ident);
343
344 i = fixup_input(context, socket_fd);
345 o = fixup_output(context, socket_fd);
346 e = fixup_error(context, socket_fd);
347
348 /* This expects the input and output are already set up */
349
350 /* Don't change the stderr file descriptor if we inherit all
351 * the way and are not on a tty */
352 if (e == EXEC_OUTPUT_INHERIT &&
353 o == EXEC_OUTPUT_INHERIT &&
354 !is_terminal_input(i))
355 return STDERR_FILENO;
356
357 /* Duplicate form stdout if possible */
358 if (e == o || e == EXEC_OUTPUT_INHERIT)
359 return dup2(STDOUT_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
360
361 switch (e) {
362
363 case EXEC_OUTPUT_NULL:
364 return open_null_as(O_WRONLY, STDERR_FILENO);
365
366 case EXEC_OUTPUT_TTY:
367 if (is_terminal_input(i))
368 return dup2(STDIN_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
369
370 /* We don't reset the terminal if this is just about output */
371 return open_terminal_as(tty_path(context), O_WRONLY, STDERR_FILENO);
372
373 case EXEC_OUTPUT_SYSLOG:
374 case EXEC_OUTPUT_KERNEL:
375 return connect_logger_as(context, e, ident, STDERR_FILENO);
376
377 case EXEC_OUTPUT_SOCKET:
378 assert(socket_fd >= 0);
379 return dup2(socket_fd, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
380
381 default:
382 assert_not_reached("Unknown error type");
383 }
384 }
385
386 static int chown_terminal(int fd, uid_t uid) {
387 struct stat st;
388
389 assert(fd >= 0);
390
391 /* This might fail. What matters are the results. */
392 fchown(fd, uid, -1);
393 fchmod(fd, TTY_MODE);
394
395 if (fstat(fd, &st) < 0)
396 return -errno;
397
398 if (st.st_uid != uid || (st.st_mode & 0777) != TTY_MODE)
399 return -EPERM;
400
401 return 0;
402 }
403
404 static int setup_confirm_stdio(const ExecContext *context,
405 int *_saved_stdin,
406 int *_saved_stdout) {
407 int fd = -1, saved_stdin, saved_stdout = -1, r;
408
409 assert(context);
410 assert(_saved_stdin);
411 assert(_saved_stdout);
412
413 /* This returns positive EXIT_xxx return values instead of
414 * negative errno style values! */
415
416 if ((saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3)) < 0)
417 return EXIT_STDIN;
418
419 if ((saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3)) < 0) {
420 r = EXIT_STDOUT;
421 goto fail;
422 }
423
424 if ((fd = acquire_terminal(
425 tty_path(context),
426 context->std_input == EXEC_INPUT_TTY_FAIL,
427 context->std_input == EXEC_INPUT_TTY_FORCE)) < 0) {
428 r = EXIT_STDIN;
429 goto fail;
430 }
431
432 if (chown_terminal(fd, getuid()) < 0) {
433 r = EXIT_STDIN;
434 goto fail;
435 }
436
437 if (dup2(fd, STDIN_FILENO) < 0) {
438 r = EXIT_STDIN;
439 goto fail;
440 }
441
442 if (dup2(fd, STDOUT_FILENO) < 0) {
443 r = EXIT_STDOUT;
444 goto fail;
445 }
446
447 if (fd >= 2)
448 close_nointr_nofail(fd);
449
450 *_saved_stdin = saved_stdin;
451 *_saved_stdout = saved_stdout;
452
453 return 0;
454
455 fail:
456 if (saved_stdout >= 0)
457 close_nointr_nofail(saved_stdout);
458
459 if (saved_stdin >= 0)
460 close_nointr_nofail(saved_stdin);
461
462 if (fd >= 0)
463 close_nointr_nofail(fd);
464
465 return r;
466 }
467
468 static int restore_conform_stdio(const ExecContext *context,
469 int *saved_stdin,
470 int *saved_stdout,
471 bool *keep_stdin,
472 bool *keep_stdout) {
473
474 assert(context);
475 assert(saved_stdin);
476 assert(*saved_stdin >= 0);
477 assert(saved_stdout);
478 assert(*saved_stdout >= 0);
479
480 /* This returns positive EXIT_xxx return values instead of
481 * negative errno style values! */
482
483 if (is_terminal_input(context->std_input)) {
484
485 /* The service wants terminal input. */
486
487 *keep_stdin = true;
488 *keep_stdout =
489 context->std_output == EXEC_OUTPUT_INHERIT ||
490 context->std_output == EXEC_OUTPUT_TTY;
491
492 } else {
493 /* If the service doesn't want a controlling terminal,
494 * then we need to get rid entirely of what we have
495 * already. */
496
497 if (release_terminal() < 0)
498 return EXIT_STDIN;
499
500 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
501 return EXIT_STDIN;
502
503 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
504 return EXIT_STDOUT;
505
506 *keep_stdout = *keep_stdin = false;
507 }
508
509 return 0;
510 }
511
512 static int get_group_creds(const char *groupname, gid_t *gid) {
513 struct group *g;
514 unsigned long lu;
515
516 assert(groupname);
517 assert(gid);
518
519 /* We enforce some special rules for gid=0: in order to avoid
520 * NSS lookups for root we hardcode its data. */
521
522 if (streq(groupname, "root") || streq(groupname, "0")) {
523 *gid = 0;
524 return 0;
525 }
526
527 if (safe_atolu(groupname, &lu) >= 0) {
528 errno = 0;
529 g = getgrgid((gid_t) lu);
530 } else {
531 errno = 0;
532 g = getgrnam(groupname);
533 }
534
535 if (!g)
536 return errno != 0 ? -errno : -ESRCH;
537
538 *gid = g->gr_gid;
539 return 0;
540 }
541
542 static int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
543 struct passwd *p;
544 unsigned long lu;
545
546 assert(username);
547 assert(*username);
548 assert(uid);
549 assert(gid);
550 assert(home);
551
552 /* We enforce some special rules for uid=0: in order to avoid
553 * NSS lookups for root we hardcode its data. */
554
555 if (streq(*username, "root") || streq(*username, "0")) {
556 *username = "root";
557 *uid = 0;
558 *gid = 0;
559 *home = "/root";
560 return 0;
561 }
562
563 if (safe_atolu(*username, &lu) >= 0) {
564 errno = 0;
565 p = getpwuid((uid_t) lu);
566
567 /* If there are multiple users with the same id, make
568 * sure to leave $USER to the configured value instead
569 * of the first occurence in the database. However if
570 * the uid was configured by a numeric uid, then let's
571 * pick the real username from /etc/passwd. */
572 if (*username && p)
573 *username = p->pw_name;
574 } else {
575 errno = 0;
576 p = getpwnam(*username);
577 }
578
579 if (!p)
580 return errno != 0 ? -errno : -ESRCH;
581
582 *uid = p->pw_uid;
583 *gid = p->pw_gid;
584 *home = p->pw_dir;
585 return 0;
586 }
587
588 static int enforce_groups(const ExecContext *context, const char *username, gid_t gid) {
589 bool keep_groups = false;
590 int r;
591
592 assert(context);
593
594 /* Lookup and ser GID and supplementary group list. Here too
595 * we avoid NSS lookups for gid=0. */
596
597 if (context->group || username) {
598
599 if (context->group)
600 if ((r = get_group_creds(context->group, &gid)) < 0)
601 return r;
602
603 /* First step, initialize groups from /etc/groups */
604 if (username && gid != 0) {
605 if (initgroups(username, gid) < 0)
606 return -errno;
607
608 keep_groups = true;
609 }
610
611 /* Second step, set our gids */
612 if (setresgid(gid, gid, gid) < 0)
613 return -errno;
614 }
615
616 if (context->supplementary_groups) {
617 int ngroups_max, k;
618 gid_t *gids;
619 char **i;
620
621 /* Final step, initialize any manually set supplementary groups */
622 ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
623
624 if (!(gids = new(gid_t, ngroups_max)))
625 return -ENOMEM;
626
627 if (keep_groups) {
628 if ((k = getgroups(ngroups_max, gids)) < 0) {
629 free(gids);
630 return -errno;
631 }
632 } else
633 k = 0;
634
635 STRV_FOREACH(i, context->supplementary_groups) {
636
637 if (k >= ngroups_max) {
638 free(gids);
639 return -E2BIG;
640 }
641
642 if ((r = get_group_creds(*i, gids+k)) < 0) {
643 free(gids);
644 return r;
645 }
646
647 k++;
648 }
649
650 if (setgroups(k, gids) < 0) {
651 free(gids);
652 return -errno;
653 }
654
655 free(gids);
656 }
657
658 return 0;
659 }
660
661 static int enforce_user(const ExecContext *context, uid_t uid) {
662 int r;
663 assert(context);
664
665 /* Sets (but doesn't lookup) the uid and make sure we keep the
666 * capabilities while doing so. */
667
668 if (context->capabilities) {
669 cap_t d;
670 static const cap_value_t bits[] = {
671 CAP_SETUID, /* Necessary so that we can run setresuid() below */
672 CAP_SETPCAP /* Necessary so that we can set PR_SET_SECUREBITS later on */
673 };
674
675 /* First step: If we need to keep capabilities but
676 * drop privileges we need to make sure we keep our
677 * caps, whiel we drop priviliges. */
678 if (uid != 0) {
679 int sb = context->secure_bits|SECURE_KEEP_CAPS;
680
681 if (prctl(PR_GET_SECUREBITS) != sb)
682 if (prctl(PR_SET_SECUREBITS, sb) < 0)
683 return -errno;
684 }
685
686 /* Second step: set the capabilites. This will reduce
687 * the capabilities to the minimum we need. */
688
689 if (!(d = cap_dup(context->capabilities)))
690 return -errno;
691
692 if (cap_set_flag(d, CAP_EFFECTIVE, ELEMENTSOF(bits), bits, CAP_SET) < 0 ||
693 cap_set_flag(d, CAP_PERMITTED, ELEMENTSOF(bits), bits, CAP_SET) < 0) {
694 r = -errno;
695 cap_free(d);
696 return r;
697 }
698
699 if (cap_set_proc(d) < 0) {
700 r = -errno;
701 cap_free(d);
702 return r;
703 }
704
705 cap_free(d);
706 }
707
708 /* Third step: actually set the uids */
709 if (setresuid(uid, uid, uid) < 0)
710 return -errno;
711
712 /* At this point we should have all necessary capabilities but
713 are otherwise a normal user. However, the caps might got
714 corrupted due to the setresuid() so we need clean them up
715 later. This is done outside of this call. */
716
717 return 0;
718 }
719
720 int exec_spawn(ExecCommand *command,
721 char **argv,
722 const ExecContext *context,
723 int fds[], unsigned n_fds,
724 bool apply_permissions,
725 bool apply_chroot,
726 bool confirm_spawn,
727 CGroupBonding *cgroup_bondings,
728 pid_t *ret) {
729
730 pid_t pid;
731 int r;
732 char *line;
733 int socket_fd;
734
735 assert(command);
736 assert(context);
737 assert(ret);
738 assert(fds || n_fds <= 0);
739
740 if (context->std_input == EXEC_INPUT_SOCKET ||
741 context->std_output == EXEC_OUTPUT_SOCKET ||
742 context->std_error == EXEC_OUTPUT_SOCKET) {
743
744 if (n_fds != 1)
745 return -EINVAL;
746
747 socket_fd = fds[0];
748
749 fds = NULL;
750 n_fds = 0;
751 } else
752 socket_fd = -1;
753
754 if (!argv)
755 argv = command->argv;
756
757 if (!(line = exec_command_line(argv)))
758 return -ENOMEM;
759
760 log_debug("About to execute: %s", line);
761 free(line);
762
763 if (cgroup_bondings)
764 if ((r = cgroup_bonding_realize_list(cgroup_bondings)))
765 return r;
766
767 if ((pid = fork()) < 0)
768 return -errno;
769
770 if (pid == 0) {
771 int i;
772 sigset_t ss;
773 const char *username = NULL, *home = NULL;
774 uid_t uid = (uid_t) -1;
775 gid_t gid = (gid_t) -1;
776 char **our_env = NULL, **final_env = NULL;
777 unsigned n_env = 0;
778 int saved_stdout = -1, saved_stdin = -1;
779 bool keep_stdout = false, keep_stdin = false;
780
781 /* child */
782
783 reset_all_signal_handlers();
784
785 if (sigemptyset(&ss) < 0 ||
786 sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
787 r = EXIT_SIGNAL_MASK;
788 goto fail;
789 }
790
791 if (!context->no_setsid)
792 if (setsid() < 0) {
793 r = EXIT_SETSID;
794 goto fail;
795 }
796
797 umask(context->umask);
798
799 if (confirm_spawn) {
800 char response;
801
802 /* Set up terminal for the question */
803 if ((r = setup_confirm_stdio(context,
804 &saved_stdin, &saved_stdout)))
805 goto fail;
806
807 /* Now ask the question. */
808 if (!(line = exec_command_line(argv))) {
809 r = EXIT_MEMORY;
810 goto fail;
811 }
812
813 r = ask(&response, "yns", "Execute %s? [Yes, No, Skip] ", line);
814 free(line);
815
816 if (r < 0 || response == 'n') {
817 r = EXIT_CONFIRM;
818 goto fail;
819 } else if (response == 's') {
820 r = 0;
821 goto fail;
822 }
823
824 /* Release terminal for the question */
825 if ((r = restore_conform_stdio(context,
826 &saved_stdin, &saved_stdout,
827 &keep_stdin, &keep_stdout)))
828 goto fail;
829 }
830
831 if (!keep_stdin)
832 if (setup_input(context, socket_fd) < 0) {
833 r = EXIT_STDIN;
834 goto fail;
835 }
836
837 if (!keep_stdout)
838 if (setup_output(context, socket_fd, file_name_from_path(command->path)) < 0) {
839 r = EXIT_STDOUT;
840 goto fail;
841 }
842
843 if (setup_error(context, socket_fd, file_name_from_path(command->path)) < 0) {
844 r = EXIT_STDERR;
845 goto fail;
846 }
847
848 if (cgroup_bondings)
849 if ((r = cgroup_bonding_install_list(cgroup_bondings, 0)) < 0) {
850 r = EXIT_CGROUP;
851 goto fail;
852 }
853
854 if (context->oom_adjust_set) {
855 char t[16];
856
857 snprintf(t, sizeof(t), "%i", context->oom_adjust);
858 char_array_0(t);
859
860 if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
861 r = EXIT_OOM_ADJUST;
862 goto fail;
863 }
864 }
865
866 if (context->nice_set)
867 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
868 r = EXIT_NICE;
869 goto fail;
870 }
871
872 if (context->cpu_sched_set) {
873 struct sched_param param;
874
875 zero(param);
876 param.sched_priority = context->cpu_sched_priority;
877
878 if (sched_setscheduler(0, context->cpu_sched_policy |
879 (context->cpu_sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0), &param) < 0) {
880 r = EXIT_SETSCHEDULER;
881 goto fail;
882 }
883 }
884
885 if (context->cpu_affinity_set)
886 if (sched_setaffinity(0, sizeof(context->cpu_affinity), &context->cpu_affinity) < 0) {
887 r = EXIT_CPUAFFINITY;
888 goto fail;
889 }
890
891 if (context->ioprio_set)
892 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
893 r = EXIT_IOPRIO;
894 goto fail;
895 }
896
897 if (context->timer_slack_ns_set)
898 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_ns_set) < 0) {
899 r = EXIT_TIMERSLACK;
900 goto fail;
901 }
902
903 if (context->user) {
904 username = context->user;
905 if (get_user_creds(&username, &uid, &gid, &home) < 0) {
906 r = EXIT_USER;
907 goto fail;
908 }
909
910 if (is_terminal_input(context->std_input))
911 if (chown_terminal(STDIN_FILENO, uid) < 0) {
912 r = EXIT_STDIN;
913 goto fail;
914 }
915 }
916
917 if (apply_permissions)
918 if (enforce_groups(context, username, uid) < 0) {
919 r = EXIT_GROUP;
920 goto fail;
921 }
922
923 if (apply_chroot) {
924 if (context->root_directory)
925 if (chroot(context->root_directory) < 0) {
926 r = EXIT_CHROOT;
927 goto fail;
928 }
929
930 if (chdir(context->working_directory ? context->working_directory : "/") < 0) {
931 r = EXIT_CHDIR;
932 goto fail;
933 }
934 } else {
935
936 char *d;
937
938 if (asprintf(&d, "%s/%s",
939 context->root_directory ? context->root_directory : "",
940 context->working_directory ? context->working_directory : "") < 0) {
941 r = EXIT_MEMORY;
942 goto fail;
943 }
944
945 if (chdir(d) < 0) {
946 free(d);
947 r = EXIT_CHDIR;
948 goto fail;
949 }
950
951 free(d);
952 }
953
954 if (close_all_fds(fds, n_fds) < 0 ||
955 shift_fds(fds, n_fds) < 0 ||
956 flags_fds(fds, n_fds, context->non_blocking) < 0) {
957 r = EXIT_FDS;
958 goto fail;
959 }
960
961 if (apply_permissions) {
962
963 for (i = 0; i < RLIMIT_NLIMITS; i++) {
964 if (!context->rlimit[i])
965 continue;
966
967 if (setrlimit(i, context->rlimit[i]) < 0) {
968 r = EXIT_LIMITS;
969 goto fail;
970 }
971 }
972
973 if (context->user)
974 if (enforce_user(context, uid) < 0) {
975 r = EXIT_USER;
976 goto fail;
977 }
978
979 /* PR_GET_SECUREBITS is not priviliged, while
980 * PR_SET_SECUREBITS is. So to suppress
981 * potential EPERMs we'll try not to call
982 * PR_SET_SECUREBITS unless necessary. */
983 if (prctl(PR_GET_SECUREBITS) != context->secure_bits)
984 if (prctl(PR_SET_SECUREBITS, context->secure_bits) < 0) {
985 r = EXIT_SECUREBITS;
986 goto fail;
987 }
988
989 if (context->capabilities)
990 if (cap_set_proc(context->capabilities) < 0) {
991 r = EXIT_CAPABILITIES;
992 goto fail;
993 }
994 }
995
996 if (!(our_env = new0(char*, 6))) {
997 r = EXIT_MEMORY;
998 goto fail;
999 }
1000
1001 if (n_fds > 0)
1002 if (asprintf(our_env + n_env++, "LISTEN_PID=%llu", (unsigned long long) getpid()) < 0 ||
1003 asprintf(our_env + n_env++, "LISTEN_FDS=%u", n_fds) < 0) {
1004 r = EXIT_MEMORY;
1005 goto fail;
1006 }
1007
1008 if (home)
1009 if (asprintf(our_env + n_env++, "HOME=%s", home) < 0) {
1010 r = EXIT_MEMORY;
1011 goto fail;
1012 }
1013
1014 if (username)
1015 if (asprintf(our_env + n_env++, "LOGNAME=%s", username) < 0 ||
1016 asprintf(our_env + n_env++, "USER=%s", username) < 0) {
1017 r = EXIT_MEMORY;
1018 goto fail;
1019 }
1020
1021 if (!(final_env = strv_env_merge(environ, our_env, context->environment, NULL))) {
1022 r = EXIT_MEMORY;
1023 goto fail;
1024 }
1025
1026 execve(command->path, argv, final_env);
1027 r = EXIT_EXEC;
1028
1029 fail:
1030 strv_free(our_env);
1031 strv_free(final_env);
1032
1033 if (saved_stdin >= 0)
1034 close_nointr_nofail(saved_stdin);
1035
1036 if (saved_stdout >= 0)
1037 close_nointr_nofail(saved_stdout);
1038
1039 _exit(r);
1040 }
1041
1042 /* We add the new process to the cgroup both in the child (so
1043 * that we can be sure that no user code is ever executed
1044 * outside of the cgroup) and in the parent (so that we can be
1045 * sure that when we kill the cgroup the process will be
1046 * killed too). */
1047 if (cgroup_bondings)
1048 if ((r = cgroup_bonding_install_list(cgroup_bondings, pid)) < 0) {
1049 r = EXIT_CGROUP;
1050 goto fail;
1051 }
1052
1053 log_debug("Forked %s as %llu", command->path, (unsigned long long) pid);
1054
1055 command->exec_status.pid = pid;
1056 command->exec_status.start_timestamp = now(CLOCK_REALTIME);
1057
1058 *ret = pid;
1059 return 0;
1060 }
1061
1062 void exec_context_init(ExecContext *c) {
1063 assert(c);
1064
1065 c->umask = 0002;
1066 c->oom_adjust = 0;
1067 c->oom_adjust_set = false;
1068 c->nice = 0;
1069 c->nice_set = false;
1070 c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
1071 c->ioprio_set = false;
1072 c->cpu_sched_policy = SCHED_OTHER;
1073 c->cpu_sched_priority = 0;
1074 c->cpu_sched_set = false;
1075 CPU_ZERO(&c->cpu_affinity);
1076 c->cpu_affinity_set = false;
1077 c->timer_slack_ns = 0;
1078 c->timer_slack_ns_set = false;
1079
1080 c->cpu_sched_reset_on_fork = false;
1081 c->non_blocking = false;
1082
1083 c->std_input = 0;
1084 c->std_output = 0;
1085 c->std_error = 0;
1086 c->syslog_priority = LOG_DAEMON|LOG_INFO;
1087
1088 c->secure_bits = 0;
1089 c->capability_bounding_set_drop = 0;
1090 }
1091
1092 void exec_context_done(ExecContext *c) {
1093 unsigned l;
1094
1095 assert(c);
1096
1097 strv_free(c->environment);
1098 c->environment = NULL;
1099
1100 for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
1101 free(c->rlimit[l]);
1102 c->rlimit[l] = NULL;
1103 }
1104
1105 free(c->working_directory);
1106 c->working_directory = NULL;
1107 free(c->root_directory);
1108 c->root_directory = NULL;
1109
1110 free(c->tty_path);
1111 c->tty_path = NULL;
1112
1113 free(c->syslog_identifier);
1114 c->syslog_identifier = NULL;
1115
1116 free(c->user);
1117 c->user = NULL;
1118
1119 free(c->group);
1120 c->group = NULL;
1121
1122 strv_free(c->supplementary_groups);
1123 c->supplementary_groups = NULL;
1124
1125 if (c->capabilities) {
1126 cap_free(c->capabilities);
1127 c->capabilities = NULL;
1128 }
1129 }
1130
1131 void exec_command_done(ExecCommand *c) {
1132 assert(c);
1133
1134 free(c->path);
1135 c->path = NULL;
1136
1137 strv_free(c->argv);
1138 c->argv = NULL;
1139 }
1140
1141 void exec_command_done_array(ExecCommand *c, unsigned n) {
1142 unsigned i;
1143
1144 for (i = 0; i < n; i++)
1145 exec_command_done(c+i);
1146 }
1147
1148 void exec_command_free_list(ExecCommand *c) {
1149 ExecCommand *i;
1150
1151 while ((i = c)) {
1152 LIST_REMOVE(ExecCommand, command, c, i);
1153 exec_command_done(i);
1154 free(i);
1155 }
1156 }
1157
1158 void exec_command_free_array(ExecCommand **c, unsigned n) {
1159 unsigned i;
1160
1161 for (i = 0; i < n; i++) {
1162 exec_command_free_list(c[i]);
1163 c[i] = NULL;
1164 }
1165 }
1166
1167 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
1168 char ** e;
1169 unsigned i;
1170
1171 assert(c);
1172 assert(f);
1173
1174 if (!prefix)
1175 prefix = "";
1176
1177 fprintf(f,
1178 "%sUMask: %04o\n"
1179 "%sWorkingDirectory: %s\n"
1180 "%sRootDirectory: %s\n"
1181 "%sNonBlocking: %s\n",
1182 prefix, c->umask,
1183 prefix, c->working_directory ? c->working_directory : "/",
1184 prefix, c->root_directory ? c->root_directory : "/",
1185 prefix, yes_no(c->non_blocking));
1186
1187 if (c->environment)
1188 for (e = c->environment; *e; e++)
1189 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
1190
1191 if (c->nice_set)
1192 fprintf(f,
1193 "%sNice: %i\n",
1194 prefix, c->nice);
1195
1196 if (c->oom_adjust_set)
1197 fprintf(f,
1198 "%sOOMAdjust: %i\n",
1199 prefix, c->oom_adjust);
1200
1201 for (i = 0; i < RLIM_NLIMITS; i++)
1202 if (c->rlimit[i])
1203 fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
1204
1205 if (c->ioprio_set)
1206 fprintf(f,
1207 "%sIOSchedulingClass: %s\n"
1208 "%sIOPriority: %i\n",
1209 prefix, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c->ioprio)),
1210 prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
1211
1212 if (c->cpu_sched_set)
1213 fprintf(f,
1214 "%sCPUSchedulingPolicy: %s\n"
1215 "%sCPUSchedulingPriority: %i\n"
1216 "%sCPUSchedulingResetOnFork: %s\n",
1217 prefix, sched_policy_to_string(c->cpu_sched_policy),
1218 prefix, c->cpu_sched_priority,
1219 prefix, yes_no(c->cpu_sched_reset_on_fork));
1220
1221 if (c->cpu_affinity_set) {
1222 fprintf(f, "%sCPUAffinity:", prefix);
1223 for (i = 0; i < CPU_SETSIZE; i++)
1224 if (CPU_ISSET(i, &c->cpu_affinity))
1225 fprintf(f, " %i", i);
1226 fputs("\n", f);
1227 }
1228
1229 if (c->timer_slack_ns_set)
1230 fprintf(f, "%sTimerSlackNS: %lu\n", prefix, c->timer_slack_ns);
1231
1232 fprintf(f,
1233 "%sStandardInput: %s\n"
1234 "%sStandardOutput: %s\n"
1235 "%sStandardError: %s\n",
1236 prefix, exec_input_to_string(c->std_input),
1237 prefix, exec_output_to_string(c->std_output),
1238 prefix, exec_output_to_string(c->std_error));
1239
1240 if (c->tty_path)
1241 fprintf(f,
1242 "%sTTYPath: %s\n",
1243 prefix, c->tty_path);
1244
1245 if (c->std_output == EXEC_OUTPUT_SYSLOG || c->std_output == EXEC_OUTPUT_KERNEL ||
1246 c->std_error == EXEC_OUTPUT_SYSLOG || c->std_error == EXEC_OUTPUT_KERNEL)
1247 fprintf(f,
1248 "%sSyslogFacility: %s\n"
1249 "%sSyslogLevel: %s\n",
1250 prefix, log_facility_to_string(LOG_FAC(c->syslog_priority)),
1251 prefix, log_level_to_string(LOG_PRI(c->syslog_priority)));
1252
1253 if (c->capabilities) {
1254 char *t;
1255 if ((t = cap_to_text(c->capabilities, NULL))) {
1256 fprintf(f, "%sCapabilities: %s\n",
1257 prefix, t);
1258 cap_free(t);
1259 }
1260 }
1261
1262 if (c->secure_bits)
1263 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
1264 prefix,
1265 (c->secure_bits & SECURE_KEEP_CAPS) ? " keep-caps" : "",
1266 (c->secure_bits & SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
1267 (c->secure_bits & SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
1268 (c->secure_bits & SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
1269 (c->secure_bits & SECURE_NOROOT) ? " noroot" : "",
1270 (c->secure_bits & SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
1271
1272 if (c->capability_bounding_set_drop) {
1273 fprintf(f, "%sCapabilityBoundingSetDrop:", prefix);
1274
1275 for (i = 0; i <= CAP_LAST_CAP; i++)
1276 if (c->capability_bounding_set_drop & (1 << i)) {
1277 char *t;
1278
1279 if ((t = cap_to_name(i))) {
1280 fprintf(f, " %s", t);
1281 free(t);
1282 }
1283 }
1284
1285 fputs("\n", f);
1286 }
1287
1288 if (c->user)
1289 fprintf(f, "%sUser: %s", prefix, c->user);
1290 if (c->group)
1291 fprintf(f, "%sGroup: %s", prefix, c->group);
1292
1293 if (c->supplementary_groups) {
1294 char **g;
1295
1296 fprintf(f, "%sSupplementaryGroups:", prefix);
1297
1298 STRV_FOREACH(g, c->supplementary_groups)
1299 fprintf(f, " %s", *g);
1300
1301 fputs("\n", f);
1302 }
1303 }
1304
1305 void exec_status_fill(ExecStatus *s, pid_t pid, int code, int status) {
1306 assert(s);
1307
1308 s->pid = pid;
1309 s->exit_timestamp = now(CLOCK_REALTIME);
1310
1311 s->code = code;
1312 s->status = status;
1313 }
1314
1315 void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
1316 char buf[FORMAT_TIMESTAMP_MAX];
1317
1318 assert(s);
1319 assert(f);
1320
1321 if (!prefix)
1322 prefix = "";
1323
1324 if (s->pid <= 0)
1325 return;
1326
1327 fprintf(f,
1328 "%sPID: %llu\n",
1329 prefix, (unsigned long long) s->pid);
1330
1331 if (s->start_timestamp > 0)
1332 fprintf(f,
1333 "%sStart Timestamp: %s\n",
1334 prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp));
1335
1336 if (s->exit_timestamp > 0)
1337 fprintf(f,
1338 "%sExit Timestamp: %s\n"
1339 "%sExit Code: %s\n"
1340 "%sExit Status: %i\n",
1341 prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp),
1342 prefix, sigchld_code_to_string(s->code),
1343 prefix, s->status);
1344 }
1345
1346 char *exec_command_line(char **argv) {
1347 size_t k;
1348 char *n, *p, **a;
1349 bool first = true;
1350
1351 assert(argv);
1352
1353 k = 1;
1354 STRV_FOREACH(a, argv)
1355 k += strlen(*a)+3;
1356
1357 if (!(n = new(char, k)))
1358 return NULL;
1359
1360 p = n;
1361 STRV_FOREACH(a, argv) {
1362
1363 if (!first)
1364 *(p++) = ' ';
1365 else
1366 first = false;
1367
1368 if (strpbrk(*a, WHITESPACE)) {
1369 *(p++) = '\'';
1370 p = stpcpy(p, *a);
1371 *(p++) = '\'';
1372 } else
1373 p = stpcpy(p, *a);
1374
1375 }
1376
1377 *p = 0;
1378
1379 /* FIXME: this doesn't really handle arguments that have
1380 * spaces and ticks in them */
1381
1382 return n;
1383 }
1384
1385 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
1386 char *p2;
1387 const char *prefix2;
1388
1389 char *cmd;
1390
1391 assert(c);
1392 assert(f);
1393
1394 if (!prefix)
1395 prefix = "";
1396 p2 = strappend(prefix, "\t");
1397 prefix2 = p2 ? p2 : prefix;
1398
1399 cmd = exec_command_line(c->argv);
1400
1401 fprintf(f,
1402 "%sCommand Line: %s\n",
1403 prefix, cmd ? cmd : strerror(ENOMEM));
1404
1405 free(cmd);
1406
1407 exec_status_dump(&c->exec_status, f, prefix2);
1408
1409 free(p2);
1410 }
1411
1412 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
1413 assert(f);
1414
1415 if (!prefix)
1416 prefix = "";
1417
1418 LIST_FOREACH(command, c, c)
1419 exec_command_dump(c, f, prefix);
1420 }
1421
1422 void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
1423 ExecCommand *end;
1424
1425 assert(l);
1426 assert(e);
1427
1428 if (*l) {
1429 /* It's kinda important that we keep the order here */
1430 LIST_FIND_TAIL(ExecCommand, command, *l, end);
1431 LIST_INSERT_AFTER(ExecCommand, command, *l, end, e);
1432 } else
1433 *l = e;
1434 }
1435
1436 int exec_command_set(ExecCommand *c, const char *path, ...) {
1437 va_list ap;
1438 char **l, *p;
1439
1440 assert(c);
1441 assert(path);
1442
1443 va_start(ap, path);
1444 l = strv_new_ap(path, ap);
1445 va_end(ap);
1446
1447 if (!l)
1448 return -ENOMEM;
1449
1450 if (!(p = strdup(path))) {
1451 strv_free(l);
1452 return -ENOMEM;
1453 }
1454
1455 free(c->path);
1456 c->path = p;
1457
1458 strv_free(c->argv);
1459 c->argv = l;
1460
1461 return 0;
1462 }
1463
1464 const char* exit_status_to_string(ExitStatus status) {
1465
1466 /* We cast to int here, so that -Wenum doesn't complain that
1467 * EXIT_SUCCESS/EXIT_FAILURE aren't in the enum */
1468
1469 switch ((int) status) {
1470
1471 case EXIT_SUCCESS:
1472 return "SUCCESS";
1473
1474 case EXIT_FAILURE:
1475 return "FAILURE";
1476
1477 case EXIT_INVALIDARGUMENT:
1478 return "INVALIDARGUMENT";
1479
1480 case EXIT_NOTIMPLEMENTED:
1481 return "NOTIMPLEMENTED";
1482
1483 case EXIT_NOPERMISSION:
1484 return "NOPERMISSION";
1485
1486 case EXIT_NOTINSTALLED:
1487 return "NOTINSSTALLED";
1488
1489 case EXIT_NOTCONFIGURED:
1490 return "NOTCONFIGURED";
1491
1492 case EXIT_NOTRUNNING:
1493 return "NOTRUNNING";
1494
1495 case EXIT_CHDIR:
1496 return "CHDIR";
1497
1498 case EXIT_NICE:
1499 return "NICE";
1500
1501 case EXIT_FDS:
1502 return "FDS";
1503
1504 case EXIT_EXEC:
1505 return "EXEC";
1506
1507 case EXIT_MEMORY:
1508 return "MEMORY";
1509
1510 case EXIT_LIMITS:
1511 return "LIMITS";
1512
1513 case EXIT_OOM_ADJUST:
1514 return "OOM_ADJUST";
1515
1516 case EXIT_SIGNAL_MASK:
1517 return "SIGNAL_MASK";
1518
1519 case EXIT_STDIN:
1520 return "STDIN";
1521
1522 case EXIT_STDOUT:
1523 return "STDOUT";
1524
1525 case EXIT_CHROOT:
1526 return "CHROOT";
1527
1528 case EXIT_IOPRIO:
1529 return "IOPRIO";
1530
1531 case EXIT_TIMERSLACK:
1532 return "TIMERSLACK";
1533
1534 case EXIT_SECUREBITS:
1535 return "SECUREBITS";
1536
1537 case EXIT_SETSCHEDULER:
1538 return "SETSCHEDULER";
1539
1540 case EXIT_CPUAFFINITY:
1541 return "CPUAFFINITY";
1542
1543 case EXIT_GROUP:
1544 return "GROUP";
1545
1546 case EXIT_USER:
1547 return "USER";
1548
1549 case EXIT_CAPABILITIES:
1550 return "CAPABILITIES";
1551
1552 case EXIT_CGROUP:
1553 return "CGROUP";
1554
1555 case EXIT_SETSID:
1556 return "SETSID";
1557
1558 case EXIT_CONFIRM:
1559 return "CONFIRM";
1560
1561 case EXIT_STDERR:
1562 return "STDERR";
1563
1564 default:
1565 return NULL;
1566 }
1567 }
1568
1569 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
1570 [EXEC_INPUT_NULL] = "null",
1571 [EXEC_INPUT_TTY] = "tty",
1572 [EXEC_INPUT_TTY_FORCE] = "tty-force",
1573 [EXEC_INPUT_TTY_FAIL] = "tty-fail",
1574 [EXEC_INPUT_SOCKET] = "socket"
1575 };
1576
1577 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
1578 [EXEC_OUTPUT_INHERIT] = "inherit",
1579 [EXEC_OUTPUT_NULL] = "null",
1580 [EXEC_OUTPUT_TTY] = "tty",
1581 [EXEC_OUTPUT_SYSLOG] = "syslog",
1582 [EXEC_OUTPUT_KERNEL] = "kernel",
1583 [EXEC_OUTPUT_SOCKET] = "socket"
1584 };
1585
1586 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
1587
1588 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);