]>
Commit | Line | Data |
---|---|---|
db9ecf05 | 1 | /* SPDX-License-Identifier: LGPL-2.1-or-later */ |
a7334b09 | 2 | |
034c6ed7 LP |
3 | #include <errno.h> |
4 | #include <fcntl.h> | |
8dd4c05b | 5 | #include <poll.h> |
d251207d | 6 | #include <sys/eventfd.h> |
f5947a5e | 7 | #include <sys/ioctl.h> |
f3e43635 | 8 | #include <sys/mman.h> |
bb0c0d6f | 9 | #include <sys/mount.h> |
8dd4c05b | 10 | #include <sys/personality.h> |
94f04347 | 11 | #include <sys/prctl.h> |
d2ffa389 | 12 | #include <sys/shm.h> |
d2ffa389 | 13 | #include <sys/types.h> |
8dd4c05b LP |
14 | #include <sys/un.h> |
15 | #include <unistd.h> | |
023a4f67 | 16 | #include <utmpx.h> |
5cb5a6ff | 17 | |
349cc4a5 | 18 | #if HAVE_PAM |
5b6319dc LP |
19 | #include <security/pam_appl.h> |
20 | #endif | |
21 | ||
349cc4a5 | 22 | #if HAVE_SELINUX |
7b52a628 MS |
23 | #include <selinux/selinux.h> |
24 | #endif | |
25 | ||
349cc4a5 | 26 | #if HAVE_SECCOMP |
17df7223 LP |
27 | #include <seccomp.h> |
28 | #endif | |
29 | ||
349cc4a5 | 30 | #if HAVE_APPARMOR |
eef65bf3 MS |
31 | #include <sys/apparmor.h> |
32 | #endif | |
33 | ||
24882e06 | 34 | #include "sd-messages.h" |
8dd4c05b | 35 | |
bb0c0d6f | 36 | #include "acl-util.h" |
8dd4c05b | 37 | #include "af-list.h" |
b5efdb8a | 38 | #include "alloc-util.h" |
349cc4a5 | 39 | #if HAVE_APPARMOR |
3ffd4af2 LP |
40 | #include "apparmor-util.h" |
41 | #endif | |
8dd4c05b LP |
42 | #include "async.h" |
43 | #include "barrier.h" | |
b1994387 | 44 | #include "bpf-lsm.h" |
8dd4c05b | 45 | #include "cap-list.h" |
430f0182 | 46 | #include "capability-util.h" |
fdb3deca | 47 | #include "cgroup-setup.h" |
f4351959 | 48 | #include "chase-symlinks.h" |
bb0c0d6f | 49 | #include "chown-recursive.h" |
da681e1b | 50 | #include "cpu-set-util.h" |
43144be4 | 51 | #include "creds-util.h" |
6a818c3c | 52 | #include "data-fd-util.h" |
f6a6225e | 53 | #include "def.h" |
686d13b9 | 54 | #include "env-file.h" |
4d1a6904 | 55 | #include "env-util.h" |
17df7223 | 56 | #include "errno-list.h" |
8a62620e | 57 | #include "escape.h" |
3ffd4af2 | 58 | #include "execute.h" |
8dd4c05b | 59 | #include "exit-status.h" |
3ffd4af2 | 60 | #include "fd-util.h" |
bb0c0d6f | 61 | #include "fileio.h" |
f97b34a6 | 62 | #include "format-util.h" |
7d50b32a | 63 | #include "glob-util.h" |
0389f4fa | 64 | #include "hexdecoct.h" |
c004493c | 65 | #include "io-util.h" |
032b3afb | 66 | #include "ioprio-util.h" |
a1164ae3 | 67 | #include "label.h" |
8dd4c05b LP |
68 | #include "log.h" |
69 | #include "macro.h" | |
e8a565cb | 70 | #include "manager.h" |
2a341bb9 | 71 | #include "manager-dump.h" |
0a970718 | 72 | #include "memory-util.h" |
f5947a5e | 73 | #include "missing_fs.h" |
5bead76e | 74 | #include "missing_ioprio.h" |
35cd0ba5 | 75 | #include "mkdir-label.h" |
21935150 | 76 | #include "mount-util.h" |
bb0c0d6f | 77 | #include "mountpoint-util.h" |
8dd4c05b | 78 | #include "namespace.h" |
6bedfcbb | 79 | #include "parse-util.h" |
8dd4c05b | 80 | #include "path-util.h" |
0b452006 | 81 | #include "process-util.h" |
d3dcf4e3 | 82 | #include "random-util.h" |
3989bdc1 | 83 | #include "recurse-dir.h" |
78f22b97 | 84 | #include "rlimit-util.h" |
8dd4c05b | 85 | #include "rm-rf.h" |
349cc4a5 | 86 | #if HAVE_SECCOMP |
3ffd4af2 LP |
87 | #include "seccomp-util.h" |
88 | #endif | |
07d46372 | 89 | #include "securebits-util.h" |
8dd4c05b | 90 | #include "selinux-util.h" |
24882e06 | 91 | #include "signal-util.h" |
8dd4c05b | 92 | #include "smack-util.h" |
57b7a260 | 93 | #include "socket-util.h" |
fd63e712 | 94 | #include "special.h" |
949befd3 | 95 | #include "stat-util.h" |
8b43440b | 96 | #include "string-table.h" |
07630cea | 97 | #include "string-util.h" |
8dd4c05b | 98 | #include "strv.h" |
7ccbd1ae | 99 | #include "syslog-util.h" |
8dd4c05b | 100 | #include "terminal-util.h" |
bb0c0d6f | 101 | #include "tmpfile-util.h" |
566b7d23 | 102 | #include "umask-util.h" |
2d3b784d | 103 | #include "unit-serialize.h" |
b1d4f8e1 | 104 | #include "user-util.h" |
8dd4c05b | 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 | |
531dca78 LP |
110 | #define SNDBUF_SIZE (8*1024*1024) |
111 | ||
da6053d0 | 112 | static int shift_fds(int fds[], size_t n_fds) { |
034c6ed7 LP |
113 | if (n_fds <= 0) |
114 | return 0; | |
115 | ||
a0d40ac5 LP |
116 | /* Modifies the fds array! (sorts it) */ |
117 | ||
034c6ed7 LP |
118 | assert(fds); |
119 | ||
5b10116e ZJS |
120 | for (int start = 0;;) { |
121 | int restart_from = -1; | |
034c6ed7 | 122 | |
5b10116e | 123 | for (int i = start; i < (int) n_fds; i++) { |
034c6ed7 LP |
124 | int nfd; |
125 | ||
126 | /* Already at right index? */ | |
127 | if (fds[i] == i+3) | |
128 | continue; | |
129 | ||
3cc2aff1 LP |
130 | nfd = fcntl(fds[i], F_DUPFD, i + 3); |
131 | if (nfd < 0) | |
034c6ed7 LP |
132 | return -errno; |
133 | ||
03e334a1 | 134 | safe_close(fds[i]); |
034c6ed7 LP |
135 | fds[i] = nfd; |
136 | ||
137 | /* Hmm, the fd we wanted isn't free? Then | |
ee33e53a | 138 | * let's remember that and try again from here */ |
034c6ed7 LP |
139 | if (nfd != i+3 && restart_from < 0) |
140 | restart_from = i; | |
141 | } | |
142 | ||
143 | if (restart_from < 0) | |
144 | break; | |
145 | ||
146 | start = restart_from; | |
147 | } | |
148 | ||
149 | return 0; | |
150 | } | |
151 | ||
25b583d7 | 152 | static int flags_fds(const int fds[], size_t n_socket_fds, size_t n_storage_fds, bool nonblock) { |
5b10116e | 153 | size_t n_fds; |
e2c76839 | 154 | int r; |
47a71eed | 155 | |
25b583d7 | 156 | n_fds = n_socket_fds + n_storage_fds; |
47a71eed LP |
157 | if (n_fds <= 0) |
158 | return 0; | |
159 | ||
160 | assert(fds); | |
161 | ||
9b141911 FB |
162 | /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags. |
163 | * O_NONBLOCK only applies to socket activation though. */ | |
47a71eed | 164 | |
5b10116e | 165 | for (size_t i = 0; i < n_fds; i++) { |
47a71eed | 166 | |
9b141911 FB |
167 | if (i < n_socket_fds) { |
168 | r = fd_nonblock(fds[i], nonblock); | |
169 | if (r < 0) | |
170 | return r; | |
171 | } | |
47a71eed | 172 | |
451a074f LP |
173 | /* We unconditionally drop FD_CLOEXEC from the fds, |
174 | * since after all we want to pass these fds to our | |
175 | * children */ | |
47a71eed | 176 | |
3cc2aff1 LP |
177 | r = fd_cloexec(fds[i], false); |
178 | if (r < 0) | |
e2c76839 | 179 | return r; |
47a71eed LP |
180 | } |
181 | ||
182 | return 0; | |
183 | } | |
184 | ||
1e22b5cd | 185 | static const char *exec_context_tty_path(const ExecContext *context) { |
80876c20 LP |
186 | assert(context); |
187 | ||
1e22b5cd LP |
188 | if (context->stdio_as_fds) |
189 | return NULL; | |
190 | ||
80876c20 LP |
191 | if (context->tty_path) |
192 | return context->tty_path; | |
193 | ||
194 | return "/dev/console"; | |
195 | } | |
196 | ||
1e22b5cd LP |
197 | static void exec_context_tty_reset(const ExecContext *context, const ExecParameters *p) { |
198 | const char *path; | |
199 | ||
6ea832a2 LP |
200 | assert(context); |
201 | ||
1e22b5cd | 202 | path = exec_context_tty_path(context); |
6ea832a2 | 203 | |
1e22b5cd LP |
204 | if (context->tty_vhangup) { |
205 | if (p && p->stdin_fd >= 0) | |
206 | (void) terminal_vhangup_fd(p->stdin_fd); | |
207 | else if (path) | |
208 | (void) terminal_vhangup(path); | |
209 | } | |
6ea832a2 | 210 | |
1e22b5cd LP |
211 | if (context->tty_reset) { |
212 | if (p && p->stdin_fd >= 0) | |
213 | (void) reset_terminal_fd(p->stdin_fd, true); | |
214 | else if (path) | |
215 | (void) reset_terminal(path); | |
216 | } | |
217 | ||
51462135 DDM |
218 | if (p && p->stdin_fd >= 0) |
219 | (void) terminal_set_size_fd(p->stdin_fd, path, context->tty_rows, context->tty_cols); | |
220 | ||
1e22b5cd LP |
221 | if (context->tty_vt_disallocate && path) |
222 | (void) vt_disallocate(path); | |
6ea832a2 LP |
223 | } |
224 | ||
6af760f3 LP |
225 | static bool is_terminal_input(ExecInput i) { |
226 | return IN_SET(i, | |
227 | EXEC_INPUT_TTY, | |
228 | EXEC_INPUT_TTY_FORCE, | |
229 | EXEC_INPUT_TTY_FAIL); | |
230 | } | |
231 | ||
3a1286b6 | 232 | static bool is_terminal_output(ExecOutput o) { |
6af760f3 LP |
233 | return IN_SET(o, |
234 | EXEC_OUTPUT_TTY, | |
6af760f3 LP |
235 | EXEC_OUTPUT_KMSG_AND_CONSOLE, |
236 | EXEC_OUTPUT_JOURNAL_AND_CONSOLE); | |
237 | } | |
238 | ||
aac8c0c3 LP |
239 | static bool is_kmsg_output(ExecOutput o) { |
240 | return IN_SET(o, | |
241 | EXEC_OUTPUT_KMSG, | |
242 | EXEC_OUTPUT_KMSG_AND_CONSOLE); | |
243 | } | |
244 | ||
6af760f3 LP |
245 | static bool exec_context_needs_term(const ExecContext *c) { |
246 | assert(c); | |
247 | ||
248 | /* Return true if the execution context suggests we should set $TERM to something useful. */ | |
249 | ||
250 | if (is_terminal_input(c->std_input)) | |
251 | return true; | |
252 | ||
253 | if (is_terminal_output(c->std_output)) | |
254 | return true; | |
255 | ||
256 | if (is_terminal_output(c->std_error)) | |
257 | return true; | |
258 | ||
259 | return !!c->tty_path; | |
3a1286b6 MS |
260 | } |
261 | ||
80876c20 | 262 | static int open_null_as(int flags, int nfd) { |
046a82c1 | 263 | int fd; |
071830ff | 264 | |
80876c20 | 265 | assert(nfd >= 0); |
071830ff | 266 | |
613b411c LP |
267 | fd = open("/dev/null", flags|O_NOCTTY); |
268 | if (fd < 0) | |
071830ff LP |
269 | return -errno; |
270 | ||
046a82c1 | 271 | return move_fd(fd, nfd, false); |
071830ff LP |
272 | } |
273 | ||
91dd5f7c LP |
274 | static int connect_journal_socket( |
275 | int fd, | |
276 | const char *log_namespace, | |
277 | uid_t uid, | |
278 | gid_t gid) { | |
279 | ||
f36a9d59 ZJS |
280 | union sockaddr_union sa; |
281 | socklen_t sa_len; | |
524daa8c ZJS |
282 | uid_t olduid = UID_INVALID; |
283 | gid_t oldgid = GID_INVALID; | |
91dd5f7c | 284 | const char *j; |
524daa8c ZJS |
285 | int r; |
286 | ||
91dd5f7c LP |
287 | j = log_namespace ? |
288 | strjoina("/run/systemd/journal.", log_namespace, "/stdout") : | |
289 | "/run/systemd/journal/stdout"; | |
290 | r = sockaddr_un_set_path(&sa.un, j); | |
291 | if (r < 0) | |
292 | return r; | |
f36a9d59 | 293 | sa_len = r; |
91dd5f7c | 294 | |
cad93f29 | 295 | if (gid_is_valid(gid)) { |
524daa8c ZJS |
296 | oldgid = getgid(); |
297 | ||
92a17af9 | 298 | if (setegid(gid) < 0) |
524daa8c ZJS |
299 | return -errno; |
300 | } | |
301 | ||
cad93f29 | 302 | if (uid_is_valid(uid)) { |
524daa8c ZJS |
303 | olduid = getuid(); |
304 | ||
92a17af9 | 305 | if (seteuid(uid) < 0) { |
524daa8c ZJS |
306 | r = -errno; |
307 | goto restore_gid; | |
308 | } | |
309 | } | |
310 | ||
7c248223 | 311 | r = RET_NERRNO(connect(fd, &sa.sa, sa_len)); |
524daa8c ZJS |
312 | |
313 | /* If we fail to restore the uid or gid, things will likely | |
314 | fail later on. This should only happen if an LSM interferes. */ | |
315 | ||
cad93f29 | 316 | if (uid_is_valid(uid)) |
524daa8c ZJS |
317 | (void) seteuid(olduid); |
318 | ||
319 | restore_gid: | |
cad93f29 | 320 | if (gid_is_valid(gid)) |
524daa8c ZJS |
321 | (void) setegid(oldgid); |
322 | ||
323 | return r; | |
324 | } | |
325 | ||
fd1f9c89 | 326 | static int connect_logger_as( |
34cf6c43 | 327 | const Unit *unit, |
fd1f9c89 | 328 | const ExecContext *context, |
af635cf3 | 329 | const ExecParameters *params, |
fd1f9c89 LP |
330 | ExecOutput output, |
331 | const char *ident, | |
fd1f9c89 LP |
332 | int nfd, |
333 | uid_t uid, | |
334 | gid_t gid) { | |
335 | ||
2ac1ff68 EV |
336 | _cleanup_close_ int fd = -1; |
337 | int r; | |
071830ff LP |
338 | |
339 | assert(context); | |
af635cf3 | 340 | assert(params); |
80876c20 LP |
341 | assert(output < _EXEC_OUTPUT_MAX); |
342 | assert(ident); | |
343 | assert(nfd >= 0); | |
071830ff | 344 | |
54fe0cdb LP |
345 | fd = socket(AF_UNIX, SOCK_STREAM, 0); |
346 | if (fd < 0) | |
80876c20 | 347 | return -errno; |
071830ff | 348 | |
91dd5f7c | 349 | r = connect_journal_socket(fd, context->log_namespace, uid, gid); |
524daa8c ZJS |
350 | if (r < 0) |
351 | return r; | |
071830ff | 352 | |
2ac1ff68 | 353 | if (shutdown(fd, SHUT_RD) < 0) |
80876c20 | 354 | return -errno; |
071830ff | 355 | |
fd1f9c89 | 356 | (void) fd_inc_sndbuf(fd, SNDBUF_SIZE); |
531dca78 | 357 | |
2ac1ff68 | 358 | if (dprintf(fd, |
62bca2c6 | 359 | "%s\n" |
80876c20 LP |
360 | "%s\n" |
361 | "%i\n" | |
54fe0cdb LP |
362 | "%i\n" |
363 | "%i\n" | |
364 | "%i\n" | |
4f4a1dbf | 365 | "%i\n", |
c867611e | 366 | context->syslog_identifier ?: ident, |
af635cf3 | 367 | params->flags & EXEC_PASS_LOG_UNIT ? unit->id : "", |
54fe0cdb LP |
368 | context->syslog_priority, |
369 | !!context->syslog_level_prefix, | |
f3dc6af2 | 370 | false, |
aac8c0c3 | 371 | is_kmsg_output(output), |
2ac1ff68 EV |
372 | is_terminal_output(output)) < 0) |
373 | return -errno; | |
80876c20 | 374 | |
2ac1ff68 | 375 | return move_fd(TAKE_FD(fd), nfd, false); |
80876c20 | 376 | } |
2ac1ff68 | 377 | |
3a274a21 | 378 | static int open_terminal_as(const char *path, int flags, int nfd) { |
046a82c1 | 379 | int fd; |
071830ff | 380 | |
80876c20 LP |
381 | assert(path); |
382 | assert(nfd >= 0); | |
fd1f9c89 | 383 | |
3a274a21 | 384 | fd = open_terminal(path, flags | O_NOCTTY); |
3cc2aff1 | 385 | if (fd < 0) |
80876c20 | 386 | return fd; |
071830ff | 387 | |
046a82c1 | 388 | return move_fd(fd, nfd, false); |
80876c20 | 389 | } |
071830ff | 390 | |
2038c3f5 | 391 | static int acquire_path(const char *path, int flags, mode_t mode) { |
86fca584 ZJS |
392 | union sockaddr_union sa; |
393 | socklen_t sa_len; | |
15a3e96f | 394 | _cleanup_close_ int fd = -1; |
86fca584 | 395 | int r; |
071830ff | 396 | |
80876c20 | 397 | assert(path); |
071830ff | 398 | |
2038c3f5 LP |
399 | if (IN_SET(flags & O_ACCMODE, O_WRONLY, O_RDWR)) |
400 | flags |= O_CREAT; | |
401 | ||
402 | fd = open(path, flags|O_NOCTTY, mode); | |
403 | if (fd >= 0) | |
15a3e96f | 404 | return TAKE_FD(fd); |
071830ff | 405 | |
2038c3f5 LP |
406 | if (errno != ENXIO) /* ENXIO is returned when we try to open() an AF_UNIX file system socket on Linux */ |
407 | return -errno; | |
2038c3f5 LP |
408 | |
409 | /* So, it appears the specified path could be an AF_UNIX socket. Let's see if we can connect to it. */ | |
410 | ||
86fca584 ZJS |
411 | r = sockaddr_un_set_path(&sa.un, path); |
412 | if (r < 0) | |
413 | return r == -EINVAL ? -ENXIO : r; | |
414 | sa_len = r; | |
415 | ||
2038c3f5 LP |
416 | fd = socket(AF_UNIX, SOCK_STREAM, 0); |
417 | if (fd < 0) | |
418 | return -errno; | |
419 | ||
86fca584 | 420 | if (connect(fd, &sa.sa, sa_len) < 0) |
2038c3f5 | 421 | return errno == EINVAL ? -ENXIO : -errno; /* Propagate initial error if we get EINVAL, i.e. we have |
e8607daf | 422 | * indication that this wasn't an AF_UNIX socket after all */ |
071830ff | 423 | |
2038c3f5 LP |
424 | if ((flags & O_ACCMODE) == O_RDONLY) |
425 | r = shutdown(fd, SHUT_WR); | |
426 | else if ((flags & O_ACCMODE) == O_WRONLY) | |
427 | r = shutdown(fd, SHUT_RD); | |
428 | else | |
86fca584 | 429 | r = 0; |
15a3e96f | 430 | if (r < 0) |
2038c3f5 | 431 | return -errno; |
2038c3f5 | 432 | |
15a3e96f | 433 | return TAKE_FD(fd); |
80876c20 | 434 | } |
071830ff | 435 | |
08f3be7a LP |
436 | static int fixup_input( |
437 | const ExecContext *context, | |
438 | int socket_fd, | |
439 | bool apply_tty_stdin) { | |
440 | ||
441 | ExecInput std_input; | |
442 | ||
443 | assert(context); | |
444 | ||
445 | std_input = context->std_input; | |
1e3ad081 LP |
446 | |
447 | if (is_terminal_input(std_input) && !apply_tty_stdin) | |
448 | return EXEC_INPUT_NULL; | |
071830ff | 449 | |
03fd9c49 | 450 | if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0) |
4f2d528d LP |
451 | return EXEC_INPUT_NULL; |
452 | ||
08f3be7a LP |
453 | if (std_input == EXEC_INPUT_DATA && context->stdin_data_size == 0) |
454 | return EXEC_INPUT_NULL; | |
455 | ||
03fd9c49 | 456 | return std_input; |
4f2d528d LP |
457 | } |
458 | ||
7966a916 | 459 | static int fixup_output(ExecOutput output, int socket_fd) { |
4f2d528d | 460 | |
7966a916 | 461 | if (output == EXEC_OUTPUT_SOCKET && socket_fd < 0) |
4f2d528d LP |
462 | return EXEC_OUTPUT_INHERIT; |
463 | ||
7966a916 | 464 | return output; |
4f2d528d LP |
465 | } |
466 | ||
a34ceba6 LP |
467 | static int setup_input( |
468 | const ExecContext *context, | |
469 | const ExecParameters *params, | |
52c239d7 | 470 | int socket_fd, |
2caa38e9 | 471 | const int named_iofds[static 3]) { |
a34ceba6 | 472 | |
4f2d528d | 473 | ExecInput i; |
51462135 | 474 | int r; |
4f2d528d LP |
475 | |
476 | assert(context); | |
a34ceba6 | 477 | assert(params); |
2caa38e9 | 478 | assert(named_iofds); |
a34ceba6 LP |
479 | |
480 | if (params->stdin_fd >= 0) { | |
481 | if (dup2(params->stdin_fd, STDIN_FILENO) < 0) | |
482 | return -errno; | |
483 | ||
484 | /* Try to make this the controlling tty, if it is a tty, and reset it */ | |
1fb0682e LP |
485 | if (isatty(STDIN_FILENO)) { |
486 | (void) ioctl(STDIN_FILENO, TIOCSCTTY, context->std_input == EXEC_INPUT_TTY_FORCE); | |
487 | (void) reset_terminal_fd(STDIN_FILENO, true); | |
51462135 | 488 | (void) terminal_set_size_fd(STDIN_FILENO, NULL, context->tty_rows, context->tty_cols); |
1fb0682e | 489 | } |
a34ceba6 LP |
490 | |
491 | return STDIN_FILENO; | |
492 | } | |
4f2d528d | 493 | |
08f3be7a | 494 | i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN); |
4f2d528d LP |
495 | |
496 | switch (i) { | |
071830ff | 497 | |
80876c20 LP |
498 | case EXEC_INPUT_NULL: |
499 | return open_null_as(O_RDONLY, STDIN_FILENO); | |
500 | ||
501 | case EXEC_INPUT_TTY: | |
502 | case EXEC_INPUT_TTY_FORCE: | |
503 | case EXEC_INPUT_TTY_FAIL: { | |
046a82c1 | 504 | int fd; |
071830ff | 505 | |
1e22b5cd | 506 | fd = acquire_terminal(exec_context_tty_path(context), |
8854d795 LP |
507 | i == EXEC_INPUT_TTY_FAIL ? ACQUIRE_TERMINAL_TRY : |
508 | i == EXEC_INPUT_TTY_FORCE ? ACQUIRE_TERMINAL_FORCE : | |
509 | ACQUIRE_TERMINAL_WAIT, | |
3a43da28 | 510 | USEC_INFINITY); |
970edce6 | 511 | if (fd < 0) |
80876c20 LP |
512 | return fd; |
513 | ||
51462135 DDM |
514 | r = terminal_set_size_fd(fd, exec_context_tty_path(context), context->tty_rows, context->tty_cols); |
515 | if (r < 0) | |
516 | return r; | |
517 | ||
046a82c1 | 518 | return move_fd(fd, STDIN_FILENO, false); |
80876c20 LP |
519 | } |
520 | ||
4f2d528d | 521 | case EXEC_INPUT_SOCKET: |
e75a9ed1 LP |
522 | assert(socket_fd >= 0); |
523 | ||
7c248223 | 524 | return RET_NERRNO(dup2(socket_fd, STDIN_FILENO)); |
4f2d528d | 525 | |
52c239d7 | 526 | case EXEC_INPUT_NAMED_FD: |
e75a9ed1 LP |
527 | assert(named_iofds[STDIN_FILENO] >= 0); |
528 | ||
52c239d7 | 529 | (void) fd_nonblock(named_iofds[STDIN_FILENO], false); |
7c248223 | 530 | return RET_NERRNO(dup2(named_iofds[STDIN_FILENO], STDIN_FILENO)); |
52c239d7 | 531 | |
08f3be7a LP |
532 | case EXEC_INPUT_DATA: { |
533 | int fd; | |
534 | ||
535 | fd = acquire_data_fd(context->stdin_data, context->stdin_data_size, 0); | |
536 | if (fd < 0) | |
537 | return fd; | |
538 | ||
539 | return move_fd(fd, STDIN_FILENO, false); | |
540 | } | |
541 | ||
2038c3f5 LP |
542 | case EXEC_INPUT_FILE: { |
543 | bool rw; | |
544 | int fd; | |
545 | ||
546 | assert(context->stdio_file[STDIN_FILENO]); | |
547 | ||
548 | rw = (context->std_output == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDOUT_FILENO])) || | |
549 | (context->std_error == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDERR_FILENO])); | |
550 | ||
551 | fd = acquire_path(context->stdio_file[STDIN_FILENO], rw ? O_RDWR : O_RDONLY, 0666 & ~context->umask); | |
552 | if (fd < 0) | |
553 | return fd; | |
554 | ||
555 | return move_fd(fd, STDIN_FILENO, false); | |
556 | } | |
557 | ||
80876c20 | 558 | default: |
04499a70 | 559 | assert_not_reached(); |
80876c20 LP |
560 | } |
561 | } | |
562 | ||
41fc585a LP |
563 | static bool can_inherit_stderr_from_stdout( |
564 | const ExecContext *context, | |
565 | ExecOutput o, | |
566 | ExecOutput e) { | |
567 | ||
568 | assert(context); | |
569 | ||
570 | /* Returns true, if given the specified STDERR and STDOUT output we can directly dup() the stdout fd to the | |
571 | * stderr fd */ | |
572 | ||
573 | if (e == EXEC_OUTPUT_INHERIT) | |
574 | return true; | |
575 | if (e != o) | |
576 | return false; | |
577 | ||
578 | if (e == EXEC_OUTPUT_NAMED_FD) | |
579 | return streq_ptr(context->stdio_fdname[STDOUT_FILENO], context->stdio_fdname[STDERR_FILENO]); | |
580 | ||
8d7dab1f | 581 | if (IN_SET(e, EXEC_OUTPUT_FILE, EXEC_OUTPUT_FILE_APPEND, EXEC_OUTPUT_FILE_TRUNCATE)) |
41fc585a LP |
582 | return streq_ptr(context->stdio_file[STDOUT_FILENO], context->stdio_file[STDERR_FILENO]); |
583 | ||
584 | return true; | |
585 | } | |
586 | ||
a34ceba6 | 587 | static int setup_output( |
34cf6c43 | 588 | const Unit *unit, |
a34ceba6 LP |
589 | const ExecContext *context, |
590 | const ExecParameters *params, | |
591 | int fileno, | |
592 | int socket_fd, | |
2caa38e9 | 593 | const int named_iofds[static 3], |
a34ceba6 | 594 | const char *ident, |
7bce046b LP |
595 | uid_t uid, |
596 | gid_t gid, | |
597 | dev_t *journal_stream_dev, | |
598 | ino_t *journal_stream_ino) { | |
a34ceba6 | 599 | |
4f2d528d LP |
600 | ExecOutput o; |
601 | ExecInput i; | |
47c1d80d | 602 | int r; |
4f2d528d | 603 | |
f2341e0a | 604 | assert(unit); |
80876c20 | 605 | assert(context); |
a34ceba6 | 606 | assert(params); |
80876c20 | 607 | assert(ident); |
7bce046b LP |
608 | assert(journal_stream_dev); |
609 | assert(journal_stream_ino); | |
80876c20 | 610 | |
a34ceba6 LP |
611 | if (fileno == STDOUT_FILENO && params->stdout_fd >= 0) { |
612 | ||
613 | if (dup2(params->stdout_fd, STDOUT_FILENO) < 0) | |
614 | return -errno; | |
615 | ||
616 | return STDOUT_FILENO; | |
617 | } | |
618 | ||
619 | if (fileno == STDERR_FILENO && params->stderr_fd >= 0) { | |
620 | if (dup2(params->stderr_fd, STDERR_FILENO) < 0) | |
621 | return -errno; | |
622 | ||
623 | return STDERR_FILENO; | |
624 | } | |
625 | ||
08f3be7a | 626 | i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN); |
03fd9c49 | 627 | o = fixup_output(context->std_output, socket_fd); |
4f2d528d | 628 | |
eb17e935 MS |
629 | if (fileno == STDERR_FILENO) { |
630 | ExecOutput e; | |
631 | e = fixup_output(context->std_error, socket_fd); | |
80876c20 | 632 | |
eb17e935 MS |
633 | /* This expects the input and output are already set up */ |
634 | ||
635 | /* Don't change the stderr file descriptor if we inherit all | |
636 | * the way and are not on a tty */ | |
637 | if (e == EXEC_OUTPUT_INHERIT && | |
638 | o == EXEC_OUTPUT_INHERIT && | |
639 | i == EXEC_INPUT_NULL && | |
640 | !is_terminal_input(context->std_input) && | |
7966a916 | 641 | getppid() != 1) |
eb17e935 MS |
642 | return fileno; |
643 | ||
644 | /* Duplicate from stdout if possible */ | |
41fc585a | 645 | if (can_inherit_stderr_from_stdout(context, o, e)) |
7c248223 | 646 | return RET_NERRNO(dup2(STDOUT_FILENO, fileno)); |
071830ff | 647 | |
eb17e935 | 648 | o = e; |
80876c20 | 649 | |
eb17e935 | 650 | } else if (o == EXEC_OUTPUT_INHERIT) { |
21d21ea4 LP |
651 | /* If input got downgraded, inherit the original value */ |
652 | if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input)) | |
1e22b5cd | 653 | return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno); |
21d21ea4 | 654 | |
08f3be7a LP |
655 | /* If the input is connected to anything that's not a /dev/null or a data fd, inherit that... */ |
656 | if (!IN_SET(i, EXEC_INPUT_NULL, EXEC_INPUT_DATA)) | |
7c248223 | 657 | return RET_NERRNO(dup2(STDIN_FILENO, fileno)); |
071830ff | 658 | |
acb591e4 LP |
659 | /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */ |
660 | if (getppid() != 1) | |
eb17e935 | 661 | return fileno; |
94f04347 | 662 | |
eb17e935 MS |
663 | /* We need to open /dev/null here anew, to get the right access mode. */ |
664 | return open_null_as(O_WRONLY, fileno); | |
071830ff | 665 | } |
94f04347 | 666 | |
eb17e935 | 667 | switch (o) { |
80876c20 LP |
668 | |
669 | case EXEC_OUTPUT_NULL: | |
eb17e935 | 670 | return open_null_as(O_WRONLY, fileno); |
80876c20 LP |
671 | |
672 | case EXEC_OUTPUT_TTY: | |
4f2d528d | 673 | if (is_terminal_input(i)) |
7c248223 | 674 | return RET_NERRNO(dup2(STDIN_FILENO, fileno)); |
80876c20 LP |
675 | |
676 | /* We don't reset the terminal if this is just about output */ | |
1e22b5cd | 677 | return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno); |
80876c20 | 678 | |
9a6bca7a | 679 | case EXEC_OUTPUT_KMSG: |
28dbc1e8 | 680 | case EXEC_OUTPUT_KMSG_AND_CONSOLE: |
706343f4 LP |
681 | case EXEC_OUTPUT_JOURNAL: |
682 | case EXEC_OUTPUT_JOURNAL_AND_CONSOLE: | |
af635cf3 | 683 | r = connect_logger_as(unit, context, params, o, ident, fileno, uid, gid); |
47c1d80d | 684 | if (r < 0) { |
7966a916 ZJS |
685 | log_unit_warning_errno(unit, r, "Failed to connect %s to the journal socket, ignoring: %m", |
686 | fileno == STDOUT_FILENO ? "stdout" : "stderr"); | |
eb17e935 | 687 | r = open_null_as(O_WRONLY, fileno); |
7bce046b LP |
688 | } else { |
689 | struct stat st; | |
690 | ||
691 | /* If we connected this fd to the journal via a stream, patch the device/inode into the passed | |
692 | * parameters, but only then. This is useful so that we can set $JOURNAL_STREAM that permits | |
ab2116b1 LP |
693 | * services to detect whether they are connected to the journal or not. |
694 | * | |
695 | * If both stdout and stderr are connected to a stream then let's make sure to store the data | |
696 | * about STDERR as that's usually the best way to do logging. */ | |
7bce046b | 697 | |
ab2116b1 LP |
698 | if (fstat(fileno, &st) >= 0 && |
699 | (*journal_stream_ino == 0 || fileno == STDERR_FILENO)) { | |
7bce046b LP |
700 | *journal_stream_dev = st.st_dev; |
701 | *journal_stream_ino = st.st_ino; | |
702 | } | |
47c1d80d MS |
703 | } |
704 | return r; | |
4f2d528d LP |
705 | |
706 | case EXEC_OUTPUT_SOCKET: | |
707 | assert(socket_fd >= 0); | |
e75a9ed1 | 708 | |
7c248223 | 709 | return RET_NERRNO(dup2(socket_fd, fileno)); |
94f04347 | 710 | |
52c239d7 | 711 | case EXEC_OUTPUT_NAMED_FD: |
e75a9ed1 LP |
712 | assert(named_iofds[fileno] >= 0); |
713 | ||
52c239d7 | 714 | (void) fd_nonblock(named_iofds[fileno], false); |
7c248223 | 715 | return RET_NERRNO(dup2(named_iofds[fileno], fileno)); |
52c239d7 | 716 | |
566b7d23 | 717 | case EXEC_OUTPUT_FILE: |
8d7dab1f LW |
718 | case EXEC_OUTPUT_FILE_APPEND: |
719 | case EXEC_OUTPUT_FILE_TRUNCATE: { | |
2038c3f5 | 720 | bool rw; |
566b7d23 | 721 | int fd, flags; |
2038c3f5 LP |
722 | |
723 | assert(context->stdio_file[fileno]); | |
724 | ||
725 | rw = context->std_input == EXEC_INPUT_FILE && | |
726 | streq_ptr(context->stdio_file[fileno], context->stdio_file[STDIN_FILENO]); | |
727 | ||
728 | if (rw) | |
7c248223 | 729 | return RET_NERRNO(dup2(STDIN_FILENO, fileno)); |
2038c3f5 | 730 | |
566b7d23 ZD |
731 | flags = O_WRONLY; |
732 | if (o == EXEC_OUTPUT_FILE_APPEND) | |
733 | flags |= O_APPEND; | |
8d7dab1f LW |
734 | else if (o == EXEC_OUTPUT_FILE_TRUNCATE) |
735 | flags |= O_TRUNC; | |
566b7d23 ZD |
736 | |
737 | fd = acquire_path(context->stdio_file[fileno], flags, 0666 & ~context->umask); | |
2038c3f5 LP |
738 | if (fd < 0) |
739 | return fd; | |
740 | ||
566b7d23 | 741 | return move_fd(fd, fileno, 0); |
2038c3f5 LP |
742 | } |
743 | ||
94f04347 | 744 | default: |
04499a70 | 745 | assert_not_reached(); |
94f04347 | 746 | } |
071830ff LP |
747 | } |
748 | ||
02a51aba | 749 | static int chown_terminal(int fd, uid_t uid) { |
4b3b5bc7 | 750 | int r; |
02a51aba LP |
751 | |
752 | assert(fd >= 0); | |
02a51aba | 753 | |
1ff74fb6 | 754 | /* Before we chown/chmod the TTY, let's ensure this is actually a tty */ |
4b3b5bc7 LP |
755 | if (isatty(fd) < 1) { |
756 | if (IN_SET(errno, EINVAL, ENOTTY)) | |
757 | return 0; /* not a tty */ | |
1ff74fb6 | 758 | |
02a51aba | 759 | return -errno; |
4b3b5bc7 | 760 | } |
02a51aba | 761 | |
4b3b5bc7 | 762 | /* This might fail. What matters are the results. */ |
f2df231f | 763 | r = fchmod_and_chown(fd, TTY_MODE, uid, GID_INVALID); |
4b3b5bc7 LP |
764 | if (r < 0) |
765 | return r; | |
02a51aba | 766 | |
4b3b5bc7 | 767 | return 1; |
02a51aba LP |
768 | } |
769 | ||
aedec452 | 770 | static int setup_confirm_stdio( |
51462135 | 771 | const ExecContext *context, |
aedec452 LP |
772 | const char *vc, |
773 | int *ret_saved_stdin, | |
774 | int *ret_saved_stdout) { | |
775 | ||
3d18b167 LP |
776 | _cleanup_close_ int fd = -1, saved_stdin = -1, saved_stdout = -1; |
777 | int r; | |
80876c20 | 778 | |
aedec452 LP |
779 | assert(ret_saved_stdin); |
780 | assert(ret_saved_stdout); | |
80876c20 | 781 | |
af6da548 LP |
782 | saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3); |
783 | if (saved_stdin < 0) | |
784 | return -errno; | |
80876c20 | 785 | |
af6da548 | 786 | saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3); |
3d18b167 LP |
787 | if (saved_stdout < 0) |
788 | return -errno; | |
80876c20 | 789 | |
8854d795 | 790 | fd = acquire_terminal(vc, ACQUIRE_TERMINAL_WAIT, DEFAULT_CONFIRM_USEC); |
3d18b167 LP |
791 | if (fd < 0) |
792 | return fd; | |
80876c20 | 793 | |
af6da548 LP |
794 | r = chown_terminal(fd, getuid()); |
795 | if (r < 0) | |
3d18b167 | 796 | return r; |
02a51aba | 797 | |
3d18b167 LP |
798 | r = reset_terminal_fd(fd, true); |
799 | if (r < 0) | |
800 | return r; | |
80876c20 | 801 | |
51462135 DDM |
802 | r = terminal_set_size_fd(fd, vc, context->tty_rows, context->tty_cols); |
803 | if (r < 0) | |
804 | return r; | |
805 | ||
aedec452 LP |
806 | r = rearrange_stdio(fd, fd, STDERR_FILENO); /* Invalidates 'fd' also on failure */ |
807 | TAKE_FD(fd); | |
2b33ab09 LP |
808 | if (r < 0) |
809 | return r; | |
80876c20 | 810 | |
aedec452 LP |
811 | *ret_saved_stdin = TAKE_FD(saved_stdin); |
812 | *ret_saved_stdout = TAKE_FD(saved_stdout); | |
3d18b167 | 813 | return 0; |
80876c20 LP |
814 | } |
815 | ||
63d77c92 | 816 | static void write_confirm_error_fd(int err, int fd, const Unit *u) { |
3b20f877 FB |
817 | assert(err < 0); |
818 | ||
819 | if (err == -ETIMEDOUT) | |
63d77c92 | 820 | dprintf(fd, "Confirmation question timed out for %s, assuming positive response.\n", u->id); |
3b20f877 FB |
821 | else { |
822 | errno = -err; | |
63d77c92 | 823 | dprintf(fd, "Couldn't ask confirmation for %s: %m, assuming positive response.\n", u->id); |
3b20f877 FB |
824 | } |
825 | } | |
826 | ||
63d77c92 | 827 | static void write_confirm_error(int err, const char *vc, const Unit *u) { |
03e334a1 | 828 | _cleanup_close_ int fd = -1; |
80876c20 | 829 | |
3b20f877 | 830 | assert(vc); |
80876c20 | 831 | |
7d5ceb64 | 832 | fd = open_terminal(vc, O_WRONLY|O_NOCTTY|O_CLOEXEC); |
af6da548 | 833 | if (fd < 0) |
3b20f877 | 834 | return; |
80876c20 | 835 | |
63d77c92 | 836 | write_confirm_error_fd(err, fd, u); |
af6da548 | 837 | } |
80876c20 | 838 | |
3d18b167 | 839 | static int restore_confirm_stdio(int *saved_stdin, int *saved_stdout) { |
af6da548 | 840 | int r = 0; |
80876c20 | 841 | |
af6da548 LP |
842 | assert(saved_stdin); |
843 | assert(saved_stdout); | |
844 | ||
845 | release_terminal(); | |
846 | ||
847 | if (*saved_stdin >= 0) | |
80876c20 | 848 | if (dup2(*saved_stdin, STDIN_FILENO) < 0) |
af6da548 | 849 | r = -errno; |
80876c20 | 850 | |
af6da548 | 851 | if (*saved_stdout >= 0) |
80876c20 | 852 | if (dup2(*saved_stdout, STDOUT_FILENO) < 0) |
af6da548 | 853 | r = -errno; |
80876c20 | 854 | |
3d18b167 LP |
855 | *saved_stdin = safe_close(*saved_stdin); |
856 | *saved_stdout = safe_close(*saved_stdout); | |
af6da548 LP |
857 | |
858 | return r; | |
859 | } | |
860 | ||
3b20f877 FB |
861 | enum { |
862 | CONFIRM_PRETEND_FAILURE = -1, | |
863 | CONFIRM_PRETEND_SUCCESS = 0, | |
864 | CONFIRM_EXECUTE = 1, | |
865 | }; | |
866 | ||
51462135 | 867 | static int ask_for_confirmation(const ExecContext *context, const char *vc, Unit *u, const char *cmdline) { |
af6da548 | 868 | int saved_stdout = -1, saved_stdin = -1, r; |
2bcd3c26 | 869 | _cleanup_free_ char *e = NULL; |
3b20f877 | 870 | char c; |
af6da548 | 871 | |
3b20f877 | 872 | /* For any internal errors, assume a positive response. */ |
51462135 | 873 | r = setup_confirm_stdio(context, vc, &saved_stdin, &saved_stdout); |
3b20f877 | 874 | if (r < 0) { |
63d77c92 | 875 | write_confirm_error(r, vc, u); |
3b20f877 FB |
876 | return CONFIRM_EXECUTE; |
877 | } | |
af6da548 | 878 | |
b0eb2944 FB |
879 | /* confirm_spawn might have been disabled while we were sleeping. */ |
880 | if (manager_is_confirm_spawn_disabled(u->manager)) { | |
881 | r = 1; | |
882 | goto restore_stdio; | |
883 | } | |
af6da548 | 884 | |
2bcd3c26 FB |
885 | e = ellipsize(cmdline, 60, 100); |
886 | if (!e) { | |
887 | log_oom(); | |
888 | r = CONFIRM_EXECUTE; | |
889 | goto restore_stdio; | |
890 | } | |
af6da548 | 891 | |
d172b175 | 892 | for (;;) { |
539622bd | 893 | r = ask_char(&c, "yfshiDjcn", "Execute %s? [y, f, s – h for help] ", e); |
d172b175 | 894 | if (r < 0) { |
63d77c92 | 895 | write_confirm_error_fd(r, STDOUT_FILENO, u); |
d172b175 FB |
896 | r = CONFIRM_EXECUTE; |
897 | goto restore_stdio; | |
898 | } | |
af6da548 | 899 | |
d172b175 | 900 | switch (c) { |
b0eb2944 FB |
901 | case 'c': |
902 | printf("Resuming normal execution.\n"); | |
903 | manager_disable_confirm_spawn(); | |
904 | r = 1; | |
905 | break; | |
dd6f9ac0 FB |
906 | case 'D': |
907 | unit_dump(u, stdout, " "); | |
908 | continue; /* ask again */ | |
d172b175 FB |
909 | case 'f': |
910 | printf("Failing execution.\n"); | |
911 | r = CONFIRM_PRETEND_FAILURE; | |
912 | break; | |
913 | case 'h': | |
b0eb2944 FB |
914 | printf(" c - continue, proceed without asking anymore\n" |
915 | " D - dump, show the state of the unit\n" | |
dd6f9ac0 | 916 | " f - fail, don't execute the command and pretend it failed\n" |
d172b175 | 917 | " h - help\n" |
eedf223a | 918 | " i - info, show a short summary of the unit\n" |
56fde33a | 919 | " j - jobs, show jobs that are in progress\n" |
d172b175 FB |
920 | " s - skip, don't execute the command and pretend it succeeded\n" |
921 | " y - yes, execute the command\n"); | |
dd6f9ac0 | 922 | continue; /* ask again */ |
eedf223a FB |
923 | case 'i': |
924 | printf(" Description: %s\n" | |
925 | " Unit: %s\n" | |
926 | " Command: %s\n", | |
927 | u->id, u->description, cmdline); | |
928 | continue; /* ask again */ | |
56fde33a FB |
929 | case 'j': |
930 | manager_dump_jobs(u->manager, stdout, " "); | |
931 | continue; /* ask again */ | |
539622bd FB |
932 | case 'n': |
933 | /* 'n' was removed in favor of 'f'. */ | |
934 | printf("Didn't understand 'n', did you mean 'f'?\n"); | |
935 | continue; /* ask again */ | |
d172b175 FB |
936 | case 's': |
937 | printf("Skipping execution.\n"); | |
938 | r = CONFIRM_PRETEND_SUCCESS; | |
939 | break; | |
940 | case 'y': | |
941 | r = CONFIRM_EXECUTE; | |
942 | break; | |
943 | default: | |
04499a70 | 944 | assert_not_reached(); |
d172b175 | 945 | } |
3b20f877 | 946 | break; |
3b20f877 | 947 | } |
af6da548 | 948 | |
3b20f877 | 949 | restore_stdio: |
af6da548 | 950 | restore_confirm_stdio(&saved_stdin, &saved_stdout); |
af6da548 | 951 | return r; |
80876c20 LP |
952 | } |
953 | ||
4d885bd3 DH |
954 | static int get_fixed_user(const ExecContext *c, const char **user, |
955 | uid_t *uid, gid_t *gid, | |
956 | const char **home, const char **shell) { | |
81a2b7ce | 957 | int r; |
4d885bd3 | 958 | const char *name; |
81a2b7ce | 959 | |
4d885bd3 | 960 | assert(c); |
81a2b7ce | 961 | |
23deef88 LP |
962 | if (!c->user) |
963 | return 0; | |
964 | ||
4d885bd3 DH |
965 | /* Note that we don't set $HOME or $SHELL if they are not particularly enlightening anyway |
966 | * (i.e. are "/" or "/bin/nologin"). */ | |
81a2b7ce | 967 | |
23deef88 | 968 | name = c->user; |
fafff8f1 | 969 | r = get_user_creds(&name, uid, gid, home, shell, USER_CREDS_CLEAN); |
4d885bd3 DH |
970 | if (r < 0) |
971 | return r; | |
81a2b7ce | 972 | |
4d885bd3 DH |
973 | *user = name; |
974 | return 0; | |
975 | } | |
976 | ||
977 | static int get_fixed_group(const ExecContext *c, const char **group, gid_t *gid) { | |
978 | int r; | |
979 | const char *name; | |
980 | ||
981 | assert(c); | |
982 | ||
983 | if (!c->group) | |
984 | return 0; | |
985 | ||
986 | name = c->group; | |
fafff8f1 | 987 | r = get_group_creds(&name, gid, 0); |
4d885bd3 DH |
988 | if (r < 0) |
989 | return r; | |
990 | ||
991 | *group = name; | |
992 | return 0; | |
993 | } | |
994 | ||
cdc5d5c5 DH |
995 | static int get_supplementary_groups(const ExecContext *c, const char *user, |
996 | const char *group, gid_t gid, | |
997 | gid_t **supplementary_gids, int *ngids) { | |
4d885bd3 DH |
998 | int r, k = 0; |
999 | int ngroups_max; | |
1000 | bool keep_groups = false; | |
1001 | gid_t *groups = NULL; | |
1002 | _cleanup_free_ gid_t *l_gids = NULL; | |
1003 | ||
1004 | assert(c); | |
1005 | ||
bbeea271 DH |
1006 | /* |
1007 | * If user is given, then lookup GID and supplementary groups list. | |
1008 | * We avoid NSS lookups for gid=0. Also we have to initialize groups | |
cdc5d5c5 DH |
1009 | * here and as early as possible so we keep the list of supplementary |
1010 | * groups of the caller. | |
bbeea271 DH |
1011 | */ |
1012 | if (user && gid_is_valid(gid) && gid != 0) { | |
1013 | /* First step, initialize groups from /etc/groups */ | |
1014 | if (initgroups(user, gid) < 0) | |
1015 | return -errno; | |
1016 | ||
1017 | keep_groups = true; | |
1018 | } | |
1019 | ||
ac6e8be6 | 1020 | if (strv_isempty(c->supplementary_groups)) |
4d885bd3 DH |
1021 | return 0; |
1022 | ||
366ddd25 DH |
1023 | /* |
1024 | * If SupplementaryGroups= was passed then NGROUPS_MAX has to | |
1025 | * be positive, otherwise fail. | |
1026 | */ | |
1027 | errno = 0; | |
1028 | ngroups_max = (int) sysconf(_SC_NGROUPS_MAX); | |
66855de7 LP |
1029 | if (ngroups_max <= 0) |
1030 | return errno_or_else(EOPNOTSUPP); | |
366ddd25 | 1031 | |
4d885bd3 DH |
1032 | l_gids = new(gid_t, ngroups_max); |
1033 | if (!l_gids) | |
1034 | return -ENOMEM; | |
81a2b7ce | 1035 | |
4d885bd3 DH |
1036 | if (keep_groups) { |
1037 | /* | |
1038 | * Lookup the list of groups that the user belongs to, we | |
1039 | * avoid NSS lookups here too for gid=0. | |
1040 | */ | |
1041 | k = ngroups_max; | |
1042 | if (getgrouplist(user, gid, l_gids, &k) < 0) | |
1043 | return -EINVAL; | |
1044 | } else | |
1045 | k = 0; | |
81a2b7ce | 1046 | |
4d885bd3 DH |
1047 | STRV_FOREACH(i, c->supplementary_groups) { |
1048 | const char *g; | |
81a2b7ce | 1049 | |
4d885bd3 DH |
1050 | if (k >= ngroups_max) |
1051 | return -E2BIG; | |
81a2b7ce | 1052 | |
4d885bd3 | 1053 | g = *i; |
fafff8f1 | 1054 | r = get_group_creds(&g, l_gids+k, 0); |
4d885bd3 DH |
1055 | if (r < 0) |
1056 | return r; | |
81a2b7ce | 1057 | |
4d885bd3 DH |
1058 | k++; |
1059 | } | |
81a2b7ce | 1060 | |
4d885bd3 DH |
1061 | /* |
1062 | * Sets ngids to zero to drop all supplementary groups, happens | |
1063 | * when we are under root and SupplementaryGroups= is empty. | |
1064 | */ | |
1065 | if (k == 0) { | |
1066 | *ngids = 0; | |
1067 | return 0; | |
1068 | } | |
81a2b7ce | 1069 | |
4d885bd3 DH |
1070 | /* Otherwise get the final list of supplementary groups */ |
1071 | groups = memdup(l_gids, sizeof(gid_t) * k); | |
1072 | if (!groups) | |
1073 | return -ENOMEM; | |
1074 | ||
1075 | *supplementary_gids = groups; | |
1076 | *ngids = k; | |
1077 | ||
1078 | groups = NULL; | |
1079 | ||
1080 | return 0; | |
1081 | } | |
1082 | ||
34cf6c43 | 1083 | static int enforce_groups(gid_t gid, const gid_t *supplementary_gids, int ngids) { |
4d885bd3 DH |
1084 | int r; |
1085 | ||
709dbeac YW |
1086 | /* Handle SupplementaryGroups= if it is not empty */ |
1087 | if (ngids > 0) { | |
4d885bd3 DH |
1088 | r = maybe_setgroups(ngids, supplementary_gids); |
1089 | if (r < 0) | |
97f0e76f | 1090 | return r; |
4d885bd3 | 1091 | } |
81a2b7ce | 1092 | |
4d885bd3 DH |
1093 | if (gid_is_valid(gid)) { |
1094 | /* Then set our gids */ | |
1095 | if (setresgid(gid, gid, gid) < 0) | |
1096 | return -errno; | |
81a2b7ce LP |
1097 | } |
1098 | ||
1099 | return 0; | |
1100 | } | |
1101 | ||
dbdc4098 TK |
1102 | static int set_securebits(int bits, int mask) { |
1103 | int current, applied; | |
1104 | current = prctl(PR_GET_SECUREBITS); | |
1105 | if (current < 0) | |
1106 | return -errno; | |
1107 | /* Clear all securebits defined in mask and set bits */ | |
1108 | applied = (current & ~mask) | bits; | |
1109 | if (current == applied) | |
1110 | return 0; | |
1111 | if (prctl(PR_SET_SECUREBITS, applied) < 0) | |
1112 | return -errno; | |
1113 | return 1; | |
1114 | } | |
1115 | ||
81a2b7ce | 1116 | static int enforce_user(const ExecContext *context, uid_t uid) { |
81a2b7ce | 1117 | assert(context); |
dbdc4098 | 1118 | int r; |
81a2b7ce | 1119 | |
4d885bd3 DH |
1120 | if (!uid_is_valid(uid)) |
1121 | return 0; | |
1122 | ||
479050b3 | 1123 | /* Sets (but doesn't look up) the uid and make sure we keep the |
dbdc4098 TK |
1124 | * capabilities while doing so. For setting secure bits the capability CAP_SETPCAP is |
1125 | * required, so we also need keep-caps in this case. | |
1126 | */ | |
81a2b7ce | 1127 | |
dbdc4098 | 1128 | if (context->capability_ambient_set != 0 || context->secure_bits != 0) { |
81a2b7ce LP |
1129 | |
1130 | /* First step: If we need to keep capabilities but | |
1131 | * drop privileges we need to make sure we keep our | |
cbb21cca | 1132 | * caps, while we drop privileges. */ |
693ced48 | 1133 | if (uid != 0) { |
dbdc4098 TK |
1134 | /* Add KEEP_CAPS to the securebits */ |
1135 | r = set_securebits(1<<SECURE_KEEP_CAPS, 0); | |
1136 | if (r < 0) | |
1137 | return r; | |
693ced48 | 1138 | } |
81a2b7ce LP |
1139 | } |
1140 | ||
479050b3 | 1141 | /* Second step: actually set the uids */ |
81a2b7ce LP |
1142 | if (setresuid(uid, uid, uid) < 0) |
1143 | return -errno; | |
1144 | ||
1145 | /* At this point we should have all necessary capabilities but | |
1146 | are otherwise a normal user. However, the caps might got | |
1147 | corrupted due to the setresuid() so we need clean them up | |
1148 | later. This is done outside of this call. */ | |
1149 | ||
1150 | return 0; | |
1151 | } | |
1152 | ||
349cc4a5 | 1153 | #if HAVE_PAM |
5b6319dc LP |
1154 | |
1155 | static int null_conv( | |
1156 | int num_msg, | |
1157 | const struct pam_message **msg, | |
1158 | struct pam_response **resp, | |
1159 | void *appdata_ptr) { | |
1160 | ||
1161 | /* We don't support conversations */ | |
1162 | ||
1163 | return PAM_CONV_ERR; | |
1164 | } | |
1165 | ||
cefc33ae LP |
1166 | #endif |
1167 | ||
5b6319dc LP |
1168 | static int setup_pam( |
1169 | const char *name, | |
1170 | const char *user, | |
940c5210 | 1171 | uid_t uid, |
2d6fce8d | 1172 | gid_t gid, |
5b6319dc | 1173 | const char *tty, |
421bb42d | 1174 | char ***env, /* updated on success */ |
5b8d1f6b | 1175 | const int fds[], size_t n_fds) { |
5b6319dc | 1176 | |
349cc4a5 | 1177 | #if HAVE_PAM |
cefc33ae | 1178 | |
5b6319dc LP |
1179 | static const struct pam_conv conv = { |
1180 | .conv = null_conv, | |
1181 | .appdata_ptr = NULL | |
1182 | }; | |
1183 | ||
2d7c6aa2 | 1184 | _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL; |
46e5bbab | 1185 | _cleanup_strv_free_ char **e = NULL; |
5b6319dc | 1186 | pam_handle_t *handle = NULL; |
d6e5f3ad | 1187 | sigset_t old_ss; |
7bb70b6e | 1188 | int pam_code = PAM_SUCCESS, r; |
5b6319dc LP |
1189 | bool close_session = false; |
1190 | pid_t pam_pid = 0, parent_pid; | |
970edce6 | 1191 | int flags = 0; |
5b6319dc LP |
1192 | |
1193 | assert(name); | |
1194 | assert(user); | |
2065ca69 | 1195 | assert(env); |
5b6319dc LP |
1196 | |
1197 | /* We set up PAM in the parent process, then fork. The child | |
35b8ca3a | 1198 | * will then stay around until killed via PR_GET_PDEATHSIG or |
5b6319dc LP |
1199 | * systemd via the cgroup logic. It will then remove the PAM |
1200 | * session again. The parent process will exec() the actual | |
1201 | * daemon. We do things this way to ensure that the main PID | |
1202 | * of the daemon is the one we initially fork()ed. */ | |
1203 | ||
7bb70b6e LP |
1204 | r = barrier_create(&barrier); |
1205 | if (r < 0) | |
2d7c6aa2 DH |
1206 | goto fail; |
1207 | ||
553d2243 | 1208 | if (log_get_max_level() < LOG_DEBUG) |
970edce6 ZJS |
1209 | flags |= PAM_SILENT; |
1210 | ||
f546241b ZJS |
1211 | pam_code = pam_start(name, user, &conv, &handle); |
1212 | if (pam_code != PAM_SUCCESS) { | |
5b6319dc LP |
1213 | handle = NULL; |
1214 | goto fail; | |
1215 | } | |
1216 | ||
3cd24c1a LP |
1217 | if (!tty) { |
1218 | _cleanup_free_ char *q = NULL; | |
1219 | ||
1220 | /* Hmm, so no TTY was explicitly passed, but an fd passed to us directly might be a TTY. Let's figure | |
1221 | * out if that's the case, and read the TTY off it. */ | |
1222 | ||
1223 | if (getttyname_malloc(STDIN_FILENO, &q) >= 0) | |
1224 | tty = strjoina("/dev/", q); | |
1225 | } | |
1226 | ||
f546241b ZJS |
1227 | if (tty) { |
1228 | pam_code = pam_set_item(handle, PAM_TTY, tty); | |
1229 | if (pam_code != PAM_SUCCESS) | |
5b6319dc | 1230 | goto fail; |
f546241b | 1231 | } |
5b6319dc | 1232 | |
84eada2f JW |
1233 | STRV_FOREACH(nv, *env) { |
1234 | pam_code = pam_putenv(handle, *nv); | |
2065ca69 JW |
1235 | if (pam_code != PAM_SUCCESS) |
1236 | goto fail; | |
1237 | } | |
1238 | ||
970edce6 | 1239 | pam_code = pam_acct_mgmt(handle, flags); |
f546241b | 1240 | if (pam_code != PAM_SUCCESS) |
5b6319dc LP |
1241 | goto fail; |
1242 | ||
3bb39ea9 DG |
1243 | pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | flags); |
1244 | if (pam_code != PAM_SUCCESS) | |
46d7c6af | 1245 | log_debug("pam_setcred() failed, ignoring: %s", pam_strerror(handle, pam_code)); |
3bb39ea9 | 1246 | |
970edce6 | 1247 | pam_code = pam_open_session(handle, flags); |
f546241b | 1248 | if (pam_code != PAM_SUCCESS) |
5b6319dc LP |
1249 | goto fail; |
1250 | ||
1251 | close_session = true; | |
1252 | ||
f546241b ZJS |
1253 | e = pam_getenvlist(handle); |
1254 | if (!e) { | |
5b6319dc LP |
1255 | pam_code = PAM_BUF_ERR; |
1256 | goto fail; | |
1257 | } | |
1258 | ||
cafc5ca1 | 1259 | /* Block SIGTERM, so that we know that it won't get lost in the child */ |
ce30c8dc | 1260 | |
72c0a2c2 | 1261 | assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM, -1) >= 0); |
5b6319dc | 1262 | |
df0ff127 | 1263 | parent_pid = getpid_cached(); |
5b6319dc | 1264 | |
4c253ed1 LP |
1265 | r = safe_fork("(sd-pam)", 0, &pam_pid); |
1266 | if (r < 0) | |
5b6319dc | 1267 | goto fail; |
4c253ed1 | 1268 | if (r == 0) { |
7bb70b6e | 1269 | int sig, ret = EXIT_PAM; |
5b6319dc | 1270 | |
cafc5ca1 | 1271 | /* The child's job is to reset the PAM session on termination */ |
2d7c6aa2 | 1272 | barrier_set_role(&barrier, BARRIER_CHILD); |
5b6319dc | 1273 | |
1da37e58 ZJS |
1274 | /* Make sure we don't keep open the passed fds in this child. We assume that otherwise only |
1275 | * those fds are open here that have been opened by PAM. */ | |
4c253ed1 | 1276 | (void) close_many(fds, n_fds); |
5b6319dc | 1277 | |
cafc5ca1 LP |
1278 | /* Drop privileges - we don't need any to pam_close_session and this will make |
1279 | * PR_SET_PDEATHSIG work in most cases. If this fails, ignore the error - but expect sd-pam | |
1280 | * threads to fail to exit normally */ | |
2d6fce8d | 1281 | |
97f0e76f LP |
1282 | r = maybe_setgroups(0, NULL); |
1283 | if (r < 0) | |
1284 | log_warning_errno(r, "Failed to setgroups() in sd-pam: %m"); | |
2d6fce8d LP |
1285 | if (setresgid(gid, gid, gid) < 0) |
1286 | log_warning_errno(errno, "Failed to setresgid() in sd-pam: %m"); | |
940c5210 | 1287 | if (setresuid(uid, uid, uid) < 0) |
2d6fce8d | 1288 | log_warning_errno(errno, "Failed to setresuid() in sd-pam: %m"); |
940c5210 | 1289 | |
9c274488 | 1290 | (void) ignore_signals(SIGPIPE); |
ce30c8dc | 1291 | |
cafc5ca1 LP |
1292 | /* Wait until our parent died. This will only work if the above setresuid() succeeds, |
1293 | * otherwise the kernel will not allow unprivileged parents kill their privileged children | |
1294 | * this way. We rely on the control groups kill logic to do the rest for us. */ | |
5b6319dc LP |
1295 | if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0) |
1296 | goto child_finish; | |
1297 | ||
cafc5ca1 LP |
1298 | /* Tell the parent that our setup is done. This is especially important regarding dropping |
1299 | * privileges. Otherwise, unit setup might race against our setresuid(2) call. | |
643f4706 | 1300 | * |
cafc5ca1 | 1301 | * If the parent aborted, we'll detect this below, hence ignore return failure here. */ |
643f4706 | 1302 | (void) barrier_place(&barrier); |
2d7c6aa2 | 1303 | |
643f4706 | 1304 | /* Check if our parent process might already have died? */ |
5b6319dc | 1305 | if (getppid() == parent_pid) { |
d6e5f3ad DM |
1306 | sigset_t ss; |
1307 | ||
1308 | assert_se(sigemptyset(&ss) >= 0); | |
1309 | assert_se(sigaddset(&ss, SIGTERM) >= 0); | |
1310 | ||
3dead8d9 LP |
1311 | for (;;) { |
1312 | if (sigwait(&ss, &sig) < 0) { | |
1313 | if (errno == EINTR) | |
1314 | continue; | |
1315 | ||
1316 | goto child_finish; | |
1317 | } | |
5b6319dc | 1318 | |
3dead8d9 LP |
1319 | assert(sig == SIGTERM); |
1320 | break; | |
1321 | } | |
5b6319dc LP |
1322 | } |
1323 | ||
3bb39ea9 DG |
1324 | pam_code = pam_setcred(handle, PAM_DELETE_CRED | flags); |
1325 | if (pam_code != PAM_SUCCESS) | |
1326 | goto child_finish; | |
1327 | ||
3dead8d9 | 1328 | /* If our parent died we'll end the session */ |
f546241b | 1329 | if (getppid() != parent_pid) { |
970edce6 | 1330 | pam_code = pam_close_session(handle, flags); |
f546241b | 1331 | if (pam_code != PAM_SUCCESS) |
5b6319dc | 1332 | goto child_finish; |
f546241b | 1333 | } |
5b6319dc | 1334 | |
7bb70b6e | 1335 | ret = 0; |
5b6319dc LP |
1336 | |
1337 | child_finish: | |
7feb2b57 LP |
1338 | /* NB: pam_end() when called in child processes should set PAM_DATA_SILENT to let the module |
1339 | * know about this. See pam_end(3) */ | |
1340 | (void) pam_end(handle, pam_code | flags | PAM_DATA_SILENT); | |
7bb70b6e | 1341 | _exit(ret); |
5b6319dc LP |
1342 | } |
1343 | ||
2d7c6aa2 DH |
1344 | barrier_set_role(&barrier, BARRIER_PARENT); |
1345 | ||
cafc5ca1 LP |
1346 | /* If the child was forked off successfully it will do all the cleanups, so forget about the handle |
1347 | * here. */ | |
5b6319dc LP |
1348 | handle = NULL; |
1349 | ||
3b8bddde | 1350 | /* Unblock SIGTERM again in the parent */ |
72c0a2c2 | 1351 | assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0); |
5b6319dc | 1352 | |
cafc5ca1 LP |
1353 | /* We close the log explicitly here, since the PAM modules might have opened it, but we don't want |
1354 | * this fd around. */ | |
5b6319dc LP |
1355 | closelog(); |
1356 | ||
cafc5ca1 LP |
1357 | /* Synchronously wait for the child to initialize. We don't care for errors as we cannot |
1358 | * recover. However, warn loudly if it happens. */ | |
2d7c6aa2 DH |
1359 | if (!barrier_place_and_sync(&barrier)) |
1360 | log_error("PAM initialization failed"); | |
1361 | ||
130d3d22 | 1362 | return strv_free_and_replace(*env, e); |
5b6319dc LP |
1363 | |
1364 | fail: | |
970edce6 ZJS |
1365 | if (pam_code != PAM_SUCCESS) { |
1366 | log_error("PAM failed: %s", pam_strerror(handle, pam_code)); | |
7bb70b6e LP |
1367 | r = -EPERM; /* PAM errors do not map to errno */ |
1368 | } else | |
1369 | log_error_errno(r, "PAM failed: %m"); | |
9ba35398 | 1370 | |
5b6319dc LP |
1371 | if (handle) { |
1372 | if (close_session) | |
970edce6 | 1373 | pam_code = pam_close_session(handle, flags); |
5b6319dc | 1374 | |
7feb2b57 | 1375 | (void) pam_end(handle, pam_code | flags); |
5b6319dc LP |
1376 | } |
1377 | ||
5b6319dc | 1378 | closelog(); |
7bb70b6e | 1379 | return r; |
cefc33ae LP |
1380 | #else |
1381 | return 0; | |
5b6319dc | 1382 | #endif |
cefc33ae | 1383 | } |
5b6319dc | 1384 | |
5d6b1584 LP |
1385 | static void rename_process_from_path(const char *path) { |
1386 | char process_name[11]; | |
1387 | const char *p; | |
1388 | size_t l; | |
1389 | ||
1390 | /* This resulting string must fit in 10 chars (i.e. the length | |
1391 | * of "/sbin/init") to look pretty in /bin/ps */ | |
1392 | ||
2b6bf07d | 1393 | p = basename(path); |
5d6b1584 LP |
1394 | if (isempty(p)) { |
1395 | rename_process("(...)"); | |
1396 | return; | |
1397 | } | |
1398 | ||
1399 | l = strlen(p); | |
1400 | if (l > 8) { | |
1401 | /* The end of the process name is usually more | |
1402 | * interesting, since the first bit might just be | |
1403 | * "systemd-" */ | |
1404 | p = p + l - 8; | |
1405 | l = 8; | |
1406 | } | |
1407 | ||
1408 | process_name[0] = '('; | |
1409 | memcpy(process_name+1, p, l); | |
1410 | process_name[1+l] = ')'; | |
1411 | process_name[1+l+1] = 0; | |
1412 | ||
1413 | rename_process(process_name); | |
1414 | } | |
1415 | ||
469830d1 LP |
1416 | static bool context_has_address_families(const ExecContext *c) { |
1417 | assert(c); | |
1418 | ||
6b000af4 | 1419 | return c->address_families_allow_list || |
469830d1 LP |
1420 | !set_isempty(c->address_families); |
1421 | } | |
1422 | ||
1423 | static bool context_has_syscall_filters(const ExecContext *c) { | |
1424 | assert(c); | |
1425 | ||
6b000af4 | 1426 | return c->syscall_allow_list || |
8cfa775f | 1427 | !hashmap_isempty(c->syscall_filter); |
469830d1 LP |
1428 | } |
1429 | ||
9df2cdd8 TM |
1430 | static bool context_has_syscall_logs(const ExecContext *c) { |
1431 | assert(c); | |
1432 | ||
1433 | return c->syscall_log_allow_list || | |
1434 | !hashmap_isempty(c->syscall_log); | |
1435 | } | |
1436 | ||
469830d1 LP |
1437 | static bool context_has_no_new_privileges(const ExecContext *c) { |
1438 | assert(c); | |
1439 | ||
1440 | if (c->no_new_privileges) | |
1441 | return true; | |
1442 | ||
1443 | if (have_effective_cap(CAP_SYS_ADMIN)) /* if we are privileged, we don't need NNP */ | |
1444 | return false; | |
1445 | ||
1446 | /* We need NNP if we have any form of seccomp and are unprivileged */ | |
0538d2a8 | 1447 | return c->lock_personality || |
469830d1 | 1448 | c->memory_deny_write_execute || |
0538d2a8 | 1449 | c->private_devices || |
fc64760d | 1450 | c->protect_clock || |
0538d2a8 | 1451 | c->protect_hostname || |
469830d1 LP |
1452 | c->protect_kernel_tunables || |
1453 | c->protect_kernel_modules || | |
84703040 | 1454 | c->protect_kernel_logs || |
0538d2a8 YW |
1455 | context_has_address_families(c) || |
1456 | exec_context_restrict_namespaces_set(c) || | |
1457 | c->restrict_realtime || | |
1458 | c->restrict_suid_sgid || | |
78e864e5 | 1459 | !set_isempty(c->syscall_archs) || |
0538d2a8 YW |
1460 | context_has_syscall_filters(c) || |
1461 | context_has_syscall_logs(c); | |
469830d1 LP |
1462 | } |
1463 | ||
bb0c0d6f LP |
1464 | static bool exec_context_has_credentials(const ExecContext *context) { |
1465 | ||
1466 | assert(context); | |
1467 | ||
1468 | return !hashmap_isempty(context->set_credentials) || | |
43144be4 | 1469 | !hashmap_isempty(context->load_credentials); |
bb0c0d6f LP |
1470 | } |
1471 | ||
349cc4a5 | 1472 | #if HAVE_SECCOMP |
17df7223 | 1473 | |
83f12b27 | 1474 | static bool skip_seccomp_unavailable(const Unit* u, const char* msg) { |
f673b62d LP |
1475 | |
1476 | if (is_seccomp_available()) | |
1477 | return false; | |
1478 | ||
f673b62d | 1479 | log_unit_debug(u, "SECCOMP features not detected in the kernel, skipping %s", msg); |
f673b62d | 1480 | return true; |
83f12b27 FS |
1481 | } |
1482 | ||
165a31c0 | 1483 | static int apply_syscall_filter(const Unit* u, const ExecContext *c, bool needs_ambient_hack) { |
469830d1 | 1484 | uint32_t negative_action, default_action, action; |
165a31c0 | 1485 | int r; |
8351ceae | 1486 | |
469830d1 | 1487 | assert(u); |
c0467cf3 | 1488 | assert(c); |
8351ceae | 1489 | |
469830d1 | 1490 | if (!context_has_syscall_filters(c)) |
83f12b27 FS |
1491 | return 0; |
1492 | ||
469830d1 LP |
1493 | if (skip_seccomp_unavailable(u, "SystemCallFilter=")) |
1494 | return 0; | |
e9642be2 | 1495 | |
005bfaf1 | 1496 | negative_action = c->syscall_errno == SECCOMP_ERROR_NUMBER_KILL ? scmp_act_kill_process() : SCMP_ACT_ERRNO(c->syscall_errno); |
e9642be2 | 1497 | |
6b000af4 | 1498 | if (c->syscall_allow_list) { |
469830d1 LP |
1499 | default_action = negative_action; |
1500 | action = SCMP_ACT_ALLOW; | |
7c66bae2 | 1501 | } else { |
469830d1 LP |
1502 | default_action = SCMP_ACT_ALLOW; |
1503 | action = negative_action; | |
57183d11 | 1504 | } |
8351ceae | 1505 | |
165a31c0 | 1506 | if (needs_ambient_hack) { |
6b000af4 | 1507 | r = seccomp_filter_set_add(c->syscall_filter, c->syscall_allow_list, syscall_filter_sets + SYSCALL_FILTER_SET_SETUID); |
165a31c0 LP |
1508 | if (r < 0) |
1509 | return r; | |
1510 | } | |
1511 | ||
b54f36c6 | 1512 | return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_filter, action, false); |
4298d0b5 LP |
1513 | } |
1514 | ||
9df2cdd8 TM |
1515 | static int apply_syscall_log(const Unit* u, const ExecContext *c) { |
1516 | #ifdef SCMP_ACT_LOG | |
1517 | uint32_t default_action, action; | |
1518 | #endif | |
1519 | ||
1520 | assert(u); | |
1521 | assert(c); | |
1522 | ||
1523 | if (!context_has_syscall_logs(c)) | |
1524 | return 0; | |
1525 | ||
1526 | #ifdef SCMP_ACT_LOG | |
1527 | if (skip_seccomp_unavailable(u, "SystemCallLog=")) | |
1528 | return 0; | |
1529 | ||
1530 | if (c->syscall_log_allow_list) { | |
1531 | /* Log nothing but the ones listed */ | |
1532 | default_action = SCMP_ACT_ALLOW; | |
1533 | action = SCMP_ACT_LOG; | |
1534 | } else { | |
1535 | /* Log everything but the ones listed */ | |
1536 | default_action = SCMP_ACT_LOG; | |
1537 | action = SCMP_ACT_ALLOW; | |
1538 | } | |
1539 | ||
1540 | return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_log, action, false); | |
1541 | #else | |
1542 | /* old libseccomp */ | |
1543 | log_unit_debug(u, "SECCOMP feature SCMP_ACT_LOG not available, skipping SystemCallLog="); | |
1544 | return 0; | |
1545 | #endif | |
1546 | } | |
1547 | ||
469830d1 LP |
1548 | static int apply_syscall_archs(const Unit *u, const ExecContext *c) { |
1549 | assert(u); | |
4298d0b5 LP |
1550 | assert(c); |
1551 | ||
469830d1 | 1552 | if (set_isempty(c->syscall_archs)) |
83f12b27 FS |
1553 | return 0; |
1554 | ||
469830d1 LP |
1555 | if (skip_seccomp_unavailable(u, "SystemCallArchitectures=")) |
1556 | return 0; | |
4298d0b5 | 1557 | |
469830d1 LP |
1558 | return seccomp_restrict_archs(c->syscall_archs); |
1559 | } | |
4298d0b5 | 1560 | |
469830d1 LP |
1561 | static int apply_address_families(const Unit* u, const ExecContext *c) { |
1562 | assert(u); | |
1563 | assert(c); | |
4298d0b5 | 1564 | |
469830d1 LP |
1565 | if (!context_has_address_families(c)) |
1566 | return 0; | |
4298d0b5 | 1567 | |
469830d1 LP |
1568 | if (skip_seccomp_unavailable(u, "RestrictAddressFamilies=")) |
1569 | return 0; | |
4298d0b5 | 1570 | |
6b000af4 | 1571 | return seccomp_restrict_address_families(c->address_families, c->address_families_allow_list); |
8351ceae | 1572 | } |
4298d0b5 | 1573 | |
83f12b27 | 1574 | static int apply_memory_deny_write_execute(const Unit* u, const ExecContext *c) { |
469830d1 | 1575 | assert(u); |
f3e43635 TM |
1576 | assert(c); |
1577 | ||
469830d1 | 1578 | if (!c->memory_deny_write_execute) |
83f12b27 FS |
1579 | return 0; |
1580 | ||
469830d1 LP |
1581 | if (skip_seccomp_unavailable(u, "MemoryDenyWriteExecute=")) |
1582 | return 0; | |
f3e43635 | 1583 | |
469830d1 | 1584 | return seccomp_memory_deny_write_execute(); |
f3e43635 TM |
1585 | } |
1586 | ||
83f12b27 | 1587 | static int apply_restrict_realtime(const Unit* u, const ExecContext *c) { |
469830d1 | 1588 | assert(u); |
f4170c67 LP |
1589 | assert(c); |
1590 | ||
469830d1 | 1591 | if (!c->restrict_realtime) |
83f12b27 FS |
1592 | return 0; |
1593 | ||
469830d1 LP |
1594 | if (skip_seccomp_unavailable(u, "RestrictRealtime=")) |
1595 | return 0; | |
f4170c67 | 1596 | |
469830d1 | 1597 | return seccomp_restrict_realtime(); |
f4170c67 LP |
1598 | } |
1599 | ||
f69567cb LP |
1600 | static int apply_restrict_suid_sgid(const Unit* u, const ExecContext *c) { |
1601 | assert(u); | |
1602 | assert(c); | |
1603 | ||
1604 | if (!c->restrict_suid_sgid) | |
1605 | return 0; | |
1606 | ||
1607 | if (skip_seccomp_unavailable(u, "RestrictSUIDSGID=")) | |
1608 | return 0; | |
1609 | ||
1610 | return seccomp_restrict_suid_sgid(); | |
1611 | } | |
1612 | ||
59e856c7 | 1613 | static int apply_protect_sysctl(const Unit *u, const ExecContext *c) { |
469830d1 | 1614 | assert(u); |
59eeb84b LP |
1615 | assert(c); |
1616 | ||
1617 | /* Turn off the legacy sysctl() system call. Many distributions turn this off while building the kernel, but | |
1618 | * let's protect even those systems where this is left on in the kernel. */ | |
1619 | ||
469830d1 | 1620 | if (!c->protect_kernel_tunables) |
59eeb84b LP |
1621 | return 0; |
1622 | ||
469830d1 LP |
1623 | if (skip_seccomp_unavailable(u, "ProtectKernelTunables=")) |
1624 | return 0; | |
59eeb84b | 1625 | |
469830d1 | 1626 | return seccomp_protect_sysctl(); |
59eeb84b LP |
1627 | } |
1628 | ||
59e856c7 | 1629 | static int apply_protect_kernel_modules(const Unit *u, const ExecContext *c) { |
469830d1 | 1630 | assert(u); |
502d704e DH |
1631 | assert(c); |
1632 | ||
25a8d8a0 | 1633 | /* Turn off module syscalls on ProtectKernelModules=yes */ |
502d704e | 1634 | |
469830d1 LP |
1635 | if (!c->protect_kernel_modules) |
1636 | return 0; | |
1637 | ||
502d704e DH |
1638 | if (skip_seccomp_unavailable(u, "ProtectKernelModules=")) |
1639 | return 0; | |
1640 | ||
b54f36c6 | 1641 | return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_MODULE, SCMP_ACT_ERRNO(EPERM), false); |
502d704e DH |
1642 | } |
1643 | ||
84703040 KK |
1644 | static int apply_protect_kernel_logs(const Unit *u, const ExecContext *c) { |
1645 | assert(u); | |
1646 | assert(c); | |
1647 | ||
1648 | if (!c->protect_kernel_logs) | |
1649 | return 0; | |
1650 | ||
1651 | if (skip_seccomp_unavailable(u, "ProtectKernelLogs=")) | |
1652 | return 0; | |
1653 | ||
1654 | return seccomp_protect_syslog(); | |
1655 | } | |
1656 | ||
daf8f72b | 1657 | static int apply_protect_clock(const Unit *u, const ExecContext *c) { |
fc64760d KK |
1658 | assert(u); |
1659 | assert(c); | |
1660 | ||
1661 | if (!c->protect_clock) | |
1662 | return 0; | |
1663 | ||
1664 | if (skip_seccomp_unavailable(u, "ProtectClock=")) | |
1665 | return 0; | |
1666 | ||
1667 | return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_CLOCK, SCMP_ACT_ERRNO(EPERM), false); | |
1668 | } | |
1669 | ||
59e856c7 | 1670 | static int apply_private_devices(const Unit *u, const ExecContext *c) { |
469830d1 | 1671 | assert(u); |
ba128bb8 LP |
1672 | assert(c); |
1673 | ||
8f81a5f6 | 1674 | /* If PrivateDevices= is set, also turn off iopl and all @raw-io syscalls. */ |
ba128bb8 | 1675 | |
469830d1 LP |
1676 | if (!c->private_devices) |
1677 | return 0; | |
1678 | ||
ba128bb8 LP |
1679 | if (skip_seccomp_unavailable(u, "PrivateDevices=")) |
1680 | return 0; | |
1681 | ||
b54f36c6 | 1682 | return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_RAW_IO, SCMP_ACT_ERRNO(EPERM), false); |
ba128bb8 LP |
1683 | } |
1684 | ||
34cf6c43 | 1685 | static int apply_restrict_namespaces(const Unit *u, const ExecContext *c) { |
469830d1 | 1686 | assert(u); |
add00535 LP |
1687 | assert(c); |
1688 | ||
1689 | if (!exec_context_restrict_namespaces_set(c)) | |
1690 | return 0; | |
1691 | ||
1692 | if (skip_seccomp_unavailable(u, "RestrictNamespaces=")) | |
1693 | return 0; | |
1694 | ||
1695 | return seccomp_restrict_namespaces(c->restrict_namespaces); | |
1696 | } | |
1697 | ||
78e864e5 | 1698 | static int apply_lock_personality(const Unit* u, const ExecContext *c) { |
e8132d63 LP |
1699 | unsigned long personality; |
1700 | int r; | |
78e864e5 TM |
1701 | |
1702 | assert(u); | |
1703 | assert(c); | |
1704 | ||
1705 | if (!c->lock_personality) | |
1706 | return 0; | |
1707 | ||
1708 | if (skip_seccomp_unavailable(u, "LockPersonality=")) | |
1709 | return 0; | |
1710 | ||
e8132d63 LP |
1711 | personality = c->personality; |
1712 | ||
1713 | /* If personality is not specified, use either PER_LINUX or PER_LINUX32 depending on what is currently set. */ | |
1714 | if (personality == PERSONALITY_INVALID) { | |
1715 | ||
1716 | r = opinionated_personality(&personality); | |
1717 | if (r < 0) | |
1718 | return r; | |
1719 | } | |
78e864e5 TM |
1720 | |
1721 | return seccomp_lock_personality(personality); | |
1722 | } | |
1723 | ||
c0467cf3 | 1724 | #endif |
8351ceae | 1725 | |
7a8288f6 | 1726 | #if HAVE_LIBBPF |
7a8288f6 DM |
1727 | static int apply_restrict_filesystems(Unit *u, const ExecContext *c) { |
1728 | assert(u); | |
1729 | assert(c); | |
1730 | ||
1731 | if (!exec_context_restrict_filesystems_set(c)) | |
1732 | return 0; | |
1733 | ||
46004616 ZJS |
1734 | if (!u->manager->restrict_fs) { |
1735 | /* LSM BPF is unsupported or lsm_bpf_setup failed */ | |
1736 | log_unit_debug(u, "LSM BPF not supported, skipping RestrictFileSystems="); | |
7a8288f6 | 1737 | return 0; |
46004616 | 1738 | } |
7a8288f6 DM |
1739 | |
1740 | return lsm_bpf_unit_restrict_filesystems(u, c->restrict_filesystems, c->restrict_filesystems_allow_list); | |
1741 | } | |
1742 | #endif | |
1743 | ||
daf8f72b | 1744 | static int apply_protect_hostname(const Unit *u, const ExecContext *c, int *ret_exit_status) { |
daf8f72b LP |
1745 | assert(u); |
1746 | assert(c); | |
1747 | ||
1748 | if (!c->protect_hostname) | |
1749 | return 0; | |
1750 | ||
1751 | if (ns_type_supported(NAMESPACE_UTS)) { | |
1752 | if (unshare(CLONE_NEWUTS) < 0) { | |
1753 | if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno)) { | |
1754 | *ret_exit_status = EXIT_NAMESPACE; | |
1755 | return log_unit_error_errno(u, errno, "Failed to set up UTS namespacing: %m"); | |
1756 | } | |
1757 | ||
1758 | log_unit_warning(u, "ProtectHostname=yes is configured, but UTS namespace setup is prohibited (container manager?), ignoring namespace setup."); | |
1759 | } | |
1760 | } else | |
1761 | log_unit_warning(u, "ProtectHostname=yes is configured, but the kernel does not support UTS namespaces, ignoring namespace setup."); | |
1762 | ||
1763 | #if HAVE_SECCOMP | |
8f3e342f ZJS |
1764 | int r; |
1765 | ||
daf8f72b LP |
1766 | if (skip_seccomp_unavailable(u, "ProtectHostname=")) |
1767 | return 0; | |
1768 | ||
1769 | r = seccomp_protect_hostname(); | |
1770 | if (r < 0) { | |
1771 | *ret_exit_status = EXIT_SECCOMP; | |
1772 | return log_unit_error_errno(u, r, "Failed to apply hostname restrictions: %m"); | |
1773 | } | |
1774 | #endif | |
1775 | ||
1776 | return 0; | |
1777 | } | |
1778 | ||
3042bbeb | 1779 | static void do_idle_pipe_dance(int idle_pipe[static 4]) { |
31a7eb86 ZJS |
1780 | assert(idle_pipe); |
1781 | ||
54eb2300 LP |
1782 | idle_pipe[1] = safe_close(idle_pipe[1]); |
1783 | idle_pipe[2] = safe_close(idle_pipe[2]); | |
31a7eb86 ZJS |
1784 | |
1785 | if (idle_pipe[0] >= 0) { | |
1786 | int r; | |
1787 | ||
1788 | r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC); | |
1789 | ||
1790 | if (idle_pipe[3] >= 0 && r == 0 /* timeout */) { | |
c7cc737f LP |
1791 | ssize_t n; |
1792 | ||
31a7eb86 | 1793 | /* Signal systemd that we are bored and want to continue. */ |
c7cc737f LP |
1794 | n = write(idle_pipe[3], "x", 1); |
1795 | if (n > 0) | |
cd972d69 | 1796 | /* Wait for systemd to react to the signal above. */ |
54756dce | 1797 | (void) fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC); |
31a7eb86 ZJS |
1798 | } |
1799 | ||
54eb2300 | 1800 | idle_pipe[0] = safe_close(idle_pipe[0]); |
31a7eb86 ZJS |
1801 | |
1802 | } | |
1803 | ||
54eb2300 | 1804 | idle_pipe[3] = safe_close(idle_pipe[3]); |
31a7eb86 ZJS |
1805 | } |
1806 | ||
fb2042dd YW |
1807 | static const char *exec_directory_env_name_to_string(ExecDirectoryType t); |
1808 | ||
7cae38c4 | 1809 | static int build_environment( |
34cf6c43 | 1810 | const Unit *u, |
9fa95f85 | 1811 | const ExecContext *c, |
1e22b5cd | 1812 | const ExecParameters *p, |
da6053d0 | 1813 | size_t n_fds, |
7cae38c4 LP |
1814 | const char *home, |
1815 | const char *username, | |
1816 | const char *shell, | |
7bce046b LP |
1817 | dev_t journal_stream_dev, |
1818 | ino_t journal_stream_ino, | |
7cae38c4 LP |
1819 | char ***ret) { |
1820 | ||
1821 | _cleanup_strv_free_ char **our_env = NULL; | |
da6053d0 | 1822 | size_t n_env = 0; |
7cae38c4 LP |
1823 | char *x; |
1824 | ||
4b58153d | 1825 | assert(u); |
7cae38c4 | 1826 | assert(c); |
7c1cb6f1 | 1827 | assert(p); |
7cae38c4 LP |
1828 | assert(ret); |
1829 | ||
dc4e2940 | 1830 | #define N_ENV_VARS 17 |
8d5bb13d | 1831 | our_env = new0(char*, N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX); |
7cae38c4 LP |
1832 | if (!our_env) |
1833 | return -ENOMEM; | |
1834 | ||
1835 | if (n_fds > 0) { | |
8dd4c05b LP |
1836 | _cleanup_free_ char *joined = NULL; |
1837 | ||
df0ff127 | 1838 | if (asprintf(&x, "LISTEN_PID="PID_FMT, getpid_cached()) < 0) |
7cae38c4 LP |
1839 | return -ENOMEM; |
1840 | our_env[n_env++] = x; | |
1841 | ||
da6053d0 | 1842 | if (asprintf(&x, "LISTEN_FDS=%zu", n_fds) < 0) |
7cae38c4 LP |
1843 | return -ENOMEM; |
1844 | our_env[n_env++] = x; | |
8dd4c05b | 1845 | |
1e22b5cd | 1846 | joined = strv_join(p->fd_names, ":"); |
8dd4c05b LP |
1847 | if (!joined) |
1848 | return -ENOMEM; | |
1849 | ||
605405c6 | 1850 | x = strjoin("LISTEN_FDNAMES=", joined); |
8dd4c05b LP |
1851 | if (!x) |
1852 | return -ENOMEM; | |
1853 | our_env[n_env++] = x; | |
7cae38c4 LP |
1854 | } |
1855 | ||
b08af3b1 | 1856 | if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) { |
df0ff127 | 1857 | if (asprintf(&x, "WATCHDOG_PID="PID_FMT, getpid_cached()) < 0) |
09812eb7 LP |
1858 | return -ENOMEM; |
1859 | our_env[n_env++] = x; | |
1860 | ||
1e22b5cd | 1861 | if (asprintf(&x, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec) < 0) |
09812eb7 LP |
1862 | return -ENOMEM; |
1863 | our_env[n_env++] = x; | |
1864 | } | |
1865 | ||
de90700f LP |
1866 | /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use blocking |
1867 | * Varlink calls back to us for look up dynamic users in PID 1. Break the deadlock between D-Bus and | |
1868 | * PID 1 by disabling use of PID1' NSS interface for looking up dynamic users. */ | |
1869 | if (p->flags & EXEC_NSS_DYNAMIC_BYPASS) { | |
1870 | x = strdup("SYSTEMD_NSS_DYNAMIC_BYPASS=1"); | |
fd63e712 LP |
1871 | if (!x) |
1872 | return -ENOMEM; | |
1873 | our_env[n_env++] = x; | |
1874 | } | |
1875 | ||
7cae38c4 | 1876 | if (home) { |
b910cc72 | 1877 | x = strjoin("HOME=", home); |
7cae38c4 LP |
1878 | if (!x) |
1879 | return -ENOMEM; | |
7bbead1d | 1880 | |
4ff361cc | 1881 | path_simplify(x + 5); |
7cae38c4 LP |
1882 | our_env[n_env++] = x; |
1883 | } | |
1884 | ||
1885 | if (username) { | |
b910cc72 | 1886 | x = strjoin("LOGNAME=", username); |
7cae38c4 LP |
1887 | if (!x) |
1888 | return -ENOMEM; | |
1889 | our_env[n_env++] = x; | |
1890 | ||
b910cc72 | 1891 | x = strjoin("USER=", username); |
7cae38c4 LP |
1892 | if (!x) |
1893 | return -ENOMEM; | |
1894 | our_env[n_env++] = x; | |
1895 | } | |
1896 | ||
1897 | if (shell) { | |
b910cc72 | 1898 | x = strjoin("SHELL=", shell); |
7cae38c4 LP |
1899 | if (!x) |
1900 | return -ENOMEM; | |
7bbead1d | 1901 | |
4ff361cc | 1902 | path_simplify(x + 6); |
7cae38c4 LP |
1903 | our_env[n_env++] = x; |
1904 | } | |
1905 | ||
4b58153d LP |
1906 | if (!sd_id128_is_null(u->invocation_id)) { |
1907 | if (asprintf(&x, "INVOCATION_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(u->invocation_id)) < 0) | |
1908 | return -ENOMEM; | |
1909 | ||
1910 | our_env[n_env++] = x; | |
1911 | } | |
1912 | ||
6af760f3 LP |
1913 | if (exec_context_needs_term(c)) { |
1914 | const char *tty_path, *term = NULL; | |
1915 | ||
1916 | tty_path = exec_context_tty_path(c); | |
1917 | ||
e8cf09b2 LP |
1918 | /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try |
1919 | * to inherit the $TERM set for PID 1. This is useful for containers so that the $TERM the | |
1920 | * container manager passes to PID 1 ends up all the way in the console login shown. */ | |
6af760f3 | 1921 | |
e8cf09b2 | 1922 | if (path_equal_ptr(tty_path, "/dev/console") && getppid() == 1) |
6af760f3 | 1923 | term = getenv("TERM"); |
e8cf09b2 | 1924 | |
6af760f3 LP |
1925 | if (!term) |
1926 | term = default_term_for_tty(tty_path); | |
7cae38c4 | 1927 | |
b910cc72 | 1928 | x = strjoin("TERM=", term); |
7cae38c4 LP |
1929 | if (!x) |
1930 | return -ENOMEM; | |
1931 | our_env[n_env++] = x; | |
1932 | } | |
1933 | ||
7bce046b LP |
1934 | if (journal_stream_dev != 0 && journal_stream_ino != 0) { |
1935 | if (asprintf(&x, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino) < 0) | |
1936 | return -ENOMEM; | |
1937 | ||
1938 | our_env[n_env++] = x; | |
1939 | } | |
1940 | ||
91dd5f7c LP |
1941 | if (c->log_namespace) { |
1942 | x = strjoin("LOG_NAMESPACE=", c->log_namespace); | |
1943 | if (!x) | |
1944 | return -ENOMEM; | |
1945 | ||
1946 | our_env[n_env++] = x; | |
1947 | } | |
1948 | ||
5b10116e | 1949 | for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) { |
211a3d87 | 1950 | _cleanup_free_ char *joined = NULL; |
fb2042dd YW |
1951 | const char *n; |
1952 | ||
1953 | if (!p->prefix[t]) | |
1954 | continue; | |
1955 | ||
211a3d87 | 1956 | if (c->directories[t].n_items == 0) |
fb2042dd YW |
1957 | continue; |
1958 | ||
1959 | n = exec_directory_env_name_to_string(t); | |
1960 | if (!n) | |
1961 | continue; | |
1962 | ||
211a3d87 LB |
1963 | for (size_t i = 0; i < c->directories[t].n_items; i++) { |
1964 | _cleanup_free_ char *prefixed = NULL; | |
fb2042dd | 1965 | |
211a3d87 LB |
1966 | prefixed = path_join(p->prefix[t], c->directories[t].items[i].path); |
1967 | if (!prefixed) | |
1968 | return -ENOMEM; | |
1969 | ||
1970 | if (!strextend_with_separator(&joined, ":", prefixed)) | |
1971 | return -ENOMEM; | |
1972 | } | |
fb2042dd YW |
1973 | |
1974 | x = strjoin(n, "=", joined); | |
1975 | if (!x) | |
1976 | return -ENOMEM; | |
1977 | ||
1978 | our_env[n_env++] = x; | |
1979 | } | |
1980 | ||
bb0c0d6f LP |
1981 | if (exec_context_has_credentials(c) && p->prefix[EXEC_DIRECTORY_RUNTIME]) { |
1982 | x = strjoin("CREDENTIALS_DIRECTORY=", p->prefix[EXEC_DIRECTORY_RUNTIME], "/credentials/", u->id); | |
1983 | if (!x) | |
1984 | return -ENOMEM; | |
1985 | ||
1986 | our_env[n_env++] = x; | |
1987 | } | |
1988 | ||
dc4e2940 YW |
1989 | if (asprintf(&x, "SYSTEMD_EXEC_PID=" PID_FMT, getpid_cached()) < 0) |
1990 | return -ENOMEM; | |
1991 | ||
1992 | our_env[n_env++] = x; | |
1993 | ||
7cae38c4 | 1994 | our_env[n_env++] = NULL; |
8d5bb13d LP |
1995 | assert(n_env <= N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX); |
1996 | #undef N_ENV_VARS | |
7cae38c4 | 1997 | |
ae2a15bc | 1998 | *ret = TAKE_PTR(our_env); |
7cae38c4 LP |
1999 | |
2000 | return 0; | |
2001 | } | |
2002 | ||
b4c14404 FB |
2003 | static int build_pass_environment(const ExecContext *c, char ***ret) { |
2004 | _cleanup_strv_free_ char **pass_env = NULL; | |
319a4f4b | 2005 | size_t n_env = 0; |
b4c14404 FB |
2006 | |
2007 | STRV_FOREACH(i, c->pass_environment) { | |
2008 | _cleanup_free_ char *x = NULL; | |
2009 | char *v; | |
2010 | ||
2011 | v = getenv(*i); | |
2012 | if (!v) | |
2013 | continue; | |
605405c6 | 2014 | x = strjoin(*i, "=", v); |
b4c14404 FB |
2015 | if (!x) |
2016 | return -ENOMEM; | |
00819cc1 | 2017 | |
319a4f4b | 2018 | if (!GREEDY_REALLOC(pass_env, n_env + 2)) |
b4c14404 | 2019 | return -ENOMEM; |
00819cc1 | 2020 | |
1cc6c93a | 2021 | pass_env[n_env++] = TAKE_PTR(x); |
b4c14404 | 2022 | pass_env[n_env] = NULL; |
b4c14404 FB |
2023 | } |
2024 | ||
ae2a15bc | 2025 | *ret = TAKE_PTR(pass_env); |
b4c14404 FB |
2026 | |
2027 | return 0; | |
2028 | } | |
2029 | ||
5e8deb94 | 2030 | bool exec_needs_mount_namespace( |
8b44a3d2 LP |
2031 | const ExecContext *context, |
2032 | const ExecParameters *params, | |
4657abb5 | 2033 | const ExecRuntime *runtime) { |
8b44a3d2 LP |
2034 | |
2035 | assert(context); | |
8b44a3d2 | 2036 | |
915e6d16 LP |
2037 | if (context->root_image) |
2038 | return true; | |
2039 | ||
2a624c36 AP |
2040 | if (!strv_isempty(context->read_write_paths) || |
2041 | !strv_isempty(context->read_only_paths) || | |
ddc155b2 TM |
2042 | !strv_isempty(context->inaccessible_paths) || |
2043 | !strv_isempty(context->exec_paths) || | |
2044 | !strv_isempty(context->no_exec_paths)) | |
8b44a3d2 LP |
2045 | return true; |
2046 | ||
42b1d8e0 | 2047 | if (context->n_bind_mounts > 0) |
d2d6c096 LP |
2048 | return true; |
2049 | ||
2abd4e38 YW |
2050 | if (context->n_temporary_filesystems > 0) |
2051 | return true; | |
2052 | ||
b3d13314 LB |
2053 | if (context->n_mount_images > 0) |
2054 | return true; | |
2055 | ||
93f59701 LB |
2056 | if (context->n_extension_images > 0) |
2057 | return true; | |
2058 | ||
a07b9926 LB |
2059 | if (!strv_isempty(context->extension_directories)) |
2060 | return true; | |
2061 | ||
37ed15d7 | 2062 | if (!IN_SET(context->mount_flags, 0, MS_SHARED)) |
8b44a3d2 LP |
2063 | return true; |
2064 | ||
2065 | if (context->private_tmp && runtime && (runtime->tmp_dir || runtime->var_tmp_dir)) | |
2066 | return true; | |
2067 | ||
8b44a3d2 | 2068 | if (context->private_devices || |
228af36f | 2069 | context->private_mounts || |
8b44a3d2 | 2070 | context->protect_system != PROTECT_SYSTEM_NO || |
59eeb84b LP |
2071 | context->protect_home != PROTECT_HOME_NO || |
2072 | context->protect_kernel_tunables || | |
c575770b | 2073 | context->protect_kernel_modules || |
94a7b275 | 2074 | context->protect_kernel_logs || |
4e399953 LP |
2075 | context->protect_control_groups || |
2076 | context->protect_proc != PROTECT_PROC_DEFAULT || | |
80271a44 XR |
2077 | context->proc_subset != PROC_SUBSET_ALL || |
2078 | context->private_ipc || | |
2079 | context->ipc_namespace_path) | |
8b44a3d2 LP |
2080 | return true; |
2081 | ||
37c56f89 | 2082 | if (context->root_directory) { |
5e98086d | 2083 | if (exec_context_get_effective_mount_apivfs(context)) |
37c56f89 YW |
2084 | return true; |
2085 | ||
5b10116e | 2086 | for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) { |
5e8deb94 | 2087 | if (params && !params->prefix[t]) |
37c56f89 YW |
2088 | continue; |
2089 | ||
211a3d87 | 2090 | if (context->directories[t].n_items > 0) |
37c56f89 YW |
2091 | return true; |
2092 | } | |
2093 | } | |
5d997827 | 2094 | |
42b1d8e0 | 2095 | if (context->dynamic_user && |
211a3d87 LB |
2096 | (context->directories[EXEC_DIRECTORY_STATE].n_items > 0 || |
2097 | context->directories[EXEC_DIRECTORY_CACHE].n_items > 0 || | |
2098 | context->directories[EXEC_DIRECTORY_LOGS].n_items > 0)) | |
42b1d8e0 YW |
2099 | return true; |
2100 | ||
91dd5f7c LP |
2101 | if (context->log_namespace) |
2102 | return true; | |
2103 | ||
8b44a3d2 LP |
2104 | return false; |
2105 | } | |
2106 | ||
5749f855 | 2107 | static int setup_private_users(uid_t ouid, gid_t ogid, uid_t uid, gid_t gid) { |
d251207d LP |
2108 | _cleanup_free_ char *uid_map = NULL, *gid_map = NULL; |
2109 | _cleanup_close_pair_ int errno_pipe[2] = { -1, -1 }; | |
2110 | _cleanup_close_ int unshare_ready_fd = -1; | |
2111 | _cleanup_(sigkill_waitp) pid_t pid = 0; | |
2112 | uint64_t c = 1; | |
d251207d LP |
2113 | ssize_t n; |
2114 | int r; | |
2115 | ||
5749f855 AZ |
2116 | /* Set up a user namespace and map the original UID/GID (IDs from before any user or group changes, i.e. |
2117 | * the IDs from the user or system manager(s)) to itself, the selected UID/GID to itself, and everything else to | |
d251207d LP |
2118 | * nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which |
2119 | * we however lack after opening the user namespace. To work around this we fork() a temporary child process, | |
2120 | * which waits for the parent to create the new user namespace while staying in the original namespace. The | |
2121 | * child then writes the UID mapping, under full privileges. The parent waits for the child to finish and | |
5749f855 AZ |
2122 | * continues execution normally. |
2123 | * For unprivileged users (i.e. without capabilities), the root to root mapping is excluded. As such, it | |
2124 | * does not need CAP_SETUID to write the single line mapping to itself. */ | |
d251207d | 2125 | |
5749f855 AZ |
2126 | /* Can only set up multiple mappings with CAP_SETUID. */ |
2127 | if (have_effective_cap(CAP_SETUID) && uid != ouid && uid_is_valid(uid)) | |
587ab01b | 2128 | r = asprintf(&uid_map, |
5749f855 | 2129 | UID_FMT " " UID_FMT " 1\n" /* Map $OUID → $OUID */ |
587ab01b | 2130 | UID_FMT " " UID_FMT " 1\n", /* Map $UID → $UID */ |
5749f855 AZ |
2131 | ouid, ouid, uid, uid); |
2132 | else | |
2133 | r = asprintf(&uid_map, | |
2134 | UID_FMT " " UID_FMT " 1\n", /* Map $OUID → $OUID */ | |
2135 | ouid, ouid); | |
d251207d | 2136 | |
5749f855 AZ |
2137 | if (r < 0) |
2138 | return -ENOMEM; | |
2139 | ||
2140 | /* Can only set up multiple mappings with CAP_SETGID. */ | |
2141 | if (have_effective_cap(CAP_SETGID) && gid != ogid && gid_is_valid(gid)) | |
587ab01b | 2142 | r = asprintf(&gid_map, |
5749f855 | 2143 | GID_FMT " " GID_FMT " 1\n" /* Map $OGID → $OGID */ |
587ab01b | 2144 | GID_FMT " " GID_FMT " 1\n", /* Map $GID → $GID */ |
5749f855 AZ |
2145 | ogid, ogid, gid, gid); |
2146 | else | |
2147 | r = asprintf(&gid_map, | |
2148 | GID_FMT " " GID_FMT " 1\n", /* Map $OGID -> $OGID */ | |
2149 | ogid, ogid); | |
2150 | ||
2151 | if (r < 0) | |
2152 | return -ENOMEM; | |
d251207d LP |
2153 | |
2154 | /* Create a communication channel so that the parent can tell the child when it finished creating the user | |
2155 | * namespace. */ | |
2156 | unshare_ready_fd = eventfd(0, EFD_CLOEXEC); | |
2157 | if (unshare_ready_fd < 0) | |
2158 | return -errno; | |
2159 | ||
2160 | /* Create a communication channel so that the child can tell the parent a proper error code in case it | |
2161 | * failed. */ | |
2162 | if (pipe2(errno_pipe, O_CLOEXEC) < 0) | |
2163 | return -errno; | |
2164 | ||
4c253ed1 LP |
2165 | r = safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &pid); |
2166 | if (r < 0) | |
2167 | return r; | |
2168 | if (r == 0) { | |
d251207d LP |
2169 | _cleanup_close_ int fd = -1; |
2170 | const char *a; | |
2171 | pid_t ppid; | |
2172 | ||
2173 | /* Child process, running in the original user namespace. Let's update the parent's UID/GID map from | |
2174 | * here, after the parent opened its own user namespace. */ | |
2175 | ||
2176 | ppid = getppid(); | |
2177 | errno_pipe[0] = safe_close(errno_pipe[0]); | |
2178 | ||
2179 | /* Wait until the parent unshared the user namespace */ | |
2180 | if (read(unshare_ready_fd, &c, sizeof(c)) < 0) { | |
2181 | r = -errno; | |
2182 | goto child_fail; | |
2183 | } | |
2184 | ||
2185 | /* Disable the setgroups() system call in the child user namespace, for good. */ | |
2186 | a = procfs_file_alloca(ppid, "setgroups"); | |
2187 | fd = open(a, O_WRONLY|O_CLOEXEC); | |
2188 | if (fd < 0) { | |
2189 | if (errno != ENOENT) { | |
2190 | r = -errno; | |
2191 | goto child_fail; | |
2192 | } | |
2193 | ||
2194 | /* If the file is missing the kernel is too old, let's continue anyway. */ | |
2195 | } else { | |
2196 | if (write(fd, "deny\n", 5) < 0) { | |
2197 | r = -errno; | |
2198 | goto child_fail; | |
2199 | } | |
2200 | ||
2201 | fd = safe_close(fd); | |
2202 | } | |
2203 | ||
2204 | /* First write the GID map */ | |
2205 | a = procfs_file_alloca(ppid, "gid_map"); | |
2206 | fd = open(a, O_WRONLY|O_CLOEXEC); | |
2207 | if (fd < 0) { | |
2208 | r = -errno; | |
2209 | goto child_fail; | |
2210 | } | |
2211 | if (write(fd, gid_map, strlen(gid_map)) < 0) { | |
2212 | r = -errno; | |
2213 | goto child_fail; | |
2214 | } | |
2215 | fd = safe_close(fd); | |
2216 | ||
2217 | /* The write the UID map */ | |
2218 | a = procfs_file_alloca(ppid, "uid_map"); | |
2219 | fd = open(a, O_WRONLY|O_CLOEXEC); | |
2220 | if (fd < 0) { | |
2221 | r = -errno; | |
2222 | goto child_fail; | |
2223 | } | |
2224 | if (write(fd, uid_map, strlen(uid_map)) < 0) { | |
2225 | r = -errno; | |
2226 | goto child_fail; | |
2227 | } | |
2228 | ||
2229 | _exit(EXIT_SUCCESS); | |
2230 | ||
2231 | child_fail: | |
2232 | (void) write(errno_pipe[1], &r, sizeof(r)); | |
2233 | _exit(EXIT_FAILURE); | |
2234 | } | |
2235 | ||
2236 | errno_pipe[1] = safe_close(errno_pipe[1]); | |
2237 | ||
2238 | if (unshare(CLONE_NEWUSER) < 0) | |
2239 | return -errno; | |
2240 | ||
2241 | /* Let the child know that the namespace is ready now */ | |
2242 | if (write(unshare_ready_fd, &c, sizeof(c)) < 0) | |
2243 | return -errno; | |
2244 | ||
2245 | /* Try to read an error code from the child */ | |
2246 | n = read(errno_pipe[0], &r, sizeof(r)); | |
2247 | if (n < 0) | |
2248 | return -errno; | |
2249 | if (n == sizeof(r)) { /* an error code was sent to us */ | |
2250 | if (r < 0) | |
2251 | return r; | |
2252 | return -EIO; | |
2253 | } | |
2254 | if (n != 0) /* on success we should have read 0 bytes */ | |
2255 | return -EIO; | |
2256 | ||
8f03de53 | 2257 | r = wait_for_terminate_and_check("(sd-userns)", TAKE_PID(pid), 0); |
d251207d LP |
2258 | if (r < 0) |
2259 | return r; | |
2e87a1fd | 2260 | if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */ |
d251207d LP |
2261 | return -EIO; |
2262 | ||
2263 | return 0; | |
2264 | } | |
2265 | ||
494d0247 YW |
2266 | static bool exec_directory_is_private(const ExecContext *context, ExecDirectoryType type) { |
2267 | if (!context->dynamic_user) | |
2268 | return false; | |
2269 | ||
2270 | if (type == EXEC_DIRECTORY_CONFIGURATION) | |
2271 | return false; | |
2272 | ||
2273 | if (type == EXEC_DIRECTORY_RUNTIME && context->runtime_directory_preserve_mode == EXEC_PRESERVE_NO) | |
2274 | return false; | |
2275 | ||
2276 | return true; | |
2277 | } | |
2278 | ||
211a3d87 LB |
2279 | static int create_many_symlinks(const char *root, const char *source, char **symlinks) { |
2280 | _cleanup_free_ char *src_abs = NULL; | |
211a3d87 LB |
2281 | int r; |
2282 | ||
2283 | assert(source); | |
2284 | ||
2285 | src_abs = path_join(root, source); | |
2286 | if (!src_abs) | |
2287 | return -ENOMEM; | |
2288 | ||
2289 | STRV_FOREACH(dst, symlinks) { | |
2290 | _cleanup_free_ char *dst_abs = NULL; | |
2291 | ||
2292 | dst_abs = path_join(root, *dst); | |
2293 | if (!dst_abs) | |
2294 | return -ENOMEM; | |
2295 | ||
2296 | r = mkdir_parents_label(dst_abs, 0755); | |
2297 | if (r < 0) | |
2298 | return r; | |
2299 | ||
2300 | r = symlink_idempotent(src_abs, dst_abs, true); | |
2301 | if (r < 0) | |
2302 | return r; | |
2303 | } | |
2304 | ||
2305 | return 0; | |
2306 | } | |
2307 | ||
3536f49e | 2308 | static int setup_exec_directory( |
07689d5d LP |
2309 | const ExecContext *context, |
2310 | const ExecParameters *params, | |
2311 | uid_t uid, | |
3536f49e | 2312 | gid_t gid, |
3536f49e | 2313 | ExecDirectoryType type, |
211a3d87 | 2314 | bool needs_mount_namespace, |
3536f49e | 2315 | int *exit_status) { |
07689d5d | 2316 | |
72fd1768 | 2317 | static const int exit_status_table[_EXEC_DIRECTORY_TYPE_MAX] = { |
3536f49e YW |
2318 | [EXEC_DIRECTORY_RUNTIME] = EXIT_RUNTIME_DIRECTORY, |
2319 | [EXEC_DIRECTORY_STATE] = EXIT_STATE_DIRECTORY, | |
2320 | [EXEC_DIRECTORY_CACHE] = EXIT_CACHE_DIRECTORY, | |
2321 | [EXEC_DIRECTORY_LOGS] = EXIT_LOGS_DIRECTORY, | |
2322 | [EXEC_DIRECTORY_CONFIGURATION] = EXIT_CONFIGURATION_DIRECTORY, | |
2323 | }; | |
07689d5d LP |
2324 | int r; |
2325 | ||
2326 | assert(context); | |
2327 | assert(params); | |
72fd1768 | 2328 | assert(type >= 0 && type < _EXEC_DIRECTORY_TYPE_MAX); |
3536f49e | 2329 | assert(exit_status); |
07689d5d | 2330 | |
3536f49e YW |
2331 | if (!params->prefix[type]) |
2332 | return 0; | |
2333 | ||
8679efde | 2334 | if (params->flags & EXEC_CHOWN_DIRECTORIES) { |
3536f49e YW |
2335 | if (!uid_is_valid(uid)) |
2336 | uid = 0; | |
2337 | if (!gid_is_valid(gid)) | |
2338 | gid = 0; | |
2339 | } | |
2340 | ||
211a3d87 | 2341 | for (size_t i = 0; i < context->directories[type].n_items; i++) { |
6c47cd7d | 2342 | _cleanup_free_ char *p = NULL, *pp = NULL; |
07689d5d | 2343 | |
211a3d87 | 2344 | p = path_join(params->prefix[type], context->directories[type].items[i].path); |
3536f49e YW |
2345 | if (!p) { |
2346 | r = -ENOMEM; | |
2347 | goto fail; | |
2348 | } | |
07689d5d | 2349 | |
23a7448e YW |
2350 | r = mkdir_parents_label(p, 0755); |
2351 | if (r < 0) | |
3536f49e | 2352 | goto fail; |
23a7448e | 2353 | |
494d0247 | 2354 | if (exec_directory_is_private(context, type)) { |
3f5b1508 LP |
2355 | /* So, here's one extra complication when dealing with DynamicUser=1 units. In that |
2356 | * case we want to avoid leaving a directory around fully accessible that is owned by | |
2357 | * a dynamic user whose UID is later on reused. To lock this down we use the same | |
2358 | * trick used by container managers to prohibit host users to get access to files of | |
2359 | * the same UID in containers: we place everything inside a directory that has an | |
2360 | * access mode of 0700 and is owned root:root, so that it acts as security boundary | |
2361 | * for unprivileged host code. We then use fs namespacing to make this directory | |
2362 | * permeable for the service itself. | |
6c47cd7d | 2363 | * |
3f5b1508 LP |
2364 | * Specifically: for a service which wants a special directory "foo/" we first create |
2365 | * a directory "private/" with access mode 0700 owned by root:root. Then we place | |
2366 | * "foo" inside of that directory (i.e. "private/foo/"), and make "foo" a symlink to | |
2367 | * "private/foo". This way, privileged host users can access "foo/" as usual, but | |
2368 | * unprivileged host users can't look into it. Inside of the namespace of the unit | |
2369 | * "private/" is replaced by a more liberally accessible tmpfs, into which the host's | |
2370 | * "private/foo/" is mounted under the same name, thus disabling the access boundary | |
2371 | * for the service and making sure it only gets access to the dirs it needs but no | |
2372 | * others. Tricky? Yes, absolutely, but it works! | |
6c47cd7d | 2373 | * |
3f5b1508 LP |
2374 | * Note that we don't do this for EXEC_DIRECTORY_CONFIGURATION as that's assumed not |
2375 | * to be owned by the service itself. | |
2376 | * | |
2377 | * Also, note that we don't do this for EXEC_DIRECTORY_RUNTIME as that's often used | |
2378 | * for sharing files or sockets with other services. */ | |
6c47cd7d | 2379 | |
4ede9802 LP |
2380 | pp = path_join(params->prefix[type], "private"); |
2381 | if (!pp) { | |
6c47cd7d LP |
2382 | r = -ENOMEM; |
2383 | goto fail; | |
2384 | } | |
2385 | ||
2386 | /* First set up private root if it doesn't exist yet, with access mode 0700 and owned by root:root */ | |
4ede9802 | 2387 | r = mkdir_safe_label(pp, 0700, 0, 0, MKDIR_WARN_MODE); |
6c47cd7d LP |
2388 | if (r < 0) |
2389 | goto fail; | |
2390 | ||
211a3d87 | 2391 | if (!path_extend(&pp, context->directories[type].items[i].path)) { |
6c47cd7d LP |
2392 | r = -ENOMEM; |
2393 | goto fail; | |
2394 | } | |
2395 | ||
2396 | /* Create all directories between the configured directory and this private root, and mark them 0755 */ | |
2397 | r = mkdir_parents_label(pp, 0755); | |
2398 | if (r < 0) | |
2399 | goto fail; | |
2400 | ||
949befd3 LP |
2401 | if (is_dir(p, false) > 0 && |
2402 | (laccess(pp, F_OK) < 0 && errno == ENOENT)) { | |
2403 | ||
2404 | /* Hmm, the private directory doesn't exist yet, but the normal one exists? If so, move | |
2405 | * it over. Most likely the service has been upgraded from one that didn't use | |
2406 | * DynamicUser=1, to one that does. */ | |
2407 | ||
cf52c45d LP |
2408 | log_info("Found pre-existing public %s= directory %s, migrating to %s.\n" |
2409 | "Apparently, service previously had DynamicUser= turned off, and has now turned it on.", | |
2410 | exec_directory_type_to_string(type), p, pp); | |
2411 | ||
949befd3 LP |
2412 | if (rename(p, pp) < 0) { |
2413 | r = -errno; | |
2414 | goto fail; | |
2415 | } | |
2416 | } else { | |
2417 | /* Otherwise, create the actual directory for the service */ | |
2418 | ||
2419 | r = mkdir_label(pp, context->directories[type].mode); | |
2420 | if (r < 0 && r != -EEXIST) | |
2421 | goto fail; | |
2422 | } | |
6c47cd7d | 2423 | |
df61e79a LB |
2424 | /* And link it up from the original place. Note that if a mount namespace is going to be |
2425 | * used, then this symlink remains on the host, and a new one for the child namespace will | |
2426 | * be created later. */ | |
6c9c51e5 | 2427 | r = symlink_idempotent(pp, p, true); |
6c47cd7d LP |
2428 | if (r < 0) |
2429 | goto fail; | |
2430 | ||
6c47cd7d | 2431 | } else { |
5c6d40d1 LP |
2432 | _cleanup_free_ char *target = NULL; |
2433 | ||
2434 | if (type != EXEC_DIRECTORY_CONFIGURATION && | |
2435 | readlink_and_make_absolute(p, &target) >= 0) { | |
578dc69f | 2436 | _cleanup_free_ char *q = NULL, *q_resolved = NULL, *target_resolved = NULL; |
5c6d40d1 LP |
2437 | |
2438 | /* This already exists and is a symlink? Interesting. Maybe it's one created | |
2193f17c LP |
2439 | * by DynamicUser=1 (see above)? |
2440 | * | |
2441 | * We do this for all directory types except for ConfigurationDirectory=, | |
2442 | * since they all support the private/ symlink logic at least in some | |
2443 | * configurations, see above. */ | |
5c6d40d1 | 2444 | |
578dc69f YW |
2445 | r = chase_symlinks(target, NULL, 0, &target_resolved, NULL); |
2446 | if (r < 0) | |
2447 | goto fail; | |
2448 | ||
211a3d87 | 2449 | q = path_join(params->prefix[type], "private", context->directories[type].items[i].path); |
5c6d40d1 LP |
2450 | if (!q) { |
2451 | r = -ENOMEM; | |
2452 | goto fail; | |
2453 | } | |
2454 | ||
578dc69f YW |
2455 | /* /var/lib or friends may be symlinks. So, let's chase them also. */ |
2456 | r = chase_symlinks(q, NULL, CHASE_NONEXISTENT, &q_resolved, NULL); | |
2457 | if (r < 0) | |
2458 | goto fail; | |
2459 | ||
2460 | if (path_equal(q_resolved, target_resolved)) { | |
5c6d40d1 LP |
2461 | |
2462 | /* Hmm, apparently DynamicUser= was once turned on for this service, | |
2463 | * but is no longer. Let's move the directory back up. */ | |
2464 | ||
cf52c45d LP |
2465 | log_info("Found pre-existing private %s= directory %s, migrating to %s.\n" |
2466 | "Apparently, service previously had DynamicUser= turned on, and has now turned it off.", | |
2467 | exec_directory_type_to_string(type), q, p); | |
2468 | ||
5c6d40d1 LP |
2469 | if (unlink(p) < 0) { |
2470 | r = -errno; | |
2471 | goto fail; | |
2472 | } | |
2473 | ||
2474 | if (rename(q, p) < 0) { | |
2475 | r = -errno; | |
2476 | goto fail; | |
2477 | } | |
2478 | } | |
2479 | } | |
2480 | ||
6c47cd7d | 2481 | r = mkdir_label(p, context->directories[type].mode); |
d484580c | 2482 | if (r < 0) { |
d484580c LP |
2483 | if (r != -EEXIST) |
2484 | goto fail; | |
2485 | ||
206e9864 LP |
2486 | if (type == EXEC_DIRECTORY_CONFIGURATION) { |
2487 | struct stat st; | |
2488 | ||
2489 | /* Don't change the owner/access mode of the configuration directory, | |
2490 | * as in the common case it is not written to by a service, and shall | |
2491 | * not be writable. */ | |
2492 | ||
2493 | if (stat(p, &st) < 0) { | |
2494 | r = -errno; | |
2495 | goto fail; | |
2496 | } | |
2497 | ||
2498 | /* Still complain if the access mode doesn't match */ | |
2499 | if (((st.st_mode ^ context->directories[type].mode) & 07777) != 0) | |
2500 | log_warning("%s \'%s\' already exists but the mode is different. " | |
2501 | "(File system: %o %sMode: %o)", | |
211a3d87 | 2502 | exec_directory_type_to_string(type), context->directories[type].items[i].path, |
206e9864 LP |
2503 | st.st_mode & 07777, exec_directory_type_to_string(type), context->directories[type].mode & 07777); |
2504 | ||
6cff72eb | 2505 | continue; |
206e9864 | 2506 | } |
6cff72eb | 2507 | } |
a1164ae3 | 2508 | } |
07689d5d | 2509 | |
206e9864 | 2510 | /* Lock down the access mode (we use chmod_and_chown() to make this idempotent. We don't |
5238e957 | 2511 | * specify UID/GID here, so that path_chown_recursive() can optimize things depending on the |
206e9864 LP |
2512 | * current UID/GID ownership.) */ |
2513 | r = chmod_and_chown(pp ?: p, context->directories[type].mode, UID_INVALID, GID_INVALID); | |
2514 | if (r < 0) | |
2515 | goto fail; | |
c71b2eb7 | 2516 | |
607b358e LP |
2517 | /* Then, change the ownership of the whole tree, if necessary. When dynamic users are used we |
2518 | * drop the suid/sgid bits, since we really don't want SUID/SGID files for dynamic UID/GID | |
7802194a | 2519 | * assignments to exist. */ |
607b358e | 2520 | r = path_chown_recursive(pp ?: p, uid, gid, context->dynamic_user ? 01777 : 07777); |
07689d5d | 2521 | if (r < 0) |
3536f49e | 2522 | goto fail; |
07689d5d LP |
2523 | } |
2524 | ||
211a3d87 LB |
2525 | /* If we are not going to run in a namespace, set up the symlinks - otherwise |
2526 | * they are set up later, to allow configuring empty var/run/etc. */ | |
2527 | if (!needs_mount_namespace) | |
2528 | for (size_t i = 0; i < context->directories[type].n_items; i++) { | |
2529 | r = create_many_symlinks(params->prefix[type], | |
2530 | context->directories[type].items[i].path, | |
2531 | context->directories[type].items[i].symlinks); | |
2532 | if (r < 0) | |
2533 | goto fail; | |
2534 | } | |
2535 | ||
07689d5d | 2536 | return 0; |
3536f49e YW |
2537 | |
2538 | fail: | |
2539 | *exit_status = exit_status_table[type]; | |
3536f49e | 2540 | return r; |
07689d5d LP |
2541 | } |
2542 | ||
bb0c0d6f LP |
2543 | static int write_credential( |
2544 | int dfd, | |
2545 | const char *id, | |
2546 | const void *data, | |
2547 | size_t size, | |
2548 | uid_t uid, | |
2549 | bool ownership_ok) { | |
2550 | ||
2551 | _cleanup_(unlink_and_freep) char *tmp = NULL; | |
2552 | _cleanup_close_ int fd = -1; | |
2553 | int r; | |
2554 | ||
2555 | r = tempfn_random_child("", "cred", &tmp); | |
2556 | if (r < 0) | |
2557 | return r; | |
2558 | ||
2559 | fd = openat(dfd, tmp, O_CREAT|O_RDWR|O_CLOEXEC|O_EXCL|O_NOFOLLOW|O_NOCTTY, 0600); | |
2560 | if (fd < 0) { | |
2561 | tmp = mfree(tmp); | |
2562 | return -errno; | |
2563 | } | |
2564 | ||
43144be4 | 2565 | r = loop_write(fd, data, size, /* do_poll = */ false); |
bb0c0d6f LP |
2566 | if (r < 0) |
2567 | return r; | |
2568 | ||
2569 | if (fchmod(fd, 0400) < 0) /* Take away "w" bit */ | |
2570 | return -errno; | |
2571 | ||
2572 | if (uid_is_valid(uid) && uid != getuid()) { | |
567aeb58 | 2573 | r = fd_add_uid_acl_permission(fd, uid, ACL_READ); |
bb0c0d6f LP |
2574 | if (r < 0) { |
2575 | if (!ERRNO_IS_NOT_SUPPORTED(r) && !ERRNO_IS_PRIVILEGE(r)) | |
2576 | return r; | |
2577 | ||
2578 | if (!ownership_ok) /* Ideally we use ACLs, since we can neatly express what we want | |
2579 | * to express: that the user gets read access and nothing | |
2580 | * else. But if the backing fs can't support that (e.g. ramfs) | |
2581 | * then we can use file ownership instead. But that's only safe if | |
2582 | * we can then re-mount the whole thing read-only, so that the | |
2583 | * user can no longer chmod() the file to gain write access. */ | |
2584 | return r; | |
2585 | ||
f5fbe71d | 2586 | if (fchown(fd, uid, GID_INVALID) < 0) |
bb0c0d6f LP |
2587 | return -errno; |
2588 | } | |
2589 | } | |
2590 | ||
2591 | if (renameat(dfd, tmp, dfd, id) < 0) | |
2592 | return -errno; | |
2593 | ||
2594 | tmp = mfree(tmp); | |
2595 | return 0; | |
2596 | } | |
2597 | ||
3989bdc1 AB |
2598 | static int load_credential( |
2599 | const ExecContext *context, | |
2600 | const ExecParameters *params, | |
2601 | ExecLoadCredential *lc, | |
2602 | const char *unit, | |
2603 | int read_dfd, | |
2604 | int write_dfd, | |
2605 | uid_t uid, | |
2606 | bool ownership_ok, | |
2607 | uint64_t *left) { | |
2608 | ||
2609 | assert(context); | |
2610 | assert(lc); | |
2611 | assert(unit); | |
2612 | assert(write_dfd >= 0); | |
2613 | assert(left); | |
2614 | ||
2615 | ReadFullFileFlags flags = READ_FULL_FILE_SECURE|READ_FULL_FILE_FAIL_WHEN_LARGER; | |
2616 | _cleanup_(erase_and_freep) char *data = NULL; | |
2617 | _cleanup_free_ char *j = NULL, *bindname = NULL; | |
2618 | bool missing_ok = true; | |
2619 | const char *source; | |
2620 | size_t size, add; | |
2621 | int r; | |
2622 | ||
2623 | if (path_is_absolute(lc->path) || read_dfd >= 0) { | |
2624 | /* If this is an absolute path, read the data directly from it, and support AF_UNIX sockets */ | |
2625 | source = lc->path; | |
2626 | flags |= READ_FULL_FILE_CONNECT_SOCKET; | |
2627 | ||
2628 | /* Pass some minimal info about the unit and the credential name we are looking to acquire | |
2629 | * via the source socket address in case we read off an AF_UNIX socket. */ | |
2630 | if (asprintf(&bindname, "@%" PRIx64"/unit/%s/%s", random_u64(), unit, lc->id) < 0) | |
2631 | return -ENOMEM; | |
2632 | ||
2633 | missing_ok = false; | |
2634 | ||
2635 | } else if (params->received_credentials) { | |
2636 | /* If this is a relative path, take it relative to the credentials we received | |
2637 | * ourselves. We don't support the AF_UNIX stuff in this mode, since we are operating | |
2638 | * on a credential store, i.e. this is guaranteed to be regular files. */ | |
2639 | j = path_join(params->received_credentials, lc->path); | |
2640 | if (!j) | |
2641 | return -ENOMEM; | |
2642 | ||
2643 | source = j; | |
2644 | } else | |
2645 | source = NULL; | |
2646 | ||
2647 | if (source) | |
2648 | r = read_full_file_full( | |
2649 | read_dfd, source, | |
2650 | UINT64_MAX, | |
2651 | lc->encrypted ? CREDENTIAL_ENCRYPTED_SIZE_MAX : CREDENTIAL_SIZE_MAX, | |
2652 | flags | (lc->encrypted ? READ_FULL_FILE_UNBASE64 : 0), | |
2653 | bindname, | |
2654 | &data, &size); | |
2655 | else | |
2656 | r = -ENOENT; | |
2657 | ||
2658 | if (r == -ENOENT && (missing_ok || hashmap_contains(context->set_credentials, lc->id))) { | |
2659 | /* Make a missing inherited credential non-fatal, let's just continue. After all apps | |
2660 | * will get clear errors if we don't pass such a missing credential on as they | |
2661 | * themselves will get ENOENT when trying to read them, which should not be much | |
2662 | * worse than when we handle the error here and make it fatal. | |
2663 | * | |
2664 | * Also, if the source file doesn't exist, but a fallback is set via SetCredentials= | |
2665 | * we are fine, too. */ | |
2666 | log_debug_errno(r, "Couldn't read inherited credential '%s', skipping: %m", lc->path); | |
2667 | return 0; | |
2668 | } | |
2669 | if (r < 0) | |
2670 | return log_debug_errno(r, "Failed to read credential '%s': %m", lc->path); | |
2671 | ||
2672 | if (lc->encrypted) { | |
2673 | _cleanup_free_ void *plaintext = NULL; | |
2674 | size_t plaintext_size = 0; | |
2675 | ||
2676 | r = decrypt_credential_and_warn(lc->id, now(CLOCK_REALTIME), NULL, data, size, &plaintext, &plaintext_size); | |
2677 | if (r < 0) | |
2678 | return r; | |
2679 | ||
2680 | free_and_replace(data, plaintext); | |
2681 | size = plaintext_size; | |
2682 | } | |
2683 | ||
2684 | add = strlen(lc->id) + size; | |
2685 | if (add > *left) | |
2686 | return -E2BIG; | |
2687 | ||
2688 | r = write_credential(write_dfd, lc->id, data, size, uid, ownership_ok); | |
2689 | if (r < 0) | |
2690 | return r; | |
2691 | ||
2692 | *left -= add; | |
2693 | return 0; | |
2694 | } | |
2695 | ||
2696 | struct load_cred_args { | |
2697 | Set *seen_creds; | |
2698 | ||
2699 | const ExecContext *context; | |
2700 | const ExecParameters *params; | |
2701 | ExecLoadCredential *parent_local_credential; | |
2702 | const char *unit; | |
2703 | int dfd; | |
2704 | uid_t uid; | |
2705 | bool ownership_ok; | |
2706 | uint64_t *left; | |
2707 | }; | |
2708 | ||
2709 | static int load_cred_recurse_dir_cb( | |
2710 | RecurseDirEvent event, | |
2711 | const char *path, | |
2712 | int dir_fd, | |
2713 | int inode_fd, | |
2714 | const struct dirent *de, | |
2715 | const struct statx *sx, | |
2716 | void *userdata) { | |
2717 | ||
2718 | _cleanup_free_ char *credname = NULL, *sub_id = NULL; | |
6394e5cd | 2719 | struct load_cred_args *args = ASSERT_PTR(userdata); |
3989bdc1 AB |
2720 | int r; |
2721 | ||
2722 | if (event != RECURSE_DIR_ENTRY) | |
2723 | return RECURSE_DIR_CONTINUE; | |
2724 | ||
2725 | if (!IN_SET(de->d_type, DT_REG, DT_SOCK)) | |
2726 | return RECURSE_DIR_CONTINUE; | |
2727 | ||
2728 | credname = strreplace(path, "/", "_"); | |
2729 | if (!credname) | |
2730 | return -ENOMEM; | |
2731 | ||
2732 | sub_id = strjoin(args->parent_local_credential->id, "_", credname); | |
2733 | if (!sub_id) | |
2734 | return -ENOMEM; | |
2735 | ||
2736 | if (!credential_name_valid(sub_id)) | |
2737 | return -EINVAL; | |
2738 | ||
2739 | if (set_contains(args->seen_creds, sub_id)) { | |
2740 | log_debug("Skipping credential with duplicated ID %s at %s", sub_id, path); | |
2741 | return RECURSE_DIR_CONTINUE; | |
2742 | } | |
2743 | ||
2744 | r = set_put_strdup(&args->seen_creds, sub_id); | |
2745 | if (r < 0) | |
2746 | return r; | |
2747 | ||
2748 | r = load_credential(args->context, args->params, | |
2749 | &(ExecLoadCredential) { | |
2750 | .id = sub_id, | |
2751 | .path = (char *) de->d_name, | |
2752 | .encrypted = args->parent_local_credential->encrypted, | |
2753 | }, args->unit, dir_fd, args->dfd, args->uid, args->ownership_ok, args->left); | |
2754 | if (r < 0) | |
2755 | return r; | |
2756 | ||
2757 | return RECURSE_DIR_CONTINUE; | |
2758 | } | |
2759 | ||
bb0c0d6f LP |
2760 | static int acquire_credentials( |
2761 | const ExecContext *context, | |
2762 | const ExecParameters *params, | |
d3dcf4e3 | 2763 | const char *unit, |
bb0c0d6f LP |
2764 | const char *p, |
2765 | uid_t uid, | |
2766 | bool ownership_ok) { | |
2767 | ||
43144be4 | 2768 | uint64_t left = CREDENTIALS_TOTAL_SIZE_MAX; |
bb0c0d6f | 2769 | _cleanup_close_ int dfd = -1; |
3989bdc1 | 2770 | _cleanup_set_free_ Set *seen_creds = NULL; |
43144be4 | 2771 | ExecLoadCredential *lc; |
bb0c0d6f | 2772 | ExecSetCredential *sc; |
bb0c0d6f LP |
2773 | int r; |
2774 | ||
2775 | assert(context); | |
2776 | assert(p); | |
2777 | ||
2778 | dfd = open(p, O_DIRECTORY|O_CLOEXEC); | |
2779 | if (dfd < 0) | |
2780 | return -errno; | |
2781 | ||
3989bdc1 AB |
2782 | seen_creds = set_new(&string_hash_ops_free); |
2783 | if (!seen_creds) | |
2784 | return -ENOMEM; | |
2785 | ||
43144be4 LP |
2786 | /* First, load credentials off disk (or acquire via AF_UNIX socket) */ |
2787 | HASHMAP_FOREACH(lc, context->load_credentials) { | |
3989bdc1 | 2788 | _cleanup_close_ int sub_fd = -1; |
d3dcf4e3 | 2789 | |
3989bdc1 AB |
2790 | /* Skip over credentials with unspecified paths. These are received by the |
2791 | * service manager via the $CREDENTIALS_DIRECTORY environment variable. */ | |
2792 | if (!is_path(lc->path) && streq(lc->id, lc->path)) | |
bb0c0d6f | 2793 | continue; |
43144be4 | 2794 | |
3989bdc1 AB |
2795 | sub_fd = open(lc->path, O_DIRECTORY|O_CLOEXEC|O_RDONLY); |
2796 | if (sub_fd < 0 && errno != ENOTDIR) | |
2797 | return -errno; | |
43144be4 | 2798 | |
3989bdc1 AB |
2799 | if (sub_fd < 0) { |
2800 | r = set_put_strdup(&seen_creds, lc->id); | |
2801 | if (r < 0) | |
2802 | return r; | |
2803 | r = load_credential(context, params, lc, unit, -1, dfd, uid, ownership_ok, &left); | |
43144be4 LP |
2804 | if (r < 0) |
2805 | return r; | |
bb0c0d6f | 2806 | |
3989bdc1 AB |
2807 | } else { |
2808 | r = recurse_dir( | |
2809 | sub_fd, | |
2810 | /* path= */ "", | |
2811 | /* statx_mask= */ 0, | |
2812 | /* n_depth_max= */ UINT_MAX, | |
2813 | RECURSE_DIR_IGNORE_DOT|RECURSE_DIR_ENSURE_TYPE, | |
2814 | load_cred_recurse_dir_cb, | |
2815 | &(struct load_cred_args) { | |
2816 | .seen_creds = seen_creds, | |
2817 | .context = context, | |
2818 | .params = params, | |
2819 | .parent_local_credential = lc, | |
2820 | .unit = unit, | |
2821 | .dfd = dfd, | |
2822 | .uid = uid, | |
2823 | .ownership_ok = ownership_ok, | |
2824 | .left = &left, | |
2825 | }); | |
2826 | if (r < 0) | |
2827 | return r; | |
43144be4 | 2828 | } |
bb0c0d6f LP |
2829 | } |
2830 | ||
43144be4 LP |
2831 | /* First we use the literally specified credentials. Note that they might be overridden again below, |
2832 | * and thus act as a "default" if the same credential is specified multiple times */ | |
2833 | HASHMAP_FOREACH(sc, context->set_credentials) { | |
2834 | _cleanup_(erase_and_freep) void *plaintext = NULL; | |
2835 | const char *data; | |
2836 | size_t size, add; | |
2837 | ||
2838 | if (faccessat(dfd, sc->id, F_OK, AT_SYMLINK_NOFOLLOW) >= 0) | |
2839 | continue; | |
2840 | if (errno != ENOENT) | |
2841 | return log_debug_errno(errno, "Failed to test if credential %s exists: %m", sc->id); | |
2842 | ||
2843 | if (sc->encrypted) { | |
2844 | r = decrypt_credential_and_warn(sc->id, now(CLOCK_REALTIME), NULL, sc->data, sc->size, &plaintext, &size); | |
2845 | if (r < 0) | |
2846 | return r; | |
2847 | ||
2848 | data = plaintext; | |
2849 | } else { | |
2850 | data = sc->data; | |
2851 | size = sc->size; | |
2852 | } | |
2853 | ||
2854 | add = strlen(sc->id) + size; | |
2855 | if (add > left) | |
2856 | return -E2BIG; | |
2857 | ||
2858 | r = write_credential(dfd, sc->id, data, size, uid, ownership_ok); | |
2859 | if (r < 0) | |
2860 | return r; | |
2861 | ||
43144be4 LP |
2862 | left -= add; |
2863 | } | |
2864 | ||
bb0c0d6f LP |
2865 | if (fchmod(dfd, 0500) < 0) /* Now take away the "w" bit */ |
2866 | return -errno; | |
2867 | ||
2868 | /* After we created all keys with the right perms, also make sure the credential store as a whole is | |
2869 | * accessible */ | |
2870 | ||
2871 | if (uid_is_valid(uid) && uid != getuid()) { | |
567aeb58 | 2872 | r = fd_add_uid_acl_permission(dfd, uid, ACL_READ | ACL_EXECUTE); |
bb0c0d6f LP |
2873 | if (r < 0) { |
2874 | if (!ERRNO_IS_NOT_SUPPORTED(r) && !ERRNO_IS_PRIVILEGE(r)) | |
2875 | return r; | |
2876 | ||
2877 | if (!ownership_ok) | |
2878 | return r; | |
2879 | ||
f5fbe71d | 2880 | if (fchown(dfd, uid, GID_INVALID) < 0) |
bb0c0d6f LP |
2881 | return -errno; |
2882 | } | |
2883 | } | |
2884 | ||
2885 | return 0; | |
2886 | } | |
2887 | ||
2888 | static int setup_credentials_internal( | |
2889 | const ExecContext *context, | |
2890 | const ExecParameters *params, | |
d3dcf4e3 | 2891 | const char *unit, |
bb0c0d6f LP |
2892 | const char *final, /* This is where the credential store shall eventually end up at */ |
2893 | const char *workspace, /* This is where we can prepare it before moving it to the final place */ | |
2894 | bool reuse_workspace, /* Whether to reuse any existing workspace mount if it already is a mount */ | |
2895 | bool must_mount, /* Whether to require that we mount something, it's not OK to use the plain directory fall back */ | |
2896 | uid_t uid) { | |
2897 | ||
2898 | int r, workspace_mounted; /* negative if we don't know yet whether we have/can mount something; true | |
2899 | * if we mounted something; false if we definitely can't mount anything */ | |
2900 | bool final_mounted; | |
2901 | const char *where; | |
2902 | ||
2903 | assert(context); | |
2904 | assert(final); | |
2905 | assert(workspace); | |
2906 | ||
2907 | if (reuse_workspace) { | |
2908 | r = path_is_mount_point(workspace, NULL, 0); | |
2909 | if (r < 0) | |
2910 | return r; | |
2911 | if (r > 0) | |
2912 | workspace_mounted = true; /* If this is already a mount, and we are supposed to reuse it, let's keep this in mind */ | |
2913 | else | |
2914 | workspace_mounted = -1; /* We need to figure out if we can mount something to the workspace */ | |
2915 | } else | |
2916 | workspace_mounted = -1; /* ditto */ | |
2917 | ||
2918 | r = path_is_mount_point(final, NULL, 0); | |
2919 | if (r < 0) | |
2920 | return r; | |
2921 | if (r > 0) { | |
2922 | /* If the final place already has something mounted, we use that. If the workspace also has | |
2923 | * something mounted we assume it's actually the same mount (but with MS_RDONLY | |
2924 | * different). */ | |
2925 | final_mounted = true; | |
2926 | ||
2927 | if (workspace_mounted < 0) { | |
2928 | /* If the final place is mounted, but the workspace we isn't, then let's bind mount | |
2929 | * the final version to the workspace, and make it writable, so that we can make | |
2930 | * changes */ | |
2931 | ||
21935150 LP |
2932 | r = mount_nofollow_verbose(LOG_DEBUG, final, workspace, NULL, MS_BIND|MS_REC, NULL); |
2933 | if (r < 0) | |
2934 | return r; | |
bb0c0d6f | 2935 | |
21935150 LP |
2936 | r = mount_nofollow_verbose(LOG_DEBUG, NULL, workspace, NULL, MS_BIND|MS_REMOUNT|MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL); |
2937 | if (r < 0) | |
2938 | return r; | |
bb0c0d6f LP |
2939 | |
2940 | workspace_mounted = true; | |
2941 | } | |
2942 | } else | |
2943 | final_mounted = false; | |
2944 | ||
2945 | if (workspace_mounted < 0) { | |
2946 | /* Nothing is mounted on the workspace yet, let's try to mount something now */ | |
2947 | for (int try = 0;; try++) { | |
2948 | ||
2949 | if (try == 0) { | |
2950 | /* Try "ramfs" first, since it's not swap backed */ | |
21935150 LP |
2951 | r = mount_nofollow_verbose(LOG_DEBUG, "ramfs", workspace, "ramfs", MS_NODEV|MS_NOEXEC|MS_NOSUID, "mode=0700"); |
2952 | if (r >= 0) { | |
bb0c0d6f LP |
2953 | workspace_mounted = true; |
2954 | break; | |
2955 | } | |
2956 | ||
2957 | } else if (try == 1) { | |
2958 | _cleanup_free_ char *opts = NULL; | |
2959 | ||
43144be4 | 2960 | if (asprintf(&opts, "mode=0700,nr_inodes=1024,size=%zu", (size_t) CREDENTIALS_TOTAL_SIZE_MAX) < 0) |
bb0c0d6f LP |
2961 | return -ENOMEM; |
2962 | ||
2963 | /* Fall back to "tmpfs" otherwise */ | |
21935150 LP |
2964 | r = mount_nofollow_verbose(LOG_DEBUG, "tmpfs", workspace, "tmpfs", MS_NODEV|MS_NOEXEC|MS_NOSUID, opts); |
2965 | if (r >= 0) { | |
bb0c0d6f LP |
2966 | workspace_mounted = true; |
2967 | break; | |
2968 | } | |
2969 | ||
2970 | } else { | |
2971 | /* If that didn't work, try to make a bind mount from the final to the workspace, so that we can make it writable there. */ | |
21935150 LP |
2972 | r = mount_nofollow_verbose(LOG_DEBUG, final, workspace, NULL, MS_BIND|MS_REC, NULL); |
2973 | if (r < 0) { | |
2974 | if (!ERRNO_IS_PRIVILEGE(r)) /* Propagate anything that isn't a permission problem */ | |
2975 | return r; | |
bb0c0d6f LP |
2976 | |
2977 | if (must_mount) /* If we it's not OK to use the plain directory | |
2978 | * fallback, propagate all errors too */ | |
21935150 | 2979 | return r; |
bb0c0d6f LP |
2980 | |
2981 | /* If we lack privileges to bind mount stuff, then let's gracefully | |
2982 | * proceed for compat with container envs, and just use the final dir | |
2983 | * as is. */ | |
2984 | ||
2985 | workspace_mounted = false; | |
2986 | break; | |
2987 | } | |
2988 | ||
2989 | /* Make the new bind mount writable (i.e. drop MS_RDONLY) */ | |
21935150 LP |
2990 | r = mount_nofollow_verbose(LOG_DEBUG, NULL, workspace, NULL, MS_BIND|MS_REMOUNT|MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL); |
2991 | if (r < 0) | |
2992 | return r; | |
bb0c0d6f LP |
2993 | |
2994 | workspace_mounted = true; | |
2995 | break; | |
2996 | } | |
2997 | } | |
2998 | } | |
2999 | ||
3000 | assert(!must_mount || workspace_mounted > 0); | |
3001 | where = workspace_mounted ? workspace : final; | |
3002 | ||
e3a0a862 CG |
3003 | (void) label_fix_container(where, final, 0); |
3004 | ||
d3dcf4e3 | 3005 | r = acquire_credentials(context, params, unit, where, uid, workspace_mounted); |
bb0c0d6f LP |
3006 | if (r < 0) |
3007 | return r; | |
3008 | ||
3009 | if (workspace_mounted) { | |
3010 | /* Make workspace read-only now, so that any bind mount we make from it defaults to read-only too */ | |
21935150 LP |
3011 | r = mount_nofollow_verbose(LOG_DEBUG, NULL, workspace, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY|MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL); |
3012 | if (r < 0) | |
3013 | return r; | |
bb0c0d6f LP |
3014 | |
3015 | /* And mount it to the final place, read-only */ | |
21935150 LP |
3016 | if (final_mounted) |
3017 | r = umount_verbose(LOG_DEBUG, workspace, MNT_DETACH|UMOUNT_NOFOLLOW); | |
3018 | else | |
3019 | r = mount_nofollow_verbose(LOG_DEBUG, workspace, final, NULL, MS_MOVE, NULL); | |
3020 | if (r < 0) | |
3021 | return r; | |
bb0c0d6f LP |
3022 | } else { |
3023 | _cleanup_free_ char *parent = NULL; | |
3024 | ||
3025 | /* If we do not have our own mount put used the plain directory fallback, then we need to | |
3026 | * open access to the top-level credential directory and the per-service directory now */ | |
3027 | ||
3028 | parent = dirname_malloc(final); | |
3029 | if (!parent) | |
3030 | return -ENOMEM; | |
3031 | if (chmod(parent, 0755) < 0) | |
3032 | return -errno; | |
3033 | } | |
3034 | ||
3035 | return 0; | |
3036 | } | |
3037 | ||
3038 | static int setup_credentials( | |
3039 | const ExecContext *context, | |
3040 | const ExecParameters *params, | |
3041 | const char *unit, | |
3042 | uid_t uid) { | |
3043 | ||
3044 | _cleanup_free_ char *p = NULL, *q = NULL; | |
bb0c0d6f LP |
3045 | int r; |
3046 | ||
3047 | assert(context); | |
3048 | assert(params); | |
3049 | ||
3050 | if (!exec_context_has_credentials(context)) | |
3051 | return 0; | |
3052 | ||
3053 | if (!params->prefix[EXEC_DIRECTORY_RUNTIME]) | |
3054 | return -EINVAL; | |
3055 | ||
3056 | /* This where we'll place stuff when we are done; this main credentials directory is world-readable, | |
3057 | * and the subdir we mount over with a read-only file system readable by the service's user */ | |
3058 | q = path_join(params->prefix[EXEC_DIRECTORY_RUNTIME], "credentials"); | |
3059 | if (!q) | |
3060 | return -ENOMEM; | |
3061 | ||
3062 | r = mkdir_label(q, 0755); /* top-level dir: world readable/searchable */ | |
3063 | if (r < 0 && r != -EEXIST) | |
3064 | return r; | |
3065 | ||
3066 | p = path_join(q, unit); | |
3067 | if (!p) | |
3068 | return -ENOMEM; | |
3069 | ||
3070 | r = mkdir_label(p, 0700); /* per-unit dir: private to user */ | |
3071 | if (r < 0 && r != -EEXIST) | |
3072 | return r; | |
3073 | ||
3074 | r = safe_fork("(sd-mkdcreds)", FORK_DEATHSIG|FORK_WAIT|FORK_NEW_MOUNTNS, NULL); | |
3075 | if (r < 0) { | |
3076 | _cleanup_free_ char *t = NULL, *u = NULL; | |
3077 | ||
3078 | /* If this is not a privilege or support issue then propagate the error */ | |
3079 | if (!ERRNO_IS_NOT_SUPPORTED(r) && !ERRNO_IS_PRIVILEGE(r)) | |
3080 | return r; | |
3081 | ||
3082 | /* Temporary workspace, that remains inaccessible all the time. We prepare stuff there before moving | |
3083 | * it into place, so that users can't access half-initialized credential stores. */ | |
3084 | t = path_join(params->prefix[EXEC_DIRECTORY_RUNTIME], "systemd/temporary-credentials"); | |
3085 | if (!t) | |
3086 | return -ENOMEM; | |
3087 | ||
3088 | /* We can't set up a mount namespace. In that case operate on a fixed, inaccessible per-unit | |
3089 | * directory outside of /run/credentials/ first, and then move it over to /run/credentials/ | |
3090 | * after it is fully set up */ | |
3091 | u = path_join(t, unit); | |
3092 | if (!u) | |
3093 | return -ENOMEM; | |
3094 | ||
3095 | FOREACH_STRING(i, t, u) { | |
3096 | r = mkdir_label(i, 0700); | |
3097 | if (r < 0 && r != -EEXIST) | |
3098 | return r; | |
3099 | } | |
3100 | ||
3101 | r = setup_credentials_internal( | |
3102 | context, | |
3103 | params, | |
d3dcf4e3 | 3104 | unit, |
bb0c0d6f LP |
3105 | p, /* final mount point */ |
3106 | u, /* temporary workspace to overmount */ | |
3107 | true, /* reuse the workspace if it is already a mount */ | |
3108 | false, /* it's OK to fall back to a plain directory if we can't mount anything */ | |
3109 | uid); | |
3110 | ||
3111 | (void) rmdir(u); /* remove the workspace again if we can. */ | |
3112 | ||
3113 | if (r < 0) | |
3114 | return r; | |
3115 | ||
3116 | } else if (r == 0) { | |
3117 | ||
3118 | /* We managed to set up a mount namespace, and are now in a child. That's great. In this case | |
3119 | * we can use the same directory for all cases, after turning off propagation. Question | |
3120 | * though is: where do we turn off propagation exactly, and where do we place the workspace | |
3121 | * directory? We need some place that is guaranteed to be a mount point in the host, and | |
3122 | * which is guaranteed to have a subdir we can mount over. /run/ is not suitable for this, | |
3123 | * since we ultimately want to move the resulting file system there, i.e. we need propagation | |
3124 | * for /run/ eventually. We could use our own /run/systemd/bind mount on itself, but that | |
3125 | * would be visible in the host mount table all the time, which we want to avoid. Hence, what | |
3126 | * we do here instead we use /dev/ and /dev/shm/ for our purposes. We know for sure that | |
3127 | * /dev/ is a mount point and we now for sure that /dev/shm/ exists. Hence we can turn off | |
3128 | * propagation on the former, and then overmount the latter. | |
3129 | * | |
3130 | * Yes it's nasty playing games with /dev/ and /dev/shm/ like this, since it does not exist | |
3131 | * for this purpose, but there are few other candidates that work equally well for us, and | |
3132 | * given that the we do this in a privately namespaced short-lived single-threaded process | |
7802194a | 3133 | * that no one else sees this should be OK to do. */ |
bb0c0d6f | 3134 | |
21935150 LP |
3135 | r = mount_nofollow_verbose(LOG_DEBUG, NULL, "/dev", NULL, MS_SLAVE|MS_REC, NULL); /* Turn off propagation from our namespace to host */ |
3136 | if (r < 0) | |
bb0c0d6f LP |
3137 | goto child_fail; |
3138 | ||
3139 | r = setup_credentials_internal( | |
3140 | context, | |
3141 | params, | |
d3dcf4e3 | 3142 | unit, |
bb0c0d6f LP |
3143 | p, /* final mount point */ |
3144 | "/dev/shm", /* temporary workspace to overmount */ | |
3145 | false, /* do not reuse /dev/shm if it is already a mount, under no circumstances */ | |
3146 | true, /* insist that something is mounted, do not allow fallback to plain directory */ | |
3147 | uid); | |
3148 | if (r < 0) | |
3149 | goto child_fail; | |
3150 | ||
3151 | _exit(EXIT_SUCCESS); | |
3152 | ||
3153 | child_fail: | |
3154 | _exit(EXIT_FAILURE); | |
3155 | } | |
3156 | ||
3157 | return 0; | |
3158 | } | |
3159 | ||
92b423b9 | 3160 | #if ENABLE_SMACK |
cefc33ae LP |
3161 | static int setup_smack( |
3162 | const ExecContext *context, | |
b83d5050 | 3163 | int executable_fd) { |
cefc33ae LP |
3164 | int r; |
3165 | ||
3166 | assert(context); | |
b83d5050 | 3167 | assert(executable_fd >= 0); |
cefc33ae | 3168 | |
cefc33ae LP |
3169 | if (context->smack_process_label) { |
3170 | r = mac_smack_apply_pid(0, context->smack_process_label); | |
3171 | if (r < 0) | |
3172 | return r; | |
3173 | } | |
3174 | #ifdef SMACK_DEFAULT_PROCESS_LABEL | |
3175 | else { | |
3176 | _cleanup_free_ char *exec_label = NULL; | |
3177 | ||
b83d5050 | 3178 | r = mac_smack_read_fd(executable_fd, SMACK_ATTR_EXEC, &exec_label); |
4c701096 | 3179 | if (r < 0 && !IN_SET(r, -ENODATA, -EOPNOTSUPP)) |
cefc33ae LP |
3180 | return r; |
3181 | ||
3182 | r = mac_smack_apply_pid(0, exec_label ? : SMACK_DEFAULT_PROCESS_LABEL); | |
3183 | if (r < 0) | |
3184 | return r; | |
3185 | } | |
cefc33ae LP |
3186 | #endif |
3187 | ||
3188 | return 0; | |
3189 | } | |
92b423b9 | 3190 | #endif |
cefc33ae | 3191 | |
6c47cd7d LP |
3192 | static int compile_bind_mounts( |
3193 | const ExecContext *context, | |
3194 | const ExecParameters *params, | |
3195 | BindMount **ret_bind_mounts, | |
da6053d0 | 3196 | size_t *ret_n_bind_mounts, |
6c47cd7d LP |
3197 | char ***ret_empty_directories) { |
3198 | ||
3199 | _cleanup_strv_free_ char **empty_directories = NULL; | |
3200 | BindMount *bind_mounts; | |
5b10116e | 3201 | size_t n, h = 0; |
6c47cd7d LP |
3202 | int r; |
3203 | ||
3204 | assert(context); | |
3205 | assert(params); | |
3206 | assert(ret_bind_mounts); | |
3207 | assert(ret_n_bind_mounts); | |
3208 | assert(ret_empty_directories); | |
3209 | ||
3210 | n = context->n_bind_mounts; | |
5b10116e | 3211 | for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) { |
6c47cd7d LP |
3212 | if (!params->prefix[t]) |
3213 | continue; | |
3214 | ||
211a3d87 | 3215 | n += context->directories[t].n_items; |
6c47cd7d LP |
3216 | } |
3217 | ||
3218 | if (n <= 0) { | |
3219 | *ret_bind_mounts = NULL; | |
3220 | *ret_n_bind_mounts = 0; | |
3221 | *ret_empty_directories = NULL; | |
3222 | return 0; | |
3223 | } | |
3224 | ||
3225 | bind_mounts = new(BindMount, n); | |
3226 | if (!bind_mounts) | |
3227 | return -ENOMEM; | |
3228 | ||
5b10116e | 3229 | for (size_t i = 0; i < context->n_bind_mounts; i++) { |
6c47cd7d LP |
3230 | BindMount *item = context->bind_mounts + i; |
3231 | char *s, *d; | |
3232 | ||
3233 | s = strdup(item->source); | |
3234 | if (!s) { | |
3235 | r = -ENOMEM; | |
3236 | goto finish; | |
3237 | } | |
3238 | ||
3239 | d = strdup(item->destination); | |
3240 | if (!d) { | |
3241 | free(s); | |
3242 | r = -ENOMEM; | |
3243 | goto finish; | |
3244 | } | |
3245 | ||
3246 | bind_mounts[h++] = (BindMount) { | |
3247 | .source = s, | |
3248 | .destination = d, | |
3249 | .read_only = item->read_only, | |
3250 | .recursive = item->recursive, | |
3251 | .ignore_enoent = item->ignore_enoent, | |
3252 | }; | |
3253 | } | |
3254 | ||
5b10116e | 3255 | for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) { |
6c47cd7d LP |
3256 | if (!params->prefix[t]) |
3257 | continue; | |
3258 | ||
211a3d87 | 3259 | if (context->directories[t].n_items == 0) |
6c47cd7d LP |
3260 | continue; |
3261 | ||
494d0247 | 3262 | if (exec_directory_is_private(context, t) && |
74e12520 | 3263 | !exec_context_with_rootfs(context)) { |
6c47cd7d LP |
3264 | char *private_root; |
3265 | ||
3266 | /* So this is for a dynamic user, and we need to make sure the process can access its own | |
3267 | * directory. For that we overmount the usually inaccessible "private" subdirectory with a | |
3268 | * tmpfs that makes it accessible and is empty except for the submounts we do this for. */ | |
3269 | ||
657ee2d8 | 3270 | private_root = path_join(params->prefix[t], "private"); |
6c47cd7d LP |
3271 | if (!private_root) { |
3272 | r = -ENOMEM; | |
3273 | goto finish; | |
3274 | } | |
3275 | ||
3276 | r = strv_consume(&empty_directories, private_root); | |
a635a7ae | 3277 | if (r < 0) |
6c47cd7d | 3278 | goto finish; |
6c47cd7d LP |
3279 | } |
3280 | ||
211a3d87 | 3281 | for (size_t i = 0; i < context->directories[t].n_items; i++) { |
6c47cd7d LP |
3282 | char *s, *d; |
3283 | ||
494d0247 | 3284 | if (exec_directory_is_private(context, t)) |
211a3d87 | 3285 | s = path_join(params->prefix[t], "private", context->directories[t].items[i].path); |
6c47cd7d | 3286 | else |
211a3d87 | 3287 | s = path_join(params->prefix[t], context->directories[t].items[i].path); |
6c47cd7d LP |
3288 | if (!s) { |
3289 | r = -ENOMEM; | |
3290 | goto finish; | |
3291 | } | |
3292 | ||
494d0247 | 3293 | if (exec_directory_is_private(context, t) && |
74e12520 | 3294 | exec_context_with_rootfs(context)) |
5609f688 YW |
3295 | /* When RootDirectory= or RootImage= are set, then the symbolic link to the private |
3296 | * directory is not created on the root directory. So, let's bind-mount the directory | |
3297 | * on the 'non-private' place. */ | |
211a3d87 | 3298 | d = path_join(params->prefix[t], context->directories[t].items[i].path); |
5609f688 YW |
3299 | else |
3300 | d = strdup(s); | |
6c47cd7d LP |
3301 | if (!d) { |
3302 | free(s); | |
3303 | r = -ENOMEM; | |
3304 | goto finish; | |
3305 | } | |
3306 | ||
3307 | bind_mounts[h++] = (BindMount) { | |
3308 | .source = s, | |
3309 | .destination = d, | |
3310 | .read_only = false, | |
9ce4e4b0 | 3311 | .nosuid = context->dynamic_user, /* don't allow suid/sgid when DynamicUser= is on */ |
6c47cd7d LP |
3312 | .recursive = true, |
3313 | .ignore_enoent = false, | |
3314 | }; | |
3315 | } | |
3316 | } | |
3317 | ||
3318 | assert(h == n); | |
3319 | ||
3320 | *ret_bind_mounts = bind_mounts; | |
3321 | *ret_n_bind_mounts = n; | |
ae2a15bc | 3322 | *ret_empty_directories = TAKE_PTR(empty_directories); |
6c47cd7d LP |
3323 | |
3324 | return (int) n; | |
3325 | ||
3326 | finish: | |
3327 | bind_mount_free_many(bind_mounts, h); | |
3328 | return r; | |
3329 | } | |
3330 | ||
df61e79a LB |
3331 | /* ret_symlinks will contain a list of pairs src:dest that describes |
3332 | * the symlinks to create later on. For example, the symlinks needed | |
3333 | * to safely give private directories to DynamicUser=1 users. */ | |
3334 | static int compile_symlinks( | |
3335 | const ExecContext *context, | |
3336 | const ExecParameters *params, | |
3337 | char ***ret_symlinks) { | |
3338 | ||
3339 | _cleanup_strv_free_ char **symlinks = NULL; | |
3340 | int r; | |
3341 | ||
3342 | assert(context); | |
3343 | assert(params); | |
3344 | assert(ret_symlinks); | |
3345 | ||
3346 | for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) { | |
211a3d87 LB |
3347 | for (size_t i = 0; i < context->directories[dt].n_items; i++) { |
3348 | _cleanup_free_ char *private_path = NULL, *path = NULL; | |
df61e79a | 3349 | |
211a3d87 LB |
3350 | STRV_FOREACH(symlink, context->directories[dt].items[i].symlinks) { |
3351 | _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL; | |
df61e79a | 3352 | |
211a3d87 LB |
3353 | src_abs = path_join(params->prefix[dt], context->directories[dt].items[i].path); |
3354 | dst_abs = path_join(params->prefix[dt], *symlink); | |
3355 | if (!src_abs || !dst_abs) | |
3356 | return -ENOMEM; | |
df61e79a | 3357 | |
211a3d87 LB |
3358 | r = strv_consume_pair(&symlinks, TAKE_PTR(src_abs), TAKE_PTR(dst_abs)); |
3359 | if (r < 0) | |
3360 | return r; | |
3361 | } | |
3362 | ||
3fa80e5e | 3363 | if (!exec_directory_is_private(context, dt) || exec_context_with_rootfs(context)) |
211a3d87 LB |
3364 | continue; |
3365 | ||
3366 | private_path = path_join(params->prefix[dt], "private", context->directories[dt].items[i].path); | |
df61e79a LB |
3367 | if (!private_path) |
3368 | return -ENOMEM; | |
3369 | ||
211a3d87 | 3370 | path = path_join(params->prefix[dt], context->directories[dt].items[i].path); |
df61e79a LB |
3371 | if (!path) |
3372 | return -ENOMEM; | |
3373 | ||
3374 | r = strv_consume_pair(&symlinks, TAKE_PTR(private_path), TAKE_PTR(path)); | |
3375 | if (r < 0) | |
3376 | return r; | |
3377 | } | |
3378 | } | |
3379 | ||
3380 | *ret_symlinks = TAKE_PTR(symlinks); | |
3381 | ||
3382 | return 0; | |
3383 | } | |
3384 | ||
4e677599 LP |
3385 | static bool insist_on_sandboxing( |
3386 | const ExecContext *context, | |
3387 | const char *root_dir, | |
3388 | const char *root_image, | |
3389 | const BindMount *bind_mounts, | |
3390 | size_t n_bind_mounts) { | |
3391 | ||
4e677599 LP |
3392 | assert(context); |
3393 | assert(n_bind_mounts == 0 || bind_mounts); | |
3394 | ||
3395 | /* Checks whether we need to insist on fs namespacing. i.e. whether we have settings configured that | |
86b52a39 | 3396 | * would alter the view on the file system beyond making things read-only or invisible, i.e. would |
4e677599 LP |
3397 | * rearrange stuff in a way we cannot ignore gracefully. */ |
3398 | ||
3399 | if (context->n_temporary_filesystems > 0) | |
3400 | return true; | |
3401 | ||
3402 | if (root_dir || root_image) | |
3403 | return true; | |
3404 | ||
b3d13314 LB |
3405 | if (context->n_mount_images > 0) |
3406 | return true; | |
3407 | ||
4e677599 LP |
3408 | if (context->dynamic_user) |
3409 | return true; | |
3410 | ||
4355c04f LB |
3411 | if (context->n_extension_images > 0 || !strv_isempty(context->extension_directories)) |
3412 | return true; | |
3413 | ||
4e677599 LP |
3414 | /* If there are any bind mounts set that don't map back onto themselves, fs namespacing becomes |
3415 | * essential. */ | |
5b10116e | 3416 | for (size_t i = 0; i < n_bind_mounts; i++) |
4e677599 LP |
3417 | if (!path_equal(bind_mounts[i].source, bind_mounts[i].destination)) |
3418 | return true; | |
3419 | ||
91dd5f7c LP |
3420 | if (context->log_namespace) |
3421 | return true; | |
3422 | ||
4e677599 LP |
3423 | return false; |
3424 | } | |
3425 | ||
6818c54c | 3426 | static int apply_mount_namespace( |
34cf6c43 | 3427 | const Unit *u, |
9f71ba8d | 3428 | ExecCommandFlags command_flags, |
6818c54c LP |
3429 | const ExecContext *context, |
3430 | const ExecParameters *params, | |
7cc5ef5f ZJS |
3431 | const ExecRuntime *runtime, |
3432 | char **error_path) { | |
6818c54c | 3433 | |
df61e79a | 3434 | _cleanup_strv_free_ char **empty_directories = NULL, **symlinks = NULL; |
56a13a49 | 3435 | const char *tmp_dir = NULL, *var_tmp_dir = NULL; |
915e6d16 | 3436 | const char *root_dir = NULL, *root_image = NULL; |
24759d8f LB |
3437 | _cleanup_free_ char *creds_path = NULL, *incoming_dir = NULL, *propagate_dir = NULL, |
3438 | *extension_dir = NULL; | |
228af36f | 3439 | NamespaceInfo ns_info; |
165a31c0 | 3440 | bool needs_sandboxing; |
6c47cd7d | 3441 | BindMount *bind_mounts = NULL; |
da6053d0 | 3442 | size_t n_bind_mounts = 0; |
6818c54c | 3443 | int r; |
93c6bb51 | 3444 | |
2b3c1b9e DH |
3445 | assert(context); |
3446 | ||
915e6d16 LP |
3447 | if (params->flags & EXEC_APPLY_CHROOT) { |
3448 | root_image = context->root_image; | |
3449 | ||
3450 | if (!root_image) | |
3451 | root_dir = context->root_directory; | |
3452 | } | |
93c6bb51 | 3453 | |
6c47cd7d LP |
3454 | r = compile_bind_mounts(context, params, &bind_mounts, &n_bind_mounts, &empty_directories); |
3455 | if (r < 0) | |
3456 | return r; | |
3457 | ||
211a3d87 | 3458 | /* Symlinks for exec dirs are set up after other mounts, before they are made read-only. */ |
df61e79a LB |
3459 | r = compile_symlinks(context, params, &symlinks); |
3460 | if (r < 0) | |
3461 | return r; | |
3462 | ||
9f71ba8d | 3463 | needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command_flags & EXEC_COMMAND_FULLY_PRIVILEGED); |
ecf63c91 NJ |
3464 | if (needs_sandboxing) { |
3465 | /* The runtime struct only contains the parent of the private /tmp, | |
3466 | * which is non-accessible to world users. Inside of it there's a /tmp | |
56a13a49 ZJS |
3467 | * that is sticky, and that's the one we want to use here. |
3468 | * This does not apply when we are using /run/systemd/empty as fallback. */ | |
ecf63c91 NJ |
3469 | |
3470 | if (context->private_tmp && runtime) { | |
56a13a49 ZJS |
3471 | if (streq_ptr(runtime->tmp_dir, RUN_SYSTEMD_EMPTY)) |
3472 | tmp_dir = runtime->tmp_dir; | |
3473 | else if (runtime->tmp_dir) | |
3474 | tmp_dir = strjoina(runtime->tmp_dir, "/tmp"); | |
3475 | ||
3476 | if (streq_ptr(runtime->var_tmp_dir, RUN_SYSTEMD_EMPTY)) | |
3477 | var_tmp_dir = runtime->var_tmp_dir; | |
f63ef937 | 3478 | else if (runtime->var_tmp_dir) |
56a13a49 | 3479 | var_tmp_dir = strjoina(runtime->var_tmp_dir, "/tmp"); |
ecf63c91 NJ |
3480 | } |
3481 | ||
b5a33299 YW |
3482 | ns_info = (NamespaceInfo) { |
3483 | .ignore_protect_paths = false, | |
3484 | .private_dev = context->private_devices, | |
3485 | .protect_control_groups = context->protect_control_groups, | |
3486 | .protect_kernel_tunables = context->protect_kernel_tunables, | |
3487 | .protect_kernel_modules = context->protect_kernel_modules, | |
94a7b275 | 3488 | .protect_kernel_logs = context->protect_kernel_logs, |
aecd5ac6 | 3489 | .protect_hostname = context->protect_hostname, |
5e98086d | 3490 | .mount_apivfs = exec_context_get_effective_mount_apivfs(context), |
228af36f | 3491 | .private_mounts = context->private_mounts, |
52b3d652 LP |
3492 | .protect_home = context->protect_home, |
3493 | .protect_system = context->protect_system, | |
4e399953 LP |
3494 | .protect_proc = context->protect_proc, |
3495 | .proc_subset = context->proc_subset, | |
80271a44 | 3496 | .private_ipc = context->private_ipc || context->ipc_namespace_path, |
6720e356 | 3497 | /* If NNP is on, we can turn on MS_NOSUID, since it won't have any effect anymore. */ |
5181630f | 3498 | .mount_nosuid = context->no_new_privileges && !mac_selinux_use(), |
b5a33299 | 3499 | }; |
ecf63c91 | 3500 | } else if (!context->dynamic_user && root_dir) |
228af36f LP |
3501 | /* |
3502 | * If DynamicUser=no and RootDirectory= is set then lets pass a relaxed | |
3503 | * sandbox info, otherwise enforce it, don't ignore protected paths and | |
3504 | * fail if we are enable to apply the sandbox inside the mount namespace. | |
3505 | */ | |
3506 | ns_info = (NamespaceInfo) { | |
3507 | .ignore_protect_paths = true, | |
3508 | }; | |
3509 | else | |
3510 | ns_info = (NamespaceInfo) {}; | |
b5a33299 | 3511 | |
37ed15d7 FB |
3512 | if (context->mount_flags == MS_SHARED) |
3513 | log_unit_debug(u, "shared mount propagation hidden by other fs namespacing unit settings: ignoring"); | |
3514 | ||
a631cbfa LP |
3515 | if (exec_context_has_credentials(context) && |
3516 | params->prefix[EXEC_DIRECTORY_RUNTIME] && | |
3517 | FLAGS_SET(params->flags, EXEC_WRITE_CREDENTIALS)) { | |
bbb4e7f3 | 3518 | creds_path = path_join(params->prefix[EXEC_DIRECTORY_RUNTIME], "credentials", u->id); |
8062e643 YW |
3519 | if (!creds_path) { |
3520 | r = -ENOMEM; | |
3521 | goto finalize; | |
3522 | } | |
bbb4e7f3 LP |
3523 | } |
3524 | ||
5e8deb94 LB |
3525 | if (MANAGER_IS_SYSTEM(u->manager)) { |
3526 | propagate_dir = path_join("/run/systemd/propagate/", u->id); | |
f2550b98 LP |
3527 | if (!propagate_dir) { |
3528 | r = -ENOMEM; | |
3529 | goto finalize; | |
3530 | } | |
3531 | ||
5e8deb94 | 3532 | incoming_dir = strdup("/run/systemd/incoming"); |
f2550b98 LP |
3533 | if (!incoming_dir) { |
3534 | r = -ENOMEM; | |
3535 | goto finalize; | |
3536 | } | |
24759d8f LB |
3537 | |
3538 | extension_dir = strdup("/run/systemd/unit-extensions"); | |
3539 | if (!extension_dir) { | |
3540 | r = -ENOMEM; | |
3541 | goto finalize; | |
3542 | } | |
3543 | } else | |
3544 | if (asprintf(&extension_dir, "/run/user/" UID_FMT "/systemd/unit-extensions", geteuid()) < 0) { | |
3545 | r = -ENOMEM; | |
3546 | goto finalize; | |
3547 | } | |
5e8deb94 | 3548 | |
18d73705 | 3549 | r = setup_namespace(root_dir, root_image, context->root_image_options, |
7bcef4ef | 3550 | &ns_info, context->read_write_paths, |
165a31c0 LP |
3551 | needs_sandboxing ? context->read_only_paths : NULL, |
3552 | needs_sandboxing ? context->inaccessible_paths : NULL, | |
ddc155b2 TM |
3553 | needs_sandboxing ? context->exec_paths : NULL, |
3554 | needs_sandboxing ? context->no_exec_paths : NULL, | |
6c47cd7d | 3555 | empty_directories, |
df61e79a | 3556 | symlinks, |
6c47cd7d LP |
3557 | bind_mounts, |
3558 | n_bind_mounts, | |
2abd4e38 YW |
3559 | context->temporary_filesystems, |
3560 | context->n_temporary_filesystems, | |
b3d13314 LB |
3561 | context->mount_images, |
3562 | context->n_mount_images, | |
56a13a49 ZJS |
3563 | tmp_dir, |
3564 | var_tmp_dir, | |
bbb4e7f3 | 3565 | creds_path, |
91dd5f7c | 3566 | context->log_namespace, |
915e6d16 | 3567 | context->mount_flags, |
d4d55b0d LB |
3568 | context->root_hash, context->root_hash_size, context->root_hash_path, |
3569 | context->root_hash_sig, context->root_hash_sig_size, context->root_hash_sig_path, | |
3570 | context->root_verity, | |
93f59701 LB |
3571 | context->extension_images, |
3572 | context->n_extension_images, | |
a07b9926 | 3573 | context->extension_directories, |
5e8deb94 LB |
3574 | propagate_dir, |
3575 | incoming_dir, | |
24759d8f | 3576 | extension_dir, |
3bdc25a4 | 3577 | root_dir || root_image ? params->notify_socket : NULL, |
7cc5ef5f | 3578 | error_path); |
93c6bb51 | 3579 | |
1beab8b0 | 3580 | /* If we couldn't set up the namespace this is probably due to a missing capability. setup_namespace() reports |
5238e957 | 3581 | * that with a special, recognizable error ENOANO. In this case, silently proceed, but only if exclusively |
1beab8b0 LP |
3582 | * sandboxing options were used, i.e. nothing such as RootDirectory= or BindMount= that would result in a |
3583 | * completely different execution environment. */ | |
aca835ed | 3584 | if (r == -ENOANO) { |
4e677599 LP |
3585 | if (insist_on_sandboxing( |
3586 | context, | |
3587 | root_dir, root_image, | |
3588 | bind_mounts, | |
3589 | n_bind_mounts)) { | |
3590 | log_unit_debug(u, "Failed to set up namespace, and refusing to continue since the selected namespacing options alter mount environment non-trivially.\n" | |
3591 | "Bind mounts: %zu, temporary filesystems: %zu, root directory: %s, root image: %s, dynamic user: %s", | |
3592 | n_bind_mounts, context->n_temporary_filesystems, yes_no(root_dir), yes_no(root_image), yes_no(context->dynamic_user)); | |
3593 | ||
3594 | r = -EOPNOTSUPP; | |
3595 | } else { | |
aca835ed | 3596 | log_unit_debug(u, "Failed to set up namespace, assuming containerized execution and ignoring."); |
4e677599 | 3597 | r = 0; |
aca835ed | 3598 | } |
93c6bb51 DH |
3599 | } |
3600 | ||
8062e643 | 3601 | finalize: |
4e677599 | 3602 | bind_mount_free_many(bind_mounts, n_bind_mounts); |
93c6bb51 DH |
3603 | return r; |
3604 | } | |
3605 | ||
915e6d16 LP |
3606 | static int apply_working_directory( |
3607 | const ExecContext *context, | |
3608 | const ExecParameters *params, | |
3609 | const char *home, | |
376fecf6 | 3610 | int *exit_status) { |
915e6d16 | 3611 | |
6732edab | 3612 | const char *d, *wd; |
2b3c1b9e DH |
3613 | |
3614 | assert(context); | |
376fecf6 | 3615 | assert(exit_status); |
2b3c1b9e | 3616 | |
6732edab LP |
3617 | if (context->working_directory_home) { |
3618 | ||
376fecf6 LP |
3619 | if (!home) { |
3620 | *exit_status = EXIT_CHDIR; | |
6732edab | 3621 | return -ENXIO; |
376fecf6 | 3622 | } |
6732edab | 3623 | |
2b3c1b9e | 3624 | wd = home; |
6732edab | 3625 | |
14eb3285 LP |
3626 | } else |
3627 | wd = empty_to_root(context->working_directory); | |
e7f1e7c6 | 3628 | |
fa97f630 | 3629 | if (params->flags & EXEC_APPLY_CHROOT) |
2b3c1b9e | 3630 | d = wd; |
fa97f630 | 3631 | else |
3b0e5bb5 | 3632 | d = prefix_roota(context->root_directory, wd); |
e7f1e7c6 | 3633 | |
376fecf6 LP |
3634 | if (chdir(d) < 0 && !context->working_directory_missing_ok) { |
3635 | *exit_status = EXIT_CHDIR; | |
2b3c1b9e | 3636 | return -errno; |
376fecf6 | 3637 | } |
e7f1e7c6 DH |
3638 | |
3639 | return 0; | |
3640 | } | |
3641 | ||
fa97f630 JB |
3642 | static int apply_root_directory( |
3643 | const ExecContext *context, | |
3644 | const ExecParameters *params, | |
3645 | const bool needs_mount_ns, | |
3646 | int *exit_status) { | |
3647 | ||
3648 | assert(context); | |
3649 | assert(exit_status); | |
3650 | ||
5b10116e | 3651 | if (params->flags & EXEC_APPLY_CHROOT) |
fa97f630 JB |
3652 | if (!needs_mount_ns && context->root_directory) |
3653 | if (chroot(context->root_directory) < 0) { | |
3654 | *exit_status = EXIT_CHROOT; | |
3655 | return -errno; | |
3656 | } | |
fa97f630 JB |
3657 | |
3658 | return 0; | |
3659 | } | |
3660 | ||
b1edf445 | 3661 | static int setup_keyring( |
34cf6c43 | 3662 | const Unit *u, |
b1edf445 LP |
3663 | const ExecContext *context, |
3664 | const ExecParameters *p, | |
3665 | uid_t uid, gid_t gid) { | |
3666 | ||
74dd6b51 | 3667 | key_serial_t keyring; |
e64c2d0b DJL |
3668 | int r = 0; |
3669 | uid_t saved_uid; | |
3670 | gid_t saved_gid; | |
74dd6b51 LP |
3671 | |
3672 | assert(u); | |
b1edf445 | 3673 | assert(context); |
74dd6b51 LP |
3674 | assert(p); |
3675 | ||
3676 | /* Let's set up a new per-service "session" kernel keyring for each system service. This has the benefit that | |
3677 | * each service runs with its own keyring shared among all processes of the service, but with no hook-up beyond | |
3678 | * that scope, and in particular no link to the per-UID keyring. If we don't do this the keyring will be | |
3679 | * automatically created on-demand and then linked to the per-UID keyring, by the kernel. The kernel's built-in | |
3680 | * on-demand behaviour is very appropriate for login users, but probably not so much for system services, where | |
3681 | * UIDs are not necessarily specific to a service but reused (at least in the case of UID 0). */ | |
3682 | ||
b1edf445 LP |
3683 | if (context->keyring_mode == EXEC_KEYRING_INHERIT) |
3684 | return 0; | |
3685 | ||
e64c2d0b DJL |
3686 | /* Acquiring a reference to the user keyring is nasty. We briefly change identity in order to get things set up |
3687 | * properly by the kernel. If we don't do that then we can't create it atomically, and that sucks for parallel | |
3688 | * execution. This mimics what pam_keyinit does, too. Setting up session keyring, to be owned by the right user | |
3689 | * & group is just as nasty as acquiring a reference to the user keyring. */ | |
3690 | ||
3691 | saved_uid = getuid(); | |
3692 | saved_gid = getgid(); | |
3693 | ||
3694 | if (gid_is_valid(gid) && gid != saved_gid) { | |
3695 | if (setregid(gid, -1) < 0) | |
3696 | return log_unit_error_errno(u, errno, "Failed to change GID for user keyring: %m"); | |
3697 | } | |
3698 | ||
3699 | if (uid_is_valid(uid) && uid != saved_uid) { | |
3700 | if (setreuid(uid, -1) < 0) { | |
3701 | r = log_unit_error_errno(u, errno, "Failed to change UID for user keyring: %m"); | |
3702 | goto out; | |
3703 | } | |
3704 | } | |
3705 | ||
74dd6b51 LP |
3706 | keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0); |
3707 | if (keyring == -1) { | |
3708 | if (errno == ENOSYS) | |
8002fb97 | 3709 | log_unit_debug_errno(u, errno, "Kernel keyring not supported, ignoring."); |
065b4774 | 3710 | else if (ERRNO_IS_PRIVILEGE(errno)) |
8002fb97 | 3711 | log_unit_debug_errno(u, errno, "Kernel keyring access prohibited, ignoring."); |
74dd6b51 | 3712 | else if (errno == EDQUOT) |
8002fb97 | 3713 | log_unit_debug_errno(u, errno, "Out of kernel keyrings to allocate, ignoring."); |
74dd6b51 | 3714 | else |
e64c2d0b | 3715 | r = log_unit_error_errno(u, errno, "Setting up kernel keyring failed: %m"); |
74dd6b51 | 3716 | |
e64c2d0b | 3717 | goto out; |
74dd6b51 LP |
3718 | } |
3719 | ||
e64c2d0b DJL |
3720 | /* When requested link the user keyring into the session keyring. */ |
3721 | if (context->keyring_mode == EXEC_KEYRING_SHARED) { | |
3722 | ||
3723 | if (keyctl(KEYCTL_LINK, | |
3724 | KEY_SPEC_USER_KEYRING, | |
3725 | KEY_SPEC_SESSION_KEYRING, 0, 0) < 0) { | |
3726 | r = log_unit_error_errno(u, errno, "Failed to link user keyring into session keyring: %m"); | |
3727 | goto out; | |
3728 | } | |
3729 | } | |
3730 | ||
3731 | /* Restore uid/gid back */ | |
3732 | if (uid_is_valid(uid) && uid != saved_uid) { | |
3733 | if (setreuid(saved_uid, -1) < 0) { | |
3734 | r = log_unit_error_errno(u, errno, "Failed to change UID back for user keyring: %m"); | |
3735 | goto out; | |
3736 | } | |
3737 | } | |
3738 | ||
3739 | if (gid_is_valid(gid) && gid != saved_gid) { | |
3740 | if (setregid(saved_gid, -1) < 0) | |
3741 | return log_unit_error_errno(u, errno, "Failed to change GID back for user keyring: %m"); | |
3742 | } | |
3743 | ||
3744 | /* Populate they keyring with the invocation ID by default, as original saved_uid. */ | |
b3415f5d LP |
3745 | if (!sd_id128_is_null(u->invocation_id)) { |
3746 | key_serial_t key; | |
3747 | ||
3748 | key = add_key("user", "invocation_id", &u->invocation_id, sizeof(u->invocation_id), KEY_SPEC_SESSION_KEYRING); | |
3749 | if (key == -1) | |
8002fb97 | 3750 | log_unit_debug_errno(u, errno, "Failed to add invocation ID to keyring, ignoring: %m"); |
b3415f5d LP |
3751 | else { |
3752 | if (keyctl(KEYCTL_SETPERM, key, | |
3753 | KEY_POS_VIEW|KEY_POS_READ|KEY_POS_SEARCH| | |
3754 | KEY_USR_VIEW|KEY_USR_READ|KEY_USR_SEARCH, 0, 0) < 0) | |
e64c2d0b | 3755 | r = log_unit_error_errno(u, errno, "Failed to restrict invocation ID permission: %m"); |
b3415f5d LP |
3756 | } |
3757 | } | |
3758 | ||
e64c2d0b | 3759 | out: |
37b22b3b | 3760 | /* Revert back uid & gid for the last time, and exit */ |
e64c2d0b DJL |
3761 | /* no extra logging, as only the first already reported error matters */ |
3762 | if (getuid() != saved_uid) | |
3763 | (void) setreuid(saved_uid, -1); | |
b1edf445 | 3764 | |
e64c2d0b DJL |
3765 | if (getgid() != saved_gid) |
3766 | (void) setregid(saved_gid, -1); | |
b1edf445 | 3767 | |
e64c2d0b | 3768 | return r; |
74dd6b51 LP |
3769 | } |
3770 | ||
3042bbeb | 3771 | static void append_socket_pair(int *array, size_t *n, const int pair[static 2]) { |
29206d46 LP |
3772 | assert(array); |
3773 | assert(n); | |
2caa38e9 | 3774 | assert(pair); |
29206d46 LP |
3775 | |
3776 | if (pair[0] >= 0) | |
3777 | array[(*n)++] = pair[0]; | |
3778 | if (pair[1] >= 0) | |
3779 | array[(*n)++] = pair[1]; | |
3780 | } | |
3781 | ||
a34ceba6 LP |
3782 | static int close_remaining_fds( |
3783 | const ExecParameters *params, | |
34cf6c43 YW |
3784 | const ExecRuntime *runtime, |
3785 | const DynamicCreds *dcreds, | |
00d9ef85 | 3786 | int user_lookup_fd, |
a34ceba6 | 3787 | int socket_fd, |
5b8d1f6b | 3788 | const int *fds, size_t n_fds) { |
a34ceba6 | 3789 | |
da6053d0 | 3790 | size_t n_dont_close = 0; |
00d9ef85 | 3791 | int dont_close[n_fds + 12]; |
a34ceba6 LP |
3792 | |
3793 | assert(params); | |
3794 | ||
3795 | if (params->stdin_fd >= 0) | |
3796 | dont_close[n_dont_close++] = params->stdin_fd; | |
3797 | if (params->stdout_fd >= 0) | |
3798 | dont_close[n_dont_close++] = params->stdout_fd; | |
3799 | if (params->stderr_fd >= 0) | |
3800 | dont_close[n_dont_close++] = params->stderr_fd; | |
3801 | ||
3802 | if (socket_fd >= 0) | |
3803 | dont_close[n_dont_close++] = socket_fd; | |
3804 | if (n_fds > 0) { | |
3805 | memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds); | |
3806 | n_dont_close += n_fds; | |
3807 | } | |
3808 | ||
a70581ff | 3809 | if (runtime) { |
29206d46 | 3810 | append_socket_pair(dont_close, &n_dont_close, runtime->netns_storage_socket); |
a70581ff XR |
3811 | append_socket_pair(dont_close, &n_dont_close, runtime->ipcns_storage_socket); |
3812 | } | |
29206d46 LP |
3813 | |
3814 | if (dcreds) { | |
3815 | if (dcreds->user) | |
3816 | append_socket_pair(dont_close, &n_dont_close, dcreds->user->storage_socket); | |
3817 | if (dcreds->group) | |
3818 | append_socket_pair(dont_close, &n_dont_close, dcreds->group->storage_socket); | |
a34ceba6 LP |
3819 | } |
3820 | ||
00d9ef85 LP |
3821 | if (user_lookup_fd >= 0) |
3822 | dont_close[n_dont_close++] = user_lookup_fd; | |
3823 | ||
a34ceba6 LP |
3824 | return close_all_fds(dont_close, n_dont_close); |
3825 | } | |
3826 | ||
00d9ef85 LP |
3827 | static int send_user_lookup( |
3828 | Unit *unit, | |
3829 | int user_lookup_fd, | |
3830 | uid_t uid, | |
3831 | gid_t gid) { | |
3832 | ||
3833 | assert(unit); | |
3834 | ||
3835 | /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID | |
3836 | * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was | |
3837 | * specified. */ | |
3838 | ||
3839 | if (user_lookup_fd < 0) | |
3840 | return 0; | |
3841 | ||
3842 | if (!uid_is_valid(uid) && !gid_is_valid(gid)) | |
3843 | return 0; | |
3844 | ||
3845 | if (writev(user_lookup_fd, | |
3846 | (struct iovec[]) { | |
e6a7ec4b LP |
3847 | IOVEC_INIT(&uid, sizeof(uid)), |
3848 | IOVEC_INIT(&gid, sizeof(gid)), | |
3849 | IOVEC_INIT_STRING(unit->id) }, 3) < 0) | |
00d9ef85 LP |
3850 | return -errno; |
3851 | ||
3852 | return 0; | |
3853 | } | |
3854 | ||
6732edab LP |
3855 | static int acquire_home(const ExecContext *c, uid_t uid, const char** home, char **buf) { |
3856 | int r; | |
3857 | ||
3858 | assert(c); | |
3859 | assert(home); | |
3860 | assert(buf); | |
3861 | ||
3862 | /* If WorkingDirectory=~ is set, try to acquire a usable home directory. */ | |
3863 | ||
3864 | if (*home) | |
3865 | return 0; | |
3866 | ||
3867 | if (!c->working_directory_home) | |
3868 | return 0; | |
3869 | ||
6732edab LP |
3870 | r = get_home_dir(buf); |
3871 | if (r < 0) | |
3872 | return r; | |
3873 | ||
3874 | *home = *buf; | |
3875 | return 1; | |
3876 | } | |
3877 | ||
da50b85a LP |
3878 | static int compile_suggested_paths(const ExecContext *c, const ExecParameters *p, char ***ret) { |
3879 | _cleanup_strv_free_ char ** list = NULL; | |
da50b85a LP |
3880 | int r; |
3881 | ||
3882 | assert(c); | |
3883 | assert(p); | |
3884 | assert(ret); | |
3885 | ||
3886 | assert(c->dynamic_user); | |
3887 | ||
3888 | /* Compile a list of paths that it might make sense to read the owning UID from to use as initial candidate for | |
3889 | * dynamic UID allocation, in order to save us from doing costly recursive chown()s of the special | |
3890 | * directories. */ | |
3891 | ||
5b10116e | 3892 | for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) { |
da50b85a LP |
3893 | if (t == EXEC_DIRECTORY_CONFIGURATION) |
3894 | continue; | |
3895 | ||
3896 | if (!p->prefix[t]) | |
3897 | continue; | |
3898 | ||
211a3d87 | 3899 | for (size_t i = 0; i < c->directories[t].n_items; i++) { |
da50b85a LP |
3900 | char *e; |
3901 | ||
494d0247 | 3902 | if (exec_directory_is_private(c, t)) |
211a3d87 | 3903 | e = path_join(p->prefix[t], "private", c->directories[t].items[i].path); |
494d0247 | 3904 | else |
211a3d87 | 3905 | e = path_join(p->prefix[t], c->directories[t].items[i].path); |
da50b85a LP |
3906 | if (!e) |
3907 | return -ENOMEM; | |
3908 | ||
3909 | r = strv_consume(&list, e); | |
3910 | if (r < 0) | |
3911 | return r; | |
3912 | } | |
3913 | } | |
3914 | ||
ae2a15bc | 3915 | *ret = TAKE_PTR(list); |
da50b85a LP |
3916 | |
3917 | return 0; | |
3918 | } | |
3919 | ||
78f93209 LP |
3920 | static int exec_parameters_get_cgroup_path(const ExecParameters *params, char **ret) { |
3921 | bool using_subcgroup; | |
3922 | char *p; | |
3923 | ||
3924 | assert(params); | |
3925 | assert(ret); | |
3926 | ||
3927 | if (!params->cgroup_path) | |
3928 | return -EINVAL; | |
3929 | ||
3930 | /* If we are called for a unit where cgroup delegation is on, and the payload created its own populated | |
3931 | * subcgroup (which we expect it to do, after all it asked for delegation), then we cannot place the control | |
3932 | * processes started after the main unit's process in the unit's main cgroup because it is now an inner one, | |
3933 | * and inner cgroups may not contain processes. Hence, if delegation is on, and this is a control process, | |
3934 | * let's use ".control" as subcgroup instead. Note that we do so only for ExecStartPost=, ExecReload=, | |
3935 | * ExecStop=, ExecStopPost=, i.e. for the commands where the main process is already forked. For ExecStartPre= | |
3936 | * this is not necessary, the cgroup is still empty. We distinguish these cases with the EXEC_CONTROL_CGROUP | |
3937 | * flag, which is only passed for the former statements, not for the latter. */ | |
3938 | ||
3939 | using_subcgroup = FLAGS_SET(params->flags, EXEC_CONTROL_CGROUP|EXEC_CGROUP_DELEGATE|EXEC_IS_CONTROL); | |
3940 | if (using_subcgroup) | |
657ee2d8 | 3941 | p = path_join(params->cgroup_path, ".control"); |
78f93209 LP |
3942 | else |
3943 | p = strdup(params->cgroup_path); | |
3944 | if (!p) | |
3945 | return -ENOMEM; | |
3946 | ||
3947 | *ret = p; | |
3948 | return using_subcgroup; | |
3949 | } | |
3950 | ||
e2b2fb7f MS |
3951 | static int exec_context_cpu_affinity_from_numa(const ExecContext *c, CPUSet *ret) { |
3952 | _cleanup_(cpu_set_reset) CPUSet s = {}; | |
3953 | int r; | |
3954 | ||
3955 | assert(c); | |
3956 | assert(ret); | |
3957 | ||
3958 | if (!c->numa_policy.nodes.set) { | |
3959 | log_debug("Can't derive CPU affinity mask from NUMA mask because NUMA mask is not set, ignoring"); | |
3960 | return 0; | |
3961 | } | |
3962 | ||
3963 | r = numa_to_cpu_set(&c->numa_policy, &s); | |
3964 | if (r < 0) | |
3965 | return r; | |
3966 | ||
3967 | cpu_set_reset(ret); | |
3968 | ||
3969 | return cpu_set_add_all(ret, &s); | |
3970 | } | |
3971 | ||
3972 | bool exec_context_get_cpu_affinity_from_numa(const ExecContext *c) { | |
3973 | assert(c); | |
3974 | ||
3975 | return c->cpu_affinity_from_numa; | |
3976 | } | |
3977 | ||
1da37e58 ZJS |
3978 | static int add_shifted_fd(int *fds, size_t fds_size, size_t *n_fds, int fd, int *ret_fd) { |
3979 | int r; | |
3980 | ||
3981 | assert(fds); | |
3982 | assert(n_fds); | |
3983 | assert(*n_fds < fds_size); | |
3984 | assert(ret_fd); | |
3985 | ||
3986 | if (fd < 0) { | |
3987 | *ret_fd = -1; | |
3988 | return 0; | |
3989 | } | |
3990 | ||
3991 | if (fd < 3 + (int) *n_fds) { | |
3992 | /* Let's move the fd up, so that it's outside of the fd range we will use to store | |
3993 | * the fds we pass to the process (or which are closed only during execve). */ | |
3994 | ||
3995 | r = fcntl(fd, F_DUPFD_CLOEXEC, 3 + (int) *n_fds); | |
3996 | if (r < 0) | |
3997 | return -errno; | |
3998 | ||
3999 | CLOSE_AND_REPLACE(fd, r); | |
4000 | } | |
4001 | ||
4002 | *ret_fd = fds[*n_fds] = fd; | |
4003 | (*n_fds) ++; | |
4004 | return 1; | |
4005 | } | |
4006 | ||
ff0af2a1 | 4007 | static int exec_child( |
f2341e0a | 4008 | Unit *unit, |
34cf6c43 | 4009 | const ExecCommand *command, |
ff0af2a1 LP |
4010 | const ExecContext *context, |
4011 | const ExecParameters *params, | |
4012 | ExecRuntime *runtime, | |
29206d46 | 4013 | DynamicCreds *dcreds, |
ff0af2a1 | 4014 | int socket_fd, |
2caa38e9 | 4015 | const int named_iofds[static 3], |
4c47affc | 4016 | int *fds, |
da6053d0 | 4017 | size_t n_socket_fds, |
25b583d7 | 4018 | size_t n_storage_fds, |
ff0af2a1 | 4019 | char **files_env, |
00d9ef85 | 4020 | int user_lookup_fd, |
12145637 | 4021 | int *exit_status) { |
d35fbf6b | 4022 | |
8c35c10d | 4023 | _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **joined_exec_search_path = NULL, **accum_env = NULL, **replaced_argv = NULL; |
1da37e58 | 4024 | int r, ngids = 0, exec_fd; |
4d885bd3 DH |
4025 | _cleanup_free_ gid_t *supplementary_gids = NULL; |
4026 | const char *username = NULL, *groupname = NULL; | |
5686391b | 4027 | _cleanup_free_ char *home_buffer = NULL; |
2b3c1b9e | 4028 | const char *home = NULL, *shell = NULL; |
7ca69792 | 4029 | char **final_argv = NULL; |
7bce046b LP |
4030 | dev_t journal_stream_dev = 0; |
4031 | ino_t journal_stream_ino = 0; | |
5749f855 | 4032 | bool userns_set_up = false; |
165a31c0 LP |
4033 | bool needs_sandboxing, /* Do we need to set up full sandboxing? (i.e. all namespacing, all MAC stuff, caps, yadda yadda */ |
4034 | needs_setuid, /* Do we need to do the actual setresuid()/setresgid() calls? */ | |
4035 | needs_mount_namespace, /* Do we need to set up a mount namespace for this kernel? */ | |
4036 | needs_ambient_hack; /* Do we need to apply the ambient capabilities hack? */ | |
349cc4a5 | 4037 | #if HAVE_SELINUX |
7f59dd35 | 4038 | _cleanup_free_ char *mac_selinux_context_net = NULL; |
43b1f709 | 4039 | bool use_selinux = false; |
ecfbc84f | 4040 | #endif |
f9fa32f0 | 4041 | #if ENABLE_SMACK |
43b1f709 | 4042 | bool use_smack = false; |
ecfbc84f | 4043 | #endif |
349cc4a5 | 4044 | #if HAVE_APPARMOR |
43b1f709 | 4045 | bool use_apparmor = false; |
ecfbc84f | 4046 | #endif |
5749f855 AZ |
4047 | uid_t saved_uid = getuid(); |
4048 | gid_t saved_gid = getgid(); | |
fed1e721 LP |
4049 | uid_t uid = UID_INVALID; |
4050 | gid_t gid = GID_INVALID; | |
1da37e58 ZJS |
4051 | size_t n_fds = n_socket_fds + n_storage_fds, /* fds to pass to the child */ |
4052 | n_keep_fds; /* total number of fds not to close */ | |
165a31c0 | 4053 | int secure_bits; |
afb11bf1 DG |
4054 | _cleanup_free_ gid_t *gids_after_pam = NULL; |
4055 | int ngids_after_pam = 0; | |
034c6ed7 | 4056 | |
f2341e0a | 4057 | assert(unit); |
5cb5a6ff LP |
4058 | assert(command); |
4059 | assert(context); | |
d35fbf6b | 4060 | assert(params); |
ff0af2a1 | 4061 | assert(exit_status); |
d35fbf6b | 4062 | |
69339ae9 LP |
4063 | /* Explicitly test for CVE-2021-4034 inspired invocations */ |
4064 | assert(command->path); | |
4065 | assert(!strv_isempty(command->argv)); | |
4066 | ||
d35fbf6b DM |
4067 | rename_process_from_path(command->path); |
4068 | ||
9c274488 LP |
4069 | /* We reset exactly these signals, since they are the only ones we set to SIG_IGN in the main |
4070 | * daemon. All others we leave untouched because we set them to SIG_DFL or a valid handler initially, | |
4071 | * both of which will be demoted to SIG_DFL. */ | |
ce30c8dc | 4072 | (void) default_signals(SIGNALS_CRASH_HANDLER, |
9c274488 | 4073 | SIGNALS_IGNORE); |
d35fbf6b DM |
4074 | |
4075 | if (context->ignore_sigpipe) | |
9c274488 | 4076 | (void) ignore_signals(SIGPIPE); |
d35fbf6b | 4077 | |
ff0af2a1 LP |
4078 | r = reset_signal_mask(); |
4079 | if (r < 0) { | |
4080 | *exit_status = EXIT_SIGNAL_MASK; | |
12145637 | 4081 | return log_unit_error_errno(unit, r, "Failed to set process signal mask: %m"); |
d35fbf6b | 4082 | } |
034c6ed7 | 4083 | |
d35fbf6b DM |
4084 | if (params->idle_pipe) |
4085 | do_idle_pipe_dance(params->idle_pipe); | |
4f2d528d | 4086 | |
2c027c62 LP |
4087 | /* Close fds we don't need very early to make sure we don't block init reexecution because it cannot bind its |
4088 | * sockets. Among the fds we close are the logging fds, and we want to keep them closed, so that we don't have | |
4089 | * any fds open we don't really want open during the transition. In order to make logging work, we switch the | |
4090 | * log subsystem into open_when_needed mode, so that it reopens the logs on every single log call. */ | |
ff0af2a1 | 4091 | |
d35fbf6b | 4092 | log_forget_fds(); |
2c027c62 | 4093 | log_set_open_when_needed(true); |
4f2d528d | 4094 | |
40a80078 LP |
4095 | /* In case anything used libc syslog(), close this here, too */ |
4096 | closelog(); | |
4097 | ||
b1994387 | 4098 | int keep_fds[n_fds + 3]; |
1da37e58 ZJS |
4099 | memcpy_safe(keep_fds, fds, n_fds * sizeof(int)); |
4100 | n_keep_fds = n_fds; | |
4101 | ||
4102 | r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, params->exec_fd, &exec_fd); | |
4103 | if (r < 0) { | |
4104 | *exit_status = EXIT_FDS; | |
4105 | return log_unit_error_errno(unit, r, "Failed to shift fd and set FD_CLOEXEC: %m"); | |
4106 | } | |
4107 | ||
b1994387 | 4108 | #if HAVE_LIBBPF |
46004616 ZJS |
4109 | if (unit->manager->restrict_fs) { |
4110 | int bpf_map_fd = lsm_bpf_map_restrict_fs_fd(unit); | |
b1994387 ILG |
4111 | if (bpf_map_fd < 0) { |
4112 | *exit_status = EXIT_FDS; | |
46004616 | 4113 | return log_unit_error_errno(unit, bpf_map_fd, "Failed to get restrict filesystems BPF map fd: %m"); |
b1994387 ILG |
4114 | } |
4115 | ||
4116 | r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, bpf_map_fd, &bpf_map_fd); | |
4117 | if (r < 0) { | |
4118 | *exit_status = EXIT_FDS; | |
4119 | return log_unit_error_errno(unit, r, "Failed to shift fd and set FD_CLOEXEC: %m"); | |
4120 | } | |
4121 | } | |
4122 | #endif | |
4123 | ||
1da37e58 | 4124 | r = close_remaining_fds(params, runtime, dcreds, user_lookup_fd, socket_fd, keep_fds, n_keep_fds); |
ff0af2a1 LP |
4125 | if (r < 0) { |
4126 | *exit_status = EXIT_FDS; | |
12145637 | 4127 | return log_unit_error_errno(unit, r, "Failed to close unwanted file descriptors: %m"); |
8c7be95e LP |
4128 | } |
4129 | ||
0af07108 ZJS |
4130 | if (!context->same_pgrp && |
4131 | setsid() < 0) { | |
4132 | *exit_status = EXIT_SETSID; | |
4133 | return log_unit_error_errno(unit, errno, "Failed to create new process session: %m"); | |
4134 | } | |
9e2f7c11 | 4135 | |
1e22b5cd | 4136 | exec_context_tty_reset(context, params); |
d35fbf6b | 4137 | |
c891efaf | 4138 | if (unit_shall_confirm_spawn(unit)) { |
3b20f877 FB |
4139 | _cleanup_free_ char *cmdline = NULL; |
4140 | ||
4ef15008 | 4141 | cmdline = quote_command_line(command->argv, SHELL_ESCAPE_EMPTY); |
3b20f877 | 4142 | if (!cmdline) { |
0460aa5c | 4143 | *exit_status = EXIT_MEMORY; |
12145637 | 4144 | return log_oom(); |
3b20f877 | 4145 | } |
d35fbf6b | 4146 | |
4ef15008 | 4147 | r = ask_for_confirmation(context, params->confirm_spawn, unit, cmdline); |
3b20f877 FB |
4148 | if (r != CONFIRM_EXECUTE) { |
4149 | if (r == CONFIRM_PRETEND_SUCCESS) { | |
4150 | *exit_status = EXIT_SUCCESS; | |
4151 | return 0; | |
4152 | } | |
ff0af2a1 | 4153 | *exit_status = EXIT_CONFIRM; |
0af07108 ZJS |
4154 | return log_unit_error_errno(unit, SYNTHETIC_ERRNO(ECANCELED), |
4155 | "Execution cancelled by the user"); | |
d35fbf6b DM |
4156 | } |
4157 | } | |
1a63a750 | 4158 | |
d521916d LP |
4159 | /* We are about to invoke NSS and PAM modules. Let's tell them what we are doing here, maybe they care. This is |
4160 | * used by nss-resolve to disable itself when we are about to start systemd-resolved, to avoid deadlocks. Note | |
4161 | * that these env vars do not survive the execve(), which means they really only apply to the PAM and NSS | |
4162 | * invocations themselves. Also note that while we'll only invoke NSS modules involved in user management they | |
4163 | * might internally call into other NSS modules that are involved in hostname resolution, we never know. */ | |
4164 | if (setenv("SYSTEMD_ACTIVATION_UNIT", unit->id, true) != 0 || | |
4165 | setenv("SYSTEMD_ACTIVATION_SCOPE", MANAGER_IS_SYSTEM(unit->manager) ? "system" : "user", true) != 0) { | |
4166 | *exit_status = EXIT_MEMORY; | |
4167 | return log_unit_error_errno(unit, errno, "Failed to update environment: %m"); | |
4168 | } | |
4169 | ||
29206d46 | 4170 | if (context->dynamic_user && dcreds) { |
da50b85a | 4171 | _cleanup_strv_free_ char **suggested_paths = NULL; |
29206d46 | 4172 | |
d521916d | 4173 | /* On top of that, make sure we bypass our own NSS module nss-systemd comprehensively for any NSS |
7802194a | 4174 | * checks, if DynamicUser=1 is used, as we shouldn't create a feedback loop with ourselves here. */ |
409093fe LP |
4175 | if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) { |
4176 | *exit_status = EXIT_USER; | |
12145637 | 4177 | return log_unit_error_errno(unit, errno, "Failed to update environment: %m"); |
409093fe LP |
4178 | } |
4179 | ||
da50b85a LP |
4180 | r = compile_suggested_paths(context, params, &suggested_paths); |
4181 | if (r < 0) { | |
4182 | *exit_status = EXIT_MEMORY; | |
4183 | return log_oom(); | |
4184 | } | |
4185 | ||
4186 | r = dynamic_creds_realize(dcreds, suggested_paths, &uid, &gid); | |
ff0af2a1 LP |
4187 | if (r < 0) { |
4188 | *exit_status = EXIT_USER; | |
d85ff944 YW |
4189 | if (r == -EILSEQ) |
4190 | return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP), | |
4191 | "Failed to update dynamic user credentials: User or group with specified name already exists."); | |
12145637 | 4192 | return log_unit_error_errno(unit, r, "Failed to update dynamic user credentials: %m"); |
524daa8c | 4193 | } |
524daa8c | 4194 | |
70dd455c | 4195 | if (!uid_is_valid(uid)) { |
29206d46 | 4196 | *exit_status = EXIT_USER; |
d85ff944 | 4197 | return log_unit_error_errno(unit, SYNTHETIC_ERRNO(ESRCH), "UID validation failed for \""UID_FMT"\"", uid); |
70dd455c ZJS |
4198 | } |
4199 | ||
4200 | if (!gid_is_valid(gid)) { | |
4201 | *exit_status = EXIT_USER; | |
d85ff944 | 4202 | return log_unit_error_errno(unit, SYNTHETIC_ERRNO(ESRCH), "GID validation failed for \""GID_FMT"\"", gid); |
29206d46 | 4203 | } |
5bc7452b | 4204 | |
29206d46 LP |
4205 | if (dcreds->user) |
4206 | username = dcreds->user->name; | |
4207 | ||
4208 | } else { | |
4d885bd3 DH |
4209 | r = get_fixed_user(context, &username, &uid, &gid, &home, &shell); |
4210 | if (r < 0) { | |
4211 | *exit_status = EXIT_USER; | |
12145637 | 4212 | return log_unit_error_errno(unit, r, "Failed to determine user credentials: %m"); |
5bc7452b | 4213 | } |
5bc7452b | 4214 | |
4d885bd3 DH |
4215 | r = get_fixed_group(context, &groupname, &gid); |
4216 | if (r < 0) { | |
4217 | *exit_status = EXIT_GROUP; | |
12145637 | 4218 | return log_unit_error_errno(unit, r, "Failed to determine group credentials: %m"); |
4d885bd3 | 4219 | } |
cdc5d5c5 | 4220 | } |
29206d46 | 4221 | |
cdc5d5c5 DH |
4222 | /* Initialize user supplementary groups and get SupplementaryGroups= ones */ |
4223 | r = get_supplementary_groups(context, username, groupname, gid, | |
4224 | &supplementary_gids, &ngids); | |
4225 | if (r < 0) { | |
4226 | *exit_status = EXIT_GROUP; | |
12145637 | 4227 | return log_unit_error_errno(unit, r, "Failed to determine supplementary groups: %m"); |
29206d46 | 4228 | } |
5bc7452b | 4229 | |
00d9ef85 LP |
4230 | r = send_user_lookup(unit, user_lookup_fd, uid, gid); |
4231 | if (r < 0) { | |
4232 | *exit_status = EXIT_USER; | |
12145637 | 4233 | return log_unit_error_errno(unit, r, "Failed to send user credentials to PID1: %m"); |
00d9ef85 LP |
4234 | } |
4235 | ||
4236 | user_lookup_fd = safe_close(user_lookup_fd); | |
4237 | ||
6732edab LP |
4238 | r = acquire_home(context, uid, &home, &home_buffer); |
4239 | if (r < 0) { | |
4240 | *exit_status = EXIT_CHDIR; | |
12145637 | 4241 | return log_unit_error_errno(unit, r, "Failed to determine $HOME for user: %m"); |
6732edab LP |
4242 | } |
4243 | ||
d35fbf6b DM |
4244 | /* If a socket is connected to STDIN/STDOUT/STDERR, we |
4245 | * must sure to drop O_NONBLOCK */ | |
4246 | if (socket_fd >= 0) | |
a34ceba6 | 4247 | (void) fd_nonblock(socket_fd, false); |
acbb0225 | 4248 | |
4c70a4a7 MS |
4249 | /* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields. |
4250 | * Hence we need to migrate to the target cgroup from init.scope before connecting to journald */ | |
4251 | if (params->cgroup_path) { | |
4252 | _cleanup_free_ char *p = NULL; | |
4253 | ||
4254 | r = exec_parameters_get_cgroup_path(params, &p); | |
4255 | if (r < 0) { | |
4256 | *exit_status = EXIT_CGROUP; | |
4257 | return log_unit_error_errno(unit, r, "Failed to acquire cgroup path: %m"); | |
4258 | } | |
4259 | ||
4260 | r = cg_attach_everywhere(params->cgroup_supported, p, 0, NULL, NULL); | |
702cf08f YW |
4261 | if (r == -EUCLEAN) { |
4262 | *exit_status = EXIT_CGROUP; | |
4263 | return log_unit_error_errno(unit, r, "Failed to attach process to cgroup %s " | |
4264 | "because the cgroup or one of its parents or " | |
4265 | "siblings is in the threaded mode: %m", p); | |
4266 | } | |
4c70a4a7 MS |
4267 | if (r < 0) { |
4268 | *exit_status = EXIT_CGROUP; | |
4269 | return log_unit_error_errno(unit, r, "Failed to attach to cgroup %s: %m", p); | |
4270 | } | |
4271 | } | |
4272 | ||
a8d08f39 | 4273 | if (context->network_namespace_path && runtime && runtime->netns_storage_socket[0] >= 0) { |
54c2459d | 4274 | r = open_shareable_ns_path(runtime->netns_storage_socket, context->network_namespace_path, CLONE_NEWNET); |
a8d08f39 LP |
4275 | if (r < 0) { |
4276 | *exit_status = EXIT_NETWORK; | |
4277 | return log_unit_error_errno(unit, r, "Failed to open network namespace path %s: %m", context->network_namespace_path); | |
4278 | } | |
4279 | } | |
4280 | ||
a70581ff XR |
4281 | if (context->ipc_namespace_path && runtime && runtime->ipcns_storage_socket[0] >= 0) { |
4282 | r = open_shareable_ns_path(runtime->ipcns_storage_socket, context->ipc_namespace_path, CLONE_NEWIPC); | |
4283 | if (r < 0) { | |
4284 | *exit_status = EXIT_NAMESPACE; | |
4285 | return log_unit_error_errno(unit, r, "Failed to open IPC namespace path %s: %m", context->ipc_namespace_path); | |
4286 | } | |
4287 | } | |
4288 | ||
52c239d7 | 4289 | r = setup_input(context, params, socket_fd, named_iofds); |
ff0af2a1 LP |
4290 | if (r < 0) { |
4291 | *exit_status = EXIT_STDIN; | |
12145637 | 4292 | return log_unit_error_errno(unit, r, "Failed to set up standard input: %m"); |
d35fbf6b | 4293 | } |
034c6ed7 | 4294 | |
52c239d7 | 4295 | 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 |
4296 | if (r < 0) { |
4297 | *exit_status = EXIT_STDOUT; | |
12145637 | 4298 | return log_unit_error_errno(unit, r, "Failed to set up standard output: %m"); |
d35fbf6b DM |
4299 | } |
4300 | ||
52c239d7 | 4301 | 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 |
4302 | if (r < 0) { |
4303 | *exit_status = EXIT_STDERR; | |
12145637 | 4304 | return log_unit_error_errno(unit, r, "Failed to set up standard error output: %m"); |
d35fbf6b DM |
4305 | } |
4306 | ||
d35fbf6b | 4307 | if (context->oom_score_adjust_set) { |
9f8168eb LP |
4308 | /* When we can't make this change due to EPERM, then let's silently skip over it. User namespaces |
4309 | * prohibit write access to this file, and we shouldn't trip up over that. */ | |
4310 | r = set_oom_score_adjust(context->oom_score_adjust); | |
065b4774 | 4311 | if (ERRNO_IS_PRIVILEGE(r)) |
f2341e0a | 4312 | log_unit_debug_errno(unit, r, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m"); |
12145637 | 4313 | else if (r < 0) { |
ff0af2a1 | 4314 | *exit_status = EXIT_OOM_ADJUST; |
12145637 | 4315 | return log_unit_error_errno(unit, r, "Failed to adjust OOM setting: %m"); |
613b411c | 4316 | } |
d35fbf6b DM |
4317 | } |
4318 | ||
ad21e542 ZJS |
4319 | if (context->coredump_filter_set) { |
4320 | r = set_coredump_filter(context->coredump_filter); | |
4321 | if (ERRNO_IS_PRIVILEGE(r)) | |
4322 | log_unit_debug_errno(unit, r, "Failed to adjust coredump_filter, ignoring: %m"); | |
4323 | else if (r < 0) | |
4324 | return log_unit_error_errno(unit, r, "Failed to adjust coredump_filter: %m"); | |
4325 | } | |
4326 | ||
39090201 DJL |
4327 | if (context->nice_set) { |
4328 | r = setpriority_closest(context->nice); | |
4329 | if (r < 0) | |
4330 | return log_unit_error_errno(unit, r, "Failed to set up process scheduling priority (nice level): %m"); | |
4331 | } | |
613b411c | 4332 | |
d35fbf6b DM |
4333 | if (context->cpu_sched_set) { |
4334 | struct sched_param param = { | |
4335 | .sched_priority = context->cpu_sched_priority, | |
4336 | }; | |
4337 | ||
ff0af2a1 LP |
4338 | r = sched_setscheduler(0, |
4339 | context->cpu_sched_policy | | |
4340 | (context->cpu_sched_reset_on_fork ? | |
4341 | SCHED_RESET_ON_FORK : 0), | |
4342 | ¶m); | |
4343 | if (r < 0) { | |
4344 | *exit_status = EXIT_SETSCHEDULER; | |
12145637 | 4345 | return log_unit_error_errno(unit, errno, "Failed to set up CPU scheduling: %m"); |
fc9b2a84 | 4346 | } |
d35fbf6b | 4347 | } |
fc9b2a84 | 4348 | |
e2b2fb7f MS |
4349 | if (context->cpu_affinity_from_numa || context->cpu_set.set) { |
4350 | _cleanup_(cpu_set_reset) CPUSet converted_cpu_set = {}; | |
4351 | const CPUSet *cpu_set; | |
4352 | ||
4353 | if (context->cpu_affinity_from_numa) { | |
4354 | r = exec_context_cpu_affinity_from_numa(context, &converted_cpu_set); | |
4355 | if (r < 0) { | |
4356 | *exit_status = EXIT_CPUAFFINITY; | |
4357 | return log_unit_error_errno(unit, r, "Failed to derive CPU affinity mask from NUMA mask: %m"); | |
4358 | } | |
4359 | ||
4360 | cpu_set = &converted_cpu_set; | |
4361 | } else | |
4362 | cpu_set = &context->cpu_set; | |
4363 | ||
4364 | if (sched_setaffinity(0, cpu_set->allocated, cpu_set->set) < 0) { | |
ff0af2a1 | 4365 | *exit_status = EXIT_CPUAFFINITY; |
12145637 | 4366 | return log_unit_error_errno(unit, errno, "Failed to set up CPU affinity: %m"); |
034c6ed7 | 4367 | } |
e2b2fb7f | 4368 | } |
034c6ed7 | 4369 | |
b070c7c0 MS |
4370 | if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) { |
4371 | r = apply_numa_policy(&context->numa_policy); | |
4372 | if (r == -EOPNOTSUPP) | |
33fe9e3f | 4373 | log_unit_debug_errno(unit, r, "NUMA support not available, ignoring."); |
b070c7c0 MS |
4374 | else if (r < 0) { |
4375 | *exit_status = EXIT_NUMA_POLICY; | |
4376 | return log_unit_error_errno(unit, r, "Failed to set NUMA memory policy: %m"); | |
4377 | } | |
4378 | } | |
4379 | ||
d35fbf6b DM |
4380 | if (context->ioprio_set) |
4381 | if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) { | |
ff0af2a1 | 4382 | *exit_status = EXIT_IOPRIO; |
12145637 | 4383 | return log_unit_error_errno(unit, errno, "Failed to set up IO scheduling priority: %m"); |
d35fbf6b | 4384 | } |
da726a4d | 4385 | |
d35fbf6b DM |
4386 | if (context->timer_slack_nsec != NSEC_INFINITY) |
4387 | if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) { | |
ff0af2a1 | 4388 | *exit_status = EXIT_TIMERSLACK; |
12145637 | 4389 | return log_unit_error_errno(unit, errno, "Failed to set up timer slack: %m"); |
4c2630eb | 4390 | } |
9eba9da4 | 4391 | |
21022b9d LP |
4392 | if (context->personality != PERSONALITY_INVALID) { |
4393 | r = safe_personality(context->personality); | |
4394 | if (r < 0) { | |
ff0af2a1 | 4395 | *exit_status = EXIT_PERSONALITY; |
12145637 | 4396 | return log_unit_error_errno(unit, r, "Failed to set up execution domain (personality): %m"); |
4c2630eb | 4397 | } |
21022b9d | 4398 | } |
94f04347 | 4399 | |
33331d11 VB |
4400 | if (context->utmp_id) { |
4401 | const char *line = context->tty_path ? | |
4402 | (path_startswith(context->tty_path, "/dev/") ?: context->tty_path) : | |
4403 | NULL; | |
df0ff127 | 4404 | utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0), |
33331d11 | 4405 | line, |
023a4f67 LP |
4406 | context->utmp_mode == EXEC_UTMP_INIT ? INIT_PROCESS : |
4407 | context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS : | |
4408 | USER_PROCESS, | |
6a93917d | 4409 | username); |
33331d11 | 4410 | } |
d35fbf6b | 4411 | |
08f67696 | 4412 | if (uid_is_valid(uid)) { |
ff0af2a1 LP |
4413 | r = chown_terminal(STDIN_FILENO, uid); |
4414 | if (r < 0) { | |
4415 | *exit_status = EXIT_STDIN; | |
12145637 | 4416 | return log_unit_error_errno(unit, r, "Failed to change ownership of terminal: %m"); |
071830ff | 4417 | } |
d35fbf6b | 4418 | } |
8e274523 | 4419 | |
4e1dfa45 | 4420 | /* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1 |
62b9bb26 | 4421 | * this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not |
4e1dfa45 | 4422 | * safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only |
62b9bb26 | 4423 | * touch a single hierarchy too. */ |
584b8688 | 4424 | if (params->cgroup_path && context->user && (params->flags & EXEC_CGROUP_DELEGATE)) { |
62b9bb26 | 4425 | r = cg_set_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, uid, gid); |
ff0af2a1 LP |
4426 | if (r < 0) { |
4427 | *exit_status = EXIT_CGROUP; | |
12145637 | 4428 | return log_unit_error_errno(unit, r, "Failed to adjust control group access: %m"); |
034c6ed7 | 4429 | } |
d35fbf6b | 4430 | } |
034c6ed7 | 4431 | |
211a3d87 LB |
4432 | needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime); |
4433 | ||
5b10116e | 4434 | for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) { |
211a3d87 | 4435 | r = setup_exec_directory(context, params, uid, gid, dt, needs_mount_namespace, exit_status); |
12145637 LP |
4436 | if (r < 0) |
4437 | return log_unit_error_errno(unit, r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]); | |
d35fbf6b | 4438 | } |
94f04347 | 4439 | |
bb0c0d6f LP |
4440 | if (FLAGS_SET(params->flags, EXEC_WRITE_CREDENTIALS)) { |
4441 | r = setup_credentials(context, params, unit->id, uid); | |
4442 | if (r < 0) { | |
4443 | *exit_status = EXIT_CREDENTIALS; | |
4444 | return log_unit_error_errno(unit, r, "Failed to set up credentials: %m"); | |
4445 | } | |
4446 | } | |
4447 | ||
7bce046b | 4448 | r = build_environment( |
fd63e712 | 4449 | unit, |
7bce046b LP |
4450 | context, |
4451 | params, | |
4452 | n_fds, | |
4453 | home, | |
4454 | username, | |
4455 | shell, | |
4456 | journal_stream_dev, | |
4457 | journal_stream_ino, | |
4458 | &our_env); | |
2065ca69 JW |
4459 | if (r < 0) { |
4460 | *exit_status = EXIT_MEMORY; | |
12145637 | 4461 | return log_oom(); |
2065ca69 JW |
4462 | } |
4463 | ||
4464 | r = build_pass_environment(context, &pass_env); | |
4465 | if (r < 0) { | |
4466 | *exit_status = EXIT_MEMORY; | |
12145637 | 4467 | return log_oom(); |
2065ca69 JW |
4468 | } |
4469 | ||
adf769b0 ZJS |
4470 | /* The $PATH variable is set to the default path in params->environment. However, this is overridden |
4471 | * if user-specified fields have $PATH set. The intention is to also override $PATH if the unit does | |
4472 | * not specify PATH but the unit has ExecSearchPath. */ | |
8c35c10d | 4473 | if (!strv_isempty(context->exec_search_path)) { |
4474 | _cleanup_free_ char *joined = NULL; | |
4475 | ||
4476 | joined = strv_join(context->exec_search_path, ":"); | |
4477 | if (!joined) { | |
4478 | *exit_status = EXIT_MEMORY; | |
4479 | return log_oom(); | |
4480 | } | |
4481 | ||
4482 | r = strv_env_assign(&joined_exec_search_path, "PATH", joined); | |
4483 | if (r < 0) { | |
4484 | *exit_status = EXIT_MEMORY; | |
4485 | return log_oom(); | |
4486 | } | |
4487 | } | |
4488 | ||
4ab3d29f | 4489 | accum_env = strv_env_merge(params->environment, |
2065ca69 | 4490 | our_env, |
8c35c10d | 4491 | joined_exec_search_path, |
2065ca69 JW |
4492 | pass_env, |
4493 | context->environment, | |
44e5d006 | 4494 | files_env); |
2065ca69 JW |
4495 | if (!accum_env) { |
4496 | *exit_status = EXIT_MEMORY; | |
12145637 | 4497 | return log_oom(); |
2065ca69 | 4498 | } |
1280503b | 4499 | accum_env = strv_env_clean(accum_env); |
2065ca69 | 4500 | |
096424d1 | 4501 | (void) umask(context->umask); |
b213e1c1 | 4502 | |
b1edf445 | 4503 | r = setup_keyring(unit, context, params, uid, gid); |
74dd6b51 LP |
4504 | if (r < 0) { |
4505 | *exit_status = EXIT_KEYRING; | |
12145637 | 4506 | return log_unit_error_errno(unit, r, "Failed to set up kernel keyring: %m"); |
74dd6b51 LP |
4507 | } |
4508 | ||
adf769b0 ZJS |
4509 | /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted |
4510 | * from it. */ | |
1703fa41 | 4511 | needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED); |
7f18ef0a | 4512 | |
adf769b0 ZJS |
4513 | /* We need the ambient capability hack, if the caller asked us to apply it and the command is marked |
4514 | * for it, and the kernel doesn't actually support ambient caps. */ | |
165a31c0 | 4515 | needs_ambient_hack = (params->flags & EXEC_APPLY_SANDBOXING) && (command->flags & EXEC_COMMAND_AMBIENT_MAGIC) && !ambient_capabilities_supported(); |
7f18ef0a | 4516 | |
adf769b0 ZJS |
4517 | /* We need setresuid() if the caller asked us to apply sandboxing and the command isn't explicitly |
4518 | * excepted from either whole sandboxing or just setresuid() itself, and the ambient hack is not | |
4519 | * desired. */ | |
165a31c0 LP |
4520 | if (needs_ambient_hack) |
4521 | needs_setuid = false; | |
4522 | else | |
4523 | needs_setuid = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & (EXEC_COMMAND_FULLY_PRIVILEGED|EXEC_COMMAND_NO_SETUID)); | |
4524 | ||
4525 | if (needs_sandboxing) { | |
adf769b0 ZJS |
4526 | /* MAC enablement checks need to be done before a new mount ns is created, as they rely on |
4527 | * /sys being present. The actual MAC context application will happen later, as late as | |
4528 | * possible, to avoid impacting our own code paths. */ | |
7f18ef0a | 4529 | |
349cc4a5 | 4530 | #if HAVE_SELINUX |
43b1f709 | 4531 | use_selinux = mac_selinux_use(); |
7f18ef0a | 4532 | #endif |
f9fa32f0 | 4533 | #if ENABLE_SMACK |
43b1f709 | 4534 | use_smack = mac_smack_use(); |
7f18ef0a | 4535 | #endif |
349cc4a5 | 4536 | #if HAVE_APPARMOR |
43b1f709 | 4537 | use_apparmor = mac_apparmor_use(); |
7f18ef0a | 4538 | #endif |
165a31c0 | 4539 | } |
7f18ef0a | 4540 | |
ce932d2d LP |
4541 | if (needs_sandboxing) { |
4542 | int which_failed; | |
4543 | ||
4544 | /* Let's set the resource limits before we call into PAM, so that pam_limits wins over what | |
4545 | * is set here. (See below.) */ | |
4546 | ||
4547 | r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed); | |
4548 | if (r < 0) { | |
4549 | *exit_status = EXIT_LIMITS; | |
4550 | return log_unit_error_errno(unit, r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed)); | |
4551 | } | |
4552 | } | |
4553 | ||
0af07108 | 4554 | if (needs_setuid && context->pam_name && username) { |
ce932d2d LP |
4555 | /* Let's call into PAM after we set up our own idea of resource limits to that pam_limits |
4556 | * wins here. (See above.) */ | |
4557 | ||
1da37e58 | 4558 | /* All fds passed in the fds array will be closed in the pam child process. */ |
0af07108 ZJS |
4559 | r = setup_pam(context->pam_name, username, uid, gid, context->tty_path, &accum_env, fds, n_fds); |
4560 | if (r < 0) { | |
4561 | *exit_status = EXIT_PAM; | |
4562 | return log_unit_error_errno(unit, r, "Failed to set up PAM session: %m"); | |
165a31c0 | 4563 | } |
ac45f971 | 4564 | |
0af07108 ZJS |
4565 | ngids_after_pam = getgroups_alloc(&gids_after_pam); |
4566 | if (ngids_after_pam < 0) { | |
4567 | *exit_status = EXIT_MEMORY; | |
4568 | return log_unit_error_errno(unit, ngids_after_pam, "Failed to obtain groups after setting up PAM: %m"); | |
5749f855 | 4569 | } |
b213e1c1 | 4570 | } |
5749f855 | 4571 | |
0af07108 | 4572 | if (needs_sandboxing && context->private_users && !have_effective_cap(CAP_SYS_ADMIN)) { |
5749f855 AZ |
4573 | /* If we're unprivileged, set up the user namespace first to enable use of the other namespaces. |
4574 | * Users with CAP_SYS_ADMIN can set up user namespaces last because they will be able to | |
4575 | * set up the all of the other namespaces (i.e. network, mount, UTS) without a user namespace. */ | |
0af07108 ZJS |
4576 | |
4577 | userns_set_up = true; | |
4578 | r = setup_private_users(saved_uid, saved_gid, uid, gid); | |
4579 | if (r < 0) { | |
4580 | *exit_status = EXIT_USER; | |
4581 | return log_unit_error_errno(unit, r, "Failed to set up user namespacing for unprivileged user: %m"); | |
5749f855 AZ |
4582 | } |
4583 | } | |
4584 | ||
a8d08f39 LP |
4585 | if ((context->private_network || context->network_namespace_path) && runtime && runtime->netns_storage_socket[0] >= 0) { |
4586 | ||
6e2d7c4f | 4587 | if (ns_type_supported(NAMESPACE_NET)) { |
54c2459d | 4588 | r = setup_shareable_ns(runtime->netns_storage_socket, CLONE_NEWNET); |
ee00d1e9 ZJS |
4589 | if (r == -EPERM) |
4590 | log_unit_warning_errno(unit, r, | |
4591 | "PrivateNetwork=yes is configured, but network namespace setup failed, ignoring: %m"); | |
4592 | else if (r < 0) { | |
6e2d7c4f MS |
4593 | *exit_status = EXIT_NETWORK; |
4594 | return log_unit_error_errno(unit, r, "Failed to set up network namespacing: %m"); | |
4595 | } | |
a8d08f39 LP |
4596 | } else if (context->network_namespace_path) { |
4597 | *exit_status = EXIT_NETWORK; | |
ee00d1e9 ZJS |
4598 | return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP), |
4599 | "NetworkNamespacePath= is not supported, refusing."); | |
6e2d7c4f MS |
4600 | } else |
4601 | log_unit_warning(unit, "PrivateNetwork=yes is configured, but the kernel does not support network namespaces, ignoring."); | |
d35fbf6b | 4602 | } |
169c1bda | 4603 | |
a70581ff XR |
4604 | if ((context->private_ipc || context->ipc_namespace_path) && runtime && runtime->ipcns_storage_socket[0] >= 0) { |
4605 | ||
4606 | if (ns_type_supported(NAMESPACE_IPC)) { | |
4607 | r = setup_shareable_ns(runtime->ipcns_storage_socket, CLONE_NEWIPC); | |
4608 | if (r == -EPERM) | |
4609 | log_unit_warning_errno(unit, r, | |
4610 | "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m"); | |
4611 | else if (r < 0) { | |
4612 | *exit_status = EXIT_NAMESPACE; | |
4613 | return log_unit_error_errno(unit, r, "Failed to set up IPC namespacing: %m"); | |
4614 | } | |
4615 | } else if (context->ipc_namespace_path) { | |
4616 | *exit_status = EXIT_NAMESPACE; | |
4617 | return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP), | |
4618 | "IPCNamespacePath= is not supported, refusing."); | |
4619 | } else | |
4620 | log_unit_warning(unit, "PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring."); | |
4621 | } | |
4622 | ||
ee818b89 | 4623 | if (needs_mount_namespace) { |
7cc5ef5f ZJS |
4624 | _cleanup_free_ char *error_path = NULL; |
4625 | ||
9f71ba8d | 4626 | r = apply_mount_namespace(unit, command->flags, context, params, runtime, &error_path); |
3fbe8dbe LP |
4627 | if (r < 0) { |
4628 | *exit_status = EXIT_NAMESPACE; | |
7cc5ef5f ZJS |
4629 | return log_unit_error_errno(unit, r, "Failed to set up mount namespacing%s%s: %m", |
4630 | error_path ? ": " : "", strempty(error_path)); | |
3fbe8dbe | 4631 | } |
d35fbf6b | 4632 | } |
81a2b7ce | 4633 | |
daf8f72b LP |
4634 | if (needs_sandboxing) { |
4635 | r = apply_protect_hostname(unit, context, exit_status); | |
4636 | if (r < 0) | |
4637 | return r; | |
aecd5ac6 TM |
4638 | } |
4639 | ||
5749f855 AZ |
4640 | /* Drop groups as early as possible. |
4641 | * This needs to be done after PrivateDevices=y setup as device nodes should be owned by the host's root. | |
4642 | * For non-root in a userns, devices will be owned by the user/group before the group change, and nobody. */ | |
165a31c0 | 4643 | if (needs_setuid) { |
afb11bf1 DG |
4644 | _cleanup_free_ gid_t *gids_to_enforce = NULL; |
4645 | int ngids_to_enforce = 0; | |
4646 | ||
4647 | ngids_to_enforce = merge_gid_lists(supplementary_gids, | |
4648 | ngids, | |
4649 | gids_after_pam, | |
4650 | ngids_after_pam, | |
4651 | &gids_to_enforce); | |
4652 | if (ngids_to_enforce < 0) { | |
4653 | *exit_status = EXIT_MEMORY; | |
4654 | return log_unit_error_errno(unit, | |
4655 | ngids_to_enforce, | |
4656 | "Failed to merge group lists. Group membership might be incorrect: %m"); | |
4657 | } | |
4658 | ||
4659 | r = enforce_groups(gid, gids_to_enforce, ngids_to_enforce); | |
096424d1 LP |
4660 | if (r < 0) { |
4661 | *exit_status = EXIT_GROUP; | |
12145637 | 4662 | return log_unit_error_errno(unit, r, "Changing group credentials failed: %m"); |
096424d1 | 4663 | } |
165a31c0 | 4664 | } |
096424d1 | 4665 | |
5749f855 AZ |
4666 | /* If the user namespace was not set up above, try to do it now. |
4667 | * It's preferred to set up the user namespace later (after all other namespaces) so as not to be | |
4668 | * restricted by rules pertaining to combining user namspaces with other namespaces (e.g. in the | |
4669 | * case of mount namespaces being less privileged when the mount point list is copied from a | |
4670 | * different user namespace). */ | |
9008e1ac | 4671 | |
5749f855 AZ |
4672 | if (needs_sandboxing && context->private_users && !userns_set_up) { |
4673 | r = setup_private_users(saved_uid, saved_gid, uid, gid); | |
4674 | if (r < 0) { | |
4675 | *exit_status = EXIT_USER; | |
4676 | return log_unit_error_errno(unit, r, "Failed to set up user namespacing: %m"); | |
d251207d LP |
4677 | } |
4678 | } | |
4679 | ||
9f71ba8d ZJS |
4680 | /* Now that the mount namespace has been set up and privileges adjusted, let's look for the thing we |
4681 | * shall execute. */ | |
4682 | ||
4683 | _cleanup_free_ char *executable = NULL; | |
b83d5050 | 4684 | _cleanup_close_ int executable_fd = -1; |
8c35c10d | 4685 | r = find_executable_full(command->path, /* root= */ NULL, context->exec_search_path, false, &executable, &executable_fd); |
9f71ba8d ZJS |
4686 | if (r < 0) { |
4687 | if (r != -ENOMEM && (command->flags & EXEC_COMMAND_IGNORE_FAILURE)) { | |
c2503e35 RH |
4688 | log_unit_struct_errno(unit, LOG_INFO, r, |
4689 | "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR, | |
4690 | LOG_UNIT_INVOCATION_ID(unit), | |
4691 | LOG_UNIT_MESSAGE(unit, "Executable %s missing, skipping: %m", | |
4692 | command->path), | |
4693 | "EXECUTABLE=%s", command->path); | |
9f71ba8d ZJS |
4694 | return 0; |
4695 | } | |
4696 | ||
4697 | *exit_status = EXIT_EXEC; | |
c2503e35 RH |
4698 | |
4699 | return log_unit_struct_errno(unit, LOG_INFO, r, | |
4700 | "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR, | |
4701 | LOG_UNIT_INVOCATION_ID(unit), | |
4702 | LOG_UNIT_MESSAGE(unit, "Failed to locate executable %s: %m", | |
4703 | command->path), | |
4704 | "EXECUTABLE=%s", command->path); | |
9f71ba8d ZJS |
4705 | } |
4706 | ||
b83d5050 ZJS |
4707 | r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, executable_fd, &executable_fd); |
4708 | if (r < 0) { | |
4709 | *exit_status = EXIT_FDS; | |
4710 | return log_unit_error_errno(unit, r, "Failed to shift fd and set FD_CLOEXEC: %m"); | |
4711 | } | |
4712 | ||
9f71ba8d | 4713 | #if HAVE_SELINUX |
49590d67 MS |
4714 | if (needs_sandboxing && use_selinux && params->selinux_context_net) { |
4715 | int fd = -1; | |
4716 | ||
4717 | if (socket_fd >= 0) | |
4718 | fd = socket_fd; | |
4719 | else if (params->n_socket_fds == 1) | |
4720 | /* If stdin is not connected to a socket but we are triggered by exactly one socket unit then we | |
4721 | * use context from that fd to compute the label. */ | |
4722 | fd = params->fds[0]; | |
4723 | ||
4724 | if (fd >= 0) { | |
4725 | r = mac_selinux_get_child_mls_label(fd, executable, context->selinux_context, &mac_selinux_context_net); | |
006d1864 TM |
4726 | if (r < 0) { |
4727 | if (!context->selinux_context_ignore) { | |
4728 | *exit_status = EXIT_SELINUX_CONTEXT; | |
4729 | return log_unit_error_errno(unit, r, "Failed to determine SELinux context: %m"); | |
4730 | } | |
4731 | log_unit_debug_errno(unit, r, "Failed to determine SELinux context, ignoring: %m"); | |
49590d67 | 4732 | } |
9f71ba8d ZJS |
4733 | } |
4734 | } | |
4735 | #endif | |
4736 | ||
165a31c0 | 4737 | /* We repeat the fd closing here, to make sure that nothing is leaked from the PAM modules. Note that we are |
a70581ff | 4738 | * more aggressive this time since socket_fd and the netns and ipcns fds we don't need anymore. We do keep the exec_fd |
5686391b LP |
4739 | * however if we have it as we want to keep it open until the final execve(). */ |
4740 | ||
1da37e58 | 4741 | r = close_all_fds(keep_fds, n_keep_fds); |
ff0af2a1 LP |
4742 | if (r >= 0) |
4743 | r = shift_fds(fds, n_fds); | |
4744 | if (r >= 0) | |
25b583d7 | 4745 | r = flags_fds(fds, n_socket_fds, n_storage_fds, context->non_blocking); |
ff0af2a1 LP |
4746 | if (r < 0) { |
4747 | *exit_status = EXIT_FDS; | |
12145637 | 4748 | return log_unit_error_errno(unit, r, "Failed to adjust passed file descriptors: %m"); |
d35fbf6b | 4749 | } |
e66cf1a3 | 4750 | |
5686391b LP |
4751 | /* At this point, the fds we want to pass to the program are all ready and set up, with O_CLOEXEC turned off |
4752 | * and at the right fd numbers. The are no other fds open, with one exception: the exec_fd if it is defined, | |
4753 | * and it has O_CLOEXEC set, after all we want it to be closed by the execve(), so that our parent knows we | |
4754 | * came this far. */ | |
4755 | ||
165a31c0 | 4756 | secure_bits = context->secure_bits; |
e66cf1a3 | 4757 | |
165a31c0 LP |
4758 | if (needs_sandboxing) { |
4759 | uint64_t bset; | |
e66cf1a3 | 4760 | |
ce932d2d LP |
4761 | /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly |
4762 | * requested. (Note this is placed after the general resource limit initialization, see | |
4763 | * above, in order to take precedence.) */ | |
f4170c67 LP |
4764 | if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) { |
4765 | if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) { | |
4766 | *exit_status = EXIT_LIMITS; | |
12145637 | 4767 | return log_unit_error_errno(unit, errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m"); |
f4170c67 LP |
4768 | } |
4769 | } | |
4770 | ||
37ac2744 JB |
4771 | #if ENABLE_SMACK |
4772 | /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the | |
4773 | * process. This is the latest place before dropping capabilities. Other MAC context are set later. */ | |
4774 | if (use_smack) { | |
b83d5050 | 4775 | r = setup_smack(context, executable_fd); |
29ff6247 | 4776 | if (r < 0 && !context->smack_process_label_ignore) { |
37ac2744 JB |
4777 | *exit_status = EXIT_SMACK_PROCESS_LABEL; |
4778 | return log_unit_error_errno(unit, r, "Failed to set SMACK process label: %m"); | |
4779 | } | |
4780 | } | |
4781 | #endif | |
4782 | ||
165a31c0 LP |
4783 | bset = context->capability_bounding_set; |
4784 | /* If the ambient caps hack is enabled (which means the kernel can't do them, and the user asked for | |
4785 | * our magic fallback), then let's add some extra caps, so that the service can drop privs of its own, | |
4786 | * instead of us doing that */ | |
4787 | if (needs_ambient_hack) | |
4788 | bset |= (UINT64_C(1) << CAP_SETPCAP) | | |
4789 | (UINT64_C(1) << CAP_SETUID) | | |
4790 | (UINT64_C(1) << CAP_SETGID); | |
4791 | ||
4792 | if (!cap_test_all(bset)) { | |
4793 | r = capability_bounding_set_drop(bset, false); | |
ff0af2a1 LP |
4794 | if (r < 0) { |
4795 | *exit_status = EXIT_CAPABILITIES; | |
12145637 | 4796 | return log_unit_error_errno(unit, r, "Failed to drop capabilities: %m"); |
3b8bddde | 4797 | } |
4c2630eb | 4798 | } |
3b8bddde | 4799 | |
16fcb191 TK |
4800 | /* Ambient capabilities are cleared during setresuid() (in enforce_user()) even with |
4801 | * keep-caps set. | |
4802 | * To be able to raise the ambient capabilities after setresuid() they have to be | |
4803 | * added to the inherited set and keep caps has to be set (done in enforce_user()). | |
4804 | * After setresuid() the ambient capabilities can be raised as they are present in | |
4805 | * the permitted and inhertiable set. However it is possible that someone wants to | |
4806 | * set ambient capabilities without changing the user, so we also set the ambient | |
4807 | * capabilities here. | |
4808 | * The requested ambient capabilities are raised in the inheritable set if the | |
4809 | * second argument is true. */ | |
943800f4 | 4810 | if (!needs_ambient_hack) { |
755d4b67 IP |
4811 | r = capability_ambient_set_apply(context->capability_ambient_set, true); |
4812 | if (r < 0) { | |
4813 | *exit_status = EXIT_CAPABILITIES; | |
12145637 | 4814 | return log_unit_error_errno(unit, r, "Failed to apply ambient capabilities (before UID change): %m"); |
755d4b67 | 4815 | } |
755d4b67 | 4816 | } |
165a31c0 | 4817 | } |
755d4b67 | 4818 | |
fa97f630 JB |
4819 | /* chroot to root directory first, before we lose the ability to chroot */ |
4820 | r = apply_root_directory(context, params, needs_mount_namespace, exit_status); | |
4821 | if (r < 0) | |
4822 | return log_unit_error_errno(unit, r, "Chrooting to the requested root directory failed: %m"); | |
4823 | ||
165a31c0 | 4824 | if (needs_setuid) { |
08f67696 | 4825 | if (uid_is_valid(uid)) { |
ff0af2a1 LP |
4826 | r = enforce_user(context, uid); |
4827 | if (r < 0) { | |
4828 | *exit_status = EXIT_USER; | |
12145637 | 4829 | return log_unit_error_errno(unit, r, "Failed to change UID to " UID_FMT ": %m", uid); |
5b6319dc | 4830 | } |
165a31c0 LP |
4831 | |
4832 | if (!needs_ambient_hack && | |
4833 | context->capability_ambient_set != 0) { | |
755d4b67 | 4834 | |
16fcb191 | 4835 | /* Raise the ambient capabilities after user change. */ |
755d4b67 IP |
4836 | r = capability_ambient_set_apply(context->capability_ambient_set, false); |
4837 | if (r < 0) { | |
4838 | *exit_status = EXIT_CAPABILITIES; | |
12145637 | 4839 | return log_unit_error_errno(unit, r, "Failed to apply ambient capabilities (after UID change): %m"); |
755d4b67 | 4840 | } |
755d4b67 | 4841 | } |
5b6319dc | 4842 | } |
165a31c0 | 4843 | } |
d35fbf6b | 4844 | |
56ef8db9 JB |
4845 | /* Apply working directory here, because the working directory might be on NFS and only the user running |
4846 | * this service might have the correct privilege to change to the working directory */ | |
fa97f630 | 4847 | r = apply_working_directory(context, params, home, exit_status); |
56ef8db9 JB |
4848 | if (r < 0) |
4849 | return log_unit_error_errno(unit, r, "Changing to the requested working directory failed: %m"); | |
4850 | ||
165a31c0 | 4851 | if (needs_sandboxing) { |
37ac2744 | 4852 | /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to |
5cd9cd35 LP |
4853 | * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires |
4854 | * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls | |
4855 | * are restricted. */ | |
4856 | ||
349cc4a5 | 4857 | #if HAVE_SELINUX |
43b1f709 | 4858 | if (use_selinux) { |
5cd9cd35 LP |
4859 | char *exec_context = mac_selinux_context_net ?: context->selinux_context; |
4860 | ||
4861 | if (exec_context) { | |
4862 | r = setexeccon(exec_context); | |
006d1864 TM |
4863 | if (r < 0) { |
4864 | if (!context->selinux_context_ignore) { | |
4865 | *exit_status = EXIT_SELINUX_CONTEXT; | |
4866 | return log_unit_error_errno(unit, r, "Failed to change SELinux context to %s: %m", exec_context); | |
4867 | } | |
4868 | log_unit_debug_errno(unit, r, "Failed to change SELinux context to %s, ignoring: %m", exec_context); | |
5cd9cd35 LP |
4869 | } |
4870 | } | |
4871 | } | |
4872 | #endif | |
4873 | ||
349cc4a5 | 4874 | #if HAVE_APPARMOR |
43b1f709 | 4875 | if (use_apparmor && context->apparmor_profile) { |
5cd9cd35 LP |
4876 | r = aa_change_onexec(context->apparmor_profile); |
4877 | if (r < 0 && !context->apparmor_profile_ignore) { | |
4878 | *exit_status = EXIT_APPARMOR_PROFILE; | |
12145637 | 4879 | return log_unit_error_errno(unit, errno, "Failed to prepare AppArmor profile change to %s: %m", context->apparmor_profile); |
5cd9cd35 LP |
4880 | } |
4881 | } | |
4882 | #endif | |
4883 | ||
165a31c0 | 4884 | /* PR_GET_SECUREBITS is not privileged, while PR_SET_SECUREBITS is. So to suppress potential EPERMs |
dbdc4098 TK |
4885 | * we'll try not to call PR_SET_SECUREBITS unless necessary. Setting securebits requires |
4886 | * CAP_SETPCAP. */ | |
4887 | if (prctl(PR_GET_SECUREBITS) != secure_bits) { | |
69e3234d | 4888 | /* CAP_SETPCAP is required to set securebits. This capability is raised into the |
dbdc4098 TK |
4889 | * effective set here. |
4890 | * The effective set is overwritten during execve with the following values: | |
4891 | * - ambient set (for non-root processes) | |
4892 | * - (inheritable | bounding) set for root processes) | |
4893 | * | |
4894 | * Hence there is no security impact to raise it in the effective set before execve | |
4895 | */ | |
4896 | r = capability_gain_cap_setpcap(NULL); | |
4897 | if (r < 0) { | |
4898 | *exit_status = EXIT_CAPABILITIES; | |
4899 | return log_unit_error_errno(unit, r, "Failed to gain CAP_SETPCAP for setting secure bits"); | |
4900 | } | |
755d4b67 | 4901 | if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) { |
ff0af2a1 | 4902 | *exit_status = EXIT_SECUREBITS; |
12145637 | 4903 | return log_unit_error_errno(unit, errno, "Failed to set process secure bits: %m"); |
ff01d048 | 4904 | } |
dbdc4098 | 4905 | } |
5b6319dc | 4906 | |
59eeb84b | 4907 | if (context_has_no_new_privileges(context)) |
d35fbf6b | 4908 | if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) { |
ff0af2a1 | 4909 | *exit_status = EXIT_NO_NEW_PRIVILEGES; |
12145637 | 4910 | return log_unit_error_errno(unit, errno, "Failed to disable new privileges: %m"); |
d35fbf6b DM |
4911 | } |
4912 | ||
349cc4a5 | 4913 | #if HAVE_SECCOMP |
469830d1 LP |
4914 | r = apply_address_families(unit, context); |
4915 | if (r < 0) { | |
4916 | *exit_status = EXIT_ADDRESS_FAMILIES; | |
12145637 | 4917 | return log_unit_error_errno(unit, r, "Failed to restrict address families: %m"); |
4c2630eb | 4918 | } |
04aa0cb9 | 4919 | |
469830d1 LP |
4920 | r = apply_memory_deny_write_execute(unit, context); |
4921 | if (r < 0) { | |
4922 | *exit_status = EXIT_SECCOMP; | |
12145637 | 4923 | return log_unit_error_errno(unit, r, "Failed to disable writing to executable memory: %m"); |
f3e43635 | 4924 | } |
f4170c67 | 4925 | |
469830d1 LP |
4926 | r = apply_restrict_realtime(unit, context); |
4927 | if (r < 0) { | |
4928 | *exit_status = EXIT_SECCOMP; | |
12145637 | 4929 | return log_unit_error_errno(unit, r, "Failed to apply realtime restrictions: %m"); |
f4170c67 LP |
4930 | } |
4931 | ||
f69567cb LP |
4932 | r = apply_restrict_suid_sgid(unit, context); |
4933 | if (r < 0) { | |
4934 | *exit_status = EXIT_SECCOMP; | |
4935 | return log_unit_error_errno(unit, r, "Failed to apply SUID/SGID restrictions: %m"); | |
4936 | } | |
4937 | ||
add00535 LP |
4938 | r = apply_restrict_namespaces(unit, context); |
4939 | if (r < 0) { | |
4940 | *exit_status = EXIT_SECCOMP; | |
12145637 | 4941 | return log_unit_error_errno(unit, r, "Failed to apply namespace restrictions: %m"); |
add00535 LP |
4942 | } |
4943 | ||
469830d1 LP |
4944 | r = apply_protect_sysctl(unit, context); |
4945 | if (r < 0) { | |
4946 | *exit_status = EXIT_SECCOMP; | |
12145637 | 4947 | return log_unit_error_errno(unit, r, "Failed to apply sysctl restrictions: %m"); |
502d704e DH |
4948 | } |
4949 | ||
469830d1 LP |
4950 | r = apply_protect_kernel_modules(unit, context); |
4951 | if (r < 0) { | |
4952 | *exit_status = EXIT_SECCOMP; | |
12145637 | 4953 | return log_unit_error_errno(unit, r, "Failed to apply module loading restrictions: %m"); |
59eeb84b LP |
4954 | } |
4955 | ||
84703040 KK |
4956 | r = apply_protect_kernel_logs(unit, context); |
4957 | if (r < 0) { | |
4958 | *exit_status = EXIT_SECCOMP; | |
4959 | return log_unit_error_errno(unit, r, "Failed to apply kernel log restrictions: %m"); | |
4960 | } | |
4961 | ||
fc64760d KK |
4962 | r = apply_protect_clock(unit, context); |
4963 | if (r < 0) { | |
4964 | *exit_status = EXIT_SECCOMP; | |
4965 | return log_unit_error_errno(unit, r, "Failed to apply clock restrictions: %m"); | |
4966 | } | |
4967 | ||
469830d1 LP |
4968 | r = apply_private_devices(unit, context); |
4969 | if (r < 0) { | |
4970 | *exit_status = EXIT_SECCOMP; | |
12145637 | 4971 | return log_unit_error_errno(unit, r, "Failed to set up private devices: %m"); |
469830d1 LP |
4972 | } |
4973 | ||
4974 | r = apply_syscall_archs(unit, context); | |
4975 | if (r < 0) { | |
4976 | *exit_status = EXIT_SECCOMP; | |
12145637 | 4977 | return log_unit_error_errno(unit, r, "Failed to apply syscall architecture restrictions: %m"); |
ba128bb8 LP |
4978 | } |
4979 | ||
78e864e5 TM |
4980 | r = apply_lock_personality(unit, context); |
4981 | if (r < 0) { | |
4982 | *exit_status = EXIT_SECCOMP; | |
12145637 | 4983 | return log_unit_error_errno(unit, r, "Failed to lock personalities: %m"); |
78e864e5 TM |
4984 | } |
4985 | ||
9df2cdd8 TM |
4986 | r = apply_syscall_log(unit, context); |
4987 | if (r < 0) { | |
4988 | *exit_status = EXIT_SECCOMP; | |
4989 | return log_unit_error_errno(unit, r, "Failed to apply system call log filters: %m"); | |
4990 | } | |
4991 | ||
5cd9cd35 LP |
4992 | /* This really should remain the last step before the execve(), to make sure our own code is unaffected |
4993 | * by the filter as little as possible. */ | |
165a31c0 | 4994 | r = apply_syscall_filter(unit, context, needs_ambient_hack); |
469830d1 LP |
4995 | if (r < 0) { |
4996 | *exit_status = EXIT_SECCOMP; | |
12145637 | 4997 | return log_unit_error_errno(unit, r, "Failed to apply system call filters: %m"); |
d35fbf6b DM |
4998 | } |
4999 | #endif | |
b1994387 ILG |
5000 | |
5001 | #if HAVE_LIBBPF | |
5002 | r = apply_restrict_filesystems(unit, context); | |
5003 | if (r < 0) { | |
5004 | *exit_status = EXIT_BPF; | |
5005 | return log_unit_error_errno(unit, r, "Failed to restrict filesystems: %m"); | |
5006 | } | |
5007 | #endif | |
5008 | ||
d35fbf6b | 5009 | } |
034c6ed7 | 5010 | |
00819cc1 LP |
5011 | if (!strv_isempty(context->unset_environment)) { |
5012 | char **ee = NULL; | |
5013 | ||
5014 | ee = strv_env_delete(accum_env, 1, context->unset_environment); | |
5015 | if (!ee) { | |
5016 | *exit_status = EXIT_MEMORY; | |
12145637 | 5017 | return log_oom(); |
00819cc1 LP |
5018 | } |
5019 | ||
130d3d22 | 5020 | strv_free_and_replace(accum_env, ee); |
00819cc1 LP |
5021 | } |
5022 | ||
7ca69792 AZ |
5023 | if (!FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) { |
5024 | replaced_argv = replace_env_argv(command->argv, accum_env); | |
5025 | if (!replaced_argv) { | |
5026 | *exit_status = EXIT_MEMORY; | |
5027 | return log_oom(); | |
5028 | } | |
5029 | final_argv = replaced_argv; | |
5030 | } else | |
5031 | final_argv = command->argv; | |
034c6ed7 | 5032 | |
f1d34068 | 5033 | if (DEBUG_LOGGING) { |
c2b2df60 | 5034 | _cleanup_free_ char *line = NULL; |
81a2b7ce | 5035 | |
4ef15008 | 5036 | line = quote_command_line(final_argv, SHELL_ESCAPE_EMPTY); |
8a62620e ZJS |
5037 | if (!line) { |
5038 | *exit_status = EXIT_MEMORY; | |
5039 | return log_oom(); | |
5040 | } | |
5041 | ||
5042 | log_unit_struct(unit, LOG_DEBUG, | |
5043 | "EXECUTABLE=%s", executable, | |
5044 | LOG_UNIT_MESSAGE(unit, "Executing: %s", line)); | |
d35fbf6b | 5045 | } |
dd305ec9 | 5046 | |
5686391b LP |
5047 | if (exec_fd >= 0) { |
5048 | uint8_t hot = 1; | |
5049 | ||
5050 | /* We have finished with all our initializations. Let's now let the manager know that. From this point | |
5051 | * on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */ | |
5052 | ||
5053 | if (write(exec_fd, &hot, sizeof(hot)) < 0) { | |
5054 | *exit_status = EXIT_EXEC; | |
5055 | return log_unit_error_errno(unit, errno, "Failed to enable exec_fd: %m"); | |
5056 | } | |
5057 | } | |
5058 | ||
a6d9111c | 5059 | r = fexecve_or_execve(executable_fd, executable, final_argv, accum_env); |
5686391b LP |
5060 | |
5061 | if (exec_fd >= 0) { | |
5062 | uint8_t hot = 0; | |
5063 | ||
5064 | /* The execve() failed. This means the exec_fd is still open. Which means we need to tell the manager | |
5065 | * that POLLHUP on it no longer means execve() succeeded. */ | |
5066 | ||
5067 | if (write(exec_fd, &hot, sizeof(hot)) < 0) { | |
5068 | *exit_status = EXIT_EXEC; | |
5069 | return log_unit_error_errno(unit, errno, "Failed to disable exec_fd: %m"); | |
5070 | } | |
5071 | } | |
12145637 | 5072 | |
ff0af2a1 | 5073 | *exit_status = EXIT_EXEC; |
9f71ba8d | 5074 | return log_unit_error_errno(unit, r, "Failed to execute %s: %m", executable); |
d35fbf6b | 5075 | } |
81a2b7ce | 5076 | |
34cf6c43 | 5077 | static int exec_context_load_environment(const Unit *unit, const ExecContext *c, char ***l); |
2caa38e9 | 5078 | static int exec_context_named_iofds(const ExecContext *c, const ExecParameters *p, int named_iofds[static 3]); |
34cf6c43 | 5079 | |
f2341e0a LP |
5080 | int exec_spawn(Unit *unit, |
5081 | ExecCommand *command, | |
d35fbf6b DM |
5082 | const ExecContext *context, |
5083 | const ExecParameters *params, | |
5084 | ExecRuntime *runtime, | |
29206d46 | 5085 | DynamicCreds *dcreds, |
d35fbf6b | 5086 | pid_t *ret) { |
8351ceae | 5087 | |
ee39ca20 | 5088 | int socket_fd, r, named_iofds[3] = { -1, -1, -1 }, *fds = NULL; |
78f93209 | 5089 | _cleanup_free_ char *subcgroup_path = NULL; |
d35fbf6b | 5090 | _cleanup_strv_free_ char **files_env = NULL; |
da6053d0 | 5091 | size_t n_storage_fds = 0, n_socket_fds = 0; |
ff0af2a1 | 5092 | _cleanup_free_ char *line = NULL; |
d35fbf6b | 5093 | pid_t pid; |
8351ceae | 5094 | |
f2341e0a | 5095 | assert(unit); |
d35fbf6b DM |
5096 | assert(command); |
5097 | assert(context); | |
5098 | assert(ret); | |
5099 | assert(params); | |
25b583d7 | 5100 | assert(params->fds || (params->n_socket_fds + params->n_storage_fds <= 0)); |
4298d0b5 | 5101 | |
d35fbf6b DM |
5102 | if (context->std_input == EXEC_INPUT_SOCKET || |
5103 | context->std_output == EXEC_OUTPUT_SOCKET || | |
5104 | context->std_error == EXEC_OUTPUT_SOCKET) { | |
17df7223 | 5105 | |
d85ff944 YW |
5106 | if (params->n_socket_fds > 1) |
5107 | return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EINVAL), "Got more than one socket."); | |
eef65bf3 | 5108 | |
d85ff944 YW |
5109 | if (params->n_socket_fds == 0) |
5110 | return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EINVAL), "Got no socket."); | |
488ab41c | 5111 | |
d35fbf6b DM |
5112 | socket_fd = params->fds[0]; |
5113 | } else { | |
5114 | socket_fd = -1; | |
5115 | fds = params->fds; | |
9b141911 | 5116 | n_socket_fds = params->n_socket_fds; |
25b583d7 | 5117 | n_storage_fds = params->n_storage_fds; |
d35fbf6b | 5118 | } |
94f04347 | 5119 | |
34cf6c43 | 5120 | r = exec_context_named_iofds(context, params, named_iofds); |
52c239d7 LB |
5121 | if (r < 0) |
5122 | return log_unit_error_errno(unit, r, "Failed to load a named file descriptor: %m"); | |
5123 | ||
f2341e0a | 5124 | r = exec_context_load_environment(unit, context, &files_env); |
ff0af2a1 | 5125 | if (r < 0) |
f2341e0a | 5126 | return log_unit_error_errno(unit, r, "Failed to load environment files: %m"); |
034c6ed7 | 5127 | |
4ef15008 | 5128 | line = quote_command_line(command->argv, SHELL_ESCAPE_EMPTY); |
d35fbf6b DM |
5129 | if (!line) |
5130 | return log_oom(); | |
fab56fc5 | 5131 | |
9f71ba8d ZJS |
5132 | /* Fork with up-to-date SELinux label database, so the child inherits the up-to-date db |
5133 | and, until the next SELinux policy changes, we save further reloads in future children. */ | |
2df2152c CG |
5134 | mac_selinux_maybe_reload(); |
5135 | ||
c2503e35 RH |
5136 | log_unit_struct(unit, LOG_DEBUG, |
5137 | LOG_UNIT_MESSAGE(unit, "About to execute %s", line), | |
5138 | "EXECUTABLE=%s", command->path, /* We won't know the real executable path until we create | |
5139 | the mount namespace in the child, but we want to log | |
5140 | from the parent, so we need to use the (possibly | |
5141 | inaccurate) path here. */ | |
5142 | LOG_UNIT_INVOCATION_ID(unit)); | |
12145637 | 5143 | |
78f93209 LP |
5144 | if (params->cgroup_path) { |
5145 | r = exec_parameters_get_cgroup_path(params, &subcgroup_path); | |
5146 | if (r < 0) | |
5147 | return log_unit_error_errno(unit, r, "Failed to acquire subcgroup path: %m"); | |
5148 | if (r > 0) { /* We are using a child cgroup */ | |
5149 | r = cg_create(SYSTEMD_CGROUP_CONTROLLER, subcgroup_path); | |
5150 | if (r < 0) | |
5151 | return log_unit_error_errno(unit, r, "Failed to create control group '%s': %m", subcgroup_path); | |
4e806bfa AZ |
5152 | |
5153 | /* Normally we would not propagate the oomd xattrs to children but since we created this | |
5154 | * sub-cgroup internally we should do it. */ | |
5155 | cgroup_oomd_xattr_apply(unit, subcgroup_path); | |
78f93209 LP |
5156 | } |
5157 | } | |
5158 | ||
d35fbf6b DM |
5159 | pid = fork(); |
5160 | if (pid < 0) | |
74129a12 | 5161 | return log_unit_error_errno(unit, errno, "Failed to fork: %m"); |
d35fbf6b DM |
5162 | |
5163 | if (pid == 0) { | |
12145637 | 5164 | int exit_status = EXIT_SUCCESS; |
ff0af2a1 | 5165 | |
f2341e0a LP |
5166 | r = exec_child(unit, |
5167 | command, | |
ff0af2a1 LP |
5168 | context, |
5169 | params, | |
5170 | runtime, | |
29206d46 | 5171 | dcreds, |
ff0af2a1 | 5172 | socket_fd, |
52c239d7 | 5173 | named_iofds, |
4c47affc | 5174 | fds, |
9b141911 | 5175 | n_socket_fds, |
25b583d7 | 5176 | n_storage_fds, |
ff0af2a1 | 5177 | files_env, |
00d9ef85 | 5178 | unit->manager->user_lookup_fds[1], |
12145637 LP |
5179 | &exit_status); |
5180 | ||
e1714f02 ZJS |
5181 | if (r < 0) { |
5182 | const char *status = | |
5183 | exit_status_to_string(exit_status, | |
e04ed6db | 5184 | EXIT_STATUS_LIBC | EXIT_STATUS_SYSTEMD); |
e1714f02 | 5185 | |
c2503e35 RH |
5186 | log_unit_struct_errno(unit, LOG_ERR, r, |
5187 | "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR, | |
5188 | LOG_UNIT_INVOCATION_ID(unit), | |
5189 | LOG_UNIT_MESSAGE(unit, "Failed at step %s spawning %s: %m", | |
5190 | status, command->path), | |
5191 | "EXECUTABLE=%s", command->path); | |
e1714f02 | 5192 | } |
4c2630eb | 5193 | |
ff0af2a1 | 5194 | _exit(exit_status); |
034c6ed7 LP |
5195 | } |
5196 | ||
f2341e0a | 5197 | log_unit_debug(unit, "Forked %s as "PID_FMT, command->path, pid); |
23635a85 | 5198 | |
78f93209 LP |
5199 | /* We add the new process to the cgroup both in the child (so that we can be sure that no user code is ever |
5200 | * executed outside of the cgroup) and in the parent (so that we can be sure that when we kill the cgroup the | |
5201 | * process will be killed too). */ | |
5202 | if (subcgroup_path) | |
5203 | (void) cg_attach(SYSTEMD_CGROUP_CONTROLLER, subcgroup_path, pid); | |
2da3263a | 5204 | |
b58b4116 | 5205 | exec_status_start(&command->exec_status, pid); |
9fb86720 | 5206 | |
034c6ed7 | 5207 | *ret = pid; |
5cb5a6ff LP |
5208 | return 0; |
5209 | } | |
5210 | ||
034c6ed7 LP |
5211 | void exec_context_init(ExecContext *c) { |
5212 | assert(c); | |
5213 | ||
4c12626c | 5214 | c->umask = 0022; |
0692548c | 5215 | c->ioprio = IOPRIO_DEFAULT_CLASS_AND_PRIO; |
94f04347 | 5216 | c->cpu_sched_policy = SCHED_OTHER; |
071830ff | 5217 | c->syslog_priority = LOG_DAEMON|LOG_INFO; |
74922904 | 5218 | c->syslog_level_prefix = true; |
353e12c2 | 5219 | c->ignore_sigpipe = true; |
3a43da28 | 5220 | c->timer_slack_nsec = NSEC_INFINITY; |
050f7277 | 5221 | c->personality = PERSONALITY_INVALID; |
5b10116e ZJS |
5222 | for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) |
5223 | c->directories[t].mode = 0755; | |
12213aed | 5224 | c->timeout_clean_usec = USEC_INFINITY; |
a103496c | 5225 | c->capability_bounding_set = CAP_ALL; |
aa9d574d YW |
5226 | assert_cc(NAMESPACE_FLAGS_INITIAL != NAMESPACE_FLAGS_ALL); |
5227 | c->restrict_namespaces = NAMESPACE_FLAGS_INITIAL; | |
d3070fbd | 5228 | c->log_level_max = -1; |
005bfaf1 TM |
5229 | #if HAVE_SECCOMP |
5230 | c->syscall_errno = SECCOMP_ERROR_NUMBER_KILL; | |
5231 | #endif | |
51462135 DDM |
5232 | c->tty_rows = UINT_MAX; |
5233 | c->tty_cols = UINT_MAX; | |
b070c7c0 | 5234 | numa_policy_reset(&c->numa_policy); |
034c6ed7 LP |
5235 | } |
5236 | ||
613b411c | 5237 | void exec_context_done(ExecContext *c) { |
5cb5a6ff LP |
5238 | assert(c); |
5239 | ||
6796073e LP |
5240 | c->environment = strv_free(c->environment); |
5241 | c->environment_files = strv_free(c->environment_files); | |
b4c14404 | 5242 | c->pass_environment = strv_free(c->pass_environment); |
00819cc1 | 5243 | c->unset_environment = strv_free(c->unset_environment); |
8c7be95e | 5244 | |
31ce987c | 5245 | rlimit_free_all(c->rlimit); |
034c6ed7 | 5246 | |
5b10116e | 5247 | for (size_t l = 0; l < 3; l++) { |
52c239d7 | 5248 | c->stdio_fdname[l] = mfree(c->stdio_fdname[l]); |
2038c3f5 LP |
5249 | c->stdio_file[l] = mfree(c->stdio_file[l]); |
5250 | } | |
52c239d7 | 5251 | |
a1e58e8e LP |
5252 | c->working_directory = mfree(c->working_directory); |
5253 | c->root_directory = mfree(c->root_directory); | |
915e6d16 | 5254 | c->root_image = mfree(c->root_image); |
18d73705 | 5255 | c->root_image_options = mount_options_free_all(c->root_image_options); |
0389f4fa LB |
5256 | c->root_hash = mfree(c->root_hash); |
5257 | c->root_hash_size = 0; | |
5258 | c->root_hash_path = mfree(c->root_hash_path); | |
d4d55b0d LB |
5259 | c->root_hash_sig = mfree(c->root_hash_sig); |
5260 | c->root_hash_sig_size = 0; | |
5261 | c->root_hash_sig_path = mfree(c->root_hash_sig_path); | |
0389f4fa | 5262 | c->root_verity = mfree(c->root_verity); |
93f59701 | 5263 | c->extension_images = mount_image_free_many(c->extension_images, &c->n_extension_images); |
a07b9926 | 5264 | c->extension_directories = strv_free(c->extension_directories); |
a1e58e8e LP |
5265 | c->tty_path = mfree(c->tty_path); |
5266 | c->syslog_identifier = mfree(c->syslog_identifier); | |
5267 | c->user = mfree(c->user); | |
5268 | c->group = mfree(c->group); | |
034c6ed7 | 5269 | |
6796073e | 5270 | c->supplementary_groups = strv_free(c->supplementary_groups); |
94f04347 | 5271 | |
a1e58e8e | 5272 | c->pam_name = mfree(c->pam_name); |
5b6319dc | 5273 | |
2a624c36 AP |
5274 | c->read_only_paths = strv_free(c->read_only_paths); |
5275 | c->read_write_paths = strv_free(c->read_write_paths); | |
5276 | c->inaccessible_paths = strv_free(c->inaccessible_paths); | |
ddc155b2 TM |
5277 | c->exec_paths = strv_free(c->exec_paths); |
5278 | c->no_exec_paths = strv_free(c->no_exec_paths); | |
8c35c10d | 5279 | c->exec_search_path = strv_free(c->exec_search_path); |
82c121a4 | 5280 | |
d2d6c096 | 5281 | bind_mount_free_many(c->bind_mounts, c->n_bind_mounts); |
8e06d57c YW |
5282 | c->bind_mounts = NULL; |
5283 | c->n_bind_mounts = 0; | |
2abd4e38 YW |
5284 | temporary_filesystem_free_many(c->temporary_filesystems, c->n_temporary_filesystems); |
5285 | c->temporary_filesystems = NULL; | |
5286 | c->n_temporary_filesystems = 0; | |
b3d13314 | 5287 | c->mount_images = mount_image_free_many(c->mount_images, &c->n_mount_images); |
d2d6c096 | 5288 | |
0985c7c4 | 5289 | cpu_set_reset(&c->cpu_set); |
b070c7c0 | 5290 | numa_policy_reset(&c->numa_policy); |
86a3475b | 5291 | |
a1e58e8e LP |
5292 | c->utmp_id = mfree(c->utmp_id); |
5293 | c->selinux_context = mfree(c->selinux_context); | |
5294 | c->apparmor_profile = mfree(c->apparmor_profile); | |
5b8e1b77 | 5295 | c->smack_process_label = mfree(c->smack_process_label); |
eef65bf3 | 5296 | |
b1994387 ILG |
5297 | c->restrict_filesystems = set_free(c->restrict_filesystems); |
5298 | ||
8cfa775f | 5299 | c->syscall_filter = hashmap_free(c->syscall_filter); |
525d3cc7 LP |
5300 | c->syscall_archs = set_free(c->syscall_archs); |
5301 | c->address_families = set_free(c->address_families); | |
e66cf1a3 | 5302 | |
5b10116e | 5303 | for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) |
211a3d87 | 5304 | exec_directory_done(&c->directories[t]); |
d3070fbd LP |
5305 | |
5306 | c->log_level_max = -1; | |
5307 | ||
5308 | exec_context_free_log_extra_fields(c); | |
08f3be7a | 5309 | |
5ac1530e ZJS |
5310 | c->log_ratelimit_interval_usec = 0; |
5311 | c->log_ratelimit_burst = 0; | |
90fc172e | 5312 | |
08f3be7a LP |
5313 | c->stdin_data = mfree(c->stdin_data); |
5314 | c->stdin_data_size = 0; | |
a8d08f39 LP |
5315 | |
5316 | c->network_namespace_path = mfree(c->network_namespace_path); | |
71d1e583 | 5317 | c->ipc_namespace_path = mfree(c->ipc_namespace_path); |
91dd5f7c LP |
5318 | |
5319 | c->log_namespace = mfree(c->log_namespace); | |
bb0c0d6f | 5320 | |
43144be4 | 5321 | c->load_credentials = hashmap_free(c->load_credentials); |
bb0c0d6f | 5322 | c->set_credentials = hashmap_free(c->set_credentials); |
e66cf1a3 LP |
5323 | } |
5324 | ||
34cf6c43 | 5325 | int exec_context_destroy_runtime_directory(const ExecContext *c, const char *runtime_prefix) { |
e66cf1a3 LP |
5326 | assert(c); |
5327 | ||
5328 | if (!runtime_prefix) | |
5329 | return 0; | |
5330 | ||
211a3d87 | 5331 | for (size_t i = 0; i < c->directories[EXEC_DIRECTORY_RUNTIME].n_items; i++) { |
c2b2df60 | 5332 | _cleanup_free_ char *p = NULL; |
e66cf1a3 | 5333 | |
494d0247 | 5334 | if (exec_directory_is_private(c, EXEC_DIRECTORY_RUNTIME)) |
211a3d87 | 5335 | p = path_join(runtime_prefix, "private", c->directories[EXEC_DIRECTORY_RUNTIME].items[i].path); |
494d0247 | 5336 | else |
211a3d87 | 5337 | p = path_join(runtime_prefix, c->directories[EXEC_DIRECTORY_RUNTIME].items[i].path); |
e66cf1a3 LP |
5338 | if (!p) |
5339 | return -ENOMEM; | |
5340 | ||
7bc4bf4a LP |
5341 | /* We execute this synchronously, since we need to be sure this is gone when we start the |
5342 | * service next. */ | |
c6878637 | 5343 | (void) rm_rf(p, REMOVE_ROOT); |
211a3d87 | 5344 | |
211a3d87 LB |
5345 | STRV_FOREACH(symlink, c->directories[EXEC_DIRECTORY_RUNTIME].items[i].symlinks) { |
5346 | _cleanup_free_ char *symlink_abs = NULL; | |
5347 | ||
5348 | if (exec_directory_is_private(c, EXEC_DIRECTORY_RUNTIME)) | |
5349 | symlink_abs = path_join(runtime_prefix, "private", *symlink); | |
5350 | else | |
5351 | symlink_abs = path_join(runtime_prefix, *symlink); | |
5352 | if (!symlink_abs) | |
5353 | return -ENOMEM; | |
5354 | ||
5355 | (void) unlink(symlink_abs); | |
5356 | } | |
5357 | ||
e66cf1a3 LP |
5358 | } |
5359 | ||
5360 | return 0; | |
5cb5a6ff LP |
5361 | } |
5362 | ||
bb0c0d6f LP |
5363 | int exec_context_destroy_credentials(const ExecContext *c, const char *runtime_prefix, const char *unit) { |
5364 | _cleanup_free_ char *p = NULL; | |
5365 | ||
5366 | assert(c); | |
5367 | ||
5368 | if (!runtime_prefix || !unit) | |
5369 | return 0; | |
5370 | ||
5371 | p = path_join(runtime_prefix, "credentials", unit); | |
5372 | if (!p) | |
5373 | return -ENOMEM; | |
5374 | ||
5375 | /* This is either a tmpfs/ramfs of its own, or a plain directory. Either way, let's first try to | |
5376 | * unmount it, and afterwards remove the mount point */ | |
5377 | (void) umount2(p, MNT_DETACH|UMOUNT_NOFOLLOW); | |
5378 | (void) rm_rf(p, REMOVE_ROOT|REMOVE_CHMOD); | |
5379 | ||
5380 | return 0; | |
5381 | } | |
5382 | ||
34cf6c43 | 5383 | static void exec_command_done(ExecCommand *c) { |
43d0fcbd LP |
5384 | assert(c); |
5385 | ||
a1e58e8e | 5386 | c->path = mfree(c->path); |
6796073e | 5387 | c->argv = strv_free(c->argv); |
43d0fcbd LP |
5388 | } |
5389 | ||
da6053d0 | 5390 | void exec_command_done_array(ExecCommand *c, size_t n) { |
fe96c0f8 | 5391 | for (size_t i = 0; i < n; i++) |
43d0fcbd LP |
5392 | exec_command_done(c+i); |
5393 | } | |
5394 | ||
f1acf85a | 5395 | ExecCommand* exec_command_free_list(ExecCommand *c) { |
5cb5a6ff LP |
5396 | ExecCommand *i; |
5397 | ||
5398 | while ((i = c)) { | |
71fda00f | 5399 | LIST_REMOVE(command, c, i); |
43d0fcbd | 5400 | exec_command_done(i); |
5cb5a6ff LP |
5401 | free(i); |
5402 | } | |
f1acf85a ZJS |
5403 | |
5404 | return NULL; | |
5cb5a6ff LP |
5405 | } |
5406 | ||
da6053d0 | 5407 | void exec_command_free_array(ExecCommand **c, size_t n) { |
5b10116e | 5408 | for (size_t i = 0; i < n; i++) |
f1acf85a | 5409 | c[i] = exec_command_free_list(c[i]); |
034c6ed7 LP |
5410 | } |
5411 | ||
6a1d4d9f | 5412 | void exec_command_reset_status_array(ExecCommand *c, size_t n) { |
5b10116e | 5413 | for (size_t i = 0; i < n; i++) |
6a1d4d9f LP |
5414 | exec_status_reset(&c[i].exec_status); |
5415 | } | |
5416 | ||
5417 | void exec_command_reset_status_list_array(ExecCommand **c, size_t n) { | |
03677889 | 5418 | for (size_t i = 0; i < n; i++) |
6a1d4d9f LP |
5419 | LIST_FOREACH(command, z, c[i]) |
5420 | exec_status_reset(&z->exec_status); | |
6a1d4d9f LP |
5421 | } |
5422 | ||
039f0e70 | 5423 | typedef struct InvalidEnvInfo { |
34cf6c43 | 5424 | const Unit *unit; |
039f0e70 LP |
5425 | const char *path; |
5426 | } InvalidEnvInfo; | |
5427 | ||
5428 | static void invalid_env(const char *p, void *userdata) { | |
5429 | InvalidEnvInfo *info = userdata; | |
5430 | ||
f2341e0a | 5431 | log_unit_error(info->unit, "Ignoring invalid environment assignment '%s': %s", p, info->path); |
039f0e70 LP |
5432 | } |
5433 | ||
52c239d7 LB |
5434 | const char* exec_context_fdname(const ExecContext *c, int fd_index) { |
5435 | assert(c); | |
5436 | ||
5437 | switch (fd_index) { | |
5073ff6b | 5438 | |
52c239d7 LB |
5439 | case STDIN_FILENO: |
5440 | if (c->std_input != EXEC_INPUT_NAMED_FD) | |
5441 | return NULL; | |
5073ff6b | 5442 | |
52c239d7 | 5443 | return c->stdio_fdname[STDIN_FILENO] ?: "stdin"; |
5073ff6b | 5444 | |
52c239d7 LB |
5445 | case STDOUT_FILENO: |
5446 | if (c->std_output != EXEC_OUTPUT_NAMED_FD) | |
5447 | return NULL; | |
5073ff6b | 5448 | |
52c239d7 | 5449 | return c->stdio_fdname[STDOUT_FILENO] ?: "stdout"; |
5073ff6b | 5450 | |
52c239d7 LB |
5451 | case STDERR_FILENO: |
5452 | if (c->std_error != EXEC_OUTPUT_NAMED_FD) | |
5453 | return NULL; | |
5073ff6b | 5454 | |
52c239d7 | 5455 | return c->stdio_fdname[STDERR_FILENO] ?: "stderr"; |
5073ff6b | 5456 | |
52c239d7 LB |
5457 | default: |
5458 | return NULL; | |
5459 | } | |
5460 | } | |
5461 | ||
2caa38e9 LP |
5462 | static int exec_context_named_iofds( |
5463 | const ExecContext *c, | |
5464 | const ExecParameters *p, | |
5465 | int named_iofds[static 3]) { | |
5466 | ||
5b10116e | 5467 | size_t targets; |
56fbd561 | 5468 | const char* stdio_fdname[3]; |
da6053d0 | 5469 | size_t n_fds; |
52c239d7 LB |
5470 | |
5471 | assert(c); | |
5472 | assert(p); | |
2caa38e9 | 5473 | assert(named_iofds); |
52c239d7 LB |
5474 | |
5475 | targets = (c->std_input == EXEC_INPUT_NAMED_FD) + | |
5476 | (c->std_output == EXEC_OUTPUT_NAMED_FD) + | |
5477 | (c->std_error == EXEC_OUTPUT_NAMED_FD); | |
5478 | ||
5b10116e | 5479 | for (size_t i = 0; i < 3; i++) |
52c239d7 LB |
5480 | stdio_fdname[i] = exec_context_fdname(c, i); |
5481 | ||
4c47affc FB |
5482 | n_fds = p->n_storage_fds + p->n_socket_fds; |
5483 | ||
5b10116e | 5484 | for (size_t i = 0; i < n_fds && targets > 0; i++) |
56fbd561 ZJS |
5485 | if (named_iofds[STDIN_FILENO] < 0 && |
5486 | c->std_input == EXEC_INPUT_NAMED_FD && | |
5487 | stdio_fdname[STDIN_FILENO] && | |
5488 | streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) { | |
5489 | ||
52c239d7 LB |
5490 | named_iofds[STDIN_FILENO] = p->fds[i]; |
5491 | targets--; | |
56fbd561 ZJS |
5492 | |
5493 | } else if (named_iofds[STDOUT_FILENO] < 0 && | |
5494 | c->std_output == EXEC_OUTPUT_NAMED_FD && | |
5495 | stdio_fdname[STDOUT_FILENO] && | |
5496 | streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) { | |
5497 | ||
52c239d7 LB |
5498 | named_iofds[STDOUT_FILENO] = p->fds[i]; |
5499 | targets--; | |
56fbd561 ZJS |
5500 | |
5501 | } else if (named_iofds[STDERR_FILENO] < 0 && | |
5502 | c->std_error == EXEC_OUTPUT_NAMED_FD && | |
5503 | stdio_fdname[STDERR_FILENO] && | |
5504 | streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) { | |
5505 | ||
52c239d7 LB |
5506 | named_iofds[STDERR_FILENO] = p->fds[i]; |
5507 | targets--; | |
5508 | } | |
5509 | ||
56fbd561 | 5510 | return targets == 0 ? 0 : -ENOENT; |
52c239d7 LB |
5511 | } |
5512 | ||
398a5009 ZJS |
5513 | static int exec_context_load_environment(const Unit *unit, const ExecContext *c, char ***ret) { |
5514 | _cleanup_strv_free_ char **v = NULL; | |
398a5009 | 5515 | int r; |
8c7be95e LP |
5516 | |
5517 | assert(c); | |
398a5009 | 5518 | assert(ret); |
8c7be95e LP |
5519 | |
5520 | STRV_FOREACH(i, c->environment_files) { | |
7fd1b19b | 5521 | _cleanup_globfree_ glob_t pglob = {}; |
398a5009 ZJS |
5522 | bool ignore = false; |
5523 | char *fn = *i; | |
8c7be95e LP |
5524 | |
5525 | if (fn[0] == '-') { | |
5526 | ignore = true; | |
313cefa1 | 5527 | fn++; |
8c7be95e LP |
5528 | } |
5529 | ||
5530 | if (!path_is_absolute(fn)) { | |
8c7be95e LP |
5531 | if (ignore) |
5532 | continue; | |
8c7be95e LP |
5533 | return -EINVAL; |
5534 | } | |
5535 | ||
2bef10ab | 5536 | /* Filename supports globbing, take all matching files */ |
398a5009 ZJS |
5537 | r = safe_glob(fn, 0, &pglob); |
5538 | if (r < 0) { | |
2bef10ab PL |
5539 | if (ignore) |
5540 | continue; | |
398a5009 | 5541 | return r; |
2bef10ab | 5542 | } |
8c7be95e | 5543 | |
d8c92e8b ZJS |
5544 | /* When we don't match anything, -ENOENT should be returned */ |
5545 | assert(pglob.gl_pathc > 0); | |
5546 | ||
5b10116e | 5547 | for (unsigned n = 0; n < pglob.gl_pathc; n++) { |
398a5009 ZJS |
5548 | _cleanup_strv_free_ char **p = NULL; |
5549 | ||
5550 | r = load_env_file(NULL, pglob.gl_pathv[n], &p); | |
5551 | if (r < 0) { | |
2bef10ab PL |
5552 | if (ignore) |
5553 | continue; | |
398a5009 | 5554 | return r; |
e9c1ea9d | 5555 | } |
398a5009 | 5556 | |
ebc05a09 | 5557 | /* Log invalid environment variables with filename */ |
039f0e70 LP |
5558 | if (p) { |
5559 | InvalidEnvInfo info = { | |
f2341e0a | 5560 | .unit = unit, |
039f0e70 LP |
5561 | .path = pglob.gl_pathv[n] |
5562 | }; | |
5563 | ||
5564 | p = strv_env_clean_with_callback(p, invalid_env, &info); | |
5565 | } | |
8c7be95e | 5566 | |
398a5009 ZJS |
5567 | if (!v) |
5568 | v = TAKE_PTR(p); | |
2bef10ab | 5569 | else { |
398a5009 | 5570 | char **m = strv_env_merge(v, p); |
c84a9488 | 5571 | if (!m) |
2bef10ab | 5572 | return -ENOMEM; |
2bef10ab | 5573 | |
398a5009 | 5574 | strv_free_and_replace(v, m); |
2bef10ab | 5575 | } |
8c7be95e LP |
5576 | } |
5577 | } | |
5578 | ||
398a5009 | 5579 | *ret = TAKE_PTR(v); |
8c7be95e LP |
5580 | |
5581 | return 0; | |
5582 | } | |
5583 | ||
6ac8fdc9 | 5584 | static bool tty_may_match_dev_console(const char *tty) { |
7b912648 | 5585 | _cleanup_free_ char *resolved = NULL; |
6ac8fdc9 | 5586 | |
1e22b5cd LP |
5587 | if (!tty) |
5588 | return true; | |
5589 | ||
a119ec7c | 5590 | tty = skip_dev_prefix(tty); |
6ac8fdc9 MS |
5591 | |
5592 | /* trivial identity? */ | |
5593 | if (streq(tty, "console")) | |
5594 | return true; | |
5595 | ||
7b912648 LP |
5596 | if (resolve_dev_console(&resolved) < 0) |
5597 | return true; /* if we could not resolve, assume it may */ | |
6ac8fdc9 MS |
5598 | |
5599 | /* "tty0" means the active VC, so it may be the same sometimes */ | |
955f1c85 | 5600 | return path_equal(resolved, tty) || (streq(resolved, "tty0") && tty_is_vc(tty)); |
6ac8fdc9 MS |
5601 | } |
5602 | ||
6c0ae739 LP |
5603 | static bool exec_context_may_touch_tty(const ExecContext *ec) { |
5604 | assert(ec); | |
1e22b5cd | 5605 | |
6c0ae739 | 5606 | return ec->tty_reset || |
1e22b5cd LP |
5607 | ec->tty_vhangup || |
5608 | ec->tty_vt_disallocate || | |
6ac8fdc9 MS |
5609 | is_terminal_input(ec->std_input) || |
5610 | is_terminal_output(ec->std_output) || | |
6c0ae739 LP |
5611 | is_terminal_output(ec->std_error); |
5612 | } | |
5613 | ||
5614 | bool exec_context_may_touch_console(const ExecContext *ec) { | |
5615 | ||
5616 | return exec_context_may_touch_tty(ec) && | |
1e22b5cd | 5617 | tty_may_match_dev_console(exec_context_tty_path(ec)); |
6ac8fdc9 MS |
5618 | } |
5619 | ||
15ae422b | 5620 | static void strv_fprintf(FILE *f, char **l) { |
15ae422b LP |
5621 | assert(f); |
5622 | ||
5623 | STRV_FOREACH(g, l) | |
5624 | fprintf(f, " %s", *g); | |
5625 | } | |
5626 | ||
ddc155b2 TM |
5627 | static void strv_dump(FILE* f, const char *prefix, const char *name, char **strv) { |
5628 | assert(f); | |
5629 | assert(prefix); | |
5630 | assert(name); | |
5631 | ||
5632 | if (!strv_isempty(strv)) { | |
a7bd1656 | 5633 | fprintf(f, "%s%s:", prefix, name); |
ddc155b2 TM |
5634 | strv_fprintf(f, strv); |
5635 | fputs("\n", f); | |
5636 | } | |
5637 | } | |
5638 | ||
34cf6c43 | 5639 | void exec_context_dump(const ExecContext *c, FILE* f, const char *prefix) { |
add00535 | 5640 | int r; |
9eba9da4 | 5641 | |
5cb5a6ff LP |
5642 | assert(c); |
5643 | assert(f); | |
5644 | ||
4ad49000 | 5645 | prefix = strempty(prefix); |
5cb5a6ff LP |
5646 | |
5647 | fprintf(f, | |
94f04347 LP |
5648 | "%sUMask: %04o\n" |
5649 | "%sWorkingDirectory: %s\n" | |
451a074f | 5650 | "%sRootDirectory: %s\n" |
15ae422b | 5651 | "%sNonBlocking: %s\n" |
64747e2d | 5652 | "%sPrivateTmp: %s\n" |
7f112f50 | 5653 | "%sPrivateDevices: %s\n" |
59eeb84b | 5654 | "%sProtectKernelTunables: %s\n" |
e66a2f65 | 5655 | "%sProtectKernelModules: %s\n" |
84703040 | 5656 | "%sProtectKernelLogs: %s\n" |
fc64760d | 5657 | "%sProtectClock: %s\n" |
59eeb84b | 5658 | "%sProtectControlGroups: %s\n" |
d251207d LP |
5659 | "%sPrivateNetwork: %s\n" |
5660 | "%sPrivateUsers: %s\n" | |
1b8689f9 LP |
5661 | "%sProtectHome: %s\n" |
5662 | "%sProtectSystem: %s\n" | |
5d997827 | 5663 | "%sMountAPIVFS: %s\n" |
f3e43635 | 5664 | "%sIgnoreSIGPIPE: %s\n" |
f4170c67 | 5665 | "%sMemoryDenyWriteExecute: %s\n" |
b1edf445 | 5666 | "%sRestrictRealtime: %s\n" |
f69567cb | 5667 | "%sRestrictSUIDSGID: %s\n" |
aecd5ac6 | 5668 | "%sKeyringMode: %s\n" |
4e399953 LP |
5669 | "%sProtectHostname: %s\n" |
5670 | "%sProtectProc: %s\n" | |
5671 | "%sProcSubset: %s\n", | |
5cb5a6ff | 5672 | prefix, c->umask, |
14eb3285 LP |
5673 | prefix, empty_to_root(c->working_directory), |
5674 | prefix, empty_to_root(c->root_directory), | |
15ae422b | 5675 | prefix, yes_no(c->non_blocking), |
64747e2d | 5676 | prefix, yes_no(c->private_tmp), |
7f112f50 | 5677 | prefix, yes_no(c->private_devices), |
59eeb84b | 5678 | prefix, yes_no(c->protect_kernel_tunables), |
e66a2f65 | 5679 | prefix, yes_no(c->protect_kernel_modules), |
84703040 | 5680 | prefix, yes_no(c->protect_kernel_logs), |
fc64760d | 5681 | prefix, yes_no(c->protect_clock), |
59eeb84b | 5682 | prefix, yes_no(c->protect_control_groups), |
d251207d LP |
5683 | prefix, yes_no(c->private_network), |
5684 | prefix, yes_no(c->private_users), | |
1b8689f9 LP |
5685 | prefix, protect_home_to_string(c->protect_home), |
5686 | prefix, protect_system_to_string(c->protect_system), | |
5e98086d | 5687 | prefix, yes_no(exec_context_get_effective_mount_apivfs(c)), |
f3e43635 | 5688 | prefix, yes_no(c->ignore_sigpipe), |
f4170c67 | 5689 | prefix, yes_no(c->memory_deny_write_execute), |
b1edf445 | 5690 | prefix, yes_no(c->restrict_realtime), |
f69567cb | 5691 | prefix, yes_no(c->restrict_suid_sgid), |
aecd5ac6 | 5692 | prefix, exec_keyring_mode_to_string(c->keyring_mode), |
4e399953 LP |
5693 | prefix, yes_no(c->protect_hostname), |
5694 | prefix, protect_proc_to_string(c->protect_proc), | |
5695 | prefix, proc_subset_to_string(c->proc_subset)); | |
fb33a393 | 5696 | |
915e6d16 LP |
5697 | if (c->root_image) |
5698 | fprintf(f, "%sRootImage: %s\n", prefix, c->root_image); | |
5699 | ||
18d73705 | 5700 | if (c->root_image_options) { |
18d73705 LB |
5701 | fprintf(f, "%sRootImageOptions:", prefix); |
5702 | LIST_FOREACH(mount_options, o, c->root_image_options) | |
5703 | if (!isempty(o->options)) | |
9ece6444 LB |
5704 | fprintf(f, " %s:%s", |
5705 | partition_designator_to_string(o->partition_designator), | |
5706 | o->options); | |
18d73705 LB |
5707 | fprintf(f, "\n"); |
5708 | } | |
5709 | ||
0389f4fa LB |
5710 | if (c->root_hash) { |
5711 | _cleanup_free_ char *encoded = NULL; | |
5712 | encoded = hexmem(c->root_hash, c->root_hash_size); | |
5713 | if (encoded) | |
5714 | fprintf(f, "%sRootHash: %s\n", prefix, encoded); | |
5715 | } | |
5716 | ||
5717 | if (c->root_hash_path) | |
5718 | fprintf(f, "%sRootHash: %s\n", prefix, c->root_hash_path); | |
5719 | ||
d4d55b0d LB |
5720 | if (c->root_hash_sig) { |
5721 | _cleanup_free_ char *encoded = NULL; | |
5722 | ssize_t len; | |
5723 | len = base64mem(c->root_hash_sig, c->root_hash_sig_size, &encoded); | |
5724 | if (len) | |
5725 | fprintf(f, "%sRootHashSignature: base64:%s\n", prefix, encoded); | |
5726 | } | |
5727 | ||
5728 | if (c->root_hash_sig_path) | |
5729 | fprintf(f, "%sRootHashSignature: %s\n", prefix, c->root_hash_sig_path); | |
5730 | ||
0389f4fa LB |
5731 | if (c->root_verity) |
5732 | fprintf(f, "%sRootVerity: %s\n", prefix, c->root_verity); | |
5733 | ||
8c7be95e LP |
5734 | STRV_FOREACH(e, c->environment) |
5735 | fprintf(f, "%sEnvironment: %s\n", prefix, *e); | |
5736 | ||
5737 | STRV_FOREACH(e, c->environment_files) | |
5738 | fprintf(f, "%sEnvironmentFile: %s\n", prefix, *e); | |
94f04347 | 5739 | |
b4c14404 FB |
5740 | STRV_FOREACH(e, c->pass_environment) |
5741 | fprintf(f, "%sPassEnvironment: %s\n", prefix, *e); | |
5742 | ||
00819cc1 LP |
5743 | STRV_FOREACH(e, c->unset_environment) |
5744 | fprintf(f, "%sUnsetEnvironment: %s\n", prefix, *e); | |
5745 | ||
53f47dfc YW |
5746 | fprintf(f, "%sRuntimeDirectoryPreserve: %s\n", prefix, exec_preserve_mode_to_string(c->runtime_directory_preserve_mode)); |
5747 | ||
5b10116e | 5748 | for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) { |
3536f49e YW |
5749 | fprintf(f, "%s%sMode: %04o\n", prefix, exec_directory_type_to_string(dt), c->directories[dt].mode); |
5750 | ||
211a3d87 LB |
5751 | for (size_t i = 0; i < c->directories[dt].n_items; i++) { |
5752 | fprintf(f, "%s%s: %s\n", prefix, exec_directory_type_to_string(dt), c->directories[dt].items[i].path); | |
5753 | ||
5754 | STRV_FOREACH(d, c->directories[dt].items[i].symlinks) | |
5755 | fprintf(f, "%s%s: %s:%s\n", prefix, exec_directory_type_symlink_to_string(dt), c->directories[dt].items[i].path, *d); | |
5756 | } | |
3536f49e | 5757 | } |
c2bbd90b | 5758 | |
5291f26d | 5759 | fprintf(f, "%sTimeoutCleanSec: %s\n", prefix, FORMAT_TIMESPAN(c->timeout_clean_usec, USEC_PER_SEC)); |
12213aed | 5760 | |
fb33a393 | 5761 | if (c->nice_set) |
5291f26d | 5762 | fprintf(f, "%sNice: %i\n", prefix, c->nice); |
fb33a393 | 5763 | |
dd6c17b1 | 5764 | if (c->oom_score_adjust_set) |
5291f26d | 5765 | fprintf(f, "%sOOMScoreAdjust: %i\n", prefix, c->oom_score_adjust); |
9eba9da4 | 5766 | |
ad21e542 | 5767 | if (c->coredump_filter_set) |
5291f26d | 5768 | fprintf(f, "%sCoredumpFilter: 0x%"PRIx64"\n", prefix, c->coredump_filter); |
ad21e542 | 5769 | |
5b10116e | 5770 | for (unsigned i = 0; i < RLIM_NLIMITS; i++) |
3c11da9d | 5771 | if (c->rlimit[i]) { |
4c3a2b84 | 5772 | fprintf(f, "%sLimit%s: " RLIM_FMT "\n", |
3c11da9d | 5773 | prefix, rlimit_to_string(i), c->rlimit[i]->rlim_max); |
4c3a2b84 | 5774 | fprintf(f, "%sLimit%sSoft: " RLIM_FMT "\n", |
3c11da9d EV |
5775 | prefix, rlimit_to_string(i), c->rlimit[i]->rlim_cur); |
5776 | } | |
94f04347 | 5777 | |
f8b69d1d | 5778 | if (c->ioprio_set) { |
1756a011 | 5779 | _cleanup_free_ char *class_str = NULL; |
f8b69d1d | 5780 | |
5bead76e | 5781 | r = ioprio_class_to_string_alloc(ioprio_prio_class(c->ioprio), &class_str); |
837df140 YW |
5782 | if (r >= 0) |
5783 | fprintf(f, "%sIOSchedulingClass: %s\n", prefix, class_str); | |
5784 | ||
5bead76e | 5785 | fprintf(f, "%sIOPriority: %d\n", prefix, ioprio_prio_data(c->ioprio)); |
f8b69d1d | 5786 | } |
94f04347 | 5787 | |
f8b69d1d | 5788 | if (c->cpu_sched_set) { |
1756a011 | 5789 | _cleanup_free_ char *policy_str = NULL; |
f8b69d1d | 5790 | |
837df140 YW |
5791 | r = sched_policy_to_string_alloc(c->cpu_sched_policy, &policy_str); |
5792 | if (r >= 0) | |
5793 | fprintf(f, "%sCPUSchedulingPolicy: %s\n", prefix, policy_str); | |
5794 | ||
94f04347 | 5795 | fprintf(f, |
38b48754 LP |
5796 | "%sCPUSchedulingPriority: %i\n" |
5797 | "%sCPUSchedulingResetOnFork: %s\n", | |
38b48754 LP |
5798 | prefix, c->cpu_sched_priority, |
5799 | prefix, yes_no(c->cpu_sched_reset_on_fork)); | |
b929bf04 | 5800 | } |
94f04347 | 5801 | |
0985c7c4 | 5802 | if (c->cpu_set.set) { |
e7fca352 MS |
5803 | _cleanup_free_ char *affinity = NULL; |
5804 | ||
5805 | affinity = cpu_set_to_range_string(&c->cpu_set); | |
5806 | fprintf(f, "%sCPUAffinity: %s\n", prefix, affinity); | |
94f04347 LP |
5807 | } |
5808 | ||
b070c7c0 MS |
5809 | if (mpol_is_valid(numa_policy_get_type(&c->numa_policy))) { |
5810 | _cleanup_free_ char *nodes = NULL; | |
5811 | ||
5812 | nodes = cpu_set_to_range_string(&c->numa_policy.nodes); | |
5813 | fprintf(f, "%sNUMAPolicy: %s\n", prefix, mpol_to_string(numa_policy_get_type(&c->numa_policy))); | |
5814 | fprintf(f, "%sNUMAMask: %s\n", prefix, strnull(nodes)); | |
5815 | } | |
5816 | ||
3a43da28 | 5817 | if (c->timer_slack_nsec != NSEC_INFINITY) |
ccd06097 | 5818 | fprintf(f, "%sTimerSlackNSec: "NSEC_FMT "\n", prefix, c->timer_slack_nsec); |
94f04347 LP |
5819 | |
5820 | fprintf(f, | |
80876c20 LP |
5821 | "%sStandardInput: %s\n" |
5822 | "%sStandardOutput: %s\n" | |
5823 | "%sStandardError: %s\n", | |
5824 | prefix, exec_input_to_string(c->std_input), | |
5825 | prefix, exec_output_to_string(c->std_output), | |
5826 | prefix, exec_output_to_string(c->std_error)); | |
5827 | ||
befc4a80 LP |
5828 | if (c->std_input == EXEC_INPUT_NAMED_FD) |
5829 | fprintf(f, "%sStandardInputFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDIN_FILENO]); | |
5830 | if (c->std_output == EXEC_OUTPUT_NAMED_FD) | |
5831 | fprintf(f, "%sStandardOutputFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDOUT_FILENO]); | |
5832 | if (c->std_error == EXEC_OUTPUT_NAMED_FD) | |
5833 | fprintf(f, "%sStandardErrorFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDERR_FILENO]); | |
5834 | ||
5835 | if (c->std_input == EXEC_INPUT_FILE) | |
5836 | fprintf(f, "%sStandardInputFile: %s\n", prefix, c->stdio_file[STDIN_FILENO]); | |
5837 | if (c->std_output == EXEC_OUTPUT_FILE) | |
5838 | fprintf(f, "%sStandardOutputFile: %s\n", prefix, c->stdio_file[STDOUT_FILENO]); | |
566b7d23 ZD |
5839 | if (c->std_output == EXEC_OUTPUT_FILE_APPEND) |
5840 | fprintf(f, "%sStandardOutputFileToAppend: %s\n", prefix, c->stdio_file[STDOUT_FILENO]); | |
8d7dab1f LW |
5841 | if (c->std_output == EXEC_OUTPUT_FILE_TRUNCATE) |
5842 | fprintf(f, "%sStandardOutputFileToTruncate: %s\n", prefix, c->stdio_file[STDOUT_FILENO]); | |
befc4a80 LP |
5843 | if (c->std_error == EXEC_OUTPUT_FILE) |
5844 | fprintf(f, "%sStandardErrorFile: %s\n", prefix, c->stdio_file[STDERR_FILENO]); | |
566b7d23 ZD |
5845 | if (c->std_error == EXEC_OUTPUT_FILE_APPEND) |
5846 | fprintf(f, "%sStandardErrorFileToAppend: %s\n", prefix, c->stdio_file[STDERR_FILENO]); | |
8d7dab1f LW |
5847 | if (c->std_error == EXEC_OUTPUT_FILE_TRUNCATE) |
5848 | fprintf(f, "%sStandardErrorFileToTruncate: %s\n", prefix, c->stdio_file[STDERR_FILENO]); | |
befc4a80 | 5849 | |
80876c20 LP |
5850 | if (c->tty_path) |
5851 | fprintf(f, | |
6ea832a2 LP |
5852 | "%sTTYPath: %s\n" |
5853 | "%sTTYReset: %s\n" | |
5854 | "%sTTYVHangup: %s\n" | |
51462135 DDM |
5855 | "%sTTYVTDisallocate: %s\n" |
5856 | "%sTTYRows: %u\n" | |
5857 | "%sTTYColumns: %u\n", | |
6ea832a2 LP |
5858 | prefix, c->tty_path, |
5859 | prefix, yes_no(c->tty_reset), | |
5860 | prefix, yes_no(c->tty_vhangup), | |
51462135 DDM |
5861 | prefix, yes_no(c->tty_vt_disallocate), |
5862 | prefix, c->tty_rows, | |
5863 | prefix, c->tty_cols); | |
94f04347 | 5864 | |
9f6444eb | 5865 | if (IN_SET(c->std_output, |
9f6444eb LP |
5866 | EXEC_OUTPUT_KMSG, |
5867 | EXEC_OUTPUT_JOURNAL, | |
9f6444eb LP |
5868 | EXEC_OUTPUT_KMSG_AND_CONSOLE, |
5869 | EXEC_OUTPUT_JOURNAL_AND_CONSOLE) || | |
5870 | IN_SET(c->std_error, | |
9f6444eb LP |
5871 | EXEC_OUTPUT_KMSG, |
5872 | EXEC_OUTPUT_JOURNAL, | |
9f6444eb LP |
5873 | EXEC_OUTPUT_KMSG_AND_CONSOLE, |
5874 | EXEC_OUTPUT_JOURNAL_AND_CONSOLE)) { | |
f8b69d1d | 5875 | |
5ce70e5b | 5876 | _cleanup_free_ char *fac_str = NULL, *lvl_str = NULL; |
f8b69d1d | 5877 | |
837df140 YW |
5878 | r = log_facility_unshifted_to_string_alloc(c->syslog_priority >> 3, &fac_str); |
5879 | if (r >= 0) | |
5880 | fprintf(f, "%sSyslogFacility: %s\n", prefix, fac_str); | |
f8b69d1d | 5881 | |
837df140 YW |
5882 | r = log_level_to_string_alloc(LOG_PRI(c->syslog_priority), &lvl_str); |
5883 | if (r >= 0) | |
5884 | fprintf(f, "%sSyslogLevel: %s\n", prefix, lvl_str); | |
f8b69d1d | 5885 | } |
94f04347 | 5886 | |
d3070fbd LP |
5887 | if (c->log_level_max >= 0) { |
5888 | _cleanup_free_ char *t = NULL; | |
5889 | ||
5890 | (void) log_level_to_string_alloc(c->log_level_max, &t); | |
5891 | ||
5892 | fprintf(f, "%sLogLevelMax: %s\n", prefix, strna(t)); | |
5893 | } | |
5894 | ||
5291f26d | 5895 | if (c->log_ratelimit_interval_usec > 0) |
90fc172e AZ |
5896 | fprintf(f, |
5897 | "%sLogRateLimitIntervalSec: %s\n", | |
5291f26d | 5898 | prefix, FORMAT_TIMESPAN(c->log_ratelimit_interval_usec, USEC_PER_SEC)); |
90fc172e | 5899 | |
5ac1530e ZJS |
5900 | if (c->log_ratelimit_burst > 0) |
5901 | fprintf(f, "%sLogRateLimitBurst: %u\n", prefix, c->log_ratelimit_burst); | |
90fc172e | 5902 | |
5b10116e ZJS |
5903 | for (size_t j = 0; j < c->n_log_extra_fields; j++) { |
5904 | fprintf(f, "%sLogExtraFields: ", prefix); | |
5905 | fwrite(c->log_extra_fields[j].iov_base, | |
5906 | 1, c->log_extra_fields[j].iov_len, | |
5907 | f); | |
5908 | fputc('\n', f); | |
d3070fbd LP |
5909 | } |
5910 | ||
91dd5f7c LP |
5911 | if (c->log_namespace) |
5912 | fprintf(f, "%sLogNamespace: %s\n", prefix, c->log_namespace); | |
5913 | ||
07d46372 YW |
5914 | if (c->secure_bits) { |
5915 | _cleanup_free_ char *str = NULL; | |
5916 | ||
5917 | r = secure_bits_to_string_alloc(c->secure_bits, &str); | |
5918 | if (r >= 0) | |
5919 | fprintf(f, "%sSecure Bits: %s\n", prefix, str); | |
5920 | } | |
94f04347 | 5921 | |
a103496c | 5922 | if (c->capability_bounding_set != CAP_ALL) { |
dd1f5bd0 | 5923 | _cleanup_free_ char *str = NULL; |
94f04347 | 5924 | |
dd1f5bd0 YW |
5925 | r = capability_set_to_string_alloc(c->capability_bounding_set, &str); |
5926 | if (r >= 0) | |
5927 | fprintf(f, "%sCapabilityBoundingSet: %s\n", prefix, str); | |
755d4b67 IP |
5928 | } |
5929 | ||
5930 | if (c->capability_ambient_set != 0) { | |
dd1f5bd0 | 5931 | _cleanup_free_ char *str = NULL; |
755d4b67 | 5932 | |
dd1f5bd0 YW |
5933 | r = capability_set_to_string_alloc(c->capability_ambient_set, &str); |
5934 | if (r >= 0) | |
5935 | fprintf(f, "%sAmbientCapabilities: %s\n", prefix, str); | |
94f04347 LP |
5936 | } |
5937 | ||
5938 | if (c->user) | |
f2d3769a | 5939 | fprintf(f, "%sUser: %s\n", prefix, c->user); |
94f04347 | 5940 | if (c->group) |
f2d3769a | 5941 | fprintf(f, "%sGroup: %s\n", prefix, c->group); |
94f04347 | 5942 | |
29206d46 LP |
5943 | fprintf(f, "%sDynamicUser: %s\n", prefix, yes_no(c->dynamic_user)); |
5944 | ||
ddc155b2 | 5945 | strv_dump(f, prefix, "SupplementaryGroups", c->supplementary_groups); |
94f04347 | 5946 | |
5b6319dc | 5947 | if (c->pam_name) |
f2d3769a | 5948 | fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name); |
5b6319dc | 5949 | |
ddc155b2 TM |
5950 | strv_dump(f, prefix, "ReadWritePaths", c->read_write_paths); |
5951 | strv_dump(f, prefix, "ReadOnlyPaths", c->read_only_paths); | |
5952 | strv_dump(f, prefix, "InaccessiblePaths", c->inaccessible_paths); | |
5953 | strv_dump(f, prefix, "ExecPaths", c->exec_paths); | |
5954 | strv_dump(f, prefix, "NoExecPaths", c->no_exec_paths); | |
8c35c10d | 5955 | strv_dump(f, prefix, "ExecSearchPath", c->exec_search_path); |
2e22afe9 | 5956 | |
5b10116e ZJS |
5957 | for (size_t i = 0; i < c->n_bind_mounts; i++) |
5958 | fprintf(f, "%s%s: %s%s:%s:%s\n", prefix, | |
5959 | c->bind_mounts[i].read_only ? "BindReadOnlyPaths" : "BindPaths", | |
5960 | c->bind_mounts[i].ignore_enoent ? "-": "", | |
5961 | c->bind_mounts[i].source, | |
5962 | c->bind_mounts[i].destination, | |
5963 | c->bind_mounts[i].recursive ? "rbind" : "norbind"); | |
d2d6c096 | 5964 | |
5b10116e ZJS |
5965 | for (size_t i = 0; i < c->n_temporary_filesystems; i++) { |
5966 | const TemporaryFileSystem *t = c->temporary_filesystems + i; | |
2abd4e38 | 5967 | |
5b10116e ZJS |
5968 | fprintf(f, "%sTemporaryFileSystem: %s%s%s\n", prefix, |
5969 | t->path, | |
5970 | isempty(t->options) ? "" : ":", | |
5971 | strempty(t->options)); | |
5972 | } | |
2abd4e38 | 5973 | |
169c1bda LP |
5974 | if (c->utmp_id) |
5975 | fprintf(f, | |
5976 | "%sUtmpIdentifier: %s\n", | |
5977 | prefix, c->utmp_id); | |
7b52a628 MS |
5978 | |
5979 | if (c->selinux_context) | |
5980 | fprintf(f, | |
5f8640fb LP |
5981 | "%sSELinuxContext: %s%s\n", |
5982 | prefix, c->selinux_context_ignore ? "-" : "", c->selinux_context); | |
17df7223 | 5983 | |
80c21aea WC |
5984 | if (c->apparmor_profile) |
5985 | fprintf(f, | |
5986 | "%sAppArmorProfile: %s%s\n", | |
5987 | prefix, c->apparmor_profile_ignore ? "-" : "", c->apparmor_profile); | |
5988 | ||
5989 | if (c->smack_process_label) | |
5990 | fprintf(f, | |
5991 | "%sSmackProcessLabel: %s%s\n", | |
5992 | prefix, c->smack_process_label_ignore ? "-" : "", c->smack_process_label); | |
5993 | ||
050f7277 | 5994 | if (c->personality != PERSONALITY_INVALID) |
ac45f971 LP |
5995 | fprintf(f, |
5996 | "%sPersonality: %s\n", | |
5997 | prefix, strna(personality_to_string(c->personality))); | |
5998 | ||
78e864e5 TM |
5999 | fprintf(f, |
6000 | "%sLockPersonality: %s\n", | |
6001 | prefix, yes_no(c->lock_personality)); | |
6002 | ||
17df7223 | 6003 | if (c->syscall_filter) { |
349cc4a5 | 6004 | #if HAVE_SECCOMP |
8cfa775f | 6005 | void *id, *val; |
17df7223 | 6006 | bool first = true; |
351a19b1 | 6007 | #endif |
17df7223 LP |
6008 | |
6009 | fprintf(f, | |
57183d11 | 6010 | "%sSystemCallFilter: ", |
17df7223 LP |
6011 | prefix); |
6012 | ||
6b000af4 | 6013 | if (!c->syscall_allow_list) |
17df7223 LP |
6014 | fputc('~', f); |
6015 | ||
349cc4a5 | 6016 | #if HAVE_SECCOMP |
90e74a66 | 6017 | HASHMAP_FOREACH_KEY(val, id, c->syscall_filter) { |
17df7223 | 6018 | _cleanup_free_ char *name = NULL; |
8cfa775f YW |
6019 | const char *errno_name = NULL; |
6020 | int num = PTR_TO_INT(val); | |
17df7223 LP |
6021 | |
6022 | if (first) | |
6023 | first = false; | |
6024 | else | |
6025 | fputc(' ', f); | |
6026 | ||
57183d11 | 6027 | name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1); |
17df7223 | 6028 | fputs(strna(name), f); |
8cfa775f YW |
6029 | |
6030 | if (num >= 0) { | |
005bfaf1 | 6031 | errno_name = seccomp_errno_or_action_to_string(num); |
8cfa775f YW |
6032 | if (errno_name) |
6033 | fprintf(f, ":%s", errno_name); | |
6034 | else | |
6035 | fprintf(f, ":%d", num); | |
6036 | } | |
17df7223 | 6037 | } |
351a19b1 | 6038 | #endif |
17df7223 LP |
6039 | |
6040 | fputc('\n', f); | |
6041 | } | |
6042 | ||
57183d11 | 6043 | if (c->syscall_archs) { |
349cc4a5 | 6044 | #if HAVE_SECCOMP |
57183d11 LP |
6045 | void *id; |
6046 | #endif | |
6047 | ||
6048 | fprintf(f, | |
6049 | "%sSystemCallArchitectures:", | |
6050 | prefix); | |
6051 | ||
349cc4a5 | 6052 | #if HAVE_SECCOMP |
90e74a66 | 6053 | SET_FOREACH(id, c->syscall_archs) |
57183d11 LP |
6054 | fprintf(f, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id) - 1))); |
6055 | #endif | |
6056 | fputc('\n', f); | |
6057 | } | |
6058 | ||
add00535 LP |
6059 | if (exec_context_restrict_namespaces_set(c)) { |
6060 | _cleanup_free_ char *s = NULL; | |
6061 | ||
86c2a9f1 | 6062 | r = namespace_flags_to_string(c->restrict_namespaces, &s); |
add00535 LP |
6063 | if (r >= 0) |
6064 | fprintf(f, "%sRestrictNamespaces: %s\n", | |
dd0395b5 | 6065 | prefix, strna(s)); |
add00535 LP |
6066 | } |
6067 | ||
b1994387 | 6068 | #if HAVE_LIBBPF |
8fe84dc8 YW |
6069 | if (exec_context_restrict_filesystems_set(c)) { |
6070 | char *fs; | |
6071 | SET_FOREACH(fs, c->restrict_filesystems) | |
6072 | fprintf(f, "%sRestrictFileSystems: %s\n", prefix, fs); | |
6073 | } | |
b1994387 ILG |
6074 | #endif |
6075 | ||
a8d08f39 LP |
6076 | if (c->network_namespace_path) |
6077 | fprintf(f, | |
6078 | "%sNetworkNamespacePath: %s\n", | |
6079 | prefix, c->network_namespace_path); | |
6080 | ||
3df90f24 | 6081 | if (c->syscall_errno > 0) { |
005bfaf1 | 6082 | #if HAVE_SECCOMP |
3df90f24 | 6083 | const char *errno_name; |
005bfaf1 | 6084 | #endif |
3df90f24 YW |
6085 | |
6086 | fprintf(f, "%sSystemCallErrorNumber: ", prefix); | |
6087 | ||
005bfaf1 TM |
6088 | #if HAVE_SECCOMP |
6089 | errno_name = seccomp_errno_or_action_to_string(c->syscall_errno); | |
3df90f24 | 6090 | if (errno_name) |
005bfaf1 | 6091 | fputs(errno_name, f); |
3df90f24 | 6092 | else |
005bfaf1 TM |
6093 | fprintf(f, "%d", c->syscall_errno); |
6094 | #endif | |
6095 | fputc('\n', f); | |
3df90f24 | 6096 | } |
b3d13314 | 6097 | |
5b10116e | 6098 | for (size_t i = 0; i < c->n_mount_images; i++) { |
79e20ceb | 6099 | fprintf(f, "%sMountImages: %s%s:%s", prefix, |
b3d13314 LB |
6100 | c->mount_images[i].ignore_enoent ? "-": "", |
6101 | c->mount_images[i].source, | |
79e20ceb | 6102 | c->mount_images[i].destination); |
427353f6 | 6103 | LIST_FOREACH(mount_options, o, c->mount_images[i].mount_options) |
79e20ceb | 6104 | fprintf(f, ":%s:%s", |
427353f6 | 6105 | partition_designator_to_string(o->partition_designator), |
79e20ceb | 6106 | strempty(o->options)); |
427353f6 LB |
6107 | fprintf(f, "\n"); |
6108 | } | |
93f59701 LB |
6109 | |
6110 | for (size_t i = 0; i < c->n_extension_images; i++) { | |
93f59701 LB |
6111 | fprintf(f, "%sExtensionImages: %s%s", prefix, |
6112 | c->extension_images[i].ignore_enoent ? "-": "", | |
6113 | c->extension_images[i].source); | |
6114 | LIST_FOREACH(mount_options, o, c->extension_images[i].mount_options) | |
6115 | fprintf(f, ":%s:%s", | |
6116 | partition_designator_to_string(o->partition_designator), | |
6117 | strempty(o->options)); | |
6118 | fprintf(f, "\n"); | |
6119 | } | |
a07b9926 LB |
6120 | |
6121 | strv_dump(f, prefix, "ExtensionDirectories", c->extension_directories); | |
5cb5a6ff LP |
6122 | } |
6123 | ||
34cf6c43 | 6124 | bool exec_context_maintains_privileges(const ExecContext *c) { |
a931ad47 LP |
6125 | assert(c); |
6126 | ||
61233823 | 6127 | /* Returns true if the process forked off would run under |
a931ad47 LP |
6128 | * an unchanged UID or as root. */ |
6129 | ||
6130 | if (!c->user) | |
6131 | return true; | |
6132 | ||
6133 | if (streq(c->user, "root") || streq(c->user, "0")) | |
6134 | return true; | |
6135 | ||
6136 | return false; | |
6137 | } | |
6138 | ||
34cf6c43 | 6139 | int exec_context_get_effective_ioprio(const ExecContext *c) { |
7f452159 LP |
6140 | int p; |
6141 | ||
6142 | assert(c); | |
6143 | ||
6144 | if (c->ioprio_set) | |
6145 | return c->ioprio; | |
6146 | ||
6147 | p = ioprio_get(IOPRIO_WHO_PROCESS, 0); | |
6148 | if (p < 0) | |
0692548c | 6149 | return IOPRIO_DEFAULT_CLASS_AND_PRIO; |
7f452159 | 6150 | |
8b330d7d | 6151 | return ioprio_normalize(p); |
7f452159 LP |
6152 | } |
6153 | ||
5e98086d ZJS |
6154 | bool exec_context_get_effective_mount_apivfs(const ExecContext *c) { |
6155 | assert(c); | |
6156 | ||
61198784 | 6157 | /* Explicit setting wins */ |
5e98086d ZJS |
6158 | if (c->mount_apivfs_set) |
6159 | return c->mount_apivfs; | |
6160 | ||
61198784 | 6161 | /* Default to "yes" if root directory or image are specified */ |
74e12520 | 6162 | if (exec_context_with_rootfs(c)) |
61198784 ZJS |
6163 | return true; |
6164 | ||
5e98086d ZJS |
6165 | return false; |
6166 | } | |
6167 | ||
d3070fbd | 6168 | void exec_context_free_log_extra_fields(ExecContext *c) { |
d3070fbd LP |
6169 | assert(c); |
6170 | ||
5b10116e | 6171 | for (size_t l = 0; l < c->n_log_extra_fields; l++) |
d3070fbd LP |
6172 | free(c->log_extra_fields[l].iov_base); |
6173 | c->log_extra_fields = mfree(c->log_extra_fields); | |
6174 | c->n_log_extra_fields = 0; | |
6175 | } | |
6176 | ||
6f765baf | 6177 | void exec_context_revert_tty(ExecContext *c) { |
0ba976e8 LP |
6178 | _cleanup_close_ int fd = -1; |
6179 | const char *path; | |
6180 | struct stat st; | |
6f765baf LP |
6181 | int r; |
6182 | ||
6183 | assert(c); | |
6184 | ||
6185 | /* First, reset the TTY (possibly kicking everybody else from the TTY) */ | |
6186 | exec_context_tty_reset(c, NULL); | |
6187 | ||
6188 | /* And then undo what chown_terminal() did earlier. Note that we only do this if we have a path | |
6189 | * configured. If the TTY was passed to us as file descriptor we assume the TTY is opened and managed | |
6190 | * by whoever passed it to us and thus knows better when and how to chmod()/chown() it back. */ | |
0ba976e8 LP |
6191 | if (!exec_context_may_touch_tty(c)) |
6192 | return; | |
6f765baf | 6193 | |
0ba976e8 LP |
6194 | path = exec_context_tty_path(c); |
6195 | if (!path) | |
6196 | return; | |
6f765baf | 6197 | |
0ba976e8 LP |
6198 | fd = open(path, O_PATH|O_CLOEXEC); |
6199 | if (fd < 0) | |
6200 | return (void) log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno, | |
6201 | "Failed to open TTY inode of '%s' to adjust ownership/access mode, ignoring: %m", | |
6202 | path); | |
6203 | ||
6204 | if (fstat(fd, &st) < 0) | |
6205 | return (void) log_warning_errno(errno, "Failed to stat TTY '%s', ignoring: %m", path); | |
6206 | ||
6207 | /* Let's add a superficial check that we only do this for stuff that looks like a TTY. We only check | |
6208 | * if things are a character device, since a proper check either means we'd have to open the TTY and | |
6209 | * use isatty(), but we'd rather not do that since opening TTYs comes with all kinds of side-effects | |
6210 | * and is slow. Or we'd have to hardcode dev_t major information, which we'd rather avoid. Why bother | |
6211 | * with this at all? → https://github.com/systemd/systemd/issues/19213 */ | |
6212 | if (!S_ISCHR(st.st_mode)) | |
6213 | return log_warning("Configured TTY '%s' is not actually a character device, ignoring.", path); | |
6214 | ||
6215 | r = fchmod_and_chown(fd, TTY_MODE, 0, TTY_GID); | |
6216 | if (r < 0) | |
6217 | log_warning_errno(r, "Failed to reset TTY ownership/access mode of %s, ignoring: %m", path); | |
6f765baf LP |
6218 | } |
6219 | ||
4c2f5842 LP |
6220 | int exec_context_get_clean_directories( |
6221 | ExecContext *c, | |
6222 | char **prefix, | |
6223 | ExecCleanMask mask, | |
6224 | char ***ret) { | |
6225 | ||
6226 | _cleanup_strv_free_ char **l = NULL; | |
4c2f5842 LP |
6227 | int r; |
6228 | ||
6229 | assert(c); | |
6230 | assert(prefix); | |
6231 | assert(ret); | |
6232 | ||
5b10116e | 6233 | for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) { |
4c2f5842 LP |
6234 | if (!FLAGS_SET(mask, 1U << t)) |
6235 | continue; | |
6236 | ||
6237 | if (!prefix[t]) | |
6238 | continue; | |
6239 | ||
211a3d87 | 6240 | for (size_t i = 0; i < c->directories[t].n_items; i++) { |
4c2f5842 LP |
6241 | char *j; |
6242 | ||
211a3d87 | 6243 | j = path_join(prefix[t], c->directories[t].items[i].path); |
4c2f5842 LP |
6244 | if (!j) |
6245 | return -ENOMEM; | |
6246 | ||
6247 | r = strv_consume(&l, j); | |
6248 | if (r < 0) | |
6249 | return r; | |
7f622a19 YW |
6250 | |
6251 | /* Also remove private directories unconditionally. */ | |
6252 | if (t != EXEC_DIRECTORY_CONFIGURATION) { | |
211a3d87 LB |
6253 | j = path_join(prefix[t], "private", c->directories[t].items[i].path); |
6254 | if (!j) | |
6255 | return -ENOMEM; | |
6256 | ||
6257 | r = strv_consume(&l, j); | |
6258 | if (r < 0) | |
6259 | return r; | |
6260 | } | |
6261 | ||
211a3d87 LB |
6262 | STRV_FOREACH(symlink, c->directories[t].items[i].symlinks) { |
6263 | j = path_join(prefix[t], *symlink); | |
7f622a19 YW |
6264 | if (!j) |
6265 | return -ENOMEM; | |
6266 | ||
6267 | r = strv_consume(&l, j); | |
6268 | if (r < 0) | |
6269 | return r; | |
6270 | } | |
4c2f5842 LP |
6271 | } |
6272 | } | |
6273 | ||
6274 | *ret = TAKE_PTR(l); | |
6275 | return 0; | |
6276 | } | |
6277 | ||
6278 | int exec_context_get_clean_mask(ExecContext *c, ExecCleanMask *ret) { | |
6279 | ExecCleanMask mask = 0; | |
6280 | ||
6281 | assert(c); | |
6282 | assert(ret); | |
6283 | ||
6284 | for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) | |
211a3d87 | 6285 | if (c->directories[t].n_items > 0) |
4c2f5842 LP |
6286 | mask |= 1U << t; |
6287 | ||
6288 | *ret = mask; | |
6289 | return 0; | |
6290 | } | |
6291 | ||
b58b4116 | 6292 | void exec_status_start(ExecStatus *s, pid_t pid) { |
034c6ed7 | 6293 | assert(s); |
5cb5a6ff | 6294 | |
2ed26ed0 LP |
6295 | *s = (ExecStatus) { |
6296 | .pid = pid, | |
6297 | }; | |
6298 | ||
b58b4116 LP |
6299 | dual_timestamp_get(&s->start_timestamp); |
6300 | } | |
6301 | ||
34cf6c43 | 6302 | void exec_status_exit(ExecStatus *s, const ExecContext *context, pid_t pid, int code, int status) { |
b58b4116 LP |
6303 | assert(s); |
6304 | ||
d46b79bb | 6305 | if (s->pid != pid) |
2ed26ed0 LP |
6306 | *s = (ExecStatus) { |
6307 | .pid = pid, | |
6308 | }; | |
b58b4116 | 6309 | |
63983207 | 6310 | dual_timestamp_get(&s->exit_timestamp); |
9fb86720 | 6311 | |
034c6ed7 LP |
6312 | s->code = code; |
6313 | s->status = status; | |
169c1bda | 6314 | |
6f765baf LP |
6315 | if (context && context->utmp_id) |
6316 | (void) utmp_put_dead_process(context->utmp_id, pid, code, status); | |
9fb86720 LP |
6317 | } |
6318 | ||
6a1d4d9f LP |
6319 | void exec_status_reset(ExecStatus *s) { |
6320 | assert(s); | |
6321 | ||
6322 | *s = (ExecStatus) {}; | |
6323 | } | |
6324 | ||
34cf6c43 | 6325 | void exec_status_dump(const ExecStatus *s, FILE *f, const char *prefix) { |
9fb86720 LP |
6326 | assert(s); |
6327 | assert(f); | |
6328 | ||
9fb86720 LP |
6329 | if (s->pid <= 0) |
6330 | return; | |
6331 | ||
4c940960 LP |
6332 | prefix = strempty(prefix); |
6333 | ||
9fb86720 | 6334 | fprintf(f, |
ccd06097 ZJS |
6335 | "%sPID: "PID_FMT"\n", |
6336 | prefix, s->pid); | |
9fb86720 | 6337 | |
af9d16e1 | 6338 | if (dual_timestamp_is_set(&s->start_timestamp)) |
9fb86720 LP |
6339 | fprintf(f, |
6340 | "%sStart Timestamp: %s\n", | |
04f5c018 | 6341 | prefix, FORMAT_TIMESTAMP(s->start_timestamp.realtime)); |
9fb86720 | 6342 | |
af9d16e1 | 6343 | if (dual_timestamp_is_set(&s->exit_timestamp)) |
9fb86720 LP |
6344 | fprintf(f, |
6345 | "%sExit Timestamp: %s\n" | |
6346 | "%sExit Code: %s\n" | |
6347 | "%sExit Status: %i\n", | |
04f5c018 | 6348 | prefix, FORMAT_TIMESTAMP(s->exit_timestamp.realtime), |
9fb86720 LP |
6349 | prefix, sigchld_code_to_string(s->code), |
6350 | prefix, s->status); | |
5cb5a6ff | 6351 | } |
44d8db9e | 6352 | |
34cf6c43 | 6353 | static void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) { |
e1d75803 | 6354 | _cleanup_free_ char *cmd = NULL; |
4c940960 | 6355 | const char *prefix2; |
44d8db9e LP |
6356 | |
6357 | assert(c); | |
6358 | assert(f); | |
6359 | ||
4c940960 | 6360 | prefix = strempty(prefix); |
63c372cb | 6361 | prefix2 = strjoina(prefix, "\t"); |
44d8db9e | 6362 | |
4ef15008 | 6363 | cmd = quote_command_line(c->argv, SHELL_ESCAPE_EMPTY); |
44d8db9e LP |
6364 | fprintf(f, |
6365 | "%sCommand Line: %s\n", | |
7c248223 | 6366 | prefix, cmd ?: strerror_safe(ENOMEM)); |
44d8db9e | 6367 | |
9fb86720 | 6368 | exec_status_dump(&c->exec_status, f, prefix2); |
44d8db9e LP |
6369 | } |
6370 | ||
6371 | void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) { | |
6372 | assert(f); | |
6373 | ||
4c940960 | 6374 | prefix = strempty(prefix); |
44d8db9e | 6375 | |
03677889 YW |
6376 | LIST_FOREACH(command, i, c) |
6377 | exec_command_dump(i, f, prefix); | |
44d8db9e | 6378 | } |
94f04347 | 6379 | |
a6a80b4f LP |
6380 | void exec_command_append_list(ExecCommand **l, ExecCommand *e) { |
6381 | ExecCommand *end; | |
6382 | ||
6383 | assert(l); | |
6384 | assert(e); | |
6385 | ||
6386 | if (*l) { | |
35b8ca3a | 6387 | /* It's kind of important, that we keep the order here */ |
71fda00f LP |
6388 | LIST_FIND_TAIL(command, *l, end); |
6389 | LIST_INSERT_AFTER(command, *l, end, e); | |
a6a80b4f LP |
6390 | } else |
6391 | *l = e; | |
6392 | } | |
6393 | ||
26fd040d LP |
6394 | int exec_command_set(ExecCommand *c, const char *path, ...) { |
6395 | va_list ap; | |
6396 | char **l, *p; | |
6397 | ||
6398 | assert(c); | |
6399 | assert(path); | |
6400 | ||
6401 | va_start(ap, path); | |
6402 | l = strv_new_ap(path, ap); | |
6403 | va_end(ap); | |
6404 | ||
6405 | if (!l) | |
6406 | return -ENOMEM; | |
6407 | ||
250a918d LP |
6408 | p = strdup(path); |
6409 | if (!p) { | |
26fd040d LP |
6410 | strv_free(l); |
6411 | return -ENOMEM; | |
6412 | } | |
6413 | ||
6897dfe8 | 6414 | free_and_replace(c->path, p); |
26fd040d | 6415 | |
130d3d22 | 6416 | return strv_free_and_replace(c->argv, l); |
26fd040d LP |
6417 | } |
6418 | ||
86b23b07 | 6419 | int exec_command_append(ExecCommand *c, const char *path, ...) { |
e63ff941 | 6420 | _cleanup_strv_free_ char **l = NULL; |
86b23b07 | 6421 | va_list ap; |
86b23b07 JS |
6422 | int r; |
6423 | ||
6424 | assert(c); | |
6425 | assert(path); | |
6426 | ||
6427 | va_start(ap, path); | |
6428 | l = strv_new_ap(path, ap); | |
6429 | va_end(ap); | |
6430 | ||
6431 | if (!l) | |
6432 | return -ENOMEM; | |
6433 | ||
e287086b | 6434 | r = strv_extend_strv(&c->argv, l, false); |
e63ff941 | 6435 | if (r < 0) |
86b23b07 | 6436 | return r; |
86b23b07 JS |
6437 | |
6438 | return 0; | |
6439 | } | |
6440 | ||
e8a565cb YW |
6441 | static void *remove_tmpdir_thread(void *p) { |
6442 | _cleanup_free_ char *path = p; | |
86b23b07 | 6443 | |
e8a565cb YW |
6444 | (void) rm_rf(path, REMOVE_ROOT|REMOVE_PHYSICAL); |
6445 | return NULL; | |
6446 | } | |
6447 | ||
6448 | static ExecRuntime* exec_runtime_free(ExecRuntime *rt, bool destroy) { | |
6449 | int r; | |
6450 | ||
6451 | if (!rt) | |
6452 | return NULL; | |
6453 | ||
6454 | if (rt->manager) | |
6455 | (void) hashmap_remove(rt->manager->exec_runtime_by_id, rt->id); | |
6456 | ||
6457 | /* When destroy is true, then rm_rf tmp_dir and var_tmp_dir. */ | |
56a13a49 ZJS |
6458 | |
6459 | if (destroy && rt->tmp_dir && !streq(rt->tmp_dir, RUN_SYSTEMD_EMPTY)) { | |
e8a565cb YW |
6460 | log_debug("Spawning thread to nuke %s", rt->tmp_dir); |
6461 | ||
6462 | r = asynchronous_job(remove_tmpdir_thread, rt->tmp_dir); | |
56a13a49 | 6463 | if (r < 0) |
e8a565cb | 6464 | log_warning_errno(r, "Failed to nuke %s: %m", rt->tmp_dir); |
56a13a49 ZJS |
6465 | else |
6466 | rt->tmp_dir = NULL; | |
e8a565cb | 6467 | } |
613b411c | 6468 | |
56a13a49 | 6469 | if (destroy && rt->var_tmp_dir && !streq(rt->var_tmp_dir, RUN_SYSTEMD_EMPTY)) { |
e8a565cb YW |
6470 | log_debug("Spawning thread to nuke %s", rt->var_tmp_dir); |
6471 | ||
6472 | r = asynchronous_job(remove_tmpdir_thread, rt->var_tmp_dir); | |
56a13a49 | 6473 | if (r < 0) |
e8a565cb | 6474 | log_warning_errno(r, "Failed to nuke %s: %m", rt->var_tmp_dir); |
56a13a49 ZJS |
6475 | else |
6476 | rt->var_tmp_dir = NULL; | |
e8a565cb YW |
6477 | } |
6478 | ||
6479 | rt->id = mfree(rt->id); | |
6480 | rt->tmp_dir = mfree(rt->tmp_dir); | |
6481 | rt->var_tmp_dir = mfree(rt->var_tmp_dir); | |
6482 | safe_close_pair(rt->netns_storage_socket); | |
a70581ff | 6483 | safe_close_pair(rt->ipcns_storage_socket); |
e8a565cb YW |
6484 | return mfree(rt); |
6485 | } | |
6486 | ||
6487 | static void exec_runtime_freep(ExecRuntime **rt) { | |
da6bc6ed | 6488 | (void) exec_runtime_free(*rt, false); |
e8a565cb YW |
6489 | } |
6490 | ||
56a13a49 ZJS |
6491 | static int exec_runtime_allocate(ExecRuntime **ret, const char *id) { |
6492 | _cleanup_free_ char *id_copy = NULL; | |
8e8009dc | 6493 | ExecRuntime *n; |
613b411c | 6494 | |
8e8009dc | 6495 | assert(ret); |
613b411c | 6496 | |
56a13a49 ZJS |
6497 | id_copy = strdup(id); |
6498 | if (!id_copy) | |
6499 | return -ENOMEM; | |
6500 | ||
8e8009dc LP |
6501 | n = new(ExecRuntime, 1); |
6502 | if (!n) | |
613b411c LP |
6503 | return -ENOMEM; |
6504 | ||
8e8009dc | 6505 | *n = (ExecRuntime) { |
56a13a49 | 6506 | .id = TAKE_PTR(id_copy), |
8e8009dc | 6507 | .netns_storage_socket = { -1, -1 }, |
a70581ff | 6508 | .ipcns_storage_socket = { -1, -1 }, |
8e8009dc LP |
6509 | }; |
6510 | ||
6511 | *ret = n; | |
613b411c LP |
6512 | return 0; |
6513 | } | |
6514 | ||
e8a565cb YW |
6515 | static int exec_runtime_add( |
6516 | Manager *m, | |
6517 | const char *id, | |
56a13a49 ZJS |
6518 | char **tmp_dir, |
6519 | char **var_tmp_dir, | |
6520 | int netns_storage_socket[2], | |
a70581ff | 6521 | int ipcns_storage_socket[2], |
e8a565cb YW |
6522 | ExecRuntime **ret) { |
6523 | ||
6524 | _cleanup_(exec_runtime_freep) ExecRuntime *rt = NULL; | |
613b411c LP |
6525 | int r; |
6526 | ||
e8a565cb | 6527 | assert(m); |
613b411c LP |
6528 | assert(id); |
6529 | ||
a70581ff | 6530 | /* tmp_dir, var_tmp_dir, {net,ipc}ns_storage_socket fds are donated on success */ |
56a13a49 | 6531 | |
56a13a49 | 6532 | r = exec_runtime_allocate(&rt, id); |
613b411c LP |
6533 | if (r < 0) |
6534 | return r; | |
6535 | ||
63083706 | 6536 | r = hashmap_ensure_put(&m->exec_runtime_by_id, &string_hash_ops, rt->id, rt); |
56a13a49 ZJS |
6537 | if (r < 0) |
6538 | return r; | |
e8a565cb | 6539 | |
56a13a49 ZJS |
6540 | assert(!!rt->tmp_dir == !!rt->var_tmp_dir); /* We require both to be set together */ |
6541 | rt->tmp_dir = TAKE_PTR(*tmp_dir); | |
6542 | rt->var_tmp_dir = TAKE_PTR(*var_tmp_dir); | |
e8a565cb YW |
6543 | |
6544 | if (netns_storage_socket) { | |
56a13a49 ZJS |
6545 | rt->netns_storage_socket[0] = TAKE_FD(netns_storage_socket[0]); |
6546 | rt->netns_storage_socket[1] = TAKE_FD(netns_storage_socket[1]); | |
613b411c LP |
6547 | } |
6548 | ||
a70581ff XR |
6549 | if (ipcns_storage_socket) { |
6550 | rt->ipcns_storage_socket[0] = TAKE_FD(ipcns_storage_socket[0]); | |
6551 | rt->ipcns_storage_socket[1] = TAKE_FD(ipcns_storage_socket[1]); | |
6552 | } | |
6553 | ||
e8a565cb YW |
6554 | rt->manager = m; |
6555 | ||
6556 | if (ret) | |
6557 | *ret = rt; | |
e8a565cb | 6558 | /* do not remove created ExecRuntime object when the operation succeeds. */ |
56a13a49 | 6559 | TAKE_PTR(rt); |
e8a565cb YW |
6560 | return 0; |
6561 | } | |
6562 | ||
74aaf59b LP |
6563 | static int exec_runtime_make( |
6564 | Manager *m, | |
6565 | const ExecContext *c, | |
6566 | const char *id, | |
6567 | ExecRuntime **ret) { | |
6568 | ||
56a13a49 | 6569 | _cleanup_(namespace_cleanup_tmpdirp) char *tmp_dir = NULL, *var_tmp_dir = NULL; |
a70581ff | 6570 | _cleanup_close_pair_ int netns_storage_socket[2] = { -1, -1 }, ipcns_storage_socket[2] = { -1, -1 }; |
e8a565cb YW |
6571 | int r; |
6572 | ||
6573 | assert(m); | |
6574 | assert(c); | |
6575 | assert(id); | |
6576 | ||
6577 | /* It is not necessary to create ExecRuntime object. */ | |
a70581ff | 6578 | if (!c->private_network && !c->private_ipc && !c->private_tmp && !c->network_namespace_path) { |
74aaf59b | 6579 | *ret = NULL; |
e8a565cb | 6580 | return 0; |
74aaf59b | 6581 | } |
e8a565cb | 6582 | |
efa2f3a1 TM |
6583 | if (c->private_tmp && |
6584 | !(prefixed_path_strv_contains(c->inaccessible_paths, "/tmp") && | |
6585 | (prefixed_path_strv_contains(c->inaccessible_paths, "/var/tmp") || | |
6586 | prefixed_path_strv_contains(c->inaccessible_paths, "/var")))) { | |
e8a565cb | 6587 | r = setup_tmp_dirs(id, &tmp_dir, &var_tmp_dir); |
613b411c LP |
6588 | if (r < 0) |
6589 | return r; | |
6590 | } | |
6591 | ||
a8d08f39 | 6592 | if (c->private_network || c->network_namespace_path) { |
e8a565cb YW |
6593 | if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, netns_storage_socket) < 0) |
6594 | return -errno; | |
6595 | } | |
6596 | ||
a70581ff XR |
6597 | if (c->private_ipc || c->ipc_namespace_path) { |
6598 | if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, ipcns_storage_socket) < 0) | |
6599 | return -errno; | |
6600 | } | |
6601 | ||
6602 | r = exec_runtime_add(m, id, &tmp_dir, &var_tmp_dir, netns_storage_socket, ipcns_storage_socket, ret); | |
e8a565cb YW |
6603 | if (r < 0) |
6604 | return r; | |
6605 | ||
613b411c LP |
6606 | return 1; |
6607 | } | |
6608 | ||
e8a565cb YW |
6609 | int exec_runtime_acquire(Manager *m, const ExecContext *c, const char *id, bool create, ExecRuntime **ret) { |
6610 | ExecRuntime *rt; | |
6611 | int r; | |
613b411c | 6612 | |
e8a565cb YW |
6613 | assert(m); |
6614 | assert(id); | |
6615 | assert(ret); | |
6616 | ||
6617 | rt = hashmap_get(m->exec_runtime_by_id, id); | |
6618 | if (rt) | |
387f6955 | 6619 | /* We already have an ExecRuntime object, let's increase the ref count and reuse it */ |
e8a565cb YW |
6620 | goto ref; |
6621 | ||
74aaf59b LP |
6622 | if (!create) { |
6623 | *ret = NULL; | |
e8a565cb | 6624 | return 0; |
74aaf59b | 6625 | } |
e8a565cb YW |
6626 | |
6627 | /* If not found, then create a new object. */ | |
6628 | r = exec_runtime_make(m, c, id, &rt); | |
74aaf59b | 6629 | if (r < 0) |
e8a565cb | 6630 | return r; |
74aaf59b LP |
6631 | if (r == 0) { |
6632 | /* When r == 0, it is not necessary to create ExecRuntime object. */ | |
6633 | *ret = NULL; | |
6634 | return 0; | |
6635 | } | |
613b411c | 6636 | |
e8a565cb YW |
6637 | ref: |
6638 | /* increment reference counter. */ | |
6639 | rt->n_ref++; | |
6640 | *ret = rt; | |
6641 | return 1; | |
6642 | } | |
613b411c | 6643 | |
e8a565cb YW |
6644 | ExecRuntime *exec_runtime_unref(ExecRuntime *rt, bool destroy) { |
6645 | if (!rt) | |
613b411c LP |
6646 | return NULL; |
6647 | ||
e8a565cb | 6648 | assert(rt->n_ref > 0); |
613b411c | 6649 | |
e8a565cb YW |
6650 | rt->n_ref--; |
6651 | if (rt->n_ref > 0) | |
f2341e0a LP |
6652 | return NULL; |
6653 | ||
e8a565cb | 6654 | return exec_runtime_free(rt, destroy); |
613b411c LP |
6655 | } |
6656 | ||
e8a565cb YW |
6657 | int exec_runtime_serialize(const Manager *m, FILE *f, FDSet *fds) { |
6658 | ExecRuntime *rt; | |
e8a565cb YW |
6659 | |
6660 | assert(m); | |
613b411c LP |
6661 | assert(f); |
6662 | assert(fds); | |
6663 | ||
90e74a66 | 6664 | HASHMAP_FOREACH(rt, m->exec_runtime_by_id) { |
e8a565cb | 6665 | fprintf(f, "exec-runtime=%s", rt->id); |
613b411c | 6666 | |
e8a565cb YW |
6667 | if (rt->tmp_dir) |
6668 | fprintf(f, " tmp-dir=%s", rt->tmp_dir); | |
613b411c | 6669 | |
e8a565cb YW |
6670 | if (rt->var_tmp_dir) |
6671 | fprintf(f, " var-tmp-dir=%s", rt->var_tmp_dir); | |
613b411c | 6672 | |
e8a565cb YW |
6673 | if (rt->netns_storage_socket[0] >= 0) { |
6674 | int copy; | |
613b411c | 6675 | |
e8a565cb YW |
6676 | copy = fdset_put_dup(fds, rt->netns_storage_socket[0]); |
6677 | if (copy < 0) | |
6678 | return copy; | |
613b411c | 6679 | |
e8a565cb YW |
6680 | fprintf(f, " netns-socket-0=%i", copy); |
6681 | } | |
613b411c | 6682 | |
e8a565cb YW |
6683 | if (rt->netns_storage_socket[1] >= 0) { |
6684 | int copy; | |
613b411c | 6685 | |
e8a565cb YW |
6686 | copy = fdset_put_dup(fds, rt->netns_storage_socket[1]); |
6687 | if (copy < 0) | |
6688 | return copy; | |
613b411c | 6689 | |
e8a565cb YW |
6690 | fprintf(f, " netns-socket-1=%i", copy); |
6691 | } | |
6692 | ||
a70581ff XR |
6693 | if (rt->ipcns_storage_socket[0] >= 0) { |
6694 | int copy; | |
6695 | ||
6696 | copy = fdset_put_dup(fds, rt->ipcns_storage_socket[0]); | |
6697 | if (copy < 0) | |
6698 | return copy; | |
6699 | ||
6700 | fprintf(f, " ipcns-socket-0=%i", copy); | |
6701 | } | |
6702 | ||
6703 | if (rt->ipcns_storage_socket[1] >= 0) { | |
6704 | int copy; | |
6705 | ||
6706 | copy = fdset_put_dup(fds, rt->ipcns_storage_socket[1]); | |
6707 | if (copy < 0) | |
6708 | return copy; | |
6709 | ||
6710 | fprintf(f, " ipcns-socket-1=%i", copy); | |
6711 | } | |
6712 | ||
e8a565cb | 6713 | fputc('\n', f); |
613b411c LP |
6714 | } |
6715 | ||
6716 | return 0; | |
6717 | } | |
6718 | ||
e8a565cb YW |
6719 | int exec_runtime_deserialize_compat(Unit *u, const char *key, const char *value, FDSet *fds) { |
6720 | _cleanup_(exec_runtime_freep) ExecRuntime *rt_create = NULL; | |
6721 | ExecRuntime *rt; | |
613b411c LP |
6722 | int r; |
6723 | ||
e8a565cb YW |
6724 | /* This is for the migration from old (v237 or earlier) deserialization text. |
6725 | * Due to the bug #7790, this may not work with the units that use JoinsNamespaceOf=. | |
6726 | * Even if the ExecRuntime object originally created by the other unit, we cannot judge | |
6727 | * so or not from the serialized text, then we always creates a new object owned by this. */ | |
6728 | ||
6729 | assert(u); | |
613b411c LP |
6730 | assert(key); |
6731 | assert(value); | |
6732 | ||
e8a565cb YW |
6733 | /* Manager manages ExecRuntime objects by the unit id. |
6734 | * So, we omit the serialized text when the unit does not have id (yet?)... */ | |
6735 | if (isempty(u->id)) { | |
6736 | log_unit_debug(u, "Invocation ID not found. Dropping runtime parameter."); | |
6737 | return 0; | |
6738 | } | |
613b411c | 6739 | |
cbc165d1 ZJS |
6740 | if (hashmap_ensure_allocated(&u->manager->exec_runtime_by_id, &string_hash_ops) < 0) |
6741 | return log_oom(); | |
e8a565cb YW |
6742 | |
6743 | rt = hashmap_get(u->manager->exec_runtime_by_id, u->id); | |
6744 | if (!rt) { | |
cbc165d1 | 6745 | if (exec_runtime_allocate(&rt_create, u->id) < 0) |
f2341e0a | 6746 | return log_oom(); |
613b411c | 6747 | |
e8a565cb YW |
6748 | rt = rt_create; |
6749 | } | |
6750 | ||
6751 | if (streq(key, "tmp-dir")) { | |
cbc165d1 ZJS |
6752 | if (free_and_strdup_warn(&rt->tmp_dir, value) < 0) |
6753 | return -ENOMEM; | |
613b411c LP |
6754 | |
6755 | } else if (streq(key, "var-tmp-dir")) { | |
cbc165d1 ZJS |
6756 | if (free_and_strdup_warn(&rt->var_tmp_dir, value) < 0) |
6757 | return -ENOMEM; | |
613b411c LP |
6758 | |
6759 | } else if (streq(key, "netns-socket-0")) { | |
6760 | int fd; | |
6761 | ||
e8a565cb | 6762 | if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd)) { |
f2341e0a | 6763 | log_unit_debug(u, "Failed to parse netns socket value: %s", value); |
e8a565cb | 6764 | return 0; |
613b411c | 6765 | } |
e8a565cb YW |
6766 | |
6767 | safe_close(rt->netns_storage_socket[0]); | |
6768 | rt->netns_storage_socket[0] = fdset_remove(fds, fd); | |
6769 | ||
613b411c LP |
6770 | } else if (streq(key, "netns-socket-1")) { |
6771 | int fd; | |
6772 | ||
e8a565cb | 6773 | if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd)) { |
f2341e0a | 6774 | log_unit_debug(u, "Failed to parse netns socket value: %s", value); |
e8a565cb | 6775 | return 0; |
613b411c | 6776 | } |
e8a565cb YW |
6777 | |
6778 | safe_close(rt->netns_storage_socket[1]); | |
6779 | rt->netns_storage_socket[1] = fdset_remove(fds, fd); | |
a70581ff | 6780 | |
613b411c LP |
6781 | } else |
6782 | return 0; | |
6783 | ||
e8a565cb YW |
6784 | /* If the object is newly created, then put it to the hashmap which manages ExecRuntime objects. */ |
6785 | if (rt_create) { | |
6786 | r = hashmap_put(u->manager->exec_runtime_by_id, rt_create->id, rt_create); | |
6787 | if (r < 0) { | |
3fe91079 | 6788 | log_unit_debug_errno(u, r, "Failed to put runtime parameter to manager's storage: %m"); |
e8a565cb YW |
6789 | return 0; |
6790 | } | |
613b411c | 6791 | |
e8a565cb | 6792 | rt_create->manager = u->manager; |
613b411c | 6793 | |
e8a565cb | 6794 | /* Avoid cleanup */ |
56a13a49 | 6795 | TAKE_PTR(rt_create); |
e8a565cb | 6796 | } |
98b47d54 | 6797 | |
e8a565cb YW |
6798 | return 1; |
6799 | } | |
613b411c | 6800 | |
56a13a49 ZJS |
6801 | int exec_runtime_deserialize_one(Manager *m, const char *value, FDSet *fds) { |
6802 | _cleanup_free_ char *tmp_dir = NULL, *var_tmp_dir = NULL; | |
6803 | char *id = NULL; | |
a70581ff | 6804 | int r, netns_fdpair[] = {-1, -1}, ipcns_fdpair[] = {-1, -1}; |
e8a565cb YW |
6805 | const char *p, *v = value; |
6806 | size_t n; | |
613b411c | 6807 | |
e8a565cb YW |
6808 | assert(m); |
6809 | assert(value); | |
6810 | assert(fds); | |
98b47d54 | 6811 | |
e8a565cb | 6812 | n = strcspn(v, " "); |
2f82562b | 6813 | id = strndupa_safe(v, n); |
e8a565cb YW |
6814 | if (v[n] != ' ') |
6815 | goto finalize; | |
6816 | p = v + n + 1; | |
6817 | ||
6818 | v = startswith(p, "tmp-dir="); | |
6819 | if (v) { | |
6820 | n = strcspn(v, " "); | |
56a13a49 ZJS |
6821 | tmp_dir = strndup(v, n); |
6822 | if (!tmp_dir) | |
6823 | return log_oom(); | |
e8a565cb YW |
6824 | if (v[n] != ' ') |
6825 | goto finalize; | |
6826 | p = v + n + 1; | |
6827 | } | |
6828 | ||
6829 | v = startswith(p, "var-tmp-dir="); | |
6830 | if (v) { | |
6831 | n = strcspn(v, " "); | |
56a13a49 ZJS |
6832 | var_tmp_dir = strndup(v, n); |
6833 | if (!var_tmp_dir) | |
6834 | return log_oom(); | |
e8a565cb YW |
6835 | if (v[n] != ' ') |
6836 | goto finalize; | |
6837 | p = v + n + 1; | |
6838 | } | |
6839 | ||
6840 | v = startswith(p, "netns-socket-0="); | |
6841 | if (v) { | |
6842 | char *buf; | |
6843 | ||
6844 | n = strcspn(v, " "); | |
2f82562b | 6845 | buf = strndupa_safe(v, n); |
c413bb28 | 6846 | |
a70581ff | 6847 | r = safe_atoi(buf, &netns_fdpair[0]); |
c413bb28 ZJS |
6848 | if (r < 0) |
6849 | return log_debug_errno(r, "Unable to parse exec-runtime specification netns-socket-0=%s: %m", buf); | |
a70581ff | 6850 | if (!fdset_contains(fds, netns_fdpair[0])) |
c413bb28 | 6851 | return log_debug_errno(SYNTHETIC_ERRNO(EBADF), |
a70581ff XR |
6852 | "exec-runtime specification netns-socket-0= refers to unknown fd %d: %m", netns_fdpair[0]); |
6853 | netns_fdpair[0] = fdset_remove(fds, netns_fdpair[0]); | |
e8a565cb YW |
6854 | if (v[n] != ' ') |
6855 | goto finalize; | |
6856 | p = v + n + 1; | |
613b411c LP |
6857 | } |
6858 | ||
e8a565cb YW |
6859 | v = startswith(p, "netns-socket-1="); |
6860 | if (v) { | |
6861 | char *buf; | |
98b47d54 | 6862 | |
e8a565cb | 6863 | n = strcspn(v, " "); |
2f82562b | 6864 | buf = strndupa_safe(v, n); |
a70581ff XR |
6865 | |
6866 | r = safe_atoi(buf, &netns_fdpair[1]); | |
c413bb28 ZJS |
6867 | if (r < 0) |
6868 | return log_debug_errno(r, "Unable to parse exec-runtime specification netns-socket-1=%s: %m", buf); | |
a70581ff XR |
6869 | if (!fdset_contains(fds, netns_fdpair[1])) |
6870 | return log_debug_errno(SYNTHETIC_ERRNO(EBADF), | |
6871 | "exec-runtime specification netns-socket-1= refers to unknown fd %d: %m", netns_fdpair[1]); | |
6872 | netns_fdpair[1] = fdset_remove(fds, netns_fdpair[1]); | |
6873 | if (v[n] != ' ') | |
6874 | goto finalize; | |
6875 | p = v + n + 1; | |
6876 | } | |
6877 | ||
6878 | v = startswith(p, "ipcns-socket-0="); | |
6879 | if (v) { | |
6880 | char *buf; | |
6881 | ||
6882 | n = strcspn(v, " "); | |
2f82562b | 6883 | buf = strndupa_safe(v, n); |
a70581ff XR |
6884 | |
6885 | r = safe_atoi(buf, &ipcns_fdpair[0]); | |
6886 | if (r < 0) | |
6887 | return log_debug_errno(r, "Unable to parse exec-runtime specification ipcns-socket-0=%s: %m", buf); | |
6888 | if (!fdset_contains(fds, ipcns_fdpair[0])) | |
6889 | return log_debug_errno(SYNTHETIC_ERRNO(EBADF), | |
6890 | "exec-runtime specification ipcns-socket-0= refers to unknown fd %d: %m", ipcns_fdpair[0]); | |
6891 | ipcns_fdpair[0] = fdset_remove(fds, ipcns_fdpair[0]); | |
6892 | if (v[n] != ' ') | |
6893 | goto finalize; | |
6894 | p = v + n + 1; | |
6895 | } | |
6896 | ||
6897 | v = startswith(p, "ipcns-socket-1="); | |
6898 | if (v) { | |
6899 | char *buf; | |
6900 | ||
6901 | n = strcspn(v, " "); | |
2f82562b | 6902 | buf = strndupa_safe(v, n); |
a70581ff XR |
6903 | |
6904 | r = safe_atoi(buf, &ipcns_fdpair[1]); | |
6905 | if (r < 0) | |
6906 | return log_debug_errno(r, "Unable to parse exec-runtime specification ipcns-socket-1=%s: %m", buf); | |
6907 | if (!fdset_contains(fds, ipcns_fdpair[1])) | |
c413bb28 | 6908 | return log_debug_errno(SYNTHETIC_ERRNO(EBADF), |
a70581ff XR |
6909 | "exec-runtime specification ipcns-socket-1= refers to unknown fd %d: %m", ipcns_fdpair[1]); |
6910 | ipcns_fdpair[1] = fdset_remove(fds, ipcns_fdpair[1]); | |
e8a565cb | 6911 | } |
98b47d54 | 6912 | |
e8a565cb | 6913 | finalize: |
a70581ff | 6914 | r = exec_runtime_add(m, id, &tmp_dir, &var_tmp_dir, netns_fdpair, ipcns_fdpair, NULL); |
7d853ca6 | 6915 | if (r < 0) |
56a13a49 ZJS |
6916 | return log_debug_errno(r, "Failed to add exec-runtime: %m"); |
6917 | return 0; | |
e8a565cb | 6918 | } |
613b411c | 6919 | |
e8a565cb YW |
6920 | void exec_runtime_vacuum(Manager *m) { |
6921 | ExecRuntime *rt; | |
e8a565cb YW |
6922 | |
6923 | assert(m); | |
6924 | ||
6925 | /* Free unreferenced ExecRuntime objects. This is used after manager deserialization process. */ | |
6926 | ||
90e74a66 | 6927 | HASHMAP_FOREACH(rt, m->exec_runtime_by_id) { |
e8a565cb YW |
6928 | if (rt->n_ref > 0) |
6929 | continue; | |
6930 | ||
6931 | (void) exec_runtime_free(rt, false); | |
6932 | } | |
613b411c LP |
6933 | } |
6934 | ||
b9c04eaf YW |
6935 | void exec_params_clear(ExecParameters *p) { |
6936 | if (!p) | |
6937 | return; | |
6938 | ||
c3f8a065 LP |
6939 | p->environment = strv_free(p->environment); |
6940 | p->fd_names = strv_free(p->fd_names); | |
6941 | p->fds = mfree(p->fds); | |
6942 | p->exec_fd = safe_close(p->exec_fd); | |
b9c04eaf YW |
6943 | } |
6944 | ||
bb0c0d6f LP |
6945 | ExecSetCredential *exec_set_credential_free(ExecSetCredential *sc) { |
6946 | if (!sc) | |
6947 | return NULL; | |
6948 | ||
6949 | free(sc->id); | |
6950 | free(sc->data); | |
6951 | return mfree(sc); | |
6952 | } | |
6953 | ||
43144be4 LP |
6954 | ExecLoadCredential *exec_load_credential_free(ExecLoadCredential *lc) { |
6955 | if (!lc) | |
6956 | return NULL; | |
6957 | ||
6958 | free(lc->id); | |
6959 | free(lc->path); | |
6960 | return mfree(lc); | |
6961 | } | |
6962 | ||
211a3d87 LB |
6963 | void exec_directory_done(ExecDirectory *d) { |
6964 | if (!d) | |
6965 | return; | |
6966 | ||
6967 | for (size_t i = 0; i < d->n_items; i++) { | |
6968 | free(d->items[i].path); | |
6969 | strv_free(d->items[i].symlinks); | |
6970 | } | |
6971 | ||
6972 | d->items = mfree(d->items); | |
6973 | d->n_items = 0; | |
6974 | d->mode = 0755; | |
6975 | } | |
6976 | ||
6977 | int exec_directory_add(ExecDirectoryItem **d, size_t *n, const char *path, char **symlinks) { | |
6978 | _cleanup_strv_free_ char **s = NULL; | |
6979 | _cleanup_free_ char *p = NULL; | |
6980 | ||
6981 | assert(d); | |
6982 | assert(n); | |
6983 | assert(path); | |
6984 | ||
6985 | p = strdup(path); | |
6986 | if (!p) | |
6987 | return -ENOMEM; | |
6988 | ||
6989 | if (symlinks) { | |
6990 | s = strv_copy(symlinks); | |
6991 | if (!s) | |
6992 | return -ENOMEM; | |
6993 | } | |
6994 | ||
6995 | if (!GREEDY_REALLOC(*d, *n + 1)) | |
6996 | return -ENOMEM; | |
6997 | ||
6998 | (*d)[(*n) ++] = (ExecDirectoryItem) { | |
6999 | .path = TAKE_PTR(p), | |
7000 | .symlinks = TAKE_PTR(s), | |
7001 | }; | |
7002 | ||
7003 | return 0; | |
7004 | } | |
7005 | ||
bb0c0d6f | 7006 | DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(exec_set_credential_hash_ops, char, string_hash_func, string_compare_func, ExecSetCredential, exec_set_credential_free); |
43144be4 | 7007 | DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(exec_load_credential_hash_ops, char, string_hash_func, string_compare_func, ExecLoadCredential, exec_load_credential_free); |
bb0c0d6f | 7008 | |
80876c20 LP |
7009 | static const char* const exec_input_table[_EXEC_INPUT_MAX] = { |
7010 | [EXEC_INPUT_NULL] = "null", | |
7011 | [EXEC_INPUT_TTY] = "tty", | |
7012 | [EXEC_INPUT_TTY_FORCE] = "tty-force", | |
4f2d528d | 7013 | [EXEC_INPUT_TTY_FAIL] = "tty-fail", |
52c239d7 LB |
7014 | [EXEC_INPUT_SOCKET] = "socket", |
7015 | [EXEC_INPUT_NAMED_FD] = "fd", | |
08f3be7a | 7016 | [EXEC_INPUT_DATA] = "data", |
2038c3f5 | 7017 | [EXEC_INPUT_FILE] = "file", |
80876c20 LP |
7018 | }; |
7019 | ||
8a0867d6 LP |
7020 | DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput); |
7021 | ||
94f04347 | 7022 | static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = { |
80876c20 | 7023 | [EXEC_OUTPUT_INHERIT] = "inherit", |
94f04347 | 7024 | [EXEC_OUTPUT_NULL] = "null", |
80876c20 | 7025 | [EXEC_OUTPUT_TTY] = "tty", |
9a6bca7a | 7026 | [EXEC_OUTPUT_KMSG] = "kmsg", |
28dbc1e8 | 7027 | [EXEC_OUTPUT_KMSG_AND_CONSOLE] = "kmsg+console", |
706343f4 LP |
7028 | [EXEC_OUTPUT_JOURNAL] = "journal", |
7029 | [EXEC_OUTPUT_JOURNAL_AND_CONSOLE] = "journal+console", | |
52c239d7 LB |
7030 | [EXEC_OUTPUT_SOCKET] = "socket", |
7031 | [EXEC_OUTPUT_NAMED_FD] = "fd", | |
2038c3f5 | 7032 | [EXEC_OUTPUT_FILE] = "file", |
566b7d23 | 7033 | [EXEC_OUTPUT_FILE_APPEND] = "append", |
8d7dab1f | 7034 | [EXEC_OUTPUT_FILE_TRUNCATE] = "truncate", |
94f04347 LP |
7035 | }; |
7036 | ||
7037 | DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput); | |
023a4f67 LP |
7038 | |
7039 | static const char* const exec_utmp_mode_table[_EXEC_UTMP_MODE_MAX] = { | |
7040 | [EXEC_UTMP_INIT] = "init", | |
7041 | [EXEC_UTMP_LOGIN] = "login", | |
7042 | [EXEC_UTMP_USER] = "user", | |
7043 | }; | |
7044 | ||
7045 | DEFINE_STRING_TABLE_LOOKUP(exec_utmp_mode, ExecUtmpMode); | |
53f47dfc YW |
7046 | |
7047 | static const char* const exec_preserve_mode_table[_EXEC_PRESERVE_MODE_MAX] = { | |
7048 | [EXEC_PRESERVE_NO] = "no", | |
7049 | [EXEC_PRESERVE_YES] = "yes", | |
7050 | [EXEC_PRESERVE_RESTART] = "restart", | |
7051 | }; | |
7052 | ||
7053 | DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(exec_preserve_mode, ExecPreserveMode, EXEC_PRESERVE_YES); | |
3536f49e | 7054 | |
6b7b2ed9 | 7055 | /* This table maps ExecDirectoryType to the setting it is configured with in the unit */ |
72fd1768 | 7056 | static const char* const exec_directory_type_table[_EXEC_DIRECTORY_TYPE_MAX] = { |
3536f49e YW |
7057 | [EXEC_DIRECTORY_RUNTIME] = "RuntimeDirectory", |
7058 | [EXEC_DIRECTORY_STATE] = "StateDirectory", | |
7059 | [EXEC_DIRECTORY_CACHE] = "CacheDirectory", | |
7060 | [EXEC_DIRECTORY_LOGS] = "LogsDirectory", | |
7061 | [EXEC_DIRECTORY_CONFIGURATION] = "ConfigurationDirectory", | |
7062 | }; | |
7063 | ||
7064 | DEFINE_STRING_TABLE_LOOKUP(exec_directory_type, ExecDirectoryType); | |
b1edf445 | 7065 | |
211a3d87 LB |
7066 | /* This table maps ExecDirectoryType to the symlink setting it is configured with in the unit */ |
7067 | static const char* const exec_directory_type_symlink_table[_EXEC_DIRECTORY_TYPE_MAX] = { | |
7068 | [EXEC_DIRECTORY_RUNTIME] = "RuntimeDirectorySymlink", | |
7069 | [EXEC_DIRECTORY_STATE] = "StateDirectorySymlink", | |
7070 | [EXEC_DIRECTORY_CACHE] = "CacheDirectorySymlink", | |
7071 | [EXEC_DIRECTORY_LOGS] = "LogsDirectorySymlink", | |
7072 | [EXEC_DIRECTORY_CONFIGURATION] = "ConfigurationDirectorySymlink", | |
7073 | }; | |
7074 | ||
7075 | DEFINE_STRING_TABLE_LOOKUP(exec_directory_type_symlink, ExecDirectoryType); | |
7076 | ||
6b7b2ed9 LP |
7077 | /* And this table maps ExecDirectoryType too, but to a generic term identifying the type of resource. This |
7078 | * one is supposed to be generic enough to be used for unit types that don't use ExecContext and per-unit | |
7079 | * directories, specifically .timer units with their timestamp touch file. */ | |
7080 | static const char* const exec_resource_type_table[_EXEC_DIRECTORY_TYPE_MAX] = { | |
7081 | [EXEC_DIRECTORY_RUNTIME] = "runtime", | |
7082 | [EXEC_DIRECTORY_STATE] = "state", | |
7083 | [EXEC_DIRECTORY_CACHE] = "cache", | |
7084 | [EXEC_DIRECTORY_LOGS] = "logs", | |
7085 | [EXEC_DIRECTORY_CONFIGURATION] = "configuration", | |
7086 | }; | |
7087 | ||
7088 | DEFINE_STRING_TABLE_LOOKUP(exec_resource_type, ExecDirectoryType); | |
7089 | ||
7090 | /* And this table also maps ExecDirectoryType, to the environment variable we pass the selected directory to | |
7091 | * the service payload in. */ | |
fb2042dd YW |
7092 | static const char* const exec_directory_env_name_table[_EXEC_DIRECTORY_TYPE_MAX] = { |
7093 | [EXEC_DIRECTORY_RUNTIME] = "RUNTIME_DIRECTORY", | |
7094 | [EXEC_DIRECTORY_STATE] = "STATE_DIRECTORY", | |
7095 | [EXEC_DIRECTORY_CACHE] = "CACHE_DIRECTORY", | |
7096 | [EXEC_DIRECTORY_LOGS] = "LOGS_DIRECTORY", | |
7097 | [EXEC_DIRECTORY_CONFIGURATION] = "CONFIGURATION_DIRECTORY", | |
7098 | }; | |
7099 | ||
7100 | DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(exec_directory_env_name, ExecDirectoryType); | |
7101 | ||
b1edf445 LP |
7102 | static const char* const exec_keyring_mode_table[_EXEC_KEYRING_MODE_MAX] = { |
7103 | [EXEC_KEYRING_INHERIT] = "inherit", | |
7104 | [EXEC_KEYRING_PRIVATE] = "private", | |
7105 | [EXEC_KEYRING_SHARED] = "shared", | |
7106 | }; | |
7107 | ||
7108 | DEFINE_STRING_TABLE_LOOKUP(exec_keyring_mode, ExecKeyringMode); |