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 int sb = context->secure_bits|SECURE_KEEP_CAPS;
467 if (prctl(PR_GET_SECUREBITS) != sb)
468 if (prctl(PR_SET_SECUREBITS, sb) < 0)
472 /* Second step: set the capabilites. This will reduce
473 * the capabilities to the minimum we need. */
475 if (!(d = cap_dup(context->capabilities)))
478 if (cap_set_flag(d, CAP_EFFECTIVE, ELEMENTSOF(bits), bits, CAP_SET) < 0 ||
479 cap_set_flag(d, CAP_PERMITTED, ELEMENTSOF(bits), bits, CAP_SET) < 0) {
485 if (cap_set_proc(d) < 0) {
494 /* Third step: actually set the uids */
495 if (setresuid(uid, uid, uid) < 0)
498 /* At this point we should have all necessary capabilities but
499 are otherwise a normal user. However, the caps might got
500 corrupted due to the setresuid() so we need clean them up
501 later. This is done outside of this call. */
506 int exec_spawn(const ExecCommand *command,
507 const ExecContext *context,
508 int *fds, unsigned n_fds,
509 bool apply_permissions,
518 assert(fds || n_fds <= 0);
520 log_debug("About to execute %s", command->path);
522 if ((pid = fork()) < 0)
528 const char *username = NULL, *home = NULL;
529 uid_t uid = (uid_t) -1;
530 gid_t gid = (gid_t) -1;
531 char **our_env = NULL, **final_env = NULL;
536 if (sigemptyset(&ss) < 0 ||
537 sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
538 r = EXIT_SIGNAL_MASK;
542 if (setpgid(0, 0) < 0) {
547 umask(context->umask);
549 if (setup_input(context) < 0) {
554 if (setup_output(context, file_name_from_path(command->path)) < 0) {
559 if (context->oom_adjust_set) {
562 snprintf(t, sizeof(t), "%i", context->oom_adjust);
565 if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
571 if (context->nice_set)
572 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
577 if (context->cpu_sched_set) {
578 struct sched_param param;
581 param.sched_priority = context->cpu_sched_priority;
583 if (sched_setscheduler(0, context->cpu_sched_policy |
584 (context->cpu_sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0), ¶m) < 0) {
585 r = EXIT_SETSCHEDULER;
590 if (context->cpu_affinity_set)
591 if (sched_setaffinity(0, sizeof(context->cpu_affinity), &context->cpu_affinity) < 0) {
592 r = EXIT_CPUAFFINITY;
596 if (context->ioprio_set)
597 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
602 if (context->timer_slack_ns_set)
603 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_ns_set) < 0) {
609 username = context->user;
610 if (get_user_creds(&username, &uid, &gid, &home) < 0) {
616 if (apply_permissions)
617 if (enforce_groups(context, username, uid) < 0) {
623 if (context->root_directory)
624 if (chroot(context->root_directory) < 0) {
629 if (chdir(context->working_directory ? context->working_directory : "/") < 0) {
637 if (asprintf(&d, "%s/%s",
638 context->root_directory ? context->root_directory : "",
639 context->working_directory ? context->working_directory : "") < 0) {
653 if (close_fds(fds, n_fds) < 0 ||
654 shift_fds(fds, n_fds) < 0 ||
655 flags_fds(fds, n_fds, context->non_blocking) < 0) {
660 if (apply_permissions) {
662 for (i = 0; i < RLIMIT_NLIMITS; i++) {
663 if (!context->rlimit[i])
666 if (setrlimit(i, context->rlimit[i]) < 0) {
673 if (enforce_user(context, uid) < 0) {
678 /* PR_GET_SECUREBITS is not priviliged, while
679 * PR_SET_SECUREBITS is. So to suppress
680 * potential EPERMs we'll try not to call
681 * PR_SET_SECUREBITS unless necessary. */
682 if (prctl(PR_GET_SECUREBITS) != context->secure_bits)
683 if (prctl(PR_SET_SECUREBITS, context->secure_bits) < 0) {
688 if (context->capabilities)
689 if (cap_set_proc(context->capabilities) < 0) {
690 r = EXIT_CAPABILITIES;
695 if (!(our_env = new0(char*, 6))) {
701 if (asprintf(our_env + n_env++, "LISTEN_PID=%llu", (unsigned long long) getpid()) < 0 ||
702 asprintf(our_env + n_env++, "LISTEN_FDS=%u", n_fds) < 0) {
708 if (asprintf(our_env + n_env++, "HOME=%s", home) < 0) {
714 if (asprintf(our_env + n_env++, "LOGNAME=%s", username) < 0 ||
715 asprintf(our_env + n_env++, "USER=%s", username) < 0) {
720 if (!(final_env = strv_env_merge(environ, our_env, context->environment, NULL))) {
725 execve(command->path, command->argv, final_env);
730 strv_free(final_env);
736 log_debug("Forked %s as %llu", command->path, (unsigned long long) pid);
742 void exec_context_init(ExecContext *c) {
747 c->oom_adjust_set = false;
750 c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
751 c->ioprio_set = false;
752 c->cpu_sched_policy = SCHED_OTHER;
753 c->cpu_sched_priority = 0;
754 c->cpu_sched_set = false;
755 CPU_ZERO(&c->cpu_affinity);
756 c->cpu_affinity_set = false;
760 c->syslog_priority = LOG_DAEMON|LOG_INFO;
763 c->capability_bounding_set_drop = 0;
766 void exec_context_done(ExecContext *c) {
771 strv_free(c->environment);
772 c->environment = NULL;
774 for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
779 free(c->working_directory);
780 c->working_directory = NULL;
781 free(c->root_directory);
782 c->root_directory = NULL;
784 free(c->syslog_identifier);
785 c->syslog_identifier = NULL;
793 strv_free(c->supplementary_groups);
794 c->supplementary_groups = NULL;
796 if (c->capabilities) {
797 cap_free(c->capabilities);
798 c->capabilities = NULL;
802 void exec_command_free_list(ExecCommand *c) {
806 LIST_REMOVE(ExecCommand, command, c, i);
814 void exec_command_free_array(ExecCommand **c, unsigned n) {
817 for (i = 0; i < n; i++) {
818 exec_command_free_list(c[i]);
823 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
835 "%sWorkingDirectory: %s\n"
836 "%sRootDirectory: %s\n"
837 "%sNonBlocking: %s\n",
839 prefix, c->working_directory ? c->working_directory : "/",
840 prefix, c->root_directory ? c->root_directory : "/",
841 prefix, yes_no(c->non_blocking));
844 for (e = c->environment; *e; e++)
845 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
852 if (c->oom_adjust_set)
855 prefix, c->oom_adjust);
857 for (i = 0; i < RLIM_NLIMITS; i++)
859 fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
863 "%sIOSchedulingClass: %s\n"
864 "%sIOPriority: %i\n",
865 prefix, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c->ioprio)),
866 prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
868 if (c->cpu_sched_set)
870 "%sCPUSchedulingPolicy: %s\n"
871 "%sCPUSchedulingPriority: %i\n"
872 "%sCPUSchedulingResetOnFork: %s\n",
873 prefix, sched_policy_to_string(c->cpu_sched_policy),
874 prefix, c->cpu_sched_priority,
875 prefix, yes_no(c->cpu_sched_reset_on_fork));
877 if (c->cpu_affinity_set) {
878 fprintf(f, "%sCPUAffinity:", prefix);
879 for (i = 0; i < CPU_SETSIZE; i++)
880 if (CPU_ISSET(i, &c->cpu_affinity))
881 fprintf(f, " %i", i);
885 if (c->timer_slack_ns_set)
886 fprintf(f, "%sTimerSlackNS: %lu\n", prefix, c->timer_slack_ns);
891 prefix, exec_input_to_string(c->input),
892 prefix, exec_output_to_string(c->output));
894 if (c->output == EXEC_OUTPUT_SYSLOG || c->output == EXEC_OUTPUT_KERNEL)
896 "%sSyslogFacility: %s\n"
897 "%sSyslogLevel: %s\n",
898 prefix, log_facility_to_string(LOG_FAC(c->syslog_priority)),
899 prefix, log_level_to_string(LOG_PRI(c->syslog_priority)));
901 if (c->capabilities) {
903 if ((t = cap_to_text(c->capabilities, NULL))) {
904 fprintf(f, "%sCapabilities: %s\n",
911 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
913 (c->secure_bits & SECURE_KEEP_CAPS) ? " keep-caps" : "",
914 (c->secure_bits & SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
915 (c->secure_bits & SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
916 (c->secure_bits & SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
917 (c->secure_bits & SECURE_NOROOT) ? " noroot" : "",
918 (c->secure_bits & SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
920 if (c->capability_bounding_set_drop) {
921 fprintf(f, "%sCapabilityBoundingSetDrop:", prefix);
923 for (i = 0; i <= CAP_LAST_CAP; i++)
924 if (c->capability_bounding_set_drop & (1 << i)) {
927 if ((t = cap_to_name(i))) {
928 fprintf(f, " %s", t);
937 fprintf(f, "%sUser: %s", prefix, c->user);
939 fprintf(f, "%sGroup: %s", prefix, c->group);
941 if (c->supplementary_groups) {
944 fprintf(f, "%sSupplementaryGroups:", prefix);
946 STRV_FOREACH(g, c->supplementary_groups)
947 fprintf(f, " %s", *g);
953 void exec_status_fill(ExecStatus *s, pid_t pid, int code, int status) {
959 s->timestamp = now(CLOCK_REALTIME);
962 char *exec_command_line(ExecCommand *c) {
971 STRV_FOREACH(a, c->argv)
974 if (!(n = new(char, k)))
978 STRV_FOREACH(a, c->argv) {
985 if (strpbrk(*a, WHITESPACE)) {
996 /* FIXME: this doesn't really handle arguments that have
997 * spaces and ticks in them */
1002 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
1011 cmd = exec_command_line(c);
1014 "%sCommand Line: %s\n",
1015 prefix, cmd ? cmd : strerror(ENOMEM));
1020 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
1026 LIST_FOREACH(command, c, c)
1027 exec_command_dump(c, f, prefix);
1030 void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
1037 /* It's kinda important that we keep the order here */
1038 LIST_FIND_TAIL(ExecCommand, command, *l, end);
1039 LIST_INSERT_AFTER(ExecCommand, command, *l, end, e);
1044 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
1045 [EXEC_OUTPUT_CONSOLE] = "console",
1046 [EXEC_OUTPUT_NULL] = "null",
1047 [EXEC_OUTPUT_SYSLOG] = "syslog",
1048 [EXEC_OUTPUT_KERNEL] = "kernel"
1051 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
1053 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
1054 [EXEC_INPUT_NULL] = "null",
1055 [EXEC_INPUT_CONSOLE] = "console"
1058 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);