1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
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.
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.
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/>.
29 #include <sys/socket.h>
31 #include <sys/prctl.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
44 #include "securebits.h"
46 static int close_fds(int except[], unsigned n_except) {
51 /* Modifies the fds array! (sorts it) */
53 if (!(d = opendir("/proc/self/fd")))
56 while ((de = readdir(d))) {
59 if (de->d_name[0] == '.')
62 if ((r = safe_atoi(de->d_name, &fd)) < 0)
76 for (i = 0; i < n_except; i++)
77 if (except[i] == fd) {
86 if ((r = close_nointr(fd)) < 0)
95 static int shift_fds(int fds[], unsigned n_fds) {
96 int start, restart_from;
109 for (i = start; i < (int) n_fds; i++) {
112 /* Already at right index? */
116 if ((nfd = fcntl(fds[i], F_DUPFD, i+3)) < 0)
119 assert_se(close_nointr(fds[i]) == 0);
122 /* Hmm, the fd we wanted isn't free? Then
123 * let's remember that and try again from here*/
124 if (nfd != i+3 && restart_from < 0)
128 if (restart_from < 0)
131 start = restart_from;
137 static int flags_fds(int fds[], unsigned n_fds, bool nonblock) {
145 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
147 for (i = 0; i < n_fds; i++) {
150 if ((flags = fcntl(fds[i], F_GETFL, 0)) < 0)
156 flags &= ~O_NONBLOCK;
158 if (fcntl(fds[i], F_SETFL, flags) < 0)
161 /* We unconditionally drop FD_CLOEXEC from the fds,
162 * since after all we want to pass these fds to our
164 if ((flags = fcntl(fds[i], F_GETFD, 0)) < 0)
167 if (fcntl(fds[i], F_SETFD, flags &~FD_CLOEXEC) < 0)
174 static int replace_null_fd(int fd, int flags) {
180 if ((nfd = open("/dev/null", flags|O_NOCTTY)) < 0)
184 close_nointr_nofail(nfd);
191 static int setup_output(const ExecContext *context, const char *ident) {
196 switch (context->output) {
198 case EXEC_OUTPUT_CONSOLE:
201 case EXEC_OUTPUT_NULL:
203 if ((r = replace_null_fd(STDOUT_FILENO, O_WRONLY)) < 0 ||
204 (r = replace_null_fd(STDERR_FILENO, O_WRONLY)) < 0)
209 case EXEC_OUTPUT_KERNEL:
210 case EXEC_OUTPUT_SYSLOG: {
215 struct sockaddr_un un;
218 close_nointr(STDOUT_FILENO);
219 close_nointr(STDERR_FILENO);
221 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
224 if (fd != STDOUT_FILENO) {
225 close_nointr_nofail(fd);
230 sa.sa.sa_family = AF_UNIX;
231 strncpy(sa.un.sun_path+1, LOGGER_SOCKET, sizeof(sa.un.sun_path)-1);
233 if (connect(fd, &sa.sa, sizeof(sa)) < 0) {
234 close_nointr_nofail(fd);
238 if (shutdown(fd, SHUT_RD) < 0) {
239 close_nointr_nofail(fd);
243 if ((fd = dup(fd)) < 0) {
244 close_nointr_nofail(fd);
248 if (fd != STDERR_FILENO) {
249 close_nointr_nofail(fd);
253 /* We speak a very simple protocol between log server
254 * and client: one line for the log destination (kmsg
255 * or syslog), followed by the priority field,
256 * followed by the process name. Since we replaced
257 * stdin/stderr we simple use stdio to write to
258 * it. Note that we use stderr, to minimize buffer
259 * flushing issues. */
265 context->output == EXEC_OUTPUT_KERNEL ? "kmsg" : "syslog",
266 context->syslog_priority,
267 context->syslog_identifier ? context->syslog_identifier : ident);
273 assert_not_reached("Unknown output type");
277 static int setup_input(const ExecContext *context) {
282 switch (context->input) {
284 case EXEC_INPUT_CONSOLE:
287 case EXEC_INPUT_NULL:
288 if ((r = replace_null_fd(STDIN_FILENO, O_RDONLY)) < 0)
294 assert_not_reached("Unknown input type");
298 static int get_group_creds(const char *groupname, gid_t *gid) {
305 /* We enforce some special rules for gid=0: in order to avoid
306 * NSS lookups for root we hardcode its data. */
308 if (streq(groupname, "root") || streq(groupname, "0")) {
313 if (safe_atolu(groupname, &lu) >= 0) {
315 g = getgrgid((gid_t) lu);
318 g = getgrnam(groupname);
322 return errno != 0 ? -errno : -ESRCH;
328 static int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
338 /* We enforce some special rules for uid=0: in order to avoid
339 * NSS lookups for root we hardcode its data. */
341 if (streq(*username, "root") || streq(*username, "0")) {
349 if (safe_atolu(*username, &lu) >= 0) {
351 p = getpwuid((uid_t) lu);
353 /* If there are multiple users with the same id, make
354 * sure to leave $USER to the configured value instead
355 * of the first occurence in the database. However if
356 * the uid was configured by a numeric uid, then let's
357 * pick the real username from /etc/passwd. */
359 *username = p->pw_name;
362 p = getpwnam(*username);
366 return errno != 0 ? -errno : -ESRCH;
374 static int enforce_groups(const ExecContext *context, const char *username, gid_t gid) {
375 bool keep_groups = false;
380 /* Lookup and ser GID and supplementary group list. Here too
381 * we avoid NSS lookups for gid=0. */
383 if (context->group || username) {
386 if ((r = get_group_creds(context->group, &gid)) < 0)
389 /* First step, initialize groups from /etc/groups */
390 if (username && gid != 0) {
391 if (initgroups(username, gid) < 0)
397 /* Second step, set our gids */
398 if (setresgid(gid, gid, gid) < 0)
402 if (context->supplementary_groups) {
407 /* Final step, initialize any manually set supplementary groups */
408 ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
410 if (!(gids = new(gid_t, ngroups_max)))
414 if ((k = getgroups(ngroups_max, gids)) < 0) {
421 STRV_FOREACH(i, context->supplementary_groups) {
423 if (k >= ngroups_max) {
428 if ((r = get_group_creds(*i, gids+k)) < 0) {
436 if (setgroups(k, gids) < 0) {
447 static int enforce_user(const ExecContext *context, uid_t uid) {
451 /* Sets (but doesn't lookup) the uid and make sure we keep the
452 * capabilities while doing so. */
454 if (context->capabilities) {
456 static const cap_value_t bits[] = {
457 CAP_SETUID, /* Necessary so that we can run setresuid() below */
458 CAP_SETPCAP /* Necessary so that we can set PR_SET_SECUREBITS later on */
461 /* First step: If we need to keep capabilities but
462 * drop privileges we need to make sure we keep our
463 * caps, whiel we drop priviliges. */
465 if (prctl(PR_SET_SECUREBITS, context->secure_bits|SECURE_KEEP_CAPS) < 0)
468 /* Second step: set the capabilites. This will reduce
469 * the capabilities to the minimum we need. */
471 if (!(d = cap_dup(context->capabilities)))
474 if (cap_set_flag(d, CAP_EFFECTIVE, ELEMENTSOF(bits), bits, CAP_SET) < 0 ||
475 cap_set_flag(d, CAP_PERMITTED, ELEMENTSOF(bits), bits, CAP_SET) < 0) {
481 if (cap_set_proc(d) < 0) {
490 /* Third step: actually set the uids */
491 if (setresuid(uid, uid, uid) < 0)
494 /* At this point we should have all necessary capabilities but
495 are otherwise a normal user. However, the caps might got
496 corrupted due to the setresuid() so we need clean them up
497 later. This is done outside of this call. */
502 int exec_spawn(const ExecCommand *command,
503 const ExecContext *context,
504 int *fds, unsigned n_fds,
505 bool apply_permissions,
514 assert(fds || n_fds <= 0);
516 log_debug("About to execute %s", command->path);
518 if ((pid = fork()) < 0)
524 const char *username = NULL, *home = NULL;
525 uid_t uid = (uid_t) -1;
526 gid_t gid = (gid_t) -1;
527 char **our_env = NULL, **final_env = NULL;
532 if (sigemptyset(&ss) < 0 ||
533 sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
534 r = EXIT_SIGNAL_MASK;
538 if (setpgid(0, 0) < 0) {
543 umask(context->umask);
545 if (setup_input(context) < 0) {
550 if (setup_output(context, file_name_from_path(command->path)) < 0) {
555 if (context->oom_adjust_set) {
558 snprintf(t, sizeof(t), "%i", context->oom_adjust);
561 if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
567 if (context->nice_set)
568 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
573 if (context->cpu_sched_set) {
574 struct sched_param param;
577 param.sched_priority = context->cpu_sched_priority;
579 if (sched_setscheduler(0, context->cpu_sched_policy |
580 (context->cpu_sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0), ¶m) < 0) {
581 r = EXIT_SETSCHEDULER;
586 if (context->cpu_affinity_set)
587 if (sched_setaffinity(0, sizeof(context->cpu_affinity), &context->cpu_affinity) < 0) {
588 r = EXIT_CPUAFFINITY;
592 if (context->ioprio_set)
593 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
598 if (context->timer_slack_ns_set)
599 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_ns_set) < 0) {
605 username = context->user;
606 if (get_user_creds(&username, &uid, &gid, &home) < 0) {
612 if (apply_permissions)
613 if (enforce_groups(context, username, uid) < 0) {
619 if (context->root_directory)
620 if (chroot(context->root_directory) < 0) {
625 if (chdir(context->working_directory ? context->working_directory : "/") < 0) {
633 if (asprintf(&d, "%s/%s",
634 context->root_directory ? context->root_directory : "",
635 context->working_directory ? context->working_directory : "") < 0) {
649 if (close_fds(fds, n_fds) < 0 ||
650 shift_fds(fds, n_fds) < 0 ||
651 flags_fds(fds, n_fds, context->non_blocking) < 0) {
656 if (apply_permissions) {
658 for (i = 0; i < RLIMIT_NLIMITS; i++) {
659 if (!context->rlimit[i])
662 if (setrlimit(i, context->rlimit[i]) < 0) {
669 if (enforce_user(context, uid) < 0) {
674 if (prctl(PR_SET_SECUREBITS, context->secure_bits) < 0) {
679 if (context->capabilities)
680 if (cap_set_proc(context->capabilities) < 0) {
681 r = EXIT_CAPABILITIES;
686 if (!(our_env = new0(char*, 6))) {
692 if (asprintf(our_env + n_env++, "LISTEN_PID=%llu", (unsigned long long) getpid()) < 0 ||
693 asprintf(our_env + n_env++, "LISTEN_FDS=%u", n_fds) < 0) {
699 if (asprintf(our_env + n_env++, "HOME=%s", home) < 0) {
705 if (asprintf(our_env + n_env++, "LOGNAME=%s", username) < 0 ||
706 asprintf(our_env + n_env++, "USER=%s", username) < 0) {
711 if (!(final_env = strv_env_merge(environ, our_env, context->environment, NULL))) {
716 execve(command->path, command->argv, final_env);
721 strv_free(final_env);
727 log_debug("Forked %s as %llu", command->path, (unsigned long long) pid);
733 void exec_context_init(ExecContext *c) {
738 c->oom_adjust_set = false;
741 c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
742 c->ioprio_set = false;
743 c->cpu_sched_policy = SCHED_OTHER;
744 c->cpu_sched_priority = 0;
745 c->cpu_sched_set = false;
746 CPU_ZERO(&c->cpu_affinity);
747 c->cpu_affinity_set = false;
751 c->syslog_priority = LOG_DAEMON|LOG_INFO;
754 c->capability_bounding_set_drop = 0;
757 void exec_context_done(ExecContext *c) {
762 strv_free(c->environment);
763 c->environment = NULL;
765 for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
770 free(c->working_directory);
771 c->working_directory = NULL;
772 free(c->root_directory);
773 c->root_directory = NULL;
775 free(c->syslog_identifier);
776 c->syslog_identifier = NULL;
784 strv_free(c->supplementary_groups);
785 c->supplementary_groups = NULL;
787 if (c->capabilities) {
788 cap_free(c->capabilities);
789 c->capabilities = NULL;
793 void exec_command_free_list(ExecCommand *c) {
797 LIST_REMOVE(ExecCommand, command, c, i);
805 void exec_command_free_array(ExecCommand **c, unsigned n) {
808 for (i = 0; i < n; i++) {
809 exec_command_free_list(c[i]);
814 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
826 "%sWorkingDirectory: %s\n"
827 "%sRootDirectory: %s\n"
828 "%sNonBlocking: %s\n",
830 prefix, c->working_directory ? c->working_directory : "/",
831 prefix, c->root_directory ? c->root_directory : "/",
832 prefix, yes_no(c->non_blocking));
835 for (e = c->environment; *e; e++)
836 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
843 if (c->oom_adjust_set)
846 prefix, c->oom_adjust);
848 for (i = 0; i < RLIM_NLIMITS; i++)
850 fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
854 "%sIOSchedulingClass: %s\n"
855 "%sIOPriority: %i\n",
856 prefix, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c->ioprio)),
857 prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
859 if (c->cpu_sched_set)
861 "%sCPUSchedulingPolicy: %s\n"
862 "%sCPUSchedulingPriority: %i\n"
863 "%sCPUSchedulingResetOnFork: %s\n",
864 prefix, sched_policy_to_string(c->cpu_sched_policy),
865 prefix, c->cpu_sched_priority,
866 prefix, yes_no(c->cpu_sched_reset_on_fork));
868 if (c->cpu_affinity_set) {
869 fprintf(f, "%sCPUAffinity:", prefix);
870 for (i = 0; i < CPU_SETSIZE; i++)
871 if (CPU_ISSET(i, &c->cpu_affinity))
872 fprintf(f, " %i", i);
876 if (c->timer_slack_ns_set)
877 fprintf(f, "%sTimerSlackNS: %lu\n", prefix, c->timer_slack_ns);
882 prefix, exec_input_to_string(c->input),
883 prefix, exec_output_to_string(c->output));
885 if (c->output == EXEC_OUTPUT_SYSLOG || c->output == EXEC_OUTPUT_KERNEL)
887 "%sSyslogFacility: %s\n"
888 "%sSyslogLevel: %s\n",
889 prefix, log_facility_to_string(LOG_FAC(c->syslog_priority)),
890 prefix, log_level_to_string(LOG_PRI(c->syslog_priority)));
892 if (c->capabilities) {
894 if ((t = cap_to_text(c->capabilities, NULL))) {
895 fprintf(f, "%sCapabilities: %s\n",
902 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
904 (c->secure_bits & SECURE_KEEP_CAPS) ? " keep-caps" : "",
905 (c->secure_bits & SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
906 (c->secure_bits & SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
907 (c->secure_bits & SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
908 (c->secure_bits & SECURE_NOROOT) ? " noroot" : "",
909 (c->secure_bits & SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
911 if (c->capability_bounding_set_drop) {
912 fprintf(f, "%sCapabilityBoundingSetDrop:", prefix);
914 for (i = 0; i <= CAP_LAST_CAP; i++)
915 if (c->capability_bounding_set_drop & (1 << i)) {
918 if ((t = cap_to_name(i))) {
919 fprintf(f, " %s", t);
928 fprintf(f, "%sUser: %s", prefix, c->user);
930 fprintf(f, "%sGroup: %s", prefix, c->group);
932 if (c->supplementary_groups) {
935 fprintf(f, "%sSupplementaryGroups:", prefix);
937 STRV_FOREACH(g, c->supplementary_groups)
938 fprintf(f, " %s", *g);
944 void exec_status_fill(ExecStatus *s, pid_t pid, int code, int status) {
950 s->timestamp = now(CLOCK_REALTIME);
953 char *exec_command_line(ExecCommand *c) {
962 STRV_FOREACH(a, c->argv)
965 if (!(n = new(char, k)))
969 STRV_FOREACH(a, c->argv) {
976 if (strpbrk(*a, WHITESPACE)) {
987 /* FIXME: this doesn't really handle arguments that have
988 * spaces and ticks in them */
993 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
1002 cmd = exec_command_line(c);
1005 "%sCommand Line: %s\n",
1006 prefix, cmd ? cmd : strerror(ENOMEM));
1011 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
1017 LIST_FOREACH(command, c, c)
1018 exec_command_dump(c, f, prefix);
1021 void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
1028 /* It's kinda important that we keep the order here */
1029 LIST_FIND_TAIL(ExecCommand, command, *l, end);
1030 LIST_INSERT_AFTER(ExecCommand, command, *l, end, e);
1035 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
1036 [EXEC_OUTPUT_CONSOLE] = "console",
1037 [EXEC_OUTPUT_NULL] = "null",
1038 [EXEC_OUTPUT_SYSLOG] = "syslog",
1039 [EXEC_OUTPUT_KERNEL] = "kernel"
1042 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
1044 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
1045 [EXEC_INPUT_NULL] = "null",
1046 [EXEC_INPUT_CONSOLE] = "console"
1049 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);