• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 15430420074

03 Jun 2025 10:29PM UTC coverage: 72.013% (-0.03%) from 72.041%
15430420074

push

github

yuwata
doc: fix integration tests guide reference

299598 of 416033 relevant lines covered (72.01%)

700977.9 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

72.36
/src/core/exec-invoke.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <grp.h>
4
#include <linux/ioprio.h>
5
#include <linux/prctl.h>
6
#include <linux/sched.h>
7
#include <linux/securebits.h>
8
#include <poll.h>
9
#include <sys/eventfd.h>
10
#include <sys/ioctl.h>
11
#include <sys/mount.h>
12
#include <sys/prctl.h>
13

14
#if HAVE_PAM
15
#include <security/pam_appl.h>
16
#endif
17

18
#include "sd-messages.h"
19

20
#include "apparmor-util.h"
21
#include "argv-util.h"
22
#include "ask-password-api.h"
23
#include "barrier.h"
24
#include "bitfield.h"
25
#include "bpf-dlopen.h"
26
#include "bpf-restrict-fs.h"
27
#include "btrfs-util.h"
28
#include "capability-util.h"
29
#include "cgroup-setup.h"
30
#include "cgroup.h"
31
#include "chase.h"
32
#include "chown-recursive.h"
33
#include "constants.h"
34
#include "copy.h"
35
#include "coredump-util.h"
36
#include "dissect-image.h"
37
#include "dynamic-user.h"
38
#include "env-util.h"
39
#include "escape.h"
40
#include "exec-credential.h"
41
#include "exec-invoke.h"
42
#include "execute.h"
43
#include "exit-status.h"
44
#include "fd-util.h"
45
#include "fs-util.h"
46
#include "hexdecoct.h"
47
#include "hostname-setup.h"
48
#include "image-policy.h"
49
#include "io-util.h"
50
#include "iovec-util.h"
51
#include "journal-send.h"
52
#include "manager.h"
53
#include "memfd-util.h"
54
#include "missing_sched.h"
55
#include "missing_syscall.h"
56
#include "mkdir-label.h"
57
#include "mount-util.h"
58
#include "namespace-util.h"
59
#include "nsflags.h"
60
#include "open-file.h"
61
#include "osc-context.h"
62
#include "path-util.h"
63
#include "pidref.h"
64
#include "proc-cmdline.h"
65
#include "process-util.h"
66
#include "psi-util.h"
67
#include "rlimit-util.h"
68
#include "seccomp-util.h"
69
#include "selinux-util.h"
70
#include "set.h"
71
#include "signal-util.h"
72
#include "smack-util.h"
73
#include "socket-util.h"
74
#include "stat-util.h"
75
#include "string-table.h"
76
#include "strv.h"
77
#include "terminal-util.h"
78
#include "user-util.h"
79
#include "utmp-wtmp.h"
80
#include "vpick.h"
81

82
#define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
83
#define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
84

85
#define SNDBUF_SIZE (8*1024*1024)
86

87
static int flag_fds(
9,557✔
88
                const int fds[],
89
                size_t n_socket_fds,
90
                size_t n_fds,
91
                bool nonblock) {
92

93
        int r;
9,557✔
94

95
        assert(fds || n_fds == 0);
9,557✔
96

97
        /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags.
98
         * O_NONBLOCK only applies to socket activation though. */
99

100
        for (size_t i = 0; i < n_fds; i++) {
12,134✔
101

102
                if (i < n_socket_fds) {
2,577✔
103
                        r = fd_nonblock(fds[i], nonblock);
2,260✔
104
                        if (r < 0)
2,260✔
105
                                return r;
106
                }
107

108
                /* We unconditionally drop FD_CLOEXEC from the fds,
109
                 * since after all we want to pass these fds to our
110
                 * children */
111

112
                r = fd_cloexec(fds[i], false);
2,577✔
113
                if (r < 0)
2,577✔
114
                        return r;
115
        }
116

117
        return 0;
118
}
119

120
static bool is_terminal_input(ExecInput i) {
42,791✔
121
        return IN_SET(i,
42,791✔
122
                      EXEC_INPUT_TTY,
123
                      EXEC_INPUT_TTY_FORCE,
124
                      EXEC_INPUT_TTY_FAIL);
125
}
126

127
static bool is_terminal_output(ExecOutput o) {
40,140✔
128
        return IN_SET(o,
40,140✔
129
                      EXEC_OUTPUT_TTY,
130
                      EXEC_OUTPUT_KMSG_AND_CONSOLE,
131
                      EXEC_OUTPUT_JOURNAL_AND_CONSOLE);
132
}
133

134
static bool is_kmsg_output(ExecOutput o) {
10,327✔
135
        return IN_SET(o,
10,327✔
136
                      EXEC_OUTPUT_KMSG,
137
                      EXEC_OUTPUT_KMSG_AND_CONSOLE);
138
}
139

140
static int open_null_as(int flags, int nfd) {
10,888✔
141
        int fd;
10,888✔
142

143
        assert(nfd >= 0);
10,888✔
144

145
        fd = open("/dev/null", flags|O_NOCTTY);
10,888✔
146
        if (fd < 0)
10,888✔
147
                return -errno;
×
148

149
        return move_fd(fd, nfd, false);
10,888✔
150
}
151

152
static int connect_journal_socket(
10,327✔
153
                int fd,
154
                const char *log_namespace,
155
                uid_t uid,
156
                gid_t gid) {
157

158
        uid_t olduid = UID_INVALID;
10,327✔
159
        gid_t oldgid = GID_INVALID;
10,327✔
160
        const char *j;
10,327✔
161
        int r;
10,327✔
162

163
        assert(fd >= 0);
10,327✔
164

165
        j = journal_stream_path(log_namespace);
10,339✔
166
        if (!j)
2✔
167
                return -EINVAL;
×
168

169
        if (gid_is_valid(gid)) {
10,327✔
170
                oldgid = getgid();
2,350✔
171

172
                if (setegid(gid) < 0)
2,350✔
173
                        return -errno;
×
174
        }
175

176
        if (uid_is_valid(uid)) {
10,327✔
177
                olduid = getuid();
2,347✔
178

179
                if (seteuid(uid) < 0) {
2,347✔
180
                        r = -errno;
×
181
                        goto restore_gid;
×
182
                }
183
        }
184

185
        r = connect_unix_path(fd, AT_FDCWD, j);
10,327✔
186

187
        /* If we fail to restore the uid or gid, things will likely fail later on. This should only happen if
188
           an LSM interferes. */
189

190
        if (uid_is_valid(uid))
10,327✔
191
                (void) seteuid(olduid);
2,347✔
192

193
 restore_gid:
7,980✔
194
        if (gid_is_valid(gid))
10,327✔
195
                (void) setegid(oldgid);
2,350✔
196

197
        return r;
198
}
199

200
static int connect_logger_as(
10,327✔
201
                const ExecContext *context,
202
                const ExecParameters *params,
203
                ExecOutput output,
204
                const char *ident,
205
                int nfd,
206
                uid_t uid,
207
                gid_t gid) {
208

209
        _cleanup_close_ int fd = -EBADF;
10,327✔
210
        int r;
10,327✔
211

212
        assert(context);
10,327✔
213
        assert(params);
10,327✔
214
        assert(output < _EXEC_OUTPUT_MAX);
10,327✔
215
        assert(ident);
10,327✔
216
        assert(nfd >= 0);
10,327✔
217

218
        fd = socket(AF_UNIX, SOCK_STREAM, 0);
10,327✔
219
        if (fd < 0)
10,327✔
220
                return -errno;
×
221

222
        r = connect_journal_socket(fd, context->log_namespace, uid, gid);
10,327✔
223
        if (r < 0)
10,327✔
224
                return r;
225

226
        if (shutdown(fd, SHUT_RD) < 0)
10,327✔
227
                return -errno;
×
228

229
        (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
10,327✔
230

231
        if (dprintf(fd,
19,907✔
232
                "%s\n"
233
                "%s\n"
234
                "%i\n"
235
                "%i\n"
236
                "%i\n"
237
                "%i\n"
238
                "%i\n",
239
                context->syslog_identifier ?: ident,
10,327✔
240
                params->flags & EXEC_PASS_LOG_UNIT ? params->unit_id : "",
10,327✔
241
                context->syslog_priority,
10,327✔
242
                !!context->syslog_level_prefix,
10,327✔
243
                false,
244
                is_kmsg_output(output),
10,327✔
245
                is_terminal_output(output)) < 0)
10,327✔
246
                return -errno;
×
247

248
        return move_fd(TAKE_FD(fd), nfd, false);
10,327✔
249
}
250

251
static int open_terminal_as(const char *path, int flags, int nfd) {
32✔
252
        int fd;
32✔
253

254
        assert(path);
32✔
255
        assert(nfd >= 0);
32✔
256

257
        fd = open_terminal(path, flags | O_NOCTTY);
32✔
258
        if (fd < 0)
32✔
259
                return fd;
260

261
        return move_fd(fd, nfd, false);
32✔
262
}
263

264
static int acquire_path(const char *path, int flags, mode_t mode) {
11✔
265
        _cleanup_close_ int fd = -EBADF;
11✔
266
        int r;
11✔
267

268
        assert(path);
11✔
269

270
        if (IN_SET(flags & O_ACCMODE_STRICT, O_WRONLY, O_RDWR))
11✔
271
                flags |= O_CREAT;
11✔
272

273
        fd = open(path, flags|O_NOCTTY, mode);
11✔
274
        if (fd >= 0)
11✔
275
                return TAKE_FD(fd);
11✔
276

277
        if (errno != ENXIO) /* ENXIO is returned when we try to open() an AF_UNIX file system socket on Linux */
×
278
                return -errno;
×
279

280
        /* So, it appears the specified path could be an AF_UNIX socket. Let's see if we can connect to it. */
281

282
        fd = socket(AF_UNIX, SOCK_STREAM, 0);
×
283
        if (fd < 0)
×
284
                return -errno;
×
285

286
        r = connect_unix_path(fd, AT_FDCWD, path);
×
287
        if (IN_SET(r, -ENOTSOCK, -EINVAL))
×
288
                /* Propagate initial error if we get ENOTSOCK or EINVAL, i.e. we have indication that this
289
                 * wasn't an AF_UNIX socket after all */
290
                return -ENXIO;
291
        if (r < 0)
×
292
                return r;
293

294
        if ((flags & O_ACCMODE_STRICT) == O_RDONLY)
×
295
                r = shutdown(fd, SHUT_WR);
×
296
        else if ((flags & O_ACCMODE_STRICT) == O_WRONLY)
×
297
                r = shutdown(fd, SHUT_RD);
×
298
        else
299
                r = 0;
300
        if (r < 0)
×
301
                return -errno;
×
302

303
        return TAKE_FD(fd);
304
}
305

306
static int fixup_input(
32,964✔
307
                const ExecContext *context,
308
                int socket_fd,
309
                bool apply_tty_stdin) {
310

311
        ExecInput std_input;
32,964✔
312

313
        assert(context);
32,964✔
314

315
        std_input = context->std_input;
32,964✔
316

317
        if (is_terminal_input(std_input) && !apply_tty_stdin)
32,964✔
318
                return EXEC_INPUT_NULL;
319

320
        if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
32,964✔
321
                return EXEC_INPUT_NULL;
322

323
        if (std_input == EXEC_INPUT_DATA && context->stdin_data_size == 0)
32,964✔
324
                return EXEC_INPUT_NULL;
×
325

326
        return std_input;
327
}
328

329
static int fixup_output(ExecOutput output, int socket_fd) {
32,964✔
330

331
        if (output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
32,964✔
332
                return EXEC_OUTPUT_INHERIT;
×
333

334
        return output;
335
}
336

337
static int setup_input(
11,534✔
338
                const ExecContext *context,
339
                const ExecParameters *params,
340
                int socket_fd,
341
                const int named_iofds[static 3]) {
342

343
        ExecInput i;
11,534✔
344
        int r;
11,534✔
345

346
        assert(context);
11,534✔
347
        assert(params);
11,534✔
348
        assert(named_iofds);
11,534✔
349

350
        if (params->stdin_fd >= 0) {
11,534✔
351
                if (dup2(params->stdin_fd, STDIN_FILENO) < 0)
546✔
352
                        return -errno;
×
353

354
                /* Try to make this our controlling tty, if it is a tty */
355
                if (isatty_safe(STDIN_FILENO) && ioctl(STDIN_FILENO, TIOCSCTTY, context->std_input == EXEC_INPUT_TTY_FORCE) < 0)
546✔
356
                        log_debug_errno(errno, "Failed to make standard input TTY our controlling terminal: %m");
2✔
357

358
                return STDIN_FILENO;
546✔
359
        }
360

361
        i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
10,988✔
362

363
        switch (i) {
10,988✔
364

365
        case EXEC_INPUT_NULL:
10,628✔
366
                return open_null_as(O_RDONLY, STDIN_FILENO);
10,628✔
367

368
        case EXEC_INPUT_TTY:
348✔
369
        case EXEC_INPUT_TTY_FORCE:
370
        case EXEC_INPUT_TTY_FAIL: {
371
                _cleanup_close_ int tty_fd = -EBADF;
348✔
372
                _cleanup_free_ char *resolved = NULL;
348✔
373
                const char *tty_path;
348✔
374

375
                tty_path = ASSERT_PTR(exec_context_tty_path(context));
348✔
376

377
                if (tty_is_console(tty_path)) {
348✔
378
                        r = resolve_dev_console(&resolved);
264✔
379
                        if (r < 0)
264✔
380
                                log_debug_errno(r, "Failed to resolve /dev/console, ignoring: %m");
×
381
                        else {
382
                                log_debug("Resolved /dev/console to %s", resolved);
264✔
383
                                tty_path = resolved;
264✔
384
                        }
385
                }
386

387
                tty_fd = acquire_terminal(tty_path,
696✔
388
                                          i == EXEC_INPUT_TTY_FAIL  ? ACQUIRE_TERMINAL_TRY :
348✔
389
                                          i == EXEC_INPUT_TTY_FORCE ? ACQUIRE_TERMINAL_FORCE :
390
                                                                      ACQUIRE_TERMINAL_WAIT,
391
                                          USEC_INFINITY);
392
                if (tty_fd < 0)
348✔
393
                        return tty_fd;
394

395
                r = move_fd(tty_fd, STDIN_FILENO, /* cloexec= */ false);
348✔
396
                if (r < 0)
348✔
397
                        return r;
×
398

399
                TAKE_FD(tty_fd);
400
                return r;
401
        }
402

403
        case EXEC_INPUT_SOCKET:
11✔
404
                assert(socket_fd >= 0);
11✔
405

406
                return RET_NERRNO(dup2(socket_fd, STDIN_FILENO));
11✔
407

408
        case EXEC_INPUT_NAMED_FD:
×
409
                assert(named_iofds[STDIN_FILENO] >= 0);
×
410

411
                (void) fd_nonblock(named_iofds[STDIN_FILENO], false);
×
412
                return RET_NERRNO(dup2(named_iofds[STDIN_FILENO], STDIN_FILENO));
11,534✔
413

414
        case EXEC_INPUT_DATA: {
1✔
415
                int fd;
1✔
416

417
                fd = memfd_new_and_seal("exec-input", context->stdin_data, context->stdin_data_size);
1✔
418
                if (fd < 0)
1✔
419
                        return fd;
420

421
                return move_fd(fd, STDIN_FILENO, false);
1✔
422
        }
423

424
        case EXEC_INPUT_FILE: {
×
425
                bool rw;
×
426
                int fd;
×
427

428
                assert(context->stdio_file[STDIN_FILENO]);
×
429

430
                rw = (context->std_output == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDOUT_FILENO])) ||
×
431
                        (context->std_error == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDERR_FILENO]));
×
432

433
                fd = acquire_path(context->stdio_file[STDIN_FILENO], rw ? O_RDWR : O_RDONLY, 0666 & ~context->umask);
×
434
                if (fd < 0)
×
435
                        return fd;
436

437
                return move_fd(fd, STDIN_FILENO, false);
×
438
        }
439

440
        default:
×
441
                assert_not_reached();
×
442
        }
443
}
444

445
static bool can_inherit_stderr_from_stdout(
10,988✔
446
                const ExecContext *context,
447
                ExecOutput o,
448
                ExecOutput e) {
449

450
        assert(context);
10,988✔
451

452
        /* Returns true, if given the specified STDERR and STDOUT output we can directly dup() the stdout fd to the
453
         * stderr fd */
454

455
        if (e == EXEC_OUTPUT_INHERIT)
10,988✔
456
                return true;
457
        if (e != o)
410✔
458
                return false;
459

460
        if (e == EXEC_OUTPUT_NAMED_FD)
407✔
461
                return streq_ptr(context->stdio_fdname[STDOUT_FILENO], context->stdio_fdname[STDERR_FILENO]);
×
462

463
        if (IN_SET(e, EXEC_OUTPUT_FILE, EXEC_OUTPUT_FILE_APPEND, EXEC_OUTPUT_FILE_TRUNCATE))
407✔
464
                return streq_ptr(context->stdio_file[STDOUT_FILENO], context->stdio_file[STDERR_FILENO]);
4✔
465

466
        return true;
467
}
468

469
static int setup_output(
23,068✔
470
                const ExecContext *context,
471
                const ExecParameters *params,
472
                int fileno,
473
                int socket_fd,
474
                const int named_iofds[static 3],
475
                const char *ident,
476
                uid_t uid,
477
                gid_t gid,
478
                dev_t *journal_stream_dev,
479
                ino_t *journal_stream_ino) {
480

481
        ExecOutput o;
23,068✔
482
        ExecInput i;
23,068✔
483
        int r;
23,068✔
484

485
        assert(context);
23,068✔
486
        assert(params);
23,068✔
487
        assert(ident);
23,068✔
488
        assert(journal_stream_dev);
23,068✔
489
        assert(journal_stream_ino);
23,068✔
490

491
        if (fileno == STDOUT_FILENO && params->stdout_fd >= 0) {
23,068✔
492

493
                if (dup2(params->stdout_fd, STDOUT_FILENO) < 0)
546✔
494
                        return -errno;
×
495

496
                return STDOUT_FILENO;
497
        }
498

499
        if (fileno == STDERR_FILENO && params->stderr_fd >= 0) {
22,522✔
500
                if (dup2(params->stderr_fd, STDERR_FILENO) < 0)
546✔
501
                        return -errno;
×
502

503
                return STDERR_FILENO;
504
        }
505

506
        i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
21,976✔
507
        o = fixup_output(context->std_output, socket_fd);
21,976✔
508

509
        // FIXME: we probably should spend some time here to verify that if we inherit an fd from stdin
510
        // (possibly indirect via inheritance from stdout) it is actually opened for write!
511

512
        if (fileno == STDERR_FILENO) {
21,976✔
513
                ExecOutput e;
10,988✔
514
                e = fixup_output(context->std_error, socket_fd);
10,988✔
515

516
                /* This expects the input and output are already set up */
517

518
                /* Don't change the stderr file descriptor if we inherit all
519
                 * the way and are not on a tty */
520
                if (e == EXEC_OUTPUT_INHERIT &&
10,988✔
521
                    o == EXEC_OUTPUT_INHERIT &&
8✔
522
                    i == EXEC_INPUT_NULL &&
×
523
                    !is_terminal_input(context->std_input) &&
×
524
                    getppid() != 1)
×
525
                        return fileno;
526

527
                /* Duplicate from stdout if possible */
528
                if (can_inherit_stderr_from_stdout(context, o, e))
10,988✔
529
                        return RET_NERRNO(dup2(STDOUT_FILENO, fileno));
10,981✔
530

531
                o = e;
532

533
        } else if (o == EXEC_OUTPUT_INHERIT) {
10,988✔
534
                /* If input got downgraded, inherit the original value */
535
                if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
8✔
536
                        return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
×
537

538
                /* If the input is connected to anything that's not a /dev/null or a data fd, inherit that... */
539
                if (!IN_SET(i, EXEC_INPUT_NULL, EXEC_INPUT_DATA))
8✔
540
                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));
8✔
541

542
                /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
543
                if (getppid() != 1)
×
544
                        return fileno;
545

546
                /* We need to open /dev/null here anew, to get the right access mode. */
547
                return open_null_as(O_WRONLY, fileno);
×
548
        }
549

550
        switch (o) {
10,987✔
551

552
        case EXEC_OUTPUT_NULL:
260✔
553
                return open_null_as(O_WRONLY, fileno);
260✔
554

555
        case EXEC_OUTPUT_TTY:
380✔
556
                if (is_terminal_input(i))
380✔
557
                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));
348✔
558

559
                return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
32✔
560

561
        case EXEC_OUTPUT_KMSG:
10,327✔
562
        case EXEC_OUTPUT_KMSG_AND_CONSOLE:
563
        case EXEC_OUTPUT_JOURNAL:
564
        case EXEC_OUTPUT_JOURNAL_AND_CONSOLE:
565
                r = connect_logger_as(context, params, o, ident, fileno, uid, gid);
10,327✔
566
                if (r < 0) {
10,327✔
567
                        log_warning_errno(r, "Failed to connect %s to the journal socket, ignoring: %m",
×
568
                                          fileno == STDOUT_FILENO ? "stdout" : "stderr");
569
                        r = open_null_as(O_WRONLY, fileno);
×
570
                } else {
571
                        struct stat st;
10,327✔
572

573
                        /* If we connected this fd to the journal via a stream, patch the device/inode into the passed
574
                         * parameters, but only then. This is useful so that we can set $JOURNAL_STREAM that permits
575
                         * services to detect whether they are connected to the journal or not.
576
                         *
577
                         * If both stdout and stderr are connected to a stream then let's make sure to store the data
578
                         * about STDERR as that's usually the best way to do logging. */
579

580
                        if (fstat(fileno, &st) >= 0 &&
10,327✔
581
                            (*journal_stream_ino == 0 || fileno == STDERR_FILENO)) {
10,327✔
582
                                *journal_stream_dev = st.st_dev;
10,327✔
583
                                *journal_stream_ino = st.st_ino;
10,327✔
584
                        }
585
                }
586
                return r;
587

588
        case EXEC_OUTPUT_SOCKET:
9✔
589
                assert(socket_fd >= 0);
9✔
590

591
                return RET_NERRNO(dup2(socket_fd, fileno));
9✔
592

593
        case EXEC_OUTPUT_NAMED_FD:
×
594
                assert(named_iofds[fileno] >= 0);
×
595

596
                (void) fd_nonblock(named_iofds[fileno], false);
×
597
                return RET_NERRNO(dup2(named_iofds[fileno], fileno));
×
598

599
        case EXEC_OUTPUT_FILE:
11✔
600
        case EXEC_OUTPUT_FILE_APPEND:
601
        case EXEC_OUTPUT_FILE_TRUNCATE: {
602
                bool rw;
11✔
603
                int fd, flags;
11✔
604

605
                assert(context->stdio_file[fileno]);
11✔
606

607
                rw = context->std_input == EXEC_INPUT_FILE &&
11✔
608
                        streq_ptr(context->stdio_file[fileno], context->stdio_file[STDIN_FILENO]);
×
609

610
                if (rw)
11✔
611
                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));
×
612

613
                flags = O_WRONLY;
11✔
614
                if (o == EXEC_OUTPUT_FILE_APPEND)
11✔
615
                        flags |= O_APPEND;
616
                else if (o == EXEC_OUTPUT_FILE_TRUNCATE)
9✔
617
                        flags |= O_TRUNC;
3✔
618

619
                fd = acquire_path(context->stdio_file[fileno], flags, 0666 & ~context->umask);
11✔
620
                if (fd < 0)
11✔
621
                        return fd;
622

623
                return move_fd(fd, fileno, 0);
11✔
624
        }
625

626
        default:
×
627
                assert_not_reached();
×
628
        }
629
}
630

631
static int chown_terminal(int fd, uid_t uid) {
2,672✔
632
        int r;
2,672✔
633

634
        assert(fd >= 0);
2,672✔
635

636
        /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
637
        if (!isatty_safe(fd))
2,672✔
638
                return 0;
639

640
        /* This might fail. What matters are the results. */
641
        r = fchmod_and_chown(fd, TTY_MODE, uid, GID_INVALID);
7✔
642
        if (r < 0)
7✔
643
                return r;
×
644

645
        return 1;
646
}
647

648
static int setup_confirm_stdio(
×
649
                const ExecContext *context,
650
                const char *vc,
651
                int *ret_saved_stdin,
652
                int *ret_saved_stdout) {
653

654
        _cleanup_close_ int fd = -EBADF, saved_stdin = -EBADF, saved_stdout = -EBADF;
×
655
        int r;
×
656

657
        assert(context);
×
658
        assert(ret_saved_stdin);
×
659
        assert(ret_saved_stdout);
×
660

661
        saved_stdin = fcntl(STDIN_FILENO, F_DUPFD_CLOEXEC, 3);
×
662
        if (saved_stdin < 0)
×
663
                return -errno;
×
664

665
        saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD_CLOEXEC, 3);
×
666
        if (saved_stdout < 0)
×
667
                return -errno;
×
668

669
        fd = acquire_terminal(vc, ACQUIRE_TERMINAL_WAIT, DEFAULT_CONFIRM_USEC);
×
670
        if (fd < 0)
×
671
                return fd;
672

673
        _cleanup_close_ int lock_fd = lock_dev_console();
×
674
        if (lock_fd < 0)
×
675
                log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
×
676

677
        r = chown_terminal(fd, getuid());
×
678
        if (r < 0)
×
679
                return r;
680

681
        r = terminal_reset_defensive(fd, TERMINAL_RESET_SWITCH_TO_TEXT);
×
682
        if (r < 0)
×
683
                return r;
684

685
        r = exec_context_apply_tty_size(context, fd, fd, vc);
×
686
        if (r < 0)
×
687
                return r;
688

689
        r = rearrange_stdio(fd, fd, STDERR_FILENO); /* Invalidates 'fd' also on failure */
×
690
        TAKE_FD(fd);
×
691
        if (r < 0)
×
692
                return r;
693

694
        *ret_saved_stdin = TAKE_FD(saved_stdin);
×
695
        *ret_saved_stdout = TAKE_FD(saved_stdout);
×
696
        return 0;
×
697
}
698

699
static void write_confirm_error_fd(int err, int fd, const char *unit_id) {
×
700
        assert(err != 0);
×
701
        assert(fd >= 0);
×
702
        assert(unit_id);
×
703

704
        errno = abs(err);
×
705

706
        if (errno == ETIMEDOUT)
×
707
                dprintf(fd, "Confirmation question timed out for %s, assuming positive response.\n", unit_id);
×
708
        else
709
                dprintf(fd, "Couldn't ask confirmation for %s, assuming positive response: %m\n", unit_id);
×
710
}
×
711

712
static void write_confirm_error(int err, const char *vc, const char *unit_id) {
×
713
        _cleanup_close_ int fd = -EBADF;
×
714

715
        assert(vc);
×
716

717
        fd = open_terminal(vc, O_WRONLY|O_NOCTTY|O_CLOEXEC);
×
718
        if (fd < 0)
×
719
                return;
×
720

721
        write_confirm_error_fd(err, fd, unit_id);
×
722
}
723

724
static int restore_confirm_stdio(int *saved_stdin, int *saved_stdout) {
×
725
        int r = 0;
×
726

727
        assert(saved_stdin);
×
728
        assert(saved_stdout);
×
729

730
        release_terminal();
×
731

732
        if (*saved_stdin >= 0)
×
733
                if (dup2(*saved_stdin, STDIN_FILENO) < 0)
×
734
                        r = -errno;
×
735

736
        if (*saved_stdout >= 0)
×
737
                if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
×
738
                        r = -errno;
×
739

740
        *saved_stdin = safe_close(*saved_stdin);
×
741
        *saved_stdout = safe_close(*saved_stdout);
×
742

743
        return r;
×
744
}
745

746
enum {
747
        CONFIRM_PRETEND_FAILURE = -1,
748
        CONFIRM_PRETEND_SUCCESS =  0,
749
        CONFIRM_EXECUTE = 1,
750
};
751

752
static bool confirm_spawn_disabled(void) {
×
753
        return access("/run/systemd/confirm_spawn_disabled", F_OK) >= 0;
×
754
}
755

756
static int ask_for_confirmation(const ExecContext *context, const ExecParameters *params, const char *cmdline) {
×
757
        int saved_stdout = -EBADF, saved_stdin = -EBADF, r;
×
758
        _cleanup_free_ char *e = NULL;
×
759
        char c;
×
760

761
        assert(context);
×
762
        assert(params);
×
763

764
        /* For any internal errors, assume a positive response. */
765
        r = setup_confirm_stdio(context, params->confirm_spawn, &saved_stdin, &saved_stdout);
×
766
        if (r < 0) {
×
767
                write_confirm_error(r, params->confirm_spawn, params->unit_id);
×
768
                return CONFIRM_EXECUTE;
769
        }
770

771
        /* confirm_spawn might have been disabled while we were sleeping. */
772
        if (!params->confirm_spawn || confirm_spawn_disabled()) {
×
773
                r = 1;
×
774
                goto restore_stdio;
×
775
        }
776

777
        e = ellipsize(cmdline, 60, 100);
×
778
        if (!e) {
×
779
                log_oom();
×
780
                r = CONFIRM_EXECUTE;
×
781
                goto restore_stdio;
×
782
        }
783

784
        for (;;) {
×
785
                r = ask_char(&c, "yfshiDjcn", "Execute %s? [y, f, s – h for help] ", e);
×
786
                if (r < 0) {
×
787
                        write_confirm_error_fd(r, STDOUT_FILENO, params->unit_id);
×
788
                        r = CONFIRM_EXECUTE;
×
789
                        goto restore_stdio;
×
790
                }
791

792
                switch (c) {
×
793
                case 'c':
×
794
                        printf("Resuming normal execution.\n");
×
795
                        manager_disable_confirm_spawn();
×
796
                        r = 1;
797
                        break;
798
                case 'D':
×
799
                        printf("  Unit: %s\n",
×
800
                               params->unit_id);
×
801
                        exec_context_dump(context, stdout, "  ");
×
802
                        exec_params_dump(params, stdout, "  ");
×
803
                        continue; /* ask again */
×
804
                case 'f':
×
805
                        printf("Failing execution.\n");
×
806
                        r = CONFIRM_PRETEND_FAILURE;
807
                        break;
808
                case 'h':
×
809
                        printf("  c - continue, proceed without asking anymore\n"
×
810
                               "  D - dump, show the state of the unit\n"
811
                               "  f - fail, don't execute the command and pretend it failed\n"
812
                               "  h - help\n"
813
                               "  i - info, show a short summary of the unit\n"
814
                               "  j - jobs, show jobs that are in progress\n"
815
                               "  s - skip, don't execute the command and pretend it succeeded\n"
816
                               "  y - yes, execute the command\n");
817
                        continue; /* ask again */
×
818
                case 'i':
×
819
                        printf("  Unit:        %s\n"
×
820
                               "  Command:     %s\n",
821
                               params->unit_id, cmdline);
×
822
                        continue; /* ask again */
×
823
                case 'j':
×
824
                        if (sigqueue(getppid(),
×
825
                                     SIGRTMIN+18,
×
826
                                     (const union sigval) { .sival_int = MANAGER_SIGNAL_COMMAND_DUMP_JOBS }) < 0)
×
827
                                return -errno;
×
828

829
                        continue; /* ask again */
×
830
                case 'n':
×
831
                        /* 'n' was removed in favor of 'f'. */
832
                        printf("Didn't understand 'n', did you mean 'f'?\n");
×
833
                        continue; /* ask again */
×
834
                case 's':
×
835
                        printf("Skipping execution.\n");
×
836
                        r = CONFIRM_PRETEND_SUCCESS;
837
                        break;
838
                case 'y':
839
                        r = CONFIRM_EXECUTE;
840
                        break;
841
                default:
×
842
                        assert_not_reached();
×
843
                }
844
                break;
845
        }
846

847
restore_stdio:
×
848
        restore_confirm_stdio(&saved_stdin, &saved_stdout);
×
849
        return r;
850
}
851

852
static int get_fixed_user(
9,379✔
853
                const char *user_or_uid,
854
                bool prefer_nss,
855
                const char **ret_username,
856
                uid_t *ret_uid,
857
                gid_t *ret_gid,
858
                const char **ret_home,
859
                const char **ret_shell) {
860

861
        int r;
9,379✔
862

863
        assert(user_or_uid);
9,379✔
864
        assert(ret_username);
9,379✔
865

866
        r = get_user_creds(&user_or_uid, ret_uid, ret_gid, ret_home, ret_shell,
18,308✔
867
                           USER_CREDS_CLEAN|(prefer_nss ? USER_CREDS_PREFER_NSS : 0));
868
        if (r < 0)
9,379✔
869
                return r;
870

871
        /* user_or_uid is normalized by get_user_creds to username */
872
        *ret_username = user_or_uid;
9,377✔
873

874
        return 0;
9,377✔
875
}
876

877
static int get_fixed_group(
11✔
878
                const char *group_or_gid,
879
                const char **ret_groupname,
880
                gid_t *ret_gid) {
881

882
        int r;
11✔
883

884
        assert(group_or_gid);
11✔
885
        assert(ret_groupname);
11✔
886

887
        r = get_group_creds(&group_or_gid, ret_gid, /* flags = */ 0);
11✔
888
        if (r < 0)
11✔
889
                return r;
890

891
        /* group_or_gid is normalized by get_group_creds to groupname */
892
        *ret_groupname = group_or_gid;
11✔
893

894
        return 0;
11✔
895
}
896

