]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/execute.c
Rename formats-util.h to format-util.h
[thirdparty/systemd.git] / src / core / execute.c
CommitLineData
a7334b09
LP
1/***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
5430f7f2
LP
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
a7334b09
LP
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5430f7f2 14 Lesser General Public License for more details.
a7334b09 15
5430f7f2 16 You should have received a copy of the GNU Lesser General Public License
a7334b09
LP
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18***/
19
034c6ed7
LP
20#include <errno.h>
21#include <fcntl.h>
8dd4c05b
LP
22#include <glob.h>
23#include <grp.h>
24#include <poll.h>
309bff19 25#include <signal.h>
8dd4c05b 26#include <string.h>
19c0b0b9 27#include <sys/capability.h>
d251207d 28#include <sys/eventfd.h>
f3e43635 29#include <sys/mman.h>
8dd4c05b 30#include <sys/personality.h>
94f04347 31#include <sys/prctl.h>
d2ffa389 32#include <sys/shm.h>
8dd4c05b 33#include <sys/socket.h>
451a074f 34#include <sys/stat.h>
d2ffa389 35#include <sys/types.h>
8dd4c05b
LP
36#include <sys/un.h>
37#include <unistd.h>
023a4f67 38#include <utmpx.h>
5cb5a6ff 39
5b6319dc
LP
40#ifdef HAVE_PAM
41#include <security/pam_appl.h>
42#endif
43
7b52a628
MS
44#ifdef HAVE_SELINUX
45#include <selinux/selinux.h>
46#endif
47
17df7223
LP
48#ifdef HAVE_SECCOMP
49#include <seccomp.h>
50#endif
51
eef65bf3
MS
52#ifdef HAVE_APPARMOR
53#include <sys/apparmor.h>
54#endif
55
24882e06 56#include "sd-messages.h"
8dd4c05b
LP
57
58#include "af-list.h"
b5efdb8a 59#include "alloc-util.h"
3ffd4af2
LP
60#ifdef HAVE_APPARMOR
61#include "apparmor-util.h"
62#endif
8dd4c05b
LP
63#include "async.h"
64#include "barrier.h"
8dd4c05b 65#include "cap-list.h"
430f0182 66#include "capability-util.h"
f6a6225e 67#include "def.h"
4d1a6904 68#include "env-util.h"
17df7223 69#include "errno-list.h"
3ffd4af2 70#include "execute.h"
8dd4c05b 71#include "exit-status.h"
3ffd4af2 72#include "fd-util.h"
8dd4c05b 73#include "fileio.h"
f97b34a6 74#include "format-util.h"
f4f15635 75#include "fs-util.h"
7d50b32a 76#include "glob-util.h"
c004493c 77#include "io-util.h"
8dd4c05b
LP
78#include "ioprio.h"
79#include "log.h"
80#include "macro.h"
81#include "missing.h"
82#include "mkdir.h"
83#include "namespace.h"
6bedfcbb 84#include "parse-util.h"
8dd4c05b 85#include "path-util.h"
0b452006 86#include "process-util.h"
78f22b97 87#include "rlimit-util.h"
8dd4c05b 88#include "rm-rf.h"
3ffd4af2
LP
89#ifdef HAVE_SECCOMP
90#include "seccomp-util.h"
91#endif
8dd4c05b
LP
92#include "securebits.h"
93#include "selinux-util.h"
24882e06 94#include "signal-util.h"
8dd4c05b 95#include "smack-util.h"
fd63e712 96#include "special.h"
8b43440b 97#include "string-table.h"
07630cea 98#include "string-util.h"
8dd4c05b 99#include "strv.h"
7ccbd1ae 100#include "syslog-util.h"
8dd4c05b
LP
101#include "terminal-util.h"
102#include "unit.h"
b1d4f8e1 103#include "user-util.h"
8dd4c05b
LP
104#include "util.h"
105#include "utmp-wtmp.h"
5cb5a6ff 106
e056b01d 107#define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
31a7eb86 108#define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
e6a26745 109
02a51aba
LP
110/* This assumes there is a 'tty' group */
111#define TTY_MODE 0620
112
531dca78
LP
113#define SNDBUF_SIZE (8*1024*1024)
114
034c6ed7
LP
115static int shift_fds(int fds[], unsigned n_fds) {
116 int start, restart_from;
117
118 if (n_fds <= 0)
119 return 0;
120
a0d40ac5
LP
121 /* Modifies the fds array! (sorts it) */
122
034c6ed7
LP
123 assert(fds);
124
125 start = 0;
126 for (;;) {
127 int i;
128
129 restart_from = -1;
130
131 for (i = start; i < (int) n_fds; i++) {
132 int nfd;
133
134 /* Already at right index? */
135 if (fds[i] == i+3)
136 continue;
137
3cc2aff1
LP
138 nfd = fcntl(fds[i], F_DUPFD, i + 3);
139 if (nfd < 0)
034c6ed7
LP
140 return -errno;
141
03e334a1 142 safe_close(fds[i]);
034c6ed7
LP
143 fds[i] = nfd;
144
145 /* Hmm, the fd we wanted isn't free? Then
ee33e53a 146 * let's remember that and try again from here */
034c6ed7
LP
147 if (nfd != i+3 && restart_from < 0)
148 restart_from = i;
149 }
150
151 if (restart_from < 0)
152 break;
153
154 start = restart_from;
155 }
156
157 return 0;
158}
159
c2748801 160static int flags_fds(const int fds[], unsigned n_fds, bool nonblock) {
47a71eed 161 unsigned i;
e2c76839 162 int r;
47a71eed
LP
163
164 if (n_fds <= 0)
165 return 0;
166
167 assert(fds);
168
451a074f 169 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
47a71eed
LP
170
171 for (i = 0; i < n_fds; i++) {
47a71eed 172
3cc2aff1
LP
173 r = fd_nonblock(fds[i], nonblock);
174 if (r < 0)
e2c76839 175 return r;
47a71eed 176
451a074f
LP
177 /* We unconditionally drop FD_CLOEXEC from the fds,
178 * since after all we want to pass these fds to our
179 * children */
47a71eed 180
3cc2aff1
LP
181 r = fd_cloexec(fds[i], false);
182 if (r < 0)
e2c76839 183 return r;
47a71eed
LP
184 }
185
186 return 0;
187}
188
1e22b5cd 189static const char *exec_context_tty_path(const ExecContext *context) {
80876c20
LP
190 assert(context);
191
1e22b5cd
LP
192 if (context->stdio_as_fds)
193 return NULL;
194
80876c20
LP
195 if (context->tty_path)
196 return context->tty_path;
197
198 return "/dev/console";
199}
200
1e22b5cd
LP
201static void exec_context_tty_reset(const ExecContext *context, const ExecParameters *p) {
202 const char *path;
203
6ea832a2
LP
204 assert(context);
205
1e22b5cd 206 path = exec_context_tty_path(context);
6ea832a2 207
1e22b5cd
LP
208 if (context->tty_vhangup) {
209 if (p && p->stdin_fd >= 0)
210 (void) terminal_vhangup_fd(p->stdin_fd);
211 else if (path)
212 (void) terminal_vhangup(path);
213 }
6ea832a2 214
1e22b5cd
LP
215 if (context->tty_reset) {
216 if (p && p->stdin_fd >= 0)
217 (void) reset_terminal_fd(p->stdin_fd, true);
218 else if (path)
219 (void) reset_terminal(path);
220 }
221
222 if (context->tty_vt_disallocate && path)
223 (void) vt_disallocate(path);
6ea832a2
LP
224}
225
6af760f3
LP
226static bool is_terminal_input(ExecInput i) {
227 return IN_SET(i,
228 EXEC_INPUT_TTY,
229 EXEC_INPUT_TTY_FORCE,
230 EXEC_INPUT_TTY_FAIL);
231}
232
3a1286b6 233static bool is_terminal_output(ExecOutput o) {
6af760f3
LP
234 return IN_SET(o,
235 EXEC_OUTPUT_TTY,
236 EXEC_OUTPUT_SYSLOG_AND_CONSOLE,
237 EXEC_OUTPUT_KMSG_AND_CONSOLE,
238 EXEC_OUTPUT_JOURNAL_AND_CONSOLE);
239}
240
241static bool exec_context_needs_term(const ExecContext *c) {
242 assert(c);
243
244 /* Return true if the execution context suggests we should set $TERM to something useful. */
245
246 if (is_terminal_input(c->std_input))
247 return true;
248
249 if (is_terminal_output(c->std_output))
250 return true;
251
252 if (is_terminal_output(c->std_error))
253 return true;
254
255 return !!c->tty_path;
3a1286b6
MS
256}
257
80876c20
LP
258static int open_null_as(int flags, int nfd) {
259 int fd, r;
071830ff 260
80876c20 261 assert(nfd >= 0);
071830ff 262
613b411c
LP
263 fd = open("/dev/null", flags|O_NOCTTY);
264 if (fd < 0)
071830ff
LP
265 return -errno;
266
80876c20
LP
267 if (fd != nfd) {
268 r = dup2(fd, nfd) < 0 ? -errno : nfd;
03e334a1 269 safe_close(fd);
80876c20
LP
270 } else
271 r = nfd;
071830ff 272
80876c20 273 return r;
071830ff
LP
274}
275
524daa8c 276static int connect_journal_socket(int fd, uid_t uid, gid_t gid) {
b92bea5d
ZJS
277 union sockaddr_union sa = {
278 .un.sun_family = AF_UNIX,
279 .un.sun_path = "/run/systemd/journal/stdout",
280 };
524daa8c
ZJS
281 uid_t olduid = UID_INVALID;
282 gid_t oldgid = GID_INVALID;
283 int r;
284
285 if (gid != GID_INVALID) {
286 oldgid = getgid();
287
288 r = setegid(gid);
289 if (r < 0)
290 return -errno;
291 }
292
293 if (uid != UID_INVALID) {
294 olduid = getuid();
295
296 r = seteuid(uid);
297 if (r < 0) {
298 r = -errno;
299 goto restore_gid;
300 }
301 }
302
fc2fffe7 303 r = connect(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un));
524daa8c
ZJS
304 if (r < 0)
305 r = -errno;
306
307 /* If we fail to restore the uid or gid, things will likely
308 fail later on. This should only happen if an LSM interferes. */
309
310 if (uid != UID_INVALID)
311 (void) seteuid(olduid);
312
313 restore_gid:
314 if (gid != GID_INVALID)
315 (void) setegid(oldgid);
316
317 return r;
318}
319
fd1f9c89 320static int connect_logger_as(
7a1ab780 321 Unit *unit,
fd1f9c89
LP
322 const ExecContext *context,
323 ExecOutput output,
324 const char *ident,
fd1f9c89
LP
325 int nfd,
326 uid_t uid,
327 gid_t gid) {
328
524daa8c 329 int fd, r;
071830ff
LP
330
331 assert(context);
80876c20
LP
332 assert(output < _EXEC_OUTPUT_MAX);
333 assert(ident);
334 assert(nfd >= 0);
071830ff 335
54fe0cdb
LP
336 fd = socket(AF_UNIX, SOCK_STREAM, 0);
337 if (fd < 0)
80876c20 338 return -errno;
071830ff 339
524daa8c
ZJS
340 r = connect_journal_socket(fd, uid, gid);
341 if (r < 0)
342 return r;
071830ff 343
80876c20 344 if (shutdown(fd, SHUT_RD) < 0) {
03e334a1 345 safe_close(fd);
80876c20
LP
346 return -errno;
347 }
071830ff 348
fd1f9c89 349 (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
531dca78 350
80876c20 351 dprintf(fd,
62bca2c6 352 "%s\n"
80876c20
LP
353 "%s\n"
354 "%i\n"
54fe0cdb
LP
355 "%i\n"
356 "%i\n"
357 "%i\n"
4f4a1dbf 358 "%i\n",
4f4a1dbf 359 context->syslog_identifier ? context->syslog_identifier : ident,
7a1ab780 360 unit->id,
54fe0cdb
LP
361 context->syslog_priority,
362 !!context->syslog_level_prefix,
363 output == EXEC_OUTPUT_SYSLOG || output == EXEC_OUTPUT_SYSLOG_AND_CONSOLE,
364 output == EXEC_OUTPUT_KMSG || output == EXEC_OUTPUT_KMSG_AND_CONSOLE,
3a1286b6 365 is_terminal_output(output));
80876c20 366
fd1f9c89
LP
367 if (fd == nfd)
368 return nfd;
369
370 r = dup2(fd, nfd) < 0 ? -errno : nfd;
371 safe_close(fd);
071830ff 372
80876c20
LP
373 return r;
374}
375static int open_terminal_as(const char *path, mode_t mode, int nfd) {
376 int fd, r;
071830ff 377
80876c20
LP
378 assert(path);
379 assert(nfd >= 0);
071830ff 380
3cc2aff1
LP
381 fd = open_terminal(path, mode | O_NOCTTY);
382 if (fd < 0)
80876c20 383 return fd;
071830ff 384
80876c20
LP
385 if (fd != nfd) {
386 r = dup2(fd, nfd) < 0 ? -errno : nfd;
03e334a1 387 safe_close(fd);
80876c20
LP
388 } else
389 r = nfd;
071830ff 390
80876c20
LP
391 return r;
392}
071830ff 393
1e3ad081
LP
394static int fixup_input(ExecInput std_input, int socket_fd, bool apply_tty_stdin) {
395
396 if (is_terminal_input(std_input) && !apply_tty_stdin)
397 return EXEC_INPUT_NULL;
071830ff 398
03fd9c49 399 if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
4f2d528d
LP
400 return EXEC_INPUT_NULL;
401
03fd9c49 402 return std_input;
4f2d528d
LP
403}
404
03fd9c49 405static int fixup_output(ExecOutput std_output, int socket_fd) {
4f2d528d 406
03fd9c49 407 if (std_output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
4f2d528d
LP
408 return EXEC_OUTPUT_INHERIT;
409
03fd9c49 410 return std_output;
4f2d528d
LP
411}
412
a34ceba6
LP
413static int setup_input(
414 const ExecContext *context,
415 const ExecParameters *params,
52c239d7
LB
416 int socket_fd,
417 int named_iofds[3]) {
a34ceba6 418
4f2d528d
LP
419 ExecInput i;
420
421 assert(context);
a34ceba6
LP
422 assert(params);
423
424 if (params->stdin_fd >= 0) {
425 if (dup2(params->stdin_fd, STDIN_FILENO) < 0)
426 return -errno;
427
428 /* Try to make this the controlling tty, if it is a tty, and reset it */
429 (void) ioctl(STDIN_FILENO, TIOCSCTTY, context->std_input == EXEC_INPUT_TTY_FORCE);
430 (void) reset_terminal_fd(STDIN_FILENO, true);
431
432 return STDIN_FILENO;
433 }
4f2d528d 434
c39f1ce2 435 i = fixup_input(context->std_input, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
4f2d528d
LP
436
437 switch (i) {
071830ff 438
80876c20
LP
439 case EXEC_INPUT_NULL:
440 return open_null_as(O_RDONLY, STDIN_FILENO);
441
442 case EXEC_INPUT_TTY:
443 case EXEC_INPUT_TTY_FORCE:
444 case EXEC_INPUT_TTY_FAIL: {
445 int fd, r;
071830ff 446
1e22b5cd 447 fd = acquire_terminal(exec_context_tty_path(context),
970edce6
ZJS
448 i == EXEC_INPUT_TTY_FAIL,
449 i == EXEC_INPUT_TTY_FORCE,
450 false,
3a43da28 451 USEC_INFINITY);
970edce6 452 if (fd < 0)
80876c20
LP
453 return fd;
454
455 if (fd != STDIN_FILENO) {
456 r = dup2(fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
03e334a1 457 safe_close(fd);
80876c20
LP
458 } else
459 r = STDIN_FILENO;
460
461 return r;
462 }
463
4f2d528d
LP
464 case EXEC_INPUT_SOCKET:
465 return dup2(socket_fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
466
52c239d7
LB
467 case EXEC_INPUT_NAMED_FD:
468 (void) fd_nonblock(named_iofds[STDIN_FILENO], false);
469 return dup2(named_iofds[STDIN_FILENO], STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
470
80876c20
LP
471 default:
472 assert_not_reached("Unknown input type");
473 }
474}
475
a34ceba6
LP
476static int setup_output(
477 Unit *unit,
478 const ExecContext *context,
479 const ExecParameters *params,
480 int fileno,
481 int socket_fd,
52c239d7 482 int named_iofds[3],
a34ceba6 483 const char *ident,
7bce046b
LP
484 uid_t uid,
485 gid_t gid,
486 dev_t *journal_stream_dev,
487 ino_t *journal_stream_ino) {
a34ceba6 488
4f2d528d
LP
489 ExecOutput o;
490 ExecInput i;
47c1d80d 491 int r;
4f2d528d 492
f2341e0a 493 assert(unit);
80876c20 494 assert(context);
a34ceba6 495 assert(params);
80876c20 496 assert(ident);
7bce046b
LP
497 assert(journal_stream_dev);
498 assert(journal_stream_ino);
80876c20 499
a34ceba6
LP
500 if (fileno == STDOUT_FILENO && params->stdout_fd >= 0) {
501
502 if (dup2(params->stdout_fd, STDOUT_FILENO) < 0)
503 return -errno;
504
505 return STDOUT_FILENO;
506 }
507
508 if (fileno == STDERR_FILENO && params->stderr_fd >= 0) {
509 if (dup2(params->stderr_fd, STDERR_FILENO) < 0)
510 return -errno;
511
512 return STDERR_FILENO;
513 }
514
c39f1ce2 515 i = fixup_input(context->std_input, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
03fd9c49 516 o = fixup_output(context->std_output, socket_fd);
4f2d528d 517
eb17e935
MS
518 if (fileno == STDERR_FILENO) {
519 ExecOutput e;
520 e = fixup_output(context->std_error, socket_fd);
80876c20 521
eb17e935
MS
522 /* This expects the input and output are already set up */
523
524 /* Don't change the stderr file descriptor if we inherit all
525 * the way and are not on a tty */
526 if (e == EXEC_OUTPUT_INHERIT &&
527 o == EXEC_OUTPUT_INHERIT &&
528 i == EXEC_INPUT_NULL &&
529 !is_terminal_input(context->std_input) &&
530 getppid () != 1)
531 return fileno;
532
533 /* Duplicate from stdout if possible */
52c239d7 534 if ((e == o && e != EXEC_OUTPUT_NAMED_FD) || e == EXEC_OUTPUT_INHERIT)
eb17e935 535 return dup2(STDOUT_FILENO, fileno) < 0 ? -errno : fileno;
071830ff 536
eb17e935 537 o = e;
80876c20 538
eb17e935 539 } else if (o == EXEC_OUTPUT_INHERIT) {
21d21ea4
LP
540 /* If input got downgraded, inherit the original value */
541 if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
1e22b5cd 542 return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
21d21ea4 543
acb591e4 544 /* If the input is connected to anything that's not a /dev/null, inherit that... */
ff876e28 545 if (i != EXEC_INPUT_NULL)
eb17e935 546 return dup2(STDIN_FILENO, fileno) < 0 ? -errno : fileno;
071830ff 547
acb591e4
LP
548 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
549 if (getppid() != 1)
eb17e935 550 return fileno;
94f04347 551
eb17e935
MS
552 /* We need to open /dev/null here anew, to get the right access mode. */
553 return open_null_as(O_WRONLY, fileno);
071830ff 554 }
94f04347 555
eb17e935 556 switch (o) {
80876c20
LP
557
558 case EXEC_OUTPUT_NULL:
eb17e935 559 return open_null_as(O_WRONLY, fileno);
80876c20
LP
560
561 case EXEC_OUTPUT_TTY:
4f2d528d 562 if (is_terminal_input(i))
eb17e935 563 return dup2(STDIN_FILENO, fileno) < 0 ? -errno : fileno;
80876c20
LP
564
565 /* We don't reset the terminal if this is just about output */
1e22b5cd 566 return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
80876c20
LP
567
568 case EXEC_OUTPUT_SYSLOG:
28dbc1e8 569 case EXEC_OUTPUT_SYSLOG_AND_CONSOLE:
9a6bca7a 570 case EXEC_OUTPUT_KMSG:
28dbc1e8 571 case EXEC_OUTPUT_KMSG_AND_CONSOLE:
706343f4
LP
572 case EXEC_OUTPUT_JOURNAL:
573 case EXEC_OUTPUT_JOURNAL_AND_CONSOLE:
7a1ab780 574 r = connect_logger_as(unit, context, o, ident, fileno, uid, gid);
47c1d80d 575 if (r < 0) {
f2341e0a 576 log_unit_error_errno(unit, r, "Failed to connect %s to the journal socket, ignoring: %m", fileno == STDOUT_FILENO ? "stdout" : "stderr");
eb17e935 577 r = open_null_as(O_WRONLY, fileno);
7bce046b
LP
578 } else {
579 struct stat st;
580
581 /* If we connected this fd to the journal via a stream, patch the device/inode into the passed
582 * parameters, but only then. This is useful so that we can set $JOURNAL_STREAM that permits
583 * services to detect whether they are connected to the journal or not. */
584
585 if (fstat(fileno, &st) >= 0) {
586 *journal_stream_dev = st.st_dev;
587 *journal_stream_ino = st.st_ino;
588 }
47c1d80d
MS
589 }
590 return r;
4f2d528d
LP
591
592 case EXEC_OUTPUT_SOCKET:
593 assert(socket_fd >= 0);
eb17e935 594 return dup2(socket_fd, fileno) < 0 ? -errno : fileno;
94f04347 595
52c239d7
LB
596 case EXEC_OUTPUT_NAMED_FD:
597 (void) fd_nonblock(named_iofds[fileno], false);
598 return dup2(named_iofds[fileno], fileno) < 0 ? -errno : fileno;
599
94f04347 600 default:
80876c20 601 assert_not_reached("Unknown error type");
94f04347 602 }
071830ff
LP
603}
604
02a51aba
LP
605static int chown_terminal(int fd, uid_t uid) {
606 struct stat st;
607
608 assert(fd >= 0);
02a51aba 609
1ff74fb6
LP
610 /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
611 if (isatty(fd) < 1)
612 return 0;
613
02a51aba 614 /* This might fail. What matters are the results. */
bab45044
LP
615 (void) fchown(fd, uid, -1);
616 (void) fchmod(fd, TTY_MODE);
02a51aba
LP
617
618 if (fstat(fd, &st) < 0)
619 return -errno;
620
d8b4e2e9 621 if (st.st_uid != uid || (st.st_mode & 0777) != TTY_MODE)
02a51aba
LP
622 return -EPERM;
623
624 return 0;
625}
626
3d18b167
LP
627static int setup_confirm_stdio(int *_saved_stdin, int *_saved_stdout) {
628 _cleanup_close_ int fd = -1, saved_stdin = -1, saved_stdout = -1;
629 int r;
80876c20 630
80876c20
LP
631 assert(_saved_stdin);
632 assert(_saved_stdout);
633
af6da548
LP
634 saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3);
635 if (saved_stdin < 0)
636 return -errno;
80876c20 637
af6da548 638 saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3);
3d18b167
LP
639 if (saved_stdout < 0)
640 return -errno;
80876c20 641
af6da548
LP
642 fd = acquire_terminal(
643 "/dev/console",
644 false,
645 false,
646 false,
647 DEFAULT_CONFIRM_USEC);
3d18b167
LP
648 if (fd < 0)
649 return fd;
80876c20 650
af6da548
LP
651 r = chown_terminal(fd, getuid());
652 if (r < 0)
3d18b167 653 return r;
02a51aba 654
3d18b167
LP
655 r = reset_terminal_fd(fd, true);
656 if (r < 0)
657 return r;
80876c20 658
3d18b167
LP
659 if (dup2(fd, STDIN_FILENO) < 0)
660 return -errno;
661
662 if (dup2(fd, STDOUT_FILENO) < 0)
663 return -errno;
80876c20
LP
664
665 if (fd >= 2)
03e334a1 666 safe_close(fd);
3d18b167 667 fd = -1;
80876c20
LP
668
669 *_saved_stdin = saved_stdin;
670 *_saved_stdout = saved_stdout;
671
3d18b167 672 saved_stdin = saved_stdout = -1;
80876c20 673
3d18b167 674 return 0;
80876c20
LP
675}
676
44b601bc 677_printf_(1, 2) static int write_confirm_message(const char *format, ...) {
03e334a1 678 _cleanup_close_ int fd = -1;
af6da548 679 va_list ap;
80876c20 680
af6da548 681 assert(format);
80876c20 682
af6da548
LP
683 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
684 if (fd < 0)
685 return fd;
80876c20 686
af6da548
LP
687 va_start(ap, format);
688 vdprintf(fd, format, ap);
689 va_end(ap);
80876c20 690
af6da548
LP
691 return 0;
692}
80876c20 693
3d18b167 694static int restore_confirm_stdio(int *saved_stdin, int *saved_stdout) {
af6da548 695 int r = 0;
80876c20 696
af6da548
LP
697 assert(saved_stdin);
698 assert(saved_stdout);
699
700 release_terminal();
701
702 if (*saved_stdin >= 0)
80876c20 703 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
af6da548 704 r = -errno;
80876c20 705
af6da548 706 if (*saved_stdout >= 0)
80876c20 707 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
af6da548 708 r = -errno;
80876c20 709
3d18b167
LP
710 *saved_stdin = safe_close(*saved_stdin);
711 *saved_stdout = safe_close(*saved_stdout);
af6da548
LP
712
713 return r;
714}
715
716static int ask_for_confirmation(char *response, char **argv) {
717 int saved_stdout = -1, saved_stdin = -1, r;
e1d75803 718 _cleanup_free_ char *line = NULL;
af6da548
LP
719
720 r = setup_confirm_stdio(&saved_stdin, &saved_stdout);
721 if (r < 0)
722 return r;
723
724 line = exec_command_line(argv);
725 if (!line)
726 return -ENOMEM;
727
418b9be5 728 r = ask_char(response, "yns", "Execute %s? [Yes, No, Skip] ", line);
af6da548
LP
729
730 restore_confirm_stdio(&saved_stdin, &saved_stdout);
731
732 return r;
80876c20
LP
733}
734
4d885bd3
DH
735static int get_fixed_user(const ExecContext *c, const char **user,
736 uid_t *uid, gid_t *gid,
737 const char **home, const char **shell) {
81a2b7ce 738 int r;
4d885bd3 739 const char *name;
81a2b7ce 740
4d885bd3 741 assert(c);
81a2b7ce 742
4d885bd3
DH
743 if (!c->user)
744 return 0;
81a2b7ce 745
4d885bd3
DH
746 /* Note that we don't set $HOME or $SHELL if they are not particularly enlightening anyway
747 * (i.e. are "/" or "/bin/nologin"). */
81a2b7ce 748
4d885bd3
DH
749 name = c->user;
750 r = get_user_creds_clean(&name, uid, gid, home, shell);
751 if (r < 0)
752 return r;
81a2b7ce 753
4d885bd3
DH
754 *user = name;
755 return 0;
756}
757
758static int get_fixed_group(const ExecContext *c, const char **group, gid_t *gid) {
759 int r;
760 const char *name;
761
762 assert(c);
763
764 if (!c->group)
765 return 0;
766
767 name = c->group;
768 r = get_group_creds(&name, gid);
769 if (r < 0)
770 return r;
771
772 *group = name;
773 return 0;
774}
775
cdc5d5c5
DH
776static int get_supplementary_groups(const ExecContext *c, const char *user,
777 const char *group, gid_t gid,
778 gid_t **supplementary_gids, int *ngids) {
4d885bd3
DH
779 char **i;
780 int r, k = 0;
781 int ngroups_max;
782 bool keep_groups = false;
783 gid_t *groups = NULL;
784 _cleanup_free_ gid_t *l_gids = NULL;
785
786 assert(c);
787
bbeea271
DH
788 /*
789 * If user is given, then lookup GID and supplementary groups list.
790 * We avoid NSS lookups for gid=0. Also we have to initialize groups
cdc5d5c5
DH
791 * here and as early as possible so we keep the list of supplementary
792 * groups of the caller.
bbeea271
DH
793 */
794 if (user && gid_is_valid(gid) && gid != 0) {
795 /* First step, initialize groups from /etc/groups */
796 if (initgroups(user, gid) < 0)
797 return -errno;
798
799 keep_groups = true;
800 }
801
4d885bd3
DH
802 if (!c->supplementary_groups)
803 return 0;
804
366ddd25
DH
805 /*
806 * If SupplementaryGroups= was passed then NGROUPS_MAX has to
807 * be positive, otherwise fail.
808 */
809 errno = 0;
810 ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
811 if (ngroups_max <= 0) {
812 if (errno > 0)
813 return -errno;
814 else
815 return -EOPNOTSUPP; /* For all other values */
816 }
817
4d885bd3
DH
818 l_gids = new(gid_t, ngroups_max);
819 if (!l_gids)
820 return -ENOMEM;
81a2b7ce 821
4d885bd3
DH
822 if (keep_groups) {
823 /*
824 * Lookup the list of groups that the user belongs to, we
825 * avoid NSS lookups here too for gid=0.
826 */
827 k = ngroups_max;
828 if (getgrouplist(user, gid, l_gids, &k) < 0)
829 return -EINVAL;
830 } else
831 k = 0;
81a2b7ce 832
4d885bd3
DH
833 STRV_FOREACH(i, c->supplementary_groups) {
834 const char *g;
81a2b7ce 835
4d885bd3
DH
836 if (k >= ngroups_max)
837 return -E2BIG;
81a2b7ce 838
4d885bd3
DH
839 g = *i;
840 r = get_group_creds(&g, l_gids+k);
841 if (r < 0)
842 return r;
81a2b7ce 843
4d885bd3
DH
844 k++;
845 }
81a2b7ce 846
4d885bd3
DH
847 /*
848 * Sets ngids to zero to drop all supplementary groups, happens
849 * when we are under root and SupplementaryGroups= is empty.
850 */
851 if (k == 0) {
852 *ngids = 0;
853 return 0;
854 }
81a2b7ce 855
4d885bd3
DH
856 /* Otherwise get the final list of supplementary groups */
857 groups = memdup(l_gids, sizeof(gid_t) * k);
858 if (!groups)
859 return -ENOMEM;
860
861 *supplementary_gids = groups;
862 *ngids = k;
863
864 groups = NULL;
865
866 return 0;
867}
868
869static int enforce_groups(const ExecContext *context, gid_t gid,
870 gid_t *supplementary_gids, int ngids) {
871 int r;
872
873 assert(context);
874
875 /* Handle SupplementaryGroups= even if it is empty */
876 if (context->supplementary_groups) {
877 r = maybe_setgroups(ngids, supplementary_gids);
878 if (r < 0)
97f0e76f 879 return r;
4d885bd3 880 }
81a2b7ce 881
4d885bd3
DH
882 if (gid_is_valid(gid)) {
883 /* Then set our gids */
884 if (setresgid(gid, gid, gid) < 0)
885 return -errno;
81a2b7ce
LP
886 }
887
888 return 0;
889}
890
891static int enforce_user(const ExecContext *context, uid_t uid) {
81a2b7ce
LP
892 assert(context);
893
4d885bd3
DH
894 if (!uid_is_valid(uid))
895 return 0;
896
479050b3 897 /* Sets (but doesn't look up) the uid and make sure we keep the
81a2b7ce
LP
898 * capabilities while doing so. */
899
479050b3 900 if (context->capability_ambient_set != 0) {
81a2b7ce
LP
901
902 /* First step: If we need to keep capabilities but
903 * drop privileges we need to make sure we keep our
cbb21cca 904 * caps, while we drop privileges. */
693ced48 905 if (uid != 0) {
cbb21cca 906 int sb = context->secure_bits | 1<<SECURE_KEEP_CAPS;
693ced48
LP
907
908 if (prctl(PR_GET_SECUREBITS) != sb)
909 if (prctl(PR_SET_SECUREBITS, sb) < 0)
910 return -errno;
911 }
81a2b7ce
LP
912 }
913
479050b3 914 /* Second step: actually set the uids */
81a2b7ce
LP
915 if (setresuid(uid, uid, uid) < 0)
916 return -errno;
917
918 /* At this point we should have all necessary capabilities but
919 are otherwise a normal user. However, the caps might got
920 corrupted due to the setresuid() so we need clean them up
921 later. This is done outside of this call. */
922
923 return 0;
924}
925
5b6319dc
LP
926#ifdef HAVE_PAM
927
928static int null_conv(
929 int num_msg,
930 const struct pam_message **msg,
931 struct pam_response **resp,
932 void *appdata_ptr) {
933
934 /* We don't support conversations */
935
936 return PAM_CONV_ERR;
937}
938
cefc33ae
LP
939#endif
940
5b6319dc
LP
941static int setup_pam(
942 const char *name,
943 const char *user,
940c5210 944 uid_t uid,
2d6fce8d 945 gid_t gid,
5b6319dc 946 const char *tty,
2065ca69 947 char ***env,
5b6319dc
LP
948 int fds[], unsigned n_fds) {
949
cefc33ae
LP
950#ifdef HAVE_PAM
951
5b6319dc
LP
952 static const struct pam_conv conv = {
953 .conv = null_conv,
954 .appdata_ptr = NULL
955 };
956
2d7c6aa2 957 _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
5b6319dc 958 pam_handle_t *handle = NULL;
d6e5f3ad 959 sigset_t old_ss;
7bb70b6e 960 int pam_code = PAM_SUCCESS, r;
84eada2f 961 char **nv, **e = NULL;
5b6319dc
LP
962 bool close_session = false;
963 pid_t pam_pid = 0, parent_pid;
970edce6 964 int flags = 0;
5b6319dc
LP
965
966 assert(name);
967 assert(user);
2065ca69 968 assert(env);
5b6319dc
LP
969
970 /* We set up PAM in the parent process, then fork. The child
35b8ca3a 971 * will then stay around until killed via PR_GET_PDEATHSIG or
5b6319dc
LP
972 * systemd via the cgroup logic. It will then remove the PAM
973 * session again. The parent process will exec() the actual
974 * daemon. We do things this way to ensure that the main PID
975 * of the daemon is the one we initially fork()ed. */
976
7bb70b6e
LP
977 r = barrier_create(&barrier);
978 if (r < 0)
2d7c6aa2
DH
979 goto fail;
980
553d2243 981 if (log_get_max_level() < LOG_DEBUG)
970edce6
ZJS
982 flags |= PAM_SILENT;
983
f546241b
ZJS
984 pam_code = pam_start(name, user, &conv, &handle);
985 if (pam_code != PAM_SUCCESS) {
5b6319dc
LP
986 handle = NULL;
987 goto fail;
988 }
989
f546241b
ZJS
990 if (tty) {
991 pam_code = pam_set_item(handle, PAM_TTY, tty);
992 if (pam_code != PAM_SUCCESS)
5b6319dc 993 goto fail;
f546241b 994 }
5b6319dc 995
84eada2f
JW
996 STRV_FOREACH(nv, *env) {
997 pam_code = pam_putenv(handle, *nv);
2065ca69
JW
998 if (pam_code != PAM_SUCCESS)
999 goto fail;
1000 }
1001
970edce6 1002 pam_code = pam_acct_mgmt(handle, flags);
f546241b 1003 if (pam_code != PAM_SUCCESS)
5b6319dc
LP
1004 goto fail;
1005
970edce6 1006 pam_code = pam_open_session(handle, flags);
f546241b 1007 if (pam_code != PAM_SUCCESS)
5b6319dc
LP
1008 goto fail;
1009
1010 close_session = true;
1011
f546241b
ZJS
1012 e = pam_getenvlist(handle);
1013 if (!e) {
5b6319dc
LP
1014 pam_code = PAM_BUF_ERR;
1015 goto fail;
1016 }
1017
1018 /* Block SIGTERM, so that we know that it won't get lost in
1019 * the child */
ce30c8dc 1020
72c0a2c2 1021 assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM, -1) >= 0);
5b6319dc
LP
1022
1023 parent_pid = getpid();
1024
f546241b 1025 pam_pid = fork();
7bb70b6e
LP
1026 if (pam_pid < 0) {
1027 r = -errno;
5b6319dc 1028 goto fail;
7bb70b6e 1029 }
5b6319dc
LP
1030
1031 if (pam_pid == 0) {
7bb70b6e 1032 int sig, ret = EXIT_PAM;
5b6319dc
LP
1033
1034 /* The child's job is to reset the PAM session on
1035 * termination */
2d7c6aa2 1036 barrier_set_role(&barrier, BARRIER_CHILD);
5b6319dc
LP
1037
1038 /* This string must fit in 10 chars (i.e. the length
5d6b1584
LP
1039 * of "/sbin/init"), to look pretty in /bin/ps */
1040 rename_process("(sd-pam)");
5b6319dc
LP
1041
1042 /* Make sure we don't keep open the passed fds in this
1043 child. We assume that otherwise only those fds are
1044 open here that have been opened by PAM. */
1045 close_many(fds, n_fds);
1046
940c5210
AK
1047 /* Drop privileges - we don't need any to pam_close_session
1048 * and this will make PR_SET_PDEATHSIG work in most cases.
1049 * If this fails, ignore the error - but expect sd-pam threads
1050 * to fail to exit normally */
2d6fce8d 1051
97f0e76f
LP
1052 r = maybe_setgroups(0, NULL);
1053 if (r < 0)
1054 log_warning_errno(r, "Failed to setgroups() in sd-pam: %m");
2d6fce8d
LP
1055 if (setresgid(gid, gid, gid) < 0)
1056 log_warning_errno(errno, "Failed to setresgid() in sd-pam: %m");
940c5210 1057 if (setresuid(uid, uid, uid) < 0)
2d6fce8d 1058 log_warning_errno(errno, "Failed to setresuid() in sd-pam: %m");
940c5210 1059
ce30c8dc
LP
1060 (void) ignore_signals(SIGPIPE, -1);
1061
940c5210
AK
1062 /* Wait until our parent died. This will only work if
1063 * the above setresuid() succeeds, otherwise the kernel
1064 * will not allow unprivileged parents kill their privileged
1065 * children this way. We rely on the control groups kill logic
5b6319dc
LP
1066 * to do the rest for us. */
1067 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
1068 goto child_finish;
1069
2d7c6aa2
DH
1070 /* Tell the parent that our setup is done. This is especially
1071 * important regarding dropping privileges. Otherwise, unit
1072 * setup might race against our setresuid(2) call. */
1073 barrier_place(&barrier);
1074
5b6319dc
LP
1075 /* Check if our parent process might already have
1076 * died? */
1077 if (getppid() == parent_pid) {
d6e5f3ad
DM
1078 sigset_t ss;
1079
1080 assert_se(sigemptyset(&ss) >= 0);
1081 assert_se(sigaddset(&ss, SIGTERM) >= 0);
1082
3dead8d9
LP
1083 for (;;) {
1084 if (sigwait(&ss, &sig) < 0) {
1085 if (errno == EINTR)
1086 continue;
1087
1088 goto child_finish;
1089 }
5b6319dc 1090
3dead8d9
LP
1091 assert(sig == SIGTERM);
1092 break;
1093 }
5b6319dc
LP
1094 }
1095
3dead8d9 1096 /* If our parent died we'll end the session */
f546241b 1097 if (getppid() != parent_pid) {
970edce6 1098 pam_code = pam_close_session(handle, flags);
f546241b 1099 if (pam_code != PAM_SUCCESS)
5b6319dc 1100 goto child_finish;
f546241b 1101 }
5b6319dc 1102
7bb70b6e 1103 ret = 0;
5b6319dc
LP
1104
1105 child_finish:
970edce6 1106 pam_end(handle, pam_code | flags);
7bb70b6e 1107 _exit(ret);
5b6319dc
LP
1108 }
1109
2d7c6aa2
DH
1110 barrier_set_role(&barrier, BARRIER_PARENT);
1111
5b6319dc
LP
1112 /* If the child was forked off successfully it will do all the
1113 * cleanups, so forget about the handle here. */
1114 handle = NULL;
1115
3b8bddde 1116 /* Unblock SIGTERM again in the parent */
72c0a2c2 1117 assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0);
5b6319dc
LP
1118
1119 /* We close the log explicitly here, since the PAM modules
1120 * might have opened it, but we don't want this fd around. */
1121 closelog();
1122
2d7c6aa2
DH
1123 /* Synchronously wait for the child to initialize. We don't care for
1124 * errors as we cannot recover. However, warn loudly if it happens. */
1125 if (!barrier_place_and_sync(&barrier))
1126 log_error("PAM initialization failed");
1127
2065ca69
JW
1128 strv_free(*env);
1129 *env = e;
aa87e624 1130
5b6319dc
LP
1131 return 0;
1132
1133fail:
970edce6
ZJS
1134 if (pam_code != PAM_SUCCESS) {
1135 log_error("PAM failed: %s", pam_strerror(handle, pam_code));
7bb70b6e
LP
1136 r = -EPERM; /* PAM errors do not map to errno */
1137 } else
1138 log_error_errno(r, "PAM failed: %m");
9ba35398 1139
5b6319dc
LP
1140 if (handle) {
1141 if (close_session)
970edce6 1142 pam_code = pam_close_session(handle, flags);
5b6319dc 1143
970edce6 1144 pam_end(handle, pam_code | flags);
5b6319dc
LP
1145 }
1146
1147 strv_free(e);
5b6319dc
LP
1148 closelog();
1149
7bb70b6e 1150 return r;
cefc33ae
LP
1151#else
1152 return 0;
5b6319dc 1153#endif
cefc33ae 1154}
5b6319dc 1155
5d6b1584
LP
1156static void rename_process_from_path(const char *path) {
1157 char process_name[11];
1158 const char *p;
1159 size_t l;
1160
1161 /* This resulting string must fit in 10 chars (i.e. the length
1162 * of "/sbin/init") to look pretty in /bin/ps */
1163
2b6bf07d 1164 p = basename(path);
5d6b1584
LP
1165 if (isempty(p)) {
1166 rename_process("(...)");
1167 return;
1168 }
1169
1170 l = strlen(p);
1171 if (l > 8) {
1172 /* The end of the process name is usually more
1173 * interesting, since the first bit might just be
1174 * "systemd-" */
1175 p = p + l - 8;
1176 l = 8;
1177 }
1178
1179 process_name[0] = '(';
1180 memcpy(process_name+1, p, l);
1181 process_name[1+l] = ')';
1182 process_name[1+l+1] = 0;
1183
1184 rename_process(process_name);
1185}
1186
c0467cf3 1187#ifdef HAVE_SECCOMP
17df7223 1188
83f12b27 1189static bool skip_seccomp_unavailable(const Unit* u, const char* msg) {
f673b62d
LP
1190
1191 if (is_seccomp_available())
1192 return false;
1193
1194 log_open();
1195 log_unit_debug(u, "SECCOMP features not detected in the kernel, skipping %s", msg);
1196 log_close();
1197 return true;
83f12b27
FS
1198}
1199
1200static int apply_seccomp(const Unit* u, const ExecContext *c) {
17df7223 1201 uint32_t negative_action, action;
8d7b0c8f 1202 scmp_filter_ctx seccomp;
c0467cf3
RC
1203 Iterator i;
1204 void *id;
17df7223 1205 int r;
8351ceae 1206
c0467cf3 1207 assert(c);
8351ceae 1208
83f12b27
FS
1209 if (skip_seccomp_unavailable(u, "syscall filtering"))
1210 return 0;
1211
17df7223
LP
1212 negative_action = c->syscall_errno == 0 ? SCMP_ACT_KILL : SCMP_ACT_ERRNO(c->syscall_errno);
1213
1214 seccomp = seccomp_init(c->syscall_whitelist ? negative_action : SCMP_ACT_ALLOW);
1215 if (!seccomp)
1216 return -ENOMEM;
8351ceae 1217
e9642be2
LP
1218 if (c->syscall_archs) {
1219
1220 SET_FOREACH(id, c->syscall_archs, i) {
1221 r = seccomp_arch_add(seccomp, PTR_TO_UINT32(id) - 1);
1222 if (r == -EEXIST)
1223 continue;
7c66bae2
LP
1224 if (r < 0)
1225 goto finish;
e9642be2 1226 }
e9642be2 1227
7c66bae2 1228 } else {
e9642be2 1229 r = seccomp_add_secondary_archs(seccomp);
7c66bae2
LP
1230 if (r < 0)
1231 goto finish;
57183d11 1232 }
8351ceae 1233
57183d11 1234 action = c->syscall_whitelist ? SCMP_ACT_ALLOW : negative_action;
17df7223
LP
1235 SET_FOREACH(id, c->syscall_filter, i) {
1236 r = seccomp_rule_add(seccomp, action, PTR_TO_INT(id) - 1, 0);
7c66bae2
LP
1237 if (r < 0)
1238 goto finish;
c0467cf3 1239 }
8351ceae 1240
7c66bae2
LP
1241 r = seccomp_attr_set(seccomp, SCMP_FLTATR_CTL_NNP, 0);
1242 if (r < 0)
1243 goto finish;
1244
17df7223 1245 r = seccomp_load(seccomp);
7c66bae2
LP
1246
1247finish:
17df7223 1248 seccomp_release(seccomp);
4298d0b5
LP
1249 return r;
1250}
1251
83f12b27 1252static int apply_address_families(const Unit* u, const ExecContext *c) {
8d7b0c8f 1253 scmp_filter_ctx seccomp;
4298d0b5
LP
1254 Iterator i;
1255 int r;
1256
1257 assert(c);
1258
83f12b27
FS
1259 if (skip_seccomp_unavailable(u, "RestrictAddressFamilies="))
1260 return 0;
1261
8d7b0c8f 1262 r = seccomp_init_conservative(&seccomp, SCMP_ACT_ALLOW);
4298d0b5 1263 if (r < 0)
8d7b0c8f 1264 return r;
4298d0b5
LP
1265
1266 if (c->address_families_whitelist) {
1267 int af, first = 0, last = 0;
1268 void *afp;
1269
1270 /* If this is a whitelist, we first block the address
1271 * families that are out of range and then everything
1272 * that is not in the set. First, we find the lowest
1273 * and highest address family in the set. */
1274
1275 SET_FOREACH(afp, c->address_families, i) {
1276 af = PTR_TO_INT(afp);
17df7223 1277
4298d0b5
LP
1278 if (af <= 0 || af >= af_max())
1279 continue;
1280
1281 if (first == 0 || af < first)
1282 first = af;
1283
1284 if (last == 0 || af > last)
1285 last = af;
1286 }
1287
1288 assert((first == 0) == (last == 0));
1289
1290 if (first == 0) {
1291
1292 /* No entries in the valid range, block everything */
1293 r = seccomp_rule_add(
1294 seccomp,
1295 SCMP_ACT_ERRNO(EPROTONOSUPPORT),
1296 SCMP_SYS(socket),
1297 0);
1298 if (r < 0)
1299 goto finish;
1300
1301 } else {
1302
1303 /* Block everything below the first entry */
1304 r = seccomp_rule_add(
1305 seccomp,
1306 SCMP_ACT_ERRNO(EPROTONOSUPPORT),
1307 SCMP_SYS(socket),
1308 1,
1309 SCMP_A0(SCMP_CMP_LT, first));
1310 if (r < 0)
1311 goto finish;
1312
1313 /* Block everything above the last entry */
1314 r = seccomp_rule_add(
1315 seccomp,
1316 SCMP_ACT_ERRNO(EPROTONOSUPPORT),
1317 SCMP_SYS(socket),
1318 1,
1319 SCMP_A0(SCMP_CMP_GT, last));
1320 if (r < 0)
1321 goto finish;
1322
1323 /* Block everything between the first and last
1324 * entry */
1325 for (af = 1; af < af_max(); af++) {
1326
1327 if (set_contains(c->address_families, INT_TO_PTR(af)))
1328 continue;
1329
1330 r = seccomp_rule_add(
1331 seccomp,
1332 SCMP_ACT_ERRNO(EPROTONOSUPPORT),
1333 SCMP_SYS(socket),
1334 1,
1335 SCMP_A0(SCMP_CMP_EQ, af));
1336 if (r < 0)
1337 goto finish;
1338 }
1339 }
1340
1341 } else {
1342 void *af;
1343
1344 /* If this is a blacklist, then generate one rule for
1345 * each address family that are then combined in OR
1346 * checks. */
1347
1348 SET_FOREACH(af, c->address_families, i) {
1349
1350 r = seccomp_rule_add(
1351 seccomp,
1352 SCMP_ACT_ERRNO(EPROTONOSUPPORT),
1353 SCMP_SYS(socket),
1354 1,
1355 SCMP_A0(SCMP_CMP_EQ, PTR_TO_INT(af)));
1356 if (r < 0)
1357 goto finish;
1358 }
1359 }
1360
4298d0b5
LP
1361 r = seccomp_load(seccomp);
1362
1363finish:
1364 seccomp_release(seccomp);
17df7223 1365 return r;
8351ceae 1366}
4298d0b5 1367
83f12b27 1368static int apply_memory_deny_write_execute(const Unit* u, const ExecContext *c) {
8d7b0c8f 1369 scmp_filter_ctx seccomp;
f3e43635
TM
1370 int r;
1371
1372 assert(c);
1373
83f12b27
FS
1374 if (skip_seccomp_unavailable(u, "MemoryDenyWriteExecute="))
1375 return 0;
1376
8d7b0c8f 1377 r = seccomp_init_conservative(&seccomp, SCMP_ACT_ALLOW);
72246c2a 1378 if (r < 0)
8d7b0c8f 1379 return r;
72246c2a 1380
f3e43635
TM
1381 r = seccomp_rule_add(
1382 seccomp,
abd84d4d 1383 SCMP_ACT_ERRNO(EPERM),
f3e43635
TM
1384 SCMP_SYS(mmap),
1385 1,
1386 SCMP_A2(SCMP_CMP_MASKED_EQ, PROT_EXEC|PROT_WRITE, PROT_EXEC|PROT_WRITE));
1387 if (r < 0)
1388 goto finish;
1389
1390 r = seccomp_rule_add(
1391 seccomp,
abd84d4d 1392 SCMP_ACT_ERRNO(EPERM),
f3e43635
TM
1393 SCMP_SYS(mprotect),
1394 1,
1395 SCMP_A2(SCMP_CMP_MASKED_EQ, PROT_EXEC, PROT_EXEC));
1396 if (r < 0)
1397 goto finish;
1398
d2ffa389
TM
1399 r = seccomp_rule_add(
1400 seccomp,
1401 SCMP_ACT_ERRNO(EPERM),
1402 SCMP_SYS(shmat),
1403 1,
1404 SCMP_A2(SCMP_CMP_MASKED_EQ, SHM_EXEC, SHM_EXEC));
1405 if (r < 0)
1406 goto finish;
1407
f3e43635
TM
1408 r = seccomp_load(seccomp);
1409
1410finish:
1411 seccomp_release(seccomp);
1412 return r;
1413}
1414
83f12b27 1415static int apply_restrict_realtime(const Unit* u, const ExecContext *c) {
f4170c67
LP
1416 static const int permitted_policies[] = {
1417 SCHED_OTHER,
1418 SCHED_BATCH,
1419 SCHED_IDLE,
1420 };
1421
8d7b0c8f 1422 scmp_filter_ctx seccomp;
f4170c67
LP
1423 unsigned i;
1424 int r, p, max_policy = 0;
1425
1426 assert(c);
1427
83f12b27
FS
1428 if (skip_seccomp_unavailable(u, "RestrictRealtime="))
1429 return 0;
1430
8d7b0c8f 1431 r = seccomp_init_conservative(&seccomp, SCMP_ACT_ALLOW);
72246c2a 1432 if (r < 0)
8d7b0c8f 1433 return r;
72246c2a 1434
f4170c67
LP
1435 /* Determine the highest policy constant we want to allow */
1436 for (i = 0; i < ELEMENTSOF(permitted_policies); i++)
1437 if (permitted_policies[i] > max_policy)
1438 max_policy = permitted_policies[i];
1439
1440 /* Go through all policies with lower values than that, and block them -- unless they appear in the
1441 * whitelist. */
1442 for (p = 0; p < max_policy; p++) {
1443 bool good = false;
1444
1445 /* Check if this is in the whitelist. */
1446 for (i = 0; i < ELEMENTSOF(permitted_policies); i++)
1447 if (permitted_policies[i] == p) {
1448 good = true;
1449 break;
1450 }
1451
1452 if (good)
1453 continue;
1454
1455 /* Deny this policy */
1456 r = seccomp_rule_add(
1457 seccomp,
1458 SCMP_ACT_ERRNO(EPERM),
1459 SCMP_SYS(sched_setscheduler),
1460 1,
1461 SCMP_A1(SCMP_CMP_EQ, p));
1462 if (r < 0)
1463 goto finish;
1464 }
1465
1466 /* Blacklist all other policies, i.e. the ones with higher values. Note that all comparisons are unsigned here,
1467 * hence no need no check for < 0 values. */
1468 r = seccomp_rule_add(
1469 seccomp,
1470 SCMP_ACT_ERRNO(EPERM),
1471 SCMP_SYS(sched_setscheduler),
1472 1,
1473 SCMP_A1(SCMP_CMP_GT, max_policy));
1474 if (r < 0)
1475 goto finish;
1476
f4170c67
LP
1477 r = seccomp_load(seccomp);
1478
1479finish:
1480 seccomp_release(seccomp);
1481 return r;
1482}
1483
59e856c7 1484static int apply_protect_sysctl(const Unit *u, const ExecContext *c) {
8d7b0c8f 1485 scmp_filter_ctx seccomp;
59eeb84b
LP
1486 int r;
1487
1488 assert(c);
1489
1490 /* Turn off the legacy sysctl() system call. Many distributions turn this off while building the kernel, but
1491 * let's protect even those systems where this is left on in the kernel. */
1492
1493 if (skip_seccomp_unavailable(u, "ProtectKernelTunables="))
1494 return 0;
1495
8d7b0c8f 1496 r = seccomp_init_conservative(&seccomp, SCMP_ACT_ALLOW);
59eeb84b 1497 if (r < 0)
8d7b0c8f 1498 return r;
59eeb84b
LP
1499
1500 r = seccomp_rule_add(
1501 seccomp,
1502 SCMP_ACT_ERRNO(EPERM),
1503 SCMP_SYS(_sysctl),
1504 0);
1505 if (r < 0)
1506 goto finish;
1507
59eeb84b
LP
1508 r = seccomp_load(seccomp);
1509
1510finish:
1511 seccomp_release(seccomp);
1512 return r;
1513}
1514
59e856c7 1515static int apply_protect_kernel_modules(const Unit *u, const ExecContext *c) {
502d704e
DH
1516 assert(c);
1517
25a8d8a0 1518 /* Turn off module syscalls on ProtectKernelModules=yes */
502d704e
DH
1519
1520 if (skip_seccomp_unavailable(u, "ProtectKernelModules="))
1521 return 0;
1522
a3be2849 1523 return seccomp_load_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_MODULE, SCMP_ACT_ERRNO(EPERM));
502d704e
DH
1524}
1525
59e856c7 1526static int apply_private_devices(const Unit *u, const ExecContext *c) {
ba128bb8
LP
1527 assert(c);
1528
8f81a5f6 1529 /* If PrivateDevices= is set, also turn off iopl and all @raw-io syscalls. */
ba128bb8
LP
1530
1531 if (skip_seccomp_unavailable(u, "PrivateDevices="))
1532 return 0;
1533
a3be2849 1534 return seccomp_load_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_RAW_IO, SCMP_ACT_ERRNO(EPERM));
ba128bb8
LP
1535}
1536
c0467cf3 1537#endif
8351ceae 1538
31a7eb86
ZJS
1539static void do_idle_pipe_dance(int idle_pipe[4]) {
1540 assert(idle_pipe);
1541
54eb2300
LP
1542 idle_pipe[1] = safe_close(idle_pipe[1]);
1543 idle_pipe[2] = safe_close(idle_pipe[2]);
31a7eb86
ZJS
1544
1545 if (idle_pipe[0] >= 0) {
1546 int r;
1547
1548 r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
1549
1550 if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
c7cc737f
LP
1551 ssize_t n;
1552
31a7eb86 1553 /* Signal systemd that we are bored and want to continue. */
c7cc737f
LP
1554 n = write(idle_pipe[3], "x", 1);
1555 if (n > 0)
cd972d69
ZJS
1556 /* Wait for systemd to react to the signal above. */
1557 fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
31a7eb86
ZJS
1558 }
1559
54eb2300 1560 idle_pipe[0] = safe_close(idle_pipe[0]);
31a7eb86
ZJS
1561
1562 }
1563
54eb2300 1564 idle_pipe[3] = safe_close(idle_pipe[3]);
31a7eb86
ZJS
1565}
1566
7cae38c4 1567static int build_environment(
fd63e712 1568 Unit *u,
9fa95f85 1569 const ExecContext *c,
1e22b5cd 1570 const ExecParameters *p,
7cae38c4
LP
1571 unsigned n_fds,
1572 const char *home,
1573 const char *username,
1574 const char *shell,
7bce046b
LP
1575 dev_t journal_stream_dev,
1576 ino_t journal_stream_ino,
7cae38c4
LP
1577 char ***ret) {
1578
1579 _cleanup_strv_free_ char **our_env = NULL;
1580 unsigned n_env = 0;
1581 char *x;
1582
4b58153d 1583 assert(u);
7cae38c4
LP
1584 assert(c);
1585 assert(ret);
1586
4b58153d 1587 our_env = new0(char*, 14);
7cae38c4
LP
1588 if (!our_env)
1589 return -ENOMEM;
1590
1591 if (n_fds > 0) {
8dd4c05b
LP
1592 _cleanup_free_ char *joined = NULL;
1593
ccd06097 1594 if (asprintf(&x, "LISTEN_PID="PID_FMT, getpid()) < 0)
7cae38c4
LP
1595 return -ENOMEM;
1596 our_env[n_env++] = x;
1597
1598 if (asprintf(&x, "LISTEN_FDS=%u", n_fds) < 0)
1599 return -ENOMEM;
1600 our_env[n_env++] = x;
8dd4c05b 1601
1e22b5cd 1602 joined = strv_join(p->fd_names, ":");
8dd4c05b
LP
1603 if (!joined)
1604 return -ENOMEM;
1605
605405c6 1606 x = strjoin("LISTEN_FDNAMES=", joined);
8dd4c05b
LP
1607 if (!x)
1608 return -ENOMEM;
1609 our_env[n_env++] = x;
7cae38c4
LP
1610 }
1611
b08af3b1 1612 if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) {
ccd06097 1613 if (asprintf(&x, "WATCHDOG_PID="PID_FMT, getpid()) < 0)
09812eb7
LP
1614 return -ENOMEM;
1615 our_env[n_env++] = x;
1616
1e22b5cd 1617 if (asprintf(&x, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec) < 0)
09812eb7
LP
1618 return -ENOMEM;
1619 our_env[n_env++] = x;
1620 }
1621
fd63e712
LP
1622 /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use D-Bus look up dynamic
1623 * users via PID 1, possibly dead-locking the dbus daemon. This way it will not use D-Bus to resolve names, but
1624 * check the database directly. */
1625 if (unit_has_name(u, SPECIAL_DBUS_SERVICE)) {
1626 x = strdup("SYSTEMD_NSS_BYPASS_BUS=1");
1627 if (!x)
1628 return -ENOMEM;
1629 our_env[n_env++] = x;
1630 }
1631
7cae38c4
LP
1632 if (home) {
1633 x = strappend("HOME=", home);
1634 if (!x)
1635 return -ENOMEM;
1636 our_env[n_env++] = x;
1637 }
1638
1639 if (username) {
1640 x = strappend("LOGNAME=", username);
1641 if (!x)
1642 return -ENOMEM;
1643 our_env[n_env++] = x;
1644
1645 x = strappend("USER=", username);
1646 if (!x)
1647 return -ENOMEM;
1648 our_env[n_env++] = x;
1649 }
1650
1651 if (shell) {
1652 x = strappend("SHELL=", shell);
1653 if (!x)
1654 return -ENOMEM;
1655 our_env[n_env++] = x;
1656 }
1657
4b58153d
LP
1658 if (!sd_id128_is_null(u->invocation_id)) {
1659 if (asprintf(&x, "INVOCATION_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(u->invocation_id)) < 0)
1660 return -ENOMEM;
1661
1662 our_env[n_env++] = x;
1663 }
1664
6af760f3
LP
1665 if (exec_context_needs_term(c)) {
1666 const char *tty_path, *term = NULL;
1667
1668 tty_path = exec_context_tty_path(c);
1669
1670 /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try to inherit
1671 * the $TERM set for PID 1. This is useful for containers so that the $TERM the container manager
1672 * passes to PID 1 ends up all the way in the console login shown. */
1673
1674 if (path_equal(tty_path, "/dev/console") && getppid() == 1)
1675 term = getenv("TERM");
1676 if (!term)
1677 term = default_term_for_tty(tty_path);
7cae38c4 1678
6af760f3 1679 x = strappend("TERM=", term);
7cae38c4
LP
1680 if (!x)
1681 return -ENOMEM;
1682 our_env[n_env++] = x;
1683 }
1684
7bce046b
LP
1685 if (journal_stream_dev != 0 && journal_stream_ino != 0) {
1686 if (asprintf(&x, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino) < 0)
1687 return -ENOMEM;
1688
1689 our_env[n_env++] = x;
1690 }
1691
7cae38c4 1692 our_env[n_env++] = NULL;
7bce046b 1693 assert(n_env <= 12);
7cae38c4
LP
1694
1695 *ret = our_env;
1696 our_env = NULL;
1697
1698 return 0;
1699}
1700
b4c14404
FB
1701static int build_pass_environment(const ExecContext *c, char ***ret) {
1702 _cleanup_strv_free_ char **pass_env = NULL;
1703 size_t n_env = 0, n_bufsize = 0;
1704 char **i;
1705
1706 STRV_FOREACH(i, c->pass_environment) {
1707 _cleanup_free_ char *x = NULL;
1708 char *v;
1709
1710 v = getenv(*i);
1711 if (!v)
1712 continue;
605405c6 1713 x = strjoin(*i, "=", v);
b4c14404
FB
1714 if (!x)
1715 return -ENOMEM;
1716 if (!GREEDY_REALLOC(pass_env, n_bufsize, n_env + 2))
1717 return -ENOMEM;
1718 pass_env[n_env++] = x;
1719 pass_env[n_env] = NULL;
1720 x = NULL;
1721 }
1722
1723 *ret = pass_env;
1724 pass_env = NULL;
1725
1726 return 0;
1727}
1728
8b44a3d2
LP
1729static bool exec_needs_mount_namespace(
1730 const ExecContext *context,
1731 const ExecParameters *params,
1732 ExecRuntime *runtime) {
1733
1734 assert(context);
1735 assert(params);
1736
2a624c36
AP
1737 if (!strv_isempty(context->read_write_paths) ||
1738 !strv_isempty(context->read_only_paths) ||
1739 !strv_isempty(context->inaccessible_paths))
8b44a3d2
LP
1740 return true;
1741
1742 if (context->mount_flags != 0)
1743 return true;
1744
1745 if (context->private_tmp && runtime && (runtime->tmp_dir || runtime->var_tmp_dir))
1746 return true;
1747
8b44a3d2
LP
1748 if (context->private_devices ||
1749 context->protect_system != PROTECT_SYSTEM_NO ||
59eeb84b
LP
1750 context->protect_home != PROTECT_HOME_NO ||
1751 context->protect_kernel_tunables ||
c575770b 1752 context->protect_kernel_modules ||
59eeb84b 1753 context->protect_control_groups)
8b44a3d2
LP
1754 return true;
1755
1756 return false;
1757}
1758
d251207d
LP
1759static int setup_private_users(uid_t uid, gid_t gid) {
1760 _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
1761 _cleanup_close_pair_ int errno_pipe[2] = { -1, -1 };
1762 _cleanup_close_ int unshare_ready_fd = -1;
1763 _cleanup_(sigkill_waitp) pid_t pid = 0;
1764 uint64_t c = 1;
1765 siginfo_t si;
1766 ssize_t n;
1767 int r;
1768
1769 /* Set up a user namespace and map root to root, the selected UID/GID to itself, and everything else to
1770 * nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which
1771 * we however lack after opening the user namespace. To work around this we fork() a temporary child process,
1772 * which waits for the parent to create the new user namespace while staying in the original namespace. The
1773 * child then writes the UID mapping, under full privileges. The parent waits for the child to finish and
1774 * continues execution normally. */
1775
1776 if (uid != 0 && uid_is_valid(uid))
1777 asprintf(&uid_map,
1778 "0 0 1\n" /* Map root → root */
1779 UID_FMT " " UID_FMT " 1\n", /* Map $UID → $UID */
e0f3720e 1780 uid, uid);
d251207d 1781 else
e0f3720e 1782 uid_map = strdup("0 0 1\n"); /* The case where the above is the same */
d251207d
LP
1783 if (!uid_map)
1784 return -ENOMEM;
1785
1786 if (gid != 0 && gid_is_valid(gid))
1787 asprintf(&gid_map,
1788 "0 0 1\n" /* Map root → root */
1789 GID_FMT " " GID_FMT " 1\n", /* Map $GID → $GID */
1790 gid, gid);
1791 else
1792 gid_map = strdup("0 0 1\n"); /* The case where the above is the same */
1793 if (!gid_map)
1794 return -ENOMEM;
1795
1796 /* Create a communication channel so that the parent can tell the child when it finished creating the user
1797 * namespace. */
1798 unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
1799 if (unshare_ready_fd < 0)
1800 return -errno;
1801
1802 /* Create a communication channel so that the child can tell the parent a proper error code in case it
1803 * failed. */
1804 if (pipe2(errno_pipe, O_CLOEXEC) < 0)
1805 return -errno;
1806
1807 pid = fork();
1808 if (pid < 0)
1809 return -errno;
1810
1811 if (pid == 0) {
1812 _cleanup_close_ int fd = -1;
1813 const char *a;
1814 pid_t ppid;
1815
1816 /* Child process, running in the original user namespace. Let's update the parent's UID/GID map from
1817 * here, after the parent opened its own user namespace. */
1818
1819 ppid = getppid();
1820 errno_pipe[0] = safe_close(errno_pipe[0]);
1821
1822 /* Wait until the parent unshared the user namespace */
1823 if (read(unshare_ready_fd, &c, sizeof(c)) < 0) {
1824 r = -errno;
1825 goto child_fail;
1826 }
1827
1828 /* Disable the setgroups() system call in the child user namespace, for good. */
1829 a = procfs_file_alloca(ppid, "setgroups");
1830 fd = open(a, O_WRONLY|O_CLOEXEC);
1831 if (fd < 0) {
1832 if (errno != ENOENT) {
1833 r = -errno;
1834 goto child_fail;
1835 }
1836
1837 /* If the file is missing the kernel is too old, let's continue anyway. */
1838 } else {
1839 if (write(fd, "deny\n", 5) < 0) {
1840 r = -errno;
1841 goto child_fail;
1842 }
1843
1844 fd = safe_close(fd);
1845 }
1846
1847 /* First write the GID map */
1848 a = procfs_file_alloca(ppid, "gid_map");
1849 fd = open(a, O_WRONLY|O_CLOEXEC);
1850 if (fd < 0) {
1851 r = -errno;
1852 goto child_fail;
1853 }
1854 if (write(fd, gid_map, strlen(gid_map)) < 0) {
1855 r = -errno;
1856 goto child_fail;
1857 }
1858 fd = safe_close(fd);
1859
1860 /* The write the UID map */
1861 a = procfs_file_alloca(ppid, "uid_map");
1862 fd = open(a, O_WRONLY|O_CLOEXEC);
1863 if (fd < 0) {
1864 r = -errno;
1865 goto child_fail;
1866 }
1867 if (write(fd, uid_map, strlen(uid_map)) < 0) {
1868 r = -errno;
1869 goto child_fail;
1870 }
1871
1872 _exit(EXIT_SUCCESS);
1873
1874 child_fail:
1875 (void) write(errno_pipe[1], &r, sizeof(r));
1876 _exit(EXIT_FAILURE);
1877 }
1878
1879 errno_pipe[1] = safe_close(errno_pipe[1]);
1880
1881 if (unshare(CLONE_NEWUSER) < 0)
1882 return -errno;
1883
1884 /* Let the child know that the namespace is ready now */
1885 if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
1886 return -errno;
1887
1888 /* Try to read an error code from the child */
1889 n = read(errno_pipe[0], &r, sizeof(r));
1890 if (n < 0)
1891 return -errno;
1892 if (n == sizeof(r)) { /* an error code was sent to us */
1893 if (r < 0)
1894 return r;
1895 return -EIO;
1896 }
1897 if (n != 0) /* on success we should have read 0 bytes */
1898 return -EIO;
1899
1900 r = wait_for_terminate(pid, &si);
1901 if (r < 0)
1902 return r;
1903 pid = 0;
1904
1905 /* If something strange happened with the child, let's consider this fatal, too */
1906 if (si.si_code != CLD_EXITED || si.si_status != 0)
1907 return -EIO;
1908
1909 return 0;
1910}
1911
07689d5d
LP
1912static int setup_runtime_directory(
1913 const ExecContext *context,
1914 const ExecParameters *params,
1915 uid_t uid,
1916 gid_t gid) {
1917
1918 char **rt;
1919 int r;
1920
1921 assert(context);
1922 assert(params);
1923
1924 STRV_FOREACH(rt, context->runtime_directory) {
1925 _cleanup_free_ char *p;
1926
605405c6 1927 p = strjoin(params->runtime_prefix, "/", *rt);
07689d5d
LP
1928 if (!p)
1929 return -ENOMEM;
1930
1931 r = mkdir_p_label(p, context->runtime_directory_mode);
1932 if (r < 0)
1933 return r;
1934
1935 r = chmod_and_chown(p, context->runtime_directory_mode, uid, gid);
1936 if (r < 0)
1937 return r;
1938 }
1939
1940 return 0;
1941}
1942
cefc33ae
LP
1943static int setup_smack(
1944 const ExecContext *context,
1945 const ExecCommand *command) {
1946
1947#ifdef HAVE_SMACK
1948 int r;
1949
1950 assert(context);
1951 assert(command);
1952
1953 if (!mac_smack_use())
1954 return 0;
1955
1956 if (context->smack_process_label) {
1957 r = mac_smack_apply_pid(0, context->smack_process_label);
1958 if (r < 0)
1959 return r;
1960 }
1961#ifdef SMACK_DEFAULT_PROCESS_LABEL
1962 else {
1963 _cleanup_free_ char *exec_label = NULL;
1964
1965 r = mac_smack_read(command->path, SMACK_ATTR_EXEC, &exec_label);
1966 if (r < 0 && r != -ENODATA && r != -EOPNOTSUPP)
1967 return r;
1968
1969 r = mac_smack_apply_pid(0, exec_label ? : SMACK_DEFAULT_PROCESS_LABEL);
1970 if (r < 0)
1971 return r;
1972 }
1973#endif
1974#endif
1975
1976 return 0;
1977}
1978
3fbe8dbe
LP
1979static int compile_read_write_paths(
1980 const ExecContext *context,
1981 const ExecParameters *params,
1982 char ***ret) {
1983
1984 _cleanup_strv_free_ char **l = NULL;
1985 char **rt;
1986
1987 /* Compile the list of writable paths. This is the combination of the explicitly configured paths, plus all
1988 * runtime directories. */
1989
1990 if (strv_isempty(context->read_write_paths) &&
1991 strv_isempty(context->runtime_directory)) {
1992 *ret = NULL; /* NOP if neither is set */
1993 return 0;
1994 }
1995
1996 l = strv_copy(context->read_write_paths);
1997 if (!l)
1998 return -ENOMEM;
1999
2000 STRV_FOREACH(rt, context->runtime_directory) {
2001 char *s;
2002
605405c6 2003 s = strjoin(params->runtime_prefix, "/", *rt);
3fbe8dbe
LP
2004 if (!s)
2005 return -ENOMEM;
2006
2007 if (strv_consume(&l, s) < 0)
2008 return -ENOMEM;
2009 }
2010
2011 *ret = l;
2012 l = NULL;
2013
2014 return 0;
2015}
2016
93c6bb51
DH
2017static int apply_mount_namespace(Unit *u, const ExecContext *context,
2018 const ExecParameters *params,
2019 ExecRuntime *runtime) {
2020 int r;
2021 _cleanup_free_ char **rw = NULL;
2022 char *tmp = NULL, *var = NULL;
2023 const char *root_dir = NULL;
2024 NameSpaceInfo ns_info = {
2025 .private_dev = context->private_devices,
2026 .protect_control_groups = context->protect_control_groups,
2027 .protect_kernel_tunables = context->protect_kernel_tunables,
2028 .protect_kernel_modules = context->protect_kernel_modules,
2029 };
2030
2b3c1b9e
DH
2031 assert(context);
2032
93c6bb51
DH
2033 /* The runtime struct only contains the parent of the private /tmp,
2034 * which is non-accessible to world users. Inside of it there's a /tmp
2035 * that is sticky, and that's the one we want to use here. */
2036
2037 if (context->private_tmp && runtime) {
2038 if (runtime->tmp_dir)
2039 tmp = strjoina(runtime->tmp_dir, "/tmp");
2040 if (runtime->var_tmp_dir)
2041 var = strjoina(runtime->var_tmp_dir, "/tmp");
2042 }
2043
2044 r = compile_read_write_paths(context, params, &rw);
2045 if (r < 0)
2046 return r;
2047
2048 if (params->flags & EXEC_APPLY_CHROOT)
2049 root_dir = context->root_directory;
2050
2051 r = setup_namespace(root_dir, &ns_info, rw,
2052 context->read_only_paths,
2053 context->inaccessible_paths,
2054 tmp,
2055 var,
2056 context->protect_home,
2057 context->protect_system,
2058 context->mount_flags);
2059
2060 /* If we couldn't set up the namespace this is probably due to a
2061 * missing capability. In this case, silently proceeed. */
2062 if (IN_SET(r, -EPERM, -EACCES)) {
2063 log_open();
2064 log_unit_debug_errno(u, r, "Failed to set up namespace, assuming containerized execution, ignoring: %m");
2065 log_close();
2066 r = 0;
2067 }
2068
2069 return r;
2070}
2071
e7f1e7c6
DH
2072static int apply_working_directory(const ExecContext *context,
2073 const ExecParameters *params,
2b3c1b9e 2074 const char *home,
e7f1e7c6 2075 const bool needs_mount_ns) {
2b3c1b9e
DH
2076 const char *d;
2077 const char *wd;
2078
2079 assert(context);
2080
2081 if (context->working_directory_home)
2082 wd = home;
2083 else if (context->working_directory)
2084 wd = context->working_directory;
2085 else
2086 wd = "/";
e7f1e7c6
DH
2087
2088 if (params->flags & EXEC_APPLY_CHROOT) {
2089 if (!needs_mount_ns && context->root_directory)
2090 if (chroot(context->root_directory) < 0)
2091 return -errno;
2092
2b3c1b9e
DH
2093 d = wd;
2094 } else
2095 d = strjoina(strempty(context->root_directory), "/", strempty(wd));
e7f1e7c6 2096
2b3c1b9e
DH
2097 if (chdir(d) < 0 && !context->working_directory_missing_ok)
2098 return -errno;
e7f1e7c6
DH
2099
2100 return 0;
2101}
2102
29206d46
LP
2103static void append_socket_pair(int *array, unsigned *n, int pair[2]) {
2104 assert(array);
2105 assert(n);
2106
2107 if (!pair)
2108 return;
2109
2110 if (pair[0] >= 0)
2111 array[(*n)++] = pair[0];
2112 if (pair[1] >= 0)
2113 array[(*n)++] = pair[1];
2114}
2115
a34ceba6
LP
2116static int close_remaining_fds(
2117 const ExecParameters *params,
2118 ExecRuntime *runtime,
29206d46 2119 DynamicCreds *dcreds,
00d9ef85 2120 int user_lookup_fd,
a34ceba6
LP
2121 int socket_fd,
2122 int *fds, unsigned n_fds) {
2123
2124 unsigned n_dont_close = 0;
00d9ef85 2125 int dont_close[n_fds + 12];
a34ceba6
LP
2126
2127 assert(params);
2128
2129 if (params->stdin_fd >= 0)
2130 dont_close[n_dont_close++] = params->stdin_fd;
2131 if (params->stdout_fd >= 0)
2132 dont_close[n_dont_close++] = params->stdout_fd;
2133 if (params->stderr_fd >= 0)
2134 dont_close[n_dont_close++] = params->stderr_fd;
2135
2136 if (socket_fd >= 0)
2137 dont_close[n_dont_close++] = socket_fd;
2138 if (n_fds > 0) {
2139 memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
2140 n_dont_close += n_fds;
2141 }
2142
29206d46
LP
2143 if (runtime)
2144 append_socket_pair(dont_close, &n_dont_close, runtime->netns_storage_socket);
2145
2146 if (dcreds) {
2147 if (dcreds->user)
2148 append_socket_pair(dont_close, &n_dont_close, dcreds->user->storage_socket);
2149 if (dcreds->group)
2150 append_socket_pair(dont_close, &n_dont_close, dcreds->group->storage_socket);
a34ceba6
LP
2151 }
2152
00d9ef85
LP
2153 if (user_lookup_fd >= 0)
2154 dont_close[n_dont_close++] = user_lookup_fd;
2155
a34ceba6
LP
2156 return close_all_fds(dont_close, n_dont_close);
2157}
2158
59eeb84b
LP
2159static bool context_has_address_families(const ExecContext *c) {
2160 assert(c);
2161
2162 return c->address_families_whitelist ||
2163 !set_isempty(c->address_families);
2164}
2165
2166static bool context_has_syscall_filters(const ExecContext *c) {
2167 assert(c);
2168
2169 return c->syscall_whitelist ||
2170 !set_isempty(c->syscall_filter) ||
2171 !set_isempty(c->syscall_archs);
2172}
2173
2174static bool context_has_no_new_privileges(const ExecContext *c) {
2175 assert(c);
2176
2177 if (c->no_new_privileges)
2178 return true;
2179
2180 if (have_effective_cap(CAP_SYS_ADMIN)) /* if we are privileged, we don't need NNP */
2181 return false;
2182
2183 return context_has_address_families(c) || /* we need NNP if we have any form of seccomp and are unprivileged */
2184 c->memory_deny_write_execute ||
2185 c->restrict_realtime ||
2186 c->protect_kernel_tunables ||
4084e8fc
DH
2187 c->protect_kernel_modules ||
2188 c->private_devices ||
59eeb84b
LP
2189 context_has_syscall_filters(c);
2190}
2191
00d9ef85
LP
2192static int send_user_lookup(
2193 Unit *unit,
2194 int user_lookup_fd,
2195 uid_t uid,
2196 gid_t gid) {
2197
2198 assert(unit);
2199
2200 /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
2201 * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
2202 * specified. */
2203
2204 if (user_lookup_fd < 0)
2205 return 0;
2206
2207 if (!uid_is_valid(uid) && !gid_is_valid(gid))
2208 return 0;
2209
2210 if (writev(user_lookup_fd,
2211 (struct iovec[]) {
2212 { .iov_base = &uid, .iov_len = sizeof(uid) },
2213 { .iov_base = &gid, .iov_len = sizeof(gid) },
2214 { .iov_base = unit->id, .iov_len = strlen(unit->id) }}, 3) < 0)
2215 return -errno;
2216
2217 return 0;
2218}
2219
ff0af2a1 2220static int exec_child(
f2341e0a 2221 Unit *unit,
ff0af2a1
LP
2222 ExecCommand *command,
2223 const ExecContext *context,
2224 const ExecParameters *params,
2225 ExecRuntime *runtime,
29206d46 2226 DynamicCreds *dcreds,
ff0af2a1
LP
2227 char **argv,
2228 int socket_fd,
52c239d7 2229 int named_iofds[3],
ff0af2a1
LP
2230 int *fds, unsigned n_fds,
2231 char **files_env,
00d9ef85 2232 int user_lookup_fd,
ff0af2a1 2233 int *exit_status) {
d35fbf6b 2234
2065ca69 2235 _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **accum_env = NULL, **final_argv = NULL;
9008e1ac 2236 _cleanup_free_ char *mac_selinux_context_net = NULL;
4d885bd3
DH
2237 _cleanup_free_ gid_t *supplementary_gids = NULL;
2238 const char *username = NULL, *groupname = NULL;
2b3c1b9e 2239 const char *home = NULL, *shell = NULL;
7bce046b
LP
2240 dev_t journal_stream_dev = 0;
2241 ino_t journal_stream_ino = 0;
2242 bool needs_mount_namespace;
fed1e721
LP
2243 uid_t uid = UID_INVALID;
2244 gid_t gid = GID_INVALID;
4d885bd3 2245 int i, r, ngids = 0;
034c6ed7 2246
f2341e0a 2247 assert(unit);
5cb5a6ff
LP
2248 assert(command);
2249 assert(context);
d35fbf6b 2250 assert(params);
ff0af2a1 2251 assert(exit_status);
d35fbf6b
DM
2252
2253 rename_process_from_path(command->path);
2254
2255 /* We reset exactly these signals, since they are the
2256 * only ones we set to SIG_IGN in the main daemon. All
2257 * others we leave untouched because we set them to
2258 * SIG_DFL or a valid handler initially, both of which
2259 * will be demoted to SIG_DFL. */
ce30c8dc
LP
2260 (void) default_signals(SIGNALS_CRASH_HANDLER,
2261 SIGNALS_IGNORE, -1);
d35fbf6b
DM
2262
2263 if (context->ignore_sigpipe)
ce30c8dc 2264 (void) ignore_signals(SIGPIPE, -1);
d35fbf6b 2265
ff0af2a1
LP
2266 r = reset_signal_mask();
2267 if (r < 0) {
2268 *exit_status = EXIT_SIGNAL_MASK;
2269 return r;
d35fbf6b 2270 }
034c6ed7 2271
d35fbf6b
DM
2272 if (params->idle_pipe)
2273 do_idle_pipe_dance(params->idle_pipe);
4f2d528d 2274
d35fbf6b
DM
2275 /* Close sockets very early to make sure we don't
2276 * block init reexecution because it cannot bind its
2277 * sockets */
ff0af2a1 2278
d35fbf6b 2279 log_forget_fds();
4f2d528d 2280
00d9ef85 2281 r = close_remaining_fds(params, runtime, dcreds, user_lookup_fd, socket_fd, fds, n_fds);
ff0af2a1
LP
2282 if (r < 0) {
2283 *exit_status = EXIT_FDS;
2284 return r;
8c7be95e
LP
2285 }
2286
d35fbf6b
DM
2287 if (!context->same_pgrp)
2288 if (setsid() < 0) {
ff0af2a1 2289 *exit_status = EXIT_SETSID;
d35fbf6b
DM
2290 return -errno;
2291 }
9e2f7c11 2292
1e22b5cd 2293 exec_context_tty_reset(context, params);
d35fbf6b 2294
c39f1ce2 2295 if (params->flags & EXEC_CONFIRM_SPAWN) {
d35fbf6b
DM
2296 char response;
2297
ff0af2a1
LP
2298 r = ask_for_confirmation(&response, argv);
2299 if (r == -ETIMEDOUT)
d35fbf6b 2300 write_confirm_message("Confirmation question timed out, assuming positive response.\n");
ff0af2a1
LP
2301 else if (r < 0)
2302 write_confirm_message("Couldn't ask confirmation question, assuming positive response: %s\n", strerror(-r));
d35fbf6b
DM
2303 else if (response == 's') {
2304 write_confirm_message("Skipping execution.\n");
ff0af2a1 2305 *exit_status = EXIT_CONFIRM;
d35fbf6b
DM
2306 return -ECANCELED;
2307 } else if (response == 'n') {
2308 write_confirm_message("Failing execution.\n");
ff0af2a1 2309 *exit_status = 0;
d35fbf6b
DM
2310 return 0;
2311 }
2312 }
1a63a750 2313
29206d46
LP
2314 if (context->dynamic_user && dcreds) {
2315
409093fe
LP
2316 /* Make sure we bypass our own NSS module for any NSS checks */
2317 if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
2318 *exit_status = EXIT_USER;
2319 return -errno;
2320 }
2321
29206d46 2322 r = dynamic_creds_realize(dcreds, &uid, &gid);
ff0af2a1
LP
2323 if (r < 0) {
2324 *exit_status = EXIT_USER;
2325 return r;
524daa8c 2326 }
524daa8c 2327
92b25bca 2328 if (!uid_is_valid(uid) || !gid_is_valid(gid)) {
29206d46
LP
2329 *exit_status = EXIT_USER;
2330 return -ESRCH;
2331 }
5bc7452b 2332
29206d46
LP
2333 if (dcreds->user)
2334 username = dcreds->user->name;
2335
2336 } else {
4d885bd3
DH
2337 r = get_fixed_user(context, &username, &uid, &gid, &home, &shell);
2338 if (r < 0) {
2339 *exit_status = EXIT_USER;
2340 return r;
5bc7452b 2341 }
5bc7452b 2342
4d885bd3
DH
2343 r = get_fixed_group(context, &groupname, &gid);
2344 if (r < 0) {
2345 *exit_status = EXIT_GROUP;
2346 return r;
2347 }
cdc5d5c5 2348 }
29206d46 2349
cdc5d5c5
DH
2350 /* Initialize user supplementary groups and get SupplementaryGroups= ones */
2351 r = get_supplementary_groups(context, username, groupname, gid,
2352 &supplementary_gids, &ngids);
2353 if (r < 0) {
2354 *exit_status = EXIT_GROUP;
2355 return r;
29206d46 2356 }
5bc7452b 2357
00d9ef85
LP
2358 r = send_user_lookup(unit, user_lookup_fd, uid, gid);
2359 if (r < 0) {
2360 *exit_status = EXIT_USER;
2361 return r;
2362 }
2363
2364 user_lookup_fd = safe_close(user_lookup_fd);
2365
d35fbf6b
DM
2366 /* If a socket is connected to STDIN/STDOUT/STDERR, we
2367 * must sure to drop O_NONBLOCK */
2368 if (socket_fd >= 0)
a34ceba6 2369 (void) fd_nonblock(socket_fd, false);
acbb0225 2370
52c239d7 2371 r = setup_input(context, params, socket_fd, named_iofds);
ff0af2a1
LP
2372 if (r < 0) {
2373 *exit_status = EXIT_STDIN;
2374 return r;
d35fbf6b 2375 }
034c6ed7 2376
52c239d7 2377 r = setup_output(unit, context, params, STDOUT_FILENO, socket_fd, named_iofds, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
ff0af2a1
LP
2378 if (r < 0) {
2379 *exit_status = EXIT_STDOUT;
2380 return r;
d35fbf6b
DM
2381 }
2382
52c239d7 2383 r = setup_output(unit, context, params, STDERR_FILENO, socket_fd, named_iofds, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
ff0af2a1
LP
2384 if (r < 0) {
2385 *exit_status = EXIT_STDERR;
2386 return r;
d35fbf6b
DM
2387 }
2388
2389 if (params->cgroup_path) {
ff0af2a1
LP
2390 r = cg_attach_everywhere(params->cgroup_supported, params->cgroup_path, 0, NULL, NULL);
2391 if (r < 0) {
2392 *exit_status = EXIT_CGROUP;
2393 return r;
309bff19 2394 }
d35fbf6b 2395 }
309bff19 2396
d35fbf6b 2397 if (context->oom_score_adjust_set) {
d5243d62 2398 char t[DECIMAL_STR_MAX(context->oom_score_adjust)];
f2b68789 2399
d5243d62
LP
2400 /* When we can't make this change due to EPERM, then
2401 * let's silently skip over it. User namespaces
2402 * prohibit write access to this file, and we
2403 * shouldn't trip up over that. */
613b411c 2404
d5243d62 2405 sprintf(t, "%i", context->oom_score_adjust);
ad118bda 2406 r = write_string_file("/proc/self/oom_score_adj", t, 0);
6cb7fa17 2407 if (r == -EPERM || r == -EACCES) {
ff0af2a1 2408 log_open();
f2341e0a 2409 log_unit_debug_errno(unit, r, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
ff0af2a1
LP
2410 log_close();
2411 } else if (r < 0) {
2412 *exit_status = EXIT_OOM_ADJUST;
d35fbf6b 2413 return -errno;
613b411c 2414 }
d35fbf6b
DM
2415 }
2416
2417 if (context->nice_set)
2418 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
ff0af2a1 2419 *exit_status = EXIT_NICE;
d35fbf6b 2420 return -errno;
613b411c
LP
2421 }
2422
d35fbf6b
DM
2423 if (context->cpu_sched_set) {
2424 struct sched_param param = {
2425 .sched_priority = context->cpu_sched_priority,
2426 };
2427
ff0af2a1
LP
2428 r = sched_setscheduler(0,
2429 context->cpu_sched_policy |
2430 (context->cpu_sched_reset_on_fork ?
2431 SCHED_RESET_ON_FORK : 0),
2432 &param);
2433 if (r < 0) {
2434 *exit_status = EXIT_SETSCHEDULER;
d35fbf6b 2435 return -errno;
fc9b2a84 2436 }
d35fbf6b 2437 }
fc9b2a84 2438
d35fbf6b
DM
2439 if (context->cpuset)
2440 if (sched_setaffinity(0, CPU_ALLOC_SIZE(context->cpuset_ncpus), context->cpuset) < 0) {
ff0af2a1 2441 *exit_status = EXIT_CPUAFFINITY;
d35fbf6b 2442 return -errno;
034c6ed7
LP
2443 }
2444
d35fbf6b
DM
2445 if (context->ioprio_set)
2446 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
ff0af2a1 2447 *exit_status = EXIT_IOPRIO;
d35fbf6b
DM
2448 return -errno;
2449 }
da726a4d 2450
d35fbf6b
DM
2451 if (context->timer_slack_nsec != NSEC_INFINITY)
2452 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
ff0af2a1 2453 *exit_status = EXIT_TIMERSLACK;
d35fbf6b 2454 return -errno;
4c2630eb 2455 }
9eba9da4 2456
050f7277 2457 if (context->personality != PERSONALITY_INVALID)
d35fbf6b 2458 if (personality(context->personality) < 0) {
ff0af2a1 2459 *exit_status = EXIT_PERSONALITY;
d35fbf6b 2460 return -errno;
4c2630eb 2461 }
94f04347 2462
d35fbf6b 2463 if (context->utmp_id)
023a4f67
LP
2464 utmp_put_init_process(context->utmp_id, getpid(), getsid(0), context->tty_path,
2465 context->utmp_mode == EXEC_UTMP_INIT ? INIT_PROCESS :
2466 context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
2467 USER_PROCESS,
2468 username ? "root" : context->user);
d35fbf6b 2469
e0d2adfd 2470 if (context->user) {
ff0af2a1
LP
2471 r = chown_terminal(STDIN_FILENO, uid);
2472 if (r < 0) {
2473 *exit_status = EXIT_STDIN;
2474 return r;
071830ff 2475 }
d35fbf6b 2476 }
8e274523 2477
a931ad47
LP
2478 /* If delegation is enabled we'll pass ownership of the cgroup
2479 * (but only in systemd's own controller hierarchy!) to the
2480 * user of the new process. */
2481 if (params->cgroup_path && context->user && params->cgroup_delegate) {
ff0af2a1
LP
2482 r = cg_set_task_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, 0644, uid, gid);
2483 if (r < 0) {
2484 *exit_status = EXIT_CGROUP;
2485 return r;
d35fbf6b 2486 }
034c6ed7 2487
034c6ed7 2488
ff0af2a1
LP
2489 r = cg_set_group_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, 0755, uid, gid);
2490 if (r < 0) {
2491 *exit_status = EXIT_CGROUP;
2492 return r;
034c6ed7 2493 }
d35fbf6b 2494 }
034c6ed7 2495
d35fbf6b 2496 if (!strv_isempty(context->runtime_directory) && params->runtime_prefix) {
07689d5d
LP
2497 r = setup_runtime_directory(context, params, uid, gid);
2498 if (r < 0) {
2499 *exit_status = EXIT_RUNTIME_DIRECTORY;
2500 return r;
d35fbf6b
DM
2501 }
2502 }
94f04347 2503
7bce046b 2504 r = build_environment(
fd63e712 2505 unit,
7bce046b
LP
2506 context,
2507 params,
2508 n_fds,
2509 home,
2510 username,
2511 shell,
2512 journal_stream_dev,
2513 journal_stream_ino,
2514 &our_env);
2065ca69
JW
2515 if (r < 0) {
2516 *exit_status = EXIT_MEMORY;
2517 return r;
2518 }
2519
2520 r = build_pass_environment(context, &pass_env);
2521 if (r < 0) {
2522 *exit_status = EXIT_MEMORY;
2523 return r;
2524 }
2525
2526 accum_env = strv_env_merge(5,
2527 params->environment,
2528 our_env,
2529 pass_env,
2530 context->environment,
2531 files_env,
2532 NULL);
2533 if (!accum_env) {
2534 *exit_status = EXIT_MEMORY;
2535 return -ENOMEM;
2536 }
1280503b 2537 accum_env = strv_env_clean(accum_env);
2065ca69 2538
096424d1 2539 (void) umask(context->umask);
b213e1c1 2540
c39f1ce2 2541 if ((params->flags & EXEC_APPLY_PERMISSIONS) && !command->privileged) {
b213e1c1 2542 if (context->pam_name && username) {
2d6fce8d 2543 r = setup_pam(context->pam_name, username, uid, gid, context->tty_path, &accum_env, fds, n_fds);
b213e1c1
SW
2544 if (r < 0) {
2545 *exit_status = EXIT_PAM;
2546 return r;
2547 }
d35fbf6b 2548 }
b213e1c1 2549 }
ac45f971 2550
d35fbf6b 2551 if (context->private_network && runtime && runtime->netns_storage_socket[0] >= 0) {
ff0af2a1
LP
2552 r = setup_netns(runtime->netns_storage_socket);
2553 if (r < 0) {
2554 *exit_status = EXIT_NETWORK;
2555 return r;
d35fbf6b
DM
2556 }
2557 }
169c1bda 2558
ee818b89 2559 needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
ee818b89 2560 if (needs_mount_namespace) {
93c6bb51 2561 r = apply_mount_namespace(unit, context, params, runtime);
3fbe8dbe
LP
2562 if (r < 0) {
2563 *exit_status = EXIT_NAMESPACE;
2564 return r;
2565 }
d35fbf6b 2566 }
81a2b7ce 2567
50b3dfb9
DH
2568 /* Apply just after mount namespace setup */
2569 r = apply_working_directory(context, params, home, needs_mount_namespace);
2570 if (r < 0) {
2571 *exit_status = EXIT_CHROOT;
2572 return r;
2573 }
2574
bbeea271 2575 /* Drop groups as early as possbile */
096424d1 2576 if ((params->flags & EXEC_APPLY_PERMISSIONS) && !command->privileged) {
4d885bd3 2577 r = enforce_groups(context, gid, supplementary_gids, ngids);
096424d1
LP
2578 if (r < 0) {
2579 *exit_status = EXIT_GROUP;
2580 return r;
2581 }
2582 }
2583
9008e1ac 2584#ifdef HAVE_SELINUX
c39f1ce2
LP
2585 if ((params->flags & EXEC_APPLY_PERMISSIONS) &&
2586 mac_selinux_use() &&
2587 params->selinux_context_net &&
2588 socket_fd >= 0 &&
2589 !command->privileged) {
2590
ff0af2a1
LP
2591 r = mac_selinux_get_child_mls_label(socket_fd, command->path, context->selinux_context, &mac_selinux_context_net);
2592 if (r < 0) {
2593 *exit_status = EXIT_SELINUX_CONTEXT;
2594 return r;
9008e1ac
MS
2595 }
2596 }
2597#endif
2598
d87a2ef7 2599 if ((params->flags & EXEC_APPLY_PERMISSIONS) && context->private_users) {
d251207d
LP
2600 r = setup_private_users(uid, gid);
2601 if (r < 0) {
2602 *exit_status = EXIT_USER;
2603 return r;
2604 }
2605 }
2606
d35fbf6b
DM
2607 /* We repeat the fd closing here, to make sure that
2608 * nothing is leaked from the PAM modules. Note that
2609 * we are more aggressive this time since socket_fd
e44da745
DM
2610 * and the netns fds we don't need anymore. The custom
2611 * endpoint fd was needed to upload the policy and can
2612 * now be closed as well. */
ff0af2a1
LP
2613 r = close_all_fds(fds, n_fds);
2614 if (r >= 0)
2615 r = shift_fds(fds, n_fds);
2616 if (r >= 0)
2617 r = flags_fds(fds, n_fds, context->non_blocking);
2618 if (r < 0) {
2619 *exit_status = EXIT_FDS;
2620 return r;
d35fbf6b 2621 }
e66cf1a3 2622
c39f1ce2 2623 if ((params->flags & EXEC_APPLY_PERMISSIONS) && !command->privileged) {
e66cf1a3 2624
755d4b67
IP
2625 int secure_bits = context->secure_bits;
2626
d35fbf6b 2627 for (i = 0; i < _RLIMIT_MAX; i++) {
03857c43 2628
d35fbf6b
DM
2629 if (!context->rlimit[i])
2630 continue;
2631
03857c43
LP
2632 r = setrlimit_closest(i, context->rlimit[i]);
2633 if (r < 0) {
ff0af2a1 2634 *exit_status = EXIT_LIMITS;
03857c43 2635 return r;
e66cf1a3
LP
2636 }
2637 }
2638
f4170c67
LP
2639 /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested. */
2640 if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
2641 if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
2642 *exit_status = EXIT_LIMITS;
2643 return -errno;
2644 }
2645 }
2646
a103496c
IP
2647 if (!cap_test_all(context->capability_bounding_set)) {
2648 r = capability_bounding_set_drop(context->capability_bounding_set, false);
ff0af2a1
LP
2649 if (r < 0) {
2650 *exit_status = EXIT_CAPABILITIES;
2651 return r;
3b8bddde 2652 }
4c2630eb 2653 }
3b8bddde 2654
755d4b67
IP
2655 /* This is done before enforce_user, but ambient set
2656 * does not survive over setresuid() if keep_caps is not set. */
2657 if (context->capability_ambient_set != 0) {
2658 r = capability_ambient_set_apply(context->capability_ambient_set, true);
2659 if (r < 0) {
2660 *exit_status = EXIT_CAPABILITIES;
2661 return r;
2662 }
755d4b67
IP
2663 }
2664
d35fbf6b 2665 if (context->user) {
ff0af2a1
LP
2666 r = enforce_user(context, uid);
2667 if (r < 0) {
2668 *exit_status = EXIT_USER;
2669 return r;
5b6319dc 2670 }
755d4b67
IP
2671 if (context->capability_ambient_set != 0) {
2672
2673 /* Fix the ambient capabilities after user change. */
2674 r = capability_ambient_set_apply(context->capability_ambient_set, false);
2675 if (r < 0) {
2676 *exit_status = EXIT_CAPABILITIES;
2677 return r;
2678 }
2679
2680 /* If we were asked to change user and ambient capabilities
2681 * were requested, we had to add keep-caps to the securebits
2682 * so that we would maintain the inherited capability set
2683 * through the setresuid(). Make sure that the bit is added
2684 * also to the context secure_bits so that we don't try to
2685 * drop the bit away next. */
2686
7f508f2c 2687 secure_bits |= 1<<SECURE_KEEP_CAPS;
755d4b67 2688 }
5b6319dc 2689 }
d35fbf6b 2690
5cd9cd35
LP
2691 /* Apply the MAC contexts late, but before seccomp syscall filtering, as those should really be last to
2692 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
2693 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
2694 * are restricted. */
2695
2696#ifdef HAVE_SELINUX
2697 if (mac_selinux_use()) {
2698 char *exec_context = mac_selinux_context_net ?: context->selinux_context;
2699
2700 if (exec_context) {
2701 r = setexeccon(exec_context);
2702 if (r < 0) {
2703 *exit_status = EXIT_SELINUX_CONTEXT;
2704 return r;
2705 }
2706 }
2707 }
2708#endif
2709
2710 r = setup_smack(context, command);
2711 if (r < 0) {
2712 *exit_status = EXIT_SMACK_PROCESS_LABEL;
2713 return r;
2714 }
2715
2716#ifdef HAVE_APPARMOR
2717 if (context->apparmor_profile && mac_apparmor_use()) {
2718 r = aa_change_onexec(context->apparmor_profile);
2719 if (r < 0 && !context->apparmor_profile_ignore) {
2720 *exit_status = EXIT_APPARMOR_PROFILE;
2721 return -errno;
2722 }
2723 }
2724#endif
2725
d35fbf6b
DM
2726 /* PR_GET_SECUREBITS is not privileged, while
2727 * PR_SET_SECUREBITS is. So to suppress
2728 * potential EPERMs we'll try not to call
2729 * PR_SET_SECUREBITS unless necessary. */
755d4b67
IP
2730 if (prctl(PR_GET_SECUREBITS) != secure_bits)
2731 if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
ff0af2a1 2732 *exit_status = EXIT_SECUREBITS;
d35fbf6b 2733 return -errno;
ff01d048 2734 }
5b6319dc 2735
59eeb84b 2736 if (context_has_no_new_privileges(context))
d35fbf6b 2737 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
ff0af2a1 2738 *exit_status = EXIT_NO_NEW_PRIVILEGES;
d35fbf6b
DM
2739 return -errno;
2740 }
2741
2742#ifdef HAVE_SECCOMP
59eeb84b 2743 if (context_has_address_families(context)) {
83f12b27 2744 r = apply_address_families(unit, context);
ff0af2a1
LP
2745 if (r < 0) {
2746 *exit_status = EXIT_ADDRESS_FAMILIES;
2747 return r;
4c2630eb
MS
2748 }
2749 }
04aa0cb9 2750
f3e43635 2751 if (context->memory_deny_write_execute) {
83f12b27 2752 r = apply_memory_deny_write_execute(unit, context);
f3e43635
TM
2753 if (r < 0) {
2754 *exit_status = EXIT_SECCOMP;
2755 return r;
2756 }
2757 }
f4170c67
LP
2758
2759 if (context->restrict_realtime) {
83f12b27 2760 r = apply_restrict_realtime(unit, context);
f4170c67
LP
2761 if (r < 0) {
2762 *exit_status = EXIT_SECCOMP;
2763 return r;
2764 }
2765 }
2766
59eeb84b
LP
2767 if (context->protect_kernel_tunables) {
2768 r = apply_protect_sysctl(unit, context);
2769 if (r < 0) {
2770 *exit_status = EXIT_SECCOMP;
2771 return r;
502d704e
DH
2772 }
2773 }
2774
2775 if (context->protect_kernel_modules) {
2776 r = apply_protect_kernel_modules(unit, context);
2777 if (r < 0) {
2778 *exit_status = EXIT_SECCOMP;
2779 return r;
59eeb84b
LP
2780 }
2781 }
2782
ba128bb8
LP
2783 if (context->private_devices) {
2784 r = apply_private_devices(unit, context);
2785 if (r < 0) {
2786 *exit_status = EXIT_SECCOMP;
2787 return r;
2788 }
2789 }
2790
5cd9cd35
LP
2791 /* This really should remain the last step before the execve(), to make sure our own code is unaffected
2792 * by the filter as little as possible. */
59eeb84b 2793 if (context_has_syscall_filters(context)) {
83f12b27 2794 r = apply_seccomp(unit, context);
ff0af2a1
LP
2795 if (r < 0) {
2796 *exit_status = EXIT_SECCOMP;
2797 return r;
81a2b7ce 2798 }
d35fbf6b
DM
2799 }
2800#endif
d35fbf6b 2801 }
034c6ed7 2802
2065ca69 2803 final_argv = replace_env_argv(argv, accum_env);
d35fbf6b 2804 if (!final_argv) {
ff0af2a1 2805 *exit_status = EXIT_MEMORY;
d35fbf6b
DM
2806 return -ENOMEM;
2807 }
034c6ed7 2808
553d2243 2809 if (_unlikely_(log_get_max_level() >= LOG_DEBUG)) {
d35fbf6b 2810 _cleanup_free_ char *line;
81a2b7ce 2811
d35fbf6b
DM
2812 line = exec_command_line(final_argv);
2813 if (line) {
2814 log_open();
f2341e0a
LP
2815 log_struct(LOG_DEBUG,
2816 LOG_UNIT_ID(unit),
2817 "EXECUTABLE=%s", command->path,
2818 LOG_UNIT_MESSAGE(unit, "Executing: %s", line),
2819 NULL);
d35fbf6b
DM
2820 log_close();
2821 }
2822 }
dd305ec9 2823
2065ca69 2824 execve(command->path, final_argv, accum_env);
ff0af2a1 2825 *exit_status = EXIT_EXEC;
d35fbf6b
DM
2826 return -errno;
2827}
81a2b7ce 2828
f2341e0a
LP
2829int exec_spawn(Unit *unit,
2830 ExecCommand *command,
d35fbf6b
DM
2831 const ExecContext *context,
2832 const ExecParameters *params,
2833 ExecRuntime *runtime,
29206d46 2834 DynamicCreds *dcreds,
d35fbf6b 2835 pid_t *ret) {
8351ceae 2836
d35fbf6b
DM
2837 _cleanup_strv_free_ char **files_env = NULL;
2838 int *fds = NULL; unsigned n_fds = 0;
ff0af2a1
LP
2839 _cleanup_free_ char *line = NULL;
2840 int socket_fd, r;
52c239d7 2841 int named_iofds[3] = { -1, -1, -1 };
ff0af2a1 2842 char **argv;
d35fbf6b 2843 pid_t pid;
8351ceae 2844
f2341e0a 2845 assert(unit);
d35fbf6b
DM
2846 assert(command);
2847 assert(context);
2848 assert(ret);
2849 assert(params);
2850 assert(params->fds || params->n_fds <= 0);
4298d0b5 2851
d35fbf6b
DM
2852 if (context->std_input == EXEC_INPUT_SOCKET ||
2853 context->std_output == EXEC_OUTPUT_SOCKET ||
2854 context->std_error == EXEC_OUTPUT_SOCKET) {
17df7223 2855
ff0af2a1 2856 if (params->n_fds != 1) {
f2341e0a 2857 log_unit_error(unit, "Got more than one socket.");
d35fbf6b 2858 return -EINVAL;
ff0af2a1 2859 }
eef65bf3 2860
d35fbf6b
DM
2861 socket_fd = params->fds[0];
2862 } else {
2863 socket_fd = -1;
2864 fds = params->fds;
2865 n_fds = params->n_fds;
2866 }
94f04347 2867
52c239d7
LB
2868 r = exec_context_named_iofds(unit, context, params, named_iofds);
2869 if (r < 0)
2870 return log_unit_error_errno(unit, r, "Failed to load a named file descriptor: %m");
2871
f2341e0a 2872 r = exec_context_load_environment(unit, context, &files_env);
ff0af2a1 2873 if (r < 0)
f2341e0a 2874 return log_unit_error_errno(unit, r, "Failed to load environment files: %m");
034c6ed7 2875
d35fbf6b 2876 argv = params->argv ?: command->argv;
d35fbf6b
DM
2877 line = exec_command_line(argv);
2878 if (!line)
2879 return log_oom();
fab56fc5 2880
f2341e0a
LP
2881 log_struct(LOG_DEBUG,
2882 LOG_UNIT_ID(unit),
2883 LOG_UNIT_MESSAGE(unit, "About to execute: %s", line),
2884 "EXECUTABLE=%s", command->path,
2885 NULL);
d35fbf6b
DM
2886 pid = fork();
2887 if (pid < 0)
74129a12 2888 return log_unit_error_errno(unit, errno, "Failed to fork: %m");
d35fbf6b
DM
2889
2890 if (pid == 0) {
ff0af2a1
LP
2891 int exit_status;
2892
f2341e0a
LP
2893 r = exec_child(unit,
2894 command,
ff0af2a1
LP
2895 context,
2896 params,
2897 runtime,
29206d46 2898 dcreds,
ff0af2a1
LP
2899 argv,
2900 socket_fd,
52c239d7 2901 named_iofds,
ff0af2a1
LP
2902 fds, n_fds,
2903 files_env,
00d9ef85 2904 unit->manager->user_lookup_fds[1],
ff0af2a1
LP
2905 &exit_status);
2906 if (r < 0) {
4c2630eb 2907 log_open();
f2341e0a
LP
2908 log_struct_errno(LOG_ERR, r,
2909 LOG_MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED),
2910 LOG_UNIT_ID(unit),
2911 LOG_UNIT_MESSAGE(unit, "Failed at step %s spawning %s: %m",
2912 exit_status_to_string(exit_status, EXIT_STATUS_SYSTEMD),
2913 command->path),
2914 "EXECUTABLE=%s", command->path,
2915 NULL);
4c2630eb
MS
2916 }
2917
ff0af2a1 2918 _exit(exit_status);
034c6ed7
LP
2919 }
2920
f2341e0a 2921 log_unit_debug(unit, "Forked %s as "PID_FMT, command->path, pid);
23635a85 2922
80876c20
LP
2923 /* We add the new process to the cgroup both in the child (so
2924 * that we can be sure that no user code is ever executed
2925 * outside of the cgroup) and in the parent (so that we can be
2926 * sure that when we kill the cgroup the process will be
2927 * killed too). */
d35fbf6b 2928 if (params->cgroup_path)
dd305ec9 2929 (void) cg_attach(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, pid);
2da3263a 2930
b58b4116 2931 exec_status_start(&command->exec_status, pid);
9fb86720 2932
034c6ed7 2933 *ret = pid;
5cb5a6ff
LP
2934 return 0;
2935}
2936
034c6ed7
LP
2937void exec_context_init(ExecContext *c) {
2938 assert(c);
2939
4c12626c 2940 c->umask = 0022;
9eba9da4 2941 c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
94f04347 2942 c->cpu_sched_policy = SCHED_OTHER;
071830ff 2943 c->syslog_priority = LOG_DAEMON|LOG_INFO;
74922904 2944 c->syslog_level_prefix = true;
353e12c2 2945 c->ignore_sigpipe = true;
3a43da28 2946 c->timer_slack_nsec = NSEC_INFINITY;
050f7277 2947 c->personality = PERSONALITY_INVALID;
e66cf1a3 2948 c->runtime_directory_mode = 0755;
a103496c 2949 c->capability_bounding_set = CAP_ALL;
034c6ed7
LP
2950}
2951
613b411c 2952void exec_context_done(ExecContext *c) {
5cb5a6ff
LP
2953 unsigned l;
2954
2955 assert(c);
2956
6796073e
LP
2957 c->environment = strv_free(c->environment);
2958 c->environment_files = strv_free(c->environment_files);
b4c14404 2959 c->pass_environment = strv_free(c->pass_environment);
8c7be95e 2960
1f6b4113 2961 for (l = 0; l < ELEMENTSOF(c->rlimit); l++)
a1e58e8e 2962 c->rlimit[l] = mfree(c->rlimit[l]);
034c6ed7 2963
52c239d7
LB
2964 for (l = 0; l < 3; l++)
2965 c->stdio_fdname[l] = mfree(c->stdio_fdname[l]);
2966
a1e58e8e
LP
2967 c->working_directory = mfree(c->working_directory);
2968 c->root_directory = mfree(c->root_directory);
2969 c->tty_path = mfree(c->tty_path);
2970 c->syslog_identifier = mfree(c->syslog_identifier);
2971 c->user = mfree(c->user);
2972 c->group = mfree(c->group);
034c6ed7 2973
6796073e 2974 c->supplementary_groups = strv_free(c->supplementary_groups);
94f04347 2975
a1e58e8e 2976 c->pam_name = mfree(c->pam_name);
5b6319dc 2977
2a624c36
AP
2978 c->read_only_paths = strv_free(c->read_only_paths);
2979 c->read_write_paths = strv_free(c->read_write_paths);
2980 c->inaccessible_paths = strv_free(c->inaccessible_paths);
82c121a4
LP
2981
2982 if (c->cpuset)
2983 CPU_FREE(c->cpuset);
86a3475b 2984
a1e58e8e
LP
2985 c->utmp_id = mfree(c->utmp_id);
2986 c->selinux_context = mfree(c->selinux_context);
2987 c->apparmor_profile = mfree(c->apparmor_profile);
eef65bf3 2988
525d3cc7
LP
2989 c->syscall_filter = set_free(c->syscall_filter);
2990 c->syscall_archs = set_free(c->syscall_archs);
2991 c->address_families = set_free(c->address_families);
e66cf1a3 2992
6796073e 2993 c->runtime_directory = strv_free(c->runtime_directory);
e66cf1a3
LP
2994}
2995
2996int exec_context_destroy_runtime_directory(ExecContext *c, const char *runtime_prefix) {
2997 char **i;
2998
2999 assert(c);
3000
3001 if (!runtime_prefix)
3002 return 0;
3003
3004 STRV_FOREACH(i, c->runtime_directory) {
3005 _cleanup_free_ char *p;
3006
605405c6 3007 p = strjoin(runtime_prefix, "/", *i);
e66cf1a3
LP
3008 if (!p)
3009 return -ENOMEM;
3010
3011 /* We execute this synchronously, since we need to be
3012 * sure this is gone when we start the service
3013 * next. */
c6878637 3014 (void) rm_rf(p, REMOVE_ROOT);
e66cf1a3
LP
3015 }
3016
3017 return 0;
5cb5a6ff
LP
3018}
3019
43d0fcbd
LP
3020void exec_command_done(ExecCommand *c) {
3021 assert(c);
3022
a1e58e8e 3023 c->path = mfree(c->path);
43d0fcbd 3024
6796073e 3025 c->argv = strv_free(c->argv);
43d0fcbd
LP
3026}
3027
3028void exec_command_done_array(ExecCommand *c, unsigned n) {
3029 unsigned i;
3030
3031 for (i = 0; i < n; i++)
3032 exec_command_done(c+i);
3033}
3034
f1acf85a 3035ExecCommand* exec_command_free_list(ExecCommand *c) {
5cb5a6ff
LP
3036 ExecCommand *i;
3037
3038 while ((i = c)) {
71fda00f 3039 LIST_REMOVE(command, c, i);
43d0fcbd 3040 exec_command_done(i);
5cb5a6ff
LP
3041 free(i);
3042 }
f1acf85a
ZJS
3043
3044 return NULL;
5cb5a6ff
LP
3045}
3046
034c6ed7
LP
3047void exec_command_free_array(ExecCommand **c, unsigned n) {
3048 unsigned i;
3049
f1acf85a
ZJS
3050 for (i = 0; i < n; i++)
3051 c[i] = exec_command_free_list(c[i]);
034c6ed7
LP
3052}
3053
039f0e70 3054typedef struct InvalidEnvInfo {
f2341e0a 3055 Unit *unit;
039f0e70
LP
3056 const char *path;
3057} InvalidEnvInfo;
3058
3059static void invalid_env(const char *p, void *userdata) {
3060 InvalidEnvInfo *info = userdata;
3061
f2341e0a 3062 log_unit_error(info->unit, "Ignoring invalid environment assignment '%s': %s", p, info->path);
039f0e70
LP
3063}
3064
52c239d7
LB
3065const char* exec_context_fdname(const ExecContext *c, int fd_index) {
3066 assert(c);
3067
3068 switch (fd_index) {
3069 case STDIN_FILENO:
3070 if (c->std_input != EXEC_INPUT_NAMED_FD)
3071 return NULL;
3072 return c->stdio_fdname[STDIN_FILENO] ?: "stdin";
3073 case STDOUT_FILENO:
3074 if (c->std_output != EXEC_OUTPUT_NAMED_FD)
3075 return NULL;
3076 return c->stdio_fdname[STDOUT_FILENO] ?: "stdout";
3077 case STDERR_FILENO:
3078 if (c->std_error != EXEC_OUTPUT_NAMED_FD)
3079 return NULL;
3080 return c->stdio_fdname[STDERR_FILENO] ?: "stderr";
3081 default:
3082 return NULL;
3083 }
3084}
3085
3086int exec_context_named_iofds(Unit *unit, const ExecContext *c, const ExecParameters *p, int named_iofds[3]) {
3087 unsigned i, targets;
3088 const char *stdio_fdname[3];
3089
3090 assert(c);
3091 assert(p);
3092
3093 targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
3094 (c->std_output == EXEC_OUTPUT_NAMED_FD) +
3095 (c->std_error == EXEC_OUTPUT_NAMED_FD);
3096
3097 for (i = 0; i < 3; i++)
3098 stdio_fdname[i] = exec_context_fdname(c, i);
3099
3100 for (i = 0; i < p->n_fds && targets > 0; i++)
3101 if (named_iofds[STDIN_FILENO] < 0 && c->std_input == EXEC_INPUT_NAMED_FD && stdio_fdname[STDIN_FILENO] && streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
3102 named_iofds[STDIN_FILENO] = p->fds[i];
3103 targets--;
3104 } else if (named_iofds[STDOUT_FILENO] < 0 && c->std_output == EXEC_OUTPUT_NAMED_FD && stdio_fdname[STDOUT_FILENO] && streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
3105 named_iofds[STDOUT_FILENO] = p->fds[i];
3106 targets--;
3107 } else if (named_iofds[STDERR_FILENO] < 0 && c->std_error == EXEC_OUTPUT_NAMED_FD && stdio_fdname[STDERR_FILENO] && streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
3108 named_iofds[STDERR_FILENO] = p->fds[i];
3109 targets--;
3110 }
3111
3112 return (targets == 0 ? 0 : -ENOENT);
3113}
3114
f2341e0a 3115int exec_context_load_environment(Unit *unit, const ExecContext *c, char ***l) {
8c7be95e
LP
3116 char **i, **r = NULL;
3117
3118 assert(c);
3119 assert(l);
3120
3121 STRV_FOREACH(i, c->environment_files) {
3122 char *fn;
3123 int k;
3124 bool ignore = false;
3125 char **p;
7fd1b19b 3126 _cleanup_globfree_ glob_t pglob = {};
2bef10ab 3127 int count, n;
8c7be95e
LP
3128
3129 fn = *i;
3130
3131 if (fn[0] == '-') {
3132 ignore = true;
313cefa1 3133 fn++;
8c7be95e
LP
3134 }
3135
3136 if (!path_is_absolute(fn)) {
8c7be95e
LP
3137 if (ignore)
3138 continue;
3139
3140 strv_free(r);
3141 return -EINVAL;
3142 }
3143
2bef10ab 3144 /* Filename supports globbing, take all matching files */
2bef10ab
PL
3145 errno = 0;
3146 if (glob(fn, 0, NULL, &pglob) != 0) {
2bef10ab
PL
3147 if (ignore)
3148 continue;
8c7be95e 3149
2bef10ab 3150 strv_free(r);
f5e5c28f 3151 return errno > 0 ? -errno : -EINVAL;
2bef10ab
PL
3152 }
3153 count = pglob.gl_pathc;
3154 if (count == 0) {
8c7be95e
LP
3155 if (ignore)
3156 continue;
3157
3158 strv_free(r);
2bef10ab 3159 return -EINVAL;
8c7be95e 3160 }
2bef10ab 3161 for (n = 0; n < count; n++) {
717603e3 3162 k = load_env_file(NULL, pglob.gl_pathv[n], NULL, &p);
2bef10ab
PL
3163 if (k < 0) {
3164 if (ignore)
3165 continue;
8c7be95e 3166
2bef10ab 3167 strv_free(r);
2bef10ab 3168 return k;
e9c1ea9d 3169 }
ebc05a09 3170 /* Log invalid environment variables with filename */
039f0e70
LP
3171 if (p) {
3172 InvalidEnvInfo info = {
f2341e0a 3173 .unit = unit,
039f0e70
LP
3174 .path = pglob.gl_pathv[n]
3175 };
3176
3177 p = strv_env_clean_with_callback(p, invalid_env, &info);
3178 }
8c7be95e 3179
2bef10ab
PL
3180 if (r == NULL)
3181 r = p;
3182 else {
3183 char **m;
8c7be95e 3184
2bef10ab
PL
3185 m = strv_env_merge(2, r, p);
3186 strv_free(r);
3187 strv_free(p);
c84a9488 3188 if (!m)
2bef10ab 3189 return -ENOMEM;
2bef10ab
PL
3190
3191 r = m;
3192 }
8c7be95e
LP
3193 }
3194 }
3195
3196 *l = r;
3197
3198 return 0;
3199}
3200
6ac8fdc9 3201static bool tty_may_match_dev_console(const char *tty) {
e1d75803 3202 _cleanup_free_ char *active = NULL;
7d6884b6 3203 char *console;
6ac8fdc9 3204
1e22b5cd
LP
3205 if (!tty)
3206 return true;
3207
6ac8fdc9
MS
3208 if (startswith(tty, "/dev/"))
3209 tty += 5;
3210
3211 /* trivial identity? */
3212 if (streq(tty, "console"))
3213 return true;
3214
3215 console = resolve_dev_console(&active);
3216 /* if we could not resolve, assume it may */
3217 if (!console)
3218 return true;
3219
3220 /* "tty0" means the active VC, so it may be the same sometimes */
e1d75803 3221 return streq(console, tty) || (streq(console, "tty0") && tty_is_vc(tty));
6ac8fdc9
MS
3222}
3223
3224bool exec_context_may_touch_console(ExecContext *ec) {
1e22b5cd
LP
3225
3226 return (ec->tty_reset ||
3227 ec->tty_vhangup ||
3228 ec->tty_vt_disallocate ||
6ac8fdc9
MS
3229 is_terminal_input(ec->std_input) ||
3230 is_terminal_output(ec->std_output) ||
3231 is_terminal_output(ec->std_error)) &&
1e22b5cd 3232 tty_may_match_dev_console(exec_context_tty_path(ec));
6ac8fdc9
MS
3233}
3234
15ae422b
LP
3235static void strv_fprintf(FILE *f, char **l) {
3236 char **g;
3237
3238 assert(f);
3239
3240 STRV_FOREACH(g, l)
3241 fprintf(f, " %s", *g);
3242}
3243
5cb5a6ff 3244void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
c2bbd90b 3245 char **e, **d;
94f04347 3246 unsigned i;
9eba9da4 3247
5cb5a6ff
LP
3248 assert(c);
3249 assert(f);
3250
4ad49000 3251 prefix = strempty(prefix);
5cb5a6ff
LP
3252
3253 fprintf(f,
94f04347
LP
3254 "%sUMask: %04o\n"
3255 "%sWorkingDirectory: %s\n"
451a074f 3256 "%sRootDirectory: %s\n"
15ae422b 3257 "%sNonBlocking: %s\n"
64747e2d 3258 "%sPrivateTmp: %s\n"
7f112f50 3259 "%sPrivateDevices: %s\n"
59eeb84b 3260 "%sProtectKernelTunables: %s\n"
e66a2f65 3261 "%sProtectKernelModules: %s\n"
59eeb84b 3262 "%sProtectControlGroups: %s\n"
d251207d
LP
3263 "%sPrivateNetwork: %s\n"
3264 "%sPrivateUsers: %s\n"
1b8689f9
LP
3265 "%sProtectHome: %s\n"
3266 "%sProtectSystem: %s\n"
f3e43635 3267 "%sIgnoreSIGPIPE: %s\n"
f4170c67
LP
3268 "%sMemoryDenyWriteExecute: %s\n"
3269 "%sRestrictRealtime: %s\n",
5cb5a6ff 3270 prefix, c->umask,
9eba9da4 3271 prefix, c->working_directory ? c->working_directory : "/",
451a074f 3272 prefix, c->root_directory ? c->root_directory : "/",
15ae422b 3273 prefix, yes_no(c->non_blocking),
64747e2d 3274 prefix, yes_no(c->private_tmp),
7f112f50 3275 prefix, yes_no(c->private_devices),
59eeb84b 3276 prefix, yes_no(c->protect_kernel_tunables),
e66a2f65 3277 prefix, yes_no(c->protect_kernel_modules),
59eeb84b 3278 prefix, yes_no(c->protect_control_groups),
d251207d
LP
3279 prefix, yes_no(c->private_network),
3280 prefix, yes_no(c->private_users),
1b8689f9
LP
3281 prefix, protect_home_to_string(c->protect_home),
3282 prefix, protect_system_to_string(c->protect_system),
f3e43635 3283 prefix, yes_no(c->ignore_sigpipe),
f4170c67
LP
3284 prefix, yes_no(c->memory_deny_write_execute),
3285 prefix, yes_no(c->restrict_realtime));
fb33a393 3286
8c7be95e
LP
3287 STRV_FOREACH(e, c->environment)
3288 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
3289
3290 STRV_FOREACH(e, c->environment_files)
3291 fprintf(f, "%sEnvironmentFile: %s\n", prefix, *e);
94f04347 3292
b4c14404
FB
3293 STRV_FOREACH(e, c->pass_environment)
3294 fprintf(f, "%sPassEnvironment: %s\n", prefix, *e);
3295
c2bbd90b
EV
3296 fprintf(f, "%sRuntimeDirectoryMode: %04o\n", prefix, c->runtime_directory_mode);
3297
3298 STRV_FOREACH(d, c->runtime_directory)
3299 fprintf(f, "%sRuntimeDirectory: %s\n", prefix, *d);
3300
fb33a393
LP
3301 if (c->nice_set)
3302 fprintf(f,
3303 "%sNice: %i\n",
3304 prefix, c->nice);
3305
dd6c17b1 3306 if (c->oom_score_adjust_set)
fb33a393 3307 fprintf(f,
dd6c17b1
LP
3308 "%sOOMScoreAdjust: %i\n",
3309 prefix, c->oom_score_adjust);
9eba9da4 3310
94f04347 3311 for (i = 0; i < RLIM_NLIMITS; i++)
3c11da9d
EV
3312 if (c->rlimit[i]) {
3313 fprintf(f, "%s%s: " RLIM_FMT "\n",
3314 prefix, rlimit_to_string(i), c->rlimit[i]->rlim_max);
3315 fprintf(f, "%s%sSoft: " RLIM_FMT "\n",
3316 prefix, rlimit_to_string(i), c->rlimit[i]->rlim_cur);
3317 }
94f04347 3318
f8b69d1d 3319 if (c->ioprio_set) {
1756a011 3320 _cleanup_free_ char *class_str = NULL;
f8b69d1d 3321
1756a011 3322 ioprio_class_to_string_alloc(IOPRIO_PRIO_CLASS(c->ioprio), &class_str);
9eba9da4
LP
3323 fprintf(f,
3324 "%sIOSchedulingClass: %s\n"
3325 "%sIOPriority: %i\n",
f8b69d1d 3326 prefix, strna(class_str),
9eba9da4 3327 prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
f8b69d1d 3328 }
94f04347 3329
f8b69d1d 3330 if (c->cpu_sched_set) {
1756a011 3331 _cleanup_free_ char *policy_str = NULL;
f8b69d1d 3332
1756a011 3333 sched_policy_to_string_alloc(c->cpu_sched_policy, &policy_str);
94f04347
LP
3334 fprintf(f,
3335 "%sCPUSchedulingPolicy: %s\n"
38b48754
LP
3336 "%sCPUSchedulingPriority: %i\n"
3337 "%sCPUSchedulingResetOnFork: %s\n",
f8b69d1d 3338 prefix, strna(policy_str),
38b48754
LP
3339 prefix, c->cpu_sched_priority,
3340 prefix, yes_no(c->cpu_sched_reset_on_fork));
b929bf04 3341 }
94f04347 3342
82c121a4 3343 if (c->cpuset) {
94f04347 3344 fprintf(f, "%sCPUAffinity:", prefix);
82c121a4
LP
3345 for (i = 0; i < c->cpuset_ncpus; i++)
3346 if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
43a99a7a 3347 fprintf(f, " %u", i);
94f04347
LP
3348 fputs("\n", f);
3349 }
3350
3a43da28 3351 if (c->timer_slack_nsec != NSEC_INFINITY)
ccd06097 3352 fprintf(f, "%sTimerSlackNSec: "NSEC_FMT "\n", prefix, c->timer_slack_nsec);
94f04347
LP
3353
3354 fprintf(f,
80876c20
LP
3355 "%sStandardInput: %s\n"
3356 "%sStandardOutput: %s\n"
3357 "%sStandardError: %s\n",
3358 prefix, exec_input_to_string(c->std_input),
3359 prefix, exec_output_to_string(c->std_output),
3360 prefix, exec_output_to_string(c->std_error));
3361
3362 if (c->tty_path)
3363 fprintf(f,
6ea832a2
LP
3364 "%sTTYPath: %s\n"
3365 "%sTTYReset: %s\n"
3366 "%sTTYVHangup: %s\n"
3367 "%sTTYVTDisallocate: %s\n",
3368 prefix, c->tty_path,
3369 prefix, yes_no(c->tty_reset),
3370 prefix, yes_no(c->tty_vhangup),
3371 prefix, yes_no(c->tty_vt_disallocate));
94f04347 3372
5ce70e5b
ZJS
3373 if (c->std_output == EXEC_OUTPUT_SYSLOG ||
3374 c->std_output == EXEC_OUTPUT_KMSG ||
3375 c->std_output == EXEC_OUTPUT_JOURNAL ||
3376 c->std_output == EXEC_OUTPUT_SYSLOG_AND_CONSOLE ||
3377 c->std_output == EXEC_OUTPUT_KMSG_AND_CONSOLE ||
3378 c->std_output == EXEC_OUTPUT_JOURNAL_AND_CONSOLE ||
3379 c->std_error == EXEC_OUTPUT_SYSLOG ||
3380 c->std_error == EXEC_OUTPUT_KMSG ||
3381 c->std_error == EXEC_OUTPUT_JOURNAL ||
3382 c->std_error == EXEC_OUTPUT_SYSLOG_AND_CONSOLE ||
3383 c->std_error == EXEC_OUTPUT_KMSG_AND_CONSOLE ||
3384 c->std_error == EXEC_OUTPUT_JOURNAL_AND_CONSOLE) {
f8b69d1d 3385
5ce70e5b 3386 _cleanup_free_ char *fac_str = NULL, *lvl_str = NULL;
f8b69d1d 3387
5ce70e5b
ZJS
3388 log_facility_unshifted_to_string_alloc(c->syslog_priority >> 3, &fac_str);
3389 log_level_to_string_alloc(LOG_PRI(c->syslog_priority), &lvl_str);
f8b69d1d 3390
94f04347
LP
3391 fprintf(f,
3392 "%sSyslogFacility: %s\n"
3393 "%sSyslogLevel: %s\n",
f8b69d1d
MS
3394 prefix, strna(fac_str),
3395 prefix, strna(lvl_str));
f8b69d1d 3396 }
94f04347 3397
94f04347
LP
3398 if (c->secure_bits)
3399 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
3400 prefix,
cbb21cca
ZJS
3401 (c->secure_bits & 1<<SECURE_KEEP_CAPS) ? " keep-caps" : "",
3402 (c->secure_bits & 1<<SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
3403 (c->secure_bits & 1<<SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
3404 (c->secure_bits & 1<<SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
3405 (c->secure_bits & 1<<SECURE_NOROOT) ? " noroot" : "",
3406 (c->secure_bits & 1<<SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
94f04347 3407
a103496c 3408 if (c->capability_bounding_set != CAP_ALL) {
ae556c21 3409 unsigned long l;
260abb78 3410 fprintf(f, "%sCapabilityBoundingSet:", prefix);
94f04347 3411
64685e0c 3412 for (l = 0; l <= cap_last_cap(); l++)
a103496c 3413 if (c->capability_bounding_set & (UINT64_C(1) << l))
2822da4f 3414 fprintf(f, " %s", strna(capability_to_name(l)));
94f04347
LP
3415
3416 fputs("\n", f);
755d4b67
IP
3417 }
3418
3419 if (c->capability_ambient_set != 0) {
3420 unsigned long l;
3421 fprintf(f, "%sAmbientCapabilities:", prefix);
3422
3423 for (l = 0; l <= cap_last_cap(); l++)
3424 if (c->capability_ambient_set & (UINT64_C(1) << l))
3425 fprintf(f, " %s", strna(capability_to_name(l)));
3426
3427 fputs("\n", f);
94f04347
LP
3428 }
3429
3430 if (c->user)
f2d3769a 3431 fprintf(f, "%sUser: %s\n", prefix, c->user);
94f04347 3432 if (c->group)
f2d3769a 3433 fprintf(f, "%sGroup: %s\n", prefix, c->group);
94f04347 3434
29206d46
LP
3435 fprintf(f, "%sDynamicUser: %s\n", prefix, yes_no(c->dynamic_user));
3436
15ae422b 3437 if (strv_length(c->supplementary_groups) > 0) {
94f04347 3438 fprintf(f, "%sSupplementaryGroups:", prefix);
15ae422b
LP
3439 strv_fprintf(f, c->supplementary_groups);
3440 fputs("\n", f);
3441 }
94f04347 3442
5b6319dc 3443 if (c->pam_name)
f2d3769a 3444 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
5b6319dc 3445
2a624c36
AP
3446 if (strv_length(c->read_write_paths) > 0) {
3447 fprintf(f, "%sReadWritePaths:", prefix);
3448 strv_fprintf(f, c->read_write_paths);
15ae422b
LP
3449 fputs("\n", f);
3450 }
3451
2a624c36
AP
3452 if (strv_length(c->read_only_paths) > 0) {
3453 fprintf(f, "%sReadOnlyPaths:", prefix);
3454 strv_fprintf(f, c->read_only_paths);
15ae422b
LP
3455 fputs("\n", f);
3456 }
94f04347 3457
2a624c36
AP
3458 if (strv_length(c->inaccessible_paths) > 0) {
3459 fprintf(f, "%sInaccessiblePaths:", prefix);
3460 strv_fprintf(f, c->inaccessible_paths);
94f04347
LP
3461 fputs("\n", f);
3462 }
2e22afe9 3463
169c1bda
LP
3464 if (c->utmp_id)
3465 fprintf(f,
3466 "%sUtmpIdentifier: %s\n",
3467 prefix, c->utmp_id);
7b52a628
MS
3468
3469 if (c->selinux_context)
3470 fprintf(f,
5f8640fb
LP
3471 "%sSELinuxContext: %s%s\n",
3472 prefix, c->selinux_context_ignore ? "-" : "", c->selinux_context);
17df7223 3473
050f7277 3474 if (c->personality != PERSONALITY_INVALID)
ac45f971
LP
3475 fprintf(f,
3476 "%sPersonality: %s\n",
3477 prefix, strna(personality_to_string(c->personality)));
3478
17df7223 3479 if (c->syscall_filter) {
351a19b1 3480#ifdef HAVE_SECCOMP
17df7223
LP
3481 Iterator j;
3482 void *id;
3483 bool first = true;
351a19b1 3484#endif
17df7223
LP
3485
3486 fprintf(f,
57183d11 3487 "%sSystemCallFilter: ",
17df7223
LP
3488 prefix);
3489
3490 if (!c->syscall_whitelist)
3491 fputc('~', f);
3492
351a19b1 3493#ifdef HAVE_SECCOMP
17df7223
LP
3494 SET_FOREACH(id, c->syscall_filter, j) {
3495 _cleanup_free_ char *name = NULL;
3496
3497 if (first)
3498 first = false;
3499 else
3500 fputc(' ', f);
3501
57183d11 3502 name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
17df7223
LP
3503 fputs(strna(name), f);
3504 }
351a19b1 3505#endif
17df7223
LP
3506
3507 fputc('\n', f);
3508 }
3509
57183d11
LP
3510 if (c->syscall_archs) {
3511#ifdef HAVE_SECCOMP
3512 Iterator j;
3513 void *id;
3514#endif
3515
3516 fprintf(f,
3517 "%sSystemCallArchitectures:",
3518 prefix);
3519
3520#ifdef HAVE_SECCOMP
3521 SET_FOREACH(id, c->syscall_archs, j)
3522 fprintf(f, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id) - 1)));
3523#endif
3524 fputc('\n', f);
3525 }
3526
b3267152 3527 if (c->syscall_errno > 0)
17df7223
LP
3528 fprintf(f,
3529 "%sSystemCallErrorNumber: %s\n",
3530 prefix, strna(errno_to_name(c->syscall_errno)));
eef65bf3
MS
3531
3532 if (c->apparmor_profile)
3533 fprintf(f,
3534 "%sAppArmorProfile: %s%s\n",
3535 prefix, c->apparmor_profile_ignore ? "-" : "", c->apparmor_profile);
5cb5a6ff
LP
3536}
3537
a931ad47
LP
3538bool exec_context_maintains_privileges(ExecContext *c) {
3539 assert(c);
3540
61233823 3541 /* Returns true if the process forked off would run under
a931ad47
LP
3542 * an unchanged UID or as root. */
3543
3544 if (!c->user)
3545 return true;
3546
3547 if (streq(c->user, "root") || streq(c->user, "0"))
3548 return true;
3549
3550 return false;
3551}
3552
b58b4116 3553void exec_status_start(ExecStatus *s, pid_t pid) {
034c6ed7 3554 assert(s);
5cb5a6ff 3555
b58b4116
LP
3556 zero(*s);
3557 s->pid = pid;
3558 dual_timestamp_get(&s->start_timestamp);
3559}
3560
6ea832a2 3561void exec_status_exit(ExecStatus *s, ExecContext *context, pid_t pid, int code, int status) {
b58b4116
LP
3562 assert(s);
3563
0b1f4ae6 3564 if (s->pid && s->pid != pid)
b58b4116
LP
3565 zero(*s);
3566
034c6ed7 3567 s->pid = pid;
63983207 3568 dual_timestamp_get(&s->exit_timestamp);
9fb86720 3569
034c6ed7
LP
3570 s->code = code;
3571 s->status = status;
169c1bda 3572
6ea832a2
LP
3573 if (context) {
3574 if (context->utmp_id)
3575 utmp_put_dead_process(context->utmp_id, pid, code, status);
3576
1e22b5cd 3577 exec_context_tty_reset(context, NULL);
6ea832a2 3578 }
9fb86720
LP
3579}
3580
3581void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
3582 char buf[FORMAT_TIMESTAMP_MAX];
3583
3584 assert(s);
3585 assert(f);
3586
9fb86720
LP
3587 if (s->pid <= 0)
3588 return;
3589
4c940960
LP
3590 prefix = strempty(prefix);
3591
9fb86720 3592 fprintf(f,
ccd06097
ZJS
3593 "%sPID: "PID_FMT"\n",
3594 prefix, s->pid);
9fb86720 3595
af9d16e1 3596 if (dual_timestamp_is_set(&s->start_timestamp))
9fb86720
LP
3597 fprintf(f,
3598 "%sStart Timestamp: %s\n",
63983207 3599 prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
9fb86720 3600
af9d16e1 3601 if (dual_timestamp_is_set(&s->exit_timestamp))
9fb86720
LP
3602 fprintf(f,
3603 "%sExit Timestamp: %s\n"
3604 "%sExit Code: %s\n"
3605 "%sExit Status: %i\n",
63983207 3606 prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
9fb86720
LP
3607 prefix, sigchld_code_to_string(s->code),
3608 prefix, s->status);
5cb5a6ff 3609}
44d8db9e 3610
9e2f7c11 3611char *exec_command_line(char **argv) {
44d8db9e
LP
3612 size_t k;
3613 char *n, *p, **a;
3614 bool first = true;
3615
9e2f7c11 3616 assert(argv);
44d8db9e 3617
9164977d 3618 k = 1;
9e2f7c11 3619 STRV_FOREACH(a, argv)
44d8db9e
LP
3620 k += strlen(*a)+3;
3621
5cd9cd35
LP
3622 n = new(char, k);
3623 if (!n)
44d8db9e
LP
3624 return NULL;
3625
3626 p = n;
9e2f7c11 3627 STRV_FOREACH(a, argv) {
44d8db9e
LP
3628
3629 if (!first)
3630 *(p++) = ' ';
3631 else
3632 first = false;
3633
3634 if (strpbrk(*a, WHITESPACE)) {
3635 *(p++) = '\'';
3636 p = stpcpy(p, *a);
3637 *(p++) = '\'';
3638 } else
3639 p = stpcpy(p, *a);
3640
3641 }
3642
9164977d
LP
3643 *p = 0;
3644
44d8db9e
LP
3645 /* FIXME: this doesn't really handle arguments that have
3646 * spaces and ticks in them */
3647
3648 return n;
3649}
3650
3651void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
e1d75803 3652 _cleanup_free_ char *cmd = NULL;
4c940960 3653 const char *prefix2;
44d8db9e
LP
3654
3655 assert(c);
3656 assert(f);
3657
4c940960 3658 prefix = strempty(prefix);
63c372cb 3659 prefix2 = strjoina(prefix, "\t");
44d8db9e 3660
9e2f7c11 3661 cmd = exec_command_line(c->argv);
44d8db9e
LP
3662 fprintf(f,
3663 "%sCommand Line: %s\n",
3664 prefix, cmd ? cmd : strerror(ENOMEM));
3665
9fb86720 3666 exec_status_dump(&c->exec_status, f, prefix2);
44d8db9e
LP
3667}
3668
3669void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
3670 assert(f);
3671
4c940960 3672 prefix = strempty(prefix);
44d8db9e
LP
3673
3674 LIST_FOREACH(command, c, c)
3675 exec_command_dump(c, f, prefix);
3676}
94f04347 3677
a6a80b4f
LP
3678void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
3679 ExecCommand *end;
3680
3681 assert(l);
3682 assert(e);
3683
3684 if (*l) {
35b8ca3a 3685 /* It's kind of important, that we keep the order here */
71fda00f
LP
3686 LIST_FIND_TAIL(command, *l, end);
3687 LIST_INSERT_AFTER(command, *l, end, e);
a6a80b4f
LP
3688 } else
3689 *l = e;
3690}
3691
26fd040d
LP
3692int exec_command_set(ExecCommand *c, const char *path, ...) {
3693 va_list ap;
3694 char **l, *p;
3695
3696 assert(c);
3697 assert(path);
3698
3699 va_start(ap, path);
3700 l = strv_new_ap(path, ap);
3701 va_end(ap);
3702
3703 if (!l)
3704 return -ENOMEM;
3705
250a918d
LP
3706 p = strdup(path);
3707 if (!p) {
26fd040d
LP
3708 strv_free(l);
3709 return -ENOMEM;
3710 }
3711
3712 free(c->path);
3713 c->path = p;
3714
3715 strv_free(c->argv);
3716 c->argv = l;
3717
3718 return 0;
3719}
3720
86b23b07 3721int exec_command_append(ExecCommand *c, const char *path, ...) {
e63ff941 3722 _cleanup_strv_free_ char **l = NULL;
86b23b07 3723 va_list ap;
86b23b07
JS
3724 int r;
3725
3726 assert(c);
3727 assert(path);
3728
3729 va_start(ap, path);
3730 l = strv_new_ap(path, ap);
3731 va_end(ap);
3732
3733 if (!l)
3734 return -ENOMEM;
3735
e287086b 3736 r = strv_extend_strv(&c->argv, l, false);
e63ff941 3737 if (r < 0)
86b23b07 3738 return r;
86b23b07
JS
3739
3740 return 0;
3741}
3742
3743
613b411c
LP
3744static int exec_runtime_allocate(ExecRuntime **rt) {
3745
3746 if (*rt)
3747 return 0;
3748
3749 *rt = new0(ExecRuntime, 1);
f146f5e1 3750 if (!*rt)
613b411c
LP
3751 return -ENOMEM;
3752
3753 (*rt)->n_ref = 1;
3754 (*rt)->netns_storage_socket[0] = (*rt)->netns_storage_socket[1] = -1;
3755
3756 return 0;
3757}
3758
3759int exec_runtime_make(ExecRuntime **rt, ExecContext *c, const char *id) {
3760 int r;
3761
3762 assert(rt);
3763 assert(c);
3764 assert(id);
3765
3766 if (*rt)
3767 return 1;
3768
3769 if (!c->private_network && !c->private_tmp)
3770 return 0;
3771
3772 r = exec_runtime_allocate(rt);
3773 if (r < 0)
3774 return r;
3775
3776 if (c->private_network && (*rt)->netns_storage_socket[0] < 0) {
33df919d 3777 if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, (*rt)->netns_storage_socket) < 0)
613b411c
LP
3778 return -errno;
3779 }
3780
3781 if (c->private_tmp && !(*rt)->tmp_dir) {
3782 r = setup_tmp_dirs(id, &(*rt)->tmp_dir, &(*rt)->var_tmp_dir);
3783 if (r < 0)
3784 return r;
3785 }
3786
3787 return 1;
3788}
3789
3790ExecRuntime *exec_runtime_ref(ExecRuntime *r) {
3791 assert(r);
3792 assert(r->n_ref > 0);
3793
3794 r->n_ref++;
3795 return r;
3796}
3797
3798ExecRuntime *exec_runtime_unref(ExecRuntime *r) {
3799
3800 if (!r)
3801 return NULL;
3802
3803 assert(r->n_ref > 0);
3804
3805 r->n_ref--;
f2341e0a
LP
3806 if (r->n_ref > 0)
3807 return NULL;
3808
3809 free(r->tmp_dir);
3810 free(r->var_tmp_dir);
3811 safe_close_pair(r->netns_storage_socket);
6b430fdb 3812 return mfree(r);
613b411c
LP
3813}
3814
f2341e0a 3815int exec_runtime_serialize(Unit *u, ExecRuntime *rt, FILE *f, FDSet *fds) {
613b411c
LP
3816 assert(u);
3817 assert(f);
3818 assert(fds);
3819
3820 if (!rt)
3821 return 0;
3822
3823 if (rt->tmp_dir)
3824 unit_serialize_item(u, f, "tmp-dir", rt->tmp_dir);
3825
3826 if (rt->var_tmp_dir)
3827 unit_serialize_item(u, f, "var-tmp-dir", rt->var_tmp_dir);
3828
3829 if (rt->netns_storage_socket[0] >= 0) {
3830 int copy;
3831
3832 copy = fdset_put_dup(fds, rt->netns_storage_socket[0]);
3833 if (copy < 0)
3834 return copy;
3835
3836 unit_serialize_item_format(u, f, "netns-socket-0", "%i", copy);
3837 }
3838
3839 if (rt->netns_storage_socket[1] >= 0) {
3840 int copy;
3841
3842 copy = fdset_put_dup(fds, rt->netns_storage_socket[1]);
3843 if (copy < 0)
3844 return copy;
3845
3846 unit_serialize_item_format(u, f, "netns-socket-1", "%i", copy);
3847 }
3848
3849 return 0;
3850}
3851
f2341e0a 3852int exec_runtime_deserialize_item(Unit *u, ExecRuntime **rt, const char *key, const char *value, FDSet *fds) {
613b411c
LP
3853 int r;
3854
3855 assert(rt);
3856 assert(key);
3857 assert(value);
3858
3859 if (streq(key, "tmp-dir")) {
3860 char *copy;
3861
3862 r = exec_runtime_allocate(rt);
3863 if (r < 0)
f2341e0a 3864 return log_oom();
613b411c
LP
3865
3866 copy = strdup(value);
3867 if (!copy)
3868 return log_oom();
3869
3870 free((*rt)->tmp_dir);
3871 (*rt)->tmp_dir = copy;
3872
3873 } else if (streq(key, "var-tmp-dir")) {
3874 char *copy;
3875
3876 r = exec_runtime_allocate(rt);
3877 if (r < 0)
f2341e0a 3878 return log_oom();
613b411c
LP
3879
3880 copy = strdup(value);
3881 if (!copy)
3882 return log_oom();
3883
3884 free((*rt)->var_tmp_dir);
3885 (*rt)->var_tmp_dir = copy;
3886
3887 } else if (streq(key, "netns-socket-0")) {
3888 int fd;
3889
3890 r = exec_runtime_allocate(rt);
3891 if (r < 0)
f2341e0a 3892 return log_oom();
613b411c
LP
3893
3894 if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd))
f2341e0a 3895 log_unit_debug(u, "Failed to parse netns socket value: %s", value);
613b411c 3896 else {
03e334a1 3897 safe_close((*rt)->netns_storage_socket[0]);
613b411c
LP
3898 (*rt)->netns_storage_socket[0] = fdset_remove(fds, fd);
3899 }
3900 } else if (streq(key, "netns-socket-1")) {
3901 int fd;
3902
3903 r = exec_runtime_allocate(rt);
3904 if (r < 0)
f2341e0a 3905 return log_oom();
613b411c
LP
3906
3907 if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd))
f2341e0a 3908 log_unit_debug(u, "Failed to parse netns socket value: %s", value);
613b411c 3909 else {
03e334a1 3910 safe_close((*rt)->netns_storage_socket[1]);
613b411c
LP
3911 (*rt)->netns_storage_socket[1] = fdset_remove(fds, fd);
3912 }
3913 } else
3914 return 0;
3915
3916 return 1;
3917}
3918
3919static void *remove_tmpdir_thread(void *p) {
3920 _cleanup_free_ char *path = p;
3921
c6878637 3922 (void) rm_rf(path, REMOVE_ROOT|REMOVE_PHYSICAL);
613b411c
LP
3923 return NULL;
3924}
3925
3926void exec_runtime_destroy(ExecRuntime *rt) {
98b47d54
LP
3927 int r;
3928
613b411c
LP
3929 if (!rt)
3930 return;
3931
3932 /* If there are multiple users of this, let's leave the stuff around */
3933 if (rt->n_ref > 1)
3934 return;
3935
3936 if (rt->tmp_dir) {
3937 log_debug("Spawning thread to nuke %s", rt->tmp_dir);
98b47d54
LP
3938
3939 r = asynchronous_job(remove_tmpdir_thread, rt->tmp_dir);
3940 if (r < 0) {
da927ba9 3941 log_warning_errno(r, "Failed to nuke %s: %m", rt->tmp_dir);
98b47d54
LP
3942 free(rt->tmp_dir);
3943 }
3944
613b411c
LP
3945 rt->tmp_dir = NULL;
3946 }
3947
3948 if (rt->var_tmp_dir) {
3949 log_debug("Spawning thread to nuke %s", rt->var_tmp_dir);
98b47d54
LP
3950
3951 r = asynchronous_job(remove_tmpdir_thread, rt->var_tmp_dir);
3952 if (r < 0) {
da927ba9 3953 log_warning_errno(r, "Failed to nuke %s: %m", rt->var_tmp_dir);
98b47d54
LP
3954 free(rt->var_tmp_dir);
3955 }
3956
613b411c
LP
3957 rt->var_tmp_dir = NULL;
3958 }
3959
3d94f76c 3960 safe_close_pair(rt->netns_storage_socket);
613b411c
LP
3961}
3962
80876c20
LP
3963static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
3964 [EXEC_INPUT_NULL] = "null",
3965 [EXEC_INPUT_TTY] = "tty",
3966 [EXEC_INPUT_TTY_FORCE] = "tty-force",
4f2d528d 3967 [EXEC_INPUT_TTY_FAIL] = "tty-fail",
52c239d7
LB
3968 [EXEC_INPUT_SOCKET] = "socket",
3969 [EXEC_INPUT_NAMED_FD] = "fd",
80876c20
LP
3970};
3971
8a0867d6
LP
3972DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);
3973
94f04347 3974static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
80876c20 3975 [EXEC_OUTPUT_INHERIT] = "inherit",
94f04347 3976 [EXEC_OUTPUT_NULL] = "null",
80876c20 3977 [EXEC_OUTPUT_TTY] = "tty",
94f04347 3978 [EXEC_OUTPUT_SYSLOG] = "syslog",
28dbc1e8 3979 [EXEC_OUTPUT_SYSLOG_AND_CONSOLE] = "syslog+console",
9a6bca7a 3980 [EXEC_OUTPUT_KMSG] = "kmsg",
28dbc1e8 3981 [EXEC_OUTPUT_KMSG_AND_CONSOLE] = "kmsg+console",
706343f4
LP
3982 [EXEC_OUTPUT_JOURNAL] = "journal",
3983 [EXEC_OUTPUT_JOURNAL_AND_CONSOLE] = "journal+console",
52c239d7
LB
3984 [EXEC_OUTPUT_SOCKET] = "socket",
3985 [EXEC_OUTPUT_NAMED_FD] = "fd",
94f04347
LP
3986};
3987
3988DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
023a4f67
LP
3989
3990static const char* const exec_utmp_mode_table[_EXEC_UTMP_MODE_MAX] = {
3991 [EXEC_UTMP_INIT] = "init",
3992 [EXEC_UTMP_LOGIN] = "login",
3993 [EXEC_UTMP_USER] = "user",
3994};
3995
3996DEFINE_STRING_TABLE_LOOKUP(exec_utmp_mode, ExecUtmpMode);