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 close_fds(int except
[], unsigned n_except
) {
52 /* Modifies the fds array! (sorts it) */
54 if (!(d
= opendir("/proc/self/fd")))
57 while ((de
= readdir(d
))) {
60 if (de
->d_name
[0] == '.')
63 if ((r
= safe_atoi(de
->d_name
, &fd
)) < 0)
77 for (i
= 0; i
< n_except
; i
++)
78 if (except
[i
] == fd
) {
87 if ((r
= close_nointr(fd
)) < 0)
96 static int shift_fds(int fds
[], unsigned n_fds
) {
97 int start
, restart_from
;
110 for (i
= start
; i
< (int) n_fds
; i
++) {
113 /* Already at right index? */
117 if ((nfd
= fcntl(fds
[i
], F_DUPFD
, i
+3)) < 0)
120 assert_se(close_nointr(fds
[i
]) == 0);
123 /* Hmm, the fd we wanted isn't free? Then
124 * let's remember that and try again from here*/
125 if (nfd
!= i
+3 && restart_from
< 0)
129 if (restart_from
< 0)
132 start
= restart_from
;
138 static int flags_fds(int fds
[], unsigned n_fds
, bool nonblock
) {
146 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
148 for (i
= 0; i
< n_fds
; i
++) {
151 if ((flags
= fcntl(fds
[i
], F_GETFL
, 0)) < 0)
157 flags
&= ~O_NONBLOCK
;
159 if (fcntl(fds
[i
], F_SETFL
, flags
) < 0)
162 /* We unconditionally drop FD_CLOEXEC from the fds,
163 * since after all we want to pass these fds to our
165 if ((flags
= fcntl(fds
[i
], F_GETFD
, 0)) < 0)
168 if (fcntl(fds
[i
], F_SETFD
, flags
&~FD_CLOEXEC
) < 0)
175 static int replace_null_fd(int fd
, int flags
) {
181 if ((nfd
= open("/dev/null", flags
|O_NOCTTY
)) < 0)
185 close_nointr_nofail(nfd
);
192 static int setup_output(const ExecContext
*context
, const char *ident
) {
197 switch (context
->output
) {
199 case EXEC_OUTPUT_CONSOLE
:
202 case EXEC_OUTPUT_NULL
:
204 if ((r
= replace_null_fd(STDOUT_FILENO
, O_WRONLY
)) < 0 ||
205 (r
= replace_null_fd(STDERR_FILENO
, O_WRONLY
)) < 0)
210 case EXEC_OUTPUT_KERNEL
:
211 case EXEC_OUTPUT_SYSLOG
: {
216 struct sockaddr_un un
;
219 close_nointr(STDOUT_FILENO
);
220 close_nointr(STDERR_FILENO
);
222 if ((fd
= socket(AF_UNIX
, SOCK_STREAM
, 0)) < 0)
225 if (fd
!= STDOUT_FILENO
) {
226 close_nointr_nofail(fd
);
231 sa
.sa
.sa_family
= AF_UNIX
;
232 strncpy(sa
.un
.sun_path
+1, LOGGER_SOCKET
, sizeof(sa
.un
.sun_path
)-1);
234 if (connect(fd
, &sa
.sa
, sizeof(sa
)) < 0) {
235 close_nointr_nofail(fd
);
239 if (shutdown(fd
, SHUT_RD
) < 0) {
240 close_nointr_nofail(fd
);
244 if ((fd
= dup(fd
)) < 0) {
245 close_nointr_nofail(fd
);
249 if (fd
!= STDERR_FILENO
) {
250 close_nointr_nofail(fd
);
254 /* We speak a very simple protocol between log server
255 * and client: one line for the log destination (kmsg
256 * or syslog), followed by the priority field,
257 * followed by the process name. Since we replaced
258 * stdin/stderr we simple use stdio to write to
259 * it. Note that we use stderr, to minimize buffer
260 * flushing issues. */
266 context
->output
== EXEC_OUTPUT_KERNEL
? "kmsg" : "syslog",
267 context
->syslog_priority
,
268 context
->syslog_identifier
? context
->syslog_identifier
: ident
);
274 assert_not_reached("Unknown output type");
278 static int setup_input(const ExecContext
*context
) {
283 switch (context
->input
) {
285 case EXEC_INPUT_CONSOLE
:
288 case EXEC_INPUT_NULL
:
289 if ((r
= replace_null_fd(STDIN_FILENO
, O_RDONLY
)) < 0)
295 assert_not_reached("Unknown input type");
299 static int get_group_creds(const char *groupname
, gid_t
*gid
) {
306 /* We enforce some special rules for gid=0: in order to avoid
307 * NSS lookups for root we hardcode its data. */
309 if (streq(groupname
, "root") || streq(groupname
, "0")) {
314 if (safe_atolu(groupname
, &lu
) >= 0) {
316 g
= getgrgid((gid_t
) lu
);
319 g
= getgrnam(groupname
);
323 return errno
!= 0 ? -errno
: -ESRCH
;
329 static int get_user_creds(const char **username
, uid_t
*uid
, gid_t
*gid
, const char **home
) {
339 /* We enforce some special rules for uid=0: in order to avoid
340 * NSS lookups for root we hardcode its data. */
342 if (streq(*username
, "root") || streq(*username
, "0")) {
350 if (safe_atolu(*username
, &lu
) >= 0) {
352 p
= getpwuid((uid_t
) lu
);
354 /* If there are multiple users with the same id, make
355 * sure to leave $USER to the configured value instead
356 * of the first occurence in the database. However if
357 * the uid was configured by a numeric uid, then let's
358 * pick the real username from /etc/passwd. */
360 *username
= p
->pw_name
;
363 p
= getpwnam(*username
);
367 return errno
!= 0 ? -errno
: -ESRCH
;
375 static int enforce_groups(const ExecContext
*context
, const char *username
, gid_t gid
) {
376 bool keep_groups
= false;
381 /* Lookup and ser GID and supplementary group list. Here too
382 * we avoid NSS lookups for gid=0. */
384 if (context
->group
|| username
) {
387 if ((r
= get_group_creds(context
->group
, &gid
)) < 0)
390 /* First step, initialize groups from /etc/groups */
391 if (username
&& gid
!= 0) {
392 if (initgroups(username
, gid
) < 0)
398 /* Second step, set our gids */
399 if (setresgid(gid
, gid
, gid
) < 0)
403 if (context
->supplementary_groups
) {
408 /* Final step, initialize any manually set supplementary groups */
409 ngroups_max
= (int) sysconf(_SC_NGROUPS_MAX
);
411 if (!(gids
= new(gid_t
, ngroups_max
)))
415 if ((k
= getgroups(ngroups_max
, gids
)) < 0) {
422 STRV_FOREACH(i
, context
->supplementary_groups
) {
424 if (k
>= ngroups_max
) {
429 if ((r
= get_group_creds(*i
, gids
+k
)) < 0) {
437 if (setgroups(k
, gids
) < 0) {
448 static int enforce_user(const ExecContext
*context
, uid_t uid
) {
452 /* Sets (but doesn't lookup) the uid and make sure we keep the
453 * capabilities while doing so. */
455 if (context
->capabilities
) {
457 static const cap_value_t bits
[] = {
458 CAP_SETUID
, /* Necessary so that we can run setresuid() below */
459 CAP_SETPCAP
/* Necessary so that we can set PR_SET_SECUREBITS later on */
462 /* First step: If we need to keep capabilities but
463 * drop privileges we need to make sure we keep our
464 * caps, whiel we drop priviliges. */
466 int sb
= context
->secure_bits
|SECURE_KEEP_CAPS
;
468 if (prctl(PR_GET_SECUREBITS
) != sb
)
469 if (prctl(PR_SET_SECUREBITS
, sb
) < 0)
473 /* Second step: set the capabilites. This will reduce
474 * the capabilities to the minimum we need. */
476 if (!(d
= cap_dup(context
->capabilities
)))
479 if (cap_set_flag(d
, CAP_EFFECTIVE
, ELEMENTSOF(bits
), bits
, CAP_SET
) < 0 ||
480 cap_set_flag(d
, CAP_PERMITTED
, ELEMENTSOF(bits
), bits
, CAP_SET
) < 0) {
486 if (cap_set_proc(d
) < 0) {
495 /* Third step: actually set the uids */
496 if (setresuid(uid
, uid
, uid
) < 0)
499 /* At this point we should have all necessary capabilities but
500 are otherwise a normal user. However, the caps might got
501 corrupted due to the setresuid() so we need clean them up
502 later. This is done outside of this call. */
507 int exec_spawn(const ExecCommand
*command
,
508 const ExecContext
*context
,
509 int *fds
, unsigned n_fds
,
510 bool apply_permissions
,
512 CGroupBonding
*cgroup_bondings
,
521 assert(fds
|| n_fds
<= 0);
523 log_debug("About to execute %s", command
->path
);
526 if ((r
= cgroup_bonding_realize_list(cgroup_bondings
)))
529 if ((pid
= fork()) < 0)
535 const char *username
= NULL
, *home
= NULL
;
536 uid_t uid
= (uid_t
) -1;
537 gid_t gid
= (gid_t
) -1;
538 char **our_env
= NULL
, **final_env
= NULL
;
543 if (sigemptyset(&ss
) < 0 ||
544 sigprocmask(SIG_SETMASK
, &ss
, NULL
) < 0) {
545 r
= EXIT_SIGNAL_MASK
;
549 if (setpgid(0, 0) < 0) {
554 umask(context
->umask
);
556 if (setup_input(context
) < 0) {
561 if (setup_output(context
, file_name_from_path(command
->path
)) < 0) {
567 if ((r
= cgroup_bonding_install_list(cgroup_bondings
, 0)) < 0) {
572 if (context
->oom_adjust_set
) {
575 snprintf(t
, sizeof(t
), "%i", context
->oom_adjust
);
578 if (write_one_line_file("/proc/self/oom_adj", t
) < 0) {
584 if (context
->nice_set
)
585 if (setpriority(PRIO_PROCESS
, 0, context
->nice
) < 0) {
590 if (context
->cpu_sched_set
) {
591 struct sched_param param
;
594 param
.sched_priority
= context
->cpu_sched_priority
;
596 if (sched_setscheduler(0, context
->cpu_sched_policy
|
597 (context
->cpu_sched_reset_on_fork
? SCHED_RESET_ON_FORK
: 0), ¶m
) < 0) {
598 r
= EXIT_SETSCHEDULER
;
603 if (context
->cpu_affinity_set
)
604 if (sched_setaffinity(0, sizeof(context
->cpu_affinity
), &context
->cpu_affinity
) < 0) {
605 r
= EXIT_CPUAFFINITY
;
609 if (context
->ioprio_set
)
610 if (ioprio_set(IOPRIO_WHO_PROCESS
, 0, context
->ioprio
) < 0) {
615 if (context
->timer_slack_ns_set
)
616 if (prctl(PR_SET_TIMERSLACK
, context
->timer_slack_ns_set
) < 0) {
622 username
= context
->user
;
623 if (get_user_creds(&username
, &uid
, &gid
, &home
) < 0) {
629 if (apply_permissions
)
630 if (enforce_groups(context
, username
, uid
) < 0) {
636 if (context
->root_directory
)
637 if (chroot(context
->root_directory
) < 0) {
642 if (chdir(context
->working_directory
? context
->working_directory
: "/") < 0) {
650 if (asprintf(&d
, "%s/%s",
651 context
->root_directory
? context
->root_directory
: "",
652 context
->working_directory
? context
->working_directory
: "") < 0) {
666 if (close_fds(fds
, n_fds
) < 0 ||
667 shift_fds(fds
, n_fds
) < 0 ||
668 flags_fds(fds
, n_fds
, context
->non_blocking
) < 0) {
673 if (apply_permissions
) {
675 for (i
= 0; i
< RLIMIT_NLIMITS
; i
++) {
676 if (!context
->rlimit
[i
])
679 if (setrlimit(i
, context
->rlimit
[i
]) < 0) {
686 if (enforce_user(context
, uid
) < 0) {
691 /* PR_GET_SECUREBITS is not priviliged, while
692 * PR_SET_SECUREBITS is. So to suppress
693 * potential EPERMs we'll try not to call
694 * PR_SET_SECUREBITS unless necessary. */
695 if (prctl(PR_GET_SECUREBITS
) != context
->secure_bits
)
696 if (prctl(PR_SET_SECUREBITS
, context
->secure_bits
) < 0) {
701 if (context
->capabilities
)
702 if (cap_set_proc(context
->capabilities
) < 0) {
703 r
= EXIT_CAPABILITIES
;
708 if (!(our_env
= new0(char*, 6))) {
714 if (asprintf(our_env
+ n_env
++, "LISTEN_PID=%llu", (unsigned long long) getpid()) < 0 ||
715 asprintf(our_env
+ n_env
++, "LISTEN_FDS=%u", n_fds
) < 0) {
721 if (asprintf(our_env
+ n_env
++, "HOME=%s", home
) < 0) {
727 if (asprintf(our_env
+ n_env
++, "LOGNAME=%s", username
) < 0 ||
728 asprintf(our_env
+ n_env
++, "USER=%s", username
) < 0) {
733 if (!(final_env
= strv_env_merge(environ
, our_env
, context
->environment
, NULL
))) {
738 execve(command
->path
, command
->argv
, final_env
);
743 strv_free(final_env
);
749 log_debug("Forked %s as %llu", command
->path
, (unsigned long long) pid
);
755 void exec_context_init(ExecContext
*c
) {
760 c
->oom_adjust_set
= false;
763 c
->ioprio
= IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE
, 0);
764 c
->ioprio_set
= false;
765 c
->cpu_sched_policy
= SCHED_OTHER
;
766 c
->cpu_sched_priority
= 0;
767 c
->cpu_sched_set
= false;
768 CPU_ZERO(&c
->cpu_affinity
);
769 c
->cpu_affinity_set
= false;
773 c
->syslog_priority
= LOG_DAEMON
|LOG_INFO
;
776 c
->capability_bounding_set_drop
= 0;
779 void exec_context_done(ExecContext
*c
) {
784 strv_free(c
->environment
);
785 c
->environment
= NULL
;
787 for (l
= 0; l
< ELEMENTSOF(c
->rlimit
); l
++) {
792 free(c
->working_directory
);
793 c
->working_directory
= NULL
;
794 free(c
->root_directory
);
795 c
->root_directory
= NULL
;
797 free(c
->syslog_identifier
);
798 c
->syslog_identifier
= NULL
;
806 strv_free(c
->supplementary_groups
);
807 c
->supplementary_groups
= NULL
;
809 if (c
->capabilities
) {
810 cap_free(c
->capabilities
);
811 c
->capabilities
= NULL
;
815 void exec_command_free_list(ExecCommand
*c
) {
819 LIST_REMOVE(ExecCommand
, command
, c
, i
);
827 void exec_command_free_array(ExecCommand
**c
, unsigned n
) {
830 for (i
= 0; i
< n
; i
++) {
831 exec_command_free_list(c
[i
]);
836 void exec_context_dump(ExecContext
*c
, FILE* f
, const char *prefix
) {
848 "%sWorkingDirectory: %s\n"
849 "%sRootDirectory: %s\n"
850 "%sNonBlocking: %s\n",
852 prefix
, c
->working_directory
? c
->working_directory
: "/",
853 prefix
, c
->root_directory
? c
->root_directory
: "/",
854 prefix
, yes_no(c
->non_blocking
));
857 for (e
= c
->environment
; *e
; e
++)
858 fprintf(f
, "%sEnvironment: %s\n", prefix
, *e
);
865 if (c
->oom_adjust_set
)
868 prefix
, c
->oom_adjust
);
870 for (i
= 0; i
< RLIM_NLIMITS
; i
++)
872 fprintf(f
, "%s%s: %llu\n", prefix
, rlimit_to_string(i
), (unsigned long long) c
->rlimit
[i
]->rlim_max
);
876 "%sIOSchedulingClass: %s\n"
877 "%sIOPriority: %i\n",
878 prefix
, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c
->ioprio
)),
879 prefix
, (int) IOPRIO_PRIO_DATA(c
->ioprio
));
881 if (c
->cpu_sched_set
)
883 "%sCPUSchedulingPolicy: %s\n"
884 "%sCPUSchedulingPriority: %i\n"
885 "%sCPUSchedulingResetOnFork: %s\n",
886 prefix
, sched_policy_to_string(c
->cpu_sched_policy
),
887 prefix
, c
->cpu_sched_priority
,
888 prefix
, yes_no(c
->cpu_sched_reset_on_fork
));
890 if (c
->cpu_affinity_set
) {
891 fprintf(f
, "%sCPUAffinity:", prefix
);
892 for (i
= 0; i
< CPU_SETSIZE
; i
++)
893 if (CPU_ISSET(i
, &c
->cpu_affinity
))
894 fprintf(f
, " %i", i
);
898 if (c
->timer_slack_ns_set
)
899 fprintf(f
, "%sTimerSlackNS: %lu\n", prefix
, c
->timer_slack_ns
);
904 prefix
, exec_input_to_string(c
->input
),
905 prefix
, exec_output_to_string(c
->output
));
907 if (c
->output
== EXEC_OUTPUT_SYSLOG
|| c
->output
== EXEC_OUTPUT_KERNEL
)
909 "%sSyslogFacility: %s\n"
910 "%sSyslogLevel: %s\n",
911 prefix
, log_facility_to_string(LOG_FAC(c
->syslog_priority
)),
912 prefix
, log_level_to_string(LOG_PRI(c
->syslog_priority
)));
914 if (c
->capabilities
) {
916 if ((t
= cap_to_text(c
->capabilities
, NULL
))) {
917 fprintf(f
, "%sCapabilities: %s\n",
924 fprintf(f
, "%sSecure Bits:%s%s%s%s%s%s\n",
926 (c
->secure_bits
& SECURE_KEEP_CAPS
) ? " keep-caps" : "",
927 (c
->secure_bits
& SECURE_KEEP_CAPS_LOCKED
) ? " keep-caps-locked" : "",
928 (c
->secure_bits
& SECURE_NO_SETUID_FIXUP
) ? " no-setuid-fixup" : "",
929 (c
->secure_bits
& SECURE_NO_SETUID_FIXUP_LOCKED
) ? " no-setuid-fixup-locked" : "",
930 (c
->secure_bits
& SECURE_NOROOT
) ? " noroot" : "",
931 (c
->secure_bits
& SECURE_NOROOT_LOCKED
) ? "noroot-locked" : "");
933 if (c
->capability_bounding_set_drop
) {
934 fprintf(f
, "%sCapabilityBoundingSetDrop:", prefix
);
936 for (i
= 0; i
<= CAP_LAST_CAP
; i
++)
937 if (c
->capability_bounding_set_drop
& (1 << i
)) {
940 if ((t
= cap_to_name(i
))) {
941 fprintf(f
, " %s", t
);
950 fprintf(f
, "%sUser: %s", prefix
, c
->user
);
952 fprintf(f
, "%sGroup: %s", prefix
, c
->group
);
954 if (c
->supplementary_groups
) {
957 fprintf(f
, "%sSupplementaryGroups:", prefix
);
959 STRV_FOREACH(g
, c
->supplementary_groups
)
960 fprintf(f
, " %s", *g
);
966 void exec_status_fill(ExecStatus
*s
, pid_t pid
, int code
, int status
) {
972 s
->timestamp
= now(CLOCK_REALTIME
);
975 char *exec_command_line(ExecCommand
*c
) {
984 STRV_FOREACH(a
, c
->argv
)
987 if (!(n
= new(char, k
)))
991 STRV_FOREACH(a
, c
->argv
) {
998 if (strpbrk(*a
, WHITESPACE
)) {
1009 /* FIXME: this doesn't really handle arguments that have
1010 * spaces and ticks in them */
1015 void exec_command_dump(ExecCommand
*c
, FILE *f
, const char *prefix
) {
1024 cmd
= exec_command_line(c
);
1027 "%sCommand Line: %s\n",
1028 prefix
, cmd
? cmd
: strerror(ENOMEM
));
1033 void exec_command_dump_list(ExecCommand
*c
, FILE *f
, const char *prefix
) {
1039 LIST_FOREACH(command
, c
, c
)
1040 exec_command_dump(c
, f
, prefix
);
1043 void exec_command_append_list(ExecCommand
**l
, ExecCommand
*e
) {
1050 /* It's kinda important that we keep the order here */
1051 LIST_FIND_TAIL(ExecCommand
, command
, *l
, end
);
1052 LIST_INSERT_AFTER(ExecCommand
, command
, *l
, end
, e
);
1057 static const char* const exec_output_table
[_EXEC_OUTPUT_MAX
] = {
1058 [EXEC_OUTPUT_CONSOLE
] = "console",
1059 [EXEC_OUTPUT_NULL
] = "null",
1060 [EXEC_OUTPUT_SYSLOG
] = "syslog",
1061 [EXEC_OUTPUT_KERNEL
] = "kernel"
1064 DEFINE_STRING_TABLE_LOOKUP(exec_output
, ExecOutput
);
1066 static const char* const exec_input_table
[_EXEC_INPUT_MAX
] = {
1067 [EXEC_INPUT_NULL
] = "null",
1068 [EXEC_INPUT_CONSOLE
] = "console"
1071 DEFINE_STRING_TABLE_LOOKUP(exec_input
, ExecInput
);