897
static int get_supplementary_groups(
11,534✔
898
                const ExecContext *c,
899
                const char *user,
900
                gid_t gid,
901
                gid_t **ret_gids) {
902

903
        int r;
11,534✔
904

905
        assert(c);
11,534✔
906
        assert(ret_gids);
11,534✔
907

908
        /*
909
         * If user is given, then lookup GID and supplementary groups list.
910
         * We avoid NSS lookups for gid=0. Also we have to initialize groups
911
         * here and as early as possible so we keep the list of supplementary
912
         * groups of the caller.
913
         */
914
        bool keep_groups = false;
11,534✔
915
        if (user && gid_is_valid(gid) && gid != 0) {
14,206✔
916
                /* First step, initialize groups from /etc/groups */
917
                if (initgroups(user, gid) < 0)
2,524✔
918
                        return -errno;
11,534✔
919

920
                keep_groups = true;
921
        }
922

923
        if (strv_isempty(c->supplementary_groups)) {
11,534✔
924
                *ret_gids = NULL;
11,525✔
925
                return 0;
11,525✔
926
        }
927

928
        /*
929
         * If SupplementaryGroups= was passed then NGROUPS_MAX has to
930
         * be positive, otherwise fail.
931
         */
932
        errno = 0;
9✔
933
        int ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
9✔
934
        if (ngroups_max <= 0)
9✔
935
                return errno_or_else(EOPNOTSUPP);
×
936

937
        _cleanup_free_ gid_t *l_gids = new(gid_t, ngroups_max);
18✔
938
        if (!l_gids)
9✔
939
                return -ENOMEM;
940

941
        int k = 0;
9✔
942
        if (keep_groups) {
9✔
943
                /*
944
                 * Lookup the list of groups that the user belongs to, we
945
                 * avoid NSS lookups here too for gid=0.
946
                 */
947
                k = ngroups_max;
9✔
948
                if (getgrouplist(user, gid, l_gids, &k) < 0)
9✔
949
                        return -EINVAL;
950
        }
951

952
        STRV_FOREACH(i, c->supplementary_groups) {
18✔
953
                if (k >= ngroups_max)
9✔
954
                        return -E2BIG;
×
955

956
                const char *g = *i;
9✔
957
                r = get_group_creds(&g, l_gids + k, /* flags = */ 0);
9✔
958
                if (r < 0)
9✔
959
                        return r;
960

961
                k++;
9✔
962
        }
963

964
        if (k == 0) {
9✔
965
                *ret_gids = NULL;
×
966
                return 0;
×
967
        }
968

969
        /* Otherwise get the final list of supplementary groups */
970
        gid_t *groups = newdup(gid_t, l_gids, k);
9✔
971
        if (!groups)
9✔
972
                return -ENOMEM;
973

974
        *ret_gids = groups;
9✔
975
        return k;
9✔
976
}
977

978
static int enforce_groups(gid_t gid, const gid_t *supplementary_gids, int ngids) {
9,563✔
979
        int r;
9,563✔
980

981
        /* Handle SupplementaryGroups= if it is not empty */
982
        if (ngids > 0) {
9,563✔
983
                r = maybe_setgroups(ngids, supplementary_gids);
270✔
984
                if (r < 0)
270✔
985
                        return r;
986
        }
987

988
        if (gid_is_valid(gid)) {
9,563✔
989
                /* Then set our gids */
990
                if (setresgid(gid, gid, gid) < 0)
2,026✔
991
                        return -errno;
1✔
992
        }
993

994
        return 0;
995
}
996

997
static int set_securebits(unsigned bits, unsigned mask) {
743✔
998
        unsigned applied;
743✔
999
        int current;
743✔
1000

1001
        current = prctl(PR_GET_SECUREBITS);
743✔
1002
        if (current < 0)
743✔
1003
                return -errno;
×
1004

1005
        /* Clear all securebits defined in mask and set bits */
1006
        applied = ((unsigned) current & ~mask) | bits;
743✔
1007
        if ((unsigned) current == applied)
743✔
1008
                return 0;
1009

1010
        if (prctl(PR_SET_SECUREBITS, applied) < 0)
53✔
1011
                return -errno;
×
1012

1013
        return 1;
1014
}
1015

1016
static int enforce_user(
2,019✔
1017
                const ExecContext *context,
1018
                uid_t uid,
1019
                uint64_t capability_ambient_set) {
1020

1021
        int r;
2,019✔
1022

1023
        assert(context);
2,019✔
1024

1025
        if (!uid_is_valid(uid))
2,019✔
1026
                return 0;
1027

1028
        /* Sets (but doesn't look up) the UIS and makes sure we keep the capabilities while doing so. For
1029
         * setting secure bits the capability CAP_SETPCAP is required, so we also need keep-caps in this
1030
         * case. */
1031

1032
        if ((capability_ambient_set != 0 || context->secure_bits != 0) && uid != 0) {
2,019✔
1033

1034
                /* First step: If we need to keep capabilities but drop privileges we need to make sure we
1035
                 * keep our caps, while we drop privileges. Add KEEP_CAPS to the securebits */
1036
                r = set_securebits(1U << SECURE_KEEP_CAPS, 0);
743✔
1037
                if (r < 0)
743✔
1038
                        return r;
1039
        }
1040

1041
        /* Second step: actually set the uids */
1042
        if (setresuid(uid, uid, uid) < 0)
2,019✔
1043
                return -errno;
×
1044

1045
        /* At this point we should have all necessary capabilities but are otherwise a normal user. However,
1046
         * the caps might got corrupted due to the setresuid() so we need clean them up later. This is done
1047
         * outside of this call. */
1048
        return 0;
1049
}
1050

1051
#if HAVE_PAM
1052

1053
static void pam_response_free_array(struct pam_response *responses, size_t n_responses) {
×
1054
        assert(responses || n_responses == 0);
×
1055

1056
        FOREACH_ARRAY(resp, responses, n_responses)
×
1057
                erase_and_free(resp->resp);
×
1058

1059
        free(responses);
×
1060
}
×
1061

1062
typedef struct AskPasswordConvData {
1063
        const ExecContext *context;
1064
        const ExecParameters *params;
1065
} AskPasswordConvData;
1066

1067
static int ask_password_conv(
5✔
1068
                int num_msg,
1069
                const struct pam_message *msg[],
1070
                struct pam_response **ret,
1071
                void *userdata) {
1072

1073
        AskPasswordConvData *data = ASSERT_PTR(userdata);
5✔
1074
        bool set_credential_env_var = false;
5✔
1075
        int r;
5✔
1076

1077
        assert(num_msg >= 0);
5✔
1078
        assert(msg);
5✔
1079
        assert(data->context);
5✔
1080
        assert(data->params);
5✔
1081

1082
        size_t n = num_msg;
5✔
1083
        struct pam_response *responses = new0(struct pam_response, n);
5✔
1084
        if (!responses)
5✔
1085
                return PAM_BUF_ERR;
5✔
1086
        CLEANUP_ARRAY(responses, n, pam_response_free_array);
5✔
1087

1088
        for (size_t i = 0; i < n; i++) {
10✔
1089
                const struct pam_message *mi = *msg + i;
5✔
1090

1091
                switch (mi->msg_style) {
5✔
1092

1093
                case PAM_PROMPT_ECHO_ON:
2✔
1094
                case PAM_PROMPT_ECHO_OFF: {
1095

1096
                        /* Locally set the $CREDENTIALS_DIRECTORY to the credentials directory we just populated */
1097
                        if (!set_credential_env_var) {
2✔
1098
                                _cleanup_free_ char *creds_dir = NULL;
2✔
1099
                                r = exec_context_get_credential_directory(data->context, data->params, data->params->unit_id, &creds_dir);
2✔
1100
                                if (r < 0)
2✔
1101
                                        return log_error_errno(r, "Failed to determine credentials directory: %m");
×
1102

1103
                                if (creds_dir) {
2✔
1104
                                        if (setenv("CREDENTIALS_DIRECTORY", creds_dir, /* overwrite= */ true) < 0)
2✔
1105
                                                return log_error_errno(r, "Failed to set $CREDENTIALS_DIRECTORY: %m");
×
1106
                                } else
1107
                                        (void) unsetenv("CREDENTIALS_DIRECTORY");
×
1108

1109
                                set_credential_env_var = true;
2✔
1110
                        }
1111

1112
                        _cleanup_free_ char *credential_name = strjoin("pam.authtok.", data->context->pam_name);
4✔
1113
                        if (!credential_name)
2✔
1114
                                return log_oom();
×
1115

1116
                        AskPasswordRequest req = {
4✔
1117
                                .message = mi->msg,
2✔
1118
                                .credential = credential_name,
1119
                                .tty_fd = -EBADF,
1120
                                .hup_fd = -EBADF,
1121
                                .until = usec_add(now(CLOCK_MONOTONIC), 15 * USEC_PER_SEC),
2✔
1122
                        };
1123

1124
                        _cleanup_strv_free_erase_ char **acquired = NULL;
×
1125
                        r = ask_password_auto(
2✔
1126
                                        &req,
1127
                                        ASK_PASSWORD_ACCEPT_CACHED|
1128
                                        ASK_PASSWORD_NO_TTY|
1129
                                        (mi->msg_style == PAM_PROMPT_ECHO_ON ? ASK_PASSWORD_ECHO : 0),
2✔
1130
                                        &acquired);
1131
                        if (r < 0) {
2✔
1132
                                log_error_errno(r, "Failed to query for password: %m");
×
1133
                                return PAM_CONV_ERR;
×
1134
                        }
1135

1136
                        responses[i].resp = strdup(ASSERT_PTR(acquired[0]));
2✔
1137
                        if (!responses[i].resp) {
2✔
1138
                                log_oom();
×
1139
                                return PAM_BUF_ERR;
1140
                        }
1141
                        break;
2✔
1142
                }
1143

1144
                case PAM_ERROR_MSG:
1145
                        log_error("PAM: %s", mi->msg);
×
1146
                        break;
1147

1148
                case PAM_TEXT_INFO:
1149
                        log_info("PAM: %s", mi->msg);
3✔
1150
                        break;
1151

1152
                default:
1153
                        return PAM_CONV_ERR;
1154
                }
1155
        }
1156

1157
        *ret = TAKE_PTR(responses);
5✔
1158
        n = 0;
5✔
1159

1160
        return PAM_SUCCESS;
5✔
1161
}
1162

1163
static int pam_close_session_and_delete_credentials(pam_handle_t *handle, int flags) {
223✔
1164
        int r, s;
223✔
1165

1166
        assert(handle);
223✔
1167

1168
        r = pam_close_session(handle, flags);
223✔
1169
        if (r != PAM_SUCCESS)
223✔
1170
                log_debug("pam_close_session() failed: %s", pam_strerror(handle, r));
50✔
1171

1172
        s = pam_setcred(handle, PAM_DELETE_CRED | flags);
223✔
1173
        if (s != PAM_SUCCESS)
223✔
1174
                log_debug("pam_setcred(PAM_DELETE_CRED) failed: %s", pam_strerror(handle, s));
156✔
1175

1176
        return r != PAM_SUCCESS ? r : s;
223✔
1177
}
1178
#endif
1179

1180
static int setup_pam(
402✔
1181
                const ExecContext *context,
1182
                ExecParameters *params,
1183
                const char *user,
1184
                uid_t uid,
1185
                gid_t gid,
1186
                char ***env, /* updated on success */
1187
                const int fds[], size_t n_fds,
1188
                int exec_fd) {
1189

1190
#if HAVE_PAM
1191
        AskPasswordConvData conv_data = {
402✔
1192
                .context = context,
1193
                .params = params,
1194
        };
1195

1196
        const struct pam_conv conv = {
402✔
1197
                .conv = ask_password_conv,
1198
                .appdata_ptr = &conv_data,
1199
        };
1200

1201
        _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
402✔
1202
        _cleanup_strv_free_ char **e = NULL;
×
1203
        _cleanup_free_ char *tty = NULL;
402✔
1204
        pam_handle_t *handle = NULL;
402✔
1205
        sigset_t old_ss;
402✔
1206
        int pam_code = PAM_SUCCESS, r;
402✔
1207
        bool close_session = false;
402✔
1208
        pid_t parent_pid;
402✔
1209
        int flags = 0;
402✔
1210

1211
        assert(context);
402✔
1212
        assert(params);
402✔
1213
        assert(user);
402✔
1214
        assert(uid_is_valid(uid));
402✔
1215
        assert(gid_is_valid(gid));
402✔
1216
        assert(fds || n_fds == 0);
402✔
1217
        assert(env);
402✔
1218

1219
        /* We set up PAM in the parent process, then fork. The child
1220
         * will then stay around until killed via PR_GET_PDEATHSIG or
1221
         * systemd via the cgroup logic. It will then remove the PAM
1222
         * session again. The parent process will exec() the actual
1223
         * daemon. We do things this way to ensure that the main PID
1224
         * of the daemon is the one we initially fork()ed. */
1225

1226
        r = barrier_create(&barrier);
402✔
1227
        if (r < 0)
402✔
1228
                goto fail;
×
1229

1230
        if (log_get_max_level() < LOG_DEBUG)
402✔
1231
                flags |= PAM_SILENT;
3✔
1232

1233
        pam_code = pam_start(context->pam_name, user, &conv, &handle);
402✔
1234
        if (pam_code != PAM_SUCCESS) {
402✔
1235
                handle = NULL;
×
1236
                goto fail;
×
1237
        }
1238

1239
        if (getttyname_malloc(STDIN_FILENO, &tty) >= 0) {
402✔
1240
                _cleanup_free_ char *q = path_join("/dev", tty);
6✔
1241
                if (!q) {
6✔
1242
                        r = -ENOMEM;
×
1243
                        goto fail;
×
1244
                }
1245

1246
                free_and_replace(tty, q);
6✔
1247
        }
1248

1249
        if (tty) {
402✔
1250
                pam_code = pam_set_item(handle, PAM_TTY, tty);
6✔
1251
                if (pam_code != PAM_SUCCESS)
6✔
1252
                        goto fail;
×
1253
        }
1254

1255
        STRV_FOREACH(nv, *env) {
5,690✔
1256
                pam_code = pam_putenv(handle, *nv);
5,288✔
1257
                if (pam_code != PAM_SUCCESS)
5,288✔
1258
                        goto fail;
×
1259
        }
1260

1261
        pam_code = pam_acct_mgmt(handle, flags);
402✔
1262
        if (pam_code != PAM_SUCCESS)
402✔
1263
                goto fail;
×
1264

1265
        pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | flags);
402✔
1266
        if (pam_code != PAM_SUCCESS)
402✔
1267
                log_debug("pam_setcred(PAM_ESTABLISH_CRED) failed, ignoring: %s", pam_strerror(handle, pam_code));
330✔
1268

1269
        pam_code = pam_open_session(handle, flags);
402✔
1270
        if (pam_code != PAM_SUCCESS)
402✔
1271
                goto fail;
×
1272

1273
        close_session = true;
402✔
1274

1275
        e = pam_getenvlist(handle);
402✔
1276
        if (!e) {
402✔
1277
                pam_code = PAM_BUF_ERR;
×
1278
                goto fail;
×
1279
        }
1280

1281
        /* Block SIGTERM, so that we know that it won't get lost in the child */
1282

1283
        assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM) >= 0);
402✔
1284

1285
        parent_pid = getpid_cached();
402✔
1286

1287
        r = safe_fork("(sd-pam)", 0, NULL);
402✔
1288
        if (r < 0)
626✔
1289
                goto fail;
×
1290
        if (r == 0) {
626✔
1291
                int ret = EXIT_PAM;
224✔
1292

1293
                /* The child's job is to reset the PAM session on termination */
1294
                barrier_set_role(&barrier, BARRIER_CHILD);
224✔
1295

1296
                /* Make sure we don't keep open the passed fds in this child. We assume that otherwise only
1297
                 * those fds are open here that have been opened by PAM. */
1298
                (void) close_many(fds, n_fds);
224✔
1299

1300
                /* Also close the 'exec_fd' in the child, since the service manager waits for the EOF induced
1301
                 * by the execve() to wait for completion, and if we'd keep the fd open here in the child
1302
                 * we'd never signal completion. */
1303
                exec_fd = safe_close(exec_fd);
224✔
1304

1305
                /* Drop privileges - we don't need any to pam_close_session and this will make
1306
                 * PR_SET_PDEATHSIG work in most cases.  If this fails, ignore the error - but expect sd-pam
1307
                 * threads to fail to exit normally */
1308

1309
                r = fully_set_uid_gid(uid, gid, /* supplementary_gids= */ NULL, /* n_supplementary_gids= */ 0);
224✔
1310
                if (r < 0)
224✔
1311
                        log_warning_errno(r, "Failed to drop privileges in sd-pam: %m");
×
1312

1313
                (void) ignore_signals(SIGPIPE);
224✔
1314

1315
                /* Wait until our parent died. This will only work if the above setresuid() succeeds,
1316
                 * otherwise the kernel will not allow unprivileged parents kill their privileged children
1317
                 * this way. We rely on the control groups kill logic to do the rest for us. */
1318
                if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
224✔
1319
                        goto child_finish;
×
1320

1321
                /* Tell the parent that our setup is done. This is especially important regarding dropping
1322
                 * privileges. Otherwise, unit setup might race against our setresuid(2) call.
1323
                 *
1324
                 * If the parent aborted, we'll detect this below, hence ignore return failure here. */
1325
                (void) barrier_place(&barrier);
224✔
1326

1327
                /* Check if our parent process might already have died? */
1328
                if (getppid() == parent_pid) {
224✔
1329
                        sigset_t ss;
224✔
1330
                        int sig;
224✔
1331

1332
                        assert_se(sigemptyset(&ss) >= 0);
224✔
1333
                        assert_se(sigaddset(&ss, SIGTERM) >= 0);
224✔
1334

1335
                        assert_se(sigwait(&ss, &sig) == 0);
224✔
1336
                        assert(sig == SIGTERM);
224✔
1337
                }
1338

1339
                /* If our parent died we'll end the session */
1340
                if (getppid() != parent_pid) {
224✔
1341
                        pam_code = pam_close_session_and_delete_credentials(handle, flags);
223✔
1342
                        if (pam_code != PAM_SUCCESS)
223✔
1343
                                goto child_finish;
156✔
1344
                }
1345

1346
                ret = 0;
1347

1348
        child_finish:
224✔
1349
                /* NB: pam_end() when called in child processes should set PAM_DATA_SILENT to let the module
1350
                 * know about this. See pam_end(3) */
1351
                (void) pam_end(handle, pam_code | flags | PAM_DATA_SILENT);
224✔
1352
                _exit(ret);
224✔
1353
        }
1354

1355
        barrier_set_role(&barrier, BARRIER_PARENT);
402✔
1356

1357
        /* If the child was forked off successfully it will do all the cleanups, so forget about the handle
1358
         * here. */
1359
        handle = NULL;
402✔
1360

1361
        /* Unblock SIGTERM again in the parent */
1362
        assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0);
402✔
1363

1364
        /* We close the log explicitly here, since the PAM modules might have opened it, but we don't want
1365
         * this fd around. */
1366
        closelog();
402✔
1367

1368
        /* Synchronously wait for the child to initialize. We don't care for errors as we cannot
1369
         * recover. However, warn loudly if it happens. */
1370
        if (!barrier_place_and_sync(&barrier))
804✔
1371
                log_error("PAM initialization failed");
×
1372

1373
        return strv_free_and_replace(*env, e);
402✔
1374

1375
fail:
×
1376
        if (pam_code != PAM_SUCCESS) {
×
1377
                log_error("PAM failed: %s", pam_strerror(handle, pam_code));
×
1378
                r = -EPERM;  /* PAM errors do not map to errno */
1379
        } else
1380
                log_error_errno(r, "PAM failed: %m");
×
1381

1382
        if (handle) {
×
1383
                if (close_session)
×
1384
                        pam_code = pam_close_session_and_delete_credentials(handle, flags);
×
1385

1386
                (void) pam_end(handle, pam_code | flags);
×
1387
        }
1388

1389
        closelog();
×
1390
        return r;
1391
#else
1392
        return 0;
1393
#endif
1394
}
1395

1396
static void rename_process_from_path(const char *path) {
11,537✔
1397
        _cleanup_free_ char *buf = NULL;
11,537✔
1398
        const char *p;
11,537✔
1399

1400
        assert(path);
11,537✔
1401

1402
        /* This resulting string must fit in 10 chars (i.e. the length of "/sbin/init") to look pretty in
1403
         * /bin/ps */
1404

1405
        if (path_extract_filename(path, &buf) < 0) {
11,537✔
1406
                rename_process("(...)");
×
1407
                return;
×
1408
        }
1409

1410
        size_t l = strlen(buf);
11,537✔
1411
        if (l > 8) {
11,537✔
1412
                /* The end of the process name is usually more interesting, since the first bit might just be
1413
                 * "systemd-" */
1414
                p = buf + l - 8;
7,981✔
1415
                l = 8;
7,981✔
1416
        } else
1417
                p = buf;
1418

1419
        char process_name[11];
11,537✔
1420
        process_name[0] = '(';
11,537✔
1421
        memcpy(process_name+1, p, l);
11,537✔
1422
        process_name[1+l] = ')';
11,537✔
1423
        process_name[1+l+1] = 0;
11,537✔
1424

1425
        (void) rename_process(process_name);
11,537✔
1426
}
1427

1428
static bool context_has_address_families(const ExecContext *c) {
12,487✔
1429
        assert(c);
12,487✔
1430

1431
        return c->address_families_allow_list ||
12,487✔
1432
                !set_isempty(c->address_families);
10,994✔
1433
}
1434

1435
static bool context_has_syscall_filters(const ExecContext *c) {
12,451✔
1436
        assert(c);
12,451✔
1437

1438
        return c->syscall_allow_list ||
12,451✔
1439
                !hashmap_isempty(c->syscall_filter);
10,973✔
1440
}
1441

1442
static bool context_has_syscall_logs(const ExecContext *c) {
12,451✔
1443
        assert(c);
12,451✔
1444

1445
        return c->syscall_log_allow_list ||
12,451✔
1446
                !hashmap_isempty(c->syscall_log);
12,451✔
1447
}
1448

1449
static bool context_has_seccomp(const ExecContext *c) {
3,646✔
1450
        assert(c);
3,646✔
1451

1452
        /* We need NNP if we have any form of seccomp and are unprivileged */
1453
        return c->lock_personality ||
6,577✔
1454
                c->memory_deny_write_execute ||
2,931✔
1455
                c->private_devices ||
2,931✔
1456
                c->protect_clock ||
2,931✔
1457
                c->protect_hostname == PROTECT_HOSTNAME_YES ||
2,931✔
1458
                c->protect_kernel_tunables ||
2,931✔
1459
                c->protect_kernel_modules ||
2,931✔
1460
                c->protect_kernel_logs ||
5,862✔
1461
                context_has_address_families(c) ||
5,862✔
1462
                exec_context_restrict_namespaces_set(c) ||
2,931✔
1463
                c->restrict_realtime ||
2,931✔
1464
                c->restrict_suid_sgid ||
2,931✔
1465
                !set_isempty(c->syscall_archs) ||
5,790✔
1466
                context_has_syscall_filters(c) ||
9,436✔
1467
                context_has_syscall_logs(c);
2,895✔
1468
}
1469

1470
static bool context_has_no_new_privileges(const ExecContext *c) {
9,556✔
1471
        assert(c);
9,556✔
1472

1473
        if (c->no_new_privileges)
9,556✔
1474
                return true;
1475

1476
        if (have_effective_cap(CAP_SYS_ADMIN) > 0) /* if we are privileged, we don't need NNP */
8,139✔
1477
                return false;
1478

1479
        return context_has_seccomp(c);
1,627✔
1480
}
1481

1482
#if HAVE_SECCOMP
1483

1484
static bool seccomp_allows_drop_privileges(const ExecContext *c) {
751✔
1485
        void *id, *val;
751✔
1486
        bool have_capget = false, have_capset = false, have_prctl = false;
751✔
1487

1488
        assert(c);
751✔
1489

1490
        /* No syscall filter, we are allowed to drop privileges */
1491
        if (hashmap_isempty(c->syscall_filter))
751✔
1492
                return true;
751✔
1493

1494
        HASHMAP_FOREACH_KEY(val, id, c->syscall_filter) {
272,261✔
1495
                _cleanup_free_ char *name = NULL;
271,562✔
1496

1497
                name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
271,562✔
1498

1499
                if (streq(name, "capget"))
271,562✔
1500
                        have_capget = true;
1501
                else if (streq(name, "capset"))
270,863✔
1502
                        have_capset = true;
1503
                else if (streq(name, "prctl"))
270,164✔
1504
                        have_prctl = true;
699✔
1505
        }
1506

1507
        if (c->syscall_allow_list)
699✔
1508
                return have_capget && have_capset && have_prctl;
699✔
1509
        else
1510
                return !(have_capget || have_capset || have_prctl);
×
1511
}
1512

1513
static bool skip_seccomp_unavailable(const char *msg) {
14,911✔
1514
        assert(msg);
14,911✔
1515

1516
        if (is_seccomp_available())
14,911✔
1517
                return false;
1518

1519
        log_debug("SECCOMP features not detected in the kernel, skipping %s", msg);
×
1520
        return true;
1521
}
1522

1523
static int apply_syscall_filter(const ExecContext *c, const ExecParameters *p) {
9,556✔
1524
        uint32_t negative_action, default_action, action;
9,556✔
1525
        int r;
9,556✔
1526

1527
        assert(c);
9,556✔
1528
        assert(p);
9,556✔
1529

1530
        if (!context_has_syscall_filters(c))
9,556✔
1531
                return 0;
1532

1533
        if (skip_seccomp_unavailable("SystemCallFilter="))
1,479✔
1534
                return 0;
1535

1536
        negative_action = c->syscall_errno == SECCOMP_ERROR_NUMBER_KILL ? scmp_act_kill_process() : SCMP_ACT_ERRNO(c->syscall_errno);
1,479✔
1537

1538
        if (c->syscall_allow_list) {
1,479✔
1539
                default_action = negative_action;
1540
                action = SCMP_ACT_ALLOW;
1541
        } else {
1542
                default_action = SCMP_ACT_ALLOW;
1✔
1543
                action = negative_action;
1✔
1544
        }
1545

1546
        /* Sending over exec_fd or handoff_timestamp_fd requires write() syscall. */
1547
        if (p->exec_fd >= 0 || p->handoff_timestamp_fd >= 0) {
1,479✔
1548
                r = seccomp_filter_set_add_by_name(c->syscall_filter, c->syscall_allow_list, "write");
1,479✔
1549
                if (r < 0)
1,479✔
1550
                        return r;
1551
        }
1552

1553
        return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_filter, action, false);
1,479✔
1554
}
1555

1556
static int apply_syscall_log(const ExecContext *c, const ExecParameters *p) {
9,556✔
1557
#ifdef SCMP_ACT_LOG
1558
        uint32_t default_action, action;
9,556✔
1559
#endif
1560

1561
        assert(c);
9,556✔
1562
        assert(p);
9,556✔
1563

1564
        if (!context_has_syscall_logs(c))
9,556✔
1565
                return 0;
1566

1567
#ifdef SCMP_ACT_LOG
1568
        if (skip_seccomp_unavailable("SystemCallLog="))
×
1569
                return 0;
1570

1571
        if (c->syscall_log_allow_list) {
×
1572
                /* Log nothing but the ones listed */
1573
                default_action = SCMP_ACT_ALLOW;
1574
                action = SCMP_ACT_LOG;
1575
        } else {
1576
                /* Log everything but the ones listed */
1577
                default_action = SCMP_ACT_LOG;
×
1578
                action = SCMP_ACT_ALLOW;
×
1579
        }
1580

1581
        return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_log, action, false);
×
1582
#else
1583
        /* old libseccomp */
1584
        log_debug( "SECCOMP feature SCMP_ACT_LOG not available, skipping SystemCallLog=");
1585
        return 0;
1586
#endif
1587
}
1588

1589
static int apply_syscall_archs(const ExecContext *c, const ExecParameters *p) {
9,556✔
1590
        assert(c);
9,556✔
1591
        assert(p);
9,556✔
1592

1593
        if (set_isempty(c->syscall_archs))
9,556✔
1594
                return 0;
1595

1596
        if (skip_seccomp_unavailable("SystemCallArchitectures="))
1,495✔
1597
                return 0;
1598

1599
        return seccomp_restrict_archs(c->syscall_archs);
1,495✔
1600
}
1601

1602
static int apply_address_families(const ExecContext *c, const ExecParameters *p) {
9,556✔
1603
        assert(c);
9,556✔
1604
        assert(p);
9,556✔
1605

1606
        if (!context_has_address_families(c))
9,556✔
1607
                return 0;
1608

1609
        if (skip_seccomp_unavailable("RestrictAddressFamilies="))
1,493✔
1610
                return 0;
1611

1612
        return seccomp_restrict_address_families(c->address_families, c->address_families_allow_list);
1,493✔
1613
}
1614

1615
static int apply_memory_deny_write_execute(const ExecContext *c, const ExecParameters *p) {
9,556✔
1616
        int r;
9,556✔
1617

1618
        assert(c);
9,556✔
1619
        assert(p);
9,556✔
1620

1621
        if (!c->memory_deny_write_execute)
9,556✔
1622
                return 0;
1623

1624
        /* use prctl() if kernel supports it (6.3) */
1625
        r = prctl(PR_SET_MDWE, PR_MDWE_REFUSE_EXEC_GAIN, 0, 0, 0);
1,493✔
1626
        if (r == 0) {
1,493✔
1627
                log_debug("Enabled MemoryDenyWriteExecute= with PR_SET_MDWE");
1,493✔
1628
                return 0;
1,493✔
1629
        }
1630
        if (r < 0 && errno != EINVAL)
×
1631
                return log_debug_errno(errno, "Failed to enable MemoryDenyWriteExecute= with PR_SET_MDWE: %m");
×
1632
        /* else use seccomp */
1633
        log_debug("Kernel doesn't support PR_SET_MDWE: falling back to seccomp");
×
1634

1635
        if (skip_seccomp_unavailable("MemoryDenyWriteExecute="))
×
1636
                return 0;
1637

1638
        return seccomp_memory_deny_write_execute();
×
1639
}
1640

1641
static int apply_restrict_realtime(const ExecContext *c, const ExecParameters *p) {
9,556✔
1642
        assert(c);
9,556✔
1643
        assert(p);
9,556✔
1644

1645
        if (!c->restrict_realtime)
9,556✔
1646
                return 0;
1647

1648
        if (skip_seccomp_unavailable("RestrictRealtime="))
1,493✔
1649
                return 0;
1650

1651
        return seccomp_restrict_realtime();
1,493✔
1652
}
1653

1654
static int apply_restrict_suid_sgid(const ExecContext *c, const ExecParameters *p) {
9,556✔
1655
        assert(c);
9,556✔
1656
        assert(p);
9,556✔
1657

1658
        if (!c->restrict_suid_sgid)
9,556✔
1659
                return 0;
1660

1661
        if (skip_seccomp_unavailable("RestrictSUIDSGID="))
1,414✔
1662
                return 0;
1663

1664
        return seccomp_restrict_suid_sgid();
1,414✔
1665
}
1666

1667
static int apply_protect_sysctl(const ExecContext *c, const ExecParameters *p) {
9,556✔
1668
        assert(c);
9,556✔
1669
        assert(p);
9,556✔
1670

1671
        /* Turn off the legacy sysctl() system call. Many distributions turn this off while building the kernel, but
1672
         * let's protect even those systems where this is left on in the kernel. */
1673

1674
        if (!c->protect_kernel_tunables)
9,556✔
1675
                return 0;
1676

1677
        if (skip_seccomp_unavailable("ProtectKernelTunables="))
364✔
1678
                return 0;
1679

1680
        return seccomp_protect_sysctl();
364✔
1681
}
1682

1683
static int apply_protect_kernel_modules(const ExecContext *c, const ExecParameters *p) {
9,556✔
1684
        assert(c);
9,556✔
1685
        assert(p);
9,556✔
1686

1687
        /* Turn off module syscalls on ProtectKernelModules=yes */
1688

1689
        if (!c->protect_kernel_modules)
9,556✔
1690
                return 0;
1691

1692
        if (skip_seccomp_unavailable("ProtectKernelModules="))
1,131✔
1693
                return 0;
1694

1695
        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_MODULE, SCMP_ACT_ERRNO(EPERM), false);
1,131✔
1696
}
1697

1698
static int apply_protect_kernel_logs(const ExecContext *c, const ExecParameters *p) {
9,556✔
1699
        assert(c);
9,556✔
1700
        assert(p);
9,556✔
1701

1702
        if (!c->protect_kernel_logs)
9,556✔
1703
                return 0;
1704

1705
        if (skip_seccomp_unavailable("ProtectKernelLogs="))
1,131✔
1706
                return 0;
1707

1708
        return seccomp_protect_syslog();
1,131✔
1709
}
1710

1711
static int apply_protect_clock(const ExecContext *c, const ExecParameters *p) {
9,556✔
1712
        assert(c);
9,556✔
1713
        assert(p);
9,556✔
1714

1715
        if (!c->protect_clock)
9,556✔
1716
                return 0;
1717

1718
        if (skip_seccomp_unavailable("ProtectClock="))
842✔
1719
                return 0;
1720

1721
        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_CLOCK, SCMP_ACT_ERRNO(EPERM), false);
842✔
1722
}
1723

1724
static int apply_private_devices(const ExecContext *c, const ExecParameters *p) {
9,556✔
1725
        assert(c);
9,556✔
1726
        assert(p);
9,556✔
1727

1728
        /* If PrivateDevices= is set, also turn off iopl and all @raw-io syscalls. */
1729

1730
        if (!c->private_devices)
9,556✔
1731
                return 0;
1732

1733
        if (skip_seccomp_unavailable("PrivateDevices="))
677✔
1734
                return 0;
1735

1736
        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_RAW_IO, SCMP_ACT_ERRNO(EPERM), false);
