]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/execute.c
core: add new RestrictNamespaces= unit file setting
[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"
6482f626 74#include "formats-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
add00535
LP
1537static int apply_restrict_namespaces(Unit *u, const ExecContext *c) {
1538 assert(c);
1539
1540 if (!exec_context_restrict_namespaces_set(c))
1541 return 0;
1542
1543 if (skip_seccomp_unavailable(u, "RestrictNamespaces="))
1544 return 0;
1545
1546 return seccomp_restrict_namespaces(c->restrict_namespaces);
1547}
1548
c0467cf3 1549#endif
8351ceae 1550
31a7eb86
ZJS
1551static void do_idle_pipe_dance(int idle_pipe[4]) {
1552 assert(idle_pipe);
1553
54eb2300
LP
1554 idle_pipe[1] = safe_close(idle_pipe[1]);
1555 idle_pipe[2] = safe_close(idle_pipe[2]);
31a7eb86
ZJS
1556
1557 if (idle_pipe[0] >= 0) {
1558 int r;
1559
1560 r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
1561
1562 if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
c7cc737f
LP
1563 ssize_t n;
1564
31a7eb86 1565 /* Signal systemd that we are bored and want to continue. */
c7cc737f
LP
1566 n = write(idle_pipe[3], "x", 1);
1567 if (n > 0)
cd972d69
ZJS
1568 /* Wait for systemd to react to the signal above. */
1569 fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
31a7eb86
ZJS
1570 }
1571
54eb2300 1572 idle_pipe[0] = safe_close(idle_pipe[0]);
31a7eb86
ZJS
1573
1574 }
1575
54eb2300 1576 idle_pipe[3] = safe_close(idle_pipe[3]);
31a7eb86
ZJS
1577}
1578
7cae38c4 1579static int build_environment(
fd63e712 1580 Unit *u,
9fa95f85 1581 const ExecContext *c,
1e22b5cd 1582 const ExecParameters *p,
7cae38c4
LP
1583 unsigned n_fds,
1584 const char *home,
1585 const char *username,
1586 const char *shell,
7bce046b
LP
1587 dev_t journal_stream_dev,
1588 ino_t journal_stream_ino,
7cae38c4
LP
1589 char ***ret) {
1590
1591 _cleanup_strv_free_ char **our_env = NULL;
1592 unsigned n_env = 0;
1593 char *x;
1594
4b58153d 1595 assert(u);
7cae38c4
LP
1596 assert(c);
1597 assert(ret);
1598
4b58153d 1599 our_env = new0(char*, 14);
7cae38c4
LP
1600 if (!our_env)
1601 return -ENOMEM;
1602
1603 if (n_fds > 0) {
8dd4c05b
LP
1604 _cleanup_free_ char *joined = NULL;
1605
ccd06097 1606 if (asprintf(&x, "LISTEN_PID="PID_FMT, getpid()) < 0)
7cae38c4
LP
1607 return -ENOMEM;
1608 our_env[n_env++] = x;
1609
1610 if (asprintf(&x, "LISTEN_FDS=%u", n_fds) < 0)
1611 return -ENOMEM;
1612 our_env[n_env++] = x;
8dd4c05b 1613
1e22b5cd 1614 joined = strv_join(p->fd_names, ":");
8dd4c05b
LP
1615 if (!joined)
1616 return -ENOMEM;
1617
605405c6 1618 x = strjoin("LISTEN_FDNAMES=", joined);
8dd4c05b
LP
1619 if (!x)
1620 return -ENOMEM;
1621 our_env[n_env++] = x;
7cae38c4
LP
1622 }
1623
b08af3b1 1624 if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) {
ccd06097 1625 if (asprintf(&x, "WATCHDOG_PID="PID_FMT, getpid()) < 0)
09812eb7
LP
1626 return -ENOMEM;
1627 our_env[n_env++] = x;
1628
1e22b5cd 1629 if (asprintf(&x, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec) < 0)
09812eb7
LP
1630 return -ENOMEM;
1631 our_env[n_env++] = x;
1632 }
1633
fd63e712
LP
1634 /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use D-Bus look up dynamic
1635 * users via PID 1, possibly dead-locking the dbus daemon. This way it will not use D-Bus to resolve names, but
1636 * check the database directly. */
1637 if (unit_has_name(u, SPECIAL_DBUS_SERVICE)) {
1638 x = strdup("SYSTEMD_NSS_BYPASS_BUS=1");
1639 if (!x)
1640 return -ENOMEM;
1641 our_env[n_env++] = x;
1642 }
1643
7cae38c4
LP
1644 if (home) {
1645 x = strappend("HOME=", home);
1646 if (!x)
1647 return -ENOMEM;
1648 our_env[n_env++] = x;
1649 }
1650
1651 if (username) {
1652 x = strappend("LOGNAME=", username);
1653 if (!x)
1654 return -ENOMEM;
1655 our_env[n_env++] = x;
1656
1657 x = strappend("USER=", username);
1658 if (!x)
1659 return -ENOMEM;
1660 our_env[n_env++] = x;
1661 }
1662
1663 if (shell) {
1664 x = strappend("SHELL=", shell);
1665 if (!x)
1666 return -ENOMEM;
1667 our_env[n_env++] = x;
1668 }
1669
4b58153d
LP
1670 if (!sd_id128_is_null(u->invocation_id)) {
1671 if (asprintf(&x, "INVOCATION_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(u->invocation_id)) < 0)
1672 return -ENOMEM;
1673
1674 our_env[n_env++] = x;
1675 }
1676
6af760f3
LP
1677 if (exec_context_needs_term(c)) {
1678 const char *tty_path, *term = NULL;
1679
1680 tty_path = exec_context_tty_path(c);
1681
1682 /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try to inherit
1683 * the $TERM set for PID 1. This is useful for containers so that the $TERM the container manager
1684 * passes to PID 1 ends up all the way in the console login shown. */
1685
1686 if (path_equal(tty_path, "/dev/console") && getppid() == 1)
1687 term = getenv("TERM");
1688 if (!term)
1689 term = default_term_for_tty(tty_path);
7cae38c4 1690
6af760f3 1691 x = strappend("TERM=", term);
7cae38c4
LP
1692 if (!x)
1693 return -ENOMEM;
1694 our_env[n_env++] = x;
1695 }
1696
7bce046b
LP
1697 if (journal_stream_dev != 0 && journal_stream_ino != 0) {
1698 if (asprintf(&x, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino) < 0)
1699 return -ENOMEM;
1700
1701 our_env[n_env++] = x;
1702 }
1703
7cae38c4 1704 our_env[n_env++] = NULL;
7bce046b 1705 assert(n_env <= 12);
7cae38c4
LP
1706
1707 *ret = our_env;
1708 our_env = NULL;
1709
1710 return 0;
1711}
1712
b4c14404
FB
1713static int build_pass_environment(const ExecContext *c, char ***ret) {
1714 _cleanup_strv_free_ char **pass_env = NULL;
1715 size_t n_env = 0, n_bufsize = 0;
1716 char **i;
1717
1718 STRV_FOREACH(i, c->pass_environment) {
1719 _cleanup_free_ char *x = NULL;
1720 char *v;
1721
1722 v = getenv(*i);
1723 if (!v)
1724 continue;
605405c6 1725 x = strjoin(*i, "=", v);
b4c14404
FB
1726 if (!x)
1727 return -ENOMEM;
1728 if (!GREEDY_REALLOC(pass_env, n_bufsize, n_env + 2))
1729 return -ENOMEM;
1730 pass_env[n_env++] = x;
1731 pass_env[n_env] = NULL;
1732 x = NULL;
1733 }
1734
1735 *ret = pass_env;
1736 pass_env = NULL;
1737
1738 return 0;
1739}
1740
8b44a3d2
LP
1741static bool exec_needs_mount_namespace(
1742 const ExecContext *context,
1743 const ExecParameters *params,
1744 ExecRuntime *runtime) {
1745
1746 assert(context);
1747 assert(params);
1748
2a624c36
AP
1749 if (!strv_isempty(context->read_write_paths) ||
1750 !strv_isempty(context->read_only_paths) ||
1751 !strv_isempty(context->inaccessible_paths))
8b44a3d2
LP
1752 return true;
1753
1754 if (context->mount_flags != 0)
1755 return true;
1756
1757 if (context->private_tmp && runtime && (runtime->tmp_dir || runtime->var_tmp_dir))
1758 return true;
1759
8b44a3d2
LP
1760 if (context->private_devices ||
1761 context->protect_system != PROTECT_SYSTEM_NO ||
59eeb84b
LP
1762 context->protect_home != PROTECT_HOME_NO ||
1763 context->protect_kernel_tunables ||
c575770b 1764 context->protect_kernel_modules ||
59eeb84b 1765 context->protect_control_groups)
8b44a3d2
LP
1766 return true;
1767
1768 return false;
1769}
1770
d251207d
LP
1771static int setup_private_users(uid_t uid, gid_t gid) {
1772 _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
1773 _cleanup_close_pair_ int errno_pipe[2] = { -1, -1 };
1774 _cleanup_close_ int unshare_ready_fd = -1;
1775 _cleanup_(sigkill_waitp) pid_t pid = 0;
1776 uint64_t c = 1;
1777 siginfo_t si;
1778 ssize_t n;
1779 int r;
1780
1781 /* Set up a user namespace and map root to root, the selected UID/GID to itself, and everything else to
1782 * nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which
1783 * we however lack after opening the user namespace. To work around this we fork() a temporary child process,
1784 * which waits for the parent to create the new user namespace while staying in the original namespace. The
1785 * child then writes the UID mapping, under full privileges. The parent waits for the child to finish and
1786 * continues execution normally. */
1787
1788 if (uid != 0 && uid_is_valid(uid))
1789 asprintf(&uid_map,
1790 "0 0 1\n" /* Map root → root */
1791 UID_FMT " " UID_FMT " 1\n", /* Map $UID → $UID */
e0f3720e 1792 uid, uid);
d251207d 1793 else
e0f3720e 1794 uid_map = strdup("0 0 1\n"); /* The case where the above is the same */
d251207d
LP
1795 if (!uid_map)
1796 return -ENOMEM;
1797
1798 if (gid != 0 && gid_is_valid(gid))
1799 asprintf(&gid_map,
1800 "0 0 1\n" /* Map root → root */
1801 GID_FMT " " GID_FMT " 1\n", /* Map $GID → $GID */
1802 gid, gid);
1803 else
1804 gid_map = strdup("0 0 1\n"); /* The case where the above is the same */
1805 if (!gid_map)
1806 return -ENOMEM;
1807
1808 /* Create a communication channel so that the parent can tell the child when it finished creating the user
1809 * namespace. */
1810 unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
1811 if (unshare_ready_fd < 0)
1812 return -errno;
1813
1814 /* Create a communication channel so that the child can tell the parent a proper error code in case it
1815 * failed. */
1816 if (pipe2(errno_pipe, O_CLOEXEC) < 0)
1817 return -errno;
1818
1819 pid = fork();
1820 if (pid < 0)
1821 return -errno;
1822
1823 if (pid == 0) {
1824 _cleanup_close_ int fd = -1;
1825 const char *a;
1826 pid_t ppid;
1827
1828 /* Child process, running in the original user namespace. Let's update the parent's UID/GID map from
1829 * here, after the parent opened its own user namespace. */
1830
1831 ppid = getppid();
1832 errno_pipe[0] = safe_close(errno_pipe[0]);
1833
1834 /* Wait until the parent unshared the user namespace */
1835 if (read(unshare_ready_fd, &c, sizeof(c)) < 0) {
1836 r = -errno;
1837 goto child_fail;
1838 }
1839
1840 /* Disable the setgroups() system call in the child user namespace, for good. */
1841 a = procfs_file_alloca(ppid, "setgroups");
1842 fd = open(a, O_WRONLY|O_CLOEXEC);
1843 if (fd < 0) {
1844 if (errno != ENOENT) {
1845 r = -errno;
1846 goto child_fail;
1847 }
1848
1849 /* If the file is missing the kernel is too old, let's continue anyway. */
1850 } else {
1851 if (write(fd, "deny\n", 5) < 0) {
1852 r = -errno;
1853 goto child_fail;
1854 }
1855
1856 fd = safe_close(fd);
1857 }
1858
1859 /* First write the GID map */
1860 a = procfs_file_alloca(ppid, "gid_map");
1861 fd = open(a, O_WRONLY|O_CLOEXEC);
1862 if (fd < 0) {
1863 r = -errno;
1864 goto child_fail;
1865 }
1866 if (write(fd, gid_map, strlen(gid_map)) < 0) {
1867 r = -errno;
1868 goto child_fail;
1869 }
1870 fd = safe_close(fd);
1871
1872 /* The write the UID map */
1873 a = procfs_file_alloca(ppid, "uid_map");
1874 fd = open(a, O_WRONLY|O_CLOEXEC);
1875 if (fd < 0) {
1876 r = -errno;
1877 goto child_fail;
1878 }
1879 if (write(fd, uid_map, strlen(uid_map)) < 0) {
1880 r = -errno;
1881 goto child_fail;
1882 }
1883
1884 _exit(EXIT_SUCCESS);
1885
1886 child_fail:
1887 (void) write(errno_pipe[1], &r, sizeof(r));
1888 _exit(EXIT_FAILURE);
1889 }
1890
1891 errno_pipe[1] = safe_close(errno_pipe[1]);
1892
1893 if (unshare(CLONE_NEWUSER) < 0)
1894 return -errno;
1895
1896 /* Let the child know that the namespace is ready now */
1897 if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
1898 return -errno;
1899
1900 /* Try to read an error code from the child */
1901 n = read(errno_pipe[0], &r, sizeof(r));
1902 if (n < 0)
1903 return -errno;
1904 if (n == sizeof(r)) { /* an error code was sent to us */
1905 if (r < 0)
1906 return r;
1907 return -EIO;
1908 }
1909 if (n != 0) /* on success we should have read 0 bytes */
1910 return -EIO;
1911
1912 r = wait_for_terminate(pid, &si);
1913 if (r < 0)
1914 return r;
1915 pid = 0;
1916
1917 /* If something strange happened with the child, let's consider this fatal, too */
1918 if (si.si_code != CLD_EXITED || si.si_status != 0)
1919 return -EIO;
1920
1921 return 0;
1922}
1923
07689d5d
LP
1924static int setup_runtime_directory(
1925 const ExecContext *context,
1926 const ExecParameters *params,
1927 uid_t uid,
1928 gid_t gid) {
1929
1930 char **rt;
1931 int r;
1932
1933 assert(context);
1934 assert(params);
1935
1936 STRV_FOREACH(rt, context->runtime_directory) {
1937 _cleanup_free_ char *p;
1938
605405c6 1939 p = strjoin(params->runtime_prefix, "/", *rt);
07689d5d
LP
1940 if (!p)
1941 return -ENOMEM;
1942
1943 r = mkdir_p_label(p, context->runtime_directory_mode);
1944 if (r < 0)
1945 return r;
1946
1947 r = chmod_and_chown(p, context->runtime_directory_mode, uid, gid);
1948 if (r < 0)
1949 return r;
1950 }
1951
1952 return 0;
1953}
1954
cefc33ae
LP
1955static int setup_smack(
1956 const ExecContext *context,
1957 const ExecCommand *command) {
1958
1959#ifdef HAVE_SMACK
1960 int r;
1961
1962 assert(context);
1963 assert(command);
1964
1965 if (!mac_smack_use())
1966 return 0;
1967
1968 if (context->smack_process_label) {
1969 r = mac_smack_apply_pid(0, context->smack_process_label);
1970 if (r < 0)
1971 return r;
1972 }
1973#ifdef SMACK_DEFAULT_PROCESS_LABEL
1974 else {
1975 _cleanup_free_ char *exec_label = NULL;
1976
1977 r = mac_smack_read(command->path, SMACK_ATTR_EXEC, &exec_label);
1978 if (r < 0 && r != -ENODATA && r != -EOPNOTSUPP)
1979 return r;
1980
1981 r = mac_smack_apply_pid(0, exec_label ? : SMACK_DEFAULT_PROCESS_LABEL);
1982 if (r < 0)
1983 return r;
1984 }
1985#endif
1986#endif
1987
1988 return 0;
1989}
1990
3fbe8dbe
LP
1991static int compile_read_write_paths(
1992 const ExecContext *context,
1993 const ExecParameters *params,
1994 char ***ret) {
1995
1996 _cleanup_strv_free_ char **l = NULL;
1997 char **rt;
1998
1999 /* Compile the list of writable paths. This is the combination of the explicitly configured paths, plus all
2000 * runtime directories. */
2001
2002 if (strv_isempty(context->read_write_paths) &&
2003 strv_isempty(context->runtime_directory)) {
2004 *ret = NULL; /* NOP if neither is set */
2005 return 0;
2006 }
2007
2008 l = strv_copy(context->read_write_paths);
2009 if (!l)
2010 return -ENOMEM;
2011
2012 STRV_FOREACH(rt, context->runtime_directory) {
2013 char *s;
2014
605405c6 2015 s = strjoin(params->runtime_prefix, "/", *rt);
3fbe8dbe
LP
2016 if (!s)
2017 return -ENOMEM;
2018
2019 if (strv_consume(&l, s) < 0)
2020 return -ENOMEM;
2021 }
2022
2023 *ret = l;
2024 l = NULL;
2025
2026 return 0;
2027}
2028
93c6bb51
DH
2029static int apply_mount_namespace(Unit *u, const ExecContext *context,
2030 const ExecParameters *params,
2031 ExecRuntime *runtime) {
2032 int r;
2033 _cleanup_free_ char **rw = NULL;
2034 char *tmp = NULL, *var = NULL;
2035 const char *root_dir = NULL;
2036 NameSpaceInfo ns_info = {
2037 .private_dev = context->private_devices,
2038 .protect_control_groups = context->protect_control_groups,
2039 .protect_kernel_tunables = context->protect_kernel_tunables,
2040 .protect_kernel_modules = context->protect_kernel_modules,
2041 };
2042
2b3c1b9e
DH
2043 assert(context);
2044
93c6bb51
DH
2045 /* The runtime struct only contains the parent of the private /tmp,
2046 * which is non-accessible to world users. Inside of it there's a /tmp
2047 * that is sticky, and that's the one we want to use here. */
2048
2049 if (context->private_tmp && runtime) {
2050 if (runtime->tmp_dir)
2051 tmp = strjoina(runtime->tmp_dir, "/tmp");
2052 if (runtime->var_tmp_dir)
2053 var = strjoina(runtime->var_tmp_dir, "/tmp");
2054 }
2055
2056 r = compile_read_write_paths(context, params, &rw);
2057 if (r < 0)
2058 return r;
2059
2060 if (params->flags & EXEC_APPLY_CHROOT)
2061 root_dir = context->root_directory;
2062
2063 r = setup_namespace(root_dir, &ns_info, rw,
2064 context->read_only_paths,
2065 context->inaccessible_paths,
2066 tmp,
2067 var,
2068 context->protect_home,
2069 context->protect_system,
2070 context->mount_flags);
2071
2072 /* If we couldn't set up the namespace this is probably due to a
2073 * missing capability. In this case, silently proceeed. */
2074 if (IN_SET(r, -EPERM, -EACCES)) {
2075 log_open();
2076 log_unit_debug_errno(u, r, "Failed to set up namespace, assuming containerized execution, ignoring: %m");
2077 log_close();
2078 r = 0;
2079 }
2080
2081 return r;
2082}
2083
e7f1e7c6
DH
2084static int apply_working_directory(const ExecContext *context,
2085 const ExecParameters *params,
2b3c1b9e 2086 const char *home,
e7f1e7c6 2087 const bool needs_mount_ns) {
2b3c1b9e
DH
2088 const char *d;
2089 const char *wd;
2090
2091 assert(context);
2092
2093 if (context->working_directory_home)
2094 wd = home;
2095 else if (context->working_directory)
2096 wd = context->working_directory;
2097 else
2098 wd = "/";
e7f1e7c6
DH
2099
2100 if (params->flags & EXEC_APPLY_CHROOT) {
2101 if (!needs_mount_ns && context->root_directory)
2102 if (chroot(context->root_directory) < 0)
2103 return -errno;
2104
2b3c1b9e
DH
2105 d = wd;
2106 } else
2107 d = strjoina(strempty(context->root_directory), "/", strempty(wd));
e7f1e7c6 2108
2b3c1b9e
DH
2109 if (chdir(d) < 0 && !context->working_directory_missing_ok)
2110 return -errno;
e7f1e7c6
DH
2111
2112 return 0;
2113}
2114
29206d46
LP
2115static void append_socket_pair(int *array, unsigned *n, int pair[2]) {
2116 assert(array);
2117 assert(n);
2118
2119 if (!pair)
2120 return;
2121
2122 if (pair[0] >= 0)
2123 array[(*n)++] = pair[0];
2124 if (pair[1] >= 0)
2125 array[(*n)++] = pair[1];
2126}
2127
a34ceba6
LP
2128static int close_remaining_fds(
2129 const ExecParameters *params,
2130 ExecRuntime *runtime,
29206d46 2131 DynamicCreds *dcreds,
00d9ef85 2132 int user_lookup_fd,
a34ceba6
LP
2133 int socket_fd,
2134 int *fds, unsigned n_fds) {
2135
2136 unsigned n_dont_close = 0;
00d9ef85 2137 int dont_close[n_fds + 12];
a34ceba6
LP
2138
2139 assert(params);
2140
2141 if (params->stdin_fd >= 0)
2142 dont_close[n_dont_close++] = params->stdin_fd;
2143 if (params->stdout_fd >= 0)
2144 dont_close[n_dont_close++] = params->stdout_fd;
2145 if (params->stderr_fd >= 0)
2146 dont_close[n_dont_close++] = params->stderr_fd;
2147
2148 if (socket_fd >= 0)
2149 dont_close[n_dont_close++] = socket_fd;
2150 if (n_fds > 0) {
2151 memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
2152 n_dont_close += n_fds;
2153 }
2154
29206d46
LP
2155 if (runtime)
2156 append_socket_pair(dont_close, &n_dont_close, runtime->netns_storage_socket);
2157
2158 if (dcreds) {
2159 if (dcreds->user)
2160 append_socket_pair(dont_close, &n_dont_close, dcreds->user->storage_socket);
2161 if (dcreds->group)
2162 append_socket_pair(dont_close, &n_dont_close, dcreds->group->storage_socket);
a34ceba6
LP
2163 }
2164
00d9ef85
LP
2165 if (user_lookup_fd >= 0)
2166 dont_close[n_dont_close++] = user_lookup_fd;
2167
a34ceba6
LP
2168 return close_all_fds(dont_close, n_dont_close);
2169}
2170
59eeb84b
LP
2171static bool context_has_address_families(const ExecContext *c) {
2172 assert(c);
2173
2174 return c->address_families_whitelist ||
2175 !set_isempty(c->address_families);
2176}
2177
2178static bool context_has_syscall_filters(const ExecContext *c) {
2179 assert(c);
2180
2181 return c->syscall_whitelist ||
2182 !set_isempty(c->syscall_filter) ||
2183 !set_isempty(c->syscall_archs);
2184}
2185
2186static bool context_has_no_new_privileges(const ExecContext *c) {
2187 assert(c);
2188
2189 if (c->no_new_privileges)
2190 return true;
2191
2192 if (have_effective_cap(CAP_SYS_ADMIN)) /* if we are privileged, we don't need NNP */
2193 return false;
2194
2195 return context_has_address_families(c) || /* we need NNP if we have any form of seccomp and are unprivileged */
2196 c->memory_deny_write_execute ||
2197 c->restrict_realtime ||
add00535 2198 exec_context_restrict_namespaces_set(c) ||
59eeb84b 2199 c->protect_kernel_tunables ||
4084e8fc
DH
2200 c->protect_kernel_modules ||
2201 c->private_devices ||
59eeb84b
LP
2202 context_has_syscall_filters(c);
2203}
2204
00d9ef85
LP
2205static int send_user_lookup(
2206 Unit *unit,
2207 int user_lookup_fd,
2208 uid_t uid,
2209 gid_t gid) {
2210
2211 assert(unit);
2212
2213 /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
2214 * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
2215 * specified. */
2216
2217 if (user_lookup_fd < 0)
2218 return 0;
2219
2220 if (!uid_is_valid(uid) && !gid_is_valid(gid))
2221 return 0;
2222
2223 if (writev(user_lookup_fd,
2224 (struct iovec[]) {
2225 { .iov_base = &uid, .iov_len = sizeof(uid) },
2226 { .iov_base = &gid, .iov_len = sizeof(gid) },
2227 { .iov_base = unit->id, .iov_len = strlen(unit->id) }}, 3) < 0)
2228 return -errno;
2229
2230 return 0;
2231}
2232
ff0af2a1 2233static int exec_child(
f2341e0a 2234 Unit *unit,
ff0af2a1
LP
2235 ExecCommand *command,
2236 const ExecContext *context,
2237 const ExecParameters *params,
2238 ExecRuntime *runtime,
29206d46 2239 DynamicCreds *dcreds,
ff0af2a1
LP
2240 char **argv,
2241 int socket_fd,
52c239d7 2242 int named_iofds[3],
ff0af2a1
LP
2243 int *fds, unsigned n_fds,
2244 char **files_env,
00d9ef85 2245 int user_lookup_fd,
ff0af2a1 2246 int *exit_status) {
d35fbf6b 2247
2065ca69 2248 _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **accum_env = NULL, **final_argv = NULL;
9008e1ac 2249 _cleanup_free_ char *mac_selinux_context_net = NULL;
4d885bd3
DH
2250 _cleanup_free_ gid_t *supplementary_gids = NULL;
2251 const char *username = NULL, *groupname = NULL;
2b3c1b9e 2252 const char *home = NULL, *shell = NULL;
7bce046b
LP
2253 dev_t journal_stream_dev = 0;
2254 ino_t journal_stream_ino = 0;
2255 bool needs_mount_namespace;
fed1e721
LP
2256 uid_t uid = UID_INVALID;
2257 gid_t gid = GID_INVALID;
4d885bd3 2258 int i, r, ngids = 0;
034c6ed7 2259
f2341e0a 2260 assert(unit);
5cb5a6ff
LP
2261 assert(command);
2262 assert(context);
d35fbf6b 2263 assert(params);
ff0af2a1 2264 assert(exit_status);
d35fbf6b
DM
2265
2266 rename_process_from_path(command->path);
2267
2268 /* We reset exactly these signals, since they are the
2269 * only ones we set to SIG_IGN in the main daemon. All
2270 * others we leave untouched because we set them to
2271 * SIG_DFL or a valid handler initially, both of which
2272 * will be demoted to SIG_DFL. */
ce30c8dc
LP
2273 (void) default_signals(SIGNALS_CRASH_HANDLER,
2274 SIGNALS_IGNORE, -1);
d35fbf6b
DM
2275
2276 if (context->ignore_sigpipe)
ce30c8dc 2277 (void) ignore_signals(SIGPIPE, -1);
d35fbf6b 2278
ff0af2a1
LP
2279 r = reset_signal_mask();
2280 if (r < 0) {
2281 *exit_status = EXIT_SIGNAL_MASK;
2282 return r;
d35fbf6b 2283 }
034c6ed7 2284
d35fbf6b
DM
2285 if (params->idle_pipe)
2286 do_idle_pipe_dance(params->idle_pipe);
4f2d528d 2287
d35fbf6b
DM
2288 /* Close sockets very early to make sure we don't
2289 * block init reexecution because it cannot bind its
2290 * sockets */
ff0af2a1 2291
d35fbf6b 2292 log_forget_fds();
4f2d528d 2293
00d9ef85 2294 r = close_remaining_fds(params, runtime, dcreds, user_lookup_fd, socket_fd, fds, n_fds);
ff0af2a1
LP
2295 if (r < 0) {
2296 *exit_status = EXIT_FDS;
2297 return r;
8c7be95e
LP
2298 }
2299
d35fbf6b
DM
2300 if (!context->same_pgrp)
2301 if (setsid() < 0) {
ff0af2a1 2302 *exit_status = EXIT_SETSID;
d35fbf6b
DM
2303 return -errno;
2304 }
9e2f7c11 2305
1e22b5cd 2306 exec_context_tty_reset(context, params);
d35fbf6b 2307
c39f1ce2 2308 if (params->flags & EXEC_CONFIRM_SPAWN) {
d35fbf6b
DM
2309 char response;
2310
ff0af2a1
LP
2311 r = ask_for_confirmation(&response, argv);
2312 if (r == -ETIMEDOUT)
d35fbf6b 2313 write_confirm_message("Confirmation question timed out, assuming positive response.\n");
ff0af2a1
LP
2314 else if (r < 0)
2315 write_confirm_message("Couldn't ask confirmation question, assuming positive response: %s\n", strerror(-r));
d35fbf6b
DM
2316 else if (response == 's') {
2317 write_confirm_message("Skipping execution.\n");
ff0af2a1 2318 *exit_status = EXIT_CONFIRM;
d35fbf6b
DM
2319 return -ECANCELED;
2320 } else if (response == 'n') {
2321 write_confirm_message("Failing execution.\n");
ff0af2a1 2322 *exit_status = 0;
d35fbf6b
DM
2323 return 0;
2324 }
2325 }
1a63a750 2326
29206d46
LP
2327 if (context->dynamic_user && dcreds) {
2328
409093fe
LP
2329 /* Make sure we bypass our own NSS module for any NSS checks */
2330 if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
2331 *exit_status = EXIT_USER;
2332 return -errno;
2333 }
2334
29206d46 2335 r = dynamic_creds_realize(dcreds, &uid, &gid);
ff0af2a1
LP
2336 if (r < 0) {
2337 *exit_status = EXIT_USER;
2338 return r;
524daa8c 2339 }
524daa8c 2340
92b25bca 2341 if (!uid_is_valid(uid) || !gid_is_valid(gid)) {
29206d46
LP
2342 *exit_status = EXIT_USER;
2343 return -ESRCH;
2344 }
5bc7452b 2345
29206d46
LP
2346 if (dcreds->user)
2347 username = dcreds->user->name;
2348
2349 } else {
4d885bd3
DH
2350 r = get_fixed_user(context, &username, &uid, &gid, &home, &shell);
2351 if (r < 0) {
2352 *exit_status = EXIT_USER;
2353 return r;
5bc7452b 2354 }
5bc7452b 2355
4d885bd3
DH
2356 r = get_fixed_group(context, &groupname, &gid);
2357 if (r < 0) {
2358 *exit_status = EXIT_GROUP;
2359 return r;
2360 }
cdc5d5c5 2361 }
29206d46 2362
cdc5d5c5
DH
2363 /* Initialize user supplementary groups and get SupplementaryGroups= ones */
2364 r = get_supplementary_groups(context, username, groupname, gid,
2365 &supplementary_gids, &ngids);
2366 if (r < 0) {
2367 *exit_status = EXIT_GROUP;
2368 return r;
29206d46 2369 }
5bc7452b 2370
00d9ef85
LP
2371 r = send_user_lookup(unit, user_lookup_fd, uid, gid);
2372 if (r < 0) {
2373 *exit_status = EXIT_USER;
2374 return r;
2375 }
2376
2377 user_lookup_fd = safe_close(user_lookup_fd);
2378
d35fbf6b
DM
2379 /* If a socket is connected to STDIN/STDOUT/STDERR, we
2380 * must sure to drop O_NONBLOCK */
2381 if (socket_fd >= 0)
a34ceba6 2382 (void) fd_nonblock(socket_fd, false);
acbb0225 2383
52c239d7 2384 r = setup_input(context, params, socket_fd, named_iofds);
ff0af2a1
LP
2385 if (r < 0) {
2386 *exit_status = EXIT_STDIN;
2387 return r;
d35fbf6b 2388 }
034c6ed7 2389
52c239d7 2390 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
2391 if (r < 0) {
2392 *exit_status = EXIT_STDOUT;
2393 return r;
d35fbf6b
DM
2394 }
2395
52c239d7 2396 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
2397 if (r < 0) {
2398 *exit_status = EXIT_STDERR;
2399 return r;
d35fbf6b
DM
2400 }
2401
2402 if (params->cgroup_path) {
ff0af2a1
LP
2403 r = cg_attach_everywhere(params->cgroup_supported, params->cgroup_path, 0, NULL, NULL);
2404 if (r < 0) {
2405 *exit_status = EXIT_CGROUP;
2406 return r;
309bff19 2407 }
d35fbf6b 2408 }
309bff19 2409
d35fbf6b 2410 if (context->oom_score_adjust_set) {
d5243d62 2411 char t[DECIMAL_STR_MAX(context->oom_score_adjust)];
f2b68789 2412
d5243d62
LP
2413 /* When we can't make this change due to EPERM, then
2414 * let's silently skip over it. User namespaces
2415 * prohibit write access to this file, and we
2416 * shouldn't trip up over that. */
613b411c 2417
d5243d62 2418 sprintf(t, "%i", context->oom_score_adjust);
ad118bda 2419 r = write_string_file("/proc/self/oom_score_adj", t, 0);
6cb7fa17 2420 if (r == -EPERM || r == -EACCES) {
ff0af2a1 2421 log_open();
f2341e0a 2422 log_unit_debug_errno(unit, r, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
ff0af2a1
LP
2423 log_close();
2424 } else if (r < 0) {
2425 *exit_status = EXIT_OOM_ADJUST;
d35fbf6b 2426 return -errno;
613b411c 2427 }
d35fbf6b
DM
2428 }
2429
2430 if (context->nice_set)
2431 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
ff0af2a1 2432 *exit_status = EXIT_NICE;
d35fbf6b 2433 return -errno;
613b411c
LP
2434 }
2435
d35fbf6b
DM
2436 if (context->cpu_sched_set) {
2437 struct sched_param param = {
2438 .sched_priority = context->cpu_sched_priority,
2439 };
2440
ff0af2a1
LP
2441 r = sched_setscheduler(0,
2442 context->cpu_sched_policy |
2443 (context->cpu_sched_reset_on_fork ?
2444 SCHED_RESET_ON_FORK : 0),
2445 &param);
2446 if (r < 0) {
2447 *exit_status = EXIT_SETSCHEDULER;
d35fbf6b 2448 return -errno;
fc9b2a84 2449 }
d35fbf6b 2450 }
fc9b2a84 2451
d35fbf6b
DM
2452 if (context->cpuset)
2453 if (sched_setaffinity(0, CPU_ALLOC_SIZE(context->cpuset_ncpus), context->cpuset) < 0) {
ff0af2a1 2454 *exit_status = EXIT_CPUAFFINITY;
d35fbf6b 2455 return -errno;
034c6ed7
LP
2456 }
2457
d35fbf6b
DM
2458 if (context->ioprio_set)
2459 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
ff0af2a1 2460 *exit_status = EXIT_IOPRIO;
d35fbf6b
DM
2461 return -errno;
2462 }
da726a4d 2463
d35fbf6b
DM
2464 if (context->timer_slack_nsec != NSEC_INFINITY)
2465 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
ff0af2a1 2466 *exit_status = EXIT_TIMERSLACK;
d35fbf6b 2467 return -errno;
4c2630eb 2468 }
9eba9da4 2469
050f7277 2470 if (context->personality != PERSONALITY_INVALID)
d35fbf6b 2471 if (personality(context->personality) < 0) {
ff0af2a1 2472 *exit_status = EXIT_PERSONALITY;
d35fbf6b 2473 return -errno;
4c2630eb 2474 }
94f04347 2475
d35fbf6b 2476 if (context->utmp_id)
023a4f67
LP
2477 utmp_put_init_process(context->utmp_id, getpid(), getsid(0), context->tty_path,
2478 context->utmp_mode == EXEC_UTMP_INIT ? INIT_PROCESS :
2479 context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
2480 USER_PROCESS,
2481 username ? "root" : context->user);
d35fbf6b 2482
e0d2adfd 2483 if (context->user) {
ff0af2a1
LP
2484 r = chown_terminal(STDIN_FILENO, uid);
2485 if (r < 0) {
2486 *exit_status = EXIT_STDIN;
2487 return r;
071830ff 2488 }
d35fbf6b 2489 }
8e274523 2490
a931ad47
LP
2491 /* If delegation is enabled we'll pass ownership of the cgroup
2492 * (but only in systemd's own controller hierarchy!) to the
2493 * user of the new process. */
2494 if (params->cgroup_path && context->user && params->cgroup_delegate) {
ff0af2a1
LP
2495 r = cg_set_task_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, 0644, uid, gid);
2496 if (r < 0) {
2497 *exit_status = EXIT_CGROUP;
2498 return r;
d35fbf6b 2499 }
034c6ed7 2500
034c6ed7 2501
ff0af2a1
LP
2502 r = cg_set_group_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, 0755, uid, gid);
2503 if (r < 0) {
2504 *exit_status = EXIT_CGROUP;
2505 return r;
034c6ed7 2506 }
d35fbf6b 2507 }
034c6ed7 2508
d35fbf6b 2509 if (!strv_isempty(context->runtime_directory) && params->runtime_prefix) {
07689d5d
LP
2510 r = setup_runtime_directory(context, params, uid, gid);
2511 if (r < 0) {
2512 *exit_status = EXIT_RUNTIME_DIRECTORY;
2513 return r;
d35fbf6b
DM
2514 }
2515 }
94f04347 2516
7bce046b 2517 r = build_environment(
fd63e712 2518 unit,
7bce046b
LP
2519 context,
2520 params,
2521 n_fds,
2522 home,
2523 username,
2524 shell,
2525 journal_stream_dev,
2526 journal_stream_ino,
2527 &our_env);
2065ca69
JW
2528 if (r < 0) {
2529 *exit_status = EXIT_MEMORY;
2530 return r;
2531 }
2532
2533 r = build_pass_environment(context, &pass_env);
2534 if (r < 0) {
2535 *exit_status = EXIT_MEMORY;
2536 return r;
2537 }
2538
2539 accum_env = strv_env_merge(5,
2540 params->environment,
2541 our_env,
2542 pass_env,
2543 context->environment,
2544 files_env,
2545 NULL);
2546 if (!accum_env) {
2547 *exit_status = EXIT_MEMORY;
2548 return -ENOMEM;
2549 }
1280503b 2550 accum_env = strv_env_clean(accum_env);
2065ca69 2551
096424d1 2552 (void) umask(context->umask);
b213e1c1 2553
c39f1ce2 2554 if ((params->flags & EXEC_APPLY_PERMISSIONS) && !command->privileged) {
b213e1c1 2555 if (context->pam_name && username) {
2d6fce8d 2556 r = setup_pam(context->pam_name, username, uid, gid, context->tty_path, &accum_env, fds, n_fds);
b213e1c1
SW
2557 if (r < 0) {
2558 *exit_status = EXIT_PAM;
2559 return r;
2560 }
d35fbf6b 2561 }
b213e1c1 2562 }
ac45f971 2563
d35fbf6b 2564 if (context->private_network && runtime && runtime->netns_storage_socket[0] >= 0) {
ff0af2a1
LP
2565 r = setup_netns(runtime->netns_storage_socket);
2566 if (r < 0) {
2567 *exit_status = EXIT_NETWORK;
2568 return r;
d35fbf6b
DM
2569 }
2570 }
169c1bda 2571
ee818b89 2572 needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
ee818b89 2573 if (needs_mount_namespace) {
93c6bb51 2574 r = apply_mount_namespace(unit, context, params, runtime);
3fbe8dbe
LP
2575 if (r < 0) {
2576 *exit_status = EXIT_NAMESPACE;
2577 return r;
2578 }
d35fbf6b 2579 }
81a2b7ce 2580
50b3dfb9
DH
2581 /* Apply just after mount namespace setup */
2582 r = apply_working_directory(context, params, home, needs_mount_namespace);
2583 if (r < 0) {
2584 *exit_status = EXIT_CHROOT;
2585 return r;
2586 }
2587
bbeea271 2588 /* Drop groups as early as possbile */
096424d1 2589 if ((params->flags & EXEC_APPLY_PERMISSIONS) && !command->privileged) {
4d885bd3 2590 r = enforce_groups(context, gid, supplementary_gids, ngids);
096424d1
LP
2591 if (r < 0) {
2592 *exit_status = EXIT_GROUP;
2593 return r;
2594 }
2595 }
2596
9008e1ac 2597#ifdef HAVE_SELINUX
c39f1ce2
LP
2598 if ((params->flags & EXEC_APPLY_PERMISSIONS) &&
2599 mac_selinux_use() &&
2600 params->selinux_context_net &&
2601 socket_fd >= 0 &&
2602 !command->privileged) {
2603
ff0af2a1
LP
2604 r = mac_selinux_get_child_mls_label(socket_fd, command->path, context->selinux_context, &mac_selinux_context_net);
2605 if (r < 0) {
2606 *exit_status = EXIT_SELINUX_CONTEXT;
2607 return r;
9008e1ac
MS
2608 }
2609 }
2610#endif
2611
d87a2ef7 2612 if ((params->flags & EXEC_APPLY_PERMISSIONS) && context->private_users) {
d251207d
LP
2613 r = setup_private_users(uid, gid);
2614 if (r < 0) {
2615 *exit_status = EXIT_USER;
2616 return r;
2617 }
2618 }
2619
d35fbf6b
DM
2620 /* We repeat the fd closing here, to make sure that
2621 * nothing is leaked from the PAM modules. Note that
2622 * we are more aggressive this time since socket_fd
e44da745
DM
2623 * and the netns fds we don't need anymore. The custom
2624 * endpoint fd was needed to upload the policy and can
2625 * now be closed as well. */
ff0af2a1
LP
2626 r = close_all_fds(fds, n_fds);
2627 if (r >= 0)
2628 r = shift_fds(fds, n_fds);
2629 if (r >= 0)
2630 r = flags_fds(fds, n_fds, context->non_blocking);
2631 if (r < 0) {
2632 *exit_status = EXIT_FDS;
2633 return r;
d35fbf6b 2634 }
e66cf1a3 2635
c39f1ce2 2636 if ((params->flags & EXEC_APPLY_PERMISSIONS) && !command->privileged) {
e66cf1a3 2637
755d4b67
IP
2638 int secure_bits = context->secure_bits;
2639
d35fbf6b 2640 for (i = 0; i < _RLIMIT_MAX; i++) {
03857c43 2641
d35fbf6b
DM
2642 if (!context->rlimit[i])
2643 continue;
2644
03857c43
LP
2645 r = setrlimit_closest(i, context->rlimit[i]);
2646 if (r < 0) {
ff0af2a1 2647 *exit_status = EXIT_LIMITS;
03857c43 2648 return r;
e66cf1a3
LP
2649 }
2650 }
2651
f4170c67
LP
2652 /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested. */
2653 if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
2654 if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
2655 *exit_status = EXIT_LIMITS;
2656 return -errno;
2657 }
2658 }
2659
a103496c
IP
2660 if (!cap_test_all(context->capability_bounding_set)) {
2661 r = capability_bounding_set_drop(context->capability_bounding_set, false);
ff0af2a1
LP
2662 if (r < 0) {
2663 *exit_status = EXIT_CAPABILITIES;
2664 return r;
3b8bddde 2665 }
4c2630eb 2666 }
3b8bddde 2667
755d4b67
IP
2668 /* This is done before enforce_user, but ambient set
2669 * does not survive over setresuid() if keep_caps is not set. */
2670 if (context->capability_ambient_set != 0) {
2671 r = capability_ambient_set_apply(context->capability_ambient_set, true);
2672 if (r < 0) {
2673 *exit_status = EXIT_CAPABILITIES;
2674 return r;
2675 }
755d4b67
IP
2676 }
2677
d35fbf6b 2678 if (context->user) {
ff0af2a1
LP
2679 r = enforce_user(context, uid);
2680 if (r < 0) {
2681 *exit_status = EXIT_USER;
2682 return r;
5b6319dc 2683 }
755d4b67
IP
2684 if (context->capability_ambient_set != 0) {
2685
2686 /* Fix the ambient capabilities after user change. */
2687 r = capability_ambient_set_apply(context->capability_ambient_set, false);
2688 if (r < 0) {
2689 *exit_status = EXIT_CAPABILITIES;
2690 return r;
2691 }
2692
2693 /* If we were asked to change user and ambient capabilities
2694 * were requested, we had to add keep-caps to the securebits
2695 * so that we would maintain the inherited capability set
2696 * through the setresuid(). Make sure that the bit is added
2697 * also to the context secure_bits so that we don't try to
2698 * drop the bit away next. */
2699
7f508f2c 2700 secure_bits |= 1<<SECURE_KEEP_CAPS;
755d4b67 2701 }
5b6319dc 2702 }
d35fbf6b 2703
5cd9cd35
LP
2704 /* Apply the MAC contexts late, but before seccomp syscall filtering, as those should really be last to
2705 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
2706 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
2707 * are restricted. */
2708
2709#ifdef HAVE_SELINUX
2710 if (mac_selinux_use()) {
2711 char *exec_context = mac_selinux_context_net ?: context->selinux_context;
2712
2713 if (exec_context) {
2714 r = setexeccon(exec_context);
2715 if (r < 0) {
2716 *exit_status = EXIT_SELINUX_CONTEXT;
2717 return r;
2718 }
2719 }
2720 }
2721#endif
2722
2723 r = setup_smack(context, command);
2724 if (r < 0) {
2725 *exit_status = EXIT_SMACK_PROCESS_LABEL;
2726 return r;
2727 }
2728
2729#ifdef HAVE_APPARMOR
2730 if (context->apparmor_profile && mac_apparmor_use()) {
2731 r = aa_change_onexec(context->apparmor_profile);
2732 if (r < 0 && !context->apparmor_profile_ignore) {
2733 *exit_status = EXIT_APPARMOR_PROFILE;
2734 return -errno;
2735 }
2736 }
2737#endif
2738
d35fbf6b
DM
2739 /* PR_GET_SECUREBITS is not privileged, while
2740 * PR_SET_SECUREBITS is. So to suppress
2741 * potential EPERMs we'll try not to call
2742 * PR_SET_SECUREBITS unless necessary. */
755d4b67
IP
2743 if (prctl(PR_GET_SECUREBITS) != secure_bits)
2744 if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
ff0af2a1 2745 *exit_status = EXIT_SECUREBITS;
d35fbf6b 2746 return -errno;
ff01d048 2747 }
5b6319dc 2748
59eeb84b 2749 if (context_has_no_new_privileges(context))
d35fbf6b 2750 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
ff0af2a1 2751 *exit_status = EXIT_NO_NEW_PRIVILEGES;
d35fbf6b
DM
2752 return -errno;
2753 }
2754
2755#ifdef HAVE_SECCOMP
59eeb84b 2756 if (context_has_address_families(context)) {
83f12b27 2757 r = apply_address_families(unit, context);
ff0af2a1
LP
2758 if (r < 0) {
2759 *exit_status = EXIT_ADDRESS_FAMILIES;
2760 return r;
4c2630eb
MS
2761 }
2762 }
04aa0cb9 2763
f3e43635 2764 if (context->memory_deny_write_execute) {
83f12b27 2765 r = apply_memory_deny_write_execute(unit, context);
f3e43635
TM
2766 if (r < 0) {
2767 *exit_status = EXIT_SECCOMP;
2768 return r;
2769 }
2770 }
f4170c67
LP
2771
2772 if (context->restrict_realtime) {
83f12b27 2773 r = apply_restrict_realtime(unit, context);
f4170c67
LP
2774 if (r < 0) {
2775 *exit_status = EXIT_SECCOMP;
2776 return r;
2777 }
2778 }
2779
add00535
LP
2780 r = apply_restrict_namespaces(unit, context);
2781 if (r < 0) {
2782 *exit_status = EXIT_SECCOMP;
2783 return r;
2784 }
2785
59eeb84b
LP
2786 if (context->protect_kernel_tunables) {
2787 r = apply_protect_sysctl(unit, context);
2788 if (r < 0) {
2789 *exit_status = EXIT_SECCOMP;
2790 return r;
502d704e
DH
2791 }
2792 }
2793
2794 if (context->protect_kernel_modules) {
2795 r = apply_protect_kernel_modules(unit, context);
2796 if (r < 0) {
2797 *exit_status = EXIT_SECCOMP;
2798 return r;
59eeb84b
LP
2799 }
2800 }
2801
ba128bb8
LP
2802 if (context->private_devices) {
2803 r = apply_private_devices(unit, context);
2804 if (r < 0) {
2805 *exit_status = EXIT_SECCOMP;
2806 return r;
2807 }
2808 }
2809
5cd9cd35
LP
2810 /* This really should remain the last step before the execve(), to make sure our own code is unaffected
2811 * by the filter as little as possible. */
59eeb84b 2812 if (context_has_syscall_filters(context)) {
83f12b27 2813 r = apply_seccomp(unit, context);
ff0af2a1
LP
2814 if (r < 0) {
2815 *exit_status = EXIT_SECCOMP;
2816 return r;
81a2b7ce 2817 }
d35fbf6b
DM
2818 }
2819#endif
d35fbf6b 2820 }
034c6ed7 2821
2065ca69 2822 final_argv = replace_env_argv(argv, accum_env);
d35fbf6b 2823 if (!final_argv) {
ff0af2a1 2824 *exit_status = EXIT_MEMORY;
d35fbf6b
DM
2825 return -ENOMEM;
2826 }
034c6ed7 2827
553d2243 2828 if (_unlikely_(log_get_max_level() >= LOG_DEBUG)) {
d35fbf6b 2829 _cleanup_free_ char *line;
81a2b7ce 2830
d35fbf6b
DM
2831 line = exec_command_line(final_argv);
2832 if (line) {
2833 log_open();
f2341e0a
LP
2834 log_struct(LOG_DEBUG,
2835 LOG_UNIT_ID(unit),
2836 "EXECUTABLE=%s", command->path,
2837 LOG_UNIT_MESSAGE(unit, "Executing: %s", line),
2838 NULL);
d35fbf6b
DM
2839 log_close();
2840 }
2841 }
dd305ec9 2842
2065ca69 2843 execve(command->path, final_argv, accum_env);
ff0af2a1 2844 *exit_status = EXIT_EXEC;
d35fbf6b
DM
2845 return -errno;
2846}
81a2b7ce 2847
f2341e0a
LP
2848int exec_spawn(Unit *unit,
2849 ExecCommand *command,
d35fbf6b
DM
2850 const ExecContext *context,
2851 const ExecParameters *params,
2852 ExecRuntime *runtime,
29206d46 2853 DynamicCreds *dcreds,
d35fbf6b 2854 pid_t *ret) {
8351ceae 2855
d35fbf6b
DM
2856 _cleanup_strv_free_ char **files_env = NULL;
2857 int *fds = NULL; unsigned n_fds = 0;
ff0af2a1
LP
2858 _cleanup_free_ char *line = NULL;
2859 int socket_fd, r;
52c239d7 2860 int named_iofds[3] = { -1, -1, -1 };
ff0af2a1 2861 char **argv;
d35fbf6b 2862 pid_t pid;
8351ceae 2863
f2341e0a 2864 assert(unit);
d35fbf6b
DM
2865 assert(command);
2866 assert(context);
2867 assert(ret);
2868 assert(params);
2869 assert(params->fds || params->n_fds <= 0);
4298d0b5 2870
d35fbf6b
DM
2871 if (context->std_input == EXEC_INPUT_SOCKET ||
2872 context->std_output == EXEC_OUTPUT_SOCKET ||
2873 context->std_error == EXEC_OUTPUT_SOCKET) {
17df7223 2874
ff0af2a1 2875 if (params->n_fds != 1) {
f2341e0a 2876 log_unit_error(unit, "Got more than one socket.");
d35fbf6b 2877 return -EINVAL;
ff0af2a1 2878 }
eef65bf3 2879
d35fbf6b
DM
2880 socket_fd = params->fds[0];
2881 } else {
2882 socket_fd = -1;
2883 fds = params->fds;
2884 n_fds = params->n_fds;
2885 }
94f04347 2886
52c239d7
LB
2887 r = exec_context_named_iofds(unit, context, params, named_iofds);
2888 if (r < 0)
2889 return log_unit_error_errno(unit, r, "Failed to load a named file descriptor: %m");
2890
f2341e0a 2891 r = exec_context_load_environment(unit, context, &files_env);
ff0af2a1 2892 if (r < 0)
f2341e0a 2893 return log_unit_error_errno(unit, r, "Failed to load environment files: %m");
034c6ed7 2894
d35fbf6b 2895 argv = params->argv ?: command->argv;
d35fbf6b
DM
2896 line = exec_command_line(argv);
2897 if (!line)
2898 return log_oom();
fab56fc5 2899
f2341e0a
LP
2900 log_struct(LOG_DEBUG,
2901 LOG_UNIT_ID(unit),
2902 LOG_UNIT_MESSAGE(unit, "About to execute: %s", line),
2903 "EXECUTABLE=%s", command->path,
2904 NULL);
d35fbf6b
DM
2905 pid = fork();
2906 if (pid < 0)
74129a12 2907 return log_unit_error_errno(unit, errno, "Failed to fork: %m");
d35fbf6b
DM
2908
2909 if (pid == 0) {
ff0af2a1
LP
2910 int exit_status;
2911
f2341e0a
LP
2912 r = exec_child(unit,
2913 command,
ff0af2a1
LP
2914 context,
2915 params,
2916 runtime,
29206d46 2917 dcreds,
ff0af2a1
LP
2918 argv,
2919 socket_fd,
52c239d7 2920 named_iofds,
ff0af2a1
LP
2921 fds, n_fds,
2922 files_env,
00d9ef85 2923 unit->manager->user_lookup_fds[1],
ff0af2a1
LP
2924 &exit_status);
2925 if (r < 0) {
4c2630eb 2926 log_open();
f2341e0a
LP
2927 log_struct_errno(LOG_ERR, r,
2928 LOG_MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED),
2929 LOG_UNIT_ID(unit),
2930 LOG_UNIT_MESSAGE(unit, "Failed at step %s spawning %s: %m",
2931 exit_status_to_string(exit_status, EXIT_STATUS_SYSTEMD),
2932 command->path),
2933 "EXECUTABLE=%s", command->path,
2934 NULL);
4c2630eb
MS
2935 }
2936
ff0af2a1 2937 _exit(exit_status);
034c6ed7
LP
2938 }
2939
f2341e0a 2940 log_unit_debug(unit, "Forked %s as "PID_FMT, command->path, pid);
23635a85 2941
80876c20
LP
2942 /* We add the new process to the cgroup both in the child (so
2943 * that we can be sure that no user code is ever executed
2944 * outside of the cgroup) and in the parent (so that we can be
2945 * sure that when we kill the cgroup the process will be
2946 * killed too). */
d35fbf6b 2947 if (params->cgroup_path)
dd305ec9 2948 (void) cg_attach(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, pid);
2da3263a 2949
b58b4116 2950 exec_status_start(&command->exec_status, pid);
9fb86720 2951
034c6ed7 2952 *ret = pid;
5cb5a6ff
LP
2953 return 0;
2954}
2955
034c6ed7
LP
2956void exec_context_init(ExecContext *c) {
2957 assert(c);
2958
4c12626c 2959 c->umask = 0022;
9eba9da4 2960 c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
94f04347 2961 c->cpu_sched_policy = SCHED_OTHER;
071830ff 2962 c->syslog_priority = LOG_DAEMON|LOG_INFO;
74922904 2963 c->syslog_level_prefix = true;
353e12c2 2964 c->ignore_sigpipe = true;
3a43da28 2965 c->timer_slack_nsec = NSEC_INFINITY;
050f7277 2966 c->personality = PERSONALITY_INVALID;
e66cf1a3 2967 c->runtime_directory_mode = 0755;
a103496c 2968 c->capability_bounding_set = CAP_ALL;
add00535 2969 c->restrict_namespaces = NAMESPACE_FLAGS_ALL;
034c6ed7
LP
2970}
2971
613b411c 2972void exec_context_done(ExecContext *c) {
5cb5a6ff
LP
2973 unsigned l;
2974
2975 assert(c);
2976
6796073e
LP
2977 c->environment = strv_free(c->environment);
2978 c->environment_files = strv_free(c->environment_files);
b4c14404 2979 c->pass_environment = strv_free(c->pass_environment);
8c7be95e 2980
1f6b4113 2981 for (l = 0; l < ELEMENTSOF(c->rlimit); l++)
a1e58e8e 2982 c->rlimit[l] = mfree(c->rlimit[l]);
034c6ed7 2983
52c239d7
LB
2984 for (l = 0; l < 3; l++)
2985 c->stdio_fdname[l] = mfree(c->stdio_fdname[l]);
2986
a1e58e8e
LP
2987 c->working_directory = mfree(c->working_directory);
2988 c->root_directory = mfree(c->root_directory);
2989 c->tty_path = mfree(c->tty_path);
2990 c->syslog_identifier = mfree(c->syslog_identifier);
2991 c->user = mfree(c->user);
2992 c->group = mfree(c->group);
034c6ed7 2993
6796073e 2994 c->supplementary_groups = strv_free(c->supplementary_groups);
94f04347 2995
a1e58e8e 2996 c->pam_name = mfree(c->pam_name);
5b6319dc 2997
2a624c36
AP
2998 c->read_only_paths = strv_free(c->read_only_paths);
2999 c->read_write_paths = strv_free(c->read_write_paths);
3000 c->inaccessible_paths = strv_free(c->inaccessible_paths);
82c121a4
LP
3001
3002 if (c->cpuset)
3003 CPU_FREE(c->cpuset);
86a3475b 3004
a1e58e8e
LP
3005 c->utmp_id = mfree(c->utmp_id);
3006 c->selinux_context = mfree(c->selinux_context);
3007 c->apparmor_profile = mfree(c->apparmor_profile);
eef65bf3 3008
525d3cc7
LP
3009 c->syscall_filter = set_free(c->syscall_filter);
3010 c->syscall_archs = set_free(c->syscall_archs);
3011 c->address_families = set_free(c->address_families);
e66cf1a3 3012
6796073e 3013 c->runtime_directory = strv_free(c->runtime_directory);
e66cf1a3
LP
3014}
3015
3016int exec_context_destroy_runtime_directory(ExecContext *c, const char *runtime_prefix) {
3017 char **i;
3018
3019 assert(c);
3020
3021 if (!runtime_prefix)
3022 return 0;
3023
3024 STRV_FOREACH(i, c->runtime_directory) {
3025 _cleanup_free_ char *p;
3026
605405c6 3027 p = strjoin(runtime_prefix, "/", *i);
e66cf1a3
LP
3028 if (!p)
3029 return -ENOMEM;
3030
3031 /* We execute this synchronously, since we need to be
3032 * sure this is gone when we start the service
3033 * next. */
c6878637 3034 (void) rm_rf(p, REMOVE_ROOT);
e66cf1a3
LP
3035 }
3036
3037 return 0;
5cb5a6ff
LP
3038}
3039
43d0fcbd
LP
3040void exec_command_done(ExecCommand *c) {
3041 assert(c);
3042
a1e58e8e 3043 c->path = mfree(c->path);
43d0fcbd 3044
6796073e 3045 c->argv = strv_free(c->argv);
43d0fcbd
LP
3046}
3047
3048void exec_command_done_array(ExecCommand *c, unsigned n) {
3049 unsigned i;
3050
3051 for (i = 0; i < n; i++)
3052 exec_command_done(c+i);
3053}
3054
f1acf85a 3055ExecCommand* exec_command_free_list(ExecCommand *c) {
5cb5a6ff
LP
3056 ExecCommand *i;
3057
3058 while ((i = c)) {
71fda00f 3059 LIST_REMOVE(command, c, i);
43d0fcbd 3060 exec_command_done(i);
5cb5a6ff
LP
3061 free(i);
3062 }
f1acf85a
ZJS
3063
3064 return NULL;
5cb5a6ff
LP
3065}
3066
034c6ed7
LP
3067void exec_command_free_array(ExecCommand **c, unsigned n) {
3068 unsigned i;
3069
f1acf85a
ZJS
3070 for (i = 0; i < n; i++)
3071 c[i] = exec_command_free_list(c[i]);
034c6ed7
LP
3072}
3073
039f0e70 3074typedef struct InvalidEnvInfo {
f2341e0a 3075 Unit *unit;
039f0e70
LP
3076 const char *path;
3077} InvalidEnvInfo;
3078
3079static void invalid_env(const char *p, void *userdata) {
3080 InvalidEnvInfo *info = userdata;
3081
f2341e0a 3082 log_unit_error(info->unit, "Ignoring invalid environment assignment '%s': %s", p, info->path);
039f0e70
LP
3083}
3084
52c239d7
LB
3085const char* exec_context_fdname(const ExecContext *c, int fd_index) {
3086 assert(c);
3087
3088 switch (fd_index) {
3089 case STDIN_FILENO:
3090 if (c->std_input != EXEC_INPUT_NAMED_FD)
3091 return NULL;
3092 return c->stdio_fdname[STDIN_FILENO] ?: "stdin";
3093 case STDOUT_FILENO:
3094 if (c->std_output != EXEC_OUTPUT_NAMED_FD)
3095 return NULL;
3096 return c->stdio_fdname[STDOUT_FILENO] ?: "stdout";
3097 case STDERR_FILENO:
3098 if (c->std_error != EXEC_OUTPUT_NAMED_FD)
3099 return NULL;
3100 return c->stdio_fdname[STDERR_FILENO] ?: "stderr";
3101 default:
3102 return NULL;
3103 }
3104}
3105
3106int exec_context_named_iofds(Unit *unit, const ExecContext *c, const ExecParameters *p, int named_iofds[3]) {
3107 unsigned i, targets;
3108 const char *stdio_fdname[3];
3109
3110 assert(c);
3111 assert(p);
3112
3113 targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
3114 (c->std_output == EXEC_OUTPUT_NAMED_FD) +
3115 (c->std_error == EXEC_OUTPUT_NAMED_FD);
3116
3117 for (i = 0; i < 3; i++)
3118 stdio_fdname[i] = exec_context_fdname(c, i);
3119
3120 for (i = 0; i < p->n_fds && targets > 0; i++)
3121 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])) {
3122 named_iofds[STDIN_FILENO] = p->fds[i];
3123 targets--;
3124 } 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])) {
3125 named_iofds[STDOUT_FILENO] = p->fds[i];
3126 targets--;
3127 } 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])) {
3128 named_iofds[STDERR_FILENO] = p->fds[i];
3129 targets--;
3130 }
3131
3132 return (targets == 0 ? 0 : -ENOENT);
3133}
3134
f2341e0a 3135int exec_context_load_environment(Unit *unit, const ExecContext *c, char ***l) {
8c7be95e
LP
3136 char **i, **r = NULL;
3137
3138 assert(c);
3139 assert(l);
3140
3141 STRV_FOREACH(i, c->environment_files) {
3142 char *fn;
3143 int k;
3144 bool ignore = false;
3145 char **p;
7fd1b19b 3146 _cleanup_globfree_ glob_t pglob = {};
2bef10ab 3147 int count, n;
8c7be95e
LP
3148
3149 fn = *i;
3150
3151 if (fn[0] == '-') {
3152 ignore = true;
313cefa1 3153 fn++;
8c7be95e
LP
3154 }
3155
3156 if (!path_is_absolute(fn)) {
8c7be95e
LP
3157 if (ignore)
3158 continue;
3159
3160 strv_free(r);
3161 return -EINVAL;
3162 }
3163
2bef10ab 3164 /* Filename supports globbing, take all matching files */
2bef10ab
PL
3165 errno = 0;
3166 if (glob(fn, 0, NULL, &pglob) != 0) {
2bef10ab
PL
3167 if (ignore)
3168 continue;
8c7be95e 3169
2bef10ab 3170 strv_free(r);
f5e5c28f 3171 return errno > 0 ? -errno : -EINVAL;
2bef10ab
PL
3172 }
3173 count = pglob.gl_pathc;
3174 if (count == 0) {
8c7be95e
LP
3175 if (ignore)
3176 continue;
3177
3178 strv_free(r);
2bef10ab 3179 return -EINVAL;
8c7be95e 3180 }
2bef10ab 3181 for (n = 0; n < count; n++) {
717603e3 3182 k = load_env_file(NULL, pglob.gl_pathv[n], NULL, &p);
2bef10ab
PL
3183 if (k < 0) {
3184 if (ignore)
3185 continue;
8c7be95e 3186
2bef10ab 3187 strv_free(r);
2bef10ab 3188 return k;
e9c1ea9d 3189 }
ebc05a09 3190 /* Log invalid environment variables with filename */
039f0e70
LP
3191 if (p) {
3192 InvalidEnvInfo info = {
f2341e0a 3193 .unit = unit,
039f0e70
LP
3194 .path = pglob.gl_pathv[n]
3195 };
3196
3197 p = strv_env_clean_with_callback(p, invalid_env, &info);
3198 }
8c7be95e 3199
2bef10ab
PL
3200 if (r == NULL)
3201 r = p;
3202 else {
3203 char **m;
8c7be95e 3204
2bef10ab
PL
3205 m = strv_env_merge(2, r, p);
3206 strv_free(r);
3207 strv_free(p);
c84a9488 3208 if (!m)
2bef10ab 3209 return -ENOMEM;
2bef10ab
PL
3210
3211 r = m;
3212 }
8c7be95e
LP
3213 }
3214 }
3215
3216 *l = r;
3217
3218 return 0;
3219}
3220
6ac8fdc9 3221static bool tty_may_match_dev_console(const char *tty) {
e1d75803 3222 _cleanup_free_ char *active = NULL;
7d6884b6 3223 char *console;
6ac8fdc9 3224
1e22b5cd
LP
3225 if (!tty)
3226 return true;
3227
6ac8fdc9
MS
3228 if (startswith(tty, "/dev/"))
3229 tty += 5;
3230
3231 /* trivial identity? */
3232 if (streq(tty, "console"))
3233 return true;
3234
3235 console = resolve_dev_console(&active);
3236 /* if we could not resolve, assume it may */
3237 if (!console)
3238 return true;
3239
3240 /* "tty0" means the active VC, so it may be the same sometimes */
e1d75803 3241 return streq(console, tty) || (streq(console, "tty0") && tty_is_vc(tty));
6ac8fdc9
MS
3242}
3243
3244bool exec_context_may_touch_console(ExecContext *ec) {
1e22b5cd
LP
3245
3246 return (ec->tty_reset ||
3247 ec->tty_vhangup ||
3248 ec->tty_vt_disallocate ||
6ac8fdc9
MS
3249 is_terminal_input(ec->std_input) ||
3250 is_terminal_output(ec->std_output) ||
3251 is_terminal_output(ec->std_error)) &&
1e22b5cd 3252 tty_may_match_dev_console(exec_context_tty_path(ec));
6ac8fdc9
MS
3253}
3254
15ae422b
LP
3255static void strv_fprintf(FILE *f, char **l) {
3256 char **g;
3257
3258 assert(f);
3259
3260 STRV_FOREACH(g, l)
3261 fprintf(f, " %s", *g);
3262}
3263
5cb5a6ff 3264void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
c2bbd90b 3265 char **e, **d;
94f04347 3266 unsigned i;
add00535 3267 int r;
9eba9da4 3268
5cb5a6ff
LP
3269 assert(c);
3270 assert(f);
3271
4ad49000 3272 prefix = strempty(prefix);
5cb5a6ff
LP
3273
3274 fprintf(f,
94f04347
LP
3275 "%sUMask: %04o\n"
3276 "%sWorkingDirectory: %s\n"
451a074f 3277 "%sRootDirectory: %s\n"
15ae422b 3278 "%sNonBlocking: %s\n"
64747e2d 3279 "%sPrivateTmp: %s\n"
7f112f50 3280 "%sPrivateDevices: %s\n"
59eeb84b 3281 "%sProtectKernelTunables: %s\n"
e66a2f65 3282 "%sProtectKernelModules: %s\n"
59eeb84b 3283 "%sProtectControlGroups: %s\n"
d251207d
LP
3284 "%sPrivateNetwork: %s\n"
3285 "%sPrivateUsers: %s\n"
1b8689f9
LP
3286 "%sProtectHome: %s\n"
3287 "%sProtectSystem: %s\n"
f3e43635 3288 "%sIgnoreSIGPIPE: %s\n"
f4170c67
LP
3289 "%sMemoryDenyWriteExecute: %s\n"
3290 "%sRestrictRealtime: %s\n",
5cb5a6ff 3291 prefix, c->umask,
9eba9da4 3292 prefix, c->working_directory ? c->working_directory : "/",
451a074f 3293 prefix, c->root_directory ? c->root_directory : "/",
15ae422b 3294 prefix, yes_no(c->non_blocking),
64747e2d 3295 prefix, yes_no(c->private_tmp),
7f112f50 3296 prefix, yes_no(c->private_devices),
59eeb84b 3297 prefix, yes_no(c->protect_kernel_tunables),
e66a2f65 3298 prefix, yes_no(c->protect_kernel_modules),
59eeb84b 3299 prefix, yes_no(c->protect_control_groups),
d251207d
LP
3300 prefix, yes_no(c->private_network),
3301 prefix, yes_no(c->private_users),
1b8689f9
LP
3302 prefix, protect_home_to_string(c->protect_home),
3303 prefix, protect_system_to_string(c->protect_system),
f3e43635 3304 prefix, yes_no(c->ignore_sigpipe),
f4170c67
LP
3305 prefix, yes_no(c->memory_deny_write_execute),
3306 prefix, yes_no(c->restrict_realtime));
fb33a393 3307
8c7be95e
LP
3308 STRV_FOREACH(e, c->environment)
3309 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
3310
3311 STRV_FOREACH(e, c->environment_files)
3312 fprintf(f, "%sEnvironmentFile: %s\n", prefix, *e);
94f04347 3313
b4c14404
FB
3314 STRV_FOREACH(e, c->pass_environment)
3315 fprintf(f, "%sPassEnvironment: %s\n", prefix, *e);
3316
c2bbd90b
EV
3317 fprintf(f, "%sRuntimeDirectoryMode: %04o\n", prefix, c->runtime_directory_mode);
3318
3319 STRV_FOREACH(d, c->runtime_directory)
3320 fprintf(f, "%sRuntimeDirectory: %s\n", prefix, *d);
3321
fb33a393
LP
3322 if (c->nice_set)
3323 fprintf(f,
3324 "%sNice: %i\n",
3325 prefix, c->nice);
3326
dd6c17b1 3327 if (c->oom_score_adjust_set)
fb33a393 3328 fprintf(f,
dd6c17b1
LP
3329 "%sOOMScoreAdjust: %i\n",
3330 prefix, c->oom_score_adjust);
9eba9da4 3331
94f04347 3332 for (i = 0; i < RLIM_NLIMITS; i++)
3c11da9d
EV
3333 if (c->rlimit[i]) {
3334 fprintf(f, "%s%s: " RLIM_FMT "\n",
3335 prefix, rlimit_to_string(i), c->rlimit[i]->rlim_max);
3336 fprintf(f, "%s%sSoft: " RLIM_FMT "\n",
3337 prefix, rlimit_to_string(i), c->rlimit[i]->rlim_cur);
3338 }
94f04347 3339
f8b69d1d 3340 if (c->ioprio_set) {
1756a011 3341 _cleanup_free_ char *class_str = NULL;
f8b69d1d 3342
1756a011 3343 ioprio_class_to_string_alloc(IOPRIO_PRIO_CLASS(c->ioprio), &class_str);
9eba9da4
LP
3344 fprintf(f,
3345 "%sIOSchedulingClass: %s\n"
3346 "%sIOPriority: %i\n",
f8b69d1d 3347 prefix, strna(class_str),
9eba9da4 3348 prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
f8b69d1d 3349 }
94f04347 3350
f8b69d1d 3351 if (c->cpu_sched_set) {
1756a011 3352 _cleanup_free_ char *policy_str = NULL;
f8b69d1d 3353
1756a011 3354 sched_policy_to_string_alloc(c->cpu_sched_policy, &policy_str);
94f04347
LP
3355 fprintf(f,
3356 "%sCPUSchedulingPolicy: %s\n"
38b48754
LP
3357 "%sCPUSchedulingPriority: %i\n"
3358 "%sCPUSchedulingResetOnFork: %s\n",
f8b69d1d 3359 prefix, strna(policy_str),
38b48754
LP
3360 prefix, c->cpu_sched_priority,
3361 prefix, yes_no(c->cpu_sched_reset_on_fork));
b929bf04 3362 }
94f04347 3363
82c121a4 3364 if (c->cpuset) {
94f04347 3365 fprintf(f, "%sCPUAffinity:", prefix);
82c121a4
LP
3366 for (i = 0; i < c->cpuset_ncpus; i++)
3367 if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
43a99a7a 3368 fprintf(f, " %u", i);
94f04347
LP
3369 fputs("\n", f);
3370 }
3371
3a43da28 3372 if (c->timer_slack_nsec != NSEC_INFINITY)
ccd06097 3373 fprintf(f, "%sTimerSlackNSec: "NSEC_FMT "\n", prefix, c->timer_slack_nsec);
94f04347
LP
3374
3375 fprintf(f,
80876c20
LP
3376 "%sStandardInput: %s\n"
3377 "%sStandardOutput: %s\n"
3378 "%sStandardError: %s\n",
3379 prefix, exec_input_to_string(c->std_input),
3380 prefix, exec_output_to_string(c->std_output),
3381 prefix, exec_output_to_string(c->std_error));
3382
3383 if (c->tty_path)
3384 fprintf(f,
6ea832a2
LP
3385 "%sTTYPath: %s\n"
3386 "%sTTYReset: %s\n"
3387 "%sTTYVHangup: %s\n"
3388 "%sTTYVTDisallocate: %s\n",
3389 prefix, c->tty_path,
3390 prefix, yes_no(c->tty_reset),
3391 prefix, yes_no(c->tty_vhangup),
3392 prefix, yes_no(c->tty_vt_disallocate));
94f04347 3393
5ce70e5b
ZJS
3394 if (c->std_output == EXEC_OUTPUT_SYSLOG ||
3395 c->std_output == EXEC_OUTPUT_KMSG ||
3396 c->std_output == EXEC_OUTPUT_JOURNAL ||
3397 c->std_output == EXEC_OUTPUT_SYSLOG_AND_CONSOLE ||
3398 c->std_output == EXEC_OUTPUT_KMSG_AND_CONSOLE ||
3399 c->std_output == EXEC_OUTPUT_JOURNAL_AND_CONSOLE ||
3400 c->std_error == EXEC_OUTPUT_SYSLOG ||
3401 c->std_error == EXEC_OUTPUT_KMSG ||
3402 c->std_error == EXEC_OUTPUT_JOURNAL ||
3403 c->std_error == EXEC_OUTPUT_SYSLOG_AND_CONSOLE ||
3404 c->std_error == EXEC_OUTPUT_KMSG_AND_CONSOLE ||
3405 c->std_error == EXEC_OUTPUT_JOURNAL_AND_CONSOLE) {
f8b69d1d 3406
5ce70e5b 3407 _cleanup_free_ char *fac_str = NULL, *lvl_str = NULL;
f8b69d1d 3408
5ce70e5b
ZJS
3409 log_facility_unshifted_to_string_alloc(c->syslog_priority >> 3, &fac_str);
3410 log_level_to_string_alloc(LOG_PRI(c->syslog_priority), &lvl_str);
f8b69d1d 3411
94f04347
LP
3412 fprintf(f,
3413 "%sSyslogFacility: %s\n"
3414 "%sSyslogLevel: %s\n",
f8b69d1d
MS
3415 prefix, strna(fac_str),
3416 prefix, strna(lvl_str));
f8b69d1d 3417 }
94f04347 3418
94f04347
LP
3419 if (c->secure_bits)
3420 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
3421 prefix,
cbb21cca
ZJS
3422 (c->secure_bits & 1<<SECURE_KEEP_CAPS) ? " keep-caps" : "",
3423 (c->secure_bits & 1<<SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
3424 (c->secure_bits & 1<<SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
3425 (c->secure_bits & 1<<SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
3426 (c->secure_bits & 1<<SECURE_NOROOT) ? " noroot" : "",
3427 (c->secure_bits & 1<<SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
94f04347 3428
a103496c 3429 if (c->capability_bounding_set != CAP_ALL) {
ae556c21 3430 unsigned long l;
260abb78 3431 fprintf(f, "%sCapabilityBoundingSet:", prefix);
94f04347 3432
64685e0c 3433 for (l = 0; l <= cap_last_cap(); l++)
a103496c 3434 if (c->capability_bounding_set & (UINT64_C(1) << l))
2822da4f 3435 fprintf(f, " %s", strna(capability_to_name(l)));
94f04347
LP
3436
3437 fputs("\n", f);
755d4b67
IP
3438 }
3439
3440 if (c->capability_ambient_set != 0) {
3441 unsigned long l;
3442 fprintf(f, "%sAmbientCapabilities:", prefix);
3443
3444 for (l = 0; l <= cap_last_cap(); l++)
3445 if (c->capability_ambient_set & (UINT64_C(1) << l))
3446 fprintf(f, " %s", strna(capability_to_name(l)));
3447
3448 fputs("\n", f);
94f04347
LP
3449 }
3450
3451 if (c->user)
f2d3769a 3452 fprintf(f, "%sUser: %s\n", prefix, c->user);
94f04347 3453 if (c->group)
f2d3769a 3454 fprintf(f, "%sGroup: %s\n", prefix, c->group);
94f04347 3455
29206d46
LP
3456 fprintf(f, "%sDynamicUser: %s\n", prefix, yes_no(c->dynamic_user));
3457
15ae422b 3458 if (strv_length(c->supplementary_groups) > 0) {
94f04347 3459 fprintf(f, "%sSupplementaryGroups:", prefix);
15ae422b
LP
3460 strv_fprintf(f, c->supplementary_groups);
3461 fputs("\n", f);
3462 }
94f04347 3463
5b6319dc 3464 if (c->pam_name)
f2d3769a 3465 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
5b6319dc 3466
2a624c36
AP
3467 if (strv_length(c->read_write_paths) > 0) {
3468 fprintf(f, "%sReadWritePaths:", prefix);
3469 strv_fprintf(f, c->read_write_paths);
15ae422b
LP
3470 fputs("\n", f);
3471 }
3472
2a624c36
AP
3473 if (strv_length(c->read_only_paths) > 0) {
3474 fprintf(f, "%sReadOnlyPaths:", prefix);
3475 strv_fprintf(f, c->read_only_paths);
15ae422b
LP
3476 fputs("\n", f);
3477 }
94f04347 3478
2a624c36
AP
3479 if (strv_length(c->inaccessible_paths) > 0) {
3480 fprintf(f, "%sInaccessiblePaths:", prefix);
3481 strv_fprintf(f, c->inaccessible_paths);
94f04347
LP
3482 fputs("\n", f);
3483 }
2e22afe9 3484
169c1bda
LP
3485 if (c->utmp_id)
3486 fprintf(f,
3487 "%sUtmpIdentifier: %s\n",
3488 prefix, c->utmp_id);
7b52a628
MS
3489
3490 if (c->selinux_context)
3491 fprintf(f,
5f8640fb
LP
3492 "%sSELinuxContext: %s%s\n",
3493 prefix, c->selinux_context_ignore ? "-" : "", c->selinux_context);
17df7223 3494
050f7277 3495 if (c->personality != PERSONALITY_INVALID)
ac45f971
LP
3496 fprintf(f,
3497 "%sPersonality: %s\n",
3498 prefix, strna(personality_to_string(c->personality)));
3499
17df7223 3500 if (c->syscall_filter) {
351a19b1 3501#ifdef HAVE_SECCOMP
17df7223
LP
3502 Iterator j;
3503 void *id;
3504 bool first = true;
351a19b1 3505#endif
17df7223
LP
3506
3507 fprintf(f,
57183d11 3508 "%sSystemCallFilter: ",
17df7223
LP
3509 prefix);
3510
3511 if (!c->syscall_whitelist)
3512 fputc('~', f);
3513
351a19b1 3514#ifdef HAVE_SECCOMP
17df7223
LP
3515 SET_FOREACH(id, c->syscall_filter, j) {
3516 _cleanup_free_ char *name = NULL;
3517
3518 if (first)
3519 first = false;
3520 else
3521 fputc(' ', f);
3522
57183d11 3523 name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
17df7223
LP
3524 fputs(strna(name), f);
3525 }
351a19b1 3526#endif
17df7223
LP
3527
3528 fputc('\n', f);
3529 }
3530
57183d11
LP
3531 if (c->syscall_archs) {
3532#ifdef HAVE_SECCOMP
3533 Iterator j;
3534 void *id;
3535#endif
3536
3537 fprintf(f,
3538 "%sSystemCallArchitectures:",
3539 prefix);
3540
3541#ifdef HAVE_SECCOMP
3542 SET_FOREACH(id, c->syscall_archs, j)
3543 fprintf(f, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id) - 1)));
3544#endif
3545 fputc('\n', f);
3546 }
3547
add00535
LP
3548 if (exec_context_restrict_namespaces_set(c)) {
3549 _cleanup_free_ char *s = NULL;
3550
3551 r = namespace_flag_to_string_many(c->restrict_namespaces, &s);
3552 if (r >= 0)
3553 fprintf(f, "%sRestrictNamespaces: %s\n",
3554 prefix, s);
3555 }
3556
b3267152 3557 if (c->syscall_errno > 0)
17df7223
LP
3558 fprintf(f,
3559 "%sSystemCallErrorNumber: %s\n",
3560 prefix, strna(errno_to_name(c->syscall_errno)));
eef65bf3
MS
3561
3562 if (c->apparmor_profile)
3563 fprintf(f,
3564 "%sAppArmorProfile: %s%s\n",
3565 prefix, c->apparmor_profile_ignore ? "-" : "", c->apparmor_profile);
5cb5a6ff
LP
3566}
3567
a931ad47
LP
3568bool exec_context_maintains_privileges(ExecContext *c) {
3569 assert(c);
3570
61233823 3571 /* Returns true if the process forked off would run under
a931ad47
LP
3572 * an unchanged UID or as root. */
3573
3574 if (!c->user)
3575 return true;
3576
3577 if (streq(c->user, "root") || streq(c->user, "0"))
3578 return true;
3579
3580 return false;
3581}
3582
b58b4116 3583void exec_status_start(ExecStatus *s, pid_t pid) {
034c6ed7 3584 assert(s);
5cb5a6ff 3585
b58b4116
LP
3586 zero(*s);
3587 s->pid = pid;
3588 dual_timestamp_get(&s->start_timestamp);
3589}
3590
6ea832a2 3591void exec_status_exit(ExecStatus *s, ExecContext *context, pid_t pid, int code, int status) {
b58b4116
LP
3592 assert(s);
3593
0b1f4ae6 3594 if (s->pid && s->pid != pid)
b58b4116
LP
3595 zero(*s);
3596
034c6ed7 3597 s->pid = pid;
63983207 3598 dual_timestamp_get(&s->exit_timestamp);
9fb86720 3599
034c6ed7
LP
3600 s->code = code;
3601 s->status = status;
169c1bda 3602
6ea832a2
LP
3603 if (context) {
3604 if (context->utmp_id)
3605 utmp_put_dead_process(context->utmp_id, pid, code, status);
3606
1e22b5cd 3607 exec_context_tty_reset(context, NULL);
6ea832a2 3608 }
9fb86720
LP
3609}
3610
3611void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
3612 char buf[FORMAT_TIMESTAMP_MAX];
3613
3614 assert(s);
3615 assert(f);
3616
9fb86720
LP
3617 if (s->pid <= 0)
3618 return;
3619
4c940960
LP
3620 prefix = strempty(prefix);
3621
9fb86720 3622 fprintf(f,
ccd06097
ZJS
3623 "%sPID: "PID_FMT"\n",
3624 prefix, s->pid);
9fb86720 3625
af9d16e1 3626 if (dual_timestamp_is_set(&s->start_timestamp))
9fb86720
LP
3627 fprintf(f,
3628 "%sStart Timestamp: %s\n",
63983207 3629 prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
9fb86720 3630
af9d16e1 3631 if (dual_timestamp_is_set(&s->exit_timestamp))
9fb86720
LP
3632 fprintf(f,
3633 "%sExit Timestamp: %s\n"
3634 "%sExit Code: %s\n"
3635 "%sExit Status: %i\n",
63983207 3636 prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
9fb86720
LP
3637 prefix, sigchld_code_to_string(s->code),
3638 prefix, s->status);
5cb5a6ff 3639}
44d8db9e 3640
9e2f7c11 3641char *exec_command_line(char **argv) {
44d8db9e
LP
3642 size_t k;
3643 char *n, *p, **a;
3644 bool first = true;
3645
9e2f7c11 3646 assert(argv);
44d8db9e 3647
9164977d 3648 k = 1;
9e2f7c11 3649 STRV_FOREACH(a, argv)
44d8db9e
LP
3650 k += strlen(*a)+3;
3651
5cd9cd35
LP
3652 n = new(char, k);
3653 if (!n)
44d8db9e
LP
3654 return NULL;
3655
3656 p = n;
9e2f7c11 3657 STRV_FOREACH(a, argv) {
44d8db9e
LP
3658
3659 if (!first)
3660 *(p++) = ' ';
3661 else
3662 first = false;
3663
3664 if (strpbrk(*a, WHITESPACE)) {
3665 *(p++) = '\'';
3666 p = stpcpy(p, *a);
3667 *(p++) = '\'';
3668 } else
3669 p = stpcpy(p, *a);
3670
3671 }
3672
9164977d
LP
3673 *p = 0;
3674
44d8db9e
LP
3675 /* FIXME: this doesn't really handle arguments that have
3676 * spaces and ticks in them */
3677
3678 return n;
3679}
3680
3681void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
e1d75803 3682 _cleanup_free_ char *cmd = NULL;
4c940960 3683 const char *prefix2;
44d8db9e
LP
3684
3685 assert(c);
3686 assert(f);
3687
4c940960 3688 prefix = strempty(prefix);
63c372cb 3689 prefix2 = strjoina(prefix, "\t");
44d8db9e 3690
9e2f7c11 3691 cmd = exec_command_line(c->argv);
44d8db9e
LP
3692 fprintf(f,
3693 "%sCommand Line: %s\n",
3694 prefix, cmd ? cmd : strerror(ENOMEM));
3695
9fb86720 3696 exec_status_dump(&c->exec_status, f, prefix2);
44d8db9e
LP
3697}
3698
3699void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
3700 assert(f);
3701
4c940960 3702 prefix = strempty(prefix);
44d8db9e
LP
3703
3704 LIST_FOREACH(command, c, c)
3705 exec_command_dump(c, f, prefix);
3706}
94f04347 3707
a6a80b4f
LP
3708void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
3709 ExecCommand *end;
3710
3711 assert(l);
3712 assert(e);
3713
3714 if (*l) {
35b8ca3a 3715 /* It's kind of important, that we keep the order here */
71fda00f
LP
3716 LIST_FIND_TAIL(command, *l, end);
3717 LIST_INSERT_AFTER(command, *l, end, e);
a6a80b4f
LP
3718 } else
3719 *l = e;
3720}
3721
26fd040d
LP
3722int exec_command_set(ExecCommand *c, const char *path, ...) {
3723 va_list ap;
3724 char **l, *p;
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
250a918d
LP
3736 p = strdup(path);
3737 if (!p) {
26fd040d
LP
3738 strv_free(l);
3739 return -ENOMEM;
3740 }
3741
3742 free(c->path);
3743 c->path = p;
3744
3745 strv_free(c->argv);
3746 c->argv = l;
3747
3748 return 0;
3749}
3750
86b23b07 3751int exec_command_append(ExecCommand *c, const char *path, ...) {
e63ff941 3752 _cleanup_strv_free_ char **l = NULL;
86b23b07 3753 va_list ap;
86b23b07
JS
3754 int r;
3755
3756 assert(c);
3757 assert(path);
3758
3759 va_start(ap, path);
3760 l = strv_new_ap(path, ap);
3761 va_end(ap);
3762
3763 if (!l)
3764 return -ENOMEM;
3765
e287086b 3766 r = strv_extend_strv(&c->argv, l, false);
e63ff941 3767 if (r < 0)
86b23b07 3768 return r;
86b23b07
JS
3769
3770 return 0;
3771}
3772
3773
613b411c
LP
3774static int exec_runtime_allocate(ExecRuntime **rt) {
3775
3776 if (*rt)
3777 return 0;
3778
3779 *rt = new0(ExecRuntime, 1);
f146f5e1 3780 if (!*rt)
613b411c
LP
3781 return -ENOMEM;
3782
3783 (*rt)->n_ref = 1;
3784 (*rt)->netns_storage_socket[0] = (*rt)->netns_storage_socket[1] = -1;
3785
3786 return 0;
3787}
3788
3789int exec_runtime_make(ExecRuntime **rt, ExecContext *c, const char *id) {
3790 int r;
3791
3792 assert(rt);
3793 assert(c);
3794 assert(id);
3795
3796 if (*rt)
3797 return 1;
3798
3799 if (!c->private_network && !c->private_tmp)
3800 return 0;
3801
3802 r = exec_runtime_allocate(rt);
3803 if (r < 0)
3804 return r;
3805
3806 if (c->private_network && (*rt)->netns_storage_socket[0] < 0) {
33df919d 3807 if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, (*rt)->netns_storage_socket) < 0)
613b411c
LP
3808 return -errno;
3809 }
3810
3811 if (c->private_tmp && !(*rt)->tmp_dir) {
3812 r = setup_tmp_dirs(id, &(*rt)->tmp_dir, &(*rt)->var_tmp_dir);
3813 if (r < 0)
3814 return r;
3815 }
3816
3817 return 1;
3818}
3819
3820ExecRuntime *exec_runtime_ref(ExecRuntime *r) {
3821 assert(r);
3822 assert(r->n_ref > 0);
3823
3824 r->n_ref++;
3825 return r;
3826}
3827
3828ExecRuntime *exec_runtime_unref(ExecRuntime *r) {
3829
3830 if (!r)
3831 return NULL;
3832
3833 assert(r->n_ref > 0);
3834
3835 r->n_ref--;
f2341e0a
LP
3836 if (r->n_ref > 0)
3837 return NULL;
3838
3839 free(r->tmp_dir);
3840 free(r->var_tmp_dir);
3841 safe_close_pair(r->netns_storage_socket);
6b430fdb 3842 return mfree(r);
613b411c
LP
3843}
3844
f2341e0a 3845int exec_runtime_serialize(Unit *u, ExecRuntime *rt, FILE *f, FDSet *fds) {
613b411c
LP
3846 assert(u);
3847 assert(f);
3848 assert(fds);
3849
3850 if (!rt)
3851 return 0;
3852
3853 if (rt->tmp_dir)
3854 unit_serialize_item(u, f, "tmp-dir", rt->tmp_dir);
3855
3856 if (rt->var_tmp_dir)
3857 unit_serialize_item(u, f, "var-tmp-dir", rt->var_tmp_dir);
3858
3859 if (rt->netns_storage_socket[0] >= 0) {
3860 int copy;
3861
3862 copy = fdset_put_dup(fds, rt->netns_storage_socket[0]);
3863 if (copy < 0)
3864 return copy;
3865
3866 unit_serialize_item_format(u, f, "netns-socket-0", "%i", copy);
3867 }
3868
3869 if (rt->netns_storage_socket[1] >= 0) {
3870 int copy;
3871
3872 copy = fdset_put_dup(fds, rt->netns_storage_socket[1]);
3873 if (copy < 0)
3874 return copy;
3875
3876 unit_serialize_item_format(u, f, "netns-socket-1", "%i", copy);
3877 }
3878
3879 return 0;
3880}
3881
f2341e0a 3882int exec_runtime_deserialize_item(Unit *u, ExecRuntime **rt, const char *key, const char *value, FDSet *fds) {
613b411c
LP
3883 int r;
3884
3885 assert(rt);
3886 assert(key);
3887 assert(value);
3888
3889 if (streq(key, "tmp-dir")) {
3890 char *copy;
3891
3892 r = exec_runtime_allocate(rt);
3893 if (r < 0)
f2341e0a 3894 return log_oom();
613b411c
LP
3895
3896 copy = strdup(value);
3897 if (!copy)
3898 return log_oom();
3899
3900 free((*rt)->tmp_dir);
3901 (*rt)->tmp_dir = copy;
3902
3903 } else if (streq(key, "var-tmp-dir")) {
3904 char *copy;
3905
3906 r = exec_runtime_allocate(rt);
3907 if (r < 0)
f2341e0a 3908 return log_oom();
613b411c
LP
3909
3910 copy = strdup(value);
3911 if (!copy)
3912 return log_oom();
3913
3914 free((*rt)->var_tmp_dir);
3915 (*rt)->var_tmp_dir = copy;
3916
3917 } else if (streq(key, "netns-socket-0")) {
3918 int fd;
3919
3920 r = exec_runtime_allocate(rt);
3921 if (r < 0)
f2341e0a 3922 return log_oom();
613b411c
LP
3923
3924 if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd))
f2341e0a 3925 log_unit_debug(u, "Failed to parse netns socket value: %s", value);
613b411c 3926 else {
03e334a1 3927 safe_close((*rt)->netns_storage_socket[0]);
613b411c
LP
3928 (*rt)->netns_storage_socket[0] = fdset_remove(fds, fd);
3929 }
3930 } else if (streq(key, "netns-socket-1")) {
3931 int fd;
3932
3933 r = exec_runtime_allocate(rt);
3934 if (r < 0)
f2341e0a 3935 return log_oom();
613b411c
LP
3936
3937 if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd))
f2341e0a 3938 log_unit_debug(u, "Failed to parse netns socket value: %s", value);
613b411c 3939 else {
03e334a1 3940 safe_close((*rt)->netns_storage_socket[1]);
613b411c
LP
3941 (*rt)->netns_storage_socket[1] = fdset_remove(fds, fd);
3942 }
3943 } else
3944 return 0;
3945
3946 return 1;
3947}
3948
3949static void *remove_tmpdir_thread(void *p) {
3950 _cleanup_free_ char *path = p;
3951
c6878637 3952 (void) rm_rf(path, REMOVE_ROOT|REMOVE_PHYSICAL);
613b411c
LP
3953 return NULL;
3954}
3955
3956void exec_runtime_destroy(ExecRuntime *rt) {
98b47d54
LP
3957 int r;
3958
613b411c
LP
3959 if (!rt)
3960 return;
3961
3962 /* If there are multiple users of this, let's leave the stuff around */
3963 if (rt->n_ref > 1)
3964 return;
3965
3966 if (rt->tmp_dir) {
3967 log_debug("Spawning thread to nuke %s", rt->tmp_dir);
98b47d54
LP
3968
3969 r = asynchronous_job(remove_tmpdir_thread, rt->tmp_dir);
3970 if (r < 0) {
da927ba9 3971 log_warning_errno(r, "Failed to nuke %s: %m", rt->tmp_dir);
98b47d54
LP
3972 free(rt->tmp_dir);
3973 }
3974
613b411c
LP
3975 rt->tmp_dir = NULL;
3976 }
3977
3978 if (rt->var_tmp_dir) {
3979 log_debug("Spawning thread to nuke %s", rt->var_tmp_dir);
98b47d54
LP
3980
3981 r = asynchronous_job(remove_tmpdir_thread, rt->var_tmp_dir);
3982 if (r < 0) {
da927ba9 3983 log_warning_errno(r, "Failed to nuke %s: %m", rt->var_tmp_dir);
98b47d54
LP
3984 free(rt->var_tmp_dir);
3985 }
3986
613b411c
LP
3987 rt->var_tmp_dir = NULL;
3988 }
3989
3d94f76c 3990 safe_close_pair(rt->netns_storage_socket);
613b411c
LP
3991}
3992
80876c20
LP
3993static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
3994 [EXEC_INPUT_NULL] = "null",
3995 [EXEC_INPUT_TTY] = "tty",
3996 [EXEC_INPUT_TTY_FORCE] = "tty-force",
4f2d528d 3997 [EXEC_INPUT_TTY_FAIL] = "tty-fail",
52c239d7
LB
3998 [EXEC_INPUT_SOCKET] = "socket",
3999 [EXEC_INPUT_NAMED_FD] = "fd",
80876c20
LP
4000};
4001
8a0867d6
LP
4002DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);
4003
94f04347 4004static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
80876c20 4005 [EXEC_OUTPUT_INHERIT] = "inherit",
94f04347 4006 [EXEC_OUTPUT_NULL] = "null",
80876c20 4007 [EXEC_OUTPUT_TTY] = "tty",
94f04347 4008 [EXEC_OUTPUT_SYSLOG] = "syslog",
28dbc1e8 4009 [EXEC_OUTPUT_SYSLOG_AND_CONSOLE] = "syslog+console",
9a6bca7a 4010 [EXEC_OUTPUT_KMSG] = "kmsg",
28dbc1e8 4011 [EXEC_OUTPUT_KMSG_AND_CONSOLE] = "kmsg+console",
706343f4
LP
4012 [EXEC_OUTPUT_JOURNAL] = "journal",
4013 [EXEC_OUTPUT_JOURNAL_AND_CONSOLE] = "journal+console",
52c239d7
LB
4014 [EXEC_OUTPUT_SOCKET] = "socket",
4015 [EXEC_OUTPUT_NAMED_FD] = "fd",
94f04347
LP
4016};
4017
4018DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
023a4f67
LP
4019
4020static const char* const exec_utmp_mode_table[_EXEC_UTMP_MODE_MAX] = {
4021 [EXEC_UTMP_INIT] = "init",
4022 [EXEC_UTMP_LOGIN] = "login",
4023 [EXEC_UTMP_USER] = "user",
4024};
4025
4026DEFINE_STRING_TABLE_LOOKUP(exec_utmp_mode, ExecUtmpMode);