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