677✔
1737
}
1738

1739
static int apply_restrict_namespaces(const ExecContext *c, const ExecParameters *p) {
9,556✔
1740
        assert(c);
9,556✔
1741
        assert(p);
9,556✔
1742

1743
        if (!exec_context_restrict_namespaces_set(c))
9,556✔
1744
                return 0;
1745

1746
        if (skip_seccomp_unavailable("RestrictNamespaces="))
1,239✔
1747
                return 0;
1748

1749
        return seccomp_restrict_namespaces(c->restrict_namespaces);
1,239✔
1750
}
1751

1752
static int apply_lock_personality(const ExecContext *c, const ExecParameters *p) {
9,556✔
1753
        unsigned long personality;
9,556✔
1754
        int r;
9,556✔
1755

1756
        assert(c);
9,556✔
1757
        assert(p);
9,556✔
1758

1759
        if (!c->lock_personality)
9,556✔
1760
                return 0;
9,556✔
1761

1762
        if (skip_seccomp_unavailable("LockPersonality="))
1,493✔
1763
                return 0;
1764

1765
        personality = c->personality;
1,493✔
1766

1767
        /* If personality is not specified, use either PER_LINUX or PER_LINUX32 depending on what is currently set. */
1768
        if (personality == PERSONALITY_INVALID) {
1,493✔
1769

1770
                r = opinionated_personality(&personality);
1,493✔
1771
                if (r < 0)
1,493✔
1772
                        return r;
1773
        }
1774

1775
        return seccomp_lock_personality(personality);
1,493✔
1776
}
1777

1778
#endif
1779

1780
#if HAVE_LIBBPF
1781
static int apply_restrict_filesystems(const ExecContext *c, const ExecParameters *p) {
9,556✔
1782
        int r;
9,556✔
1783

1784
        assert(c);
9,556✔
1785
        assert(p);
9,556✔
1786

1787
        if (!exec_context_restrict_filesystems_set(c))
9,556✔
1788
                return 0;
1789

1790
        if (p->bpf_restrict_fs_map_fd < 0) {
×
1791
                /* LSM BPF is unsupported or lsm_bpf_setup failed */
1792
                log_debug("LSM BPF not supported, skipping RestrictFileSystems=");
×
1793
                return 0;
×
1794
        }
1795

1796
        /* We are in a new binary, so dl-open again */
1797
        r = dlopen_bpf();
×
1798
        if (r < 0)
×
1799
                return r;
1800

1801
        return bpf_restrict_fs_update(c->restrict_filesystems, p->cgroup_id, p->bpf_restrict_fs_map_fd, c->restrict_filesystems_allow_list);
×
1802
}
1803
#endif
1804

1805
static int apply_protect_hostname(const ExecContext *c, const ExecParameters *p, int *ret_exit_status) {
9,559✔
1806
        int r;
9,559✔
1807

1808
        assert(c);
9,559✔
1809
        assert(p);
9,559✔
1810
        assert(ret_exit_status);
9,559✔
1811

1812
        if (c->protect_hostname == PROTECT_HOSTNAME_NO)
9,559✔
1813
                return 0;
1814

1815
        if (namespace_type_supported(NAMESPACE_UTS)) {
666✔
1816
                if (unshare(CLONE_NEWUTS) < 0) {
666✔
1817
                        if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno)) {
×
1818
                                *ret_exit_status = EXIT_NAMESPACE;
×
1819
                                return log_error_errno(errno, "Failed to set up UTS namespacing: %m");
×
1820
                        }
1821

1822
                        log_warning("ProtectHostname=%s is configured, but UTS namespace setup is prohibited (container manager?), ignoring namespace setup.",
×
1823
                                    protect_hostname_to_string(c->protect_hostname));
1824

1825
                } else if (c->private_hostname) {
666✔
1826
                        r = sethostname_idempotent(c->private_hostname);
4✔
1827
                        if (r < 0) {
4✔
1828
                                *ret_exit_status = EXIT_NAMESPACE;
×
1829
                                return log_error_errno(r, "Failed to set private hostname '%s': %m", c->private_hostname);
×
1830
                        }
1831
                }
1832
        } else
1833
                log_warning("ProtectHostname=%s is configured, but the kernel does not support UTS namespaces, ignoring namespace setup.",
×
1834
                            protect_hostname_to_string(c->protect_hostname));
1835

1836
#if HAVE_SECCOMP
1837
        if (c->protect_hostname == PROTECT_HOSTNAME_YES) {
666✔
1838
                if (skip_seccomp_unavailable("ProtectHostname="))
660✔
1839
                        return 0;
1840

1841
                r = seccomp_protect_hostname();
660✔
1842
                if (r < 0) {
660✔
1843
                        *ret_exit_status = EXIT_SECCOMP;
×
1844
                        return log_error_errno(r, "Failed to apply hostname restrictions: %m");
×
1845
                }
1846
        }
1847
#endif
1848

1849
        return 1;
1850
}
1851

1852
static void do_idle_pipe_dance(int idle_pipe[static 4]) {
150✔
1853
        assert(idle_pipe);
150✔
1854

1855
        idle_pipe[1] = safe_close(idle_pipe[1]);
150✔
1856
        idle_pipe[2] = safe_close(idle_pipe[2]);
150✔
1857

1858
        if (idle_pipe[0] >= 0) {
150✔
1859
                int r;
150✔
1860

1861
                r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
150✔
1862

1863
                if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
150✔
1864
                        ssize_t n;
108✔
1865

1866
                        /* Signal systemd that we are bored and want to continue. */
1867
                        n = write(idle_pipe[3], "x", 1);
108✔
1868
                        if (n > 0)
108✔
1869
                                /* Wait for systemd to react to the signal above. */
1870
                                (void) fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
108✔
1871
                }
1872

1873
                idle_pipe[0] = safe_close(idle_pipe[0]);
150✔
1874

1875
        }
1876

1877
        idle_pipe[3] = safe_close(idle_pipe[3]);
150✔
1878
}
150✔
1879

1880
static const char *exec_directory_env_name_to_string(ExecDirectoryType t);
1881

1882
/* And this table also maps ExecDirectoryType, to the environment variable we pass the selected directory to
1883
 * the service payload in. */
1884
static const char* const exec_directory_env_name_table[_EXEC_DIRECTORY_TYPE_MAX] = {
1885
        [EXEC_DIRECTORY_RUNTIME]       = "RUNTIME_DIRECTORY",
1886
        [EXEC_DIRECTORY_STATE]         = "STATE_DIRECTORY",
1887
        [EXEC_DIRECTORY_CACHE]         = "CACHE_DIRECTORY",
1888
        [EXEC_DIRECTORY_LOGS]          = "LOGS_DIRECTORY",
1889
        [EXEC_DIRECTORY_CONFIGURATION] = "CONFIGURATION_DIRECTORY",
1890
};
1891

1892
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(exec_directory_env_name, ExecDirectoryType);
2,498✔
1893

1894
static int build_environment(
9,583✔
1895
                const ExecContext *c,
1896
                const ExecParameters *p,
1897
                const CGroupContext *cgroup_context,
1898
                size_t n_fds,
1899
                const char *home,
1900
                const char *username,
1901
                const char *shell,
1902
                dev_t journal_stream_dev,
1903
                ino_t journal_stream_ino,
1904
                const char *memory_pressure_path,
1905
                bool needs_sandboxing,
1906
                char ***ret) {
1907

1908
        _cleanup_strv_free_ char **our_env = NULL;
9,583✔
1909
        size_t n_env = 0;
9,583✔
1910
        char *x;
9,583✔
1911
        int r;
9,583✔
1912

1913
        assert(c);
9,583✔
1914
        assert(p);
9,583✔
1915
        assert(cgroup_context);
9,583✔
1916
        assert(ret);
9,583✔
1917

1918
#define N_ENV_VARS 19
1919
        our_env = new0(char*, N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX + 1);
9,583✔
1920
        if (!our_env)
9,583✔
1921
                return -ENOMEM;
1922

1923
        if (n_fds > 0) {
9,583✔
1924
                _cleanup_free_ char *joined = NULL;
1,537✔
1925

1926
                if (asprintf(&x, "LISTEN_PID="PID_FMT, getpid_cached()) < 0)
1,537✔
1927
                        return -ENOMEM;
1928
                our_env[n_env++] = x;
1,537✔
1929

1930
                if (asprintf(&x, "LISTEN_FDS=%zu", n_fds) < 0)
1,537✔
1931
                        return -ENOMEM;
1932
                our_env[n_env++] = x;
1,537✔
1933

1934
                joined = strv_join(p->fd_names, ":");
1,537✔
1935
                if (!joined)
1,537✔
1936
                        return -ENOMEM;
1937

1938
                x = strjoin("LISTEN_FDNAMES=", joined);
1,537✔
1939
                if (!x)
1,537✔
1940
                        return -ENOMEM;
1941
                our_env[n_env++] = x;
1,537✔
1942
        }
1943

1944
        if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) {
9,583✔
1945
                if (asprintf(&x, "WATCHDOG_PID="PID_FMT, getpid_cached()) < 0)
1,487✔
1946
                        return -ENOMEM;
1947
                our_env[n_env++] = x;
1,487✔
1948

1949
                if (asprintf(&x, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec) < 0)
1,487✔
1950
                        return -ENOMEM;
1951
                our_env[n_env++] = x;
1,487✔
1952
        }
1953

1954
        /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use blocking
1955
         * Varlink calls back to us for look up dynamic users in PID 1. Break the deadlock between D-Bus and
1956
         * PID 1 by disabling use of PID1' NSS interface for looking up dynamic users. */
1957
        if (p->flags & EXEC_NSS_DYNAMIC_BYPASS) {
9,583✔
1958
                x = strdup("SYSTEMD_NSS_DYNAMIC_BYPASS=1");
121✔
1959
                if (!x)
121✔
1960
                        return -ENOMEM;
1961
                our_env[n_env++] = x;
121✔
1962
        }
1963

1964
        /* We query "root" if this is a system unit and User= is not specified. $USER is always set. $HOME
1965
         * could cause problem for e.g. getty, since login doesn't override $HOME, and $LOGNAME and $SHELL don't
1966
         * really make much sense since we're not logged in. Hence we conditionalize the three based on
1967
         * SetLoginEnvironment= switch. */
1968
        if (!username && !c->dynamic_user && p->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
9,583✔
1969
                assert(!c->user);
6,767✔
1970

1971
                r = get_fixed_user("root", /* prefer_nss = */ false, &username, NULL, NULL, &home, &shell);
6,767✔
1972
                if (r < 0)
6,767✔
1973
                        return log_debug_errno(r, "Failed to determine user credentials for root: %m");
×
1974
        }
1975

1976
        bool set_user_login_env = exec_context_get_set_login_environment(c);
9,583✔
1977

1978
        if (username) {
9,583✔
1979
                x = strjoin("USER=", username);
8,789✔
1980
                if (!x)
8,789✔
1981
                        return -ENOMEM;
1982
                our_env[n_env++] = x;
8,789✔
1983

1984
                if (set_user_login_env) {
8,789✔
1985
                        x = strjoin("LOGNAME=", username);
2,018✔
1986
                        if (!x)
2,018✔
1987
                                return -ENOMEM;
1988
                        our_env[n_env++] = x;
2,018✔
1989
                }
1990
        }
1991

1992
        /* Note that we don't set $HOME or $SHELL if they are not particularly enlightening anyway
1993
         * (i.e. are "/" or "/bin/nologin"). */
1994

1995
        if (home && set_user_login_env && !empty_or_root(home)) {
9,583✔
1996
                x = strjoin("HOME=", home);
415✔
1997
                if (!x)
415✔
1998
                        return -ENOMEM;
1999

2000
                path_simplify(x + 5);
415✔
2001
                our_env[n_env++] = x;
415✔
2002
        }
2003

2004
        if (shell && set_user_login_env && !shell_is_placeholder(shell)) {
9,583✔
2005
                x = strjoin("SHELL=", shell);
417✔
2006
                if (!x)
417✔
2007
                        return -ENOMEM;
2008

2009
                path_simplify(x + 6);
417✔
2010
                our_env[n_env++] = x;
417✔
2011
        }
2012

2013
        if (!sd_id128_is_null(p->invocation_id)) {
9,583✔
2014
                assert(p->invocation_id_string);
9,583✔
2015

2016
                x = strjoin("INVOCATION_ID=", p->invocation_id_string);
9,583✔
2017
                if (!x)
9,583✔
2018
                        return -ENOMEM;
2019

2020
                our_env[n_env++] = x;
9,583✔
2021
        }
2022

2023
        if (journal_stream_dev != 0 && journal_stream_ino != 0) {
9,583✔
2024
                if (asprintf(&x, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino) < 0)
8,796✔
2025
                        return -ENOMEM;
2026

2027
                our_env[n_env++] = x;
8,796✔
2028
        }
2029

2030
        if (c->log_namespace) {
9,583✔
2031
                x = strjoin("LOG_NAMESPACE=", c->log_namespace);
2✔
2032
                if (!x)
2✔
2033
                        return -ENOMEM;
2034

2035
                our_env[n_env++] = x;
2✔
2036
        }
2037

2038
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
57,498✔
2039
                _cleanup_free_ char *joined = NULL;
47,915✔
2040
                const char *n;
47,915✔
2041

2042
                if (!p->prefix[t])
47,915✔
2043
                        continue;
×
2044

2045
                if (c->directories[t].n_items == 0)
47,915✔
2046
                        continue;
45,417✔
2047

2048
                n = exec_directory_env_name_to_string(t);
2,498✔
2049
                if (!n)
2,498✔
2050
                        continue;
×
2051

2052
                for (size_t i = 0; i < c->directories[t].n_items; i++) {
5,492✔
2053
                        _cleanup_free_ char *prefixed = NULL;
2,994✔
2054

2055
                        prefixed = path_join(p->prefix[t], c->directories[t].items[i].path);
2,994✔
2056
                        if (!prefixed)
2,994✔
2057
                                return -ENOMEM;
2058

2059
                        if (!strextend_with_separator(&joined, ":", prefixed))
2,994✔
2060
                                return -ENOMEM;
2061
                }
2062

2063
                x = strjoin(n, "=", joined);
2,498✔
2064
                if (!x)
2,498✔
2065
                        return -ENOMEM;
2066

2067
                our_env[n_env++] = x;
2,498✔
2068
        }
2069

2070
        _cleanup_free_ char *creds_dir = NULL;
9,583✔
2071
        r = exec_context_get_credential_directory(c, p, p->unit_id, &creds_dir);
9,583✔
2072
        if (r < 0)
9,583✔
2073
                return r;
2074
        if (r > 0) {
9,583✔
2075
                x = strjoin("CREDENTIALS_DIRECTORY=", creds_dir);
1,941✔
2076
                if (!x)
1,941✔
2077
                        return -ENOMEM;
2078

2079
                our_env[n_env++] = x;
1,941✔
2080
        }
2081

2082
        if (asprintf(&x, "SYSTEMD_EXEC_PID=" PID_FMT, getpid_cached()) < 0)
9,583✔
2083
                return -ENOMEM;
2084

2085
        our_env[n_env++] = x;
9,583✔
2086

2087
        if (memory_pressure_path) {
9,583✔
2088
                x = strjoin("MEMORY_PRESSURE_WATCH=", memory_pressure_path);
9,185✔
2089
                if (!x)
9,185✔
2090
                        return -ENOMEM;
2091

2092
                our_env[n_env++] = x;
9,185✔
2093

2094
                if (!path_equal(memory_pressure_path, "/dev/null")) {
9,185✔
2095
                        _cleanup_free_ char *b = NULL, *e = NULL;
9,185✔
2096

2097
                        if (asprintf(&b, "%s " USEC_FMT " " USEC_FMT,
9,185✔
2098
                                     MEMORY_PRESSURE_DEFAULT_TYPE,
2099
                                     cgroup_context->memory_pressure_threshold_usec == USEC_INFINITY ? MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC :
9,185✔
2100
                                     CLAMP(cgroup_context->memory_pressure_threshold_usec, 1U, MEMORY_PRESSURE_DEFAULT_WINDOW_USEC),
9,185✔
2101
                                     MEMORY_PRESSURE_DEFAULT_WINDOW_USEC) < 0)
2102
                                return -ENOMEM;
2103

2104
                        if (base64mem(b, strlen(b) + 1, &e) < 0)
9,185✔
2105
                                return -ENOMEM;
2106

2107
                        x = strjoin("MEMORY_PRESSURE_WRITE=", e);
9,185✔
2108
                        if (!x)
9,185✔
2109
                                return -ENOMEM;
2110

2111
                        our_env[n_env++] = x;
9,185✔
2112
                }
2113
        }
2114

2115
        if (p->notify_socket) {
9,583✔
2116
                x = strjoin("NOTIFY_SOCKET=", exec_get_private_notify_socket_path(c, p, needs_sandboxing) ?: p->notify_socket);
1,893✔
2117
                if (!x)
1,893✔
2118
                        return -ENOMEM;
2119

2120
                our_env[n_env++] = x;
1,893✔
2121
        }
2122

2123
        assert(c->private_var_tmp >= 0 && c->private_var_tmp < _PRIVATE_TMP_MAX);
9,583✔
2124
        if (needs_sandboxing && c->private_tmp != c->private_var_tmp) {
9,583✔
2125
                assert(c->private_tmp == PRIVATE_TMP_DISCONNECTED);
284✔
2126
                assert(c->private_var_tmp == PRIVATE_TMP_NO);
284✔
2127

2128
                /* When private tmpfs is enabled only on /tmp/, then explicitly set $TMPDIR to suggest the
2129
                 * service to use /tmp/. */
2130

2131
                x = strdup("TMPDIR=/tmp");
284✔
2132
                if (!x)
284✔
2133
                        return -ENOMEM;
2134

2135
                our_env[n_env++] = x;
284✔
2136
        }
2137

2138
        assert(n_env <= N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
9,583✔
2139
#undef N_ENV_VARS
2140

2141
        *ret = TAKE_PTR(our_env);
9,583✔
2142

2143
        return 0;
9,583✔
2144
}
2145

2146
static int build_pass_environment(const ExecContext *c, char ***ret) {
9,583✔
2147
        _cleanup_strv_free_ char **pass_env = NULL;
9,583✔
2148
        size_t n_env = 0;
9,583✔
2149

2150
        assert(c);
9,583✔
2151
        assert(ret);
9,583✔
2152

2153
        STRV_FOREACH(i, c->pass_environment) {
9,885✔
2154
                _cleanup_free_ char *x = NULL;
×
2155
                char *v;
302✔
2156

2157
                v = getenv(*i);
302✔
2158
                if (!v)
302✔
2159
                        continue;
×
2160
                x = strjoin(*i, "=", v);
302✔
2161
                if (!x)
302✔
2162
                        return -ENOMEM;
2163

2164
                if (!GREEDY_REALLOC(pass_env, n_env + 2))
302✔
2165
                        return -ENOMEM;
2166

2167
                pass_env[n_env++] = TAKE_PTR(x);
302✔
2168
                pass_env[n_env] = NULL;
302✔
2169
        }
2170

2171
        *ret = TAKE_PTR(pass_env);
9,583✔
2172
        return 0;
9,583✔
2173
}
2174

2175
static int setup_private_users(PrivateUsers private_users, uid_t ouid, gid_t ogid, uid_t uid, gid_t gid, bool allow_setgroups) {
9,567✔
2176
        _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
9,567✔
2177
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
9,567✔
2178
        _cleanup_close_ int unshare_ready_fd = -EBADF;
9,567✔
2179
        _cleanup_(sigkill_waitp) pid_t pid = 0;
9,567✔
2180
        uint64_t c = 1;
9,567✔
2181
        ssize_t n;
9,567✔
2182
        int r;
9,567✔
2183

2184
        /* Set up a user namespace and map the original UID/GID (IDs from before any user or group changes, i.e.
2185
         * the IDs from the user or system manager(s)) to itself, the selected UID/GID to itself, and everything else to
2186
         * nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which
2187
         * we however lack after opening the user namespace. To work around this we fork() a temporary child process,
2188
         * which waits for the parent to create the new user namespace while staying in the original namespace. The
2189
         * child then writes the UID mapping, under full privileges. The parent waits for the child to finish and
2190
         * continues execution normally.
2191
         * For unprivileged users (i.e. without capabilities), the root to root mapping is excluded. As such, it
2192
         * does not need CAP_SETUID to write the single line mapping to itself. */
2193

2194
        if (private_users == PRIVATE_USERS_NO)
9,567✔
2195
                return 0;
2196

2197
        if (private_users == PRIVATE_USERS_IDENTITY) {
52✔
2198
                uid_map = strdup("0 0 65536\n");
4✔
2199
                if (!uid_map)
4✔
2200
                        return -ENOMEM;
2201
        } else if (private_users == PRIVATE_USERS_FULL) {
48✔
2202
                /* Map all UID/GID from original to new user namespace. We can't use `0 0 UINT32_MAX` because
2203
                 * this is the same UID/GID map as the init user namespace and systemd's running_in_userns()
2204
                 * checks whether its in a user namespace by comparing uid_map/gid_map to `0 0 UINT32_MAX`.
2205
                 * Thus, we still map all UIDs/GIDs but do it using two extents to differentiate the new user
2206
                 * namespace from the init namespace:
2207
                 *   0 0 1
2208
                 *   1 1 UINT32_MAX - 1
2209
                 *
2210
                 * systemd will remove the heuristic in running_in_userns() and use namespace inodes in version 258
2211
                 * (PR #35382). But some users may be running a container image with older systemd < 258 so we keep
2212
                 * this uid_map/gid_map hack until version 259 for version N-1 compatibility.
2213
                 *
2214
                 * TODO: Switch to `0 0 UINT32_MAX` in systemd v259.
2215
                 *
2216
                 * Note the kernel defines the UID range between 0 and UINT32_MAX so we map all UIDs even though
2217
                 * the UID range beyond INT32_MAX (e.g. i.e. the range above the signed 32-bit range) is
2218
                 * icky. For example, setfsuid() returns the old UID as signed integer. But units can decide to
2219
                 * use these UIDs/GIDs so we need to map them. */
2220
                r = asprintf(&uid_map, "0 0 1\n"
5✔
2221
                                       "1 1 " UID_FMT "\n", (uid_t) (UINT32_MAX - 1));
2222
                if (r < 0)
5✔
2223
                        return -ENOMEM;
2224
        /* Can only set up multiple mappings with CAP_SETUID. */
2225
        } else if (have_effective_cap(CAP_SETUID) > 0 && uid != ouid && uid_is_valid(uid)) {
43✔
2226
                r = asprintf(&uid_map,
2✔
2227
                             UID_FMT " " UID_FMT " 1\n"     /* Map $OUID → $OUID */
2228
                             UID_FMT " " UID_FMT " 1\n",    /* Map $UID → $UID */
2229
                             ouid, ouid, uid, uid);
2230
                if (r < 0)
2✔
2231
                        return -ENOMEM;
2232
        } else {
2233
                r = asprintf(&uid_map,
41✔
2234
                             UID_FMT " " UID_FMT " 1\n",    /* Map $OUID → $OUID */
2235
                             ouid, ouid);
2236
                if (r < 0)
41✔
2237
                        return -ENOMEM;
2238
        }
2239

2240
        if (private_users == PRIVATE_USERS_IDENTITY) {
52✔
2241
                gid_map = strdup("0 0 65536\n");
4✔
2242
                if (!gid_map)
4✔
2243
                        return -ENOMEM;
2244
        } else if (private_users == PRIVATE_USERS_FULL) {
48✔
2245
                r = asprintf(&gid_map, "0 0 1\n"
5✔
2246
                                       "1 1 " GID_FMT "\n", (gid_t) (UINT32_MAX - 1));
2247
                if (r < 0)
5✔
2248
                        return -ENOMEM;
2249
        /* Can only set up multiple mappings with CAP_SETGID. */
2250
        } else if (have_effective_cap(CAP_SETGID) > 0 && gid != ogid && gid_is_valid(gid)) {
59✔
2251
                r = asprintf(&gid_map,
2✔
2252
                             GID_FMT " " GID_FMT " 1\n"     /* Map $OGID → $OGID */
2253
                             GID_FMT " " GID_FMT " 1\n",    /* Map $GID → $GID */
2254
                             ogid, ogid, gid, gid);
2255
                if (r < 0)
2✔
2256
                        return -ENOMEM;
2257
        } else {
2258
                r = asprintf(&gid_map,
41✔
2259
                             GID_FMT " " GID_FMT " 1\n",    /* Map $OGID -> $OGID */
2260
                             ogid, ogid);
2261
                if (r < 0)
41✔
2262
                        return -ENOMEM;
2263
        }
2264

2265
        /* Create a communication channel so that the parent can tell the child when it finished creating the user
2266
         * namespace. */
2267
        unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
52✔
2268
        if (unshare_ready_fd < 0)
52✔
2269
                return -errno;
×
2270

2271
        /* Create a communication channel so that the child can tell the parent a proper error code in case it
2272
         * failed. */
2273
        if (pipe2(errno_pipe, O_CLOEXEC) < 0)
52✔
2274
                return -errno;
×
2275

2276
        r = safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL, &pid);
52✔
2277
        if (r < 0)
103✔
2278
                return r;
2279
        if (r == 0) {
103✔
2280
                _cleanup_close_ int fd = -EBADF;
×
2281
                const char *a;
51✔
2282
                pid_t ppid;
51✔
2283

2284
                /* Child process, running in the original user namespace. Let's update the parent's UID/GID map from
2285
                 * here, after the parent opened its own user namespace. */
2286

2287
                ppid = getppid();
51✔
2288
                errno_pipe[0] = safe_close(errno_pipe[0]);
51✔
2289

2290
                /* Wait until the parent unshared the user namespace */
2291
                if (read(unshare_ready_fd, &c, sizeof(c)) < 0)
51✔
2292
                        report_errno_and_exit(errno_pipe[1], -errno);
×
2293

2294
                /* Disable the setgroups() system call in the child user namespace, for good, unless PrivateUsers=full
2295
                 * and using the system service manager. */
2296
                a = procfs_file_alloca(ppid, "setgroups");
51✔
2297
                fd = open(a, O_WRONLY|O_CLOEXEC);
51✔
2298
                if (fd < 0) {
51✔
2299
                        if (errno != ENOENT) {
×
2300
                                r = log_debug_errno(errno, "Failed to open %s: %m", a);
×
2301
                                report_errno_and_exit(errno_pipe[1], r);
×
2302
                        }
2303

2304
                        /* If the file is missing the kernel is too old, let's continue anyway. */
2305
                } else {
2306
                        const char *setgroups = allow_setgroups ? "allow\n" : "deny\n";
51✔
2307
                        if (write(fd, setgroups, strlen(setgroups)) < 0) {
51✔
2308
                                r = log_debug_errno(errno, "Failed to write '%s' to %s: %m", setgroups, a);
×
2309
                                report_errno_and_exit(errno_pipe[1], r);
×
2310
                        }
2311

2312
                        fd = safe_close(fd);
51✔
2313
                }
2314

2315
                /* First write the GID map */
2316
                a = procfs_file_alloca(ppid, "gid_map");
51✔
2317
                fd = open(a, O_WRONLY|O_CLOEXEC);
51✔
2318
                if (fd < 0) {
51✔
2319
                        r = log_debug_errno(errno, "Failed to open %s: %m", a);
×
2320
                        report_errno_and_exit(errno_pipe[1], r);
×
2321
                }
2322

2323
                if (write(fd, gid_map, strlen(gid_map)) < 0) {
51✔
2324
                        r = log_debug_errno(errno, "Failed to write GID map to %s: %m", a);
×
2325
                        report_errno_and_exit(errno_pipe[1], r);
×
2326
                }
2327

2328
                fd = safe_close(fd);
51✔
2329

2330
                /* The write the UID map */
2331
                a = procfs_file_alloca(ppid, "uid_map");
51✔
2332
                fd = open(a, O_WRONLY|O_CLOEXEC);
51✔
2333
                if (fd < 0) {
51✔
2334
                        r = log_debug_errno(errno, "Failed to open %s: %m", a);
×
2335
                        report_errno_and_exit(errno_pipe[1], r);
×
2336
                }
2337

2338
                if (write(fd, uid_map, strlen(uid_map)) < 0) {
51✔
2339
                        r = log_debug_errno(errno, "Failed to write UID map to %s: %m", a);
×
2340
                        report_errno_and_exit(errno_pipe[1], r);
×
2341
                }
2342

2343
                _exit(EXIT_SUCCESS);
51✔
2344
        }
2345

2346
        errno_pipe[1] = safe_close(errno_pipe[1]);
52✔
2347

2348
        if (unshare(CLONE_NEWUSER) < 0)
52✔
2349
                return log_debug_errno(errno, "Failed to unshare user namespace: %m");
×
2350

2351
        /* Let the child know that the namespace is ready now */
2352
        if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
52✔
2353
                return -errno;
×
2354

2355
        /* Try to read an error code from the child */
2356
        n = read(errno_pipe[0], &r, sizeof(r));
52✔
2357
        if (n < 0)
52✔
2358
                return -errno;
×
2359
        if (n == sizeof(r)) { /* an error code was sent to us */
52✔
2360
                if (r < 0)
×
2361
                        return r;
2362
                return -EIO;
×
2363
        }
2364
        if (n != 0) /* on success we should have read 0 bytes */
52✔
2365
                return -EIO;
2366

2367
        r = wait_for_terminate_and_check("(sd-userns)", TAKE_PID(pid), 0);
52✔
2368
        if (r < 0)
52✔
2369
                return r;
2370
        if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
52✔
2371
                return -EIO;
×
2372

2373
        return 1;
2374
}
2375

