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"
47 static int shift_fds(int fds
[], unsigned n_fds
) {
48 int start
, restart_from
;
53 /* Modifies the fds array! (sorts it) */
63 for (i
= start
; i
< (int) n_fds
; i
++) {
66 /* Already at right index? */
70 if ((nfd
= fcntl(fds
[i
], F_DUPFD
, i
+3)) < 0)
73 assert_se(close_nointr(fds
[i
]) == 0);
76 /* Hmm, the fd we wanted isn't free? Then
77 * let's remember that and try again from here*/
78 if (nfd
!= i
+3 && restart_from
< 0)
91 static int flags_fds(int fds
[], unsigned n_fds
, bool nonblock
) {
100 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
102 for (i
= 0; i
< n_fds
; i
++) {
104 if ((r
= fd_nonblock(fds
[i
], nonblock
)) < 0)
107 /* We unconditionally drop FD_CLOEXEC from the fds,
108 * since after all we want to pass these fds to our
111 if ((r
= fd_cloexec(fds
[i
], false)) < 0)
118 static int replace_null_fd(int fd
, int flags
) {
124 if ((nfd
= open("/dev/null", flags
|O_NOCTTY
)) < 0)
128 close_nointr_nofail(nfd
);
135 static int setup_output(const ExecContext
*context
, const char *ident
) {
140 switch (context
->output
) {
142 case EXEC_OUTPUT_CONSOLE
:
145 case EXEC_OUTPUT_NULL
:
147 if ((r
= replace_null_fd(STDOUT_FILENO
, O_WRONLY
)) < 0 ||
148 (r
= replace_null_fd(STDERR_FILENO
, O_WRONLY
)) < 0)
153 case EXEC_OUTPUT_KERNEL
:
154 case EXEC_OUTPUT_SYSLOG
: {
159 struct sockaddr_un un
;
162 close_nointr(STDOUT_FILENO
);
163 close_nointr(STDERR_FILENO
);
165 if ((fd
= socket(AF_UNIX
, SOCK_STREAM
, 0)) < 0)
168 if (fd
!= STDOUT_FILENO
) {
169 close_nointr_nofail(fd
);
174 sa
.sa
.sa_family
= AF_UNIX
;
175 strncpy(sa
.un
.sun_path
+1, LOGGER_SOCKET
, sizeof(sa
.un
.sun_path
)-1);
177 if (connect(fd
, &sa
.sa
, sizeof(sa
)) < 0) {
178 close_nointr_nofail(fd
);
182 if (shutdown(fd
, SHUT_RD
) < 0) {
183 close_nointr_nofail(fd
);
187 if ((fd
= dup(fd
)) < 0) {
188 close_nointr_nofail(fd
);
192 if (fd
!= STDERR_FILENO
) {
193 close_nointr_nofail(fd
);
197 /* We speak a very simple protocol between log server
198 * and client: one line for the log destination (kmsg
199 * or syslog), followed by the priority field,
200 * followed by the process name. Since we replaced
201 * stdin/stderr we simple use stdio to write to
202 * it. Note that we use stderr, to minimize buffer
203 * flushing issues. */
209 context
->output
== EXEC_OUTPUT_KERNEL
? "kmsg" : "syslog",
210 context
->syslog_priority
,
211 context
->syslog_identifier
? context
->syslog_identifier
: ident
);
217 assert_not_reached("Unknown output type");
221 static int setup_input(const ExecContext
*context
) {
226 switch (context
->input
) {
228 case EXEC_INPUT_CONSOLE
:
231 case EXEC_INPUT_NULL
:
232 if ((r
= replace_null_fd(STDIN_FILENO
, O_RDONLY
)) < 0)
238 assert_not_reached("Unknown input type");
242 static int get_group_creds(const char *groupname
, gid_t
*gid
) {
249 /* We enforce some special rules for gid=0: in order to avoid
250 * NSS lookups for root we hardcode its data. */
252 if (streq(groupname
, "root") || streq(groupname
, "0")) {
257 if (safe_atolu(groupname
, &lu
) >= 0) {
259 g
= getgrgid((gid_t
) lu
);
262 g
= getgrnam(groupname
);
266 return errno
!= 0 ? -errno
: -ESRCH
;
272 static int get_user_creds(const char **username
, uid_t
*uid
, gid_t
*gid
, const char **home
) {
282 /* We enforce some special rules for uid=0: in order to avoid
283 * NSS lookups for root we hardcode its data. */
285 if (streq(*username
, "root") || streq(*username
, "0")) {
293 if (safe_atolu(*username
, &lu
) >= 0) {
295 p
= getpwuid((uid_t
) lu
);
297 /* If there are multiple users with the same id, make
298 * sure to leave $USER to the configured value instead
299 * of the first occurence in the database. However if
300 * the uid was configured by a numeric uid, then let's
301 * pick the real username from /etc/passwd. */
303 *username
= p
->pw_name
;
306 p
= getpwnam(*username
);
310 return errno
!= 0 ? -errno
: -ESRCH
;
318 static int enforce_groups(const ExecContext
*context
, const char *username
, gid_t gid
) {
319 bool keep_groups
= false;
324 /* Lookup and ser GID and supplementary group list. Here too
325 * we avoid NSS lookups for gid=0. */
327 if (context
->group
|| username
) {
330 if ((r
= get_group_creds(context
->group
, &gid
)) < 0)
333 /* First step, initialize groups from /etc/groups */
334 if (username
&& gid
!= 0) {
335 if (initgroups(username
, gid
) < 0)
341 /* Second step, set our gids */
342 if (setresgid(gid
, gid
, gid
) < 0)
346 if (context
->supplementary_groups
) {
351 /* Final step, initialize any manually set supplementary groups */
352 ngroups_max
= (int) sysconf(_SC_NGROUPS_MAX
);
354 if (!(gids
= new(gid_t
, ngroups_max
)))
358 if ((k
= getgroups(ngroups_max
, gids
)) < 0) {
365 STRV_FOREACH(i
, context
->supplementary_groups
) {
367 if (k
>= ngroups_max
) {
372 if ((r
= get_group_creds(*i
, gids
+k
)) < 0) {
380 if (setgroups(k
, gids
) < 0) {
391 static int enforce_user(const ExecContext
*context
, uid_t uid
) {
395 /* Sets (but doesn't lookup) the uid and make sure we keep the
396 * capabilities while doing so. */
398 if (context
->capabilities
) {
400 static const cap_value_t bits
[] = {
401 CAP_SETUID
, /* Necessary so that we can run setresuid() below */
402 CAP_SETPCAP
/* Necessary so that we can set PR_SET_SECUREBITS later on */
405 /* First step: If we need to keep capabilities but
406 * drop privileges we need to make sure we keep our
407 * caps, whiel we drop priviliges. */
409 int sb
= context
->secure_bits
|SECURE_KEEP_CAPS
;
411 if (prctl(PR_GET_SECUREBITS
) != sb
)
412 if (prctl(PR_SET_SECUREBITS
, sb
) < 0)
416 /* Second step: set the capabilites. This will reduce
417 * the capabilities to the minimum we need. */
419 if (!(d
= cap_dup(context
->capabilities
)))
422 if (cap_set_flag(d
, CAP_EFFECTIVE
, ELEMENTSOF(bits
), bits
, CAP_SET
) < 0 ||
423 cap_set_flag(d
, CAP_PERMITTED
, ELEMENTSOF(bits
), bits
, CAP_SET
) < 0) {
429 if (cap_set_proc(d
) < 0) {
438 /* Third step: actually set the uids */
439 if (setresuid(uid
, uid
, uid
) < 0)
442 /* At this point we should have all necessary capabilities but
443 are otherwise a normal user. However, the caps might got
444 corrupted due to the setresuid() so we need clean them up
445 later. This is done outside of this call. */
450 int exec_spawn(ExecCommand
*command
,
451 const ExecContext
*context
,
452 int *fds
, unsigned n_fds
,
453 bool apply_permissions
,
455 CGroupBonding
*cgroup_bondings
,
464 assert(fds
|| n_fds
<= 0);
466 log_debug("About to execute %s", command
->path
);
469 if ((r
= cgroup_bonding_realize_list(cgroup_bondings
)))
472 if ((pid
= fork()) < 0)
478 const char *username
= NULL
, *home
= NULL
;
479 uid_t uid
= (uid_t
) -1;
480 gid_t gid
= (gid_t
) -1;
481 char **our_env
= NULL
, **final_env
= NULL
;
486 if (sigemptyset(&ss
) < 0 ||
487 sigprocmask(SIG_SETMASK
, &ss
, NULL
) < 0) {
488 r
= EXIT_SIGNAL_MASK
;
492 if (context
->new_session
) {
498 if (setpgid(0, 0) < 0) {
504 umask(context
->umask
);
506 if (setup_input(context
) < 0) {
511 if (setup_output(context
, file_name_from_path(command
->path
)) < 0) {
517 if ((r
= cgroup_bonding_install_list(cgroup_bondings
, 0)) < 0) {
522 if (context
->oom_adjust_set
) {
525 snprintf(t
, sizeof(t
), "%i", context
->oom_adjust
);
528 if (write_one_line_file("/proc/self/oom_adj", t
) < 0) {
534 if (context
->nice_set
)
535 if (setpriority(PRIO_PROCESS
, 0, context
->nice
) < 0) {
540 if (context
->cpu_sched_set
) {
541 struct sched_param param
;
544 param
.sched_priority
= context
->cpu_sched_priority
;
546 if (sched_setscheduler(0, context
->cpu_sched_policy
|
547 (context
->cpu_sched_reset_on_fork
? SCHED_RESET_ON_FORK
: 0), ¶m
) < 0) {
548 r
= EXIT_SETSCHEDULER
;
553 if (context
->cpu_affinity_set
)
554 if (sched_setaffinity(0, sizeof(context
->cpu_affinity
), &context
->cpu_affinity
) < 0) {
555 r
= EXIT_CPUAFFINITY
;
559 if (context
->ioprio_set
)
560 if (ioprio_set(IOPRIO_WHO_PROCESS
, 0, context
->ioprio
) < 0) {
565 if (context
->timer_slack_ns_set
)
566 if (prctl(PR_SET_TIMERSLACK
, context
->timer_slack_ns_set
) < 0) {
572 username
= context
->user
;
573 if (get_user_creds(&username
, &uid
, &gid
, &home
) < 0) {
579 if (apply_permissions
)
580 if (enforce_groups(context
, username
, uid
) < 0) {
586 if (context
->root_directory
)
587 if (chroot(context
->root_directory
) < 0) {
592 if (chdir(context
->working_directory
? context
->working_directory
: "/") < 0) {
600 if (asprintf(&d
, "%s/%s",
601 context
->root_directory
? context
->root_directory
: "",
602 context
->working_directory
? context
->working_directory
: "") < 0) {
616 if (close_all_fds(fds
, n_fds
) < 0 ||
617 shift_fds(fds
, n_fds
) < 0 ||
618 flags_fds(fds
, n_fds
, context
->non_blocking
) < 0) {
623 if (apply_permissions
) {
625 for (i
= 0; i
< RLIMIT_NLIMITS
; i
++) {
626 if (!context
->rlimit
[i
])
629 if (setrlimit(i
, context
->rlimit
[i
]) < 0) {
636 if (enforce_user(context
, uid
) < 0) {
641 /* PR_GET_SECUREBITS is not priviliged, while
642 * PR_SET_SECUREBITS is. So to suppress
643 * potential EPERMs we'll try not to call
644 * PR_SET_SECUREBITS unless necessary. */
645 if (prctl(PR_GET_SECUREBITS
) != context
->secure_bits
)
646 if (prctl(PR_SET_SECUREBITS
, context
->secure_bits
) < 0) {
651 if (context
->capabilities
)
652 if (cap_set_proc(context
->capabilities
) < 0) {
653 r
= EXIT_CAPABILITIES
;
658 if (!(our_env
= new0(char*, 6))) {
664 if (asprintf(our_env
+ n_env
++, "LISTEN_PID=%llu", (unsigned long long) getpid()) < 0 ||
665 asprintf(our_env
+ n_env
++, "LISTEN_FDS=%u", n_fds
) < 0) {
671 if (asprintf(our_env
+ n_env
++, "HOME=%s", home
) < 0) {
677 if (asprintf(our_env
+ n_env
++, "LOGNAME=%s", username
) < 0 ||
678 asprintf(our_env
+ n_env
++, "USER=%s", username
) < 0) {
683 if (!(final_env
= strv_env_merge(environ
, our_env
, context
->environment
, NULL
))) {
688 execve(command
->path
, command
->argv
, final_env
);
693 strv_free(final_env
);
699 log_debug("Forked %s as %llu", command
->path
, (unsigned long long) pid
);
701 command
->exec_status
.pid
= pid
;
702 command
->exec_status
.start_timestamp
= now(CLOCK_REALTIME
);
708 void exec_context_init(ExecContext
*c
) {
713 c
->oom_adjust_set
= false;
716 c
->ioprio
= IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE
, 0);
717 c
->ioprio_set
= false;
718 c
->cpu_sched_policy
= SCHED_OTHER
;
719 c
->cpu_sched_priority
= 0;
720 c
->cpu_sched_set
= false;
721 CPU_ZERO(&c
->cpu_affinity
);
722 c
->cpu_affinity_set
= false;
723 c
->timer_slack_ns
= 0;
724 c
->timer_slack_ns_set
= false;
726 c
->cpu_sched_reset_on_fork
= false;
727 c
->non_blocking
= false;
728 c
->new_session
= false;
732 c
->syslog_priority
= LOG_DAEMON
|LOG_INFO
;
735 c
->capability_bounding_set_drop
= 0;
738 void exec_context_done(ExecContext
*c
) {
743 strv_free(c
->environment
);
744 c
->environment
= NULL
;
746 for (l
= 0; l
< ELEMENTSOF(c
->rlimit
); l
++) {
751 free(c
->working_directory
);
752 c
->working_directory
= NULL
;
753 free(c
->root_directory
);
754 c
->root_directory
= NULL
;
756 free(c
->syslog_identifier
);
757 c
->syslog_identifier
= NULL
;
765 strv_free(c
->supplementary_groups
);
766 c
->supplementary_groups
= NULL
;
768 if (c
->capabilities
) {
769 cap_free(c
->capabilities
);
770 c
->capabilities
= NULL
;
774 void exec_command_free_list(ExecCommand
*c
) {
778 LIST_REMOVE(ExecCommand
, command
, c
, i
);
786 void exec_command_free_array(ExecCommand
**c
, unsigned n
) {
789 for (i
= 0; i
< n
; i
++) {
790 exec_command_free_list(c
[i
]);
795 void exec_context_dump(ExecContext
*c
, FILE* f
, const char *prefix
) {
807 "%sWorkingDirectory: %s\n"
808 "%sRootDirectory: %s\n"
809 "%sNonBlocking: %s\n"
810 "%sNewSession: %s\n",
812 prefix
, c
->working_directory
? c
->working_directory
: "/",
813 prefix
, c
->root_directory
? c
->root_directory
: "/",
814 prefix
, yes_no(c
->non_blocking
),
815 prefix
, yes_no(c
->new_session
));
818 for (e
= c
->environment
; *e
; e
++)
819 fprintf(f
, "%sEnvironment: %s\n", prefix
, *e
);
826 if (c
->oom_adjust_set
)
829 prefix
, c
->oom_adjust
);
831 for (i
= 0; i
< RLIM_NLIMITS
; i
++)
833 fprintf(f
, "%s%s: %llu\n", prefix
, rlimit_to_string(i
), (unsigned long long) c
->rlimit
[i
]->rlim_max
);
837 "%sIOSchedulingClass: %s\n"
838 "%sIOPriority: %i\n",
839 prefix
, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c
->ioprio
)),
840 prefix
, (int) IOPRIO_PRIO_DATA(c
->ioprio
));
842 if (c
->cpu_sched_set
)
844 "%sCPUSchedulingPolicy: %s\n"
845 "%sCPUSchedulingPriority: %i\n"
846 "%sCPUSchedulingResetOnFork: %s\n",
847 prefix
, sched_policy_to_string(c
->cpu_sched_policy
),
848 prefix
, c
->cpu_sched_priority
,
849 prefix
, yes_no(c
->cpu_sched_reset_on_fork
));
851 if (c
->cpu_affinity_set
) {
852 fprintf(f
, "%sCPUAffinity:", prefix
);
853 for (i
= 0; i
< CPU_SETSIZE
; i
++)
854 if (CPU_ISSET(i
, &c
->cpu_affinity
))
855 fprintf(f
, " %i", i
);
859 if (c
->timer_slack_ns_set
)
860 fprintf(f
, "%sTimerSlackNS: %lu\n", prefix
, c
->timer_slack_ns
);
865 prefix
, exec_input_to_string(c
->input
),
866 prefix
, exec_output_to_string(c
->output
));
868 if (c
->output
== EXEC_OUTPUT_SYSLOG
|| c
->output
== EXEC_OUTPUT_KERNEL
)
870 "%sSyslogFacility: %s\n"
871 "%sSyslogLevel: %s\n",
872 prefix
, log_facility_to_string(LOG_FAC(c
->syslog_priority
)),
873 prefix
, log_level_to_string(LOG_PRI(c
->syslog_priority
)));
875 if (c
->capabilities
) {
877 if ((t
= cap_to_text(c
->capabilities
, NULL
))) {
878 fprintf(f
, "%sCapabilities: %s\n",
885 fprintf(f
, "%sSecure Bits:%s%s%s%s%s%s\n",
887 (c
->secure_bits
& SECURE_KEEP_CAPS
) ? " keep-caps" : "",
888 (c
->secure_bits
& SECURE_KEEP_CAPS_LOCKED
) ? " keep-caps-locked" : "",
889 (c
->secure_bits
& SECURE_NO_SETUID_FIXUP
) ? " no-setuid-fixup" : "",
890 (c
->secure_bits
& SECURE_NO_SETUID_FIXUP_LOCKED
) ? " no-setuid-fixup-locked" : "",
891 (c
->secure_bits
& SECURE_NOROOT
) ? " noroot" : "",
892 (c
->secure_bits
& SECURE_NOROOT_LOCKED
) ? "noroot-locked" : "");
894 if (c
->capability_bounding_set_drop
) {
895 fprintf(f
, "%sCapabilityBoundingSetDrop:", prefix
);
897 for (i
= 0; i
<= CAP_LAST_CAP
; i
++)
898 if (c
->capability_bounding_set_drop
& (1 << i
)) {
901 if ((t
= cap_to_name(i
))) {
902 fprintf(f
, " %s", t
);
911 fprintf(f
, "%sUser: %s", prefix
, c
->user
);
913 fprintf(f
, "%sGroup: %s", prefix
, c
->group
);
915 if (c
->supplementary_groups
) {
918 fprintf(f
, "%sSupplementaryGroups:", prefix
);
920 STRV_FOREACH(g
, c
->supplementary_groups
)
921 fprintf(f
, " %s", *g
);
927 void exec_status_fill(ExecStatus
*s
, pid_t pid
, int code
, int status
) {
931 s
->exit_timestamp
= now(CLOCK_REALTIME
);
937 void exec_status_dump(ExecStatus
*s
, FILE *f
, const char *prefix
) {
938 char buf
[FORMAT_TIMESTAMP_MAX
];
951 prefix
, (unsigned long long) s
->pid
);
953 if (s
->start_timestamp
> 0)
955 "%sStart Timestamp: %s\n",
956 prefix
, format_timestamp(buf
, sizeof(buf
), s
->start_timestamp
));
958 if (s
->exit_timestamp
> 0)
960 "%sExit Timestamp: %s\n"
962 "%sExit Status: %i\n",
963 prefix
, format_timestamp(buf
, sizeof(buf
), s
->exit_timestamp
),
964 prefix
, sigchld_code_to_string(s
->code
),
968 char *exec_command_line(ExecCommand
*c
) {
977 STRV_FOREACH(a
, c
->argv
)
980 if (!(n
= new(char, k
)))
984 STRV_FOREACH(a
, c
->argv
) {
991 if (strpbrk(*a
, WHITESPACE
)) {
1002 /* FIXME: this doesn't really handle arguments that have
1003 * spaces and ticks in them */
1008 void exec_command_dump(ExecCommand
*c
, FILE *f
, const char *prefix
) {
1010 const char *prefix2
;
1019 p2
= strappend(prefix
, "\t");
1020 prefix2
= p2
? p2
: prefix
;
1022 cmd
= exec_command_line(c
);
1025 "%sCommand Line: %s\n",
1026 prefix
, cmd
? cmd
: strerror(ENOMEM
));
1030 exec_status_dump(&c
->exec_status
, f
, prefix2
);
1035 void exec_command_dump_list(ExecCommand
*c
, FILE *f
, const char *prefix
) {
1041 LIST_FOREACH(command
, c
, c
)
1042 exec_command_dump(c
, f
, prefix
);
1045 void exec_command_append_list(ExecCommand
**l
, ExecCommand
*e
) {
1052 /* It's kinda important that we keep the order here */
1053 LIST_FIND_TAIL(ExecCommand
, command
, *l
, end
);
1054 LIST_INSERT_AFTER(ExecCommand
, command
, *l
, end
, e
);
1059 static const char* const exec_output_table
[_EXEC_OUTPUT_MAX
] = {
1060 [EXEC_OUTPUT_CONSOLE
] = "console",
1061 [EXEC_OUTPUT_NULL
] = "null",
1062 [EXEC_OUTPUT_SYSLOG
] = "syslog",
1063 [EXEC_OUTPUT_KERNEL
] = "kernel"
1066 DEFINE_STRING_TABLE_LOOKUP(exec_output
, ExecOutput
);
1068 static const char* const exec_input_table
[_EXEC_INPUT_MAX
] = {
1069 [EXEC_INPUT_NULL
] = "null",
1070 [EXEC_INPUT_CONSOLE
] = "console"
1073 DEFINE_STRING_TABLE_LOOKUP(exec_input
, ExecInput
);