2376
static int can_mount_proc(void) {
10✔
2377
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
5✔
2378
        _cleanup_(sigkill_waitp) pid_t pid = 0;
×
2379
        ssize_t n;
10✔
2380
        int r;
10✔
2381

2382
        /* If running via unprivileged user manager and /proc/ is masked (e.g. /proc/kmsg is over-mounted with tmpfs
2383
         * like systemd-nspawn does), then mounting /proc/ will fail with EPERM. This is due to a kernel restriction
2384
         * where unprivileged user namespaces cannot mount a less restrictive instance of /proc. */
2385

2386
        /* Create a communication channel so that the child can tell the parent a proper error code in case it
2387
         * failed. */
2388
        if (pipe2(errno_pipe, O_CLOEXEC) < 0)
10✔
2389
                return log_debug_errno(errno, "Failed to create pipe for communicating with child process (sd-proc-check): %m");
×
2390

2391
        /* Fork a child process into its own mount and PID namespace. Note safe_fork() already remounts / as SLAVE
2392
         * with FORK_MOUNTNS_SLAVE. */
2393
        r = safe_fork("(sd-proc-check)",
10✔
2394
                      FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE|FORK_NEW_PIDNS, &pid);
2395
        if (r < 0)
10✔
2396
                return log_debug_errno(r, "Failed to fork child process (sd-proc-check): %m");
×
2397
        if (r == 0) {
10✔
2398
                errno_pipe[0] = safe_close(errno_pipe[0]);
5✔
2399

2400
                /* Try mounting /proc on /dev/shm/. No need to clean up the mount since the mount
2401
                 * namespace will be cleaned up once the process exits. */
2402
                r = mount_follow_verbose(LOG_DEBUG, "proc", "/dev/shm/", "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
5✔
2403
                if (r < 0) {
5✔
2404
                        (void) write(errno_pipe[1], &r, sizeof(r));
1✔
2405
                        _exit(EXIT_FAILURE);
1✔
2406
                }
2407

2408
                _exit(EXIT_SUCCESS);
4✔
2409
        }
2410

2411
        errno_pipe[1] = safe_close(errno_pipe[1]);
5✔
2412

2413
        /* Try to read an error code from the child */
2414
        n = read(errno_pipe[0], &r, sizeof(r));
5✔
2415
        if (n < 0)
5✔
2416
                return log_debug_errno(errno, "Failed to read errno from pipe with child process (sd-proc-check): %m");
×
2417
        if (n == sizeof(r)) { /* an error code was sent to us */
5✔
2418
                /* This is the expected case where proc cannot be mounted due to permissions. */
2419
                if (ERRNO_IS_NEG_PRIVILEGE(r))
5✔
2420
                        return 0;
2421
                if (r < 0)
×
2422
                        return r;
2423

2424
                return -EIO;
×
2425
        }
2426
        if (n != 0) /* on success we should have read 0 bytes */
4✔
2427
                return -EIO;
2428

2429
        r = wait_for_terminate_and_check("(sd-proc-check)", TAKE_PID(pid), 0 /* flags= */);
4✔
2430
        if (r < 0)
4✔
2431
                return log_debug_errno(r, "Failed to wait for (sd-proc-check) child process to terminate: %m");
×
2432
        if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
4✔
2433
                return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Child process (sd-proc-check) exited with unexpected exit status '%d'.", r);
×
2434

2435
        return 1;
2436
}
2437

2438
static int setup_private_pids(const ExecContext *c, ExecParameters *p) {
9✔
2439
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
×
2440
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
6✔
2441
        ssize_t n;
9✔
2442
        int r, q;
9✔
2443

2444
        assert(c);
9✔
2445
        assert(p);
9✔
2446
        assert(p->pidref_transport_fd >= 0);
9✔
2447

2448
        /* The first process created after unsharing a pid namespace becomes PID 1 in the pid namespace, so
2449
         * we have to fork after unsharing the pid namespace to become PID 1. The parent sends the child
2450
         * pidref to the manager and exits while the child process continues with the rest of exec_invoke()
2451
         * and finally executes the actual payload. */
2452

2453
        /* Create a communication channel so that the parent can tell the child a proper error code in case it
2454
         * failed to send child pidref to the manager. */
2455
        if (pipe2(errno_pipe, O_CLOEXEC) < 0)
9✔
2456
                return log_debug_errno(errno, "Failed to create pipe for communicating with parent process: %m");
×
2457

2458
        /* Set FORK_DETACH to immediately re-parent the child process to the invoking manager process. */
2459
        r = pidref_safe_fork("(sd-pidns-child)", FORK_NEW_PIDNS|FORK_DETACH, &pidref);
9✔
2460
        if (r < 0)
15✔
2461
                return log_debug_errno(r, "Failed to fork child into new pid namespace: %m");
×
2462
        if (r > 0) {
15✔
2463
                errno_pipe[0] = safe_close(errno_pipe[0]);
9✔
2464

2465
                /* In the parent process, we send the child pidref to the manager and exit.
2466
                 * If PIDFD is not supported, only the child PID is sent. The server then
2467
                 * uses the child PID to set the new exec main process. */
2468
                q = send_one_fd_iov(
9✔
2469
                                p->pidref_transport_fd,
2470
                                pidref.fd,
2471
                                &IOVEC_MAKE(&pidref.pid, sizeof(pidref.pid)),
2472
                                /*iovlen=*/ 1,
2473
                                /*flags=*/ 0);
2474
                /* Send error code to child process. */
2475
                (void) write(errno_pipe[1], &q, sizeof(q));
9✔
2476
                /* Exit here so we only go through the destructors in exec_invoke only once - in the child - as
2477
                 * some destructors have external effects. The main codepaths continue in the child process. */
2478
                _exit(q < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
9✔
2479
        }
2480

2481
        errno_pipe[1] = safe_close(errno_pipe[1]);
6✔
2482
        p->pidref_transport_fd = safe_close(p->pidref_transport_fd);
6✔
2483

2484
        /* Try to read an error code from the parent. Note a child process cannot wait for the parent so we always
2485
         * receive an errno even on success. */
2486
        n = read(errno_pipe[0], &r, sizeof(r));
6✔
2487
        if (n < 0)
6✔
2488
                return log_debug_errno(errno, "Failed to read errno from pipe with parent process: %m");
×
2489
        if (n != sizeof(r))
6✔
2490
                return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to read enough bytes from pipe with parent process");
×
2491
        if (r < 0)
6✔
2492
                return log_debug_errno(r, "Failed to send child pidref to manager: %m");
×
2493

2494
        /* NOTE! This function returns in the child process only. */
2495
        return r;
2496
}
2497

2498
static int create_many_symlinks(const char *root, const char *source, char **symlinks) {
1,530✔
2499
        _cleanup_free_ char *src_abs = NULL;
1,530✔
2500
        int r;
1,530✔
2501

2502
        assert(source);
1,530✔
2503

2504
        src_abs = path_join(root, source);
1,530✔
2505
        if (!src_abs)
1,530✔
2506
                return -ENOMEM;
2507

2508
        STRV_FOREACH(dst, symlinks) {
1,543✔
2509
                _cleanup_free_ char *dst_abs = NULL;
13✔
2510

2511
                dst_abs = path_join(root, *dst);
13✔
2512
                if (!dst_abs)
13✔
2513
                        return -ENOMEM;
2514

2515
                r = mkdir_parents_label(dst_abs, 0755);
13✔
2516
                if (r < 0)
13✔
2517
                        return r;
2518

2519
                r = symlink_idempotent(src_abs, dst_abs, true);
13✔
2520
                if (r < 0)
13✔
2521
                        return r;
2522
        }
2523

2524
        return 0;
2525
}
2526

2527
static int setup_exec_directory(
57,656✔
2528
                const ExecContext *context,
2529
                const ExecParameters *params,
2530
                uid_t uid,
2531
                gid_t gid,
2532
                ExecDirectoryType type,
2533
                bool needs_mount_namespace,
2534
                int *exit_status) {
2535

2536
        static const int exit_status_table[_EXEC_DIRECTORY_TYPE_MAX] = {
57,656✔
2537
                [EXEC_DIRECTORY_RUNTIME]       = EXIT_RUNTIME_DIRECTORY,
2538
                [EXEC_DIRECTORY_STATE]         = EXIT_STATE_DIRECTORY,
2539
                [EXEC_DIRECTORY_CACHE]         = EXIT_CACHE_DIRECTORY,
2540
                [EXEC_DIRECTORY_LOGS]          = EXIT_LOGS_DIRECTORY,
2541
                [EXEC_DIRECTORY_CONFIGURATION] = EXIT_CONFIGURATION_DIRECTORY,
2542
        };
2543
        int r;
57,656✔
2544

2545
        assert(context);
57,656✔
2546
        assert(params);
57,656✔
2547
        assert(type >= 0 && type < _EXEC_DIRECTORY_TYPE_MAX);
57,656✔
2548
        assert(exit_status);
57,656✔
2549

2550
        if (!params->prefix[type])
57,656✔
2551
                return 0;
2552

2553
        if (params->flags & EXEC_CHOWN_DIRECTORIES) {
57,656✔
2554
                if (!uid_is_valid(uid))
53,681✔
2555
                        uid = 0;
40,321✔
2556
                if (!gid_is_valid(gid))
53,681✔
2557
                        gid = 0;
40,301✔
2558
        }
2559

2560
        FOREACH_ARRAY(i, context->directories[type].items, context->directories[type].n_items) {
61,365✔
2561
                _cleanup_free_ char *p = NULL, *pp = NULL;
3,710✔
2562

2563
                p = path_join(params->prefix[type], i->path);
3,710✔
2564
                if (!p) {
3,710✔
2565
                        r = -ENOMEM;
×
2566
                        goto fail;
×
2567
                }
2568

2569
                r = mkdir_parents_label(p, 0755);
3,710✔
2570
                if (r < 0)
3,710✔
2571
                        goto fail;
×
2572

2573
                if (IN_SET(type, EXEC_DIRECTORY_STATE, EXEC_DIRECTORY_LOGS) && params->runtime_scope == RUNTIME_SCOPE_USER) {
3,710✔
2574

2575
                        /* If we are in user mode, and a configuration directory exists but a state directory
2576
                         * doesn't exist, then we likely are upgrading from an older systemd version that
2577
                         * didn't know the more recent addition to the xdg-basedir spec: the $XDG_STATE_HOME
2578
                         * directory. In older systemd versions EXEC_DIRECTORY_STATE was aliased to
2579
                         * EXEC_DIRECTORY_CONFIGURATION, with the advent of $XDG_STATE_HOME it is now
2580
                         * separated. If a service has both dirs configured but only the configuration dir
2581
                         * exists and the state dir does not, we assume we are looking at an update
2582
                         * situation. Hence, create a compatibility symlink, so that all expectations are
2583
                         * met.
2584
                         *
2585
                         * (We also do something similar with the log directory, which still doesn't exist in
2586
                         * the xdg basedir spec. We'll make it a subdir of the state dir.) */
2587

2588
                        /* this assumes the state dir is always created before the configuration dir */
2589
                        assert_cc(EXEC_DIRECTORY_STATE < EXEC_DIRECTORY_LOGS);
7✔
2590
                        assert_cc(EXEC_DIRECTORY_LOGS < EXEC_DIRECTORY_CONFIGURATION);
7✔
2591

2592
                        r = access_nofollow(p, F_OK);
7✔
2593
                        if (r == -ENOENT) {
7✔
2594
                                _cleanup_free_ char *q = NULL;
3✔
2595

2596
                                /* OK, we know that the state dir does not exist. Let's see if the dir exists
2597
                                 * under the configuration hierarchy. */
2598

2599
                                if (type == EXEC_DIRECTORY_STATE)
3✔
2600
                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], i->path);
3✔
2601
                                else if (type == EXEC_DIRECTORY_LOGS)
×
2602
                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], "log", i->path);
×
2603
                                else
2604
                                        assert_not_reached();
×
2605
                                if (!q) {
3✔
2606
                                        r = -ENOMEM;
×
2607
                                        goto fail;
×
2608
                                }
2609

2610
                                r = access_nofollow(q, F_OK);
3✔
2611
                                if (r >= 0) {
3✔
2612
                                        /* It does exist! This hence looks like an update. Symlink the
2613
                                         * configuration directory into the state directory. */
2614

2615
                                        r = symlink_idempotent(q, p, /* make_relative= */ true);
1✔
2616
                                        if (r < 0)
1✔
2617
                                                goto fail;
×
2618

2619
                                        log_notice("Unit state directory %s missing but matching configuration directory %s exists, assuming update from systemd 253 or older, creating compatibility symlink.", p, q);
1✔
2620
                                        continue;
1✔
2621
                                } else if (r != -ENOENT)
2✔
2622
                                        log_warning_errno(r, "Unable to detect whether unit configuration directory '%s' exists, assuming not: %m", q);
2✔
2623

2624
                        } else if (r < 0)
4✔
2625
                                log_warning_errno(r, "Unable to detect whether unit state directory '%s' is missing, assuming it is: %m", p);
×
2626
                }
2627

2628
                if (exec_directory_is_private(context, type)) {
3,709✔
2629
                        /* So, here's one extra complication when dealing with DynamicUser=1 units. In that
2630
                         * case we want to avoid leaving a directory around fully accessible that is owned by
2631
                         * a dynamic user whose UID is later on reused. To lock this down we use the same
2632
                         * trick used by container managers to prohibit host users to get access to files of
2633
                         * the same UID in containers: we place everything inside a directory that has an
2634
                         * access mode of 0700 and is owned root:root, so that it acts as security boundary
2635
                         * for unprivileged host code. We then use fs namespacing to make this directory
2636
                         * permeable for the service itself.
2637
                         *
2638
                         * Specifically: for a service which wants a special directory "foo/" we first create
2639
                         * a directory "private/" with access mode 0700 owned by root:root. Then we place
2640
                         * "foo" inside of that directory (i.e. "private/foo/"), and make "foo" a symlink to
2641
                         * "private/foo". This way, privileged host users can access "foo/" as usual, but
2642
                         * unprivileged host users can't look into it. Inside of the namespace of the unit
2643
                         * "private/" is replaced by a more liberally accessible tmpfs, into which the host's
2644
                         * "private/foo/" is mounted under the same name, thus disabling the access boundary
2645
                         * for the service and making sure it only gets access to the dirs it needs but no
2646
                         * others. Tricky? Yes, absolutely, but it works!
2647
                         *
2648
                         * Note that we don't do this for EXEC_DIRECTORY_CONFIGURATION as that's assumed not
2649
                         * to be owned by the service itself.
2650
                         *
2651
                         * Also, note that we don't do this for EXEC_DIRECTORY_RUNTIME as that's often used
2652
                         * for sharing files or sockets with other services. */
2653

2654
                        pp = path_join(params->prefix[type], "private");
13✔
2655
                        if (!pp) {
13✔
2656
                                r = -ENOMEM;
×
2657
                                goto fail;
×
2658
                        }
2659

2660
                        /* First set up private root if it doesn't exist yet, with access mode 0700 and owned by root:root */
2661
                        r = mkdir_safe_label(pp, 0700, 0, 0, MKDIR_WARN_MODE);
13✔
2662
                        if (r < 0)
13✔
2663
                                goto fail;
×
2664

2665
                        if (!path_extend(&pp, i->path)) {
13✔
2666
                                r = -ENOMEM;
×
2667
                                goto fail;
×
2668
                        }
2669

2670
                        /* Create all directories between the configured directory and this private root, and mark them 0755 */
2671
                        r = mkdir_parents_label(pp, 0755);
13✔
2672
                        if (r < 0)
13✔
2673
                                goto fail;
×
2674

2675
                        if (is_dir(p, false) > 0 &&
13✔
2676
                            (access_nofollow(pp, F_OK) == -ENOENT)) {
×
2677

2678
                                /* Hmm, the private directory doesn't exist yet, but the normal one exists? If so, move
2679
                                 * it over. Most likely the service has been upgraded from one that didn't use
2680
                                 * DynamicUser=1, to one that does. */
2681

2682
                                log_info("Found pre-existing public %s= directory %s, migrating to %s.\n"
×
2683
                                         "Apparently, service previously had DynamicUser= turned off, and has now turned it on.",
2684
                                         exec_directory_type_to_string(type), p, pp);
2685

2686
                                r = RET_NERRNO(rename(p, pp));
×
2687
                                if (r < 0)
×
2688
                                        goto fail;
×
2689
                        } else {
2690
                                /* Otherwise, create the actual directory for the service */
2691

2692
                                r = mkdir_label(pp, context->directories[type].mode);
13✔
2693
                                if (r < 0 && r != -EEXIST)
13✔
2694
                                        goto fail;
×
2695
                        }
2696

2697
                        if (!FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE)) {
13✔
2698
                                /* And link it up from the original place.
2699
                                 * Notes
2700
                                 * 1) If a mount namespace is going to be used, then this symlink remains on
2701
                                 *    the host, and a new one for the child namespace will be created later.
2702
                                 * 2) It is not necessary to create this symlink when one of its parent
2703
                                 *    directories is specified and already created. E.g.
2704
                                 *        StateDirectory=foo foo/bar
2705
                                 *    In that case, the inode points to pp and p for "foo/bar" are the same:
2706
                                 *        pp = "/var/lib/private/foo/bar"
2707
                                 *        p = "/var/lib/foo/bar"
2708
                                 *    and, /var/lib/foo is a symlink to /var/lib/private/foo. So, not only
2709
                                 *    we do not need to create the symlink, but we cannot create the symlink.
2710
                                 *    See issue #24783. */
2711
                                r = symlink_idempotent(pp, p, true);
13✔
2712
                                if (r < 0)
13✔
2713
                                        goto fail;
×
2714
                        }
2715

2716
                } else {
2717
                        _cleanup_free_ char *target = NULL;
3,696✔
2718

2719
                        if (EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type) &&
7,352✔
2720
                            readlink_and_make_absolute(p, &target) >= 0) {
3,656✔
2721
                                _cleanup_free_ char *q = NULL, *q_resolved = NULL, *target_resolved = NULL;
11✔
2722

2723
                                /* This already exists and is a symlink? Interesting. Maybe it's one created
2724
                                 * by DynamicUser=1 (see above)?
2725
                                 *
2726
                                 * We do this for all directory types except for ConfigurationDirectory=,
2727
                                 * since they all support the private/ symlink logic at least in some
2728
                                 * configurations, see above. */
2729

2730
                                r = chase(target, NULL, 0, &target_resolved, NULL);
11✔
2731
                                if (r < 0)
11✔
2732
                                        goto fail;
×
2733

2734
                                q = path_join(params->prefix[type], "private", i->path);
11✔
2735
                                if (!q) {
11✔
2736
                                        r = -ENOMEM;
×
2737
                                        goto fail;
×
2738
                                }
2739

2740
                                /* /var/lib or friends may be symlinks. So, let's chase them also. */
2741
                                r = chase(q, NULL, CHASE_NONEXISTENT, &q_resolved, NULL);
11✔
2742
                                if (r < 0)
11✔
2743
                                        goto fail;
×
2744

2745
                                if (path_equal(q_resolved, target_resolved)) {
11✔
2746

2747
                                        /* Hmm, apparently DynamicUser= was once turned on for this service,
2748
                                         * but is no longer. Let's move the directory back up. */
2749

2750
                                        log_info("Found pre-existing private %s= directory %s, migrating to %s.\n"
8✔
2751
                                                 "Apparently, service previously had DynamicUser= turned on, and has now turned it off.",
2752
                                                 exec_directory_type_to_string(type), q, p);
2753

2754
                                        r = RET_NERRNO(unlink(p));
8✔
2755
                                        if (r < 0)
×
2756
                                                goto fail;
×
2757

2758
                                        r = RET_NERRNO(rename(q, p));
11✔
2759
                                        if (r < 0)
×
2760
                                                goto fail;
×
2761
                                }
2762
                        }
2763

2764
                        r = mkdir_label(p, context->directories[type].mode);
3,696✔
2765
                        if (r < 0) {
3,696✔
2766
                                if (r != -EEXIST)
2,639✔
2767
                                        goto fail;
×
2768

2769
                                if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type)) {
2,639✔
2770
                                        struct stat st;
27✔
2771

2772
                                        /* Don't change the owner/access mode of the configuration directory,
2773
                                         * as in the common case it is not written to by a service, and shall
2774
                                         * not be writable. */
2775

2776
                                        r = RET_NERRNO(stat(p, &st));
27✔
2777
                                        if (r < 0)
×
2778
                                                goto fail;
×
2779

2780
                                        /* Still complain if the access mode doesn't match */
2781
                                        if (((st.st_mode ^ context->directories[type].mode) & 07777) != 0)
27✔
2782
                                                log_warning("%s \'%s\' already exists but the mode is different. "
×
2783
                                                            "(File system: %o %sMode: %o)",
2784
                                                            exec_directory_type_to_string(type), i->path,
2785
                                                            st.st_mode & 07777, exec_directory_type_to_string(type), context->directories[type].mode & 07777);
2786

2787
                                        continue;
27✔
2788
                                }
2789
                        }
2790
                }
2791

2792
                /* Lock down the access mode (we use chmod_and_chown() to make this idempotent. We don't
2793
                 * specify UID/GID here, so that path_chown_recursive() can optimize things depending on the
2794
                 * current UID/GID ownership.) */
2795
                const char *target_dir = pp ?: p;
3,682✔
2796
                r = chmod_and_chown(target_dir, context->directories[type].mode, UID_INVALID, GID_INVALID);
3,682✔
2797
                if (r < 0)
3,682✔
2798
                        goto fail;
×
2799

2800
                /* Skip the rest (which deals with ownership) in user mode, since ownership changes are not
2801
                 * available to user code anyway */
2802
                if (params->runtime_scope != RUNTIME_SCOPE_SYSTEM)
3,682✔
2803
                        continue;
9✔
2804

2805
                int idmapping_supported = is_idmapping_supported(target_dir);
3,673✔
2806
                if (idmapping_supported < 0) {
3,673✔
2807
                        r = log_debug_errno(idmapping_supported, "Unable to determine if ID mapping is supported on mount '%s': %m", target_dir);
×
2808
                        goto fail;
×
2809
                }
2810

2811
                log_debug("ID-mapping is%ssupported for exec directory %s", idmapping_supported ? " " : " not ", target_dir);
3,679✔
2812

2813
                /* Change the ownership of the whole tree, if necessary. When dynamic users are used we
2814
                 * drop the suid/sgid bits, since we really don't want SUID/SGID files for dynamic UID/GID
2815
                 * assignments to exist. */
2816
                uid_t chown_uid = uid;
3,673✔
2817
                gid_t chown_gid = gid;
3,673✔
2818
                bool do_chown = false;
3,673✔
2819

2820
                if (uid == 0 || gid == 0 || !idmapping_supported) {
3,673✔
2821
                        do_chown = true;
1,428✔
2822
                        i->idmapped = false;
1,428✔
2823
                } else {
2824
                        /* Use 'nobody' uid/gid for exec directories if ID-mapping is supported. For backward compatibility,
2825
                         * continue doing chmod/chown if the directory was chmod/chowned before (if uid/gid is not 'nobody') */
2826
                        struct stat st;
2,245✔
2827
                        r = RET_NERRNO(stat(target_dir, &st));
2,245✔
2828
                        if (r < 0)
×
2829
                                goto fail;
×
2830

2831
                        if (st.st_uid == UID_NOBODY && st.st_gid == GID_NOBODY) {
2,245✔
2832
                                do_chown = false;
7✔
2833
                                i->idmapped = true;
7✔
2834
                       } else if (exec_directory_is_private(context, type) && st.st_uid == 0 && st.st_gid == 0) {
2,238✔
2835
                                chown_uid = UID_NOBODY;
6✔
2836
                                chown_gid = GID_NOBODY;
6✔
2837
                                do_chown = true;
6✔
2838
                                i->idmapped = true;
6✔
2839
                        } else {
2840
                                do_chown = true;
2,232✔
2841
                                i->idmapped = false;
2,232✔
2842
                        }
2843
                }
2844

2845
                if (do_chown) {
3,673✔
2846
                        r = path_chown_recursive(target_dir, chown_uid, chown_gid, context->dynamic_user ? 01777 : 07777, AT_SYMLINK_FOLLOW);
7,323✔
2847
                        if (r < 0)
3,666✔
2848
                                goto fail;
1✔
2849
                }
2850
        }
2851

2852
        /* If we are not going to run in a namespace, set up the symlinks - otherwise
2853
         * they are set up later, to allow configuring empty var/run/etc. */
2854
        if (!needs_mount_namespace)
57,655✔
2855
                FOREACH_ARRAY(i, context->directories[type].items, context->directories[type].n_items) {
46,085✔
2856
                        r = create_many_symlinks(params->prefix[type], i->path, i->symlinks);
1,530✔
2857
                        if (r < 0)
1,530✔
2858
                                goto fail;
×
2859
                }
2860

2861
        return 0;
2862

2863
fail:
1✔
2864
        *exit_status = exit_status_table[type];
1✔
2865
        return r;
1✔
2866
}
2867

2868
#if ENABLE_SMACK
2869
static int setup_smack(
×
2870
                const ExecContext *context,
2871
                const ExecParameters *params,
2872
                int executable_fd) {
2873
        int r;
×
2874

2875
        assert(context);
×
2876
        assert(params);
×
2877
        assert(executable_fd >= 0);
×
2878

2879
        if (context->smack_process_label) {
×
2880
                r = mac_smack_apply_pid(0, context->smack_process_label);
×
2881
                if (r < 0)
×
2882
                        return r;
×
2883
        } else if (params->fallback_smack_process_label) {
×
2884
                _cleanup_free_ char *exec_label = NULL;
×
2885

2886
                r = mac_smack_read_fd(executable_fd, SMACK_ATTR_EXEC, &exec_label);
×
2887
                if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
×
2888
                        return r;
2889

2890
                r = mac_smack_apply_pid(0, exec_label ?: params->fallback_smack_process_label);
×
2891
                if (r < 0)
×
2892
                        return r;
2893
        }
2894

2895
        return 0;
2896
}
2897
#endif
2898

2899
static int compile_bind_mounts(
1,999✔
2900
                const ExecContext *context,
2901
                const ExecParameters *params,
2902
                uid_t exec_directory_uid, /* only used for id-mapped mounts Exec directories */
2903
                gid_t exec_directory_gid, /* only used for id-mapped mounts Exec directories */
2904
                BindMount **ret_bind_mounts,
2905
                size_t *ret_n_bind_mounts,
2906
                char ***ret_empty_directories) {
2907

2908
        _cleanup_strv_free_ char **empty_directories = NULL;
1,999✔
2909
        BindMount *bind_mounts = NULL;
1,999✔
2910
        size_t n, h = 0;
1,999✔
2911
        int r;
1,999✔
2912

2913
        assert(context);
1,999✔
2914
        assert(params);
1,999✔
2915
        assert(ret_bind_mounts);
1,999✔
2916
        assert(ret_n_bind_mounts);
1,999✔
2917
        assert(ret_empty_directories);
1,999✔
2918

2919
        CLEANUP_ARRAY(bind_mounts, h, bind_mount_free_many);
1,999✔
2920

2921
        n = context->n_bind_mounts;
1,999✔
2922
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
11,994✔
2923
                if (!params->prefix[t])
9,995✔
2924
                        continue;
×
2925

2926
                FOREACH_ARRAY(i, context->directories[t].items, context->directories[t].n_items)
11,583✔
2927
                        n += !FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE) || FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY);
1,588✔
2928
        }
2929

2930
        if (n <= 0) {
1,999✔
2931
                *ret_bind_mounts = NULL;
1,075✔
2932
                *ret_n_bind_mounts = 0;
1,075✔
2933
                *ret_empty_directories = NULL;
1,075✔
2934
                return 0;
1,075✔
2935
        }
2936

2937
        bind_mounts = new(BindMount, n);
924✔
2938
        if (!bind_mounts)
924✔
2939
                return -ENOMEM;
2940

2941
        FOREACH_ARRAY(item, context->bind_mounts, context->n_bind_mounts) {
946✔
2942
                r = bind_mount_add(&bind_mounts, &h, item);
22✔
2943
                if (r < 0)
22✔
2944
                        return r;
2945
        }
2946

2947
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
5,544✔
2948
                if (!params->prefix[t])
4,620✔
2949
                        continue;
×
2950

2951
                if (context->directories[t].n_items == 0)
4,620✔
2952
                        continue;
3,488✔
2953

2954
                if (exec_directory_is_private(context, t) &&
1,145✔
2955
                    !exec_context_with_rootfs(context)) {
13✔
2956
                        char *private_root;
13✔
2957

2958
                        /* So this is for a dynamic user, and we need to make sure the process can access its own
2959
                         * directory. For that we overmount the usually inaccessible "private" subdirectory with a
2960
                         * tmpfs that makes it accessible and is empty except for the submounts we do this for. */
2961

2962
                        private_root = path_join(params->prefix[t], "private");
13✔
2963
                        if (!private_root)
13✔
2964
                                return -ENOMEM;
2965

2966
                        r = strv_consume(&empty_directories, private_root);
13✔
2967
                        if (r < 0)
13✔
2968
                                return r;
2969
                }
2970

2971
                FOREACH_ARRAY(i, context->directories[t].items, context->directories[t].n_items) {
2,720✔
2972
                        _cleanup_free_ char *s = NULL, *d = NULL;
1,588✔
2973

2974
                        /* When one of the parent directories is in the list, we cannot create the symlink
2975
                         * for the child directory. See also the comments in setup_exec_directory().
2976
                         * But if it needs to be read only, then we have to create a bind mount anyway to
2977
                         * make it so. */
2978
                        if (FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE) && !FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY))
1,588✔
2979
                                continue;
×
2980

2981
                        if (exec_directory_is_private(context, t))
1,588✔
2982
                                s = path_join(params->prefix[t], "private", i->path);
13✔
2983
                        else
2984
                                s = path_join(params->prefix[t], i->path);
1,575✔
2985
                        if (!s)
1,588✔
2986
                                return -ENOMEM;
2987

2988
                        if (exec_directory_is_private(context, t) &&
1,601✔
2989
                            exec_context_with_rootfs(context))
13✔
2990
                                /* When RootDirectory= or RootImage= are set, then the symbolic link to the private
2991
                                 * directory is not created on the root directory. So, let's bind-mount the directory
2992
                                 * on the 'non-private' place. */
2993
                                d = path_join(params->prefix[t], i->path);
×
2994
                        else
2995
                                d = strdup(s);
1,588✔
2996
                        if (!d)
1,588✔
2997
                                return -ENOMEM;
2998

2999
                        bind_mounts[h++] = (BindMount) {
1,588✔
3000
                                .source = TAKE_PTR(s),
1,588✔
3001
                                .destination = TAKE_PTR(d),
1,588✔
3002
                                .nosuid = context->dynamic_user, /* don't allow suid/sgid when DynamicUser= is on */
1,588✔
3003
                                .recursive = true,
3004
                                .read_only = FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY),
1,588✔
3005
                                .idmapped = i->idmapped,
1,588✔
3006
                                .uid = exec_directory_uid,
3007
                                .gid = exec_directory_gid,
3008
                        };
3009
                }
3010
        }
3011

3012
        assert(h == n);
924✔
3013

3014
        *ret_bind_mounts = TAKE_PTR(bind_mounts);
924✔
3015
        *ret_n_bind_mounts = n;
924✔
3016
        *ret_empty_directories = TAKE_PTR(empty_directories);
924✔
3017

3018
        return (int) n;
924✔
3019
}
3020

3021
/* ret_symlinks will contain a list of pairs src:dest that describes
3022
 * the symlinks to create later on. For example, the symlinks needed
3023
 * to safely give private directories to DynamicUser=1 users. */
3024
static int compile_symlinks(
1,999✔
3025
                const ExecContext *context,
3026
                const ExecParameters *params,
3027
                bool setup_os_release_symlink,
3028
                char ***ret_symlinks) {
3029

3030
        _cleanup_strv_free_ char **symlinks = NULL;
1,999✔
3031
        int r;
1,999✔
3032

3033
        assert(context);
1,999✔
3034
        assert(params);
1,999✔
3035
        assert(ret_symlinks);
1,999✔
3036

3037
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++)
11,994✔
3038
                FOREACH_ARRAY(i, context->directories[dt].items, context->directories[dt].n_items) {
11,583✔
3039
                        _cleanup_free_ char *private_path = NULL, *path = NULL;
1,575✔
3040

3041
                        STRV_FOREACH(symlink, i->symlinks) {
1,714✔
3042
                                _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;
126✔
3043

3044
                                src_abs = path_join(params->prefix[dt], i->path);
126✔
3045
                                dst_abs = path_join(params->prefix[dt], *symlink);
126✔
3046
                                if (!src_abs || !dst_abs)
126✔
3047
                                        return -ENOMEM;
3048

3049
                                r = strv_consume_pair(&symlinks, TAKE_PTR(src_abs), TAKE_PTR(dst_abs));
126✔
3050
                                if (r < 0)
126✔
3051
                                        return r;
3052
                        }
3053

3054
                        if (!exec_directory_is_private(context, dt) ||
1,601✔
3055
                            exec_context_with_rootfs(context) ||
13✔
3056
                            FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE))
13✔
3057
                                continue;
1,575✔
3058

3059
                        private_path = path_join(params->prefix[dt], "private", i->path);
13✔
3060
                        if (!private_path)
13✔
3061
                                return -ENOMEM;
3062

3063
                        path = path_join(params->prefix[dt], i->path);
13✔
3064
                        if (!path)
13✔
3065
                                return -ENOMEM;
3066

3067
                        r = strv_consume_pair(&symlinks, TAKE_PTR(private_path), TAKE_PTR(path));
13✔
3068
                        if (r < 0)
13✔
3069
                                return r;
3070
                }
3071

3072
        /* We make the host's os-release available via a symlink, so that we can copy it atomically
3073
         * and readers will never get a half-written version. Note that, while the paths specified here are
3074
         * absolute, when they are processed in namespace.c they will be made relative automatically, i.e.:
3075
         * 'os-release -> .os-release-stage/os-release' is what will be created. */
3076
        if (setup_os_release_symlink) {
1,999✔
3077
                r = strv_extend_many(
7✔
3078
                                &symlinks,
3079
                                "/run/host/.os-release-stage/os-release",
3080
                                "/run/host/os-release");
3081
                if (r < 0)
7✔
3082
                        return r;
3083
        }
3084

3085
        *ret_symlinks = TAKE_PTR(symlinks);
1,999✔
3086

3087
        return 0;
1,999✔
3088
}
3089

3090
static bool insist_on_sandboxing(
×
3091
                const ExecContext *context,
3092
                const char *root_dir,
3093
                const char *root_image,
3094
                const BindMount *bind_mounts,
3095
                size_t n_bind_mounts) {
3096

3097
        assert(context);
×
3098
        assert(n_bind_mounts == 0 || bind_mounts);
×
3099

3100
        /* Checks whether we need to insist on fs namespacing. i.e. whether we have settings configured that
3101
         * would alter the view on the file system beyond making things read-only or invisible, i.e. would
3102
         * rearrange stuff in a way we cannot ignore gracefully. */
3103

3104
        if (context->n_temporary_filesystems > 0)
×
3105
                return true;
3106

3107
        if (root_dir || root_image)
×
3108
                return true;
3109

3110
        if (context->n_mount_images > 0)
×
3111
                return true;
3112

3113
        if (context->dynamic_user)
×
3114
                return true;
3115

3116
        if (context->n_extension_images > 0 || !strv_isempty(context->extension_directories))
×
3117
                return true;
3118

3119
        /* If there are any bind mounts set that don't map back onto themselves, fs namespacing becomes
3120
         * essential. */
3121
        FOREACH_ARRAY(i, bind_mounts, n_bind_mounts)
×
3122
                if (!path_equal(i->source, i->destination))
×
3123
                        return true;
3124

3125
        if (context->log_namespace)
×
3126
                return true;
×
3127

3128
        return false;
3129
}
3130

3131
static int setup_ephemeral(
1,999✔
3132
                const ExecContext *context,
3133
                ExecRuntime *runtime,
3134
                char **root_image,            /* both input and output! modified if ephemeral logic enabled */
3135
                char **root_directory,        /* ditto */
3136
                char **reterr_path) {
3137

3138
        _cleanup_close_ int fd = -EBADF;
1,999✔
3139
        _cleanup_free_ char *new_root = NULL;
1,999✔
3140
        int r;
1,999✔
3141

3142
        assert(context);
1,999✔
3143
        assert(runtime);
1,999✔
3144
        assert(root_image);
1,999✔
3145
        assert(root_directory);
1,999✔
3146

3147
        if (!*root_image && !*root_directory)
1,999✔
3148
                return 0;
3149

3150
        if (!runtime->ephemeral_copy)
8✔
3151
                return 0;
3152

3153
        assert(runtime->ephemeral_storage_socket[0] >= 0);
×
3154
        assert(runtime->ephemeral_storage_socket[1] >= 0);
×
3155

3156
        new_root = strdup(runtime->ephemeral_copy);
×
3157
        if (!new_root)
×
3158
                return log_oom_debug();
×
3159

3160
        r = posix_lock(runtime->ephemeral_storage_socket[0], LOCK_EX);
×
3161
        if (r < 0)
×
3162
                return log_debug_errno(r, "Failed to lock ephemeral storage socket: %m");
×
3163

3164
        CLEANUP_POSIX_UNLOCK(runtime->ephemeral_storage_socket[0]);
×
3165

3166
        fd = receive_one_fd(runtime->ephemeral_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
×
3167
        if (fd >= 0)
×
3168
                /* We got an fd! That means ephemeral has already been set up, so nothing to do here. */
3169
                return 0;
3170
        if (fd != -EAGAIN)
×
3171
                return log_debug_errno(fd, "Failed to receive file descriptor queued on ephemeral storage socket: %m");
×
3172

3173
        if (*root_image) {
×
3174
                log_debug("Making ephemeral copy of %s to %s", *root_image, new_root);
×
3175

3176
                fd = copy_file(*root_image, new_root, O_EXCL, 0600,
×
3177
                               COPY_LOCK_BSD|COPY_REFLINK|COPY_CRTIME|COPY_NOCOW_AFTER);
3178
                if (fd < 0) {
×
3179
                        *reterr_path = strdup(*root_image);
×
3180
                        return log_debug_errno(fd, "Failed to copy image %s to %s: %m",
×
3181
                                               *root_image, new_root);
3182
                }
3183
        } else {
3184
                assert(*root_directory);
×
3185

3186
                log_debug("Making ephemeral snapshot of %s to %s", *root_directory, new_root);
×
3187

3188
                fd = btrfs_subvol_snapshot_at(
×
3189
                                AT_FDCWD, *root_directory,
3190
                                AT_FDCWD, new_root,
3191
                                BTRFS_SNAPSHOT_FALLBACK_COPY |
3192
                                BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
3193
                                BTRFS_SNAPSHOT_RECURSIVE |
3194
                                BTRFS_SNAPSHOT_LOCK_BSD);
3195
                if (fd < 0) {
×
3196
                        *reterr_path = strdup(*root_directory);
×
3197
                        return log_debug_errno(fd, "Failed to snapshot directory %s to %s: %m",
×
3198
                                               *root_directory, new_root);
3199
                }
3200
        }
3201

3202
        r = send_one_fd(runtime->ephemeral_storage_socket[1], fd, MSG_DONTWAIT);
×
3203
        if (r < 0)
×
3204
                return log_debug_errno(r, "Failed to queue file descriptor on ephemeral storage socket: %m");
×
3205

3206
        if (*root_image)
×
3207
                free_and_replace(*root_image, new_root);
×
3208
        else {
3209
                assert(*root_directory);
×
3210
                free_and_replace(*root_directory, new_root);
×
3211
        }
3212

3213
        return 1;
3214
}
3215

3216
static int verity_settings_prepare(
7✔
3217
                VeritySettings *verity,
3218
                const char *root_image,
3219
                const void *root_hash,
3220
                size_t root_hash_size,
3221
                const char *root_hash_path,
3222
                const void *root_hash_sig,
3223
                size_t root_hash_sig_size,
3224
                const char *root_hash_sig_path,
3225
                const char *verity_data_path) {
3226

3227
        int r;
7✔
3228

3229
        assert(verity);
7✔
3230

3231
        if (root_hash) {
7✔
3232
                void *d;
4✔
3233

3234
                d = memdup(root_hash, root_hash_size);
4✔
3235
                if (!d)
4✔
3236
                        return -ENOMEM;
7✔
3237

3238
                free_and_replace(verity->root_hash, d);
4✔
3239
                verity->root_hash_size = root_hash_size;
4✔
3240
                verity->designator = PARTITION_ROOT;
4✔
3241
        }
3242

3243
        if (root_hash_sig) {
7✔
3244
                void *d;
×
3245

3246
                d = memdup(root_hash_sig, root_hash_sig_size);
×
3247
                if (!d)
×
3248
                        return -ENOMEM;
7✔
3249

3250
                free_and_replace(verity->root_hash_sig, d);
×
3251
                verity->root_hash_sig_size = root_hash_sig_size;
×
3252
                verity->designator = PARTITION_ROOT;
×
3253
        }
3254

3255
        if (verity_data_path) {
7✔
3256
                r = free_and_strdup(&verity->data_path, verity_data_path);
×
3257
                if (r < 0)
×
3258
                        return r;
3259
        }
3260

3261
        r = verity_settings_load(
7✔
3262
                        verity,
3263
                        root_image,
3264
                        root_hash_path,
3265
                        root_hash_sig_path);
3266
        if (r < 0)
7✔
3267
                return log_debug_errno(r, "Failed to load root hash: %m");
×
3268

3269
        return 0;
3270
}
3271

3272
static int pick_versions(
2,001✔
3273
                const ExecContext *context,
3274
                const ExecParameters *params,
3275
                char **ret_root_image,
3276
                char **ret_root_directory,
3277
                char **reterr_path) {
3278

3279
        int r;
2,001✔
3280

3281
        assert(context);
2,001✔
3282
        assert(params);
2,001✔
3283
        assert(ret_root_image);
2,001✔
3284
        assert(ret_root_directory);
2,001✔
3285

3286
        if (context->root_image) {
2,001✔
3287
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
8✔
3288

3289
                r = path_pick(/* toplevel_path= */ NULL,
16✔
3290
                              /* toplevel_fd= */ AT_FDCWD,
3291
                              context->root_image,
8✔
3292
                              &pick_filter_image_raw,
3293
                              PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3294
                              &result);
3295
                if (r < 0) {
8✔
3296
                        *reterr_path = strdup(context->root_image);
1✔
3297
                        return r;
1✔
3298
                }
3299

3300
                if (!result.path) {
7✔
3301
                        *reterr_path = strdup(context->root_image);
×
3302
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_image);
×
3303
                }
3304

3305
                *ret_root_image = TAKE_PTR(result.path);
7✔
3306
                *ret_root_directory = NULL;
7✔
3307
                return r;
7✔
3308
        }
3309

3310
        if (context->root_directory) {
1,993✔
3311
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
2✔
3312

3313
                r = path_pick(/* toplevel_path= */ NULL,
4✔
3314
                              /* toplevel_fd= */ AT_FDCWD,
3315
                              context->root_directory,
2✔
3316
                              &pick_filter_image_dir,
3317
                              PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3318
                              &result);
3319
                if (r < 0) {
2✔
3320
                        *reterr_path = strdup(context->root_directory);
×
3321
                        return r;
×
3322
                }
3323

3324
                if (!result.path) {
2✔
3325
                        *reterr_path = strdup(context->root_directory);
1✔
3326
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_directory);
1✔
3327
                }
3328

3329
                *ret_root_image = NULL;
1✔
3330
                *ret_root_directory = TAKE_PTR(result.path);
1✔
3331
                return r;
1✔
3332
        }
3333

3334
        *ret_root_image = *ret_root_directory = NULL;
1,991✔
3335
        return 0;
1,991✔
3336
}
3337

3338
static int apply_mount_namespace(
2,001✔
3339
                ExecCommandFlags command_flags,
3340
                const ExecContext *context,
3341
                const ExecParameters *params,
3342
                ExecRuntime *runtime,
3343
                const char *memory_pressure_path,
3344
                bool needs_sandboxing,
3345
                char **reterr_path,
3346
                uid_t exec_directory_uid,
3347
                gid_t exec_directory_gid) {
3348

3349
        _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
2,001✔
3350
        _cleanup_strv_free_ char **empty_directories = NULL, **symlinks = NULL,
2,001✔
3351
                        **read_write_paths_cleanup = NULL;
×
3352
        _cleanup_free_ char *creds_path = NULL, *incoming_dir = NULL, *propagate_dir = NULL,
×
3353
                *private_namespace_dir = NULL, *host_os_release_stage = NULL, *root_image = NULL, *root_dir = NULL;
2,001✔
3354
        const char *tmp_dir = NULL, *var_tmp_dir = NULL;
2,001✔
3355
        char **read_write_paths;
2,001✔
3356
        bool setup_os_release_symlink;
2,001✔
3357
        BindMount *bind_mounts = NULL;
2,001✔
3358
        size_t n_bind_mounts = 0;
2,001✔
3359
        int r;
2,001✔
3360

3361
        assert(context);
2,001✔
3362
        assert(params);
2,001✔
3363
        assert(runtime);
2,001✔
3364

3365
        CLEANUP_ARRAY(bind_mounts, n_bind_mounts, bind_mount_free_many);
2,001✔
3366

3367
        if (params->flags & EXEC_APPLY_CHROOT) {
2,001✔
3368
                r = pick_versions(
2,001✔
3369
                                context,
3370
                                params,
3371
                                &root_image,
3372
                                &root_dir,
3373
                                reterr_path);
3374
                if (r < 0)
2,001✔
3375
                        return r;
3376

3377
                r = setup_ephemeral(
1,999✔
3378
                                context,
3379
                                runtime,
3380
                                &root_image,
3381
                                &root_dir,
3382
                                reterr_path);
3383
                if (r < 0)
1,999✔
3384
                        return r;
3385
        }
3386

3387
        r = compile_bind_mounts(context, params, exec_directory_uid, exec_directory_gid, &bind_mounts, &n_bind_mounts, &empty_directories);
1,999✔
3388
        if (r < 0)
1,999✔
3389
                return r;
3390

3391
        /* We need to make the pressure path writable even if /sys/fs/cgroups is made read-only, as the
3392
         * service will need to write to it in order to start the notifications. */
3393
        if (exec_is_cgroup_mount_read_only(context) && memory_pressure_path && !streq(memory_pressure_path, "/dev/null")) {
1,999✔
3394
                read_write_paths_cleanup = strv_copy(context->read_write_paths);
1,138✔
3395
                if (!read_write_paths_cleanup)
1,138✔
3396
                        return -ENOMEM;
3397

3398
                r = strv_extend(&read_write_paths_cleanup, memory_pressure_path);
1,138✔
3399
                if (r < 0)
1,138✔
3400
                        return r;
3401

3402
                read_write_paths = read_write_paths_cleanup;
1,138✔
3403
        } else
3404
                read_write_paths = context->read_write_paths;
861✔
3405

3406
        if (needs_sandboxing) {
1,999✔
3407
                /* The runtime struct only contains the parent of the private /tmp, which is non-accessible
3408
                 * to world users. Inside of it there's a /tmp that is sticky, and that's the one we want to
3409
                 * use here.  This does not apply when we are using /run/systemd/empty as fallback. */
3410

3411
                if (context->private_tmp == PRIVATE_TMP_CONNECTED && runtime->shared) {
1,999✔
3412
                        if (streq_ptr(runtime->shared->tmp_dir, RUN_SYSTEMD_EMPTY))
324✔
3413
                                tmp_dir = runtime->shared->tmp_dir;
3414
                        else if (runtime->shared->tmp_dir)
324✔
3415
                                tmp_dir = strjoina(runtime->shared->tmp_dir, "/tmp");
1,620✔
3416

3417
                        if (streq_ptr(runtime->shared->var_tmp_dir, RUN_SYSTEMD_EMPTY))
324✔
3418
                                var_tmp_dir = runtime->shared->var_tmp_dir;
3419
                        else if (runtime->shared->var_tmp_dir)
324✔
3420
                                var_tmp_dir = strjoina(runtime->shared->var_tmp_dir, "/tmp");
1,620✔
3421
                }
3422
        }
3423

3424
        /* Symlinks (exec dirs, os-release) are set up after other mounts, before they are made read-only. */
3425
        setup_os_release_symlink = needs_sandboxing && exec_context_get_effective_mount_apivfs(context) && (root_dir || root_image);
1,999✔
3426
        r = compile_symlinks(context, params, setup_os_release_symlink, &symlinks);
1,999✔
3427
        if (r < 0)
1,999✔
3428
                return r;
3429

3430
        if (context->mount_propagation_flag == MS_SHARED)
1,999✔
3431
                log_debug("shared mount propagation hidden by other fs namespacing unit settings: ignoring");
×
3432

3433
        r = exec_context_get_credential_directory(context, params, params->unit_id, &creds_path);
1,999✔
3434
        if (r < 0)
1,999✔
3435
                return r;
3436

3437
        if (params->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
1,999✔
3438
                propagate_dir = path_join("/run/systemd/propagate/", params->unit_id);
1,972✔
3439
                if (!propagate_dir)
1,972✔
3440
                        return -ENOMEM;
3441

3442
                incoming_dir = strdup("/run/systemd/incoming");
1,972✔
3443
                if (!incoming_dir)
1,972✔
3444
                        return -ENOMEM;
3445

3446
                private_namespace_dir = strdup("/run/systemd");
1,972✔
3447
                if (!private_namespace_dir)
1,972✔
3448
                        return -ENOMEM;
3449

3450
                /* If running under a different root filesystem, propagate the host's os-release. We make a
3451
                 * copy rather than just bind mounting it, so that it can be updated on soft-reboot. */
3452
                if (setup_os_release_symlink) {
1,972✔
3453
                        host_os_release_stage = strdup("/run/systemd/propagate/.os-release-stage");
7✔
3454
                        if (!host_os_release_stage)
7✔
3455
                                return -ENOMEM;
3456
                }
3457
        } else {
3458
                assert(params->runtime_scope == RUNTIME_SCOPE_USER);
27✔
3459

3460
                if (asprintf(&private_namespace_dir, "/run/user/" UID_FMT "/systemd", geteuid()) < 0)
27✔
3461
                        return -ENOMEM;
3462

3463
                if (setup_os_release_symlink) {
27✔
3464
                        if (asprintf(&host_os_release_stage,
×
3465
                                     "/run/user/" UID_FMT "/systemd/propagate/.os-release-stage",
3466
                                     geteuid()) < 0)
3467
                                return -ENOMEM;
3468
                }
3469
        }
3470

3471
        if (root_image) {
1,999✔
3472
                r = verity_settings_prepare(
14✔
3473
                        &verity,
3474
                        root_image,
3475
                        context->root_hash, context->root_hash_size, context->root_hash_path,
7✔
3476
                        context->root_hash_sig, context->root_hash_sig_size, context->root_hash_sig_path,
7✔
3477
                        context->root_verity);
7✔
3478
                if (r < 0)
7✔
3479
                        return r;
3480
        }
3481

3482
        NamespaceParameters parameters = {
×
3483
                .runtime_scope = params->runtime_scope,
1,999✔
3484

3485
                .root_directory = root_dir,
3486
                .root_image = root_image,
3487
                .root_image_options = context->root_image_options,
1,999✔
3488
                .root_image_policy = context->root_image_policy ?: &image_policy_service,
1,999✔
3489

3490
                .read_write_paths = read_write_paths,
3491
                .read_only_paths = needs_sandboxing ? context->read_only_paths : NULL,
1,999✔
3492
                .inaccessible_paths = needs_sandboxing ? context->inaccessible_paths : NULL,
1,999✔
3493

3494
                .exec_paths = needs_sandboxing ? context->exec_paths : NULL,
1,999✔
3495
                .no_exec_paths = needs_sandboxing ? context->no_exec_paths : NULL,
1,999✔
3496

3497
                .empty_directories = empty_directories,
3498
                .symlinks = symlinks,
3499

3500
                .bind_mounts = bind_mounts,
3501
                .n_bind_mounts = n_bind_mounts,
3502

3503
                .temporary_filesystems = context->temporary_filesystems,
1,999✔
3504
                .n_temporary_filesystems = context->n_temporary_filesystems,
1,999✔
3505

3506
                .mount_images = context->mount_images,
1,999✔
3507
                .n_mount_images = context->n_mount_images,
1,999✔
3508
                .mount_image_policy = context->mount_image_policy ?: &image_policy_service,
1,999✔
3509

3510
                .tmp_dir = tmp_dir,
3511
                .var_tmp_dir = var_tmp_dir,
3512

3513
                .creds_path = creds_path,
3514
                .log_namespace = context->log_namespace,
1,999✔
3515
                .mount_propagation_flag = context->mount_propagation_flag,
1,999✔
3516

3517
                .verity = &verity,
3518

3519
                .extension_images = context->extension_images,
1,999✔
3520
                .n_extension_images = context->n_extension_images,
1,999✔
3521
                .extension_image_policy = context->extension_image_policy ?: &image_policy_sysext,
1,999✔
3522
                .extension_directories = context->extension_directories,
1,999✔
3523

3524
                .propagate_dir = propagate_dir,
3525
                .incoming_dir = incoming_dir,
3526
                .private_namespace_dir = private_namespace_dir,
3527
                .host_notify_socket = params->notify_socket,
1,999✔
3528
                .notify_socket_path = exec_get_private_notify_socket_path(context, params, needs_sandboxing),
1,999✔
3529
                .host_os_release_stage = host_os_release_stage,
3530

3531
                /* If DynamicUser=no and RootDirectory= is set then lets pass a relaxed sandbox info,
3532
                 * otherwise enforce it, don't ignore protected paths and fail if we are enable to apply the
3533
                 * sandbox inside the mount namespace. */
3534
                .ignore_protect_paths = !needs_sandboxing && !context->dynamic_user && root_dir,
1,999✔
3535

3536
                .protect_control_groups = needs_sandboxing ? exec_get_protect_control_groups(context) : PROTECT_CONTROL_GROUPS_NO,
1,999✔
3537
                .protect_kernel_tunables = needs_sandboxing && context->protect_kernel_tunables,
1,999✔
3538
                .protect_kernel_modules = needs_sandboxing && context->protect_kernel_modules,
1,999✔
3539
                .protect_kernel_logs = needs_sandboxing && context->protect_kernel_logs,
1,999✔
3540

3541
                .private_dev = needs_sandboxing && context->private_devices,
1,999✔
3542
                .private_network = needs_sandboxing && exec_needs_network_namespace(context),
1,999✔
3543
                .private_ipc = needs_sandboxing && exec_needs_ipc_namespace(context),
1,999✔
3544
                .private_pids = needs_sandboxing && exec_needs_pid_namespace(context) ? context->private_pids : PRIVATE_PIDS_NO,
1,999✔
3545
                .private_tmp = needs_sandboxing ? context->private_tmp : PRIVATE_TMP_NO,
1,999✔
3546
                .private_var_tmp = needs_sandboxing ? context->private_var_tmp : PRIVATE_TMP_NO,
1,999✔
3547

3548
                .mount_apivfs = needs_sandboxing && exec_context_get_effective_mount_apivfs(context),
1,999✔
3549
                .bind_log_sockets = needs_sandboxing && exec_context_get_effective_bind_log_sockets(context),
1,999✔
3550

3551
                /* If NNP is on, we can turn on MS_NOSUID, since it won't have any effect anymore. */
3552
                .mount_nosuid = needs_sandboxing && context->no_new_privileges && !mac_selinux_use(),
1,999✔
3553

3554
                .protect_home = needs_sandboxing ? context->protect_home : PROTECT_HOME_NO,
1,999✔
3555
                .protect_hostname = needs_sandboxing ? context->protect_hostname : PROTECT_HOSTNAME_NO,
1,999✔
3556
                .protect_system = needs_sandboxing ? context->protect_system : PROTECT_SYSTEM_NO,
1,999✔
3557
                .protect_proc = needs_sandboxing ? context->protect_proc : PROTECT_PROC_DEFAULT,
1,999✔
3558
                .proc_subset = needs_sandboxing ? context->proc_subset : PROC_SUBSET_ALL,
1,999✔
3559
        };
3560

3561
        r = setup_namespace(&parameters, reterr_path);
1,999✔
3562
        /* If we couldn't set up the namespace this is probably due to a missing capability. setup_namespace() reports
3563
         * that with a special, recognizable error ENOANO. In this case, silently proceed, but only if exclusively
3564
         * sandboxing options were used, i.e. nothing such as RootDirectory= or BindMount= that would result in a
3565
         * completely different execution environment. */
3566
        if (r == -ENOANO) {
1,999✔
3567
                if (insist_on_sandboxing(
×
3568
                                    context,
3569
                                    root_dir, root_image,
3570
                                    bind_mounts,
3571
                                    n_bind_mounts))
3572
                        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
×
3573
                                               "Failed to set up namespace, and refusing to continue since "
3574
                                               "the selected namespacing options alter mount environment non-trivially.\n"
3575
                                               "Bind mounts: %zu, temporary filesystems: %zu, root directory: %s, root image: %s, dynamic user: %s",
3576
                                               n_bind_mounts,
3577
                                               context->n_temporary_filesystems,
3578
                                               yes_no(root_dir),
3579
                                               yes_no(root_image),
3580
                                               yes_no(context->dynamic_user));
3581

3582
                log_debug("Failed to set up namespace, assuming containerized execution and ignoring.");
×
3583
                return 0;
×
3584
        }
3585

3586
        return r;
3587
}
3588

3589
static int apply_working_directory(
9,557✔
3590
                const ExecContext *context,
3591
                const ExecParameters *params,
3592
                ExecRuntime *runtime,
3593
                const char *pwent_home,
3594
                char * const *env) {
3595

3596
        const char *wd;
9,557✔
3597
        int r;
9,557✔
3598

3599
        assert(context);
9,557✔
3600
        assert(params);
9,557✔
3601
        assert(runtime);
9,557✔
3602

3603
        if (context->working_directory_home) {
9,557✔
3604
                /* Preferably use the data from $HOME, in case it was updated by a PAM module */
3605
                wd = strv_env_get(env, "HOME");
103✔
3606
                if (!wd) {
103✔
3607
                        /* If that's not available, use the data from the struct passwd entry: */
3608
                        if (!pwent_home)
1✔
3609
                                return -ENXIO;
3610

3611
                        wd = pwent_home;
3612
                }
3613
        } else
3614
                wd = empty_to_root(context->working_directory);
9,454✔
3615

3616
        if (params->flags & EXEC_APPLY_CHROOT)
9,557✔
3617
                r = RET_NERRNO(chdir(wd));
9,557✔
3618
        else {
3619
                _cleanup_close_ int dfd = -EBADF;
×
3620

3621
                r = chase(wd,
×
3622
                          runtime->ephemeral_copy ?: context->root_directory,
×
3623
                          CHASE_PREFIX_ROOT|CHASE_AT_RESOLVE_IN_ROOT,
3624
                          /* ret_path= */ NULL,
3625
                          &dfd);
3626
                if (r >= 0)
×
3627
                        r = RET_NERRNO(fchdir(dfd));
×
3628
        }
3629
        return context->working_directory_missing_ok ? 0 : r;
9,557✔
3630
}
3631

3632
static int apply_root_directory(
9,557✔
3633
                const ExecContext *context,
3634
                const ExecParameters *params,
3635
                ExecRuntime *runtime,
3636
                const bool needs_mount_ns,
3637
                int *exit_status) {
3638

3639
        assert(context);
9,557✔
3640
        assert(params);
9,557✔
3641
        assert(runtime);
9,557✔
3642
        assert(exit_status);
9,557✔
3643

3644
        if (params->flags & EXEC_APPLY_CHROOT)
9,557✔
3645
                if (!needs_mount_ns && context->root_directory)
9,557✔
3646
                        if (chroot(runtime->ephemeral_copy ?: context->root_directory) < 0) {
×
3647
                                *exit_status = EXIT_CHROOT;
×
3648
                                return -errno;
×
3649
                        }
3650

3651
        return 0;
3652
}
3653

3654
static int setup_keyring(
9,583✔
3655
                const ExecContext *context,
3656
                const ExecParameters *p,
3657
                uid_t uid,
3658
                gid_t gid) {
3659

3660
        key_serial_t keyring;
9,583✔
3661
        int r = 0;
9,583✔
3662
        uid_t saved_uid;
9,583✔
3663
        gid_t saved_gid;
9,583✔
3664

3665
        assert(context);
9,583✔
3666
        assert(p);
9,583✔
3667

3668
        /* Let's set up a new per-service "session" kernel keyring for each system service. This has the benefit that
3669
         * each service runs with its own keyring shared among all processes of the service, but with no hook-up beyond
3670
         * that scope, and in particular no link to the per-UID keyring. If we don't do this the keyring will be
3671
         * automatically created on-demand and then linked to the per-UID keyring, by the kernel. The kernel's built-in
3672
         * on-demand behaviour is very appropriate for login users, but probably not so much for system services, where
3673
         * UIDs are not necessarily specific to a service but reused (at least in the case of UID 0). */
3674

3675
        if (context->keyring_mode == EXEC_KEYRING_INHERIT)
9,583✔
3676
                return 0;
3677

3678
        /* Acquiring a reference to the user keyring is nasty. We briefly change identity in order to get things set up
3679
         * properly by the kernel. If we don't do that then we can't create it atomically, and that sucks for parallel
3680
         * execution. This mimics what pam_keyinit does, too. Setting up session keyring, to be owned by the right user
3681
         * & group is just as nasty as acquiring a reference to the user keyring. */
3682

3683
        saved_uid = getuid();
8,616✔
3684
        saved_gid = getgid();
8,616✔
3685

3686
        if (gid_is_valid(gid) && gid != saved_gid) {
8,616✔
3687
                if (setregid(gid, -1) < 0)
1,763✔
3688
                        return log_error_errno(errno, "Failed to change GID for user keyring: %m");
×
3689
        }
3690

3691
        if (uid_is_valid(uid) && uid != saved_uid) {
8,616✔
3692
                if (setreuid(uid, -1) < 0) {
1,760✔
3693
                        r = log_error_errno(errno, "Failed to change UID for user keyring: %m");
×
3694
                        goto out;
×
3695
                }
3696
        }
3697

3698
        keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
8,616✔
3699
        if (keyring == -1) {
8,616✔
3700
                if (errno == ENOSYS)
×
3701
                        log_debug_errno(errno, "Kernel keyring not supported, ignoring.");
×
3702
                else if (ERRNO_IS_PRIVILEGE(errno))
×
3703
                        log_debug_errno(errno, "Kernel keyring access prohibited, ignoring.");
×
3704
                else if (errno == EDQUOT)
×
3705
                        log_debug_errno(errno, "Out of kernel keyrings to allocate, ignoring.");
×
3706
                else
3707
                        r = log_error_errno(errno, "Setting up kernel keyring failed: %m");
×
3708

3709
                goto out;
×
3710
        }
3711

3712
        /* When requested link the user keyring into the session keyring. */
3713
        if (context->keyring_mode == EXEC_KEYRING_SHARED) {
8,616✔
3714

3715
                if (keyctl(KEYCTL_LINK,
931✔
3716
                           KEY_SPEC_USER_KEYRING,
3717
                           KEY_SPEC_SESSION_KEYRING, 0, 0) < 0) {
3718
                        r = log_error_errno(errno, "Failed to link user keyring into session keyring: %m");
×
3719
                        goto out;
×
3720
                }
3721
        }
3722

3723
        /* Restore uid/gid back */
3724
        if (uid_is_valid(uid) && uid != saved_uid) {
8,616✔
3725
                if (setreuid(saved_uid, -1) < 0) {
1,760✔
3726
                        r = log_error_errno(errno, "Failed to change UID back for user keyring: %m");
×
3727
                        goto out;
×
3728
                }
3729
        }
3730

3731
        if (gid_is_valid(gid) && gid != saved_gid) {
8,616✔
3732
                if (setregid(saved_gid, -1) < 0)
1,763✔
3733
                        return log_error_errno(errno, "Failed to change GID back for user keyring: %m");
×
3734
        }
3735

3736
        /* Populate they keyring with the invocation ID by default, as original saved_uid. */
3737
        if (!sd_id128_is_null(p->invocation_id)) {
8,616✔
3738
                key_serial_t key;
8,616✔
3739

3740
                key = add_key("user",
17,232✔
3741
                              "invocation_id",
3742
                              &p->invocation_id,
8,616✔
3743
                              sizeof(p->invocation_id),
3744
                              KEY_SPEC_SESSION_KEYRING);
3745
                if (key == -1)
8,616✔
3746
                        log_debug_errno(errno, "Failed to add invocation ID to keyring, ignoring: %m");
×
3747
                else {
3748
                        if (keyctl(KEYCTL_SETPERM, key,
8,616✔
3749
                                   KEY_POS_VIEW|KEY_POS_READ|KEY_POS_SEARCH|
3750
                                   KEY_USR_VIEW|KEY_USR_READ|KEY_USR_SEARCH, 0, 0) < 0)
3751
                                r = log_error_errno(errno, "Failed to restrict invocation ID permission: %m");
×
3752
                }
3753
        }
3754

3755
out:
8,616✔
3756
        /* Revert back uid & gid for the last time, and exit */
3757
        /* no extra logging, as only the first already reported error matters */
3758
        if (getuid() != saved_uid)
8,616✔
3759
                (void) setreuid(saved_uid, -1);
×
3760

3761
        if (getgid() != saved_gid)
8,616✔
3762
                (void) setregid(saved_gid, -1);
×
3763

3764
        return r;
3765
}
3766

3767
static void append_socket_pair(int *array, size_t *n, const int pair[static 2]) {
34,732✔
3768
        assert(array);
34,732✔
3769
        assert(n);
34,732✔
3770
        assert(pair);
34,732✔
3771

3772
        if (pair[0] >= 0)
34,732✔
3773
                array[(*n)++] = pair[0];
190✔
3774
        if (pair[1] >= 0)
34,732✔
3775
                array[(*n)++] = pair[1];
190✔
3776
}
34,732✔
3777

3778
static int close_remaining_fds(
11,536✔
3779
                const ExecParameters *params,
3780
                const ExecRuntime *runtime,
3781
                int socket_fd,
3782
                const int *fds,
3783
                size_t n_fds) {
11,536✔
3784

3785
        size_t n_dont_close = 0;
11,536✔
3786
        int dont_close[n_fds + 17];
11,536✔
3787

3788
        assert(params);
11,536✔
3789
        assert(runtime);
11,536✔
3790

3791
        if (params->stdin_fd >= 0)
11,536✔
3792
                dont_close[n_dont_close++] = params->stdin_fd;
546✔
3793
        if (params->stdout_fd >= 0)
11,536✔
3794
                dont_close[n_dont_close++] = params->stdout_fd;
546✔
3795
        if (params->stderr_fd >= 0)
11,536✔
3796
                dont_close[n_dont_close++] = params->stderr_fd;
546✔
3797

3798
        if (socket_fd >= 0)
11,536✔
3799
                dont_close[n_dont_close++] = socket_fd;
17✔
3800
        if (n_fds > 0) {
11,536✔
3801
                memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
11,536✔
3802
                n_dont_close += n_fds;
11,536✔
3803
        }
3804

3805
        append_socket_pair(dont_close, &n_dont_close, runtime->ephemeral_storage_socket);
11,536✔
3806

3807
        if (runtime->shared) {
11,536✔
3808
                append_socket_pair(dont_close, &n_dont_close, runtime->shared->netns_storage_socket);
11,536✔
3809
                append_socket_pair(dont_close, &n_dont_close, runtime->shared->ipcns_storage_socket);
11,536✔
3810
        }
3811

3812
        if (runtime->dynamic_creds) {
11,536✔
3813
                if (runtime->dynamic_creds->user)
11,536✔
3814
                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->user->storage_socket);
62✔
3815
                if (runtime->dynamic_creds->group)
11,536✔
3816
                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->group->storage_socket);
62✔
3817
        }
3818

3819
        if (params->user_lookup_fd >= 0)
11,536✔
3820
                dont_close[n_dont_close++] = params->user_lookup_fd;
11,536✔
3821

3822
        if (params->handoff_timestamp_fd >= 0)
11,536✔
3823
                dont_close[n_dont_close++] = params->handoff_timestamp_fd;
11,536✔
3824

3825
        if (params->pidref_transport_fd >= 0)
11,536✔
3826
                dont_close[n_dont_close++] = params->pidref_transport_fd;
10,488✔
3827

3828
        assert(n_dont_close <= ELEMENTSOF(dont_close));
11,536✔
3829

3830
        return close_all_fds(dont_close, n_dont_close);
11,536✔
3831
}
3832

3833
static int send_user_lookup(
11,534✔
3834
                const char *unit_id,
3835
                int user_lookup_fd,
3836
                uid_t uid,
3837
                gid_t gid) {
3838

3839
        assert(unit_id);
11,534✔
3840

3841
        /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
3842
         * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
3843
         * specified. */
3844

3845
        if (user_lookup_fd < 0)
11,534✔
3846
                return 0;
3847

3848
        if (!uid_is_valid(uid) && !gid_is_valid(gid))
11,534✔
3849
                return 0;
3850

3851
        if (writev(user_lookup_fd,
2,677✔
3852
               (struct iovec[]) {
2,677✔
3853
                           IOVEC_MAKE(&uid, sizeof(uid)),
3854
                           IOVEC_MAKE(&gid, sizeof(gid)),
3855
                           IOVEC_MAKE_STRING(unit_id) }, 3) < 0)
2,677✔
3856
                return -errno;
×
3857

3858
        return 0;
2,677✔
3859
}
3860

3861
static int acquire_home(const ExecContext *c, const char **home, char **ret_buf) {
11,534✔
3862
        int r;
11,534✔
3863

3864
        assert(c);
11,534✔
3865
        assert(home);
11,534✔
3866
        assert(ret_buf);
11,534✔
3867

3868
        /* If WorkingDirectory=~ is set, try to acquire a usable home directory. */
3869

3870
        if (*home) /* Already acquired from get_fixed_user()? */
11,534✔
3871
                return 0;
3872

3873
        if (!c->working_directory_home)
8,924✔
3874
                return 0;
3875

3876
        if (c->dynamic_user || (c->user && is_this_me(c->user) <= 0))
×
3877
                return -EADDRNOTAVAIL;
×
3878

3879
        r = get_home_dir(ret_buf);
×
3880
        if (r < 0)
×
3881
                return r;
3882

3883
        *home = *ret_buf;
×
3884
        return 1;
×
3885
}
3886

3887
static int compile_suggested_paths(const ExecContext *c, const ExecParameters *p, char ***ret) {
62✔
3888
        _cleanup_strv_free_ char ** list = NULL;
62✔
3889
        int r;
62✔
3890

3891
        assert(c);
62✔
3892
        assert(p);
62✔
3893
        assert(ret);
62✔
3894

3895
        assert(c->dynamic_user);
62✔
3896

3897
        /* Compile a list of paths that it might make sense to read the owning UID from to use as initial candidate for
3898
         * dynamic UID allocation, in order to save us from doing costly recursive chown()s of the special
3899
         * directories. */
3900

3901
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
372✔
3902

3903
                if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(t))
310✔
3904
                        continue;
62✔
3905

3906
                if (!p->prefix[t])
248✔
3907
                        continue;
×
3908

3909
                for (size_t i = 0; i < c->directories[t].n_items; i++) {
263✔
3910
                        char *e;
15✔
3911

3912
                        if (exec_directory_is_private(c, t))
15✔
3913
                                e = path_join(p->prefix[t], "private", c->directories[t].items[i].path);
13✔
3914
                        else
3915
                                e = path_join(p->prefix[t], c->directories[t].items[i].path);
2✔
3916
                        if (!e)
15✔
3917
                                return -ENOMEM;
3918

3919
                        r = strv_consume(&list, e);
15✔
3920
                        if (r < 0)
15✔
3921
                                return r;
3922
                }
3923
        }
3924

3925
        *ret = TAKE_PTR(list);
62✔
3926

3927
        return 0;
62✔
3928
}
3929

3930
static int exec_context_cpu_affinity_from_numa(const ExecContext *c, CPUSet *ret) {
2✔
3931
        _cleanup_(cpu_set_reset) CPUSet s = {};
2✔
3932
        int r;
2✔
3933

3934
        assert(c);
2✔
3935
        assert(ret);
2✔
3936

3937
        if (!c->numa_policy.nodes.set) {
2✔
3938
                log_debug("Can't derive CPU affinity mask from NUMA mask because NUMA mask is not set, ignoring");
×
3939
                return 0;
×
3940
        }
3941

3942
        r = numa_to_cpu_set(&c->numa_policy, &s);
2✔
3943
        if (r < 0)
2✔
3944
                return r;
3945

3946
        cpu_set_reset(ret);
2✔
3947

3948
        return cpu_set_add_all(ret, &s);
2✔
3949
}
3950

3951
static int add_shifted_fd(int *fds, size_t fds_size, size_t *n_fds, int *fd) {
44,165✔
3952
        int r;
44,165✔
3953

3954
        assert(fds);
44,165✔
3955
        assert(n_fds);
44,165✔
3956
        assert(*n_fds < fds_size);
44,165✔
3957
        assert(fd);
44,165✔
3958

3959
        if (*fd < 0)
44,165✔
3960
               return 0;
44,165✔
3961

3962
        if (*fd < 3 + (int) *n_fds) {
21,489✔
3963
                /* Let's move the fd up, so that it's outside of the fd range we will use to store
3964
                 * the fds we pass to the process (or which are closed only during execve). */
3965

3966
                r = fcntl(*fd, F_DUPFD_CLOEXEC, 3 + (int) *n_fds);
9,556✔
3967
                if (r < 0)
9,556✔
3968
                        return -errno;
×
3969

3970
                close_and_replace(*fd, r);
9,556✔
3971
        }
3972

3973
        fds[(*n_fds)++] = *fd;
21,489✔
3974
        return 1;
21,489✔
3975
}
3976

3977
static int connect_unix_harder(const OpenFile *of, int ofd) {
1✔
3978
        static const int socket_types[] = { SOCK_DGRAM, SOCK_STREAM, SOCK_SEQPACKET };
1✔
3979

3980
        union sockaddr_union addr = {
1✔
3981
                .un.sun_family = AF_UNIX,
3982
        };
3983
        socklen_t sa_len;
1✔
3984
        int r;
1✔
3985

3986
        assert(of);
1✔
3987
        assert(ofd >= 0);
1✔
3988

3989
        r = sockaddr_un_set_path(&addr.un, FORMAT_PROC_FD_PATH(ofd));
1✔
3990
        if (r < 0)
1✔
3991
                return log_debug_errno(r, "Failed to set sockaddr for '%s': %m", of->path);
×
3992
        sa_len = r;
1✔
3993

3994
        FOREACH_ELEMENT(i, socket_types) {
2✔
3995
                _cleanup_close_ int fd = -EBADF;
2✔
3996

3997
                fd = socket(AF_UNIX, *i|SOCK_CLOEXEC, 0);
2✔
3998
                if (fd < 0)
2✔
3999
                        return log_debug_errno(errno, "Failed to create socket for '%s': %m", of->path);
×
4000

4001
                r = RET_NERRNO(connect(fd, &addr.sa, sa_len));
2✔
4002
                if (r >= 0)
1✔
4003
                        return TAKE_FD(fd);
1✔
4004
                if (r != -EPROTOTYPE)
1✔
4005
                        return log_debug_errno(r, "Failed to connect to socket for '%s': %m", of->path);
×
4006
        }
4007

4008
        return log_debug_errno(SYNTHETIC_ERRNO(EPROTOTYPE), "No suitable socket type to connect to socket '%s'.", of->path);
×
4009
}
4010

4011
static int get_open_file_fd(const OpenFile *of) {
5✔
4012
        _cleanup_close_ int fd = -EBADF, ofd = -EBADF;
5✔
4013
        struct stat st;
5✔
4014

4015
        assert(of);
5✔
4016

4017
        ofd = open(of->path, O_PATH | O_CLOEXEC);
5✔
4018
        if (ofd < 0)
5✔
4019
                return log_debug_errno(errno, "Failed to open '%s' as O_PATH: %m", of->path);
2✔
4020

4021
        if (fstat(ofd, &st) < 0)
3✔
4022
                return log_debug_errno( errno, "Failed to stat '%s': %m", of->path);
×
4023

4024
        if (S_ISSOCK(st.st_mode)) {
3✔
4025
                fd = connect_unix_harder(of, ofd);
1✔
4026
                if (fd < 0)
1✔
4027
                        return fd;
4028

4029
                if (FLAGS_SET(of->flags, OPENFILE_READ_ONLY) && shutdown(fd, SHUT_WR) < 0)
1✔
4030
                        return log_debug_errno(errno, "Failed to shutdown send for socket '%s': %m", of->path);
×
4031

4032
                log_debug("Opened socket '%s' as fd %d.", of->path, fd);
1✔
4033
        } else {
4034
                int flags = FLAGS_SET(of->flags, OPENFILE_READ_ONLY) ? O_RDONLY : O_RDWR;
2✔
4035
                if (FLAGS_SET(of->flags, OPENFILE_APPEND))
2✔
4036
                        flags |= O_APPEND;
×
4037
                else if (FLAGS_SET(of->flags, OPENFILE_TRUNCATE))
2✔
4038
                        flags |= O_TRUNC;
×
4039

4040
                fd = fd_reopen(ofd, flags|O_NOCTTY|O_CLOEXEC);
2✔
4041
                if (fd < 0)
2✔
4042
                        return log_debug_errno(fd, "Failed to reopen file '%s': %m", of->path);
×
4043

4044
                log_debug("Opened file '%s' as fd %d.", of->path, fd);
2✔
4045
        }
4046

4047
        return TAKE_FD(fd);
4048
}
4049

4050
static int collect_open_file_fds(ExecParameters *p, size_t *n_fds) {
11,537✔
4051
        assert(p);
11,537✔
4052
        assert(n_fds);
11,537✔
4053

4054
        LIST_FOREACH(open_files, of, p->open_files) {
11,537✔
4055
                _cleanup_close_ int fd = -EBADF;
11,542✔
4056

4057
                fd = get_open_file_fd(of);
5✔
4058
                if (fd < 0) {
5✔
4059
                        if (FLAGS_SET(of->flags, OPENFILE_GRACEFUL)) {
2✔
4060
                                log_full_errno(fd == -ENOENT || ERRNO_IS_NEG_PRIVILEGE(fd) ? LOG_DEBUG : LOG_WARNING,
1✔
4061
                                               fd,
4062
                                               "Failed to get OpenFile= file descriptor for '%s', ignoring: %m",
4063
                                               of->path);
4064
                                continue;
1✔
4065
                        }
4066

4067
                        return log_error_errno(fd, "Failed to get OpenFile= file descriptor for '%s': %m", of->path);
1✔
4068
                }
4069

4070
                if (!GREEDY_REALLOC(p->fds, *n_fds + 1))
3✔
4071
                        return log_oom();
×
4072

4073
                if (strv_extend(&p->fd_names, of->fdname) < 0)
3✔
4074
                        return log_oom();
×
4075

4076
                p->fds[(*n_fds)++] = TAKE_FD(fd);
3✔
4077
        }
4078

4079
        return 0;
4080
}
4081

4082
static void log_command_line(
9,556✔
4083
                const ExecContext *context,
4084
                const ExecParameters *params,
4085
                const char *msg,
4086
                const char *executable,
4087
                char **argv) {
4088

4089
        assert(context);
9,556✔
4090
        assert(params);
9,556✔
4091
        assert(msg);
9,556✔
4092
        assert(executable);
9,556✔
4093

4094
        if (!DEBUG_LOGGING)
9,556✔
4095
                return;
9,556✔
4096

4097
        _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);
18,464✔
4098

4099
        log_struct(LOG_DEBUG,
17,675✔
4100
                   LOG_ITEM("EXECUTABLE=%s", executable),
4101
                   LOG_EXEC_MESSAGE(params, "%s: %s", msg, strnull(cmdline)),
4102
                   LOG_EXEC_INVOCATION_ID(params));
4103
}
4104

4105
static bool exec_context_needs_cap_sys_admin(const ExecContext *context) {
1,653✔
4106
        assert(context);
1,653✔
4107

4108
        return context->private_users != PRIVATE_USERS_NO ||
3,293✔
4109
               context->private_tmp != PRIVATE_TMP_NO ||
1,640✔
4110
               context->private_devices ||
1,625✔
4111
               context->private_network ||
1,618✔
4112
               context->network_namespace_path ||
1,611✔
4113
               context->private_ipc ||
1,611✔
4114
               context->ipc_namespace_path ||
1,611✔
4115
               context->private_mounts > 0 ||
1,611✔
4116
               context->mount_apivfs > 0 ||
1,601✔
4117
               context->bind_log_sockets > 0 ||
1,601✔
4118
               context->n_bind_mounts > 0 ||
1,601✔
4119
               context->n_temporary_filesystems > 0 ||
1,596✔
4120
               context->root_directory ||
1,596✔
4121
               !strv_isempty(context->extension_directories) ||
1,596✔
4122
               context->protect_system != PROTECT_SYSTEM_NO ||
1,596✔
4123
               context->protect_home != PROTECT_HOME_NO ||
3,177✔
4124
               exec_needs_pid_namespace(context) ||
1,581✔
4125
               context->protect_kernel_tunables ||
1,559✔
4126
               context->protect_kernel_modules ||
1,554✔
4127
               context->protect_kernel_logs ||
3,098✔
4128
               exec_needs_cgroup_mount(context) ||
1,549✔
4129
               context->protect_clock ||
1,549✔
4130
               context->protect_hostname != PROTECT_HOSTNAME_NO ||
1,544✔
4131
               !strv_isempty(context->read_write_paths) ||
1,539✔
4132
               !strv_isempty(context->read_only_paths) ||
1,524✔
4133
               !strv_isempty(context->inaccessible_paths) ||
1,524✔
4134
               !strv_isempty(context->exec_paths) ||
1,524✔
4135
               !strv_isempty(context->no_exec_paths) ||
3,177✔
4136
               context->delegate_namespaces != NAMESPACE_FLAGS_INITIAL;
1,524✔
4137
}
4138

4139
static PrivateUsers exec_context_get_effective_private_users(
9,567✔
4140
                const ExecContext *context,
4141
                const ExecParameters *params) {
4142

4143
        assert(context);
9,567✔
4144
        assert(params);
9,567✔
4145

4146
        if (context->private_users != PRIVATE_USERS_NO)
9,567✔
4147
                return context->private_users;
4148

4149
        /* If any namespace is delegated with DelegateNamespaces=, always set up a user namespace. */
4150
        if (context->delegate_namespaces != NAMESPACE_FLAGS_INITIAL)
9,541✔
4151
                return PRIVATE_USERS_SELF;
3✔
4152

4153
        return PRIVATE_USERS_NO;
4154
}
4155

4156
static bool exec_namespace_is_delegated(
23,291✔
4157
                const ExecContext *context,
4158
                const ExecParameters *params,
4159
                bool have_cap_sys_admin,
4160
                unsigned long namespace) {
4161

4162
        assert(context);
23,291✔
4163
        assert(params);
23,291✔
4164
        assert(namespace != CLONE_NEWUSER);
23,291✔
4165

4166
        /* If we need unprivileged private users, we've already unshared a user namespace by the time we call
4167
         * setup_delegated_namespaces() for the first time so let's make sure we do all other namespace
4168
         * unsharing in the first call to setup_delegated_namespaces() by returning false here. */
4169
        if (!have_cap_sys_admin && exec_context_needs_cap_sys_admin(context))
23,291✔
4170
                return false;
4171

4172
        if (context->delegate_namespaces == NAMESPACE_FLAGS_INITIAL)
23,189✔
4173
                return params->runtime_scope == RUNTIME_SCOPE_USER;
23,121✔
4174

4175
        if (FLAGS_SET(context->delegate_namespaces, namespace))
68✔
4176
                return true;
4177

4178
        /* Various namespaces imply mountns for private procfs/sysfs/cgroupfs instances, which means when
4179
         * those are delegated mountns must be deferred too.
4180
         *
4181
         * The list should stay in sync with exec_needs_mount_namespace(). */
4182
        if (namespace == CLONE_NEWNS)
16✔
4183
                return context->delegate_namespaces & (CLONE_NEWPID|CLONE_NEWCGROUP|CLONE_NEWNET);
4✔
4184

4185
        return false;
4186
}
4187

4188
static int setup_delegated_namespaces(
19,145✔
4189
                const ExecContext *context,
4190
                ExecParameters *params,
4191
                ExecRuntime *runtime,
4192
                bool delegate,
4193
                const char *memory_pressure_path,
4194
                uid_t uid,
4195
                uid_t gid,
4196
                const ExecCommand *command,
4197
                bool needs_sandboxing,
4198
                bool have_cap_sys_admin,
4199
                int *reterr_exit_status) {
4200

4201
        int r;
19,145✔
4202

4203
        /* This function is called twice, once before unsharing the user namespace, and once after unsharing
4204
         * the user namespace. When called before unsharing the user namespace, "delegate" is set to "false".
4205
         * When called after unsharing the user namespace, "delegate" is set to "true". The net effect is
4206
         * that all namespaces that should not be delegated are unshared when this function is called the
4207
         * first time and all namespaces that should be delegated are unshared when this function is called
4208
         * the second time. */
4209

4210
        assert(context);
19,145✔
4211
        assert(params);
19,145✔
4212
        assert(runtime);
19,145✔
4213
        assert(reterr_exit_status);
19,145✔
4214

4215
        if (exec_needs_network_namespace(context) &&
19,264✔
4216
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWNET) == delegate &&
119✔
4217
            runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
60✔
4218

4219
                /* Try to enable network namespacing if network namespacing is available and we have
4220
                 * CAP_NET_ADMIN in the current user namespace (either the system manager one or the unit's
4221
                 * own user namespace). We need CAP_NET_ADMIN to be able to configure the loopback device in
4222
                 * the new network namespace. And if we don't have that, then we could only create a network
4223
                 * namespace without the ability to set up "lo". Hence gracefully skip things then. */
4224
                if (namespace_type_supported(NAMESPACE_NET) && have_effective_cap(CAP_NET_ADMIN) > 0) {
60✔
4225
                        r = setup_shareable_ns(runtime->shared->netns_storage_socket, CLONE_NEWNET);
60✔
4226
                        if (ERRNO_IS_NEG_PRIVILEGE(r))
60✔
4227
                                log_notice_errno(r, "PrivateNetwork=yes is configured, but network namespace setup not permitted, proceeding without: %m");
×
4228
                        else if (r < 0) {
60✔
4229
                                *reterr_exit_status = EXIT_NETWORK;
×
4230
                                return log_error_errno(r, "Failed to set up network namespacing: %m");
×
4231
                        } else
4232
                                log_debug("Set up %snetwork namespace", delegate ? "delegated " : "");
115✔
4233
                } else if (context->network_namespace_path) {
×
4234
                        *reterr_exit_status = EXIT_NETWORK;
×
4235
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "NetworkNamespacePath= is not supported, refusing.");
×
4236
                } else
4237
                        log_notice("PrivateNetwork=yes is configured, but the kernel does not support or we lack privileges for network namespace, proceeding without.");
×
4238
        }
4239

4240
        if (exec_needs_ipc_namespace(context) &&
19,156✔
4241
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWIPC) == delegate &&
11✔
4242
            runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
6✔
4243

4244
                if (namespace_type_supported(NAMESPACE_IPC)) {
6✔
4245
                        r = setup_shareable_ns(runtime->shared->ipcns_storage_socket, CLONE_NEWIPC);
6✔
4246
                        if (ERRNO_IS_NEG_PRIVILEGE(r))
6✔
4247
                                log_warning_errno(r, "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m");
×
4248
                        else if (r < 0) {
6✔
4249
                                *reterr_exit_status = EXIT_NAMESPACE;
×
4250
                                return log_error_errno(r, "Failed to set up IPC namespacing: %m");
×
4251
                        } else
4252
                                log_debug("Set up %sIPC namespace", delegate ? "delegated " : "");
8✔
4253
                } else if (context->ipc_namespace_path) {
×
4254
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4255
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "IPCNamespacePath= is not supported, refusing.");
×
4256
                } else
4257
                        log_warning("PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring.");
×
4258
        }
4259

4260
        if (needs_sandboxing && exec_needs_cgroup_namespace(context) &&
19,170✔
4261
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWCGROUP) == delegate) {
25✔
4262
                if (unshare(CLONE_NEWCGROUP) < 0) {
13✔
4263
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4264
                        return log_error_errno(errno, "Failed to set up cgroup namespacing: %m");
×
4265
                }
4266

4267
                log_debug("Set up %scgroup namespace", delegate ? "delegated " : "");
22✔
4268
        }
4269

4270
        /* Unshare a new PID namespace before setting up mounts to ensure /proc/ is mounted with only processes in PID namespace visible.
4271
         * Note PrivatePIDs=yes implies MountAPIVFS=yes so we'll always ensure procfs is remounted. */
4272
        if (needs_sandboxing && exec_needs_pid_namespace(context) &&
19,170✔
4273
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWPID) == delegate) {
25✔
4274
                if (params->pidref_transport_fd < 0) {
15✔
4275
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4276
                        return log_error_errno(SYNTHETIC_ERRNO(ENOTCONN), "PidRef socket is not set up: %m");
×
4277
                }
4278

4279
                /* If we had CAP_SYS_ADMIN prior to joining the user namespace, then we are privileged and don't need
4280
                 * to check if we can mount /proc/.
4281
                 *
4282
                 * We need to check prior to entering the user namespace because if we're running unprivileged or in a
4283
                 * system without CAP_SYS_ADMIN, then we can have CAP_SYS_ADMIN in the current user namespace but not
4284
                 * once we unshare a mount namespace. */
4285
                if (!have_cap_sys_admin || delegate) {
15✔
4286
                        r = can_mount_proc();
10✔
4287
                        if (r < 0) {
5✔
4288
                                *reterr_exit_status = EXIT_NAMESPACE;
×
4289
                                return log_error_errno(r, "Failed to detect if /proc/ can be remounted: %m");
×
4290
                        }
4291
                        if (r == 0) {
5✔
4292
                                *reterr_exit_status = EXIT_NAMESPACE;
1✔
4293
                                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
1✔
4294
                                                       "PrivatePIDs=yes is configured, but /proc/ cannot be re-mounted due to lack of privileges, refusing.");
4295
                        }
4296
                }
4297

4298
                r = setup_private_pids(context, params);
9✔
4299
                if (r < 0) {
6✔
4300
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4301
                        return log_error_errno(r, "Failed to set up pid namespace: %m");
×
4302
                }
4303

4304
                log_debug("Set up %spid namespace", delegate ? "delegated " : "");
12✔
4305
        }
4306

4307
        /* If PrivatePIDs= yes is configured, we're now running as pid 1 in a pid namespace! */
4308

4309
        if (exec_needs_mount_namespace(context, params, runtime) &&
23,126✔
4310
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWNS) == delegate) {
3,990✔
4311
                _cleanup_free_ char *error_path = NULL;
2,001✔
4312

4313
                r = apply_mount_namespace(command->flags,
2,001✔
4314
                                          context,
4315
                                          params,
4316
                                          runtime,
4317
                                          memory_pressure_path,
4318
                                          needs_sandboxing,
4319
                                          &error_path,
4320
                                          uid,
4321
                                          gid);
4322
                if (r < 0) {
2,001✔
4323
                        *reterr_exit_status = EXIT_NAMESPACE;
15✔
4324
                        return log_error_errno(r, "Failed to set up mount namespacing%s%s: %m",
29✔
4325
                                               error_path ? ": " : "", strempty(error_path));
4326
                }
4327

4328
                log_debug("Set up %smount namespace", delegate ? "delegated " : "");
3,944✔
4329
        }
4330

4331
        if (needs_sandboxing &&
38,242✔
4332
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWUTS) == delegate) {
19,121✔
4333
                r = apply_protect_hostname(context, params, reterr_exit_status);
9,559✔
4334
                if (r < 0)
9,559✔
4335
                        return r;
4336
                if (r > 0)
9,559✔
4337
                        log_debug("Set up %sUTS namespace", delegate ? "delegated " : "");
1,327✔
4338
        }
4339

4340
        return 0;
4341
}
4342

4343
static bool exec_context_shall_confirm_spawn(const ExecContext *context) {
×
4344
        assert(context);
×
4345

4346
        if (confirm_spawn_disabled())
×
4347
                return false;
4348

4349
        /* For some reasons units remaining in the same process group
4350
         * as PID 1 fail to acquire the console even if it's not used
4351
         * by any process. So skip the confirmation question for them. */
4352
        return !context->same_pgrp;
×
4353
}
4354

4355
static int exec_context_named_iofds(
11,537✔
4356
                const ExecContext *c,
4357
                const ExecParameters *p,
4358
                int named_iofds[static 3]) {
4359

4360
        size_t targets;
11,537✔
4361
        const char* stdio_fdname[3];
11,537✔
4362
        size_t n_fds;
11,537✔
4363

4364
        assert(c);
11,537✔
4365
        assert(p);
11,537✔
4366
        assert(named_iofds);
11,537✔
4367

4368
        targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
11,537✔
4369
                  (c->std_output == EXEC_OUTPUT_NAMED_FD) +
11,537✔
4370
                  (c->std_error == EXEC_OUTPUT_NAMED_FD);
11,537✔
4371

4372
        for (size_t i = 0; i < 3; i++)
46,148✔
4373
                stdio_fdname[i] = exec_context_fdname(c, i);
34,611✔
4374

4375
        n_fds = p->n_storage_fds + p->n_socket_fds + p->n_extra_fds;
11,537✔
4376

4377
        for (size_t i = 0; i < n_fds  && targets > 0; i++)
11,537✔
4378
                if (named_iofds[STDIN_FILENO] < 0 &&
×
4379
                    c->std_input == EXEC_INPUT_NAMED_FD &&
×
4380
                    stdio_fdname[STDIN_FILENO] &&
×
4381
                    streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
×
4382

4383
                        named_iofds[STDIN_FILENO] = p->fds[i];
×
4384
                        targets--;
×
4385

4386
                } else if (named_iofds[STDOUT_FILENO] < 0 &&
×
4387
                           c->std_output == EXEC_OUTPUT_NAMED_FD &&
×
4388
                           stdio_fdname[STDOUT_FILENO] &&
×
4389
                           streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
×
4390

4391
                        named_iofds[STDOUT_FILENO] = p->fds[i];
×
4392
                        targets--;
×
4393

4394
                } else if (named_iofds[STDERR_FILENO] < 0 &&
×
4395
                           c->std_error == EXEC_OUTPUT_NAMED_FD &&
×
4396
                           stdio_fdname[STDERR_FILENO] &&
×
4397
                           streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
×
4398

4399
                        named_iofds[STDERR_FILENO] = p->fds[i];
×
4400
                        targets--;
×
4401
                }
4402

4403
        return targets == 0 ? 0 : -ENOENT;
11,537✔
4404
}
4405

4406
static void exec_shared_runtime_close(ExecSharedRuntime *shared) {
9,557✔
4407
        if (!shared)
9,557✔
4408
                return;
4409

4410
        safe_close_pair(shared->netns_storage_socket);
9,557✔
4411
        safe_close_pair(shared->ipcns_storage_socket);
9,557✔
4412
}
4413

4414
static void exec_runtime_close(ExecRuntime *rt) {
9,557✔
4415
        if (!rt)
9,557✔
4416
                return;
4417

4418
        safe_close_pair(rt->ephemeral_storage_socket);
9,557✔
4419

4420
        exec_shared_runtime_close(rt->shared);
9,557✔
4421
        dynamic_creds_close(rt->dynamic_creds);
9,557✔
4422
}
4423

4424
static void exec_params_close(ExecParameters *p) {
9,557✔
4425
        if (!p)
9,557✔
4426
                return;
4427

4428
        p->stdin_fd = safe_close(p->stdin_fd);
9,557✔
4429
        p->stdout_fd = safe_close(p->stdout_fd);
9,557✔
4430
        p->stderr_fd = safe_close(p->stderr_fd);
9,557✔
4431
}
4432

4433
static int exec_fd_mark_hot(
9,559✔
4434
                const ExecContext *c,
4435
                ExecParameters *p,
4436
                bool hot,
4437
                int *reterr_exit_status) {
4438

4439
        assert(c);
9,559✔
4440
        assert(p);
9,559✔
4441

4442
        if (p->exec_fd < 0)
9,559✔
4443
                return 0;
9,559✔
4444

4445
        uint8_t x = hot;
287✔
4446

4447
        if (write(p->exec_fd, &x, sizeof(x)) < 0) {
287✔
4448
                if (reterr_exit_status)
×
4449
                        *reterr_exit_status = EXIT_EXEC;
×
4450
                return log_error_errno(errno, "Failed to mark exec_fd as %s: %m", hot ? "hot" : "cold");
×
4451
        }
4452

4453
        return 1;
4454
}
4455

4456
static int send_handoff_timestamp(
9,556✔
4457
                const ExecContext *c,
4458
                ExecParameters *p,
4459
                int *reterr_exit_status) {
4460

4461
        assert(c);
9,556✔
4462
        assert(p);
9,556✔
4463

4464
        if (p->handoff_timestamp_fd < 0)
9,556✔
4465
                return 0;
9,556✔
4466

4467
        dual_timestamp dt;
9,556✔
4468
        dual_timestamp_now(&dt);
9,556✔
4469

4470
        if (write(p->handoff_timestamp_fd, (const usec_t[2]) { dt.realtime, dt.monotonic }, sizeof(usec_t) * 2) < 0) {
9,556✔
4471
                if (reterr_exit_status)
×
4472
                        *reterr_exit_status = EXIT_EXEC;
×
4473
                return log_error_errno(errno, "Failed to send handoff timestamp: %m");
×
4474
        }
4475

4476
        return 1;
9,556✔
4477
}
4478

4479
static void prepare_terminal(
11,534✔
4480
                const ExecContext *context,
4481
                ExecParameters *p) {
4482

4483
        _cleanup_close_ int lock_fd = -EBADF;
11,534✔
4484

4485
        /* This is the "constructive" reset, i.e. is about preparing things for our invocation rather than
4486
         * cleaning up things from older invocations. */
4487

4488
        assert(context);
11,534✔
4489
        assert(p);
11,534✔
4490

4491
        /* We only try to reset things if we there's the chance our stdout points to a TTY */
4492
        if (!(is_terminal_output(context->std_output) ||
11,534✔
4493
              (context->std_output == EXEC_OUTPUT_INHERIT && is_terminal_input(context->std_input)) ||
10,927✔
4494
              context->std_output == EXEC_OUTPUT_NAMED_FD ||
4495
              p->stdout_fd >= 0))
10,927✔
4496
                return;
10,381✔
4497

4498
        /* Let's explicitly determine whether to reset via ANSI sequences or not, taking our ExecContext
4499
         * information into account */
4500
        bool use_ansi = exec_context_shall_ansi_seq_reset(context);
1,153✔
4501

4502
        if (context->tty_reset) {
1,153✔
4503
                /* When we are resetting the TTY, then let's create a lock first, to synchronize access. This
4504
                 * in particular matters as concurrent resets and the TTY size ANSI DSR logic done by the
4505
                 * exec_context_apply_tty_size() below might interfere */
4506
                lock_fd = lock_dev_console();
153✔
4507
                if (lock_fd < 0)
153✔
4508
                        log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
×
4509

4510
                /* We explicitly control whether to send ansi sequences or not here, since we want to consult
4511
                 * the env vars explicitly configured in the ExecContext, rather than our own environment
4512
                 * block. */
4513
                (void) terminal_reset_defensive(STDOUT_FILENO, use_ansi ? TERMINAL_RESET_FORCE_ANSI_SEQ : TERMINAL_RESET_AVOID_ANSI_SEQ);
156✔
4514
        }
4515

4516
        (void) exec_context_apply_tty_size(context, STDIN_FILENO, STDOUT_FILENO, /* tty_path= */ NULL);
1,153✔
4517

4518
        if (use_ansi)
1,153✔
4519
                (void) osc_context_open_service(p->unit_id, p->invocation_id, /* ret_seq= */ NULL);
150✔
4520
}
4521

4522
static int setup_term_environment(const ExecContext *context, char ***env) {
9,583✔
4523
        int r;
9,583✔
4524

4525
        assert(context);
9,583✔
4526
        assert(env);
9,583✔
4527

4528
        /* Already specified by user? */
4529
        if (strv_env_get(*env, "TERM"))
9,583✔
4530
                return 0;
4531

4532
        /* Do we need $TERM at all? */
4533
        if (!is_terminal_input(context->std_input) &&
9,439✔
4534
            !is_terminal_output(context->std_output) &&
9,269✔
4535
            !is_terminal_output(context->std_error) &&
9,010✔
4536
            !context->tty_path)
9,009✔
4537
                return 0;
4538

4539
        const char *tty_path = exec_context_tty_path(context);
432✔
4540
        if (tty_path) {
432✔
4541
                /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try
4542
                 * to inherit the $TERM set for PID 1. This is useful for containers so that the $TERM the
4543
                 * container manager passes to PID 1 ends up all the way in the console login shown.
4544
                 *
4545
                 * Note that if this doesn't work out we won't bother with querying systemd.tty.term.console
4546
                 * kernel cmdline option or DCS anymore either, because pid1 also imports $TERM based on those
4547
                 * and it should have showed up as our $TERM if there were anything. */
4548
                if (tty_is_console(tty_path) && getppid() == 1) {
430✔
4549
                        const char *term = strv_find_prefix(environ, "TERM=");
389✔
4550
                        if (term) {
389✔
4551
                                r = strv_env_replace_strdup(env, term);
389✔
4552
                                if (r < 0)
389✔
4553
                                        return r;
4554

4555
                                FOREACH_STRING(i, "COLORTERM=", "NO_COLOR=") {
1,167✔
4556
                                        const char *s = strv_find_prefix(environ, i);
778✔
4557
                                        if (!s)
778✔
4558
                                                continue;
778✔
4559

4560
                                        r = strv_env_replace_strdup(env, s);
×
4561
                                        if (r < 0)
×
4562
                                                return r;
×
4563
                                }
4564

4565
                                return 1;
389✔
4566
                        }
4567

4568
                } else {
4569
                        if (in_charset(skip_dev_prefix(tty_path), ALPHANUMERICAL)) {
41✔
4570
                                _cleanup_free_ char *key = NULL, *cmdline = NULL;
41✔
4571

4572
                                key = strjoin("systemd.tty.term.", skip_dev_prefix(tty_path));
41✔
4573
                                if (!key)
41✔
4574
                                        return -ENOMEM;
4575

4576
                                r = proc_cmdline_get_key(key, /* flags = */ 0, &cmdline);
41✔
4577
                                if (r > 0)
41✔
4578
                                        return strv_env_assign(env, "TERM", cmdline);
×
4579
                                if (r < 0)
41✔
4580
                                        log_debug_errno(r, "Failed to read '%s' from kernel cmdline, ignoring: %m", key);
41✔
4581
                        }
4582

4583
                        /* This handles real virtual terminals (returning "linux") and
4584
                         * any terminals which support the DCS +q query sequence. */
4585
                        _cleanup_free_ char *dcs_term = NULL;
41✔
4586
                        r = query_term_for_tty(tty_path, &dcs_term);
41✔
4587
                        if (r >= 0)
41✔
4588
                                return strv_env_assign(env, "TERM", dcs_term);
41✔
4589
                }
4590
        }
4591

4592
        /* If $TERM is not known and we pick a fallback default, then let's also set
4593
         * $COLORTERM=truecolor. That's because our fallback default is vt220, which is
4594
         * generally a safe bet (as it supports PageUp/PageDown unlike vt100, and is quite
4595
         * universally available in terminfo/termcap), except for the fact that real DEC
4596
         * vt220 gear never actually supported color. Most tools these days generate color on
4597
         * vt220 anyway, ignoring the physical capabilities of the real hardware, but some
4598
         * tools actually believe in the historical truth. Which is unfortunate since *we*
4599
         * *don't* care about the historical truth, we just want sane defaults if nothing
4600
         * better is explicitly configured. It's 2025 after all, at the time of writing,
4601
         * pretty much all terminal emulators actually *do* support color, hence if we don't
4602
         * know any better let's explicitly claim color support via $COLORTERM. Or in other
4603
         * words: we now explicitly claim to be connected to a franken-vt220 with true color
4604
         * support. */
4605
        r = strv_env_replace_strdup(env, "COLORTERM=truecolor");
2✔
4606
        if (r < 0)
2✔
4607
                return r;
4608

4609
        return strv_env_replace_strdup(env, "TERM=" FALLBACK_TERM);
2✔
4610
}
4611

4612
int exec_invoke(
11,537✔
4613
                const ExecCommand *command,
4614
                const ExecContext *context,
4615
                ExecParameters *params,
4616
                ExecRuntime *runtime,
4617
                const CGroupContext *cgroup_context,
4618
                int *exit_status) {
11,537✔
4619

4620
        _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **joined_exec_search_path = NULL, **accum_env = NULL;
28✔
4621
        int r;
11,537✔
4622
        const char *username = NULL, *groupname = NULL;
11,537✔
4623
        _cleanup_free_ char *home_buffer = NULL, *memory_pressure_path = NULL, *own_user = NULL;
×
4624
        const char *pwent_home = NULL, *shell = NULL;
11,537✔
4625
        dev_t journal_stream_dev = 0;
11,537✔
4626
        ino_t journal_stream_ino = 0;
11,537✔
4627
        bool needs_sandboxing,          /* Do we need to set up full sandboxing? (i.e. all namespacing, all MAC stuff, caps, yadda yadda */
11,537✔
4628
                needs_setuid,           /* Do we need to do the actual setresuid()/setresgid() calls? */
4629
                needs_mount_namespace,  /* Do we need to set up a mount namespace for this kernel? */
4630
                have_cap_sys_admin,
4631
                userns_set_up = false,
11,537✔
4632
                keep_seccomp_privileges = false;
11,537✔
4633
#if HAVE_SELINUX
4634
        _cleanup_free_ char *mac_selinux_context_net = NULL;
4635
        bool use_selinux = false;
4636
#endif
4637
#if ENABLE_SMACK
4638
        bool use_smack = false;
11,537✔
4639
#endif
4640
#if HAVE_APPARMOR
4641
        bool use_apparmor = false;
4642
#endif
4643
#if HAVE_SECCOMP
4644
        uint64_t saved_bset = 0;
11,537✔
4645
#endif
4646
        uid_t saved_uid = getuid();
11,537✔
4647
        gid_t saved_gid = getgid();
11,537✔
4648
        uid_t uid = UID_INVALID;
11,537✔
4649
        gid_t gid = GID_INVALID;
11,537✔
4650
        size_t n_fds, /* fds to pass to the child */
11,537✔
4651
               n_keep_fds; /* total number of fds not to close */
4652
        int secure_bits;
11,537✔
4653
        _cleanup_free_ gid_t *gids = NULL, *gids_after_pam = NULL;
28✔
4654
        int ngids = 0, ngids_after_pam = 0;
11,537✔
4655
        int socket_fd = -EBADF, named_iofds[3] = EBADF_TRIPLET;
11,537✔
4656
        size_t n_storage_fds, n_socket_fds, n_extra_fds;
11,537✔
4657

4658
        assert(command);
11,537✔
4659
        assert(context);
11,537✔
4660
        assert(params);
11,537✔
4661
        assert(runtime);
11,537✔
4662
        assert(cgroup_context);
11,537✔
4663
        assert(exit_status);
11,537✔
4664

4665
        LOG_CONTEXT_PUSH_EXEC(context, params);
33,049✔
4666

4667
        /* Explicitly test for CVE-2021-4034 inspired invocations */
4668
        if (!command->path || strv_isempty(command->argv)) {
11,537✔
4669
                *exit_status = EXIT_EXEC;
×
4670
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid command line arguments.");
×
4671
        }
4672

4673
        if (context->std_input == EXEC_INPUT_SOCKET ||
11,537✔
4674
            context->std_output == EXEC_OUTPUT_SOCKET ||
11,526✔
4675
            context->std_error == EXEC_OUTPUT_SOCKET) {
11,520✔
4676

4677
                if (params->n_socket_fds > 1)
17✔
4678
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Got more than one socket.");
×
4679

4680
                if (params->n_socket_fds == 0)
17✔
4681
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Got no socket.");
×
4682

4683
                socket_fd = params->fds[0];
17✔
4684
                n_storage_fds = n_socket_fds = n_extra_fds = 0;
17✔
4685
        } else {
4686
                n_socket_fds = params->n_socket_fds;
11,520✔
4687
                n_storage_fds = params->n_storage_fds;
11,520✔
4688
                n_extra_fds = params->n_extra_fds;
11,520✔
4689
        }
4690
        n_fds = n_socket_fds + n_storage_fds + n_extra_fds;
11,537✔
4691

4692
        r = exec_context_named_iofds(context, params, named_iofds);
11,537✔
4693
        if (r < 0)
11,537✔
4694
                return log_error_errno(r, "Failed to load a named file descriptor: %m");
×
4695

4696
        rename_process_from_path(command->path);
11,537✔
4697

4698
        /* We reset exactly these signals, since they are the only ones we set to SIG_IGN in the main
4699
         * daemon. All others we leave untouched because we set them to SIG_DFL or a valid handler initially,
4700
         * both of which will be demoted to SIG_DFL. */
4701
        (void) default_signals(SIGNALS_CRASH_HANDLER,
11,537✔
4702
                               SIGNALS_IGNORE);
4703

4704
        if (context->ignore_sigpipe)
11,537✔
4705
                (void) ignore_signals(SIGPIPE);
11,178✔
4706

4707
        r = reset_signal_mask();
11,537✔
4708
        if (r < 0) {
11,537✔
4709
                *exit_status = EXIT_SIGNAL_MASK;
×
4710
                return log_error_errno(r, "Failed to set process signal mask: %m");
×
4711
        }
4712

4713
        if (params->idle_pipe)
11,537✔
4714
                do_idle_pipe_dance(params->idle_pipe);
150✔
4715

4716
        /* Close fds we don't need very early to make sure we don't block init reexecution because it cannot bind its
4717
         * sockets. Among the fds we close are the logging fds, and we want to keep them closed, so that we don't have
4718
         * any fds open we don't really want open during the transition. In order to make logging work, we switch the
4719
         * log subsystem into open_when_needed mode, so that it reopens the logs on every single log call. */
4720

4721
        log_forget_fds();
11,537✔
4722
        log_set_open_when_needed(true);
11,537✔
4723
        log_settle_target();
11,537✔
4724

4725
        /* In case anything used libc syslog(), close this here, too */
4726
        closelog();
11,537✔
4727

4728
        r = collect_open_file_fds(params, &n_fds);
11,537✔
4729
        if (r < 0) {
11,537✔
4730
                *exit_status = EXIT_FDS;
1✔
4731
                return log_error_errno(r, "Failed to get OpenFile= file descriptors: %m");
1✔
4732
        }
4733

4734
        int keep_fds[n_fds + 4];
11,536✔
4735
        memcpy_safe(keep_fds, params->fds, n_fds * sizeof(int));
11,536✔
4736
        n_keep_fds = n_fds;
11,536✔
4737

4738
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->exec_fd);
11,536✔
4739
        if (r < 0) {
11,536✔
4740
                *exit_status = EXIT_FDS;
×
4741
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
4742
        }
4743

4744
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->handoff_timestamp_fd);
11,536✔
4745
        if (r < 0) {
11,536✔
4746
                *exit_status = EXIT_FDS;
×
4747
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
4748
        }
4749

4750
#if HAVE_LIBBPF
4751
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->bpf_restrict_fs_map_fd);
11,536✔
4752
        if (r < 0) {
11,536✔
4753
                *exit_status = EXIT_FDS;
×
4754
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
4755
        }
4756
#endif
4757

4758
        r = close_remaining_fds(params, runtime, socket_fd, keep_fds, n_keep_fds);
11,536✔
4759
        if (r < 0) {
11,536✔
4760
                *exit_status = EXIT_FDS;
×
4761
                return log_error_errno(r, "Failed to close unwanted file descriptors: %m");
×
4762
        }
4763

4764
        if (!context->same_pgrp &&
22,207✔
4765
            setsid() < 0) {
10,671✔
4766
                *exit_status = EXIT_SETSID;
×
4767
                return log_error_errno(errno, "Failed to create new process session: %m");
×
4768
        }
4769

4770
        /* Now, reset the TTY associated to this service "destructively" (i.e. possibly even hang up or
4771
         * disallocate the VT), to get rid of any prior uses of the device. Note that we do not keep any fd
4772
         * open here, hence some of the settings made here might vanish again, depending on the TTY driver
4773
         * used. A 2nd ("constructive") initialization after we opened the input/output fds we actually want
4774
         * will fix this. Note that we pass a NULL invocation ID here – as exec_context_tty_reset() expects
4775
         * the invocation ID associated with the OSC 3008 context ID to close. But we don't want to close any
4776
         * OSC 3008 context here, and opening a fresh OSC 3008 context happens a bit further down. */
4777
        exec_context_tty_reset(context, params, /* invocation_id= */ SD_ID128_NULL);
11,536✔
4778

4779
        if (params->shall_confirm_spawn && exec_context_shall_confirm_spawn(context)) {
11,536✔
4780
                _cleanup_free_ char *cmdline = NULL;
×
4781

4782
                cmdline = quote_command_line(command->argv, SHELL_ESCAPE_EMPTY);
×
4783
                if (!cmdline) {
×
4784
                        *exit_status = EXIT_MEMORY;
×
4785
                        return log_oom();
×
4786
                }
4787

4788
                r = ask_for_confirmation(context, params, cmdline);
×
4789
                if (r != CONFIRM_EXECUTE) {
×
4790
                        if (r == CONFIRM_PRETEND_SUCCESS) {
×
4791
                                *exit_status = EXIT_SUCCESS;
×
4792
                                return 0;
×
4793
                        }
4794

4795
                        *exit_status = EXIT_CONFIRM;
×
4796
                        return log_error_errno(SYNTHETIC_ERRNO(ECANCELED), "Execution cancelled by the user.");
×
4797
                }
4798
        }
4799

4800
        /* We are about to invoke NSS and PAM modules. Let's tell them what we are doing here, maybe they care. This is
4801
         * used by nss-resolve to disable itself when we are about to start systemd-resolved, to avoid deadlocks. Note
4802
         * that these env vars do not survive the execve(), which means they really only apply to the PAM and NSS
4803
         * invocations themselves. Also note that while we'll only invoke NSS modules involved in user management they
4804
         * might internally call into other NSS modules that are involved in hostname resolution, we never know. */
4805
        if (setenv("SYSTEMD_ACTIVATION_UNIT", params->unit_id, true) != 0 ||
23,072✔
4806
            setenv("SYSTEMD_ACTIVATION_SCOPE", runtime_scope_to_string(params->runtime_scope), true) != 0) {
11,536✔
4807
                *exit_status = EXIT_MEMORY;
×
4808
                return log_error_errno(errno, "Failed to update environment: %m");
×
4809
        }
4810

4811
        if (context->dynamic_user && runtime->dynamic_creds) {
11,598✔
4812
                _cleanup_strv_free_ char **suggested_paths = NULL;
62✔
4813

4814
                /* On top of that, make sure we bypass our own NSS module nss-systemd comprehensively for any NSS
4815
                 * checks, if DynamicUser=1 is used, as we shouldn't create a feedback loop with ourselves here. */
4816
                if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
62✔
4817
                        *exit_status = EXIT_USER;
×
4818
                        return log_error_errno(errno, "Failed to update environment: %m");
×
4819
                }
4820

4821
                r = compile_suggested_paths(context, params, &suggested_paths);
62✔
4822
                if (r < 0) {
62✔
4823
                        *exit_status = EXIT_MEMORY;
×
4824
                        return log_oom();
×
4825
                }
4826

4827
                r = dynamic_creds_realize(runtime->dynamic_creds, suggested_paths, &uid, &gid);
62✔
4828
                if (r < 0) {
62✔
4829
                        *exit_status = EXIT_USER;
×
4830
                        if (r == -EILSEQ)
×
4831
                                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
×
4832
                                                       "Failed to update dynamic user credentials: User or group with specified name already exists.");
4833
                        return log_error_errno(r, "Failed to update dynamic user credentials: %m");
×
4834
                }
4835

4836
                if (!uid_is_valid(uid)) {
62✔
4837
                        *exit_status = EXIT_USER;
×
4838
                        return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "UID validation failed for \""UID_FMT"\".", uid);
×
4839
                }
4840

4841
                if (!gid_is_valid(gid)) {
62✔
4842
                        *exit_status = EXIT_USER;
×
4843
                        return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "GID validation failed for \""GID_FMT"\".", gid);
×
4844
                }
4845

4846
                if (runtime->dynamic_creds->user)
62✔
4847
                        username = runtime->dynamic_creds->user->name;
62✔
4848

4849
        } else {
4850
                const char *u;
11,474✔
4851

4852
                if (context->user)
11,474✔
4853
                        u = context->user;
4854
                else if (context->pam_name || FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL)) {
8,927✔
4855
                        /* If PAM is enabled but no user name is explicitly selected, then use our own one. */
4856
                        own_user = getusername_malloc();
65✔
4857
                        if (!own_user) {
65✔
4858
                                *exit_status = EXIT_USER;
×
4859
                                return log_error_errno(r, "Failed to determine my own user ID: %m");
×
4860
                        }
4861
                        u = own_user;
4862
                } else
4863
                        u = NULL;
4864

4865
                if (u) {
4866
                        /* We can't use nss unconditionally for root without risking deadlocks if some IPC services
4867
                         * will be started by pid1 and are ordered after us. But if SetLoginEnvironment= is
4868
                         * enabled *explicitly* (i.e. no exec_context_get_set_login_environment() here),
4869
                         * or PAM shall be invoked, let's consult NSS even for root, so that the user
4870
                         * gets accurate $SHELL in session(-like) contexts. */
4871
                        r = get_fixed_user(u,
2,612✔
4872
                                           /* prefer_nss = */ context->set_login_environment > 0 || context->pam_name,
2,612✔
4873
                                           &username, &uid, &gid, &pwent_home, &shell);
4874
                        if (r < 0) {
2,612✔
4875
                                *exit_status = EXIT_USER;
2✔
4876
                                return log_error_errno(r, "Failed to determine user credentials: %m");
2✔
4877
                        }
4878
                }
4879

4880
                if (context->group) {
11,472✔
4881
                        r = get_fixed_group(context->group, &groupname, &gid);
11✔
4882
                        if (r < 0) {
11✔
4883
                                *exit_status = EXIT_GROUP;
×
4884
                                return log_error_errno(r, "Failed to determine group credentials: %m");
×
4885
                        }
4886
                }
4887
        }
4888

4889
        /* Initialize user supplementary groups and get SupplementaryGroups= ones */
4890
        ngids = get_supplementary_groups(context, username, gid, &gids);
11,534✔
4891
        if (ngids < 0) {
11,534✔
4892
                *exit_status = EXIT_GROUP;
×
4893
                return log_error_errno(ngids, "Failed to determine supplementary groups: %m");
×
4894
        }
4895

4896
        r = send_user_lookup(params->unit_id, params->user_lookup_fd, uid, gid);
11,534✔
4897
        if (r < 0) {
11,534✔
4898
                *exit_status = EXIT_USER;
×
4899
                return log_error_errno(r, "Failed to send user credentials to PID1: %m");
×
4900
        }
4901

4902
        params->user_lookup_fd = safe_close(params->user_lookup_fd);
11,534✔
4903

4904
        r = acquire_home(context, &pwent_home, &home_buffer);
11,534✔
4905
        if (r < 0) {
11,534✔
4906
                *exit_status = EXIT_CHDIR;
×
4907
                return log_error_errno(r, "Failed to determine $HOME for the invoking user: %m");
×
4908
        }
4909

4910
        /* If a socket is connected to STDIN/STDOUT/STDERR, we must drop O_NONBLOCK */
4911
        if (socket_fd >= 0)
11,534✔
4912
                (void) fd_nonblock(socket_fd, false);
17✔
4913

4914
        /* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields.
4915
         * Hence we need to migrate to the target cgroup from init.scope before connecting to journald */
4916
        if (params->cgroup_path) {
11,534✔
4917
                _cleanup_free_ char *p = NULL;
11,534✔
4918

4919
                r = exec_params_get_cgroup_path(params, cgroup_context, &p);
11,534✔
4920
                if (r < 0) {
11,534✔
4921
                        *exit_status = EXIT_CGROUP;
×
4922
                        return log_error_errno(r, "Failed to acquire cgroup path: %m");
×
4923
                }
4924

4925
                r = cg_attach(p, 0);
11,534✔
4926
                if (r == -EUCLEAN) {
11,534✔
4927
                        *exit_status = EXIT_CGROUP;
×
4928
                        return log_error_errno(r,
×
4929
                                               "Failed to attach process to cgroup '%s', "
4930
                                               "because the cgroup or one of its parents or "
4931
                                               "siblings is in the threaded mode.", p);
4932
                }
4933
                if (r < 0) {
11,534✔
4934
                        *exit_status = EXIT_CGROUP;
×
4935
                        return log_error_errno(r, "Failed to attach to cgroup %s: %m", p);
×
4936
                }
4937
        }
4938

4939
        if (context->network_namespace_path && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
11,534✔
4940
                r = open_shareable_ns_path(runtime->shared->netns_storage_socket, context->network_namespace_path, CLONE_NEWNET);
×
4941
                if (r < 0) {
×
4942
                        *exit_status = EXIT_NETWORK;
×
4943
                        return log_error_errno(r, "Failed to open network namespace path %s: %m", context->network_namespace_path);
×
4944
                }
4945
        }
4946

4947
        if (context->ipc_namespace_path && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
11,534✔
4948
                r = open_shareable_ns_path(runtime->shared->ipcns_storage_socket, context->ipc_namespace_path, CLONE_NEWIPC);
×
4949
                if (r < 0) {
×
4950
                        *exit_status = EXIT_NAMESPACE;
×
4951
                        return log_error_errno(r, "Failed to open IPC namespace path %s: %m", context->ipc_namespace_path);
×
4952
                }
4953
        }
4954

4955
        r = setup_input(context, params, socket_fd, named_iofds);
11,534✔
4956
        if (r < 0) {
11,534✔
4957
                *exit_status = EXIT_STDIN;
×
4958
                return log_error_errno(r, "Failed to set up standard input: %m");
×
4959
        }
4960

4961
        _cleanup_free_ char *fname = NULL;
25✔
4962
        r = path_extract_filename(command->path, &fname);
11,534✔
4963
        if (r < 0) {
11,534✔
4964
                *exit_status = EXIT_STDOUT;
×
4965
                return log_error_errno(r, "Failed to extract filename from path %s: %m", command->path);
×
4966
        }
4967

4968
        r = setup_output(context, params, STDOUT_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
11,534✔
4969
        if (r < 0) {
11,534✔
4970
                *exit_status = EXIT_STDOUT;
×
4971
                return log_error_errno(r, "Failed to set up standard output: %m");
×
4972
        }
4973

4974
        r = setup_output(context, params, STDERR_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
11,534✔
4975
        if (r < 0) {
11,534✔
4976
                *exit_status = EXIT_STDERR;
×
4977
                return log_error_errno(r, "Failed to set up standard error output: %m");
×
4978
        }
4979

4980
        /* Now that stdin/stdout are definiely opened, properly initialize it with our desired
4981
         * settings. Note: this is a "constructive" reset, it prepares things for us to use. This is
4982
         * different from the "destructive" TTY reset further up. Also note: we apply this on stdin/stdout in
4983
         * case this is a tty, regardless if we opened it ourselves or got it passed in pre-opened. */
4984
        prepare_terminal(context, params);
11,534✔
4985

4986
        if (context->oom_score_adjust_set) {
11,534✔
4987
                /* When we can't make this change due to EPERM, then let's silently skip over it. User
4988
                 * namespaces prohibit write access to this file, and we shouldn't trip up over that. */
4989
                r = set_oom_score_adjust(context->oom_score_adjust);
1,306✔
4990
                if (ERRNO_IS_NEG_PRIVILEGE(r))
1,306✔
4991
                        log_debug_errno(r, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
×
4992
                else if (r < 0) {
1,306✔
4993
                        *exit_status = EXIT_OOM_ADJUST;
×
4994
                        return log_error_errno(r, "Failed to adjust OOM setting: %m");
×
4995
                }
4996
        }
4997

4998
        if (context->coredump_filter_set) {
11,534✔
4999
                r = set_coredump_filter(context->coredump_filter);
2✔
5000
                if (ERRNO_IS_NEG_PRIVILEGE(r))
2✔
5001
                        log_debug_errno(r, "Failed to adjust coredump_filter, ignoring: %m");
×
5002
                else if (r < 0) {
2✔
5003
                        *exit_status = EXIT_LIMITS;
×
5004
                        return log_error_errno(r, "Failed to adjust coredump_filter: %m");
×
5005
                }
5006
        }
5007

5008
        if (context->cpu_sched_set) {
11,534✔
5009
                struct sched_attr attr = {
×
5010
                        .size = sizeof(attr),
5011
                        .sched_policy = context->cpu_sched_policy,
×
5012
                        .sched_priority = context->cpu_sched_priority,
×
5013
                        .sched_flags = context->cpu_sched_reset_on_fork ? SCHED_FLAG_RESET_ON_FORK : 0,
×
5014
                };
5015

5016
                r = sched_setattr(/* pid= */ 0, &attr, /* flags= */ 0);
×
5017
                if (r < 0) {
×
5018
                        *exit_status = EXIT_SETSCHEDULER;
×
5019
                        return log_error_errno(errno, "Failed to set up CPU scheduling: %m");
×
5020
                }
5021
        }
5022

5023
        /*
5024
         * Set nice value _after_ the call to sched_setattr() because struct sched_attr includes sched_nice
5025
         * which we do not set, thus it will clobber any previously set nice value. Scheduling policy might
5026
         * be reasonably set together with nice value e.g. in case of SCHED_BATCH (see sched(7)).
5027
         * It would be ideal to set both with the same call, but we cannot easily do so because of all the
5028
         * extra logic in setpriority_closest().
5029
         */
5030
        if (context->nice_set) {
11,534✔
5031
                r = setpriority_closest(context->nice);
15✔
5032
                if (r < 0) {
15✔
5033
                        *exit_status = EXIT_NICE;
×
5034
                        return log_error_errno(r, "Failed to set up process scheduling priority (nice level): %m");
×
5035
                }
5036
        }
5037

5038
        if (context->cpu_affinity_from_numa || context->cpu_set.set) {
11,534✔
5039
                _cleanup_(cpu_set_reset) CPUSet converted_cpu_set = {};
2✔
5040
                const CPUSet *cpu_set;
2✔
5041

5042
                if (context->cpu_affinity_from_numa) {
2✔
5043
                        r = exec_context_cpu_affinity_from_numa(context, &converted_cpu_set);
2✔
5044
                        if (r < 0) {
2✔
5045
                                *exit_status = EXIT_CPUAFFINITY;
×
5046
                                return log_error_errno(r, "Failed to derive CPU affinity mask from NUMA mask: %m");
×
5047
                        }
5048

5049
                        cpu_set = &converted_cpu_set;
5050
                } else
5051
                        cpu_set = &context->cpu_set;
×
5052

5053
                if (sched_setaffinity(0, cpu_set->allocated, cpu_set->set) < 0) {
2✔
5054
                        *exit_status = EXIT_CPUAFFINITY;
×
5055
                        return log_error_errno(errno, "Failed to set up CPU affinity: %m");
×
5056
                }
5057
        }
5058

5059
        if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) {
11,534✔
5060
                r = apply_numa_policy(&context->numa_policy);
19✔
5061
                if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
19✔
5062
                        log_debug_errno(r, "NUMA support not available, ignoring.");
×
5063
                else if (r < 0) {
19✔
5064
                        *exit_status = EXIT_NUMA_POLICY;
2✔
5065
                        return log_error_errno(r, "Failed to set NUMA memory policy: %m");
2✔
5066
                }
5067
        }
5068

5069
        if (context->ioprio_set)
11,532✔
5070
                if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
8✔
5071
                        *exit_status = EXIT_IOPRIO;
×
5072
                        return log_error_errno(errno, "Failed to set up IO scheduling priority: %m");
×
5073
                }
5074

5075
        if (context->timer_slack_nsec != NSEC_INFINITY)
11,532✔
5076
                if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
×
5077
                        *exit_status = EXIT_TIMERSLACK;
×
5078
                        return log_error_errno(errno, "Failed to set up timer slack: %m");
×
5079
                }
5080

5081
        if (context->personality != PERSONALITY_INVALID) {
11,532✔
5082
                r = safe_personality(context->personality);
×
5083
                if (r < 0) {
×
5084
                        *exit_status = EXIT_PERSONALITY;
×
5085
                        return log_error_errno(r, "Failed to set up execution domain (personality): %m");
×
5086
                }
5087
        }
5088

5089
        if (context->memory_ksm >= 0)
11,532✔
5090
                if (prctl(PR_SET_MEMORY_MERGE, context->memory_ksm, 0, 0, 0) < 0) {
×
5091
                        if (ERRNO_IS_NOT_SUPPORTED(errno))
×
5092
                                log_debug_errno(errno, "KSM support not available, ignoring.");
×
5093
                        else {
5094
                                *exit_status = EXIT_KSM;
×
5095
                                return log_error_errno(errno, "Failed to set KSM: %m");
×
5096
                        }
5097
                }
5098

5099
#if ENABLE_UTMP
5100
        if (context->utmp_id) {
11,532✔
5101
                _cleanup_free_ char *username_alloc = NULL;
155✔
5102

5103
                if (!username && context->utmp_mode == EXEC_UTMP_USER) {
155✔
5104
                        username_alloc = uid_to_name(uid_is_valid(uid) ? uid : saved_uid);
1✔
5105
                        if (!username_alloc) {
1✔
5106
                                *exit_status = EXIT_USER;
×
5107
                                return log_oom();
×
5108
                        }
5109
                }
5110

5111
                const char *line = context->tty_path ?
×
5112
                        (path_startswith(context->tty_path, "/dev/") ?: context->tty_path) :
155✔
5113
                        NULL;
5114
                utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
155✔
5115
                                      line,
5116
                                      context->utmp_mode == EXEC_UTMP_INIT  ? INIT_PROCESS :
155✔
5117
                                      context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
7✔
5118
                                      USER_PROCESS,
5119
                                      username ?: username_alloc);
155✔
5120
        }
5121
#endif
5122

5123
        if (uid_is_valid(uid)) {
11,532✔
5124
                r = chown_terminal(STDIN_FILENO, uid);
2,672✔
5125
                if (r < 0) {
2,672✔
5126
                        *exit_status = EXIT_STDIN;
×
5127
                        return log_error_errno(r, "Failed to change ownership of terminal: %m");
×
5128
                }
5129
        }
5130

5131
        /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted
5132
         * from it. */
5133
        needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
11,532✔
5134

5135
        if (params->cgroup_path) {
11,532✔
5136
                /* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1
5137
                 * this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not
5138
                 * safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only
5139
                 * touch a single hierarchy too. */
5140

5141
                if (params->flags & EXEC_CGROUP_DELEGATE) {
11,532✔
5142
                        _cleanup_free_ char *p = NULL;
667✔
5143

5144
                        r = cg_set_access(params->cgroup_path, uid, gid);
667✔
5145
                        if (r < 0) {
667✔
5146
                                *exit_status = EXIT_CGROUP;
×
5147
                                return log_error_errno(r, "Failed to adjust control group access: %m");
×
5148
                        }
5149

5150
                        r = exec_params_get_cgroup_path(params, cgroup_context, &p);
667✔
5151
                        if (r < 0) {
667✔
5152
                                *exit_status = EXIT_CGROUP;
×
5153
                                return log_error_errno(r, "Failed to acquire cgroup path: %m");
×
5154
                        }
5155
                        if (r > 0) {
667✔
5156
                                r = cg_set_access_recursive(p, uid, gid);
326✔
5157
                                if (r < 0) {
326✔
5158
                                        *exit_status = EXIT_CGROUP;
×
5159
                                        return log_error_errno(r, "Failed to adjust control subgroup access: %m");
×
5160
                                }
5161
                        }
5162
                }
5163

5164
                if (is_pressure_supported() > 0) {
11,532✔
5165
                        if (cgroup_context_want_memory_pressure(cgroup_context)) {
11,532✔
5166
                                r = cg_get_path("memory", params->cgroup_path, "memory.pressure", &memory_pressure_path);
11,135✔
5167
                                if (r < 0) {
11,135✔
5168
                                        *exit_status = EXIT_MEMORY;
×
5169
                                        return log_oom();
×
5170
                                }
5171

5172
                                r = chmod_and_chown(memory_pressure_path, 0644, uid, gid);
11,135✔
5173
                                if (r < 0) {
11,135✔
5174
                                        log_full_errno(r == -ENOENT || ERRNO_IS_PRIVILEGE(r) ? LOG_DEBUG : LOG_WARNING, r,
2✔
5175
                                                       "Failed to adjust ownership of '%s', ignoring: %m", memory_pressure_path);
5176
                                        memory_pressure_path = mfree(memory_pressure_path);
1✔
5177
                                }
5178
                                /* First we use the current cgroup path to chmod and chown the memory pressure path, then pass the path relative
5179
                                 * to the cgroup namespace to environment variables and mounts. If chown/chmod fails, we should not pass memory
5180
                                 * pressure path environment variable or read-write mount to the unit. This is why we check if
5181
                                 * memory_pressure_path != NULL in the conditional below. */
5182
                                if (memory_pressure_path && needs_sandboxing && exec_needs_cgroup_namespace(context)) {
11,135✔
5183
                                        memory_pressure_path = mfree(memory_pressure_path);
13✔
5184
                                        r = cg_get_path("memory", "", "memory.pressure", &memory_pressure_path);
13✔
5185
                                        if (r < 0) {
13✔
5186
                                                *exit_status = EXIT_MEMORY;
×
5187
                                                return log_oom();
×
5188
                                        }
5189
                                }
5190
                        } else if (cgroup_context->memory_pressure_watch == CGROUP_PRESSURE_WATCH_NO) {
397✔
5191
                                memory_pressure_path = strdup("/dev/null"); /* /dev/null is explicit indicator for turning of memory pressure watch */
×
5192
                                if (!memory_pressure_path) {
×
5193
                                        *exit_status = EXIT_MEMORY;
×
5194
                                        return log_oom();
×
5195
                                }
5196
                        }
5197
                }
5198
        }
5199

5200
        needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
11,532✔
5201

5202
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
69,187✔
5203
                r = setup_exec_directory(context, params, uid, gid, dt, needs_mount_namespace, exit_status);
57,656✔
5204
                if (r < 0)
57,656✔
5205
                        return log_error_errno(r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
1✔
5206
        }
5207

5208
        r = exec_setup_credentials(context, params, params->unit_id, uid, gid);
11,531✔
5209
        if (r < 0) {
9,583✔
5210
                *exit_status = EXIT_CREDENTIALS;
×
5211
                return log_error_errno(r, "Failed to set up credentials: %m");
×
5212
        }
5213

5214
        r = build_environment(
9,583✔
5215
                        context,
5216
                        params,
5217
                        cgroup_context,
5218
                        n_fds,
5219
                        pwent_home,
5220
                        username,
5221
                        shell,
5222
                        journal_stream_dev,
5223
                        journal_stream_ino,
5224
                        memory_pressure_path,
5225
                        needs_sandboxing,
5226
                        &our_env);
5227
        if (r < 0) {
9,583✔
5228
                *exit_status = EXIT_MEMORY;
×
5229
                return log_oom();
×
5230
        }
5231

5232
        r = build_pass_environment(context, &pass_env);
9,583✔
5233
        if (r < 0) {
9,583✔
5234
                *exit_status = EXIT_MEMORY;
×
5235
                return log_oom();
×
5236
        }
5237

5238
        /* The $PATH variable is set to the default path in params->environment. However, this is overridden
5239
         * if user-specified fields have $PATH set. The intention is to also override $PATH if the unit does
5240
         * not specify PATH but the unit has ExecSearchPath. */
5241
        if (!strv_isempty(context->exec_search_path)) {
9,583✔
5242
                _cleanup_free_ char *joined = NULL;
×
5243

5244
                joined = strv_join(context->exec_search_path, ":");
×
5245
                if (!joined) {
×
5246
                        *exit_status = EXIT_MEMORY;
×
5247
                        return log_oom();
×
5248
                }
5249

5250
                r = strv_env_assign(&joined_exec_search_path, "PATH", joined);
×
5251
                if (r < 0) {
×
5252
                        *exit_status = EXIT_MEMORY;
×
5253
                        return log_oom();
×
5254
                }
5255
        }
5256

5257
        accum_env = strv_env_merge(params->environment,
9,583✔
5258
                                   our_env,
5259
                                   joined_exec_search_path,
5260
                                   pass_env,
5261
                                   context->environment,
5262
                                   params->files_env);
5263
        if (!accum_env) {
9,583✔
5264
                *exit_status = EXIT_MEMORY;
×
5265
                return log_oom();
×
5266
        }
5267
        strv_env_clean(accum_env);
9,583✔
5268

5269
        (void) umask(context->umask);
9,583✔
5270

5271
        r = setup_term_environment(context, &accum_env);
9,583✔
5272
        if (r < 0) {
9,583✔
5273
                *exit_status = EXIT_MEMORY;
×
5274
                return log_error_errno(r, "Failed to construct $TERM: %m");
×
5275
        }
5276

5277
        r = setup_keyring(context, params, uid, gid);
9,583✔
5278
        if (r < 0) {
9,583✔
5279
                *exit_status = EXIT_KEYRING;
×
5280
                return log_error_errno(r, "Failed to set up kernel keyring: %m");
×
5281
        }
5282

5283
        /* We need setresuid() if the caller asked us to apply sandboxing and the command isn't explicitly
5284
         * excepted from either whole sandboxing or just setresuid() itself. */
5285
        needs_setuid = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & (EXEC_COMMAND_FULLY_PRIVILEGED|EXEC_COMMAND_NO_SETUID));
9,583✔
5286

5287
        uint64_t capability_ambient_set = context->capability_ambient_set;
9,583✔
5288

5289
        /* Check CAP_SYS_ADMIN before we enter user namespace to see if we can mount /proc even though its masked. */
5290
        have_cap_sys_admin = have_effective_cap(CAP_SYS_ADMIN) > 0;
9,583✔
5291

5292
        if (needs_sandboxing) {
9,583✔
5293
                /* MAC enablement checks need to be done before a new mount ns is created, as they rely on
5294
                 * /sys being present. The actual MAC context application will happen later, as late as
5295
                 * possible, to avoid impacting our own code paths. */
5296

5297
#if HAVE_SELINUX
5298
                use_selinux = mac_selinux_use();
5299
#endif
5300
#if ENABLE_SMACK
5301
                use_smack = mac_smack_use();
9,583✔
5302
#endif
5303
#if HAVE_APPARMOR
5304
                if (mac_apparmor_use()) {
5305
                        r = dlopen_libapparmor();
5306
                        if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r))
5307
                                log_warning_errno(r, "Failed to load libapparmor, ignoring: %m");
5308
                        use_apparmor = r >= 0;
5309
                }
5310
#endif
5311
        }
5312

5313
        if (needs_sandboxing) {
9,583✔
5314
                int which_failed;
9,583✔
5315

5316
                /* Let's set the resource limits before we call into PAM, so that pam_limits wins over what
5317
                 * is set here. (See below.) */
5318

5319
                r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed);
9,583✔
5320
                if (r < 0) {
9,583✔
5321
                        *exit_status = EXIT_LIMITS;
×
5322
                        return log_error_errno(r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
×
5323
                }
5324
        }
5325

5326
        if (needs_setuid && context->pam_name && username) {
9,583✔
5327
                /* Let's call into PAM after we set up our own idea of resource limits so that pam_limits
5328
                 * wins here. (See above.) */
5329

5330
                /* All fds passed in the fds array will be closed in the pam child process. */
5331
                r = setup_pam(context, params, username, uid, gid, &accum_env, params->fds, n_fds, params->exec_fd);
402✔
5332
                if (r < 0) {
402✔
5333
                        *exit_status = EXIT_PAM;
×
5334
                        return log_error_errno(r, "Failed to set up PAM session: %m");
×
5335
                }
5336

5337
                /* PAM modules might have set some ambient caps. Query them here and merge them into
5338
                 * the caps we want to set in the end, so that we don't end up unsetting them. */
5339
                uint64_t ambient_after_pam;
402✔
5340
                r = capability_get_ambient(&ambient_after_pam);
402✔
5341
                if (r < 0) {
402✔
5342
                        *exit_status = EXIT_CAPABILITIES;
×
5343
                        return log_error_errno(r, "Failed to query ambient caps: %m");
×
5344
                }
5345

5346
                capability_ambient_set |= ambient_after_pam;
402✔
5347

5348
                ngids_after_pam = getgroups_alloc(&gids_after_pam);
402✔
5349
                if (ngids_after_pam < 0) {
402✔
5350
                        *exit_status = EXIT_GROUP;
×
5351
                        return log_error_errno(ngids_after_pam, "Failed to obtain groups after setting up PAM: %m");
×
5352
                }
5353
        }
5354

5355
        if (needs_sandboxing && !have_cap_sys_admin && exec_context_needs_cap_sys_admin(context)) {
9,583✔
5356
                /* If we're unprivileged, set up the user namespace first to enable use of the other namespaces.
5357
                 * Users with CAP_SYS_ADMIN can set up user namespaces last because they will be able to
5358
                 * set up all of the other namespaces (i.e. network, mount, UTS) without a user namespace. */
5359
                PrivateUsers pu = exec_context_get_effective_private_users(context, params);
27✔
5360
                if (pu == PRIVATE_USERS_NO)
27✔
5361
                        pu = PRIVATE_USERS_SELF;
23✔
5362

5363
                /* The kernel requires /proc/pid/setgroups be set to "deny" prior to writing /proc/pid/gid_map in
5364
                 * unprivileged user namespaces. */
5365
                r = setup_private_users(pu, saved_uid, saved_gid, uid, gid, /* allow_setgroups= */ false);
27✔
5366
                /* If it was requested explicitly and we can't set it up, fail early. Otherwise, continue and let
5367
                 * the actual requested operations fail (or silently continue). */
5368
                if (r < 0 && context->private_users != PRIVATE_USERS_NO) {
27✔
5369
                        *exit_status = EXIT_USER;
×
5370
                        return log_error_errno(r, "Failed to set up user namespacing for unprivileged user: %m");
×
5371
                }
5372
                if (r < 0)
×
5373
                        log_info_errno(r, "Failed to set up user namespacing for unprivileged user, ignoring: %m");
×
5374
                else {
5375
                        assert(r > 0);
27✔
5376
                        userns_set_up = true;
27✔
5377
                        log_debug("Set up unprivileged user namespace");
27✔
5378
                }
5379
        }
5380

5381
        /* Call setup_delegated_namespaces() the first time to unshare all non-delegated namespaces. */
5382
        r = setup_delegated_namespaces(
9,583✔
5383
                        context,
5384
                        params,
5385
                        runtime,
5386
                        /* delegate= */ false,
5387
                        memory_pressure_path,
5388
                        uid,
5389
                        gid,
5390
                        command,
5391
                        needs_sandboxing,
5392
                        have_cap_sys_admin,
5393
                        exit_status);
5394
        if (r < 0)
9,579✔
5395
                return r;
5396

5397
        /* Drop groups as early as possible.
5398
         * This needs to be done after PrivateDevices=yes setup as device nodes should be owned by the host's root.
5399
         * For non-root in a userns, devices will be owned by the user/group before the group change, and nobody. */
5400
        if (needs_setuid) {
9,563✔
5401
                _cleanup_free_ gid_t *gids_to_enforce = NULL;
9,563✔
5402
                int ngids_to_enforce;
9,563✔
5403

5404
                ngids_to_enforce = merge_gid_lists(gids,
9,563✔
5405
                                                   ngids,
5406
                                                   gids_after_pam,
5407
                                                   ngids_after_pam,
5408
                                                   &gids_to_enforce);
5409
                if (ngids_to_enforce < 0) {
9,563✔
5410
                        *exit_status = EXIT_GROUP;
×
5411
                        return log_error_errno(ngids_to_enforce, "Failed to merge group lists. Group membership might be incorrect: %m");
×
5412
                }
5413

5414
                r = enforce_groups(gid, gids_to_enforce, ngids_to_enforce);
9,563✔
5415
                if (r < 0) {
9,563✔
5416
                        *exit_status = EXIT_GROUP;
1✔
5417
                        return log_error_errno(r, "Changing group credentials failed: %m");
1✔
5418
                }
5419
        }
5420

5421
        /* If the user namespace was not set up above, try to do it now.
5422
         * It's preferred to set up the user namespace later (after all other namespaces) so as not to be
5423
         * restricted by rules pertaining to combining user namespaces with other namespaces (e.g. in the
5424
         * case of mount namespaces being less privileged when the mount point list is copied from a
5425
         * different user namespace). */
5426

5427
        if (needs_sandboxing && !userns_set_up) {
9,562✔
5428
                PrivateUsers pu = exec_context_get_effective_private_users(context, params);
9,540✔
5429

5430
                r = setup_private_users(pu, saved_uid, saved_gid, uid, gid,
9,540✔
5431
                                        /* allow_setgroups= */ pu == PRIVATE_USERS_FULL);
5432
                if (r < 0) {
9,540✔
5433
                        *exit_status = EXIT_USER;
×
5434
                        return log_error_errno(r, "Failed to set up user namespacing: %m");
×
5435
                }
5436
                if (r > 0)
9,540✔
5437
                        log_debug("Set up privileged user namespace");
25✔
5438
        }
5439

5440
        /* Call setup_delegated_namespaces() the second time to unshare all delegated namespaces. */
5441
        r = setup_delegated_namespaces(
9,562✔
5442
                        context,
5443
                        params,
5444
                        runtime,
5445
                        /* delegate= */ true,
5446
                        memory_pressure_path,
5447
                        uid,
5448
                        gid,
5449
                        command,
5450
                        needs_sandboxing,
5451
                        have_cap_sys_admin,
5452
                        exit_status);
5453
        if (r < 0)
9,558✔
5454
                return r;
5455

5456
        /* Now that the mount namespace has been set up and privileges adjusted, let's look for the thing we
5457
         * shall execute. */
5458

5459
        const char *path = command->path;
9,558✔
5460

5461
        if (FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL)) {
9,558✔
5462
                if (shell_is_placeholder(shell)) {
13✔
5463
                        log_debug("Shell prefixing requested for user without default shell, using /bin/sh: %s",
2✔
5464
                                  strna(username));
5465
                        assert(streq(path, _PATH_BSHELL));
2✔
5466
                } else
5467
                        path = shell;
5468
        }
5469

5470
        _cleanup_free_ char *executable = NULL;
5✔
5471
        _cleanup_close_ int executable_fd = -EBADF;
5✔
5472
        r = find_executable_full(path, /* root= */ NULL, context->exec_search_path, false, &executable, &executable_fd);
9,558✔
5473
        if (r < 0) {
9,558✔
5474
                *exit_status = EXIT_EXEC;
1✔
5475
                log_struct_errno(LOG_NOTICE, r,
1✔
5476
                                 LOG_MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED_STR),
5477
                                 LOG_EXEC_MESSAGE(params, "Unable to locate executable '%s': %m", path),
5478
                                 LOG_ITEM("EXECUTABLE=%s", path));
5479
                /* If the error will be ignored by manager, tune down the log level here. Missing executable
5480
                 * is very much expected in this case. */
5481
                return r != -ENOMEM && FLAGS_SET(command->flags, EXEC_COMMAND_IGNORE_FAILURE) ? 1 : r;
1✔
5482
        }
5483

5484
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &executable_fd);
9,557✔
5485
        if (r < 0) {
9,557✔
5486
                *exit_status = EXIT_FDS;
×
5487
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
5488
        }
5489

5490
#if HAVE_SELINUX
5491
        if (needs_sandboxing && use_selinux && params->selinux_context_net) {
5492
                int fd = -EBADF;
5493

5494
                if (socket_fd >= 0)
5495
                        fd = socket_fd;
5496
                else if (params->n_socket_fds == 1)
5497
                        /* If stdin is not connected to a socket but we are triggered by exactly one socket unit then we
5498
                         * use context from that fd to compute the label. */
5499
                        fd = params->fds[0];
5500

5501
                if (fd >= 0) {
5502
                        r = mac_selinux_get_child_mls_label(fd, executable, context->selinux_context, &mac_selinux_context_net);
5503
                        if (r < 0) {
5504
                                if (!context->selinux_context_ignore) {
5505
                                        *exit_status = EXIT_SELINUX_CONTEXT;
5506
                                        return log_error_errno(r, "Failed to determine SELinux context: %m");
5507
                                }
5508
                                log_debug_errno(r, "Failed to determine SELinux context, ignoring: %m");
5509
                        }
5510
                }
5511
        }
5512
#endif
5513

5514
        /* We repeat the fd closing here, to make sure that nothing is leaked from the PAM modules. Note that
5515
         * we are more aggressive this time, since we don't need socket_fd and the netns and ipcns fds any
5516
         * more. We do keep exec_fd and handoff_timestamp_fd however, if we have it, since we need to keep
5517
         * them open until the final execve(). But first, close the remaining sockets in the context
5518
         * objects. */
5519

5520
        exec_runtime_close(runtime);
9,557✔
5521
        exec_params_close(params);
9,557✔
5522

5523
        r = close_all_fds(keep_fds, n_keep_fds);
9,557✔
5524
        if (r >= 0)
9,557✔
5525
                r = pack_fds(params->fds, n_fds);
9,557✔
5526
        if (r >= 0)
9,557✔
5527
                r = flag_fds(params->fds, n_socket_fds, n_fds, context->non_blocking);
9,557✔
5528
        if (r < 0) {
9,557✔
5529
                *exit_status = EXIT_FDS;
×
5530
                return log_error_errno(r, "Failed to adjust passed file descriptors: %m");
×
5531
        }
5532

5533
        /* At this point, the fds we want to pass to the program are all ready and set up, with O_CLOEXEC turned off
5534
         * and at the right fd numbers. The are no other fds open, with one exception: the exec_fd if it is defined,
5535
         * and it has O_CLOEXEC set, after all we want it to be closed by the execve(), so that our parent knows we
5536
         * came this far. */
5537

5538
        secure_bits = context->secure_bits;
9,557✔
5539

5540
        if (needs_sandboxing) {
9,557✔
5541
                uint64_t bset;
9,557✔
5542

5543
                /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested.
5544
                 * (Note this is placed after the general resource limit initialization, see above, in order
5545
                 * to take precedence.) */
5546
                if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
9,557✔
5547
                        if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
1,493✔
5548
                                *exit_status = EXIT_LIMITS;
×
5549
                                return log_error_errno(errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m");
×
5550
                        }
5551
                }
5552

5553
#if ENABLE_SMACK
5554
                /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the
5555
                 * process. This is the latest place before dropping capabilities. Other MAC context are set later. */
5556
                if (use_smack) {
9,557✔
5557
                        r = setup_smack(context, params, executable_fd);
×
5558
                        if (r < 0 && !context->smack_process_label_ignore) {
×
5559
                                *exit_status = EXIT_SMACK_PROCESS_LABEL;
×
5560
                                return log_error_errno(r, "Failed to set SMACK process label: %m");
×
5561
                        }
5562
                }
5563
#endif
5564

5565
                bset = context->capability_bounding_set;
9,557✔
5566

5567
#if HAVE_SECCOMP
5568
                /* If the service has any form of a seccomp filter and it allows dropping privileges, we'll
5569
                 * keep the needed privileges to apply it even if we're not root. */
5570
                if (needs_setuid &&
19,114✔
5571
                    uid_is_valid(uid) &&
11,576✔
5572
                    context_has_seccomp(context) &&
2,770✔
5573
                    seccomp_allows_drop_privileges(context)) {
751✔
5574
                        keep_seccomp_privileges = true;
751✔
5575

5576
                        if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
751✔
5577
                                *exit_status = EXIT_USER;
×
5578
                                return log_error_errno(errno, "Failed to enable keep capabilities flag: %m");
×
5579
                        }
5580

5581
                        /* Save the current bounding set so we can restore it after applying the seccomp
5582
                         * filter */
5583
                        saved_bset = bset;
751✔
5584
                        bset |= (UINT64_C(1) << CAP_SYS_ADMIN) |
751✔
5585
                                (UINT64_C(1) << CAP_SETPCAP);
5586
                }
5587
#endif
5588

5589
                if (!cap_test_all(bset)) {
9,557✔
5590
                        r = capability_bounding_set_drop(bset, /* right_now= */ false);
1,619✔
5591
                        if (r < 0) {
1,619✔
5592
                                *exit_status = EXIT_CAPABILITIES;
×
5593
                                return log_error_errno(r, "Failed to drop capabilities: %m");
×
5594
                        }
5595
                }
5596

5597
                /* Ambient capabilities are cleared during setresuid() (in enforce_user()) even with
5598
                 * keep-caps set.
5599
                 *
5600
                 * To be able to raise the ambient capabilities after setresuid() they have to be added to
5601
                 * the inherited set and keep caps has to be set (done in enforce_user()).  After setresuid()
5602
                 * the ambient capabilities can be raised as they are present in the permitted and
5603
                 * inhertiable set. However it is possible that someone wants to set ambient capabilities
5604
                 * without changing the user, so we also set the ambient capabilities here.
5605
                 *
5606
                 * The requested ambient capabilities are raised in the inheritable set if the second
5607
                 * argument is true. */
5608
                if (capability_ambient_set != 0) {
9,557✔
5609
                        r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ true);
746✔
5610
                        if (r < 0) {
746✔
5611
                                *exit_status = EXIT_CAPABILITIES;
×
5612
                                return log_error_errno(r, "Failed to apply ambient capabilities (before UID change): %m");
×
5613
                        }
5614
                }
5615
        }
5616

5617
        /* chroot to root directory first, before we lose the ability to chroot */
5618
        r = apply_root_directory(context, params, runtime, needs_mount_namespace, exit_status);
9,557✔
5619
        if (r < 0)
9,557✔
5620
                return log_error_errno(r, "Chrooting to the requested root directory failed: %m");
×
5621

5622
        if (needs_setuid) {
9,557✔
5623
                if (uid_is_valid(uid)) {
9,557✔
5624
                        r = enforce_user(context, uid, capability_ambient_set);
2,019✔
5625
                        if (r < 0) {
2,019✔
5626
                                *exit_status = EXIT_USER;
×
5627
                                return log_error_errno(r, "Failed to change UID to " UID_FMT ": %m", uid);
×
5628
                        }
5629

5630
                        if (keep_seccomp_privileges) {
2,019✔
5631
                                if (!BIT_SET(capability_ambient_set, CAP_SETUID)) {
751✔
5632
                                        r = drop_capability(CAP_SETUID);
751✔
5633
                                        if (r < 0) {
751✔
5634
                                                *exit_status = EXIT_USER;
×
5635
                                                return log_error_errno(r, "Failed to drop CAP_SETUID: %m");
×
5636
                                        }
5637
                                }
5638

5639
                                r = keep_capability(CAP_SYS_ADMIN);
751✔
5640
                                if (r < 0) {
751✔
5641
                                        *exit_status = EXIT_USER;
×
5642
                                        return log_error_errno(r, "Failed to keep CAP_SYS_ADMIN: %m");
×
5643
                                }
5644

5645
                                r = keep_capability(CAP_SETPCAP);
751✔
5646
                                if (r < 0) {
751✔
5647
                                        *exit_status = EXIT_USER;
×
5648
                                        return log_error_errno(r, "Failed to keep CAP_SETPCAP: %m");
×
5649
                                }
5650
                        }
5651

5652
                        if (capability_ambient_set != 0) {
2,019✔
5653

5654
                                /* Raise the ambient capabilities after user change. */
5655
                                r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ false);
743✔
5656
                                if (r < 0) {
743✔
5657
                                        *exit_status = EXIT_CAPABILITIES;
×
5658
                                        return log_error_errno(r, "Failed to apply ambient capabilities (after UID change): %m");
×
5659
                                }
5660
                        }
5661
                }
5662
        }
5663

5664
        /* Apply working directory here, because the working directory might be on NFS and only the user
5665
         * running this service might have the correct privilege to change to the working directory. Also, it
5666
         * is absolutely 💣 crucial 💣 we applied all mount namespacing rearrangements before this, so that
5667
         * the cwd cannot be used to pin directories outside of the sandbox. */
5668
        r = apply_working_directory(context, params, runtime, pwent_home, accum_env);
9,557✔
5669
        if (r < 0) {
9,557✔
5670
                *exit_status = EXIT_CHDIR;
1✔
5671
                return log_error_errno(r, "Changing to the requested working directory failed: %m");
1✔
5672
        }
5673

5674
        if (needs_sandboxing) {
9,556✔
5675
                /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to
5676
                 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
5677
                 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
5678
                 * are restricted. */
5679

5680
#if HAVE_SELINUX
5681
                if (use_selinux) {
5682
                        char *exec_context = mac_selinux_context_net ?: context->selinux_context;
5683

5684
                        if (exec_context) {
5685
                                r = setexeccon(exec_context);
5686
                                if (r < 0) {
5687
                                        if (!context->selinux_context_ignore) {
5688
                                                *exit_status = EXIT_SELINUX_CONTEXT;
5689
                                                return log_error_errno(r, "Failed to change SELinux context to %s: %m", exec_context);
5690
                                        }
5691
                                        log_debug_errno(r, "Failed to change SELinux context to %s, ignoring: %m", exec_context);
5692
                                }
5693
                        }
5694
                }
5695
#endif
5696

5697
#if HAVE_APPARMOR
5698
                if (use_apparmor && context->apparmor_profile) {
5699
                        r = ASSERT_PTR(sym_aa_change_onexec)(context->apparmor_profile);
5700
                        if (r < 0 && !context->apparmor_profile_ignore) {
5701
                                *exit_status = EXIT_APPARMOR_PROFILE;
5702
                                return log_error_errno(errno, "Failed to prepare AppArmor profile change to %s: %m",
5703
                                                       context->apparmor_profile);
5704
                        }
5705
                }
5706
#endif
5707

5708
                /* PR_GET_SECUREBITS is not privileged, while PR_SET_SECUREBITS is. So to suppress potential
5709
                 * EPERMs we'll try not to call PR_SET_SECUREBITS unless necessary. Setting securebits
5710
                 * requires CAP_SETPCAP. */
5711
                if (prctl(PR_GET_SECUREBITS) != secure_bits) {
9,556✔
5712
                        /* CAP_SETPCAP is required to set securebits. This capability is raised into the
5713
                         * effective set here.
5714
                         *
5715
                         * The effective set is overwritten during execve() with the following values:
5716
                         *
5717
                         * - ambient set (for non-root processes)
5718
                         *
5719
                         * - (inheritable | bounding) set for root processes)
5720
                         *
5721
                         * Hence there is no security impact to raise it in the effective set before execve
5722
                         */
5723
                        r = capability_gain_cap_setpcap(/* ret_before_caps = */ NULL);
803✔
5724
                        if (r < 0) {
803✔
5725
                                *exit_status = EXIT_CAPABILITIES;
×
5726
                                return log_error_errno(r, "Failed to gain CAP_SETPCAP for setting secure bits");
×
5727
                        }
5728
                        if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
803✔
5729
                                *exit_status = EXIT_SECUREBITS;
×
5730
                                return log_error_errno(errno, "Failed to set process secure bits: %m");
×
5731
                        }
5732
                }
5733

5734
                if (context_has_no_new_privileges(context))
9,556✔
5735
                        if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
1,417✔
5736
                                *exit_status = EXIT_NO_NEW_PRIVILEGES;
×
5737
                                return log_error_errno(errno, "Failed to disable new privileges: %m");
×
5738
                        }
5739

5740
#if HAVE_SECCOMP
5741
                r = apply_address_families(context, params);
9,556✔
5742
                if (r < 0) {
9,556✔
5743
                        *exit_status = EXIT_ADDRESS_FAMILIES;
×
5744
                        return log_error_errno(r, "Failed to restrict address families: %m");
×
5745
                }
5746

5747
                r = apply_memory_deny_write_execute(context, params);
9,556✔
5748
                if (r < 0) {
9,556✔
5749
                        *exit_status = EXIT_SECCOMP;
×
5750
                        return log_error_errno(r, "Failed to disable writing to executable memory: %m");
×
5751
                }
5752

5753
                r = apply_restrict_realtime(context, params);
9,556✔
5754
                if (r < 0) {
9,556✔
5755
                        *exit_status = EXIT_SECCOMP;
×
5756
                        return log_error_errno(r, "Failed to apply realtime restrictions: %m");
×
5757
                }
5758

5759
                r = apply_restrict_suid_sgid(context, params);
9,556✔
5760
                if (r < 0) {
9,556✔
5761
                        *exit_status = EXIT_SECCOMP;
×
5762
                        return log_error_errno(r, "Failed to apply SUID/SGID restrictions: %m");
×
5763
                }
5764

5765
                r = apply_restrict_namespaces(context, params);
9,556✔
5766
                if (r < 0) {
9,556✔
5767
                        *exit_status = EXIT_SECCOMP;
×
5768
                        return log_error_errno(r, "Failed to apply namespace restrictions: %m");
×
5769
                }
5770

5771
                r = apply_protect_sysctl(context, params);
9,556✔
5772
                if (r < 0) {
9,556✔
5773
                        *exit_status = EXIT_SECCOMP;
×
5774
                        return log_error_errno(r, "Failed to apply sysctl restrictions: %m");
×
5775
                }
5776

5777
                r = apply_protect_kernel_modules(context, params);
9,556✔
5778
                if (r < 0) {
9,556✔
5779
                        *exit_status = EXIT_SECCOMP;
×
5780
                        return log_error_errno(r, "Failed to apply module loading restrictions: %m");
×
5781
                }
5782

5783
                r = apply_protect_kernel_logs(context, params);
9,556✔
5784
                if (r < 0) {
9,556✔
5785
                        *exit_status = EXIT_SECCOMP;
×
5786
                        return log_error_errno(r, "Failed to apply kernel log restrictions: %m");
×
5787
                }
5788

5789
                r = apply_protect_clock(context, params);
9,556✔
5790
                if (r < 0) {
9,556✔
5791
                        *exit_status = EXIT_SECCOMP;
×
5792
                        return log_error_errno(r, "Failed to apply clock restrictions: %m");
×
5793
                }
5794

5795
                r = apply_private_devices(context, params);
9,556✔
5796
                if (r < 0) {
9,556✔
5797
                        *exit_status = EXIT_SECCOMP;
×
5798
                        return log_error_errno(r, "Failed to set up private devices: %m");
×
5799
                }
5800

5801
                r = apply_syscall_archs(context, params);
9,556✔
5802
                if (r < 0) {
9,556✔
5803
                        *exit_status = EXIT_SECCOMP;
×
5804
                        return log_error_errno(r, "Failed to apply syscall architecture restrictions: %m");
×
5805
                }
5806

5807
                r = apply_lock_personality(context, params);
9,556✔
5808
                if (r < 0) {
9,556✔
5809
                        *exit_status = EXIT_SECCOMP;
×
5810
                        return log_error_errno(r, "Failed to lock personalities: %m");
×
5811
                }
5812

5813
                r = apply_syscall_log(context, params);
9,556✔
5814
                if (r < 0) {
9,556✔
5815
                        *exit_status = EXIT_SECCOMP;
×
5816
                        return log_error_errno(r, "Failed to apply system call log filters: %m");
×
5817
                }
5818
#endif
5819

5820
#if HAVE_LIBBPF
5821
                r = apply_restrict_filesystems(context, params);
9,556✔
5822
                if (r < 0) {
9,556✔
5823
                        *exit_status = EXIT_BPF;
×
5824
                        return log_error_errno(r, "Failed to restrict filesystems: %m");
×
5825
                }
5826
#endif
5827

5828
#if HAVE_SECCOMP
5829
                /* This really should remain as close to the execve() as possible, to make sure our own code is affected
5830
                 * by the filter as little as possible. */
5831
                r = apply_syscall_filter(context, params);
9,556✔
5832
                if (r < 0) {
9,556✔
5833
                        *exit_status = EXIT_SECCOMP;
×
5834
                        return log_error_errno(r, "Failed to apply system call filters: %m");
×
5835
                }
5836

5837
                if (keep_seccomp_privileges) {
9,556✔
5838
                        /* Restore the capability bounding set with what's expected from the service + the
5839
                         * ambient capabilities hack */
5840
                        if (!cap_test_all(saved_bset)) {
750✔
5841
                                r = capability_bounding_set_drop(saved_bset, /* right_now= */ false);
715✔
5842
                                if (r < 0) {
715✔
5843
                                        *exit_status = EXIT_CAPABILITIES;
×
5844
                                        return log_error_errno(r, "Failed to drop bset capabilities: %m");
×
5845
                                }
5846
                        }
5847

5848
                        /* Only drop CAP_SYS_ADMIN if it's not in the bounding set, otherwise we'll break
5849
                         * applications that use it. */
5850
                        if (!BIT_SET(saved_bset, CAP_SYS_ADMIN)) {
750✔
5851
                                r = drop_capability(CAP_SYS_ADMIN);
280✔
5852
                                if (r < 0) {
280✔
5853
                                        *exit_status = EXIT_USER;
×
5854
                                        return log_error_errno(r, "Failed to drop CAP_SYS_ADMIN: %m");
×
5855
                                }
5856
                        }
5857

5858
                        /* Only drop CAP_SETPCAP if it's not in the bounding set, otherwise we'll break
5859
                         * applications that use it. */
5860
                        if (!BIT_SET(saved_bset, CAP_SETPCAP)) {
750✔
5861
                                r = drop_capability(CAP_SETPCAP);
533✔
5862
                                if (r < 0) {
533✔
5863
                                        *exit_status = EXIT_USER;
×
5864
                                        return log_error_errno(r, "Failed to drop CAP_SETPCAP: %m");
×
5865
                                }
5866
                        }
5867

5868
                        if (prctl(PR_SET_KEEPCAPS, 0) < 0) {
750✔
5869
                                *exit_status = EXIT_USER;
×
5870
                                return log_error_errno(errno, "Failed to drop keep capabilities flag: %m");
×
5871
                        }
5872
                }
5873
#endif
5874

5875
        }
5876

5877
        if (!strv_isempty(context->unset_environment)) {
9,556✔
5878
                char **ee = NULL;
269✔
5879

5880
                ee = strv_env_delete(accum_env, 1, context->unset_environment);
269✔
5881
                if (!ee) {
269✔
5882
                        *exit_status = EXIT_MEMORY;
×
5883
                        return log_oom();
5✔
5884
                }
5885

5886
                strv_free_and_replace(accum_env, ee);
269✔
5887
        }
5888

5889
        _cleanup_strv_free_ char **replaced_argv = NULL, **argv_via_shell = NULL;
3✔
5890
        char **final_argv = FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL) ? strv_skip(command->argv, 1) : command->argv;
9,556✔
5891

5892
        if (final_argv && !FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) {
9,556✔
5893
                _cleanup_strv_free_ char **unset_variables = NULL, **bad_variables = NULL;
9,383✔
5894

5895
                r = replace_env_argv(final_argv, accum_env, &replaced_argv, &unset_variables, &bad_variables);
9,383✔
5896
                if (r < 0) {
9,383✔
5897
                        *exit_status = EXIT_MEMORY;
×
5898
                        return log_error_errno(r, "Failed to replace environment variables: %m");
×
5899
                }
5900
                final_argv = replaced_argv;
9,383✔
5901

5902
                if (!strv_isempty(unset_variables)) {
9,383✔
5903
                        _cleanup_free_ char *ju = strv_join(unset_variables, ", ");
10✔
5904
                        log_warning("Referenced but unset environment variable evaluates to an empty string: %s", strna(ju));
5✔
5905
                }
5906

5907
                if (!strv_isempty(bad_variables)) {
9,383✔
5908
                        _cleanup_free_ char *jb = strv_join(bad_variables, ", ");
×
5909
                        log_warning("Invalid environment variable name evaluates to an empty string: %s", strna(jb));
×
5910
                }
5911
        }
5912

5913
        if (FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL)) {
9,556✔
5914
                r = strv_extendf(&argv_via_shell, "%s%s", command->argv[0][0] == '-' ? "-" : "", path);
17✔
5915
                if (r < 0) {
13✔
5916
                        *exit_status = EXIT_MEMORY;
×
5917
                        return log_oom();
×
5918
                }
5919

5920
                if (!strv_isempty(final_argv)) {
13✔
5921
                        _cleanup_free_ char *cmdline_joined = NULL;
13✔
5922

5923
                        cmdline_joined = strv_join(final_argv, " ");
13✔
5924
                        if (!cmdline_joined) {
13✔
5925
                                *exit_status = EXIT_MEMORY;
×
5926
                                return log_oom();
×
5927
                        }
5928

5929
                        r = strv_extend_many(&argv_via_shell, "-c", cmdline_joined);
13✔
5930
                        if (r < 0) {
13✔
5931
                                *exit_status = EXIT_MEMORY;
×
5932
                                return log_oom();
×
5933
                        }
5934
                }
5935

5936
                final_argv = argv_via_shell;
13✔
5937
        }
5938

5939
        log_command_line(context, params, "Executing", executable, final_argv);
9,556✔
5940

5941
        /* We have finished with all our initializations. Let's now let the manager know that. From this
5942
         * point on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */
5943

5944
        r = exec_fd_mark_hot(context, params, /* hot= */ true, exit_status);
9,556✔
5945
        if (r < 0)
9,556✔
5946
                return r;
5947

5948
        /* As last thing before the execve(), let's send the handoff timestamp */
5949
        r = send_handoff_timestamp(context, params, exit_status);
9,556✔
5950
        if (r < 0) {
9,556✔
5951
                /* If this handoff timestamp failed, let's undo the marking as hot */
5952
                (void) exec_fd_mark_hot(context, params, /* hot= */ false, /* reterr_exit_status= */ NULL);
×
5953
                return r;
5954
        }
5955

5956
        /* NB: we leave executable_fd, exec_fd, handoff_timestamp_fd open here. This is safe, because they
5957
         * have O_CLOEXEC set, and the execve() below will thus automatically close them. In fact, for
5958
         * exec_fd this is pretty much the whole raison d'etre. */
5959

5960
        r = fexecve_or_execve(executable_fd, executable, final_argv, accum_env);
9,556✔
5961

5962
        /* The execve() failed, let's undo the marking as hot */
5963
        (void) exec_fd_mark_hot(context, params, /* hot= */ false, /* reterr_exit_status= */ NULL);
3✔
5964

5965
        *exit_status = EXIT_EXEC;
3✔
5966
        return log_error_errno(r, "Failed to execute %s: %m", executable);
3✔
5967
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc