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

systemd / systemd / 14950366571

10 May 2025 12:04PM UTC coverage: 72.229% (-0.02%) from 72.251%
14950366571

push

github

keszybz
test: fix root check for test-bpf-foreign-programs

This test requires root, but the check was mistakenly dropped, causing it
to fail with an assert when running without root:

src/test/test-bpf-foreign-programs.c:308: Assertion failed: expected "test_bpf_cgroup_programs(m, "single_prog.service", single_prog, ELEMENTSOF(single_prog))" to succeed, but got error: Operation not permitted

Restore the uid check

Follow-up for 22e2f0642

0 of 3 new or added lines in 1 file covered. (0.0%)

176 existing lines in 40 files now uncovered.

297455 of 411822 relevant lines covered (72.23%)

704153.97 hits per line

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

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

3
#include <linux/prctl.h>
4
#include <linux/sched.h>
5
#include <linux/securebits.h>
6
#include <sys/eventfd.h>
7
#include <sys/ioctl.h>
8
#include <sys/mount.h>
9
#include <sys/prctl.h>
10

11
#if HAVE_PAM
12
#include <security/pam_appl.h>
13
#include <security/pam_misc.h>
14
#endif
15

16
#include "sd-messages.h"
17

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

71
#define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
72
#define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
73

74
#define SNDBUF_SIZE (8*1024*1024)
75

76
static int flag_fds(
9,542✔
77
                const int fds[],
78
                size_t n_socket_fds,
79
                size_t n_fds,
80
                bool nonblock) {
81

82
        int r;
9,542✔
83

84
        assert(fds || n_fds == 0);
9,542✔
85

86
        /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags.
87
         * O_NONBLOCK only applies to socket activation though. */
88

89
        for (size_t i = 0; i < n_fds; i++) {
12,115✔
90

91
                if (i < n_socket_fds) {
2,573✔
92
                        r = fd_nonblock(fds[i], nonblock);
2,257✔
93
                        if (r < 0)
2,257✔
94
                                return r;
95
                }
96

97
                /* We unconditionally drop FD_CLOEXEC from the fds,
98
                 * since after all we want to pass these fds to our
99
                 * children */
100

101
                r = fd_cloexec(fds[i], false);
2,573✔
102
                if (r < 0)
2,573✔
103
                        return r;
104
        }
105

106
        return 0;
107
}
108

109
static bool is_terminal_input(ExecInput i) {
42,921✔
110
        return IN_SET(i,
42,921✔
111
                      EXEC_INPUT_TTY,
112
                      EXEC_INPUT_TTY_FORCE,
113
                      EXEC_INPUT_TTY_FAIL);
114
}
115

116
static bool is_terminal_output(ExecOutput o) {
40,368✔
117
        return IN_SET(o,
40,368✔
118
                      EXEC_OUTPUT_TTY,
119
                      EXEC_OUTPUT_KMSG_AND_CONSOLE,
120
                      EXEC_OUTPUT_JOURNAL_AND_CONSOLE);
121
}
122

123
static bool is_kmsg_output(ExecOutput o) {
10,324✔
124
        return IN_SET(o,
10,324✔
125
                      EXEC_OUTPUT_KMSG,
126
                      EXEC_OUTPUT_KMSG_AND_CONSOLE);
127
}
128

129
static bool exec_context_needs_term(const ExecContext *c) {
9,566✔
130
        assert(c);
9,566✔
131

132
        /* Return true if the execution context suggests we should set $TERM to something useful. */
133

134
        if (is_terminal_input(c->std_input))
9,566✔
135
                return true;
136

137
        if (is_terminal_output(c->std_output))
9,394✔
138
                return true;
139

140
        if (is_terminal_output(c->std_error))
9,135✔
141
                return true;
142

143
        return !!c->tty_path;
9,134✔
144
}
145

146
static int open_null_as(int flags, int nfd) {
10,885✔
147
        int fd;
10,885✔
148

149
        assert(nfd >= 0);
10,885✔
150

151
        fd = open("/dev/null", flags|O_NOCTTY);
10,885✔
152
        if (fd < 0)
10,885✔
153
                return -errno;
×
154

155
        return move_fd(fd, nfd, false);
10,885✔
156
}
157

158
static int connect_journal_socket(
10,324✔
159
                int fd,
160
                const char *log_namespace,
161
                uid_t uid,
162
                gid_t gid) {
163

164
        uid_t olduid = UID_INVALID;
10,324✔
165
        gid_t oldgid = GID_INVALID;
10,324✔
166
        const char *j;
10,324✔
167
        int r;
10,324✔
168

169
        assert(fd >= 0);
10,324✔
170

171
        j = journal_stream_path(log_namespace);
10,336✔
172
        if (!j)
2✔
173
                return -EINVAL;
×
174

175
        if (gid_is_valid(gid)) {
10,324✔
176
                oldgid = getgid();
2,334✔
177

178
                if (setegid(gid) < 0)
2,334✔
179
                        return -errno;
×
180
        }
181

182
        if (uid_is_valid(uid)) {
10,324✔
183
                olduid = getuid();
2,331✔
184

185
                if (seteuid(uid) < 0) {
2,331✔
186
                        r = -errno;
×
187
                        goto restore_gid;
×
188
                }
189
        }
190

191
        r = connect_unix_path(fd, AT_FDCWD, j);
10,324✔
192

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

196
        if (uid_is_valid(uid))
10,324✔
197
                (void) seteuid(olduid);
2,331✔
198

199
 restore_gid:
7,993✔
200
        if (gid_is_valid(gid))
10,324✔
201
                (void) setegid(oldgid);
2,334✔
202

203
        return r;
204
}
205

206
static int connect_logger_as(
10,324✔
207
                const ExecContext *context,
208
                const ExecParameters *params,
209
                ExecOutput output,
210
                const char *ident,
211
                int nfd,
212
                uid_t uid,
213
                gid_t gid) {
214

215
        _cleanup_close_ int fd = -EBADF;
10,324✔
216
        int r;
10,324✔
217

218
        assert(context);
10,324✔
219
        assert(params);
10,324✔
220
        assert(output < _EXEC_OUTPUT_MAX);
10,324✔
221
        assert(ident);
10,324✔
222
        assert(nfd >= 0);
10,324✔
223

224
        fd = socket(AF_UNIX, SOCK_STREAM, 0);
10,324✔
225
        if (fd < 0)
10,324✔
226
                return -errno;
×
227

228
        r = connect_journal_socket(fd, context->log_namespace, uid, gid);
10,324✔
229
        if (r < 0)
10,324✔
230
                return r;
231

232
        if (shutdown(fd, SHUT_RD) < 0)
10,324✔
233
                return -errno;
×
234

235
        (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
10,324✔
236

237
        if (dprintf(fd,
19,899✔
238
                "%s\n"
239
                "%s\n"
240
                "%i\n"
241
                "%i\n"
242
                "%i\n"
243
                "%i\n"
244
                "%i\n",
245
                context->syslog_identifier ?: ident,
10,324✔
246
                params->flags & EXEC_PASS_LOG_UNIT ? params->unit_id : "",
10,324✔
247
                context->syslog_priority,
10,324✔
248
                !!context->syslog_level_prefix,
10,324✔
249
                false,
250
                is_kmsg_output(output),
10,324✔
251
                is_terminal_output(output)) < 0)
10,324✔
252
                return -errno;
×
253

254
        return move_fd(TAKE_FD(fd), nfd, false);
10,324✔
255
}
256

257
static int open_terminal_as(const char *path, int flags, int nfd) {
32✔
258
        int fd;
32✔
259

260
        assert(path);
32✔
261
        assert(nfd >= 0);
32✔
262

263
        fd = open_terminal(path, flags | O_NOCTTY);
32✔
264
        if (fd < 0)
32✔
265
                return fd;
266

267
        return move_fd(fd, nfd, false);
32✔
268
}
269

270
static int acquire_path(const char *path, int flags, mode_t mode) {
11✔
271
        _cleanup_close_ int fd = -EBADF;
11✔
272
        int r;
11✔
273

274
        assert(path);
11✔
275

276
        if (IN_SET(flags & O_ACCMODE_STRICT, O_WRONLY, O_RDWR))
11✔
277
                flags |= O_CREAT;
11✔
278

279
        fd = open(path, flags|O_NOCTTY, mode);
11✔
280
        if (fd >= 0)
11✔
281
                return TAKE_FD(fd);
11✔
282

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

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

288
        fd = socket(AF_UNIX, SOCK_STREAM, 0);
×
289
        if (fd < 0)
×
290
                return -errno;
×
291

292
        r = connect_unix_path(fd, AT_FDCWD, path);
×
293
        if (IN_SET(r, -ENOTSOCK, -EINVAL))
×
294
                /* Propagate initial error if we get ENOTSOCK or EINVAL, i.e. we have indication that this
295
                 * wasn't an AF_UNIX socket after all */
296
                return -ENXIO;
297
        if (r < 0)
×
298
                return r;
299

300
        if ((flags & O_ACCMODE_STRICT) == O_RDONLY)
×
301
                r = shutdown(fd, SHUT_WR);
×
302
        else if ((flags & O_ACCMODE_STRICT) == O_WRONLY)
×
303
                r = shutdown(fd, SHUT_RD);
×
304
        else
305
                r = 0;
306
        if (r < 0)
×
307
                return -errno;
×
308

309
        return TAKE_FD(fd);
310
}
311

312
static int fixup_input(
32,964✔
313
                const ExecContext *context,
314
                int socket_fd,
315
                bool apply_tty_stdin) {
316

317
        ExecInput std_input;
32,964✔
318

319
        assert(context);
32,964✔
320

321
        std_input = context->std_input;
32,964✔
322

323
        if (is_terminal_input(std_input) && !apply_tty_stdin)
32,964✔
324
                return EXEC_INPUT_NULL;
325

326
        if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
32,964✔
327
                return EXEC_INPUT_NULL;
328

329
        if (std_input == EXEC_INPUT_DATA && context->stdin_data_size == 0)
32,964✔
330
                return EXEC_INPUT_NULL;
×
331

332
        return std_input;
333
}
334

335
static int fixup_output(ExecOutput output, int socket_fd) {
32,964✔
336

337
        if (output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
32,964✔
338
                return EXEC_OUTPUT_INHERIT;
×
339

340
        return output;
341
}
342

343
static int setup_input(
11,515✔
344
                const ExecContext *context,
345
                const ExecParameters *params,
346
                int socket_fd,
347
                const int named_iofds[static 3]) {
348

349
        ExecInput i;
11,515✔
350
        int r;
11,515✔
351

352
        assert(context);
11,515✔
353
        assert(params);
11,515✔
354
        assert(named_iofds);
11,515✔
355

356
        if (params->stdin_fd >= 0) {
11,515✔
357
                if (dup2(params->stdin_fd, STDIN_FILENO) < 0)
527✔
358
                        return -errno;
×
359

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

364
                return STDIN_FILENO;
527✔
365
        }
366

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

369
        switch (i) {
10,988✔
370

371
        case EXEC_INPUT_NULL:
10,625✔
372
                return open_null_as(O_RDONLY, STDIN_FILENO);
10,625✔
373

374
        case EXEC_INPUT_TTY:
351✔
375
        case EXEC_INPUT_TTY_FORCE:
376
        case EXEC_INPUT_TTY_FAIL: {
377
                _cleanup_close_ int tty_fd = -EBADF;
351✔
378
                _cleanup_free_ char *resolved = NULL;
351✔
379
                const char *tty_path;
351✔
380

381
                tty_path = ASSERT_PTR(exec_context_tty_path(context));
351✔
382

383
                if (tty_is_console(tty_path)) {
351✔
384
                        r = resolve_dev_console(&resolved);
267✔
385
                        if (r < 0)
267✔
386
                                log_debug_errno(r, "Failed to resolve /dev/console, ignoring: %m");
×
387
                        else {
388
                                log_debug("Resolved /dev/console to %s", resolved);
267✔
389
                                tty_path = resolved;
267✔
390
                        }
391
                }
392

393
                tty_fd = acquire_terminal(tty_path,
702✔
394
                                          i == EXEC_INPUT_TTY_FAIL  ? ACQUIRE_TERMINAL_TRY :
351✔
395
                                          i == EXEC_INPUT_TTY_FORCE ? ACQUIRE_TERMINAL_FORCE :
396
                                                                      ACQUIRE_TERMINAL_WAIT,
397
                                          USEC_INFINITY);
398
                if (tty_fd < 0)
351✔
399
                        return tty_fd;
400

401
                r = move_fd(tty_fd, STDIN_FILENO, /* cloexec= */ false);
351✔
402
                if (r < 0)
351✔
403
                        return r;
×
404

405
                TAKE_FD(tty_fd);
406
                return r;
407
        }
408

409
        case EXEC_INPUT_SOCKET:
11✔
410
                assert(socket_fd >= 0);
11✔
411

412
                return RET_NERRNO(dup2(socket_fd, STDIN_FILENO));
11✔
413

414
        case EXEC_INPUT_NAMED_FD:
×
415
                assert(named_iofds[STDIN_FILENO] >= 0);
×
416

417
                (void) fd_nonblock(named_iofds[STDIN_FILENO], false);
×
418
                return RET_NERRNO(dup2(named_iofds[STDIN_FILENO], STDIN_FILENO));
11,515✔
419

420
        case EXEC_INPUT_DATA: {
1✔
421
                int fd;
1✔
422

423
                fd = memfd_new_and_seal("exec-input", context->stdin_data, context->stdin_data_size);
1✔
424
                if (fd < 0)
1✔
425
                        return fd;
426

427
                return move_fd(fd, STDIN_FILENO, false);
1✔
428
        }
429

430
        case EXEC_INPUT_FILE: {
×
431
                bool rw;
×
432
                int fd;
×
433

434
                assert(context->stdio_file[STDIN_FILENO]);
×
435

436
                rw = (context->std_output == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDOUT_FILENO])) ||
×
437
                        (context->std_error == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDERR_FILENO]));
×
438

439
                fd = acquire_path(context->stdio_file[STDIN_FILENO], rw ? O_RDWR : O_RDONLY, 0666 & ~context->umask);
×
440
                if (fd < 0)
×
441
                        return fd;
442

443
                return move_fd(fd, STDIN_FILENO, false);
×
444
        }
445

446
        default:
×
447
                assert_not_reached();
×
448
        }
449
}
450

451
static bool can_inherit_stderr_from_stdout(
10,988✔
452
                const ExecContext *context,
453
                ExecOutput o,
454
                ExecOutput e) {
455

456
        assert(context);
10,988✔
457

458
        /* Returns true, if given the specified STDERR and STDOUT output we can directly dup() the stdout fd to the
459
         * stderr fd */
460

461
        if (e == EXEC_OUTPUT_INHERIT)
10,988✔
462
                return true;
463
        if (e != o)
411✔
464
                return false;
465

466
        if (e == EXEC_OUTPUT_NAMED_FD)
408✔
467
                return streq_ptr(context->stdio_fdname[STDOUT_FILENO], context->stdio_fdname[STDERR_FILENO]);
×
468

469
        if (IN_SET(e, EXEC_OUTPUT_FILE, EXEC_OUTPUT_FILE_APPEND, EXEC_OUTPUT_FILE_TRUNCATE))
408✔
470
                return streq_ptr(context->stdio_file[STDOUT_FILENO], context->stdio_file[STDERR_FILENO]);
4✔
471

472
        return true;
473
}
474

475
static int setup_output(
23,030✔
476
                const ExecContext *context,
477
                const ExecParameters *params,
478
                int fileno,
479
                int socket_fd,
480
                const int named_iofds[static 3],
481
                const char *ident,
482
                uid_t uid,
483
                gid_t gid,
484
                dev_t *journal_stream_dev,
485
                ino_t *journal_stream_ino) {
486

487
        ExecOutput o;
23,030✔
488
        ExecInput i;
23,030✔
489
        int r;
23,030✔
490

491
        assert(context);
23,030✔
492
        assert(params);
23,030✔
493
        assert(ident);
23,030✔
494
        assert(journal_stream_dev);
23,030✔
495
        assert(journal_stream_ino);
23,030✔
496

497
        if (fileno == STDOUT_FILENO && params->stdout_fd >= 0) {
23,030✔
498

499
                if (dup2(params->stdout_fd, STDOUT_FILENO) < 0)
527✔
500
                        return -errno;
×
501

502
                return STDOUT_FILENO;
503
        }
504

505
        if (fileno == STDERR_FILENO && params->stderr_fd >= 0) {
22,503✔
506
                if (dup2(params->stderr_fd, STDERR_FILENO) < 0)
527✔
507
                        return -errno;
×
508

509
                return STDERR_FILENO;
510
        }
511

512
        i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
21,976✔
513
        o = fixup_output(context->std_output, socket_fd);
21,976✔
514

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

518
        if (fileno == STDERR_FILENO) {
21,976✔
519
                ExecOutput e;
10,988✔
520
                e = fixup_output(context->std_error, socket_fd);
10,988✔
521

522
                /* This expects the input and output are already set up */
523

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

533
                /* Duplicate from stdout if possible */
534
                if (can_inherit_stderr_from_stdout(context, o, e))
10,988✔
535
                        return RET_NERRNO(dup2(STDOUT_FILENO, fileno));
10,981✔
536

537
                o = e;
538

539
        } else if (o == EXEC_OUTPUT_INHERIT) {
10,988✔
540
                /* If input got downgraded, inherit the original value */
541
                if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
8✔
542
                        return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
×
543

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

548
                /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
549
                if (getppid() != 1)
×
550
                        return fileno;
551

552
                /* We need to open /dev/null here anew, to get the right access mode. */
553
                return open_null_as(O_WRONLY, fileno);
×
554
        }
555

556
        switch (o) {
10,987✔
557

558
        case EXEC_OUTPUT_NULL:
260✔
559
                return open_null_as(O_WRONLY, fileno);
260✔
560

561
        case EXEC_OUTPUT_TTY:
383✔
562
                if (is_terminal_input(i))
383✔
563
                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));
351✔
564

565
                return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
32✔
566

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

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

586
                        if (fstat(fileno, &st) >= 0 &&
10,324✔
587
                            (*journal_stream_ino == 0 || fileno == STDERR_FILENO)) {
10,324✔
588
                                *journal_stream_dev = st.st_dev;
10,324✔
589
                                *journal_stream_ino = st.st_ino;
10,324✔
590
                        }
591
                }
592
                return r;
593

594
        case EXEC_OUTPUT_SOCKET:
9✔
595
                assert(socket_fd >= 0);
9✔
596

597
                return RET_NERRNO(dup2(socket_fd, fileno));
9✔
598

599
        case EXEC_OUTPUT_NAMED_FD:
×
600
                assert(named_iofds[fileno] >= 0);
×
601

602
                (void) fd_nonblock(named_iofds[fileno], false);
×
603
                return RET_NERRNO(dup2(named_iofds[fileno], fileno));
×
604

605
        case EXEC_OUTPUT_FILE:
11✔
606
        case EXEC_OUTPUT_FILE_APPEND:
607
        case EXEC_OUTPUT_FILE_TRUNCATE: {
608
                bool rw;
11✔
609
                int fd, flags;
11✔
610

611
                assert(context->stdio_file[fileno]);
11✔
612

613
                rw = context->std_input == EXEC_INPUT_FILE &&
11✔
614
                        streq_ptr(context->stdio_file[fileno], context->stdio_file[STDIN_FILENO]);
×
615

616
                if (rw)
11✔
617
                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));
×
618

619
                flags = O_WRONLY;
11✔
620
                if (o == EXEC_OUTPUT_FILE_APPEND)
11✔
621
                        flags |= O_APPEND;
622
                else if (o == EXEC_OUTPUT_FILE_TRUNCATE)
9✔
623
                        flags |= O_TRUNC;
3✔
624

625
                fd = acquire_path(context->stdio_file[fileno], flags, 0666 & ~context->umask);
11✔
626
                if (fd < 0)
11✔
627
                        return fd;
628

629
                return move_fd(fd, fileno, 0);
11✔
630
        }
631

632
        default:
×
633
                assert_not_reached();
×
634
        }
635
}
636

637
static int chown_terminal(int fd, uid_t uid) {
2,641✔
638
        int r;
2,641✔
639

640
        assert(fd >= 0);
2,641✔
641

642
        /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
643
        if (!isatty_safe(fd))
2,641✔
644
                return 0;
645

646
        /* This might fail. What matters are the results. */
647
        r = fchmod_and_chown(fd, TTY_MODE, uid, GID_INVALID);
7✔
648
        if (r < 0)
7✔
649
                return r;
×
650

651
        return 1;
652
}
653

654
static int setup_confirm_stdio(
×
655
                const ExecContext *context,
656
                const char *vc,
657
                int *ret_saved_stdin,
658
                int *ret_saved_stdout) {
659

660
        _cleanup_close_ int fd = -EBADF, saved_stdin = -EBADF, saved_stdout = -EBADF;
×
661
        int r;
×
662

663
        assert(context);
×
664
        assert(ret_saved_stdin);
×
665
        assert(ret_saved_stdout);
×
666

667
        saved_stdin = fcntl(STDIN_FILENO, F_DUPFD_CLOEXEC, 3);
×
668
        if (saved_stdin < 0)
×
669
                return -errno;
×
670

671
        saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD_CLOEXEC, 3);
×
672
        if (saved_stdout < 0)
×
673
                return -errno;
×
674

675
        fd = acquire_terminal(vc, ACQUIRE_TERMINAL_WAIT, DEFAULT_CONFIRM_USEC);
×
676
        if (fd < 0)
×
677
                return fd;
678

679
        _cleanup_close_ int lock_fd = lock_dev_console();
×
680
        if (lock_fd < 0)
×
681
                log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
×
682

683
        r = chown_terminal(fd, getuid());
×
684
        if (r < 0)
×
685
                return r;
686

687
        r = terminal_reset_defensive(fd, TERMINAL_RESET_SWITCH_TO_TEXT);
×
688
        if (r < 0)
×
689
                return r;
690

691
        r = exec_context_apply_tty_size(context, fd, fd, vc);
×
692
        if (r < 0)
×
693
                return r;
694

695
        r = rearrange_stdio(fd, fd, STDERR_FILENO); /* Invalidates 'fd' also on failure */
×
696
        TAKE_FD(fd);
×
697
        if (r < 0)
×
698
                return r;
699

700
        *ret_saved_stdin = TAKE_FD(saved_stdin);
×
701
        *ret_saved_stdout = TAKE_FD(saved_stdout);
×
702
        return 0;
×
703
}
704

705
static void write_confirm_error_fd(int err, int fd, const char *unit_id) {
×
706
        assert(err != 0);
×
707
        assert(fd >= 0);
×
708
        assert(unit_id);
×
709

710
        errno = abs(err);
×
711

712
        if (errno == ETIMEDOUT)
×
713
                dprintf(fd, "Confirmation question timed out for %s, assuming positive response.\n", unit_id);
×
714
        else
715
                dprintf(fd, "Couldn't ask confirmation for %s, assuming positive response: %m\n", unit_id);
×
716
}
×
717

718
static void write_confirm_error(int err, const char *vc, const char *unit_id) {
×
719
        _cleanup_close_ int fd = -EBADF;
×
720

721
        assert(vc);
×
722

723
        fd = open_terminal(vc, O_WRONLY|O_NOCTTY|O_CLOEXEC);
×
724
        if (fd < 0)
×
725
                return;
×
726

727
        write_confirm_error_fd(err, fd, unit_id);
×
728
}
729

730
static int restore_confirm_stdio(int *saved_stdin, int *saved_stdout) {
×
731
        int r = 0;
×
732

733
        assert(saved_stdin);
×
734
        assert(saved_stdout);
×
735

736
        release_terminal();
×
737

738
        if (*saved_stdin >= 0)
×
739
                if (dup2(*saved_stdin, STDIN_FILENO) < 0)
×
740
                        r = -errno;
×
741

742
        if (*saved_stdout >= 0)
×
743
                if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
×
744
                        r = -errno;
×
745

746
        *saved_stdin = safe_close(*saved_stdin);
×
747
        *saved_stdout = safe_close(*saved_stdout);
×
748

749
        return r;
×
750
}
751

752
enum {
753
        CONFIRM_PRETEND_FAILURE = -1,
754
        CONFIRM_PRETEND_SUCCESS =  0,
755
        CONFIRM_EXECUTE = 1,
756
};
757

758
static bool confirm_spawn_disabled(void) {
×
759
        return access("/run/systemd/confirm_spawn_disabled", F_OK) >= 0;
×
760
}
761

762
static int ask_for_confirmation(const ExecContext *context, const ExecParameters *params, const char *cmdline) {
×
763
        int saved_stdout = -EBADF, saved_stdin = -EBADF, r;
×
764
        _cleanup_free_ char *e = NULL;
×
765
        char c;
×
766

767
        assert(context);
×
768
        assert(params);
×
769

770
        /* For any internal errors, assume a positive response. */
771
        r = setup_confirm_stdio(context, params->confirm_spawn, &saved_stdin, &saved_stdout);
×
772
        if (r < 0) {
×
773
                write_confirm_error(r, params->confirm_spawn, params->unit_id);
×
774
                return CONFIRM_EXECUTE;
775
        }
776

777
        /* confirm_spawn might have been disabled while we were sleeping. */
778
        if (!params->confirm_spawn || confirm_spawn_disabled()) {
×
779
                r = 1;
×
780
                goto restore_stdio;
×
781
        }
782

783
        e = ellipsize(cmdline, 60, 100);
×
784
        if (!e) {
×
785
                log_oom();
×
786
                r = CONFIRM_EXECUTE;
×
787
                goto restore_stdio;
×
788
        }
789

790
        for (;;) {
×
791
                r = ask_char(&c, "yfshiDjcn", "Execute %s? [y, f, s – h for help] ", e);
×
792
                if (r < 0) {
×
793
                        write_confirm_error_fd(r, STDOUT_FILENO, params->unit_id);
×
794
                        r = CONFIRM_EXECUTE;
×
795
                        goto restore_stdio;
×
796
                }
797

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

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

853
restore_stdio:
×
854
        restore_confirm_stdio(&saved_stdin, &saved_stdout);
×
855
        return r;
856
}
857

858
static int get_fixed_user(
9,361✔
859
                const char *user_or_uid,
860
                bool prefer_nss,
861
                const char **ret_username,
862
                uid_t *ret_uid,
863
                gid_t *ret_gid,
864
                const char **ret_home,
865
                const char **ret_shell) {
866

867
        int r;
9,361✔
868

869
        assert(user_or_uid);
9,361✔
870
        assert(ret_username);
9,361✔
871

872
        r = get_user_creds(&user_or_uid, ret_uid, ret_gid, ret_home, ret_shell,
18,286✔
873
                           USER_CREDS_CLEAN|(prefer_nss ? USER_CREDS_PREFER_NSS : 0));
874
        if (r < 0)
9,361✔
875
                return r;
876

877
        /* user_or_uid is normalized by get_user_creds to username */
878
        *ret_username = user_or_uid;
9,359✔
879

880
        return 0;
9,359✔
881
}
882

883
static int get_fixed_group(
11✔
884
                const char *group_or_gid,
885
                const char **ret_groupname,
886
                gid_t *ret_gid) {
887

888
        int r;
11✔
889

890
        assert(group_or_gid);
11✔
891
        assert(ret_groupname);
11✔
892

893
        r = get_group_creds(&group_or_gid, ret_gid, /* flags = */ 0);
11✔
894
        if (r < 0)
11✔
895
                return r;
896

897
        /* group_or_gid is normalized by get_group_creds to groupname */
898
        *ret_groupname = group_or_gid;
11✔
899

900
        return 0;
11✔
901
}
902

903
static int get_supplementary_groups(
11,515✔
904
                const ExecContext *c,
905
                const char *user,
906
                gid_t gid,
907
                gid_t **ret_gids) {
908

909
        int r;
11,515✔
910

911
        assert(c);
11,515✔
912
        assert(ret_gids);
11,515✔
913

914
        /*
915
         * If user is given, then lookup GID and supplementary groups list.
916
         * We avoid NSS lookups for gid=0. Also we have to initialize groups
917
         * here and as early as possible so we keep the list of supplementary
918
         * groups of the caller.
919
         */
920
        bool keep_groups = false;
11,515✔
921
        if (user && gid_is_valid(gid) && gid != 0) {
14,156✔
922
                /* First step, initialize groups from /etc/groups */
923
                if (initgroups(user, gid) < 0)
2,503✔
924
                        return -errno;
11,515✔
925

926
                keep_groups = true;
927
        }
928

929
        if (strv_isempty(c->supplementary_groups)) {
11,515✔
930
                *ret_gids = NULL;
11,506✔
931
                return 0;
11,506✔
932
        }
933

934
        /*
935
         * If SupplementaryGroups= was passed then NGROUPS_MAX has to
936
         * be positive, otherwise fail.
937
         */
938
        errno = 0;
9✔
939
        int ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
9✔
940
        if (ngroups_max <= 0)
9✔
941
                return errno_or_else(EOPNOTSUPP);
×
942

943
        _cleanup_free_ gid_t *l_gids = new(gid_t, ngroups_max);
18✔
944
        if (!l_gids)
9✔
945
                return -ENOMEM;
946

947
        int k = 0;
9✔
948
        if (keep_groups) {
9✔
949
                /*
950
                 * Lookup the list of groups that the user belongs to, we
951
                 * avoid NSS lookups here too for gid=0.
952
                 */
953
                k = ngroups_max;
9✔
954
                if (getgrouplist(user, gid, l_gids, &k) < 0)
9✔
955
                        return -EINVAL;
956
        }
957

958
        STRV_FOREACH(i, c->supplementary_groups) {
18✔
959
                if (k >= ngroups_max)
9✔
960
                        return -E2BIG;
×
961

962
                const char *g = *i;
9✔
963
                r = get_group_creds(&g, l_gids + k, /* flags = */ 0);
9✔
964
                if (r < 0)
9✔
965
                        return r;
966

967
                k++;
9✔
968
        }
969

970
        if (k == 0) {
9✔
971
                *ret_gids = NULL;
×
972
                return 0;
×
973
        }
974

975
        /* Otherwise get the final list of supplementary groups */
976
        gid_t *groups = newdup(gid_t, l_gids, k);
9✔
977
        if (!groups)
9✔
978
                return -ENOMEM;
979

980
        *ret_gids = groups;
9✔
981
        return k;
9✔
982
}
983

984
static int enforce_groups(gid_t gid, const gid_t *supplementary_gids, int ngids) {
9,546✔
985
        int r;
9,546✔
986

987
        /* Handle SupplementaryGroups= if it is not empty */
988
        if (ngids > 0) {
9,546✔
989
                r = maybe_setgroups(ngids, supplementary_gids);
262✔
990
                if (r < 0)
262✔
991
                        return r;
992
        }
993

994
        if (gid_is_valid(gid)) {
9,546✔
995
                /* Then set our gids */
996
                if (setresgid(gid, gid, gid) < 0)
1,998✔
997
                        return -errno;
1✔
998
        }
999

1000
        return 0;
1001
}
1002

1003
static int set_securebits(unsigned bits, unsigned mask) {
740✔
1004
        unsigned applied;
740✔
1005
        int current;
740✔
1006

1007
        current = prctl(PR_GET_SECUREBITS);
740✔
1008
        if (current < 0)
740✔
1009
                return -errno;
×
1010

1011
        /* Clear all securebits defined in mask and set bits */
1012
        applied = ((unsigned) current & ~mask) | bits;
740✔
1013
        if ((unsigned) current == applied)
740✔
1014
                return 0;
1015

1016
        if (prctl(PR_SET_SECUREBITS, applied) < 0)
53✔
1017
                return -errno;
×
1018

1019
        return 1;
1020
}
1021

1022
static int enforce_user(
1,991✔
1023
                const ExecContext *context,
1024
                uid_t uid,
1025
                uint64_t capability_ambient_set) {
1026

1027
        int r;
1,991✔
1028

1029
        assert(context);
1,991✔
1030

1031
        if (!uid_is_valid(uid))
1,991✔
1032
                return 0;
1033

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

1038
        if ((capability_ambient_set != 0 || context->secure_bits != 0) && uid != 0) {
1,991✔
1039

1040
                /* First step: If we need to keep capabilities but drop privileges we need to make sure we
1041
                 * keep our caps, while we drop privileges. Add KEEP_CAPS to the securebits */
1042
                r = set_securebits(1U << SECURE_KEEP_CAPS, 0);
740✔
1043
                if (r < 0)
740✔
1044
                        return r;
1045
        }
1046

1047
        /* Second step: actually set the uids */
1048
        if (setresuid(uid, uid, uid) < 0)
1,991✔
1049
                return -errno;
×
1050

1051
        /* At this point we should have all necessary capabilities but are otherwise a normal user. However,
1052
         * the caps might got corrupted due to the setresuid() so we need clean them up later. This is done
1053
         * outside of this call. */
1054
        return 0;
1055
}
1056

1057
#if HAVE_PAM
1058

1059
static void pam_response_free_array(struct pam_response *responses, size_t n_responses) {
×
1060
        assert(responses || n_responses == 0);
×
1061

1062
        FOREACH_ARRAY(resp, responses, n_responses)
×
1063
                erase_and_free(resp->resp);
×
1064

1065
        free(responses);
×
1066
}
×
1067

1068
typedef struct AskPasswordConvData {
1069
        const ExecContext *context;
1070
        const ExecParameters *params;
1071
} AskPasswordConvData;
1072

1073
static int ask_password_conv(
5✔
1074
                int num_msg,
1075
                const struct pam_message *msg[],
1076
                struct pam_response **ret,
1077
                void *userdata) {
1078

1079
        AskPasswordConvData *data = ASSERT_PTR(userdata);
5✔
1080
        bool set_credential_env_var = false;
5✔
1081
        int r;
5✔
1082

1083
        assert(num_msg >= 0);
5✔
1084
        assert(msg);
5✔
1085
        assert(data->context);
5✔
1086
        assert(data->params);
5✔
1087

1088
        size_t n = num_msg;
5✔
1089
        struct pam_response *responses = new0(struct pam_response, n);
5✔
1090
        if (!responses)
5✔
1091
                return PAM_BUF_ERR;
5✔
1092
        CLEANUP_ARRAY(responses, n, pam_response_free_array);
5✔
1093

1094
        for (size_t i = 0; i < n; i++) {
10✔
1095
                const struct pam_message *mi = *msg + i;
5✔
1096

1097
                switch (mi->msg_style) {
5✔
1098

1099
                case PAM_PROMPT_ECHO_ON:
2✔
1100
                case PAM_PROMPT_ECHO_OFF: {
1101

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

1109
                                if (creds_dir) {
2✔
1110
                                        if (setenv("CREDENTIALS_DIRECTORY", creds_dir, /* overwrite= */ true) < 0)
2✔
1111
                                                return log_error_errno(r, "Failed to set $CREDENTIALS_DIRECTORY: %m");
×
1112
                                } else
1113
                                        (void) unsetenv("CREDENTIALS_DIRECTORY");
×
1114

1115
                                set_credential_env_var = true;
2✔
1116
                        }
1117

1118
                        _cleanup_free_ char *credential_name = strjoin("pam.authtok.", data->context->pam_name);
4✔
1119
                        if (!credential_name)
2✔
1120
                                return log_oom();
×
1121

1122
                        AskPasswordRequest req = {
4✔
1123
                                .message = mi->msg,
2✔
1124
                                .credential = credential_name,
1125
                                .tty_fd = -EBADF,
1126
                                .hup_fd = -EBADF,
1127
                                .until = usec_add(now(CLOCK_MONOTONIC), 15 * USEC_PER_SEC),
2✔
1128
                        };
1129

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

1142
                        responses[i].resp = strdup(ASSERT_PTR(acquired[0]));
2✔
1143
                        if (!responses[i].resp) {
2✔
1144
                                log_oom();
×
1145
                                return PAM_BUF_ERR;
1146
                        }
1147
                        break;
2✔
1148
                }
1149

1150
                case PAM_ERROR_MSG:
1151
                        log_error("PAM: %s", mi->msg);
×
1152
                        break;
1153

1154
                case PAM_TEXT_INFO:
1155
                        log_info("PAM: %s", mi->msg);
3✔
1156
                        break;
1157

1158
                default:
1159
                        return PAM_CONV_ERR;
1160
                }
1161
        }
1162

1163
        *ret = TAKE_PTR(responses);
5✔
1164
        n = 0;
5✔
1165

1166
        return PAM_SUCCESS;
5✔
1167
}
1168

1169
static int pam_close_session_and_delete_credentials(pam_handle_t *handle, int flags) {
207✔
1170
        int r, s;
207✔
1171

1172
        assert(handle);
207✔
1173

1174
        r = pam_close_session(handle, flags);
207✔
1175
        if (r != PAM_SUCCESS)
207✔
1176
                log_debug("pam_close_session() failed: %s", pam_strerror(handle, r));
48✔
1177

1178
        s = pam_setcred(handle, PAM_DELETE_CRED | flags);
207✔
1179
        if (s != PAM_SUCCESS)
207✔
1180
                log_debug("pam_setcred(PAM_DELETE_CRED) failed: %s", pam_strerror(handle, s));
142✔
1181

1182
        return r != PAM_SUCCESS ? r : s;
207✔
1183
}
1184
#endif
1185

1186
static int setup_pam(
388✔
1187
                const ExecContext *context,
1188
                ExecParameters *params,
1189
                const char *user,
1190
                uid_t uid,
1191
                gid_t gid,
1192
                char ***env, /* updated on success */
1193
                const int fds[], size_t n_fds,
1194
                int exec_fd) {
1195

1196
#if HAVE_PAM
1197
        AskPasswordConvData conv_data = {
388✔
1198
                .context = context,
1199
                .params = params,
1200
        };
1201

1202
        const struct pam_conv conv = {
388✔
1203
                .conv = ask_password_conv,
1204
                .appdata_ptr = &conv_data,
1205
        };
1206

1207
        _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
388✔
1208
        _cleanup_strv_free_ char **e = NULL;
×
1209
        _cleanup_free_ char *tty = NULL;
388✔
1210
        pam_handle_t *handle = NULL;
388✔
1211
        sigset_t old_ss;
388✔
1212
        int pam_code = PAM_SUCCESS, r;
388✔
1213
        bool close_session = false;
388✔
1214
        pid_t parent_pid;
388✔
1215
        int flags = 0;
388✔
1216

1217
        assert(context);
388✔
1218
        assert(params);
388✔
1219
        assert(user);
388✔
1220
        assert(uid_is_valid(uid));
388✔
1221
        assert(gid_is_valid(gid));
388✔
1222
        assert(fds || n_fds == 0);
388✔
1223
        assert(env);
388✔
1224

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

1232
        r = barrier_create(&barrier);
388✔
1233
        if (r < 0)
388✔
1234
                goto fail;
×
1235

1236
        if (log_get_max_level() < LOG_DEBUG)
388✔
1237
                flags |= PAM_SILENT;
3✔
1238

1239
        pam_code = pam_start(context->pam_name, user, &conv, &handle);
388✔
1240
        if (pam_code != PAM_SUCCESS) {
388✔
1241
                handle = NULL;
×
1242
                goto fail;
×
1243
        }
1244

1245
        if (getttyname_malloc(STDIN_FILENO, &tty) >= 0) {
388✔
1246
                _cleanup_free_ char *q = path_join("/dev", tty);
6✔
1247
                if (!q) {
6✔
1248
                        r = -ENOMEM;
×
1249
                        goto fail;
×
1250
                }
1251

1252
                free_and_replace(tty, q);
6✔
1253
        }
1254

1255
        if (tty) {
388✔
1256
                pam_code = pam_set_item(handle, PAM_TTY, tty);
6✔
1257
                if (pam_code != PAM_SUCCESS)
6✔
1258
                        goto fail;
×
1259
        }
1260

1261
        STRV_FOREACH(nv, *env) {
5,475✔
1262
                pam_code = pam_putenv(handle, *nv);
5,087✔
1263
                if (pam_code != PAM_SUCCESS)
5,087✔
1264
                        goto fail;
×
1265
        }
1266

1267
        pam_code = pam_acct_mgmt(handle, flags);
388✔
1268
        if (pam_code != PAM_SUCCESS)
388✔
1269
                goto fail;
×
1270

1271
        pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | flags);
388✔
1272
        if (pam_code != PAM_SUCCESS)
388✔
1273
                log_debug("pam_setcred(PAM_ESTABLISH_CRED) failed, ignoring: %s", pam_strerror(handle, pam_code));
319✔
1274

1275
        pam_code = pam_open_session(handle, flags);
388✔
1276
        if (pam_code != PAM_SUCCESS)
388✔
1277
                goto fail;
×
1278

1279
        close_session = true;
388✔
1280

1281
        e = pam_getenvlist(handle);
388✔
1282
        if (!e) {
388✔
1283
                pam_code = PAM_BUF_ERR;
×
1284
                goto fail;
×
1285
        }
1286

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

1289
        assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM) >= 0);
388✔
1290

1291
        parent_pid = getpid_cached();
388✔
1292

1293
        r = safe_fork("(sd-pam)", 0, NULL);
388✔
1294
        if (r < 0)
595✔
1295
                goto fail;
×
1296
        if (r == 0) {
595✔
1297
                int ret = EXIT_PAM;
207✔
1298

1299
                /* The child's job is to reset the PAM session on termination */
1300
                barrier_set_role(&barrier, BARRIER_CHILD);
207✔
1301

1302
                /* Make sure we don't keep open the passed fds in this child. We assume that otherwise only
1303
                 * those fds are open here that have been opened by PAM. */
1304
                (void) close_many(fds, n_fds);
207✔
1305

1306
                /* Also close the 'exec_fd' in the child, since the service manager waits for the EOF induced
1307
                 * by the execve() to wait for completion, and if we'd keep the fd open here in the child
1308
                 * we'd never signal completion. */
1309
                exec_fd = safe_close(exec_fd);
207✔
1310

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

1315
                r = fully_set_uid_gid(uid, gid, /* supplementary_gids= */ NULL, /* n_supplementary_gids= */ 0);
207✔
1316
                if (r < 0)
207✔
1317
                        log_warning_errno(r, "Failed to drop privileges in sd-pam: %m");
×
1318

1319
                (void) ignore_signals(SIGPIPE);
207✔
1320

1321
                /* Wait until our parent died. This will only work if the above setresuid() succeeds,
1322
                 * otherwise the kernel will not allow unprivileged parents kill their privileged children
1323
                 * this way. We rely on the control groups kill logic to do the rest for us. */
1324
                if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
207✔
1325
                        goto child_finish;
×
1326

1327
                /* Tell the parent that our setup is done. This is especially important regarding dropping
1328
                 * privileges. Otherwise, unit setup might race against our setresuid(2) call.
1329
                 *
1330
                 * If the parent aborted, we'll detect this below, hence ignore return failure here. */
1331
                (void) barrier_place(&barrier);
207✔
1332

1333
                /* Check if our parent process might already have died? */
1334
                if (getppid() == parent_pid) {
207✔
1335
                        sigset_t ss;
207✔
1336
                        int sig;
207✔
1337

1338
                        assert_se(sigemptyset(&ss) >= 0);
207✔
1339
                        assert_se(sigaddset(&ss, SIGTERM) >= 0);
207✔
1340

1341
                        assert_se(sigwait(&ss, &sig) == 0);
207✔
1342
                        assert(sig == SIGTERM);
207✔
1343
                }
1344

1345
                /* If our parent died we'll end the session */
1346
                if (getppid() != parent_pid) {
207✔
1347
                        pam_code = pam_close_session_and_delete_credentials(handle, flags);
207✔
1348
                        if (pam_code != PAM_SUCCESS)
207✔
1349
                                goto child_finish;
142✔
1350
                }
1351

1352
                ret = 0;
1353

1354
        child_finish:
207✔
1355
                /* NB: pam_end() when called in child processes should set PAM_DATA_SILENT to let the module
1356
                 * know about this. See pam_end(3) */
1357
                (void) pam_end(handle, pam_code | flags | PAM_DATA_SILENT);
207✔
1358
                _exit(ret);
207✔
1359
        }
1360

1361
        barrier_set_role(&barrier, BARRIER_PARENT);
388✔
1362

1363
        /* If the child was forked off successfully it will do all the cleanups, so forget about the handle
1364
         * here. */
1365
        handle = NULL;
388✔
1366

1367
        /* Unblock SIGTERM again in the parent */
1368
        assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0);
388✔
1369

1370
        /* We close the log explicitly here, since the PAM modules might have opened it, but we don't want
1371
         * this fd around. */
1372
        closelog();
388✔
1373

1374
        /* Synchronously wait for the child to initialize. We don't care for errors as we cannot
1375
         * recover. However, warn loudly if it happens. */
1376
        if (!barrier_place_and_sync(&barrier))
776✔
1377
                log_error("PAM initialization failed");
×
1378

1379
        return strv_free_and_replace(*env, e);
388✔
1380

1381
fail:
×
1382
        if (pam_code != PAM_SUCCESS) {
×
1383
                log_error("PAM failed: %s", pam_strerror(handle, pam_code));
×
1384
                r = -EPERM;  /* PAM errors do not map to errno */
1385
        } else
1386
                log_error_errno(r, "PAM failed: %m");
×
1387

1388
        if (handle) {
×
1389
                if (close_session)
×
1390
                        pam_code = pam_close_session_and_delete_credentials(handle, flags);
×
1391

1392
                (void) pam_end(handle, pam_code | flags);
×
1393
        }
1394

1395
        closelog();
×
1396
        return r;
1397
#else
1398
        return 0;
1399
#endif
1400
}
1401

1402
static void rename_process_from_path(const char *path) {
11,518✔
1403
        _cleanup_free_ char *buf = NULL;
11,518✔
1404
        const char *p;
11,518✔
1405

1406
        assert(path);
11,518✔
1407

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

1411
        if (path_extract_filename(path, &buf) < 0) {
11,518✔
1412
                rename_process("(...)");
×
1413
                return;
×
1414
        }
1415

1416
        size_t l = strlen(buf);
11,518✔
1417
        if (l > 8) {
11,518✔
1418
                /* The end of the process name is usually more interesting, since the first bit might just be
1419
                 * "systemd-" */
1420
                p = buf + l - 8;
7,962✔
1421
                l = 8;
7,962✔
1422
        } else
1423
                p = buf;
1424

1425
        char process_name[11];
11,518✔
1426
        process_name[0] = '(';
11,518✔
1427
        memcpy(process_name+1, p, l);
11,518✔
1428
        process_name[1+l] = ')';
11,518✔
1429
        process_name[1+l+1] = 0;
11,518✔
1430

1431
        (void) rename_process(process_name);
11,518✔
1432
}
1433

1434
static bool context_has_address_families(const ExecContext *c) {
12,422✔
1435
        assert(c);
12,422✔
1436

1437
        return c->address_families_allow_list ||
12,422✔
1438
                !set_isempty(c->address_families);
10,932✔
1439
}
1440

1441
static bool context_has_syscall_filters(const ExecContext *c) {
12,386✔
1442
        assert(c);
12,386✔
1443

1444
        return c->syscall_allow_list ||
12,386✔
1445
                !hashmap_isempty(c->syscall_filter);
10,911✔
1446
}
1447

1448
static bool context_has_syscall_logs(const ExecContext *c) {
12,386✔
1449
        assert(c);
12,386✔
1450

1451
        return c->syscall_log_allow_list ||
12,386✔
1452
                !hashmap_isempty(c->syscall_log);
12,386✔
1453
}
1454

1455
static bool context_has_seccomp(const ExecContext *c) {
3,593✔
1456
        assert(c);
3,593✔
1457

1458
        /* We need NNP if we have any form of seccomp and are unprivileged */
1459
        return c->lock_personality ||
6,474✔
1460
                c->memory_deny_write_execute ||
2,881✔
1461
                c->private_devices ||
2,881✔
1462
                c->protect_clock ||
2,881✔
1463
                c->protect_hostname == PROTECT_HOSTNAME_YES ||
2,881✔
1464
                c->protect_kernel_tunables ||
2,881✔
1465
                c->protect_kernel_modules ||
2,881✔
1466
                c->protect_kernel_logs ||
5,762✔
1467
                context_has_address_families(c) ||
5,762✔
1468
                exec_context_restrict_namespaces_set(c) ||
2,881✔
1469
                c->restrict_realtime ||
2,881✔
1470
                c->restrict_suid_sgid ||
2,881✔
1471
                !set_isempty(c->syscall_archs) ||
5,690✔
1472
                context_has_syscall_filters(c) ||
9,283✔
1473
                context_has_syscall_logs(c);
2,845✔
1474
}
1475

1476
static bool context_has_no_new_privileges(const ExecContext *c) {
9,541✔
1477
        assert(c);
9,541✔
1478

1479
        if (c->no_new_privileges)
9,541✔
1480
                return true;
1481

1482
        if (have_effective_cap(CAP_SYS_ADMIN) > 0) /* if we are privileged, we don't need NNP */
8,127✔
1483
                return false;
1484

1485
        return context_has_seccomp(c);
1,602✔
1486
}
1487

1488
#if HAVE_SECCOMP
1489

1490
static bool seccomp_allows_drop_privileges(const ExecContext *c) {
748✔
1491
        void *id, *val;
748✔
1492
        bool have_capget = false, have_capset = false, have_prctl = false;
748✔
1493

1494
        assert(c);
748✔
1495

1496
        /* No syscall filter, we are allowed to drop privileges */
1497
        if (hashmap_isempty(c->syscall_filter))
748✔
1498
                return true;
748✔
1499

1500
        HASHMAP_FOREACH_KEY(val, id, c->syscall_filter) {
271,095✔
1501
                _cleanup_free_ char *name = NULL;
270,399✔
1502

1503
                name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
270,399✔
1504

1505
                if (streq(name, "capget"))
270,399✔
1506
                        have_capget = true;
1507
                else if (streq(name, "capset"))
269,703✔
1508
                        have_capset = true;
1509
                else if (streq(name, "prctl"))
269,007✔
1510
                        have_prctl = true;
696✔
1511
        }
1512

1513
        if (c->syscall_allow_list)
696✔
1514
                return have_capget && have_capset && have_prctl;
696✔
1515
        else
1516
                return !(have_capget || have_capset || have_prctl);
×
1517
}
1518

1519
static bool skip_seccomp_unavailable(const char *msg) {
14,875✔
1520
        assert(msg);
14,875✔
1521

1522
        if (is_seccomp_available())
14,875✔
1523
                return false;
1524

1525
        log_debug("SECCOMP features not detected in the kernel, skipping %s", msg);
×
1526
        return true;
1527
}
1528

1529
static int apply_syscall_filter(const ExecContext *c, const ExecParameters *p) {
9,541✔
1530
        uint32_t negative_action, default_action, action;
9,541✔
1531
        int r;
9,541✔
1532

1533
        assert(c);
9,541✔
1534
        assert(p);
9,541✔
1535

1536
        if (!context_has_syscall_filters(c))
9,541✔
1537
                return 0;
1538

1539
        if (skip_seccomp_unavailable("SystemCallFilter="))
1,476✔
1540
                return 0;
1541

1542
        negative_action = c->syscall_errno == SECCOMP_ERROR_NUMBER_KILL ? scmp_act_kill_process() : SCMP_ACT_ERRNO(c->syscall_errno);
1,476✔
1543

1544
        if (c->syscall_allow_list) {
1,476✔
1545
                default_action = negative_action;
1546
                action = SCMP_ACT_ALLOW;
1547
        } else {
1548
                default_action = SCMP_ACT_ALLOW;
1✔
1549
                action = negative_action;
1✔
1550
        }
1551

1552
        /* Sending over exec_fd or handoff_timestamp_fd requires write() syscall. */
1553
        if (p->exec_fd >= 0 || p->handoff_timestamp_fd >= 0) {
1,476✔
1554
                r = seccomp_filter_set_add_by_name(c->syscall_filter, c->syscall_allow_list, "write");
1,476✔
1555
                if (r < 0)
1,476✔
1556
                        return r;
1557
        }
1558

1559
        return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_filter, action, false);
1,476✔
1560
}
1561

1562
static int apply_syscall_log(const ExecContext *c, const ExecParameters *p) {
9,541✔
1563
#ifdef SCMP_ACT_LOG
1564
        uint32_t default_action, action;
9,541✔
1565
#endif
1566

1567
        assert(c);
9,541✔
1568
        assert(p);
9,541✔
1569

1570
        if (!context_has_syscall_logs(c))
9,541✔
1571
                return 0;
1572

1573
#ifdef SCMP_ACT_LOG
1574
        if (skip_seccomp_unavailable("SystemCallLog="))
×
1575
                return 0;
1576

1577
        if (c->syscall_log_allow_list) {
×
1578
                /* Log nothing but the ones listed */
1579
                default_action = SCMP_ACT_ALLOW;
1580
                action = SCMP_ACT_LOG;
1581
        } else {
1582
                /* Log everything but the ones listed */
1583
                default_action = SCMP_ACT_LOG;
×
1584
                action = SCMP_ACT_ALLOW;
×
1585
        }
1586

1587
        return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_log, action, false);
×
1588
#else
1589
        /* old libseccomp */
1590
        log_debug( "SECCOMP feature SCMP_ACT_LOG not available, skipping SystemCallLog=");
1591
        return 0;
1592
#endif
1593
}
1594

1595
static int apply_syscall_archs(const ExecContext *c, const ExecParameters *p) {
9,541✔
1596
        assert(c);
9,541✔
1597
        assert(p);
9,541✔
1598

1599
        if (set_isempty(c->syscall_archs))
9,541✔
1600
                return 0;
1601

1602
        if (skip_seccomp_unavailable("SystemCallArchitectures="))
1,492✔
1603
                return 0;
1604

1605
        return seccomp_restrict_archs(c->syscall_archs);
1,492✔
1606
}
1607

1608
static int apply_address_families(const ExecContext *c, const ExecParameters *p) {
9,541✔
1609
        assert(c);
9,541✔
1610
        assert(p);
9,541✔
1611

1612
        if (!context_has_address_families(c))
9,541✔
1613
                return 0;
1614

1615
        if (skip_seccomp_unavailable("RestrictAddressFamilies="))
1,490✔
1616
                return 0;
1617

1618
        return seccomp_restrict_address_families(c->address_families, c->address_families_allow_list);
1,490✔
1619
}
1620

1621
static int apply_memory_deny_write_execute(const ExecContext *c, const ExecParameters *p) {
9,541✔
1622
        int r;
9,541✔
1623

1624
        assert(c);
9,541✔
1625
        assert(p);
9,541✔
1626

1627
        if (!c->memory_deny_write_execute)
9,541✔
1628
                return 0;
1629

1630
        /* use prctl() if kernel supports it (6.3) */
1631
        r = prctl(PR_SET_MDWE, PR_MDWE_REFUSE_EXEC_GAIN, 0, 0, 0);
1,490✔
1632
        if (r == 0) {
1,490✔
1633
                log_debug("Enabled MemoryDenyWriteExecute= with PR_SET_MDWE");
1,490✔
1634
                return 0;
1,490✔
1635
        }
1636
        if (r < 0 && errno != EINVAL)
×
1637
                return log_debug_errno(errno, "Failed to enable MemoryDenyWriteExecute= with PR_SET_MDWE: %m");
×
1638
        /* else use seccomp */
1639
        log_debug("Kernel doesn't support PR_SET_MDWE: falling back to seccomp");
×
1640

1641
        if (skip_seccomp_unavailable("MemoryDenyWriteExecute="))
×
1642
                return 0;
1643

1644
        return seccomp_memory_deny_write_execute();
×
1645
}
1646

1647
static int apply_restrict_realtime(const ExecContext *c, const ExecParameters *p) {
9,541✔
1648
        assert(c);
9,541✔
1649
        assert(p);
9,541✔
1650

1651
        if (!c->restrict_realtime)
9,541✔
1652
                return 0;
1653

1654
        if (skip_seccomp_unavailable("RestrictRealtime="))
1,490✔
1655
                return 0;
1656

1657
        return seccomp_restrict_realtime();
1,490✔
1658
}
1659

1660
static int apply_restrict_suid_sgid(const ExecContext *c, const ExecParameters *p) {
9,541✔
1661
        assert(c);
9,541✔
1662
        assert(p);
9,541✔
1663

1664
        if (!c->restrict_suid_sgid)
9,541✔
1665
                return 0;
1666

1667
        if (skip_seccomp_unavailable("RestrictSUIDSGID="))
1,410✔
1668
                return 0;
1669

1670
        return seccomp_restrict_suid_sgid();
1,410✔
1671
}
1672

1673
static int apply_protect_sysctl(const ExecContext *c, const ExecParameters *p) {
9,541✔
1674
        assert(c);
9,541✔
1675
        assert(p);
9,541✔
1676

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

1680
        if (!c->protect_kernel_tunables)
9,541✔
1681
                return 0;
1682

1683
        if (skip_seccomp_unavailable("ProtectKernelTunables="))
362✔
1684
                return 0;
1685

1686
        return seccomp_protect_sysctl();
362✔
1687
}
1688

1689
static int apply_protect_kernel_modules(const ExecContext *c, const ExecParameters *p) {
9,541✔
1690
        assert(c);
9,541✔
1691
        assert(p);
9,541✔
1692

1693
        /* Turn off module syscalls on ProtectKernelModules=yes */
1694

1695
        if (!c->protect_kernel_modules)
9,541✔
1696
                return 0;
1697

1698
        if (skip_seccomp_unavailable("ProtectKernelModules="))
1,127✔
1699
                return 0;
1700

1701
        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_MODULE, SCMP_ACT_ERRNO(EPERM), false);
1,127✔
1702
}
1703

1704
static int apply_protect_kernel_logs(const ExecContext *c, const ExecParameters *p) {
9,541✔
1705
        assert(c);
9,541✔
1706
        assert(p);
9,541✔
1707

1708
        if (!c->protect_kernel_logs)
9,541✔
1709
                return 0;
1710

1711
        if (skip_seccomp_unavailable("ProtectKernelLogs="))
1,127✔
1712
                return 0;
1713

1714
        return seccomp_protect_syslog();
1,127✔
1715
}
1716

1717
static int apply_protect_clock(const ExecContext *c, const ExecParameters *p) {
9,541✔
1718
        assert(c);
9,541✔
1719
        assert(p);
9,541✔
1720

1721
        if (!c->protect_clock)
9,541✔
1722
                return 0;
1723

1724
        if (skip_seccomp_unavailable("ProtectClock="))
839✔
1725
                return 0;
1726

1727
        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_CLOCK, SCMP_ACT_ERRNO(EPERM), false);
839✔
1728
}
1729

1730
static int apply_private_devices(const ExecContext *c, const ExecParameters *p) {
9,541✔
1731
        assert(c);
9,541✔
1732
        assert(p);
9,541✔
1733

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

1736
        if (!c->private_devices)
9,541✔
1737
                return 0;
1738

1739
        if (skip_seccomp_unavailable("PrivateDevices="))
676✔
1740
                return 0;
1741

1742
        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_RAW_IO, SCMP_ACT_ERRNO(EPERM), false);
676✔
1743
}
1744

1745
static int apply_restrict_namespaces(const ExecContext *c, const ExecParameters *p) {
9,541✔
1746
        assert(c);
9,541✔
1747
        assert(p);
9,541✔
1748

1749
        if (!exec_context_restrict_namespaces_set(c))
9,541✔
1750
                return 0;
1751

1752
        if (skip_seccomp_unavailable("RestrictNamespaces="))
1,236✔
1753
                return 0;
1754

1755
        return seccomp_restrict_namespaces(c->restrict_namespaces);
1,236✔
1756
}
1757

1758
static int apply_lock_personality(const ExecContext *c, const ExecParameters *p) {
9,541✔
1759
        unsigned long personality;
9,541✔
1760
        int r;
9,541✔
1761

1762
        assert(c);
9,541✔
1763
        assert(p);
9,541✔
1764

1765
        if (!c->lock_personality)
9,541✔
1766
                return 0;
9,541✔
1767

1768
        if (skip_seccomp_unavailable("LockPersonality="))
1,490✔
1769
                return 0;
1770

1771
        personality = c->personality;
1,490✔
1772

1773
        /* If personality is not specified, use either PER_LINUX or PER_LINUX32 depending on what is currently set. */
1774
        if (personality == PERSONALITY_INVALID) {
1,490✔
1775

1776
                r = opinionated_personality(&personality);
1,490✔
1777
                if (r < 0)
1,490✔
1778
                        return r;
1779
        }
1780

1781
        return seccomp_lock_personality(personality);
1,490✔
1782
}
1783

1784
#endif
1785

1786
#if HAVE_LIBBPF
1787
static int apply_restrict_filesystems(const ExecContext *c, const ExecParameters *p) {
9,541✔
1788
        int r;
9,541✔
1789

1790
        assert(c);
9,541✔
1791
        assert(p);
9,541✔
1792

1793
        if (!exec_context_restrict_filesystems_set(c))
9,541✔
1794
                return 0;
1795

1796
        if (p->bpf_restrict_fs_map_fd < 0) {
×
1797
                /* LSM BPF is unsupported or lsm_bpf_setup failed */
1798
                log_debug("LSM BPF not supported, skipping RestrictFileSystems=");
×
1799
                return 0;
×
1800
        }
1801

1802
        /* We are in a new binary, so dl-open again */
1803
        r = dlopen_bpf();
×
1804
        if (r < 0)
×
1805
                return r;
1806

1807
        return bpf_restrict_fs_update(c->restrict_filesystems, p->cgroup_id, p->bpf_restrict_fs_map_fd, c->restrict_filesystems_allow_list);
×
1808
}
1809
#endif
1810

1811
static int apply_protect_hostname(const ExecContext *c, const ExecParameters *p, int *ret_exit_status) {
9,544✔
1812
        int r;
9,544✔
1813

1814
        assert(c);
9,544✔
1815
        assert(p);
9,544✔
1816
        assert(ret_exit_status);
9,544✔
1817

1818
        if (c->protect_hostname == PROTECT_HOSTNAME_NO)
9,544✔
1819
                return 0;
1820

1821
        if (namespace_type_supported(NAMESPACE_UTS)) {
666✔
1822
                if (unshare(CLONE_NEWUTS) < 0) {
666✔
1823
                        if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno)) {
×
1824
                                *ret_exit_status = EXIT_NAMESPACE;
×
1825
                                return log_error_errno(errno, "Failed to set up UTS namespacing: %m");
×
1826
                        }
1827

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

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

1842
#if HAVE_SECCOMP
1843
        if (c->protect_hostname == PROTECT_HOSTNAME_YES) {
666✔
1844
                if (skip_seccomp_unavailable("ProtectHostname="))
660✔
1845
                        return 0;
1846

1847
                r = seccomp_protect_hostname();
660✔
1848
                if (r < 0) {
660✔
1849
                        *ret_exit_status = EXIT_SECCOMP;
×
1850
                        return log_error_errno(r, "Failed to apply hostname restrictions: %m");
×
1851
                }
1852
        }
1853
#endif
1854

1855
        return 1;
1856
}
1857

1858
static void do_idle_pipe_dance(int idle_pipe[static 4]) {
153✔
1859
        assert(idle_pipe);
153✔
1860

1861
        idle_pipe[1] = safe_close(idle_pipe[1]);
153✔
1862
        idle_pipe[2] = safe_close(idle_pipe[2]);
153✔
1863

1864
        if (idle_pipe[0] >= 0) {
153✔
1865
                int r;
153✔
1866

1867
                r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
153✔
1868

1869
                if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
153✔
1870
                        ssize_t n;
112✔
1871

1872
                        /* Signal systemd that we are bored and want to continue. */
1873
                        n = write(idle_pipe[3], "x", 1);
112✔
1874
                        if (n > 0)
112✔
1875
                                /* Wait for systemd to react to the signal above. */
1876
                                (void) fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
112✔
1877
                }
1878

1879
                idle_pipe[0] = safe_close(idle_pipe[0]);
153✔
1880

1881
        }
1882

1883
        idle_pipe[3] = safe_close(idle_pipe[3]);
153✔
1884
}
153✔
1885

1886
static const char *exec_directory_env_name_to_string(ExecDirectoryType t);
1887

1888
/* And this table also maps ExecDirectoryType, to the environment variable we pass the selected directory to
1889
 * the service payload in. */
1890
static const char* const exec_directory_env_name_table[_EXEC_DIRECTORY_TYPE_MAX] = {
1891
        [EXEC_DIRECTORY_RUNTIME]       = "RUNTIME_DIRECTORY",
1892
        [EXEC_DIRECTORY_STATE]         = "STATE_DIRECTORY",
1893
        [EXEC_DIRECTORY_CACHE]         = "CACHE_DIRECTORY",
1894
        [EXEC_DIRECTORY_LOGS]          = "LOGS_DIRECTORY",
1895
        [EXEC_DIRECTORY_CONFIGURATION] = "CONFIGURATION_DIRECTORY",
1896
};
1897

1898
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(exec_directory_env_name, ExecDirectoryType);
2,491✔
1899

1900
static int build_environment(
9,566✔
1901
                const ExecContext *c,
1902
                const ExecParameters *p,
1903
                const CGroupContext *cgroup_context,
1904
                size_t n_fds,
1905
                const char *home,
1906
                const char *username,
1907
                const char *shell,
1908
                dev_t journal_stream_dev,
1909
                ino_t journal_stream_ino,
1910
                const char *memory_pressure_path,
1911
                bool needs_sandboxing,
1912
                char ***ret) {
1913

1914
        _cleanup_strv_free_ char **our_env = NULL;
9,566✔
1915
        size_t n_env = 0;
9,566✔
1916
        char *x;
9,566✔
1917
        int r;
9,566✔
1918

1919
        assert(c);
9,566✔
1920
        assert(p);
9,566✔
1921
        assert(cgroup_context);
9,566✔
1922
        assert(ret);
9,566✔
1923

1924
#define N_ENV_VARS 21
1925
        our_env = new0(char*, N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
9,566✔
1926
        if (!our_env)
9,566✔
1927
                return -ENOMEM;
1928

1929
        if (n_fds > 0) {
9,566✔
1930
                _cleanup_free_ char *joined = NULL;
1,535✔
1931

1932
                if (asprintf(&x, "LISTEN_PID="PID_FMT, getpid_cached()) < 0)
1,535✔
1933
                        return -ENOMEM;
1934
                our_env[n_env++] = x;
1,535✔
1935

1936
                if (asprintf(&x, "LISTEN_FDS=%zu", n_fds) < 0)
1,535✔
1937
                        return -ENOMEM;
1938
                our_env[n_env++] = x;
1,535✔
1939

1940
                joined = strv_join(p->fd_names, ":");
1,535✔
1941
                if (!joined)
1,535✔
1942
                        return -ENOMEM;
1943

1944
                x = strjoin("LISTEN_FDNAMES=", joined);
1,535✔
1945
                if (!x)
1,535✔
1946
                        return -ENOMEM;
1947
                our_env[n_env++] = x;
1,535✔
1948
        }
1949

1950
        if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) {
9,566✔
1951
                if (asprintf(&x, "WATCHDOG_PID="PID_FMT, getpid_cached()) < 0)
1,484✔
1952
                        return -ENOMEM;
1953
                our_env[n_env++] = x;
1,484✔
1954

1955
                if (asprintf(&x, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec) < 0)
1,484✔
1956
                        return -ENOMEM;
1957
                our_env[n_env++] = x;
1,484✔
1958
        }
1959

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

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

1977
                r = get_fixed_user("root", /* prefer_nss = */ false, &username, NULL, NULL, &home, &shell);
6,780✔
1978
                if (r < 0)
6,780✔
1979
                        return log_debug_errno(r, "Failed to determine user credentials for root: %m");
×
1980
        }
1981

1982
        bool set_user_login_env = exec_context_get_set_login_environment(c);
9,566✔
1983

1984
        if (username) {
9,566✔
1985
                x = strjoin("USER=", username);
8,774✔
1986
                if (!x)
8,774✔
1987
                        return -ENOMEM;
1988
                our_env[n_env++] = x;
8,774✔
1989

1990
                if (set_user_login_env) {
8,774✔
1991
                        x = strjoin("LOGNAME=", username);
1,994✔
1992
                        if (!x)
1,994✔
1993
                                return -ENOMEM;
1994
                        our_env[n_env++] = x;
1,994✔
1995
                }
1996
        }
1997

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

2001
        if (home && set_user_login_env && !empty_or_root(home)) {
9,566✔
2002
                x = strjoin("HOME=", home);
401✔
2003
                if (!x)
401✔
2004
                        return -ENOMEM;
2005

2006
                path_simplify(x + 5);
401✔
2007
                our_env[n_env++] = x;
401✔
2008
        }
2009

2010
        if (shell && set_user_login_env && !shell_is_placeholder(shell)) {
9,566✔
2011
                x = strjoin("SHELL=", shell);
403✔
2012
                if (!x)
403✔
2013
                        return -ENOMEM;
2014

2015
                path_simplify(x + 6);
403✔
2016
                our_env[n_env++] = x;
403✔
2017
        }
2018

2019
        if (!sd_id128_is_null(p->invocation_id)) {
9,566✔
2020
                assert(p->invocation_id_string);
9,566✔
2021

2022
                x = strjoin("INVOCATION_ID=", p->invocation_id_string);
9,566✔
2023
                if (!x)
9,566✔
2024
                        return -ENOMEM;
2025

2026
                our_env[n_env++] = x;
9,566✔
2027
        }
2028

2029
        if (exec_context_needs_term(c)) {
9,566✔
2030
                _cleanup_free_ char *cmdline = NULL;
448✔
2031
                const char *tty_path, *term = NULL;
448✔
2032

2033
                tty_path = exec_context_tty_path(c);
448✔
2034

2035
                /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try
2036
                 * to inherit the $TERM set for PID 1. This is useful for containers so that the $TERM the
2037
                 * container manager passes to PID 1 ends up all the way in the console login shown. */
2038

2039
                if (path_equal(tty_path, "/dev/console") && getppid() == 1)
448✔
2040
                        term = getenv("TERM");
391✔
2041
                else if (tty_path && in_charset(skip_dev_prefix(tty_path), ALPHANUMERICAL)) {
57✔
2042
                        _cleanup_free_ char *key = NULL;
41✔
2043

2044
                        key = strjoin("systemd.tty.term.", skip_dev_prefix(tty_path));
41✔
2045
                        if (!key)
41✔
2046
                                return -ENOMEM;
×
2047

2048
                        r = proc_cmdline_get_key(key, 0, &cmdline);
41✔
2049
                        if (r < 0)
41✔
2050
                                log_debug_errno(r, "Failed to read %s from kernel cmdline, ignoring: %m", key);
41✔
2051
                        else if (r > 0)
41✔
2052
                                term = cmdline;
×
2053
                }
2054

2055
                if (!term) {
432✔
2056
                        /* If no precise $TERM is known and we pick a fallback default, then let's also set
2057
                         * $COLORTERM=truecolor. That's because our fallback default is vt220, which is
2058
                         * generally a safe bet (as it supports PageUp/PageDown unlike vt100, and is quite
2059
                         * universally available in terminfo/termcap), except for the fact that real DEC
2060
                         * vt220 gear never actually supported color. Most tools these days generate color on
2061
                         * vt220 anyway, ignoring the physical capabilities of the real hardware, but some
2062
                         * tools actually believe in the historical truth. Which is unfortunate since *we*
2063
                         * *don't* care about the historical truth, we just want sane defaults if nothing
2064
                         * better is explicitly configured. It's 2025 after all, at the time of writing,
2065
                         * pretty much all terminal emulators actually *do* support color, hence if we don't
2066
                         * know any better let's explicitly claim color support via $COLORTERM. Or in other
2067
                         * words: we now explicitly claim to be connected to a franken-vt220 with true color
2068
                         * support. */
2069
                        x = strdup("COLORTERM=truecolor");
57✔
2070
                        if (!x)
57✔
2071
                                return -ENOMEM;
2072

2073
                        our_env[n_env++] = x;
57✔
2074

2075
                        term = default_term_for_tty(tty_path);
57✔
2076
                }
2077

2078
                x = strjoin("TERM=", term);
448✔
2079
                if (!x)
448✔
2080
                        return -ENOMEM;
2081
                our_env[n_env++] = x;
448✔
2082
        }
2083

2084
        if (journal_stream_dev != 0 && journal_stream_ino != 0) {
9,566✔
2085
                if (asprintf(&x, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino) < 0)
8,796✔
2086
                        return -ENOMEM;
2087

2088
                our_env[n_env++] = x;
8,796✔
2089
        }
2090

2091
        if (c->log_namespace) {
9,566✔
2092
                x = strjoin("LOG_NAMESPACE=", c->log_namespace);
2✔
2093
                if (!x)
2✔
2094
                        return -ENOMEM;
2095

2096
                our_env[n_env++] = x;
2✔
2097
        }
2098

2099
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
57,396✔
2100
                _cleanup_free_ char *joined = NULL;
47,830✔
2101
                const char *n;
47,830✔
2102

2103
                if (!p->prefix[t])
47,830✔
2104
                        continue;
×
2105

2106
                if (c->directories[t].n_items == 0)
47,830✔
2107
                        continue;
45,339✔
2108

2109
                n = exec_directory_env_name_to_string(t);
2,491✔
2110
                if (!n)
2,491✔
2111
                        continue;
×
2112

2113
                for (size_t i = 0; i < c->directories[t].n_items; i++) {
5,478✔
2114
                        _cleanup_free_ char *prefixed = NULL;
2,987✔
2115

2116
                        prefixed = path_join(p->prefix[t], c->directories[t].items[i].path);
2,987✔
2117
                        if (!prefixed)
2,987✔
2118
                                return -ENOMEM;
2119

2120
                        if (!strextend_with_separator(&joined, ":", prefixed))
2,987✔
2121
                                return -ENOMEM;
2122
                }
2123

2124
                x = strjoin(n, "=", joined);
2,491✔
2125
                if (!x)
2,491✔
2126
                        return -ENOMEM;
2127

2128
                our_env[n_env++] = x;
2,491✔
2129
        }
2130

2131
        _cleanup_free_ char *creds_dir = NULL;
9,566✔
2132
        r = exec_context_get_credential_directory(c, p, p->unit_id, &creds_dir);
9,566✔
2133
        if (r < 0)
9,566✔
2134
                return r;
2135
        if (r > 0) {
9,566✔
2136
                x = strjoin("CREDENTIALS_DIRECTORY=", creds_dir);
1,940✔
2137
                if (!x)
1,940✔
2138
                        return -ENOMEM;
2139

2140
                our_env[n_env++] = x;
1,940✔
2141
        }
2142

2143
        if (asprintf(&x, "SYSTEMD_EXEC_PID=" PID_FMT, getpid_cached()) < 0)
9,566✔
2144
                return -ENOMEM;
2145

2146
        our_env[n_env++] = x;
9,566✔
2147

2148
        if (memory_pressure_path) {
9,566✔
2149
                x = strjoin("MEMORY_PRESSURE_WATCH=", memory_pressure_path);
9,167✔
2150
                if (!x)
9,167✔
2151
                        return -ENOMEM;
2152

2153
                our_env[n_env++] = x;
9,167✔
2154

2155
                if (!path_equal(memory_pressure_path, "/dev/null")) {
9,167✔
2156
                        _cleanup_free_ char *b = NULL, *e = NULL;
9,167✔
2157

2158
                        if (asprintf(&b, "%s " USEC_FMT " " USEC_FMT,
9,167✔
2159
                                     MEMORY_PRESSURE_DEFAULT_TYPE,
2160
                                     cgroup_context->memory_pressure_threshold_usec == USEC_INFINITY ? MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC :
9,167✔
2161
                                     CLAMP(cgroup_context->memory_pressure_threshold_usec, 1U, MEMORY_PRESSURE_DEFAULT_WINDOW_USEC),
9,167✔
2162
                                     MEMORY_PRESSURE_DEFAULT_WINDOW_USEC) < 0)
2163
                                return -ENOMEM;
2164

2165
                        if (base64mem(b, strlen(b) + 1, &e) < 0)
9,167✔
2166
                                return -ENOMEM;
2167

2168
                        x = strjoin("MEMORY_PRESSURE_WRITE=", e);
9,167✔
2169
                        if (!x)
9,167✔
2170
                                return -ENOMEM;
2171

2172
                        our_env[n_env++] = x;
9,167✔
2173
                }
2174
        }
2175

2176
        if (p->notify_socket) {
9,566✔
2177
                x = strjoin("NOTIFY_SOCKET=", exec_get_private_notify_socket_path(c, p, needs_sandboxing) ?: p->notify_socket);
1,887✔
2178
                if (!x)
1,887✔
2179
                        return -ENOMEM;
2180

2181
                our_env[n_env++] = x;
1,887✔
2182
        }
2183

2184
        assert(n_env < N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
9,566✔
2185
#undef N_ENV_VARS
2186

2187
        *ret = TAKE_PTR(our_env);
9,566✔
2188

2189
        return 0;
9,566✔
2190
}
2191

2192
static int build_pass_environment(const ExecContext *c, char ***ret) {
9,566✔
2193
        _cleanup_strv_free_ char **pass_env = NULL;
9,566✔
2194
        size_t n_env = 0;
9,566✔
2195

2196
        assert(c);
9,566✔
2197
        assert(ret);
9,566✔
2198

2199
        STRV_FOREACH(i, c->pass_environment) {
9,869✔
2200
                _cleanup_free_ char *x = NULL;
×
2201
                char *v;
303✔
2202

2203
                v = getenv(*i);
303✔
2204
                if (!v)
303✔
2205
                        continue;
×
2206
                x = strjoin(*i, "=", v);
303✔
2207
                if (!x)
303✔
2208
                        return -ENOMEM;
2209

2210
                if (!GREEDY_REALLOC(pass_env, n_env + 2))
303✔
2211
                        return -ENOMEM;
2212

2213
                pass_env[n_env++] = TAKE_PTR(x);
303✔
2214
                pass_env[n_env] = NULL;
303✔
2215
        }
2216

2217
        *ret = TAKE_PTR(pass_env);
9,566✔
2218
        return 0;
9,566✔
2219
}
2220

2221
static int setup_private_users(PrivateUsers private_users, uid_t ouid, gid_t ogid, uid_t uid, gid_t gid, bool allow_setgroups) {
9,550✔
2222
        _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
9,550✔
2223
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
9,550✔
2224
        _cleanup_close_ int unshare_ready_fd = -EBADF;
9,550✔
2225
        _cleanup_(sigkill_waitp) pid_t pid = 0;
9,550✔
2226
        uint64_t c = 1;
9,550✔
2227
        ssize_t n;
9,550✔
2228
        int r;
9,550✔
2229

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

2240
        if (private_users == PRIVATE_USERS_NO)
9,550✔
2241
                return 0;
2242

2243
        if (private_users == PRIVATE_USERS_IDENTITY) {
50✔
2244
                uid_map = strdup("0 0 65536\n");
4✔
2245
                if (!uid_map)
4✔
2246
                        return -ENOMEM;
2247
        } else if (private_users == PRIVATE_USERS_FULL) {
46✔
2248
                /* Map all UID/GID from original to new user namespace. We can't use `0 0 UINT32_MAX` because
2249
                 * this is the same UID/GID map as the init user namespace and systemd's running_in_userns()
2250
                 * checks whether its in a user namespace by comparing uid_map/gid_map to `0 0 UINT32_MAX`.
2251
                 * Thus, we still map all UIDs/GIDs but do it using two extents to differentiate the new user
2252
                 * namespace from the init namespace:
2253
                 *   0 0 1
2254
                 *   1 1 UINT32_MAX - 1
2255
                 *
2256
                 * systemd will remove the heuristic in running_in_userns() and use namespace inodes in version 258
2257
                 * (PR #35382). But some users may be running a container image with older systemd < 258 so we keep
2258
                 * this uid_map/gid_map hack until version 259 for version N-1 compatibility.
2259
                 *
2260
                 * TODO: Switch to `0 0 UINT32_MAX` in systemd v259.
2261
                 *
2262
                 * Note the kernel defines the UID range between 0 and UINT32_MAX so we map all UIDs even though
2263
                 * the UID range beyond INT32_MAX (e.g. i.e. the range above the signed 32-bit range) is
2264
                 * icky. For example, setfsuid() returns the old UID as signed integer. But units can decide to
2265
                 * use these UIDs/GIDs so we need to map them. */
2266
                r = asprintf(&uid_map, "0 0 1\n"
3✔
2267
                                       "1 1 " UID_FMT "\n", (uid_t) (UINT32_MAX - 1));
2268
                if (r < 0)
3✔
2269
                        return -ENOMEM;
2270
        /* Can only set up multiple mappings with CAP_SETUID. */
2271
        } else if (have_effective_cap(CAP_SETUID) > 0 && uid != ouid && uid_is_valid(uid)) {
43✔
2272
                r = asprintf(&uid_map,
2✔
2273
                             UID_FMT " " UID_FMT " 1\n"     /* Map $OUID → $OUID */
2274
                             UID_FMT " " UID_FMT " 1\n",    /* Map $UID → $UID */
2275
                             ouid, ouid, uid, uid);
2276
                if (r < 0)
2✔
2277
                        return -ENOMEM;
2278
        } else {
2279
                r = asprintf(&uid_map,
41✔
2280
                             UID_FMT " " UID_FMT " 1\n",    /* Map $OUID → $OUID */
2281
                             ouid, ouid);
2282
                if (r < 0)
41✔
2283
                        return -ENOMEM;
2284
        }
2285

2286
        if (private_users == PRIVATE_USERS_IDENTITY) {
50✔
2287
                gid_map = strdup("0 0 65536\n");
4✔
2288
                if (!gid_map)
4✔
2289
                        return -ENOMEM;
2290
        } else if (private_users == PRIVATE_USERS_FULL) {
46✔
2291
                r = asprintf(&gid_map, "0 0 1\n"
3✔
2292
                                       "1 1 " GID_FMT "\n", (gid_t) (UINT32_MAX - 1));
2293
                if (r < 0)
3✔
2294
                        return -ENOMEM;
2295
        /* Can only set up multiple mappings with CAP_SETGID. */
2296
        } else if (have_effective_cap(CAP_SETGID) > 0 && gid != ogid && gid_is_valid(gid)) {
59✔
2297
                r = asprintf(&gid_map,
2✔
2298
                             GID_FMT " " GID_FMT " 1\n"     /* Map $OGID → $OGID */
2299
                             GID_FMT " " GID_FMT " 1\n",    /* Map $GID → $GID */
2300
                             ogid, ogid, gid, gid);
2301
                if (r < 0)
2✔
2302
                        return -ENOMEM;
2303
        } else {
2304
                r = asprintf(&gid_map,
41✔
2305
                             GID_FMT " " GID_FMT " 1\n",    /* Map $OGID -> $OGID */
2306
                             ogid, ogid);
2307
                if (r < 0)
41✔
2308
                        return -ENOMEM;
2309
        }
2310

2311
        /* Create a communication channel so that the parent can tell the child when it finished creating the user
2312
         * namespace. */
2313
        unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
50✔
2314
        if (unshare_ready_fd < 0)
50✔
2315
                return -errno;
×
2316

2317
        /* Create a communication channel so that the child can tell the parent a proper error code in case it
2318
         * failed. */
2319
        if (pipe2(errno_pipe, O_CLOEXEC) < 0)
50✔
2320
                return -errno;
×
2321

2322
        r = safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL, &pid);
50✔
2323
        if (r < 0)
100✔
2324
                return r;
2325
        if (r == 0) {
100✔
2326
                _cleanup_close_ int fd = -EBADF;
×
2327
                const char *a;
50✔
2328
                pid_t ppid;
50✔
2329

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

2333
                ppid = getppid();
50✔
2334
                errno_pipe[0] = safe_close(errno_pipe[0]);
50✔
2335

2336
                /* Wait until the parent unshared the user namespace */
2337
                if (read(unshare_ready_fd, &c, sizeof(c)) < 0)
50✔
2338
                        report_errno_and_exit(errno_pipe[1], -errno);
×
2339

2340
                /* Disable the setgroups() system call in the child user namespace, for good, unless PrivateUsers=full
2341
                 * and using the system service manager. */
2342
                a = procfs_file_alloca(ppid, "setgroups");
50✔
2343
                fd = open(a, O_WRONLY|O_CLOEXEC);
50✔
2344
                if (fd < 0) {
50✔
2345
                        if (errno != ENOENT) {
×
2346
                                r = log_debug_errno(errno, "Failed to open %s: %m", a);
×
2347
                                report_errno_and_exit(errno_pipe[1], r);
×
2348
                        }
2349

2350
                        /* If the file is missing the kernel is too old, let's continue anyway. */
2351
                } else {
2352
                        const char *setgroups = allow_setgroups ? "allow\n" : "deny\n";
50✔
2353
                        if (write(fd, setgroups, strlen(setgroups)) < 0) {
50✔
2354
                                r = log_debug_errno(errno, "Failed to write '%s' to %s: %m", setgroups, a);
×
2355
                                report_errno_and_exit(errno_pipe[1], r);
×
2356
                        }
2357

2358
                        fd = safe_close(fd);
50✔
2359
                }
2360

2361
                /* First write the GID map */
2362
                a = procfs_file_alloca(ppid, "gid_map");
50✔
2363
                fd = open(a, O_WRONLY|O_CLOEXEC);
50✔
2364
                if (fd < 0) {
50✔
2365
                        r = log_debug_errno(errno, "Failed to open %s: %m", a);
×
2366
                        report_errno_and_exit(errno_pipe[1], r);
×
2367
                }
2368

2369
                if (write(fd, gid_map, strlen(gid_map)) < 0) {
50✔
2370
                        r = log_debug_errno(errno, "Failed to write GID map to %s: %m", a);
×
2371
                        report_errno_and_exit(errno_pipe[1], r);
×
2372
                }
2373

2374
                fd = safe_close(fd);
50✔
2375

2376
                /* The write the UID map */
2377
                a = procfs_file_alloca(ppid, "uid_map");
50✔
2378
                fd = open(a, O_WRONLY|O_CLOEXEC);
50✔
2379
                if (fd < 0) {
50✔
2380
                        r = log_debug_errno(errno, "Failed to open %s: %m", a);
×
2381
                        report_errno_and_exit(errno_pipe[1], r);
×
2382
                }
2383

2384
                if (write(fd, uid_map, strlen(uid_map)) < 0) {
50✔
2385
                        r = log_debug_errno(errno, "Failed to write UID map to %s: %m", a);
×
2386
                        report_errno_and_exit(errno_pipe[1], r);
×
2387
                }
2388

2389
                _exit(EXIT_SUCCESS);
50✔
2390
        }
2391

2392
        errno_pipe[1] = safe_close(errno_pipe[1]);
50✔
2393

2394
        if (unshare(CLONE_NEWUSER) < 0)
50✔
2395
                return log_debug_errno(errno, "Failed to unshare user namespace: %m");
×
2396

2397
        /* Let the child know that the namespace is ready now */
2398
        if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
50✔
2399
                return -errno;
×
2400

2401
        /* Try to read an error code from the child */
2402
        n = read(errno_pipe[0], &r, sizeof(r));
50✔
2403
        if (n < 0)
50✔
2404
                return -errno;
×
2405
        if (n == sizeof(r)) { /* an error code was sent to us */
50✔
2406
                if (r < 0)
×
2407
                        return r;
2408
                return -EIO;
×
2409
        }
2410
        if (n != 0) /* on success we should have read 0 bytes */
50✔
2411
                return -EIO;
2412

2413
        r = wait_for_terminate_and_check("(sd-userns)", TAKE_PID(pid), 0);
50✔
2414
        if (r < 0)
50✔
2415
                return r;
2416
        if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
50✔
2417
                return -EIO;
×
2418

2419
        return 1;
2420
}
2421

2422
static int can_mount_proc(void) {
8✔
2423
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
4✔
2424
        _cleanup_(sigkill_waitp) pid_t pid = 0;
×
2425
        ssize_t n;
8✔
2426
        int r;
8✔
2427

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

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

2437
        /* Fork a child process into its own mount and PID namespace. Note safe_fork() already remounts / as SLAVE
2438
         * with FORK_MOUNTNS_SLAVE. */
2439
        r = safe_fork("(sd-proc-check)",
8✔
2440
                      FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE|FORK_NEW_PIDNS, &pid);
2441
        if (r < 0)
8✔
2442
                return log_debug_errno(r, "Failed to fork child process (sd-proc-check): %m");
×
2443
        if (r == 0) {
8✔
2444
                errno_pipe[0] = safe_close(errno_pipe[0]);
4✔
2445

2446
                /* Try mounting /proc on /dev/shm/. No need to clean up the mount since the mount
2447
                 * namespace will be cleaned up once the process exits. */
2448
                r = mount_follow_verbose(LOG_DEBUG, "proc", "/dev/shm/", "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
4✔
2449
                if (r < 0) {
4✔
2450
                        (void) write(errno_pipe[1], &r, sizeof(r));
1✔
2451
                        _exit(EXIT_FAILURE);
1✔
2452
                }
2453

2454
                _exit(EXIT_SUCCESS);
3✔
2455
        }
2456

2457
        errno_pipe[1] = safe_close(errno_pipe[1]);
4✔
2458

2459
        /* Try to read an error code from the child */
2460
        n = read(errno_pipe[0], &r, sizeof(r));
4✔
2461
        if (n < 0)
4✔
2462
                return log_debug_errno(errno, "Failed to read errno from pipe with child process (sd-proc-check): %m");
×
2463
        if (n == sizeof(r)) { /* an error code was sent to us */
4✔
2464
                /* This is the expected case where proc cannot be mounted due to permissions. */
2465
                if (ERRNO_IS_NEG_PRIVILEGE(r))
4✔
2466
                        return 0;
2467
                if (r < 0)
×
2468
                        return r;
2469

2470
                return -EIO;
×
2471
        }
2472
        if (n != 0) /* on success we should have read 0 bytes */
3✔
2473
                return -EIO;
2474

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

2481
        return 1;
2482
}
2483

2484
static int setup_private_pids(const ExecContext *c, ExecParameters *p) {
8✔
2485
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
×
2486
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
6✔
2487
        ssize_t n;
8✔
2488
        int r, q;
8✔
2489

2490
        assert(c);
8✔
2491
        assert(p);
8✔
2492
        assert(p->pidref_transport_fd >= 0);
8✔
2493

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

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

2504
        /* Set FORK_DETACH to immediately re-parent the child process to the invoking manager process. */
2505
        r = pidref_safe_fork("(sd-pidns-child)", FORK_NEW_PIDNS|FORK_DETACH, &pidref);
8✔
2506
        if (r < 0)
14✔
2507
                return log_debug_errno(r, "Failed to fork child into new pid namespace: %m");
×
2508
        if (r > 0) {
14✔
2509
                errno_pipe[0] = safe_close(errno_pipe[0]);
8✔
2510

2511
                /* In the parent process, we send the child pidref to the manager and exit.
2512
                 * If PIDFD is not supported, only the child PID is sent. The server then
2513
                 * uses the child PID to set the new exec main process. */
2514
                q = send_one_fd_iov(
8✔
2515
                                p->pidref_transport_fd,
2516
                                pidref.fd,
2517
                                &IOVEC_MAKE(&pidref.pid, sizeof(pidref.pid)),
2518
                                /*iovlen=*/ 1,
2519
                                /*flags=*/ 0);
2520
                /* Send error code to child process. */
2521
                (void) write(errno_pipe[1], &q, sizeof(q));
8✔
2522
                /* Exit here so we only go through the destructors in exec_invoke only once - in the child - as
2523
                 * some destructors have external effects. The main codepaths continue in the child process. */
2524
                _exit(q < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
8✔
2525
        }
2526

2527
        errno_pipe[1] = safe_close(errno_pipe[1]);
6✔
2528
        p->pidref_transport_fd = safe_close(p->pidref_transport_fd);
6✔
2529

2530
        /* Try to read an error code from the parent. Note a child process cannot wait for the parent so we always
2531
         * receive an errno even on success. */
2532
        n = read(errno_pipe[0], &r, sizeof(r));
6✔
2533
        if (n < 0)
6✔
2534
                return log_debug_errno(errno, "Failed to read errno from pipe with parent process: %m");
×
2535
        if (n != sizeof(r))
6✔
2536
                return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to read enough bytes from pipe with parent process");
×
2537
        if (r < 0)
6✔
2538
                return log_debug_errno(r, "Failed to send child pidref to manager: %m");
×
2539

2540
        /* NOTE! This function returns in the child process only. */
2541
        return r;
2542
}
2543

2544
static int create_many_symlinks(const char *root, const char *source, char **symlinks) {
1,526✔
2545
        _cleanup_free_ char *src_abs = NULL;
1,526✔
2546
        int r;
1,526✔
2547

2548
        assert(source);
1,526✔
2549

2550
        src_abs = path_join(root, source);
1,526✔
2551
        if (!src_abs)
1,526✔
2552
                return -ENOMEM;
2553

2554
        STRV_FOREACH(dst, symlinks) {
1,539✔
2555
                _cleanup_free_ char *dst_abs = NULL;
13✔
2556

2557
                dst_abs = path_join(root, *dst);
13✔
2558
                if (!dst_abs)
13✔
2559
                        return -ENOMEM;
2560

2561
                r = mkdir_parents_label(dst_abs, 0755);
13✔
2562
                if (r < 0)
13✔
2563
                        return r;
2564

2565
                r = symlink_idempotent(src_abs, dst_abs, true);
13✔
2566
                if (r < 0)
13✔
2567
                        return r;
2568
        }
2569

2570
        return 0;
2571
}
2572

2573
static int setup_exec_directory(
57,561✔
2574
                const ExecContext *context,
2575
                const ExecParameters *params,
2576
                uid_t uid,
2577
                gid_t gid,
2578
                ExecDirectoryType type,
2579
                bool needs_mount_namespace,
2580
                int *exit_status) {
2581

2582
        static const int exit_status_table[_EXEC_DIRECTORY_TYPE_MAX] = {
57,561✔
2583
                [EXEC_DIRECTORY_RUNTIME]       = EXIT_RUNTIME_DIRECTORY,
2584
                [EXEC_DIRECTORY_STATE]         = EXIT_STATE_DIRECTORY,
2585
                [EXEC_DIRECTORY_CACHE]         = EXIT_CACHE_DIRECTORY,
2586
                [EXEC_DIRECTORY_LOGS]          = EXIT_LOGS_DIRECTORY,
2587
                [EXEC_DIRECTORY_CONFIGURATION] = EXIT_CONFIGURATION_DIRECTORY,
2588
        };
2589
        int r;
57,561✔
2590

2591
        assert(context);
57,561✔
2592
        assert(params);
57,561✔
2593
        assert(type >= 0 && type < _EXEC_DIRECTORY_TYPE_MAX);
57,561✔
2594
        assert(exit_status);
57,561✔
2595

2596
        if (!params->prefix[type])
57,561✔
2597
                return 0;
2598

2599
        if (params->flags & EXEC_CHOWN_DIRECTORIES) {
57,561✔
2600
                if (!uid_is_valid(uid))
53,596✔
2601
                        uid = 0;
40,391✔
2602
                if (!gid_is_valid(gid))
53,596✔
2603
                        gid = 0;
40,371✔
2604
        }
2605

2606
        FOREACH_ARRAY(i, context->directories[type].items, context->directories[type].n_items) {
61,260✔
2607
                _cleanup_free_ char *p = NULL, *pp = NULL;
3,700✔
2608

2609
                p = path_join(params->prefix[type], i->path);
3,700✔
2610
                if (!p) {
3,700✔
2611
                        r = -ENOMEM;
×
2612
                        goto fail;
×
2613
                }
2614

2615
                r = mkdir_parents_label(p, 0755);
3,700✔
2616
                if (r < 0)
3,700✔
2617
                        goto fail;
×
2618

2619
                if (IN_SET(type, EXEC_DIRECTORY_STATE, EXEC_DIRECTORY_LOGS) && params->runtime_scope == RUNTIME_SCOPE_USER) {
3,700✔
2620

2621
                        /* If we are in user mode, and a configuration directory exists but a state directory
2622
                         * doesn't exist, then we likely are upgrading from an older systemd version that
2623
                         * didn't know the more recent addition to the xdg-basedir spec: the $XDG_STATE_HOME
2624
                         * directory. In older systemd versions EXEC_DIRECTORY_STATE was aliased to
2625
                         * EXEC_DIRECTORY_CONFIGURATION, with the advent of $XDG_STATE_HOME it is now
2626
                         * separated. If a service has both dirs configured but only the configuration dir
2627
                         * exists and the state dir does not, we assume we are looking at an update
2628
                         * situation. Hence, create a compatibility symlink, so that all expectations are
2629
                         * met.
2630
                         *
2631
                         * (We also do something similar with the log directory, which still doesn't exist in
2632
                         * the xdg basedir spec. We'll make it a subdir of the state dir.) */
2633

2634
                        /* this assumes the state dir is always created before the configuration dir */
2635
                        assert_cc(EXEC_DIRECTORY_STATE < EXEC_DIRECTORY_LOGS);
7✔
2636
                        assert_cc(EXEC_DIRECTORY_LOGS < EXEC_DIRECTORY_CONFIGURATION);
7✔
2637

2638
                        r = access_nofollow(p, F_OK);
7✔
2639
                        if (r == -ENOENT) {
7✔
2640
                                _cleanup_free_ char *q = NULL;
3✔
2641

2642
                                /* OK, we know that the state dir does not exist. Let's see if the dir exists
2643
                                 * under the configuration hierarchy. */
2644

2645
                                if (type == EXEC_DIRECTORY_STATE)
3✔
2646
                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], i->path);
3✔
2647
                                else if (type == EXEC_DIRECTORY_LOGS)
×
2648
                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], "log", i->path);
×
2649
                                else
2650
                                        assert_not_reached();
×
2651
                                if (!q) {
3✔
2652
                                        r = -ENOMEM;
×
2653
                                        goto fail;
×
2654
                                }
2655

2656
                                r = access_nofollow(q, F_OK);
3✔
2657
                                if (r >= 0) {
3✔
2658
                                        /* It does exist! This hence looks like an update. Symlink the
2659
                                         * configuration directory into the state directory. */
2660

2661
                                        r = symlink_idempotent(q, p, /* make_relative= */ true);
1✔
2662
                                        if (r < 0)
1✔
2663
                                                goto fail;
×
2664

2665
                                        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✔
2666
                                        continue;
1✔
2667
                                } else if (r != -ENOENT)
2✔
2668
                                        log_warning_errno(r, "Unable to detect whether unit configuration directory '%s' exists, assuming not: %m", q);
2✔
2669

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

2674
                if (exec_directory_is_private(context, type)) {
3,699✔
2675
                        /* So, here's one extra complication when dealing with DynamicUser=1 units. In that
2676
                         * case we want to avoid leaving a directory around fully accessible that is owned by
2677
                         * a dynamic user whose UID is later on reused. To lock this down we use the same
2678
                         * trick used by container managers to prohibit host users to get access to files of
2679
                         * the same UID in containers: we place everything inside a directory that has an
2680
                         * access mode of 0700 and is owned root:root, so that it acts as security boundary
2681
                         * for unprivileged host code. We then use fs namespacing to make this directory
2682
                         * permeable for the service itself.
2683
                         *
2684
                         * Specifically: for a service which wants a special directory "foo/" we first create
2685
                         * a directory "private/" with access mode 0700 owned by root:root. Then we place
2686
                         * "foo" inside of that directory (i.e. "private/foo/"), and make "foo" a symlink to
2687
                         * "private/foo". This way, privileged host users can access "foo/" as usual, but
2688
                         * unprivileged host users can't look into it. Inside of the namespace of the unit
2689
                         * "private/" is replaced by a more liberally accessible tmpfs, into which the host's
2690
                         * "private/foo/" is mounted under the same name, thus disabling the access boundary
2691
                         * for the service and making sure it only gets access to the dirs it needs but no
2692
                         * others. Tricky? Yes, absolutely, but it works!
2693
                         *
2694
                         * Note that we don't do this for EXEC_DIRECTORY_CONFIGURATION as that's assumed not
2695
                         * to be owned by the service itself.
2696
                         *
2697
                         * Also, note that we don't do this for EXEC_DIRECTORY_RUNTIME as that's often used
2698
                         * for sharing files or sockets with other services. */
2699

2700
                        pp = path_join(params->prefix[type], "private");
13✔
2701
                        if (!pp) {
13✔
2702
                                r = -ENOMEM;
×
2703
                                goto fail;
×
2704
                        }
2705

2706
                        /* First set up private root if it doesn't exist yet, with access mode 0700 and owned by root:root */
2707
                        r = mkdir_safe_label(pp, 0700, 0, 0, MKDIR_WARN_MODE);
13✔
2708
                        if (r < 0)
13✔
2709
                                goto fail;
×
2710

2711
                        if (!path_extend(&pp, i->path)) {
13✔
2712
                                r = -ENOMEM;
×
2713
                                goto fail;
×
2714
                        }
2715

2716
                        /* Create all directories between the configured directory and this private root, and mark them 0755 */
2717
                        r = mkdir_parents_label(pp, 0755);
13✔
2718
                        if (r < 0)
13✔
2719
                                goto fail;
×
2720

2721
                        if (is_dir(p, false) > 0 &&
13✔
2722
                            (access_nofollow(pp, F_OK) == -ENOENT)) {
×
2723

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

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

2732
                                r = RET_NERRNO(rename(p, pp));
×
2733
                                if (r < 0)
×
2734
                                        goto fail;
×
2735
                        } else {
2736
                                /* Otherwise, create the actual directory for the service */
2737

2738
                                r = mkdir_label(pp, context->directories[type].mode);
13✔
2739
                                if (r < 0 && r != -EEXIST)
13✔
2740
                                        goto fail;
×
2741
                        }
2742

2743
                        if (!FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE)) {
13✔
2744
                                /* And link it up from the original place.
2745
                                 * Notes
2746
                                 * 1) If a mount namespace is going to be used, then this symlink remains on
2747
                                 *    the host, and a new one for the child namespace will be created later.
2748
                                 * 2) It is not necessary to create this symlink when one of its parent
2749
                                 *    directories is specified and already created. E.g.
2750
                                 *        StateDirectory=foo foo/bar
2751
                                 *    In that case, the inode points to pp and p for "foo/bar" are the same:
2752
                                 *        pp = "/var/lib/private/foo/bar"
2753
                                 *        p = "/var/lib/foo/bar"
2754
                                 *    and, /var/lib/foo is a symlink to /var/lib/private/foo. So, not only
2755
                                 *    we do not need to create the symlink, but we cannot create the symlink.
2756
                                 *    See issue #24783. */
2757
                                r = symlink_idempotent(pp, p, true);
13✔
2758
                                if (r < 0)
13✔
2759
                                        goto fail;
×
2760
                        }
2761

2762
                } else {
2763
                        _cleanup_free_ char *target = NULL;
3,686✔
2764

2765
                        if (EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type) &&
7,332✔
2766
                            readlink_and_make_absolute(p, &target) >= 0) {
3,646✔
2767
                                _cleanup_free_ char *q = NULL, *q_resolved = NULL, *target_resolved = NULL;
11✔
2768

2769
                                /* This already exists and is a symlink? Interesting. Maybe it's one created
2770
                                 * by DynamicUser=1 (see above)?
2771
                                 *
2772
                                 * We do this for all directory types except for ConfigurationDirectory=,
2773
                                 * since they all support the private/ symlink logic at least in some
2774
                                 * configurations, see above. */
2775

2776
                                r = chase(target, NULL, 0, &target_resolved, NULL);
11✔
2777
                                if (r < 0)
11✔
2778
                                        goto fail;
×
2779

2780
                                q = path_join(params->prefix[type], "private", i->path);
11✔
2781
                                if (!q) {
11✔
2782
                                        r = -ENOMEM;
×
2783
                                        goto fail;
×
2784
                                }
2785

2786
                                /* /var/lib or friends may be symlinks. So, let's chase them also. */
2787
                                r = chase(q, NULL, CHASE_NONEXISTENT, &q_resolved, NULL);
11✔
2788
                                if (r < 0)
11✔
2789
                                        goto fail;
×
2790

2791
                                if (path_equal(q_resolved, target_resolved)) {
11✔
2792

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

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

2800
                                        r = RET_NERRNO(unlink(p));
8✔
2801
                                        if (r < 0)
×
2802
                                                goto fail;
×
2803

2804
                                        r = RET_NERRNO(rename(q, p));
11✔
2805
                                        if (r < 0)
×
2806
                                                goto fail;
×
2807
                                }
2808
                        }
2809

2810
                        r = mkdir_label(p, context->directories[type].mode);
3,686✔
2811
                        if (r < 0) {
3,686✔
2812
                                if (r != -EEXIST)
2,642✔
2813
                                        goto fail;
×
2814

2815
                                if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type)) {
2,642✔
2816
                                        struct stat st;
27✔
2817

2818
                                        /* Don't change the owner/access mode of the configuration directory,
2819
                                         * as in the common case it is not written to by a service, and shall
2820
                                         * not be writable. */
2821

2822
                                        r = RET_NERRNO(stat(p, &st));
27✔
2823
                                        if (r < 0)
×
2824
                                                goto fail;
×
2825

2826
                                        /* Still complain if the access mode doesn't match */
2827
                                        if (((st.st_mode ^ context->directories[type].mode) & 07777) != 0)
27✔
2828
                                                log_warning("%s \'%s\' already exists but the mode is different. "
×
2829
                                                            "(File system: %o %sMode: %o)",
2830
                                                            exec_directory_type_to_string(type), i->path,
2831
                                                            st.st_mode & 07777, exec_directory_type_to_string(type), context->directories[type].mode & 07777);
2832

2833
                                        continue;
27✔
2834
                                }
2835
                        }
2836
                }
2837

2838
                /* Lock down the access mode (we use chmod_and_chown() to make this idempotent. We don't
2839
                 * specify UID/GID here, so that path_chown_recursive() can optimize things depending on the
2840
                 * current UID/GID ownership.) */
2841
                const char *target_dir = pp ?: p;
3,672✔
2842
                r = chmod_and_chown(target_dir, context->directories[type].mode, UID_INVALID, GID_INVALID);
3,672✔
2843
                if (r < 0)
3,672✔
2844
                        goto fail;
×
2845

2846
                /* Skip the rest (which deals with ownership) in user mode, since ownership changes are not
2847
                 * available to user code anyway */
2848
                if (params->runtime_scope != RUNTIME_SCOPE_SYSTEM)
3,672✔
2849
                        continue;
9✔
2850

2851
                int idmapping_supported = is_idmapping_supported(target_dir);
3,663✔
2852
                if (idmapping_supported < 0) {
3,663✔
2853
                        r = log_debug_errno(idmapping_supported, "Unable to determine if ID mapping is supported on mount '%s': %m", target_dir);
×
2854
                        goto fail;
×
2855
                }
2856

2857
                log_debug("ID-mapping is%ssupported for exec directory %s", idmapping_supported ? " " : " not ", target_dir);
3,669✔
2858

2859
                /* Change the ownership of the whole tree, if necessary. When dynamic users are used we
2860
                 * drop the suid/sgid bits, since we really don't want SUID/SGID files for dynamic UID/GID
2861
                 * assignments to exist. */
2862
                uid_t chown_uid = uid;
3,663✔
2863
                gid_t chown_gid = gid;
3,663✔
2864
                bool do_chown = false;
3,663✔
2865

2866
                if (uid == 0 || gid == 0 || !idmapping_supported) {
3,663✔
2867
                        do_chown = true;
1,428✔
2868
                        i->idmapped = false;
1,428✔
2869
                } else {
2870
                        /* Use 'nobody' uid/gid for exec directories if ID-mapping is supported. For backward compatibility,
2871
                         * continue doing chmod/chown if the directory was chmod/chowned before (if uid/gid is not 'nobody') */
2872
                        struct stat st;
2,235✔
2873
                        r = RET_NERRNO(stat(target_dir, &st));
2,235✔
2874
                        if (r < 0)
×
2875
                                goto fail;
×
2876

2877
                        if (st.st_uid == UID_NOBODY && st.st_gid == GID_NOBODY) {
2,235✔
2878
                                do_chown = false;
7✔
2879
                                i->idmapped = true;
7✔
2880
                       } else if (exec_directory_is_private(context, type) && st.st_uid == 0 && st.st_gid == 0) {
2,228✔
2881
                                chown_uid = UID_NOBODY;
6✔
2882
                                chown_gid = GID_NOBODY;
6✔
2883
                                do_chown = true;
6✔
2884
                                i->idmapped = true;
6✔
2885
                        } else {
2886
                                do_chown = true;
2,222✔
2887
                                i->idmapped = false;
2,222✔
2888
                        }
2889
                }
2890

2891
                if (do_chown) {
3,663✔
2892
                        r = path_chown_recursive(target_dir, chown_uid, chown_gid, context->dynamic_user ? 01777 : 07777, AT_SYMLINK_FOLLOW);
7,303✔
2893
                        if (r < 0)
3,656✔
2894
                                goto fail;
1✔
2895
                }
2896
        }
2897

2898
        /* If we are not going to run in a namespace, set up the symlinks - otherwise
2899
         * they are set up later, to allow configuring empty var/run/etc. */
2900
        if (!needs_mount_namespace)
57,560✔
2901
                FOREACH_ARRAY(i, context->directories[type].items, context->directories[type].n_items) {
45,956✔
2902
                        r = create_many_symlinks(params->prefix[type], i->path, i->symlinks);
1,526✔
2903
                        if (r < 0)
1,526✔
2904
                                goto fail;
×
2905
                }
2906

2907
        return 0;
2908

2909
fail:
1✔
2910
        *exit_status = exit_status_table[type];
1✔
2911
        return r;
1✔
2912
}
2913

2914
#if ENABLE_SMACK
2915
static int setup_smack(
×
2916
                const ExecContext *context,
2917
                const ExecParameters *params,
2918
                int executable_fd) {
2919
        int r;
×
2920

2921
        assert(context);
×
2922
        assert(params);
×
2923
        assert(executable_fd >= 0);
×
2924

2925
        if (context->smack_process_label) {
×
2926
                r = mac_smack_apply_pid(0, context->smack_process_label);
×
2927
                if (r < 0)
×
2928
                        return r;
×
2929
        } else if (params->fallback_smack_process_label) {
×
2930
                _cleanup_free_ char *exec_label = NULL;
×
2931

2932
                r = mac_smack_read_fd(executable_fd, SMACK_ATTR_EXEC, &exec_label);
×
2933
                if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
×
2934
                        return r;
2935

2936
                r = mac_smack_apply_pid(0, exec_label ?: params->fallback_smack_process_label);
×
2937
                if (r < 0)
×
2938
                        return r;
2939
        }
2940

2941
        return 0;
2942
}
2943
#endif
2944

2945
static int compile_bind_mounts(
2,010✔
2946
                const ExecContext *context,
2947
                const ExecParameters *params,
2948
                uid_t exec_directory_uid, /* only used for id-mapped mounts Exec directories */
2949
                gid_t exec_directory_gid, /* only used for id-mapped mounts Exec directories */
2950
                BindMount **ret_bind_mounts,
2951
                size_t *ret_n_bind_mounts,
2952
                char ***ret_empty_directories) {
2953

2954
        _cleanup_strv_free_ char **empty_directories = NULL;
2,010✔
2955
        BindMount *bind_mounts = NULL;
2,010✔
2956
        size_t n, h = 0;
2,010✔
2957
        int r;
2,010✔
2958

2959
        assert(context);
2,010✔
2960
        assert(params);
2,010✔
2961
        assert(ret_bind_mounts);
2,010✔
2962
        assert(ret_n_bind_mounts);
2,010✔
2963
        assert(ret_empty_directories);
2,010✔
2964

2965
        CLEANUP_ARRAY(bind_mounts, h, bind_mount_free_many);
2,010✔
2966

2967
        n = context->n_bind_mounts;
2,010✔
2968
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
12,060✔
2969
                if (!params->prefix[t])
10,050✔
2970
                        continue;
×
2971

2972
                FOREACH_ARRAY(i, context->directories[t].items, context->directories[t].n_items)
11,635✔
2973
                        n += !FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE) || FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY);
1,585✔
2974
        }
2975

2976
        if (n <= 0) {
2,010✔
2977
                *ret_bind_mounts = NULL;
1,091✔
2978
                *ret_n_bind_mounts = 0;
1,091✔
2979
                *ret_empty_directories = NULL;
1,091✔
2980
                return 0;
1,091✔
2981
        }
2982

2983
        bind_mounts = new(BindMount, n);
919✔
2984
        if (!bind_mounts)
919✔
2985
                return -ENOMEM;
2986

2987
        FOREACH_ARRAY(item, context->bind_mounts, context->n_bind_mounts) {
939✔
2988
                r = bind_mount_add(&bind_mounts, &h, item);
20✔
2989
                if (r < 0)
20✔
2990
                        return r;
2991
        }
2992

2993
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
5,514✔
2994
                if (!params->prefix[t])
4,595✔
2995
                        continue;
×
2996

2997
                if (context->directories[t].n_items == 0)
4,595✔
2998
                        continue;
3,466✔
2999

3000
                if (exec_directory_is_private(context, t) &&
1,142✔
3001
                    !exec_context_with_rootfs(context)) {
13✔
3002
                        char *private_root;
13✔
3003

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

3008
                        private_root = path_join(params->prefix[t], "private");
13✔
3009
                        if (!private_root)
13✔
3010
                                return -ENOMEM;
3011

3012
                        r = strv_consume(&empty_directories, private_root);
13✔
3013
                        if (r < 0)
13✔
3014
                                return r;
3015
                }
3016

3017
                FOREACH_ARRAY(i, context->directories[t].items, context->directories[t].n_items) {
2,714✔
3018
                        _cleanup_free_ char *s = NULL, *d = NULL;
1,585✔
3019

3020
                        /* When one of the parent directories is in the list, we cannot create the symlink
3021
                         * for the child directory. See also the comments in setup_exec_directory().
3022
                         * But if it needs to be read only, then we have to create a bind mount anyway to
3023
                         * make it so. */
3024
                        if (FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE) && !FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY))
1,585✔
3025
                                continue;
×
3026

3027
                        if (exec_directory_is_private(context, t))
1,585✔
3028
                                s = path_join(params->prefix[t], "private", i->path);
13✔
3029
                        else
3030
                                s = path_join(params->prefix[t], i->path);
1,572✔
3031
                        if (!s)
1,585✔
3032
                                return -ENOMEM;
3033

3034
                        if (exec_directory_is_private(context, t) &&
1,598✔
3035
                            exec_context_with_rootfs(context))
13✔
3036
                                /* When RootDirectory= or RootImage= are set, then the symbolic link to the private
3037
                                 * directory is not created on the root directory. So, let's bind-mount the directory
3038
                                 * on the 'non-private' place. */
3039
                                d = path_join(params->prefix[t], i->path);
×
3040
                        else
3041
                                d = strdup(s);
1,585✔
3042
                        if (!d)
1,585✔
3043
                                return -ENOMEM;
3044

3045
                        bind_mounts[h++] = (BindMount) {
1,585✔
3046
                                .source = TAKE_PTR(s),
1,585✔
3047
                                .destination = TAKE_PTR(d),
1,585✔
3048
                                .nosuid = context->dynamic_user, /* don't allow suid/sgid when DynamicUser= is on */
1,585✔
3049
                                .recursive = true,
3050
                                .read_only = FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY),
1,585✔
3051
                                .idmapped = i->idmapped,
1,585✔
3052
                                .uid = exec_directory_uid,
3053
                                .gid = exec_directory_gid,
3054
                        };
3055
                }
3056
        }
3057

3058
        assert(h == n);
919✔
3059

3060
        *ret_bind_mounts = TAKE_PTR(bind_mounts);
919✔
3061
        *ret_n_bind_mounts = n;
919✔
3062
        *ret_empty_directories = TAKE_PTR(empty_directories);
919✔
3063

3064
        return (int) n;
919✔
3065
}
3066

3067
/* ret_symlinks will contain a list of pairs src:dest that describes
3068
 * the symlinks to create later on. For example, the symlinks needed
3069
 * to safely give private directories to DynamicUser=1 users. */
3070
static int compile_symlinks(
2,010✔
3071
                const ExecContext *context,
3072
                const ExecParameters *params,
3073
                bool setup_os_release_symlink,
3074
                char ***ret_symlinks) {
3075

3076
        _cleanup_strv_free_ char **symlinks = NULL;
2,010✔
3077
        int r;
2,010✔
3078

3079
        assert(context);
2,010✔
3080
        assert(params);
2,010✔
3081
        assert(ret_symlinks);
2,010✔
3082

3083
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++)
12,060✔
3084
                FOREACH_ARRAY(i, context->directories[dt].items, context->directories[dt].n_items) {
11,635✔
3085
                        _cleanup_free_ char *private_path = NULL, *path = NULL;
1,572✔
3086

3087
                        STRV_FOREACH(symlink, i->symlinks) {
1,711✔
3088
                                _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;
126✔
3089

3090
                                src_abs = path_join(params->prefix[dt], i->path);
126✔
3091
                                dst_abs = path_join(params->prefix[dt], *symlink);
126✔
3092
                                if (!src_abs || !dst_abs)
126✔
3093
                                        return -ENOMEM;
3094

3095
                                r = strv_consume_pair(&symlinks, TAKE_PTR(src_abs), TAKE_PTR(dst_abs));
126✔
3096
                                if (r < 0)
126✔
3097
                                        return r;
3098
                        }
3099

3100
                        if (!exec_directory_is_private(context, dt) ||
1,598✔
3101
                            exec_context_with_rootfs(context) ||
13✔
3102
                            FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE))
13✔
3103
                                continue;
1,572✔
3104

3105
                        private_path = path_join(params->prefix[dt], "private", i->path);
13✔
3106
                        if (!private_path)
13✔
3107
                                return -ENOMEM;
3108

3109
                        path = path_join(params->prefix[dt], i->path);
13✔
3110
                        if (!path)
13✔
3111
                                return -ENOMEM;
3112

3113
                        r = strv_consume_pair(&symlinks, TAKE_PTR(private_path), TAKE_PTR(path));
13✔
3114
                        if (r < 0)
13✔
3115
                                return r;
3116
                }
3117

3118
        /* We make the host's os-release available via a symlink, so that we can copy it atomically
3119
         * and readers will never get a half-written version. Note that, while the paths specified here are
3120
         * absolute, when they are processed in namespace.c they will be made relative automatically, i.e.:
3121
         * 'os-release -> .os-release-stage/os-release' is what will be created. */
3122
        if (setup_os_release_symlink) {
2,010✔
3123
                r = strv_extend_many(
7✔
3124
                                &symlinks,
3125
                                "/run/host/.os-release-stage/os-release",
3126
                                "/run/host/os-release");
3127
                if (r < 0)
7✔
3128
                        return r;
3129
        }
3130

3131
        *ret_symlinks = TAKE_PTR(symlinks);
2,010✔
3132

3133
        return 0;
2,010✔
3134
}
3135

3136
static bool insist_on_sandboxing(
×
3137
                const ExecContext *context,
3138
                const char *root_dir,
3139
                const char *root_image,
3140
                const BindMount *bind_mounts,
3141
                size_t n_bind_mounts) {
3142

3143
        assert(context);
×
3144
        assert(n_bind_mounts == 0 || bind_mounts);
×
3145

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

3150
        if (context->n_temporary_filesystems > 0)
×
3151
                return true;
3152

3153
        if (root_dir || root_image)
×
3154
                return true;
3155

3156
        if (context->n_mount_images > 0)
×
3157
                return true;
3158

3159
        if (context->dynamic_user)
×
3160
                return true;
3161

3162
        if (context->n_extension_images > 0 || !strv_isempty(context->extension_directories))
×
3163
                return true;
3164

3165
        /* If there are any bind mounts set that don't map back onto themselves, fs namespacing becomes
3166
         * essential. */
3167
        FOREACH_ARRAY(i, bind_mounts, n_bind_mounts)
×
3168
                if (!path_equal(i->source, i->destination))
×
3169
                        return true;
3170

3171
        if (context->log_namespace)
×
3172
                return true;
×
3173

3174
        return false;
3175
}
3176

3177
static int setup_ephemeral(
2,010✔
3178
                const ExecContext *context,
3179
                ExecRuntime *runtime,
3180
                char **root_image,            /* both input and output! modified if ephemeral logic enabled */
3181
                char **root_directory,        /* ditto */
3182
                char **reterr_path) {
3183

3184
        _cleanup_close_ int fd = -EBADF;
2,010✔
3185
        _cleanup_free_ char *new_root = NULL;
2,010✔
3186
        int r;
2,010✔
3187

3188
        assert(context);
2,010✔
3189
        assert(runtime);
2,010✔
3190
        assert(root_image);
2,010✔
3191
        assert(root_directory);
2,010✔
3192

3193
        if (!*root_image && !*root_directory)
2,010✔
3194
                return 0;
3195

3196
        if (!runtime->ephemeral_copy)
8✔
3197
                return 0;
3198

3199
        assert(runtime->ephemeral_storage_socket[0] >= 0);
×
3200
        assert(runtime->ephemeral_storage_socket[1] >= 0);
×
3201

3202
        new_root = strdup(runtime->ephemeral_copy);
×
3203
        if (!new_root)
×
3204
                return log_oom_debug();
×
3205

3206
        r = posix_lock(runtime->ephemeral_storage_socket[0], LOCK_EX);
×
3207
        if (r < 0)
×
3208
                return log_debug_errno(r, "Failed to lock ephemeral storage socket: %m");
×
3209

3210
        CLEANUP_POSIX_UNLOCK(runtime->ephemeral_storage_socket[0]);
×
3211

3212
        fd = receive_one_fd(runtime->ephemeral_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
×
3213
        if (fd >= 0)
×
3214
                /* We got an fd! That means ephemeral has already been set up, so nothing to do here. */
3215
                return 0;
3216
        if (fd != -EAGAIN)
×
3217
                return log_debug_errno(fd, "Failed to receive file descriptor queued on ephemeral storage socket: %m");
×
3218

3219
        if (*root_image) {
×
3220
                log_debug("Making ephemeral copy of %s to %s", *root_image, new_root);
×
3221

3222
                fd = copy_file(*root_image, new_root, O_EXCL, 0600,
×
3223
                               COPY_LOCK_BSD|COPY_REFLINK|COPY_CRTIME|COPY_NOCOW_AFTER);
3224
                if (fd < 0) {
×
3225
                        *reterr_path = strdup(*root_image);
×
3226
                        return log_debug_errno(fd, "Failed to copy image %s to %s: %m",
×
3227
                                               *root_image, new_root);
3228
                }
3229
        } else {
3230
                assert(*root_directory);
×
3231

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

3234
                fd = btrfs_subvol_snapshot_at(
×
3235
                                AT_FDCWD, *root_directory,
3236
                                AT_FDCWD, new_root,
3237
                                BTRFS_SNAPSHOT_FALLBACK_COPY |
3238
                                BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
3239
                                BTRFS_SNAPSHOT_RECURSIVE |
3240
                                BTRFS_SNAPSHOT_LOCK_BSD);
3241
                if (fd < 0) {
×
3242
                        *reterr_path = strdup(*root_directory);
×
3243
                        return log_debug_errno(fd, "Failed to snapshot directory %s to %s: %m",
×
3244
                                               *root_directory, new_root);
3245
                }
3246
        }
3247

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

3252
        if (*root_image)
×
3253
                free_and_replace(*root_image, new_root);
×
3254
        else {
3255
                assert(*root_directory);
×
3256
                free_and_replace(*root_directory, new_root);
×
3257
        }
3258

3259
        return 1;
3260
}
3261

3262
static int verity_settings_prepare(
7✔
3263
                VeritySettings *verity,
3264
                const char *root_image,
3265
                const void *root_hash,
3266
                size_t root_hash_size,
3267
                const char *root_hash_path,
3268
                const void *root_hash_sig,
3269
                size_t root_hash_sig_size,
3270
                const char *root_hash_sig_path,
3271
                const char *verity_data_path) {
3272

3273
        int r;
7✔
3274

3275
        assert(verity);
7✔
3276

3277
        if (root_hash) {
7✔
3278
                void *d;
4✔
3279

3280
                d = memdup(root_hash, root_hash_size);
4✔
3281
                if (!d)
4✔
3282
                        return -ENOMEM;
7✔
3283

3284
                free_and_replace(verity->root_hash, d);
4✔
3285
                verity->root_hash_size = root_hash_size;
4✔
3286
                verity->designator = PARTITION_ROOT;
4✔
3287
        }
3288

3289
        if (root_hash_sig) {
7✔
3290
                void *d;
×
3291

3292
                d = memdup(root_hash_sig, root_hash_sig_size);
×
3293
                if (!d)
×
3294
                        return -ENOMEM;
7✔
3295

3296
                free_and_replace(verity->root_hash_sig, d);
×
3297
                verity->root_hash_sig_size = root_hash_sig_size;
×
3298
                verity->designator = PARTITION_ROOT;
×
3299
        }
3300

3301
        if (verity_data_path) {
7✔
3302
                r = free_and_strdup(&verity->data_path, verity_data_path);
×
3303
                if (r < 0)
×
3304
                        return r;
3305
        }
3306

3307
        r = verity_settings_load(
7✔
3308
                        verity,
3309
                        root_image,
3310
                        root_hash_path,
3311
                        root_hash_sig_path);
3312
        if (r < 0)
7✔
3313
                return log_debug_errno(r, "Failed to load root hash: %m");
×
3314

3315
        return 0;
3316
}
3317

3318
static int pick_versions(
2,012✔
3319
                const ExecContext *context,
3320
                const ExecParameters *params,
3321
                char **ret_root_image,
3322
                char **ret_root_directory,
3323
                char **reterr_path) {
3324

3325
        int r;
2,012✔
3326

3327
        assert(context);
2,012✔
3328
        assert(params);
2,012✔
3329
        assert(ret_root_image);
2,012✔
3330
        assert(ret_root_directory);
2,012✔
3331

3332
        if (context->root_image) {
2,012✔
3333
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
8✔
3334

3335
                r = path_pick(/* toplevel_path= */ NULL,
16✔
3336
                              /* toplevel_fd= */ AT_FDCWD,
3337
                              context->root_image,
8✔
3338
                              &pick_filter_image_raw,
3339
                              PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3340
                              &result);
3341
                if (r < 0) {
8✔
3342
                        *reterr_path = strdup(context->root_image);
1✔
3343
                        return r;
1✔
3344
                }
3345

3346
                if (!result.path) {
7✔
3347
                        *reterr_path = strdup(context->root_image);
×
3348
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_image);
×
3349
                }
3350

3351
                *ret_root_image = TAKE_PTR(result.path);
7✔
3352
                *ret_root_directory = NULL;
7✔
3353
                return r;
7✔
3354
        }
3355

3356
        if (context->root_directory) {
2,004✔
3357
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
2✔
3358

3359
                r = path_pick(/* toplevel_path= */ NULL,
4✔
3360
                              /* toplevel_fd= */ AT_FDCWD,
3361
                              context->root_directory,
2✔
3362
                              &pick_filter_image_dir,
3363
                              PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3364
                              &result);
3365
                if (r < 0) {
2✔
3366
                        *reterr_path = strdup(context->root_directory);
×
3367
                        return r;
×
3368
                }
3369

3370
                if (!result.path) {
2✔
3371
                        *reterr_path = strdup(context->root_directory);
1✔
3372
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_directory);
1✔
3373
                }
3374

3375
                *ret_root_image = NULL;
1✔
3376
                *ret_root_directory = TAKE_PTR(result.path);
1✔
3377
                return r;
1✔
3378
        }
3379

3380
        *ret_root_image = *ret_root_directory = NULL;
2,002✔
3381
        return 0;
2,002✔
3382
}
3383

3384
static int apply_mount_namespace(
2,012✔
3385
                ExecCommandFlags command_flags,
3386
                const ExecContext *context,
3387
                const ExecParameters *params,
3388
                ExecRuntime *runtime,
3389
                const char *memory_pressure_path,
3390
                bool needs_sandboxing,
3391
                char **reterr_path,
3392
                uid_t exec_directory_uid,
3393
                gid_t exec_directory_gid) {
3394

3395
        _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
2,012✔
3396
        _cleanup_strv_free_ char **empty_directories = NULL, **symlinks = NULL,
2,012✔
3397
                        **read_write_paths_cleanup = NULL;
×
3398
        _cleanup_free_ char *creds_path = NULL, *incoming_dir = NULL, *propagate_dir = NULL,
×
3399
                *private_namespace_dir = NULL, *host_os_release_stage = NULL, *root_image = NULL, *root_dir = NULL;
2,012✔
3400
        const char *tmp_dir = NULL, *var_tmp_dir = NULL;
2,012✔
3401
        char **read_write_paths;
2,012✔
3402
        bool setup_os_release_symlink;
2,012✔
3403
        BindMount *bind_mounts = NULL;
2,012✔
3404
        size_t n_bind_mounts = 0;
2,012✔
3405
        int r;
2,012✔
3406

3407
        assert(context);
2,012✔
3408
        assert(params);
2,012✔
3409
        assert(runtime);
2,012✔
3410

3411
        CLEANUP_ARRAY(bind_mounts, n_bind_mounts, bind_mount_free_many);
2,012✔
3412

3413
        if (params->flags & EXEC_APPLY_CHROOT) {
2,012✔
3414
                r = pick_versions(
2,012✔
3415
                                context,
3416
                                params,
3417
                                &root_image,
3418
                                &root_dir,
3419
                                reterr_path);
3420
                if (r < 0)
2,012✔
3421
                        return r;
3422

3423
                r = setup_ephemeral(
2,010✔
3424
                                context,
3425
                                runtime,
3426
                                &root_image,
3427
                                &root_dir,
3428
                                reterr_path);
3429
                if (r < 0)
2,010✔
3430
                        return r;
3431
        }
3432

3433
        r = compile_bind_mounts(context, params, exec_directory_uid, exec_directory_gid, &bind_mounts, &n_bind_mounts, &empty_directories);
2,010✔
3434
        if (r < 0)
2,010✔
3435
                return r;
3436

3437
        /* We need to make the pressure path writable even if /sys/fs/cgroups is made read-only, as the
3438
         * service will need to write to it in order to start the notifications. */
3439
        if (exec_is_cgroup_mount_read_only(context) && memory_pressure_path && !streq(memory_pressure_path, "/dev/null")) {
2,010✔
3440
                read_write_paths_cleanup = strv_copy(context->read_write_paths);
1,134✔
3441
                if (!read_write_paths_cleanup)
1,134✔
3442
                        return -ENOMEM;
3443

3444
                r = strv_extend(&read_write_paths_cleanup, memory_pressure_path);
1,134✔
3445
                if (r < 0)
1,134✔
3446
                        return r;
3447

3448
                read_write_paths = read_write_paths_cleanup;
1,134✔
3449
        } else
3450
                read_write_paths = context->read_write_paths;
876✔
3451

3452
        if (needs_sandboxing) {
2,010✔
3453
                /* The runtime struct only contains the parent of the private /tmp, which is non-accessible
3454
                 * to world users. Inside of it there's a /tmp that is sticky, and that's the one we want to
3455
                 * use here.  This does not apply when we are using /run/systemd/empty as fallback. */
3456

3457
                if (context->private_tmp == PRIVATE_TMP_CONNECTED && runtime->shared) {
2,010✔
3458
                        if (streq_ptr(runtime->shared->tmp_dir, RUN_SYSTEMD_EMPTY))
323✔
3459
                                tmp_dir = runtime->shared->tmp_dir;
3460
                        else if (runtime->shared->tmp_dir)
323✔
3461
                                tmp_dir = strjoina(runtime->shared->tmp_dir, "/tmp");
1,615✔
3462

3463
                        if (streq_ptr(runtime->shared->var_tmp_dir, RUN_SYSTEMD_EMPTY))
323✔
3464
                                var_tmp_dir = runtime->shared->var_tmp_dir;
3465
                        else if (runtime->shared->var_tmp_dir)
323✔
3466
                                var_tmp_dir = strjoina(runtime->shared->var_tmp_dir, "/tmp");
1,615✔
3467
                }
3468
        }
3469

3470
        /* Symlinks (exec dirs, os-release) are set up after other mounts, before they are made read-only. */
3471
        setup_os_release_symlink = needs_sandboxing && exec_context_get_effective_mount_apivfs(context) && (root_dir || root_image);
2,010✔
3472
        r = compile_symlinks(context, params, setup_os_release_symlink, &symlinks);
2,010✔
3473
        if (r < 0)
2,010✔
3474
                return r;
3475

3476
        if (context->mount_propagation_flag == MS_SHARED)
2,010✔
3477
                log_debug("shared mount propagation hidden by other fs namespacing unit settings: ignoring");
×
3478

3479
        r = exec_context_get_credential_directory(context, params, params->unit_id, &creds_path);
2,010✔
3480
        if (r < 0)
2,010✔
3481
                return r;
3482

3483
        if (params->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
2,010✔
3484
                propagate_dir = path_join("/run/systemd/propagate/", params->unit_id);
1,983✔
3485
                if (!propagate_dir)
1,983✔
3486
                        return -ENOMEM;
3487

3488
                incoming_dir = strdup("/run/systemd/incoming");
1,983✔
3489
                if (!incoming_dir)
1,983✔
3490
                        return -ENOMEM;
3491

3492
                private_namespace_dir = strdup("/run/systemd");
1,983✔
3493
                if (!private_namespace_dir)
1,983✔
3494
                        return -ENOMEM;
3495

3496
                /* If running under a different root filesystem, propagate the host's os-release. We make a
3497
                 * copy rather than just bind mounting it, so that it can be updated on soft-reboot. */
3498
                if (setup_os_release_symlink) {
1,983✔
3499
                        host_os_release_stage = strdup("/run/systemd/propagate/.os-release-stage");
7✔
3500
                        if (!host_os_release_stage)
7✔
3501
                                return -ENOMEM;
3502
                }
3503
        } else {
3504
                assert(params->runtime_scope == RUNTIME_SCOPE_USER);
27✔
3505

3506
                if (asprintf(&private_namespace_dir, "/run/user/" UID_FMT "/systemd", geteuid()) < 0)
27✔
3507
                        return -ENOMEM;
3508

3509
                if (setup_os_release_symlink) {
27✔
3510
                        if (asprintf(&host_os_release_stage,
×
3511
                                     "/run/user/" UID_FMT "/systemd/propagate/.os-release-stage",
3512
                                     geteuid()) < 0)
3513
                                return -ENOMEM;
3514
                }
3515
        }
3516

3517
        if (root_image) {
2,010✔
3518
                r = verity_settings_prepare(
14✔
3519
                        &verity,
3520
                        root_image,
3521
                        context->root_hash, context->root_hash_size, context->root_hash_path,
7✔
3522
                        context->root_hash_sig, context->root_hash_sig_size, context->root_hash_sig_path,
7✔
3523
                        context->root_verity);
7✔
3524
                if (r < 0)
7✔
3525
                        return r;
3526
        }
3527

3528
        NamespaceParameters parameters = {
×
3529
                .runtime_scope = params->runtime_scope,
2,010✔
3530

3531
                .root_directory = root_dir,
3532
                .root_image = root_image,
3533
                .root_image_options = context->root_image_options,
2,010✔
3534
                .root_image_policy = context->root_image_policy ?: &image_policy_service,
2,010✔
3535

3536
                .read_write_paths = read_write_paths,
3537
                .read_only_paths = needs_sandboxing ? context->read_only_paths : NULL,
2,010✔
3538
                .inaccessible_paths = needs_sandboxing ? context->inaccessible_paths : NULL,
2,010✔
3539

3540
                .exec_paths = needs_sandboxing ? context->exec_paths : NULL,
2,010✔
3541
                .no_exec_paths = needs_sandboxing ? context->no_exec_paths : NULL,
2,010✔
3542

3543
                .empty_directories = empty_directories,
3544
                .symlinks = symlinks,
3545

3546
                .bind_mounts = bind_mounts,
3547
                .n_bind_mounts = n_bind_mounts,
3548

3549
                .temporary_filesystems = context->temporary_filesystems,
2,010✔
3550
                .n_temporary_filesystems = context->n_temporary_filesystems,
2,010✔
3551

3552
                .mount_images = context->mount_images,
2,010✔
3553
                .n_mount_images = context->n_mount_images,
2,010✔
3554
                .mount_image_policy = context->mount_image_policy ?: &image_policy_service,
2,010✔
3555

3556
                .tmp_dir = tmp_dir,
3557
                .var_tmp_dir = var_tmp_dir,
3558

3559
                .creds_path = creds_path,
3560
                .log_namespace = context->log_namespace,
2,010✔
3561
                .mount_propagation_flag = context->mount_propagation_flag,
2,010✔
3562

3563
                .verity = &verity,
3564

3565
                .extension_images = context->extension_images,
2,010✔
3566
                .n_extension_images = context->n_extension_images,
2,010✔
3567
                .extension_image_policy = context->extension_image_policy ?: &image_policy_sysext,
2,010✔
3568
                .extension_directories = context->extension_directories,
2,010✔
3569

3570
                .propagate_dir = propagate_dir,
3571
                .incoming_dir = incoming_dir,
3572
                .private_namespace_dir = private_namespace_dir,
3573
                .host_notify_socket = params->notify_socket,
2,010✔
3574
                .notify_socket_path = exec_get_private_notify_socket_path(context, params, needs_sandboxing),
2,010✔
3575
                .host_os_release_stage = host_os_release_stage,
3576

3577
                /* If DynamicUser=no and RootDirectory= is set then lets pass a relaxed sandbox info,
3578
                 * otherwise enforce it, don't ignore protected paths and fail if we are enable to apply the
3579
                 * sandbox inside the mount namespace. */
3580
                .ignore_protect_paths = !needs_sandboxing && !context->dynamic_user && root_dir,
2,010✔
3581

3582
                .protect_control_groups = needs_sandboxing ? exec_get_protect_control_groups(context) : PROTECT_CONTROL_GROUPS_NO,
2,010✔
3583
                .protect_kernel_tunables = needs_sandboxing && context->protect_kernel_tunables,
2,010✔
3584
                .protect_kernel_modules = needs_sandboxing && context->protect_kernel_modules,
2,010✔
3585
                .protect_kernel_logs = needs_sandboxing && context->protect_kernel_logs,
2,010✔
3586

3587
                .private_dev = needs_sandboxing && context->private_devices,
2,010✔
3588
                .private_network = needs_sandboxing && exec_needs_network_namespace(context),
2,010✔
3589
                .private_ipc = needs_sandboxing && exec_needs_ipc_namespace(context),
2,010✔
3590
                .private_pids = needs_sandboxing && exec_needs_pid_namespace(context) ? context->private_pids : PRIVATE_PIDS_NO,
2,010✔
3591
                .private_tmp = needs_sandboxing ? context->private_tmp : PRIVATE_TMP_NO,
2,010✔
3592

3593
                .mount_apivfs = needs_sandboxing && exec_context_get_effective_mount_apivfs(context),
2,010✔
3594
                .bind_log_sockets = needs_sandboxing && exec_context_get_effective_bind_log_sockets(context),
2,010✔
3595

3596
                /* If NNP is on, we can turn on MS_NOSUID, since it won't have any effect anymore. */
3597
                .mount_nosuid = needs_sandboxing && context->no_new_privileges && !mac_selinux_use(),
2,010✔
3598

3599
                .protect_home = needs_sandboxing ? context->protect_home : PROTECT_HOME_NO,
2,010✔
3600
                .protect_hostname = needs_sandboxing ? context->protect_hostname : PROTECT_HOSTNAME_NO,
2,010✔
3601
                .protect_system = needs_sandboxing ? context->protect_system : PROTECT_SYSTEM_NO,
2,010✔
3602
                .protect_proc = needs_sandboxing ? context->protect_proc : PROTECT_PROC_DEFAULT,
2,010✔
3603
                .proc_subset = needs_sandboxing ? context->proc_subset : PROC_SUBSET_ALL,
2,010✔
3604
        };
3605

3606
        r = setup_namespace(&parameters, reterr_path);
2,010✔
3607
        /* If we couldn't set up the namespace this is probably due to a missing capability. setup_namespace() reports
3608
         * that with a special, recognizable error ENOANO. In this case, silently proceed, but only if exclusively
3609
         * sandboxing options were used, i.e. nothing such as RootDirectory= or BindMount= that would result in a
3610
         * completely different execution environment. */
3611
        if (r == -ENOANO) {
2,010✔
3612
                if (insist_on_sandboxing(
×
3613
                                    context,
3614
                                    root_dir, root_image,
3615
                                    bind_mounts,
3616
                                    n_bind_mounts))
3617
                        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
×
3618
                                               "Failed to set up namespace, and refusing to continue since "
3619
                                               "the selected namespacing options alter mount environment non-trivially.\n"
3620
                                               "Bind mounts: %zu, temporary filesystems: %zu, root directory: %s, root image: %s, dynamic user: %s",
3621
                                               n_bind_mounts,
3622
                                               context->n_temporary_filesystems,
3623
                                               yes_no(root_dir),
3624
                                               yes_no(root_image),
3625
                                               yes_no(context->dynamic_user));
3626

3627
                log_debug("Failed to set up namespace, assuming containerized execution and ignoring.");
×
3628
                return 0;
×
3629
        }
3630

3631
        return r;
3632
}
3633

3634
static int apply_working_directory(
9,542✔
3635
                const ExecContext *context,
3636
                const ExecParameters *params,
3637
                ExecRuntime *runtime,
3638
                const char *pwent_home,
3639
                char * const *env) {
3640

3641
        const char *wd;
9,542✔
3642
        int r;
9,542✔
3643

3644
        assert(context);
9,542✔
3645
        assert(params);
9,542✔
3646
        assert(runtime);
9,542✔
3647

3648
        if (context->working_directory_home) {
9,542✔
3649
                /* Preferably use the data from $HOME, in case it was updated by a PAM module */
3650
                wd = strv_env_get(env, "HOME");
93✔
3651
                if (!wd) {
93✔
3652
                        /* If that's not available, use the data from the struct passwd entry: */
3653
                        if (!pwent_home)
1✔
3654
                                return -ENXIO;
3655

3656
                        wd = pwent_home;
3657
                }
3658
        } else
3659
                wd = empty_to_root(context->working_directory);
9,449✔
3660

3661
        if (params->flags & EXEC_APPLY_CHROOT)
9,542✔
3662
                r = RET_NERRNO(chdir(wd));
9,542✔
3663
        else {
3664
                _cleanup_close_ int dfd = -EBADF;
×
3665

3666
                r = chase(wd,
×
3667
                          runtime->ephemeral_copy ?: context->root_directory,
×
3668
                          CHASE_PREFIX_ROOT|CHASE_AT_RESOLVE_IN_ROOT,
3669
                          /* ret_path= */ NULL,
3670
                          &dfd);
3671
                if (r >= 0)
×
3672
                        r = RET_NERRNO(fchdir(dfd));
×
3673
        }
3674
        return context->working_directory_missing_ok ? 0 : r;
9,542✔
3675
}
3676

3677
static int apply_root_directory(
9,542✔
3678
                const ExecContext *context,
3679
                const ExecParameters *params,
3680
                ExecRuntime *runtime,
3681
                const bool needs_mount_ns,
3682
                int *exit_status) {
3683

3684
        assert(context);
9,542✔
3685
        assert(params);
9,542✔
3686
        assert(runtime);
9,542✔
3687
        assert(exit_status);
9,542✔
3688

3689
        if (params->flags & EXEC_APPLY_CHROOT)
9,542✔
3690
                if (!needs_mount_ns && context->root_directory)
9,542✔
3691
                        if (chroot(runtime->ephemeral_copy ?: context->root_directory) < 0) {
×
3692
                                *exit_status = EXIT_CHROOT;
×
3693
                                return -errno;
×
3694
                        }
3695

3696
        return 0;
3697
}
3698

3699
static int setup_keyring(
9,566✔
3700
                const ExecContext *context,
3701
                const ExecParameters *p,
3702
                uid_t uid,
3703
                gid_t gid) {
3704

3705
        key_serial_t keyring;
9,566✔
3706
        int r = 0;
9,566✔
3707
        uid_t saved_uid;
9,566✔
3708
        gid_t saved_gid;
9,566✔
3709

3710
        assert(context);
9,566✔
3711
        assert(p);
9,566✔
3712

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

3720
        if (context->keyring_mode == EXEC_KEYRING_INHERIT)
9,566✔
3721
                return 0;
3722

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

3728
        saved_uid = getuid();
8,600✔
3729
        saved_gid = getgid();
8,600✔
3730

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

3736
        if (uid_is_valid(uid) && uid != saved_uid) {
8,600✔
3737
                if (setreuid(uid, -1) < 0) {
1,743✔
3738
                        r = log_error_errno(errno, "Failed to change UID for user keyring: %m");
×
3739
                        goto out;
×
3740
                }
3741
        }
3742

3743
        keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
8,600✔
3744
        if (keyring == -1) {
8,600✔
3745
                if (errno == ENOSYS)
×
3746
                        log_debug_errno(errno, "Kernel keyring not supported, ignoring.");
×
3747
                else if (ERRNO_IS_PRIVILEGE(errno))
×
3748
                        log_debug_errno(errno, "Kernel keyring access prohibited, ignoring.");
×
3749
                else if (errno == EDQUOT)
×
3750
                        log_debug_errno(errno, "Out of kernel keyrings to allocate, ignoring.");
×
3751
                else
3752
                        r = log_error_errno(errno, "Setting up kernel keyring failed: %m");
×
3753

3754
                goto out;
×
3755
        }
3756

3757
        /* When requested link the user keyring into the session keyring. */
3758
        if (context->keyring_mode == EXEC_KEYRING_SHARED) {
8,600✔
3759

3760
                if (keyctl(KEYCTL_LINK,
935✔
3761
                           KEY_SPEC_USER_KEYRING,
3762
                           KEY_SPEC_SESSION_KEYRING, 0, 0) < 0) {
3763
                        r = log_error_errno(errno, "Failed to link user keyring into session keyring: %m");
×
3764
                        goto out;
×
3765
                }
3766
        }
3767

3768
        /* Restore uid/gid back */
3769
        if (uid_is_valid(uid) && uid != saved_uid) {
8,600✔
3770
                if (setreuid(saved_uid, -1) < 0) {
1,743✔
3771
                        r = log_error_errno(errno, "Failed to change UID back for user keyring: %m");
×
3772
                        goto out;
×
3773
                }
3774
        }
3775

3776
        if (gid_is_valid(gid) && gid != saved_gid) {
8,600✔
3777
                if (setregid(saved_gid, -1) < 0)
1,746✔
3778
                        return log_error_errno(errno, "Failed to change GID back for user keyring: %m");
×
3779
        }
3780

3781
        /* Populate they keyring with the invocation ID by default, as original saved_uid. */
3782
        if (!sd_id128_is_null(p->invocation_id)) {
8,600✔
3783
                key_serial_t key;
8,600✔
3784

3785
                key = add_key("user",
17,200✔
3786
                              "invocation_id",
3787
                              &p->invocation_id,
8,600✔
3788
                              sizeof(p->invocation_id),
3789
                              KEY_SPEC_SESSION_KEYRING);
3790
                if (key == -1)
8,600✔
3791
                        log_debug_errno(errno, "Failed to add invocation ID to keyring, ignoring: %m");
×
3792
                else {
3793
                        if (keyctl(KEYCTL_SETPERM, key,
8,600✔
3794
                                   KEY_POS_VIEW|KEY_POS_READ|KEY_POS_SEARCH|
3795
                                   KEY_USR_VIEW|KEY_USR_READ|KEY_USR_SEARCH, 0, 0) < 0)
3796
                                r = log_error_errno(errno, "Failed to restrict invocation ID permission: %m");
×
3797
                }
3798
        }
3799

3800
out:
8,600✔
3801
        /* Revert back uid & gid for the last time, and exit */
3802
        /* no extra logging, as only the first already reported error matters */
3803
        if (getuid() != saved_uid)
8,600✔
3804
                (void) setreuid(saved_uid, -1);
×
3805

3806
        if (getgid() != saved_gid)
8,600✔
3807
                (void) setregid(saved_gid, -1);
×
3808

3809
        return r;
3810
}
3811

3812
static void append_socket_pair(int *array, size_t *n, const int pair[static 2]) {
34,675✔
3813
        assert(array);
34,675✔
3814
        assert(n);
34,675✔
3815
        assert(pair);
34,675✔
3816

3817
        if (pair[0] >= 0)
34,675✔
3818
                array[(*n)++] = pair[0];
186✔
3819
        if (pair[1] >= 0)
34,675✔
3820
                array[(*n)++] = pair[1];
186✔
3821
}
34,675✔
3822

3823
static int close_remaining_fds(
11,517✔
3824
                const ExecParameters *params,
3825
                const ExecRuntime *runtime,
3826
                int socket_fd,
3827
                const int *fds,
3828
                size_t n_fds) {
11,517✔
3829

3830
        size_t n_dont_close = 0;
11,517✔
3831
        int dont_close[n_fds + 17];
11,517✔
3832

3833
        assert(params);
11,517✔
3834
        assert(runtime);
11,517✔
3835

3836
        if (params->stdin_fd >= 0)
11,517✔
3837
                dont_close[n_dont_close++] = params->stdin_fd;
527✔
3838
        if (params->stdout_fd >= 0)
11,517✔
3839
                dont_close[n_dont_close++] = params->stdout_fd;
527✔
3840
        if (params->stderr_fd >= 0)
11,517✔
3841
                dont_close[n_dont_close++] = params->stderr_fd;
527✔
3842

3843
        if (socket_fd >= 0)
11,517✔
3844
                dont_close[n_dont_close++] = socket_fd;
17✔
3845
        if (n_fds > 0) {
11,517✔
3846
                memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
11,517✔
3847
                n_dont_close += n_fds;
11,517✔
3848
        }
3849

3850
        append_socket_pair(dont_close, &n_dont_close, runtime->ephemeral_storage_socket);
11,517✔
3851

3852
        if (runtime->shared) {
11,517✔
3853
                append_socket_pair(dont_close, &n_dont_close, runtime->shared->netns_storage_socket);
11,517✔
3854
                append_socket_pair(dont_close, &n_dont_close, runtime->shared->ipcns_storage_socket);
11,517✔
3855
        }
3856

3857
        if (runtime->dynamic_creds) {
11,517✔
3858
                if (runtime->dynamic_creds->user)
11,517✔
3859
                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->user->storage_socket);
62✔
3860
                if (runtime->dynamic_creds->group)
11,517✔
3861
                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->group->storage_socket);
62✔
3862
        }
3863

3864
        if (params->user_lookup_fd >= 0)
11,517✔
3865
                dont_close[n_dont_close++] = params->user_lookup_fd;
11,517✔
3866

3867
        if (params->handoff_timestamp_fd >= 0)
11,517✔
3868
                dont_close[n_dont_close++] = params->handoff_timestamp_fd;
11,517✔
3869

3870
        if (params->pidref_transport_fd >= 0)
11,517✔
3871
                dont_close[n_dont_close++] = params->pidref_transport_fd;
10,464✔
3872

3873
        assert(n_dont_close <= ELEMENTSOF(dont_close));
11,517✔
3874

3875
        return close_all_fds(dont_close, n_dont_close);
11,517✔
3876
}
3877

3878
static int send_user_lookup(
11,515✔
3879
                const char *unit_id,
3880
                int user_lookup_fd,
3881
                uid_t uid,
3882
                gid_t gid) {
3883

3884
        assert(unit_id);
11,515✔
3885

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

3890
        if (user_lookup_fd < 0)
11,515✔
3891
                return 0;
3892

3893
        if (!uid_is_valid(uid) && !gid_is_valid(gid))
11,515✔
3894
                return 0;
3895

3896
        if (writev(user_lookup_fd,
2,646✔
3897
               (struct iovec[]) {
2,646✔
3898
                           IOVEC_MAKE(&uid, sizeof(uid)),
3899
                           IOVEC_MAKE(&gid, sizeof(gid)),
3900
                           IOVEC_MAKE_STRING(unit_id) }, 3) < 0)
2,646✔
3901
                return -errno;
×
3902

3903
        return 0;
2,646✔
3904
}
3905

3906
static int acquire_home(const ExecContext *c, const char **home, char **ret_buf) {
11,515✔
3907
        int r;
11,515✔
3908

3909
        assert(c);
11,515✔
3910
        assert(home);
11,515✔
3911
        assert(ret_buf);
11,515✔
3912

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

3915
        if (*home) /* Already acquired from get_fixed_user()? */
11,515✔
3916
                return 0;
3917

3918
        if (!c->working_directory_home)
8,936✔
3919
                return 0;
3920

3921
        if (c->dynamic_user || (c->user && is_this_me(c->user) <= 0))
×
3922
                return -EADDRNOTAVAIL;
×
3923

3924
        r = get_home_dir(ret_buf);
×
3925
        if (r < 0)
×
3926
                return r;
3927

3928
        *home = *ret_buf;
×
3929
        return 1;
×
3930
}
3931

3932
static int compile_suggested_paths(const ExecContext *c, const ExecParameters *p, char ***ret) {
62✔
3933
        _cleanup_strv_free_ char ** list = NULL;
62✔
3934
        int r;
62✔
3935

3936
        assert(c);
62✔
3937
        assert(p);
62✔
3938
        assert(ret);
62✔
3939

3940
        assert(c->dynamic_user);
62✔
3941

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

3946
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
372✔
3947

3948
                if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(t))
310✔
3949
                        continue;
62✔
3950

3951
                if (!p->prefix[t])
248✔
3952
                        continue;
×
3953

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

3957
                        if (exec_directory_is_private(c, t))
15✔
3958
                                e = path_join(p->prefix[t], "private", c->directories[t].items[i].path);
13✔
3959
                        else
3960
                                e = path_join(p->prefix[t], c->directories[t].items[i].path);
2✔
3961
                        if (!e)
15✔
3962
                                return -ENOMEM;
3963

3964
                        r = strv_consume(&list, e);
15✔
3965
                        if (r < 0)
15✔
3966
                                return r;
3967
                }
3968
        }
3969

3970
        *ret = TAKE_PTR(list);
62✔
3971

3972
        return 0;
62✔
3973
}
3974

3975
static int exec_context_cpu_affinity_from_numa(const ExecContext *c, CPUSet *ret) {
2✔
3976
        _cleanup_(cpu_set_reset) CPUSet s = {};
2✔
3977
        int r;
2✔
3978

3979
        assert(c);
2✔
3980
        assert(ret);
2✔
3981

3982
        if (!c->numa_policy.nodes.set) {
2✔
3983
                log_debug("Can't derive CPU affinity mask from NUMA mask because NUMA mask is not set, ignoring");
×
3984
                return 0;
×
3985
        }
3986

3987
        r = numa_to_cpu_set(&c->numa_policy, &s);
2✔
3988
        if (r < 0)
2✔
3989
                return r;
3990

3991
        cpu_set_reset(ret);
2✔
3992

3993
        return cpu_set_add_all(ret, &s);
2✔
3994
}
3995

3996
static int add_shifted_fd(int *fds, size_t fds_size, size_t *n_fds, int *fd) {
44,093✔
3997
        int r;
44,093✔
3998

3999
        assert(fds);
44,093✔
4000
        assert(n_fds);
44,093✔
4001
        assert(*n_fds < fds_size);
44,093✔
4002
        assert(fd);
44,093✔
4003

4004
        if (*fd < 0)
44,093✔
4005
               return 0;
44,093✔
4006

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

4011
                r = fcntl(*fd, F_DUPFD_CLOEXEC, 3 + (int) *n_fds);
9,542✔
4012
                if (r < 0)
9,542✔
4013
                        return -errno;
×
4014

4015
                close_and_replace(*fd, r);
9,542✔
4016
        }
4017

4018
        fds[(*n_fds)++] = *fd;
21,441✔
4019
        return 1;
21,441✔
4020
}
4021

4022
static int connect_unix_harder(const OpenFile *of, int ofd) {
1✔
4023
        static const int socket_types[] = { SOCK_DGRAM, SOCK_STREAM, SOCK_SEQPACKET };
1✔
4024

4025
        union sockaddr_union addr = {
1✔
4026
                .un.sun_family = AF_UNIX,
4027
        };
4028
        socklen_t sa_len;
1✔
4029
        int r;
1✔
4030

4031
        assert(of);
1✔
4032
        assert(ofd >= 0);
1✔
4033

4034
        r = sockaddr_un_set_path(&addr.un, FORMAT_PROC_FD_PATH(ofd));
1✔
4035
        if (r < 0)
1✔
4036
                return log_debug_errno(r, "Failed to set sockaddr for '%s': %m", of->path);
×
4037
        sa_len = r;
1✔
4038

4039
        FOREACH_ELEMENT(i, socket_types) {
2✔
4040
                _cleanup_close_ int fd = -EBADF;
2✔
4041

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

4046
                r = RET_NERRNO(connect(fd, &addr.sa, sa_len));
2✔
4047
                if (r >= 0)
1✔
4048
                        return TAKE_FD(fd);
1✔
4049
                if (r != -EPROTOTYPE)
1✔
4050
                        return log_debug_errno(r, "Failed to connect to socket for '%s': %m", of->path);
×
4051
        }
4052

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

4056
static int get_open_file_fd(const OpenFile *of) {
5✔
4057
        _cleanup_close_ int fd = -EBADF, ofd = -EBADF;
5✔
4058
        struct stat st;
5✔
4059

4060
        assert(of);
5✔
4061

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

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

4069
        if (S_ISSOCK(st.st_mode)) {
3✔
4070
                fd = connect_unix_harder(of, ofd);
1✔
4071
                if (fd < 0)
1✔
4072
                        return fd;
4073

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

4077
                log_debug("Opened socket '%s' as fd %d.", of->path, fd);
1✔
4078
        } else {
4079
                int flags = FLAGS_SET(of->flags, OPENFILE_READ_ONLY) ? O_RDONLY : O_RDWR;
2✔
4080
                if (FLAGS_SET(of->flags, OPENFILE_APPEND))
2✔
4081
                        flags |= O_APPEND;
×
4082
                else if (FLAGS_SET(of->flags, OPENFILE_TRUNCATE))
2✔
4083
                        flags |= O_TRUNC;
×
4084

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

4089
                log_debug("Opened file '%s' as fd %d.", of->path, fd);
2✔
4090
        }
4091

4092
        return TAKE_FD(fd);
4093
}
4094

4095
static int collect_open_file_fds(ExecParameters *p, size_t *n_fds) {
11,518✔
4096
        assert(p);
11,518✔
4097
        assert(n_fds);
11,518✔
4098

4099
        LIST_FOREACH(open_files, of, p->open_files) {
11,518✔
4100
                _cleanup_close_ int fd = -EBADF;
11,523✔
4101

4102
                fd = get_open_file_fd(of);
5✔
4103
                if (fd < 0) {
5✔
4104
                        if (FLAGS_SET(of->flags, OPENFILE_GRACEFUL)) {
2✔
4105
                                log_full_errno(fd == -ENOENT || ERRNO_IS_NEG_PRIVILEGE(fd) ? LOG_DEBUG : LOG_WARNING,
1✔
4106
                                               fd,
4107
                                               "Failed to get OpenFile= file descriptor for '%s', ignoring: %m",
4108
                                               of->path);
4109
                                continue;
1✔
4110
                        }
4111

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

4115
                if (!GREEDY_REALLOC(p->fds, *n_fds + 1))
3✔
4116
                        return log_oom();
×
4117

4118
                if (strv_extend(&p->fd_names, of->fdname) < 0)
3✔
4119
                        return log_oom();
×
4120

4121
                p->fds[(*n_fds)++] = TAKE_FD(fd);
3✔
4122
        }
4123

4124
        return 0;
4125
}
4126

4127
static void log_command_line(
9,541✔
4128
                const ExecContext *context,
4129
                const ExecParameters *params,
4130
                const char *msg,
4131
                const char *executable,
4132
                char **argv) {
4133

4134
        assert(context);
9,541✔
4135
        assert(params);
9,541✔
4136
        assert(msg);
9,541✔
4137
        assert(executable);
9,541✔
4138

4139
        if (!DEBUG_LOGGING)
9,541✔
4140
                return;
9,541✔
4141

4142
        _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);
18,428✔
4143

4144
        log_struct(LOG_DEBUG,
17,641✔
4145
                   LOG_ITEM("EXECUTABLE=%s", executable),
4146
                   LOG_EXEC_MESSAGE(params, "%s: %s", msg, strnull(cmdline)),
4147
                   LOG_EXEC_INVOCATION_ID(params));
4148
}
4149

4150
static bool exec_context_needs_cap_sys_admin(const ExecContext *context) {
1,623✔
4151
        assert(context);
1,623✔
4152

4153
        return context->private_users != PRIVATE_USERS_NO ||
3,233✔
4154
               context->private_tmp != PRIVATE_TMP_NO ||
1,610✔
4155
               context->private_devices ||
1,595✔
4156
               context->private_network ||
1,588✔
4157
               context->network_namespace_path ||
1,581✔
4158
               context->private_ipc ||
1,581✔
4159
               context->ipc_namespace_path ||
1,581✔
4160
               context->private_mounts > 0 ||
1,581✔
4161
               context->mount_apivfs > 0 ||
1,571✔
4162
               context->bind_log_sockets > 0 ||
1,571✔
4163
               context->n_bind_mounts > 0 ||
1,571✔
4164
               context->n_temporary_filesystems > 0 ||
1,566✔
4165
               context->root_directory ||
1,566✔
4166
               !strv_isempty(context->extension_directories) ||
1,566✔
4167
               context->protect_system != PROTECT_SYSTEM_NO ||
1,566✔
4168
               context->protect_home != PROTECT_HOME_NO ||
3,117✔
4169
               exec_needs_pid_namespace(context) ||
1,551✔
4170
               context->protect_kernel_tunables ||
1,529✔
4171
               context->protect_kernel_modules ||
1,524✔
4172
               context->protect_kernel_logs ||
3,038✔
4173
               exec_needs_cgroup_mount(context) ||
1,519✔
4174
               context->protect_clock ||
1,519✔
4175
               context->protect_hostname != PROTECT_HOSTNAME_NO ||
1,514✔
4176
               !strv_isempty(context->read_write_paths) ||
1,509✔
4177
               !strv_isempty(context->read_only_paths) ||
1,494✔
4178
               !strv_isempty(context->inaccessible_paths) ||
1,494✔
4179
               !strv_isempty(context->exec_paths) ||
1,494✔
4180
               !strv_isempty(context->no_exec_paths) ||
3,117✔
4181
               context->delegate_namespaces != NAMESPACE_FLAGS_INITIAL;
1,494✔
4182
}
4183

4184
static PrivateUsers exec_context_get_effective_private_users(
9,550✔
4185
                const ExecContext *context,
4186
                const ExecParameters *params) {
4187

4188
        assert(context);
9,550✔
4189
        assert(params);
9,550✔
4190

4191
        if (context->private_users != PRIVATE_USERS_NO)
9,550✔
4192
                return context->private_users;
4193

4194
        /* If any namespace is delegated with DelegateNamespaces=, always set up a user namespace. */
4195
        if (context->delegate_namespaces != NAMESPACE_FLAGS_INITIAL)
9,526✔
4196
                return PRIVATE_USERS_SELF;
3✔
4197

4198
        return PRIVATE_USERS_NO;
4199
}
4200

4201
static bool exec_namespace_is_delegated(
23,263✔
4202
                const ExecContext *context,
4203
                const ExecParameters *params,
4204
                bool have_cap_sys_admin,
4205
                unsigned long namespace) {
4206

4207
        assert(context);
23,263✔
4208
        assert(params);
23,263✔
4209
        assert(namespace != CLONE_NEWUSER);
23,263✔
4210

4211
        /* If we need unprivileged private users, we've already unshared a user namespace by the time we call
4212
         * setup_delegated_namespaces() for the first time so let's make sure we do all other namespace
4213
         * unsharing in the first call to setup_delegated_namespaces() by returning false here. */
4214
        if (!have_cap_sys_admin && exec_context_needs_cap_sys_admin(context))
23,263✔
4215
                return false;
4216

4217
        if (context->delegate_namespaces == NAMESPACE_FLAGS_INITIAL)
23,161✔
4218
                return params->runtime_scope == RUNTIME_SCOPE_USER;
23,113✔
4219

4220
        if (FLAGS_SET(context->delegate_namespaces, namespace))
48✔
4221
                return true;
4222

4223
        /* Various namespaces imply mountns for private procfs/sysfs/cgroupfs instances, which means when
4224
         * those are delegated mountns must be deferred too.
4225
         *
4226
         * The list should stay in sync with exec_needs_mount_namespace(). */
4227
        if (namespace == CLONE_NEWNS)
16✔
4228
                return context->delegate_namespaces & (CLONE_NEWPID|CLONE_NEWCGROUP|CLONE_NEWNET);
4✔
4229

4230
        return false;
4231
}
4232

4233
static int setup_delegated_namespaces(
19,111✔
4234
                const ExecContext *context,
4235
                ExecParameters *params,
4236
                ExecRuntime *runtime,
4237
                bool delegate,
4238
                const char *memory_pressure_path,
4239
                uid_t uid,
4240
                uid_t gid,
4241
                const ExecCommand *command,
4242
                bool needs_sandboxing,
4243
                bool have_cap_sys_admin,
4244
                int *reterr_exit_status) {
4245

4246
        int r;
19,111✔
4247

4248
        /* This function is called twice, once before unsharing the user namespace, and once after unsharing
4249
         * the user namespace. When called before unsharing the user namespace, "delegate" is set to "false".
4250
         * When called after unsharing the user namespace, "delegate" is set to "true". The net effect is
4251
         * that all namespaces that should not be delegated are unshared when this function is called the
4252
         * first time and all namespaces that should be delegated are unshared when this function is called
4253
         * the second time. */
4254

4255
        assert(context);
19,111✔
4256
        assert(params);
19,111✔
4257
        assert(runtime);
19,111✔
4258
        assert(reterr_exit_status);
19,111✔
4259

4260
        if (exec_needs_network_namespace(context) &&
19,226✔
4261
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWNET) == delegate &&
115✔
4262
            runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
58✔
4263

4264
                /* Try to enable network namespacing if network namespacing is available and we have
4265
                 * CAP_NET_ADMIN in the current user namespace (either the system manager one or the unit's
4266
                 * own user namespace). We need CAP_NET_ADMIN to be able to configure the loopback device in
4267
                 * the new network namespace. And if we don't have that, then we could only create a network
4268
                 * namespace without the ability to set up "lo". Hence gracefully skip things then. */
4269
                if (namespace_type_supported(NAMESPACE_NET) && have_effective_cap(CAP_NET_ADMIN) > 0) {
58✔
4270
                        r = setup_shareable_ns(runtime->shared->netns_storage_socket, CLONE_NEWNET);
58✔
4271
                        if (ERRNO_IS_NEG_PRIVILEGE(r))
58✔
4272
                                log_notice_errno(r, "PrivateNetwork=yes is configured, but network namespace setup not permitted, proceeding without: %m");
×
4273
                        else if (r < 0) {
58✔
4274
                                *reterr_exit_status = EXIT_NETWORK;
×
4275
                                return log_error_errno(r, "Failed to set up network namespacing: %m");
×
4276
                        } else
4277
                                log_debug("Set up %snetwork namespace", delegate ? "delegated " : "");
113✔
4278
                } else if (context->network_namespace_path) {
×
4279
                        *reterr_exit_status = EXIT_NETWORK;
×
4280
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "NetworkNamespacePath= is not supported, refusing.");
×
4281
                } else
4282
                        log_notice("PrivateNetwork=yes is configured, but the kernel does not support or we lack privileges for network namespace, proceeding without.");
×
4283
        }
4284

4285
        if (exec_needs_ipc_namespace(context) &&
19,118✔
4286
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWIPC) == delegate &&
7✔
4287
            runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
4✔
4288

4289
                if (namespace_type_supported(NAMESPACE_IPC)) {
4✔
4290
                        r = setup_shareable_ns(runtime->shared->ipcns_storage_socket, CLONE_NEWIPC);
4✔
4291
                        if (ERRNO_IS_NEG_PRIVILEGE(r))
4✔
4292
                                log_warning_errno(r, "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m");
×
4293
                        else if (r < 0) {
4✔
4294
                                *reterr_exit_status = EXIT_NAMESPACE;
×
4295
                                return log_error_errno(r, "Failed to set up IPC namespacing: %m");
×
4296
                        } else
4297
                                log_debug("Set up %sIPC namespace", delegate ? "delegated " : "");
6✔
4298
                } else if (context->ipc_namespace_path) {
×
4299
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4300
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "IPCNamespacePath= is not supported, refusing.");
×
4301
                } else
4302
                        log_warning("PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring.");
×
4303
        }
4304

4305
        if (needs_sandboxing && exec_needs_cgroup_namespace(context) &&
19,132✔
4306
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWCGROUP) == delegate) {
21✔
4307
                if (unshare(CLONE_NEWCGROUP) < 0) {
11✔
4308
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4309
                        return log_error_errno(errno, "Failed to set up cgroup namespacing: %m");
×
4310
                }
4311

4312
                log_debug("Set up %scgroup namespace", delegate ? "delegated " : "");
20✔
4313
        }
4314

4315
        /* Unshare a new PID namespace before setting up mounts to ensure /proc/ is mounted with only processes in PID namespace visible.
4316
         * Note PrivatePIDs=yes implies MountAPIVFS=yes so we'll always ensure procfs is remounted. */
4317
        if (needs_sandboxing && exec_needs_pid_namespace(context) &&
19,132✔
4318
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWPID) == delegate) {
21✔
4319
                if (params->pidref_transport_fd < 0) {
13✔
4320
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4321
                        return log_error_errno(SYNTHETIC_ERRNO(ENOTCONN), "PidRef socket is not set up: %m");
×
4322
                }
4323

4324
                /* If we had CAP_SYS_ADMIN prior to joining the user namespace, then we are privileged and don't need
4325
                 * to check if we can mount /proc/.
4326
                 *
4327
                 * We need to check prior to entering the user namespace because if we're running unprivileged or in a
4328
                 * system without CAP_SYS_ADMIN, then we can have CAP_SYS_ADMIN in the current user namespace but not
4329
                 * once we unshare a mount namespace. */
4330
                if (!have_cap_sys_admin || delegate) {
13✔
4331
                        r = can_mount_proc();
8✔
4332
                        if (r < 0) {
4✔
4333
                                *reterr_exit_status = EXIT_NAMESPACE;
×
4334
                                return log_error_errno(r, "Failed to detect if /proc/ can be remounted: %m");
×
4335
                        }
4336
                        if (r == 0) {
4✔
4337
                                *reterr_exit_status = EXIT_NAMESPACE;
1✔
4338
                                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
1✔
4339
                                                       "PrivatePIDs=yes is configured, but /proc/ cannot be re-mounted due to lack of privileges, refusing.");
4340
                        }
4341
                }
4342

4343
                r = setup_private_pids(context, params);
8✔
4344
                if (r < 0) {
6✔
4345
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4346
                        return log_error_errno(r, "Failed to set up pid namespace: %m");
×
4347
                }
4348

4349
                log_debug("Set up %spid namespace", delegate ? "delegated " : "");
12✔
4350
        }
4351

4352
        /* If PrivatePIDs= yes is configured, we're now running as pid 1 in a pid namespace! */
4353

4354
        if (exec_needs_mount_namespace(context, params, runtime) &&
23,114✔
4355
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWNS) == delegate) {
4,010✔
4356
                _cleanup_free_ char *error_path = NULL;
2,012✔
4357

4358
                r = apply_mount_namespace(command->flags,
2,012✔
4359
                                          context,
4360
                                          params,
4361
                                          runtime,
4362
                                          memory_pressure_path,
4363
                                          needs_sandboxing,
4364
                                          &error_path,
4365
                                          uid,
4366
                                          gid);
4367
                if (r < 0) {
2,012✔
4368
                        *reterr_exit_status = EXIT_NAMESPACE;
15✔
4369
                        return log_error_errno(r, "Failed to set up mount namespacing%s%s: %m",
29✔
4370
                                               error_path ? ": " : "", strempty(error_path));
4371
                }
4372

4373
                log_debug("Set up %smount namespace", delegate ? "delegated " : "");
3,966✔
4374
        }
4375

4376
        if (needs_sandboxing &&
38,178✔
4377
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWUTS) == delegate) {
19,089✔
4378
                r = apply_protect_hostname(context, params, reterr_exit_status);
9,544✔
4379
                if (r < 0)
9,544✔
4380
                        return r;
4381
                if (r > 0)
9,544✔
4382
                        log_debug("Set up %sUTS namespace", delegate ? "delegated " : "");
1,327✔
4383
        }
4384

4385
        return 0;
4386
}
4387

4388
static bool exec_context_shall_confirm_spawn(const ExecContext *context) {
×
4389
        assert(context);
×
4390

4391
        if (confirm_spawn_disabled())
×
4392
                return false;
4393

4394
        /* For some reasons units remaining in the same process group
4395
         * as PID 1 fail to acquire the console even if it's not used
4396
         * by any process. So skip the confirmation question for them. */
4397
        return !context->same_pgrp;
×
4398
}
4399

4400
static int exec_context_named_iofds(
11,518✔
4401
                const ExecContext *c,
4402
                const ExecParameters *p,
4403
                int named_iofds[static 3]) {
4404

4405
        size_t targets;
11,518✔
4406
        const char* stdio_fdname[3];
11,518✔
4407
        size_t n_fds;
11,518✔
4408

4409
        assert(c);
11,518✔
4410
        assert(p);
11,518✔
4411
        assert(named_iofds);
11,518✔
4412

4413
        targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
11,518✔
4414
                  (c->std_output == EXEC_OUTPUT_NAMED_FD) +
11,518✔
4415
                  (c->std_error == EXEC_OUTPUT_NAMED_FD);
11,518✔
4416

4417
        for (size_t i = 0; i < 3; i++)
46,072✔
4418
                stdio_fdname[i] = exec_context_fdname(c, i);
34,554✔
4419

4420
        n_fds = p->n_storage_fds + p->n_socket_fds + p->n_extra_fds;
11,518✔
4421

4422
        for (size_t i = 0; i < n_fds  && targets > 0; i++)
11,518✔
4423
                if (named_iofds[STDIN_FILENO] < 0 &&
×
4424
                    c->std_input == EXEC_INPUT_NAMED_FD &&
×
4425
                    stdio_fdname[STDIN_FILENO] &&
×
4426
                    streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
×
4427

4428
                        named_iofds[STDIN_FILENO] = p->fds[i];
×
4429
                        targets--;
×
4430

4431
                } else if (named_iofds[STDOUT_FILENO] < 0 &&
×
4432
                           c->std_output == EXEC_OUTPUT_NAMED_FD &&
×
4433
                           stdio_fdname[STDOUT_FILENO] &&
×
4434
                           streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
×
4435

4436
                        named_iofds[STDOUT_FILENO] = p->fds[i];
×
4437
                        targets--;
×
4438

4439
                } else if (named_iofds[STDERR_FILENO] < 0 &&
×
4440
                           c->std_error == EXEC_OUTPUT_NAMED_FD &&
×
4441
                           stdio_fdname[STDERR_FILENO] &&
×
4442
                           streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
×
4443

4444
                        named_iofds[STDERR_FILENO] = p->fds[i];
×
4445
                        targets--;
×
4446
                }
4447

4448
        return targets == 0 ? 0 : -ENOENT;
11,518✔
4449
}
4450

4451
static void exec_shared_runtime_close(ExecSharedRuntime *shared) {
9,542✔
4452
        if (!shared)
9,542✔
4453
                return;
4454

4455
        safe_close_pair(shared->netns_storage_socket);
9,542✔
4456
        safe_close_pair(shared->ipcns_storage_socket);
9,542✔
4457
}
4458

4459
static void exec_runtime_close(ExecRuntime *rt) {
9,542✔
4460
        if (!rt)
9,542✔
4461
                return;
4462

4463
        safe_close_pair(rt->ephemeral_storage_socket);
9,542✔
4464

4465
        exec_shared_runtime_close(rt->shared);
9,542✔
4466
        dynamic_creds_close(rt->dynamic_creds);
9,542✔
4467
}
4468

4469
static void exec_params_close(ExecParameters *p) {
9,542✔
4470
        if (!p)
9,542✔
4471
                return;
4472

4473
        p->stdin_fd = safe_close(p->stdin_fd);
9,542✔
4474
        p->stdout_fd = safe_close(p->stdout_fd);
9,542✔
4475
        p->stderr_fd = safe_close(p->stderr_fd);
9,542✔
4476
}
4477

4478
static int exec_fd_mark_hot(
9,544✔
4479
                const ExecContext *c,
4480
                ExecParameters *p,
4481
                bool hot,
4482
                int *reterr_exit_status) {
4483

4484
        assert(c);
9,544✔
4485
        assert(p);
9,544✔
4486

4487
        if (p->exec_fd < 0)
9,544✔
4488
                return 0;
9,544✔
4489

4490
        uint8_t x = hot;
275✔
4491

4492
        if (write(p->exec_fd, &x, sizeof(x)) < 0) {
275✔
4493
                if (reterr_exit_status)
×
4494
                        *reterr_exit_status = EXIT_EXEC;
×
4495
                return log_error_errno(errno, "Failed to mark exec_fd as %s: %m", hot ? "hot" : "cold");
×
4496
        }
4497

4498
        return 1;
4499
}
4500

4501
static int send_handoff_timestamp(
9,541✔
4502
                const ExecContext *c,
4503
                ExecParameters *p,
4504
                int *reterr_exit_status) {
4505

4506
        assert(c);
9,541✔
4507
        assert(p);
9,541✔
4508

4509
        if (p->handoff_timestamp_fd < 0)
9,541✔
4510
                return 0;
9,541✔
4511

4512
        dual_timestamp dt;
9,541✔
4513
        dual_timestamp_now(&dt);
9,541✔
4514

4515
        if (write(p->handoff_timestamp_fd, (const usec_t[2]) { dt.realtime, dt.monotonic }, sizeof(usec_t) * 2) < 0) {
9,541✔
4516
                if (reterr_exit_status)
×
4517
                        *reterr_exit_status = EXIT_EXEC;
×
4518
                return log_error_errno(errno, "Failed to send handoff timestamp: %m");
×
4519
        }
4520

4521
        return 1;
9,541✔
4522
}
4523

4524
static void prepare_terminal(
11,515✔
4525
                const ExecContext *context,
4526
                ExecParameters *p) {
4527

4528
        _cleanup_close_ int lock_fd = -EBADF;
11,515✔
4529

4530
        /* This is the "constructive" reset, i.e. is about preparing things for our invocation rather than
4531
         * cleaning up things from older invocations. */
4532

4533
        assert(context);
11,515✔
4534
        assert(p);
11,515✔
4535

4536
        /* We only try to reset things if we there's the chance our stdout points to a TTY */
4537
        if (!(is_terminal_output(context->std_output) ||
11,515✔
4538
              (context->std_output == EXEC_OUTPUT_INHERIT && is_terminal_input(context->std_input)) ||
10,905✔
4539
              context->std_output == EXEC_OUTPUT_NAMED_FD ||
4540
              p->stdout_fd >= 0))
10,905✔
4541
                return;
10,378✔
4542

4543
        /* Let's explicitly determine whether to reset via ANSI sequences or not, taking our ExecContext
4544
         * information into account */
4545
        bool use_ansi = exec_context_shall_ansi_seq_reset(context);
1,137✔
4546

4547
        if (context->tty_reset) {
1,137✔
4548
                /* When we are resetting the TTY, then let's create a lock first, to synchronize access. This
4549
                 * in particular matters as concurrent resets and the TTY size ANSI DSR logic done by the
4550
                 * exec_context_apply_tty_size() below might interfere */
4551
                lock_fd = lock_dev_console();
156✔
4552
                if (lock_fd < 0)
156✔
4553
                        log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
×
4554

4555
                /* We explicitly control whether to send ansi sequences or not here, since we want to consult
4556
                 * the env vars explicitly configured in the ExecContext, rather than our own environment
4557
                 * block. */
4558
                (void) terminal_reset_defensive(STDOUT_FILENO, use_ansi ? TERMINAL_RESET_FORCE_ANSI_SEQ : TERMINAL_RESET_AVOID_ANSI_SEQ);
159✔
4559
        }
4560

4561
        (void) exec_context_apply_tty_size(context, STDIN_FILENO, STDOUT_FILENO, /* tty_path= */ NULL);
1,137✔
4562

4563
        if (use_ansi)
1,137✔
4564
                (void) osc_context_open_service(p->unit_id, p->invocation_id, /* ret_seq= */ NULL);
153✔
4565
}
4566

4567
int exec_invoke(
11,518✔
4568
                const ExecCommand *command,
4569
                const ExecContext *context,
4570
                ExecParameters *params,
4571
                ExecRuntime *runtime,
4572
                const CGroupContext *cgroup_context,
4573
                int *exit_status) {
11,518✔
4574

4575
        _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **joined_exec_search_path = NULL, **accum_env = NULL, **replaced_argv = NULL;
28✔
4576
        int r;
11,518✔
4577
        const char *username = NULL, *groupname = NULL;
11,518✔
4578
        _cleanup_free_ char *home_buffer = NULL, *memory_pressure_path = NULL, *own_user = NULL;
×
4579
        const char *pwent_home = NULL, *shell = NULL;
11,518✔
4580
        char **final_argv = NULL;
11,518✔
4581
        dev_t journal_stream_dev = 0;
11,518✔
4582
        ino_t journal_stream_ino = 0;
11,518✔
4583
        bool needs_sandboxing,          /* Do we need to set up full sandboxing? (i.e. all namespacing, all MAC stuff, caps, yadda yadda */
11,518✔
4584
                needs_setuid,           /* Do we need to do the actual setresuid()/setresgid() calls? */
4585
                needs_mount_namespace,  /* Do we need to set up a mount namespace for this kernel? */
4586
                have_cap_sys_admin,
4587
                userns_set_up = false,
11,518✔
4588
                keep_seccomp_privileges = false;
11,518✔
4589
#if HAVE_SELINUX
4590
        _cleanup_free_ char *mac_selinux_context_net = NULL;
4591
        bool use_selinux = false;
4592
#endif
4593
#if ENABLE_SMACK
4594
        bool use_smack = false;
11,518✔
4595
#endif
4596
#if HAVE_APPARMOR
4597
        bool use_apparmor = false;
4598
#endif
4599
#if HAVE_SECCOMP
4600
        uint64_t saved_bset = 0;
11,518✔
4601
#endif
4602
        uid_t saved_uid = getuid();
11,518✔
4603
        gid_t saved_gid = getgid();
11,518✔
4604
        uid_t uid = UID_INVALID;
11,518✔
4605
        gid_t gid = GID_INVALID;
11,518✔
4606
        size_t n_fds, /* fds to pass to the child */
11,518✔
4607
               n_keep_fds; /* total number of fds not to close */
4608
        int secure_bits;
11,518✔
4609
        _cleanup_free_ gid_t *gids = NULL, *gids_after_pam = NULL;
28✔
4610
        int ngids = 0, ngids_after_pam = 0;
11,518✔
4611
        int socket_fd = -EBADF, named_iofds[3] = EBADF_TRIPLET;
11,518✔
4612
        size_t n_storage_fds, n_socket_fds, n_extra_fds;
11,518✔
4613

4614
        assert(command);
11,518✔
4615
        assert(context);
11,518✔
4616
        assert(params);
11,518✔
4617
        assert(runtime);
11,518✔
4618
        assert(cgroup_context);
11,518✔
4619
        assert(exit_status);
11,518✔
4620

4621
        LOG_CONTEXT_PUSH_EXEC(context, params);
32,996✔
4622

4623
        /* Explicitly test for CVE-2021-4034 inspired invocations */
4624
        if (!command->path || strv_isempty(command->argv)) {
11,518✔
4625
                *exit_status = EXIT_EXEC;
×
4626
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid command line arguments.");
×
4627
        }
4628

4629
        if (context->std_input == EXEC_INPUT_SOCKET ||
11,518✔
4630
            context->std_output == EXEC_OUTPUT_SOCKET ||
11,507✔
4631
            context->std_error == EXEC_OUTPUT_SOCKET) {
11,501✔
4632

4633
                if (params->n_socket_fds > 1)
17✔
4634
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Got more than one socket.");
×
4635

4636
                if (params->n_socket_fds == 0)
17✔
4637
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Got no socket.");
×
4638

4639
                socket_fd = params->fds[0];
17✔
4640
                n_storage_fds = n_socket_fds = n_extra_fds = 0;
17✔
4641
        } else {
4642
                n_socket_fds = params->n_socket_fds;
11,501✔
4643
                n_storage_fds = params->n_storage_fds;
11,501✔
4644
                n_extra_fds = params->n_extra_fds;
11,501✔
4645
        }
4646
        n_fds = n_socket_fds + n_storage_fds + n_extra_fds;
11,518✔
4647

4648
        r = exec_context_named_iofds(context, params, named_iofds);
11,518✔
4649
        if (r < 0)
11,518✔
4650
                return log_error_errno(r, "Failed to load a named file descriptor: %m");
×
4651

4652
        rename_process_from_path(command->path);
11,518✔
4653

4654
        /* We reset exactly these signals, since they are the only ones we set to SIG_IGN in the main
4655
         * daemon. All others we leave untouched because we set them to SIG_DFL or a valid handler initially,
4656
         * both of which will be demoted to SIG_DFL. */
4657
        (void) default_signals(SIGNALS_CRASH_HANDLER,
11,518✔
4658
                               SIGNALS_IGNORE);
4659

4660
        if (context->ignore_sigpipe)
11,518✔
4661
                (void) ignore_signals(SIGPIPE);
11,168✔
4662

4663
        r = reset_signal_mask();
11,518✔
4664
        if (r < 0) {
11,518✔
4665
                *exit_status = EXIT_SIGNAL_MASK;
×
4666
                return log_error_errno(r, "Failed to set process signal mask: %m");
×
4667
        }
4668

4669
        if (params->idle_pipe)
11,518✔
4670
                do_idle_pipe_dance(params->idle_pipe);
153✔
4671

4672
        /* Close fds we don't need very early to make sure we don't block init reexecution because it cannot bind its
4673
         * sockets. Among the fds we close are the logging fds, and we want to keep them closed, so that we don't have
4674
         * any fds open we don't really want open during the transition. In order to make logging work, we switch the
4675
         * log subsystem into open_when_needed mode, so that it reopens the logs on every single log call. */
4676

4677
        log_forget_fds();
11,518✔
4678
        log_set_open_when_needed(true);
11,518✔
4679
        log_settle_target();
11,518✔
4680

4681
        /* In case anything used libc syslog(), close this here, too */
4682
        closelog();
11,518✔
4683

4684
        r = collect_open_file_fds(params, &n_fds);
11,518✔
4685
        if (r < 0) {
11,518✔
4686
                *exit_status = EXIT_FDS;
1✔
4687
                return log_error_errno(r, "Failed to get OpenFile= file descriptors: %m");
1✔
4688
        }
4689

4690
        int keep_fds[n_fds + 4];
11,517✔
4691
        memcpy_safe(keep_fds, params->fds, n_fds * sizeof(int));
11,517✔
4692
        n_keep_fds = n_fds;
11,517✔
4693

4694
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->exec_fd);
11,517✔
4695
        if (r < 0) {
11,517✔
4696
                *exit_status = EXIT_FDS;
×
4697
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
4698
        }
4699

4700
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->handoff_timestamp_fd);
11,517✔
4701
        if (r < 0) {
11,517✔
4702
                *exit_status = EXIT_FDS;
×
4703
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
4704
        }
4705

4706
#if HAVE_LIBBPF
4707
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->bpf_restrict_fs_map_fd);
11,517✔
4708
        if (r < 0) {
11,517✔
4709
                *exit_status = EXIT_FDS;
×
4710
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
4711
        }
4712
#endif
4713

4714
        r = close_remaining_fds(params, runtime, socket_fd, keep_fds, n_keep_fds);
11,517✔
4715
        if (r < 0) {
11,517✔
4716
                *exit_status = EXIT_FDS;
×
4717
                return log_error_errno(r, "Failed to close unwanted file descriptors: %m");
×
4718
        }
4719

4720
        if (!context->same_pgrp &&
22,165✔
4721
            setsid() < 0) {
10,648✔
4722
                *exit_status = EXIT_SETSID;
×
4723
                return log_error_errno(errno, "Failed to create new process session: %m");
×
4724
        }
4725

4726
        /* Now, reset the TTY associated to this service "destructively" (i.e. possibly even hang up or
4727
         * disallocate the VT), to get rid of any prior uses of the device. Note that we do not keep any fd
4728
         * open here, hence some of the settings made here might vanish again, depending on the TTY driver
4729
         * used. A 2nd ("constructive") initialization after we opened the input/output fds we actually want
4730
         * will fix this. Note that we pass a NULL invocation ID here – as exec_context_tty_reset() expects
4731
         * the invocation ID associated with the OSC 3008 context ID to close. But we don't want to close any
4732
         * OSC 3008 context here, and opening a fresh OSC 3008 context happens a bit further down. */
4733
        exec_context_tty_reset(context, params, /* invocation_id= */ SD_ID128_NULL);
11,517✔
4734

4735
        if (params->shall_confirm_spawn && exec_context_shall_confirm_spawn(context)) {
11,517✔
4736
                _cleanup_free_ char *cmdline = NULL;
×
4737

4738
                cmdline = quote_command_line(command->argv, SHELL_ESCAPE_EMPTY);
×
4739
                if (!cmdline) {
×
4740
                        *exit_status = EXIT_MEMORY;
×
4741
                        return log_oom();
×
4742
                }
4743

4744
                r = ask_for_confirmation(context, params, cmdline);
×
4745
                if (r != CONFIRM_EXECUTE) {
×
4746
                        if (r == CONFIRM_PRETEND_SUCCESS) {
×
4747
                                *exit_status = EXIT_SUCCESS;
×
4748
                                return 0;
×
4749
                        }
4750

4751
                        *exit_status = EXIT_CONFIRM;
×
4752
                        return log_error_errno(SYNTHETIC_ERRNO(ECANCELED), "Execution cancelled by the user.");
×
4753
                }
4754
        }
4755

4756
        /* We are about to invoke NSS and PAM modules. Let's tell them what we are doing here, maybe they care. This is
4757
         * used by nss-resolve to disable itself when we are about to start systemd-resolved, to avoid deadlocks. Note
4758
         * that these env vars do not survive the execve(), which means they really only apply to the PAM and NSS
4759
         * invocations themselves. Also note that while we'll only invoke NSS modules involved in user management they
4760
         * might internally call into other NSS modules that are involved in hostname resolution, we never know. */
4761
        if (setenv("SYSTEMD_ACTIVATION_UNIT", params->unit_id, true) != 0 ||
23,034✔
4762
            setenv("SYSTEMD_ACTIVATION_SCOPE", runtime_scope_to_string(params->runtime_scope), true) != 0) {
11,517✔
4763
                *exit_status = EXIT_MEMORY;
×
4764
                return log_error_errno(errno, "Failed to update environment: %m");
×
4765
        }
4766

4767
        if (context->dynamic_user && runtime->dynamic_creds) {
11,579✔
4768
                _cleanup_strv_free_ char **suggested_paths = NULL;
62✔
4769

4770
                /* On top of that, make sure we bypass our own NSS module nss-systemd comprehensively for any NSS
4771
                 * checks, if DynamicUser=1 is used, as we shouldn't create a feedback loop with ourselves here. */
4772
                if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
62✔
4773
                        *exit_status = EXIT_USER;
×
4774
                        return log_error_errno(errno, "Failed to update environment: %m");
×
4775
                }
4776

4777
                r = compile_suggested_paths(context, params, &suggested_paths);
62✔
4778
                if (r < 0) {
62✔
4779
                        *exit_status = EXIT_MEMORY;
×
4780
                        return log_oom();
×
4781
                }
4782

4783
                r = dynamic_creds_realize(runtime->dynamic_creds, suggested_paths, &uid, &gid);
62✔
4784
                if (r < 0) {
62✔
4785
                        *exit_status = EXIT_USER;
×
4786
                        if (r == -EILSEQ)
×
4787
                                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
×
4788
                                                       "Failed to update dynamic user credentials: User or group with specified name already exists.");
4789
                        return log_error_errno(r, "Failed to update dynamic user credentials: %m");
×
4790
                }
4791

4792
                if (!uid_is_valid(uid)) {
62✔
4793
                        *exit_status = EXIT_USER;
×
4794
                        return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "UID validation failed for \""UID_FMT"\".", uid);
×
4795
                }
4796

4797
                if (!gid_is_valid(gid)) {
62✔
4798
                        *exit_status = EXIT_USER;
×
4799
                        return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "GID validation failed for \""GID_FMT"\".", gid);
×
4800
                }
4801

4802
                if (runtime->dynamic_creds->user)
62✔
4803
                        username = runtime->dynamic_creds->user->name;
62✔
4804

4805
        } else {
4806
                const char *u;
11,455✔
4807

4808
                if (context->user)
11,455✔
4809
                        u = context->user;
4810
                else if (context->pam_name) {
8,933✔
4811
                        /* If PAM is enabled but no user name is explicitly selected, then use our own one. */
4812
                        own_user = getusername_malloc();
59✔
4813
                        if (!own_user) {
59✔
4814
                                *exit_status = EXIT_USER;
×
4815
                                return log_error_errno(r, "Failed to determine my own user ID: %m");
×
4816
                        }
4817
                        u = own_user;
4818
                } else
4819
                        u = NULL;
4820

4821
                if (u) {
4822
                        /* We can't use nss unconditionally for root without risking deadlocks if some IPC services
4823
                         * will be started by pid1 and are ordered after us. But if SetLoginEnvironment= is
4824
                         * enabled *explicitly* (i.e. no exec_context_get_set_login_environment() here),
4825
                         * or PAM shall be invoked, let's consult NSS even for root, so that the user
4826
                         * gets accurate $SHELL in session(-like) contexts. */
4827
                        r = get_fixed_user(u,
2,581✔
4828
                                           /* prefer_nss = */ context->set_login_environment > 0 || context->pam_name,
2,581✔
4829
                                           &username, &uid, &gid, &pwent_home, &shell);
4830
                        if (r < 0) {
2,581✔
4831
                                *exit_status = EXIT_USER;
2✔
4832
                                return log_error_errno(r, "Failed to determine user credentials: %m");
2✔
4833
                        }
4834
                }
4835

4836
                if (context->group) {
11,453✔
4837
                        r = get_fixed_group(context->group, &groupname, &gid);
11✔
4838
                        if (r < 0) {
11✔
4839
                                *exit_status = EXIT_GROUP;
×
4840
                                return log_error_errno(r, "Failed to determine group credentials: %m");
×
4841
                        }
4842
                }
4843
        }
4844

4845
        /* Initialize user supplementary groups and get SupplementaryGroups= ones */
4846
        ngids = get_supplementary_groups(context, username, gid, &gids);
11,515✔
4847
        if (ngids < 0) {
11,515✔
4848
                *exit_status = EXIT_GROUP;
×
4849
                return log_error_errno(ngids, "Failed to determine supplementary groups: %m");
×
4850
        }
4851

4852
        r = send_user_lookup(params->unit_id, params->user_lookup_fd, uid, gid);
11,515✔
4853
        if (r < 0) {
11,515✔
4854
                *exit_status = EXIT_USER;
×
4855
                return log_error_errno(r, "Failed to send user credentials to PID1: %m");
×
4856
        }
4857

4858
        params->user_lookup_fd = safe_close(params->user_lookup_fd);
11,515✔
4859

4860
        r = acquire_home(context, &pwent_home, &home_buffer);
11,515✔
4861
        if (r < 0) {
11,515✔
4862
                *exit_status = EXIT_CHDIR;
×
4863
                return log_error_errno(r, "Failed to determine $HOME for the invoking user: %m");
×
4864
        }
4865

4866
        /* If a socket is connected to STDIN/STDOUT/STDERR, we must drop O_NONBLOCK */
4867
        if (socket_fd >= 0)
11,515✔
4868
                (void) fd_nonblock(socket_fd, false);
17✔
4869

4870
        /* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields.
4871
         * Hence we need to migrate to the target cgroup from init.scope before connecting to journald */
4872
        if (params->cgroup_path) {
11,515✔
4873
                _cleanup_free_ char *p = NULL;
11,515✔
4874

4875
                r = exec_params_get_cgroup_path(params, cgroup_context, &p);
11,515✔
4876
                if (r < 0) {
11,515✔
4877
                        *exit_status = EXIT_CGROUP;
×
4878
                        return log_error_errno(r, "Failed to acquire cgroup path: %m");
×
4879
                }
4880

4881
                r = cg_attach(p, 0);
11,515✔
4882
                if (r == -EUCLEAN) {
11,515✔
4883
                        *exit_status = EXIT_CGROUP;
×
4884
                        return log_error_errno(r,
×
4885
                                               "Failed to attach process to cgroup '%s', "
4886
                                               "because the cgroup or one of its parents or "
4887
                                               "siblings is in the threaded mode.", p);
4888
                }
4889
                if (r < 0) {
11,515✔
4890
                        *exit_status = EXIT_CGROUP;
×
4891
                        return log_error_errno(r, "Failed to attach to cgroup %s: %m", p);
×
4892
                }
4893
        }
4894

4895
        if (context->network_namespace_path && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
11,515✔
4896
                r = open_shareable_ns_path(runtime->shared->netns_storage_socket, context->network_namespace_path, CLONE_NEWNET);
×
4897
                if (r < 0) {
×
4898
                        *exit_status = EXIT_NETWORK;
×
4899
                        return log_error_errno(r, "Failed to open network namespace path %s: %m", context->network_namespace_path);
×
4900
                }
4901
        }
4902

4903
        if (context->ipc_namespace_path && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
11,515✔
4904
                r = open_shareable_ns_path(runtime->shared->ipcns_storage_socket, context->ipc_namespace_path, CLONE_NEWIPC);
×
4905
                if (r < 0) {
×
4906
                        *exit_status = EXIT_NAMESPACE;
×
4907
                        return log_error_errno(r, "Failed to open IPC namespace path %s: %m", context->ipc_namespace_path);
×
4908
                }
4909
        }
4910

4911
        r = setup_input(context, params, socket_fd, named_iofds);
11,515✔
4912
        if (r < 0) {
11,515✔
UNCOV
4913
                *exit_status = EXIT_STDIN;
×
UNCOV
4914
                return log_error_errno(r, "Failed to set up standard input: %m");
×
4915
        }
4916

4917
        _cleanup_free_ char *fname = NULL;
25✔
4918
        r = path_extract_filename(command->path, &fname);
11,515✔
4919
        if (r < 0) {
11,515✔
4920
                *exit_status = EXIT_STDOUT;
×
4921
                return log_error_errno(r, "Failed to extract filename from path %s: %m", command->path);
×
4922
        }
4923

4924
        r = setup_output(context, params, STDOUT_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
11,515✔
4925
        if (r < 0) {
11,515✔
4926
                *exit_status = EXIT_STDOUT;
×
4927
                return log_error_errno(r, "Failed to set up standard output: %m");
×
4928
        }
4929

4930
        r = setup_output(context, params, STDERR_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
11,515✔
4931
        if (r < 0) {
11,515✔
4932
                *exit_status = EXIT_STDERR;
×
4933
                return log_error_errno(r, "Failed to set up standard error output: %m");
×
4934
        }
4935

4936
        /* Now that stdin/stdout are definiely opened, properly initialize it with our desired
4937
         * settings. Note: this is a "constructive" reset, it prepares things for us to use. This is
4938
         * different from the "destructive" TTY reset further up. Also note: we apply this on stdin/stdout in
4939
         * case this is a tty, regardless if we opened it ourselves or got it passed in pre-opened. */
4940
        prepare_terminal(context, params);
11,515✔
4941

4942
        if (context->oom_score_adjust_set) {
11,515✔
4943
                /* When we can't make this change due to EPERM, then let's silently skip over it. User
4944
                 * namespaces prohibit write access to this file, and we shouldn't trip up over that. */
4945
                r = set_oom_score_adjust(context->oom_score_adjust);
1,297✔
4946
                if (ERRNO_IS_NEG_PRIVILEGE(r))
1,297✔
4947
                        log_debug_errno(r, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
×
4948
                else if (r < 0) {
1,297✔
4949
                        *exit_status = EXIT_OOM_ADJUST;
×
4950
                        return log_error_errno(r, "Failed to adjust OOM setting: %m");
×
4951
                }
4952
        }
4953

4954
        if (context->coredump_filter_set) {
11,515✔
4955
                r = set_coredump_filter(context->coredump_filter);
2✔
4956
                if (ERRNO_IS_NEG_PRIVILEGE(r))
2✔
4957
                        log_debug_errno(r, "Failed to adjust coredump_filter, ignoring: %m");
×
4958
                else if (r < 0) {
2✔
4959
                        *exit_status = EXIT_LIMITS;
×
4960
                        return log_error_errno(r, "Failed to adjust coredump_filter: %m");
×
4961
                }
4962
        }
4963

4964
        if (context->cpu_sched_set) {
11,515✔
4965
                struct sched_attr attr = {
×
4966
                        .size = sizeof(attr),
4967
                        .sched_policy = context->cpu_sched_policy,
×
4968
                        .sched_priority = context->cpu_sched_priority,
×
4969
                        .sched_flags = context->cpu_sched_reset_on_fork ? SCHED_FLAG_RESET_ON_FORK : 0,
×
4970
                };
4971

4972
                r = sched_setattr(/* pid= */ 0, &attr, /* flags= */ 0);
×
4973
                if (r < 0) {
×
4974
                        *exit_status = EXIT_SETSCHEDULER;
×
4975
                        return log_error_errno(errno, "Failed to set up CPU scheduling: %m");
×
4976
                }
4977
        }
4978

4979
        /*
4980
         * Set nice value _after_ the call to sched_setattr() because struct sched_attr includes sched_nice
4981
         * which we do not set, thus it will clobber any previously set nice value. Scheduling policy might
4982
         * be reasonably set together with nice value e.g. in case of SCHED_BATCH (see sched(7)).
4983
         * It would be ideal to set both with the same call, but we cannot easily do so because of all the
4984
         * extra logic in setpriority_closest().
4985
         */
4986
        if (context->nice_set) {
11,515✔
4987
                r = setpriority_closest(context->nice);
15✔
4988
                if (r < 0) {
15✔
4989
                        *exit_status = EXIT_NICE;
×
4990
                        return log_error_errno(r, "Failed to set up process scheduling priority (nice level): %m");
×
4991
                }
4992
        }
4993

4994
        if (context->cpu_affinity_from_numa || context->cpu_set.set) {
11,515✔
4995
                _cleanup_(cpu_set_reset) CPUSet converted_cpu_set = {};
2✔
4996
                const CPUSet *cpu_set;
2✔
4997

4998
                if (context->cpu_affinity_from_numa) {
2✔
4999
                        r = exec_context_cpu_affinity_from_numa(context, &converted_cpu_set);
2✔
5000
                        if (r < 0) {
2✔
5001
                                *exit_status = EXIT_CPUAFFINITY;
×
5002
                                return log_error_errno(r, "Failed to derive CPU affinity mask from NUMA mask: %m");
×
5003
                        }
5004

5005
                        cpu_set = &converted_cpu_set;
5006
                } else
5007
                        cpu_set = &context->cpu_set;
×
5008

5009
                if (sched_setaffinity(0, cpu_set->allocated, cpu_set->set) < 0) {
2✔
5010
                        *exit_status = EXIT_CPUAFFINITY;
×
5011
                        return log_error_errno(errno, "Failed to set up CPU affinity: %m");
×
5012
                }
5013
        }
5014

5015
        if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) {
11,515✔
5016
                r = apply_numa_policy(&context->numa_policy);
19✔
5017
                if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
19✔
5018
                        log_debug_errno(r, "NUMA support not available, ignoring.");
×
5019
                else if (r < 0) {
19✔
5020
                        *exit_status = EXIT_NUMA_POLICY;
2✔
5021
                        return log_error_errno(r, "Failed to set NUMA memory policy: %m");
2✔
5022
                }
5023
        }
5024

5025
        if (context->ioprio_set)
11,513✔
5026
                if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
7✔
5027
                        *exit_status = EXIT_IOPRIO;
×
5028
                        return log_error_errno(errno, "Failed to set up IO scheduling priority: %m");
×
5029
                }
5030

5031
        if (context->timer_slack_nsec != NSEC_INFINITY)
11,513✔
5032
                if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
×
5033
                        *exit_status = EXIT_TIMERSLACK;
×
5034
                        return log_error_errno(errno, "Failed to set up timer slack: %m");
×
5035
                }
5036

5037
        if (context->personality != PERSONALITY_INVALID) {
11,513✔
5038
                r = safe_personality(context->personality);
×
5039
                if (r < 0) {
×
5040
                        *exit_status = EXIT_PERSONALITY;
×
5041
                        return log_error_errno(r, "Failed to set up execution domain (personality): %m");
×
5042
                }
5043
        }
5044

5045
        if (context->memory_ksm >= 0)
11,513✔
5046
                if (prctl(PR_SET_MEMORY_MERGE, context->memory_ksm, 0, 0, 0) < 0) {
×
5047
                        if (ERRNO_IS_NOT_SUPPORTED(errno))
×
5048
                                log_debug_errno(errno, "KSM support not available, ignoring.");
×
5049
                        else {
5050
                                *exit_status = EXIT_KSM;
×
5051
                                return log_error_errno(errno, "Failed to set KSM: %m");
×
5052
                        }
5053
                }
5054

5055
#if ENABLE_UTMP
5056
        if (context->utmp_id) {
11,513✔
5057
                _cleanup_free_ char *username_alloc = NULL;
158✔
5058

5059
                if (!username && context->utmp_mode == EXEC_UTMP_USER) {
158✔
5060
                        username_alloc = uid_to_name(uid_is_valid(uid) ? uid : saved_uid);
1✔
5061
                        if (!username_alloc) {
1✔
5062
                                *exit_status = EXIT_USER;
×
5063
                                return log_oom();
×
5064
                        }
5065
                }
5066

5067
                const char *line = context->tty_path ?
×
5068
                        (path_startswith(context->tty_path, "/dev/") ?: context->tty_path) :
158✔
5069
                        NULL;
5070
                utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
158✔
5071
                                      line,
5072
                                      context->utmp_mode == EXEC_UTMP_INIT  ? INIT_PROCESS :
158✔
5073
                                      context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
7✔
5074
                                      USER_PROCESS,
5075
                                      username ?: username_alloc);
158✔
5076
        }
5077
#endif
5078

5079
        if (uid_is_valid(uid)) {
11,513✔
5080
                r = chown_terminal(STDIN_FILENO, uid);
2,641✔
5081
                if (r < 0) {
2,641✔
5082
                        *exit_status = EXIT_STDIN;
×
5083
                        return log_error_errno(r, "Failed to change ownership of terminal: %m");
×
5084
                }
5085
        }
5086

5087
        /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted
5088
         * from it. */
5089
        needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
11,513✔
5090

5091
        if (params->cgroup_path) {
11,513✔
5092
                /* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1
5093
                 * this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not
5094
                 * safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only
5095
                 * touch a single hierarchy too. */
5096

5097
                if (params->flags & EXEC_CGROUP_DELEGATE) {
11,513✔
5098
                        _cleanup_free_ char *p = NULL;
666✔
5099

5100
                        r = cg_set_access(params->cgroup_path, uid, gid);
666✔
5101
                        if (r < 0) {
666✔
5102
                                *exit_status = EXIT_CGROUP;
×
5103
                                return log_error_errno(r, "Failed to adjust control group access: %m");
×
5104
                        }
5105

5106
                        r = exec_params_get_cgroup_path(params, cgroup_context, &p);
666✔
5107
                        if (r < 0) {
666✔
5108
                                *exit_status = EXIT_CGROUP;
×
5109
                                return log_error_errno(r, "Failed to acquire cgroup path: %m");
×
5110
                        }
5111
                        if (r > 0) {
666✔
5112
                                r = cg_set_access_recursive(p, uid, gid);
325✔
5113
                                if (r < 0) {
325✔
5114
                                        *exit_status = EXIT_CGROUP;
×
5115
                                        return log_error_errno(r, "Failed to adjust control subgroup access: %m");
×
5116
                                }
5117
                        }
5118
                }
5119

5120
                if (is_pressure_supported() > 0) {
11,513✔
5121
                        if (cgroup_context_want_memory_pressure(cgroup_context)) {
11,513✔
5122
                                r = cg_get_path("memory", params->cgroup_path, "memory.pressure", &memory_pressure_path);
11,115✔
5123
                                if (r < 0) {
11,115✔
5124
                                        *exit_status = EXIT_MEMORY;
×
5125
                                        return log_oom();
×
5126
                                }
5127

5128
                                r = chmod_and_chown(memory_pressure_path, 0644, uid, gid);
11,115✔
5129
                                if (r < 0) {
11,115✔
5130
                                        log_full_errno(r == -ENOENT || ERRNO_IS_PRIVILEGE(r) ? LOG_DEBUG : LOG_WARNING, r,
2✔
5131
                                                       "Failed to adjust ownership of '%s', ignoring: %m", memory_pressure_path);
5132
                                        memory_pressure_path = mfree(memory_pressure_path);
1✔
5133
                                }
5134
                                /* First we use the current cgroup path to chmod and chown the memory pressure path, then pass the path relative
5135
                                 * to the cgroup namespace to environment variables and mounts. If chown/chmod fails, we should not pass memory
5136
                                 * pressure path environment variable or read-write mount to the unit. This is why we check if
5137
                                 * memory_pressure_path != NULL in the conditional below. */
5138
                                if (memory_pressure_path && needs_sandboxing && exec_needs_cgroup_namespace(context)) {
11,115✔
5139
                                        memory_pressure_path = mfree(memory_pressure_path);
11✔
5140
                                        r = cg_get_path("memory", "", "memory.pressure", &memory_pressure_path);
11✔
5141
                                        if (r < 0) {
11✔
5142
                                                *exit_status = EXIT_MEMORY;
×
5143
                                                return log_oom();
×
5144
                                        }
5145
                                }
5146
                        } else if (cgroup_context->memory_pressure_watch == CGROUP_PRESSURE_WATCH_NO) {
398✔
5147
                                memory_pressure_path = strdup("/dev/null"); /* /dev/null is explicit indicator for turning of memory pressure watch */
×
5148
                                if (!memory_pressure_path) {
×
5149
                                        *exit_status = EXIT_MEMORY;
×
5150
                                        return log_oom();
×
5151
                                }
5152
                        }
5153
                }
5154
        }
5155

5156
        needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
11,513✔
5157

5158
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
69,073✔
5159
                r = setup_exec_directory(context, params, uid, gid, dt, needs_mount_namespace, exit_status);
57,561✔
5160
                if (r < 0)
57,561✔
5161
                        return log_error_errno(r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
1✔
5162
        }
5163

5164
        r = exec_setup_credentials(context, params, params->unit_id, uid, gid);
11,512✔
5165
        if (r < 0) {
9,566✔
5166
                *exit_status = EXIT_CREDENTIALS;
×
5167
                return log_error_errno(r, "Failed to set up credentials: %m");
×
5168
        }
5169

5170
        r = build_environment(
9,566✔
5171
                        context,
5172
                        params,
5173
                        cgroup_context,
5174
                        n_fds,
5175
                        pwent_home,
5176
                        username,
5177
                        shell,
5178
                        journal_stream_dev,
5179
                        journal_stream_ino,
5180
                        memory_pressure_path,
5181
                        needs_sandboxing,
5182
                        &our_env);
5183
        if (r < 0) {
9,566✔
5184
                *exit_status = EXIT_MEMORY;
×
5185
                return log_oom();
×
5186
        }
5187

5188
        r = build_pass_environment(context, &pass_env);
9,566✔
5189
        if (r < 0) {
9,566✔
5190
                *exit_status = EXIT_MEMORY;
×
5191
                return log_oom();
×
5192
        }
5193

5194
        /* The $PATH variable is set to the default path in params->environment. However, this is overridden
5195
         * if user-specified fields have $PATH set. The intention is to also override $PATH if the unit does
5196
         * not specify PATH but the unit has ExecSearchPath. */
5197
        if (!strv_isempty(context->exec_search_path)) {
9,566✔
5198
                _cleanup_free_ char *joined = NULL;
×
5199

5200
                joined = strv_join(context->exec_search_path, ":");
×
5201
                if (!joined) {
×
5202
                        *exit_status = EXIT_MEMORY;
×
5203
                        return log_oom();
×
5204
                }
5205

5206
                r = strv_env_assign(&joined_exec_search_path, "PATH", joined);
×
5207
                if (r < 0) {
×
5208
                        *exit_status = EXIT_MEMORY;
×
5209
                        return log_oom();
×
5210
                }
5211
        }
5212

5213
        accum_env = strv_env_merge(params->environment,
9,566✔
5214
                                   our_env,
5215
                                   joined_exec_search_path,
5216
                                   pass_env,
5217
                                   context->environment,
5218
                                   params->files_env);
5219
        if (!accum_env) {
9,566✔
5220
                *exit_status = EXIT_MEMORY;
×
5221
                return log_oom();
×
5222
        }
5223
        accum_env = strv_env_clean(accum_env);
9,566✔
5224

5225
        (void) umask(context->umask);
9,566✔
5226

5227
        r = setup_keyring(context, params, uid, gid);
9,566✔
5228
        if (r < 0) {
9,566✔
5229
                *exit_status = EXIT_KEYRING;
×
5230
                return log_error_errno(r, "Failed to set up kernel keyring: %m");
×
5231
        }
5232

5233
        /* We need setresuid() if the caller asked us to apply sandboxing and the command isn't explicitly
5234
         * excepted from either whole sandboxing or just setresuid() itself. */
5235
        needs_setuid = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & (EXEC_COMMAND_FULLY_PRIVILEGED|EXEC_COMMAND_NO_SETUID));
9,566✔
5236

5237
        uint64_t capability_ambient_set = context->capability_ambient_set;
9,566✔
5238

5239
        /* Check CAP_SYS_ADMIN before we enter user namespace to see if we can mount /proc even though its masked. */
5240
        have_cap_sys_admin = have_effective_cap(CAP_SYS_ADMIN) > 0;
9,566✔
5241

5242
        if (needs_sandboxing) {
9,566✔
5243
                /* MAC enablement checks need to be done before a new mount ns is created, as they rely on
5244
                 * /sys being present. The actual MAC context application will happen later, as late as
5245
                 * possible, to avoid impacting our own code paths. */
5246

5247
#if HAVE_SELINUX
5248
                use_selinux = mac_selinux_use();
5249
#endif
5250
#if ENABLE_SMACK
5251
                use_smack = mac_smack_use();
9,566✔
5252
#endif
5253
#if HAVE_APPARMOR
5254
                if (mac_apparmor_use()) {
5255
                        r = dlopen_libapparmor();
5256
                        if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r))
5257
                                log_warning_errno(r, "Failed to load libapparmor, ignoring: %m");
5258
                        use_apparmor = r >= 0;
5259
                }
5260
#endif
5261
        }
5262

5263
        if (needs_sandboxing) {
9,566✔
5264
                int which_failed;
9,566✔
5265

5266
                /* Let's set the resource limits before we call into PAM, so that pam_limits wins over what
5267
                 * is set here. (See below.) */
5268

5269
                r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed);
9,566✔
5270
                if (r < 0) {
9,566✔
5271
                        *exit_status = EXIT_LIMITS;
×
5272
                        return log_error_errno(r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
×
5273
                }
5274
        }
5275

5276
        if (needs_setuid && context->pam_name && username) {
9,566✔
5277
                /* Let's call into PAM after we set up our own idea of resource limits so that pam_limits
5278
                 * wins here. (See above.) */
5279

5280
                /* All fds passed in the fds array will be closed in the pam child process. */
5281
                r = setup_pam(context, params, username, uid, gid, &accum_env, params->fds, n_fds, params->exec_fd);
388✔
5282
                if (r < 0) {
388✔
5283
                        *exit_status = EXIT_PAM;
×
5284
                        return log_error_errno(r, "Failed to set up PAM session: %m");
×
5285
                }
5286

5287
                /* PAM modules might have set some ambient caps. Query them here and merge them into
5288
                 * the caps we want to set in the end, so that we don't end up unsetting them. */
5289
                uint64_t ambient_after_pam;
388✔
5290
                r = capability_get_ambient(&ambient_after_pam);
388✔
5291
                if (r < 0) {
388✔
5292
                        *exit_status = EXIT_CAPABILITIES;
×
5293
                        return log_error_errno(r, "Failed to query ambient caps: %m");
×
5294
                }
5295

5296
                capability_ambient_set |= ambient_after_pam;
388✔
5297

5298
                ngids_after_pam = getgroups_alloc(&gids_after_pam);
388✔
5299
                if (ngids_after_pam < 0) {
388✔
5300
                        *exit_status = EXIT_GROUP;
×
5301
                        return log_error_errno(ngids_after_pam, "Failed to obtain groups after setting up PAM: %m");
×
5302
                }
5303
        }
5304

5305
        if (needs_sandboxing && !have_cap_sys_admin && exec_context_needs_cap_sys_admin(context)) {
9,566✔
5306
                /* If we're unprivileged, set up the user namespace first to enable use of the other namespaces.
5307
                 * Users with CAP_SYS_ADMIN can set up user namespaces last because they will be able to
5308
                 * set up all of the other namespaces (i.e. network, mount, UTS) without a user namespace. */
5309
                PrivateUsers pu = exec_context_get_effective_private_users(context, params);
27✔
5310
                if (pu == PRIVATE_USERS_NO)
27✔
5311
                        pu = PRIVATE_USERS_SELF;
23✔
5312

5313
                /* The kernel requires /proc/pid/setgroups be set to "deny" prior to writing /proc/pid/gid_map in
5314
                 * unprivileged user namespaces. */
5315
                r = setup_private_users(pu, saved_uid, saved_gid, uid, gid, /* allow_setgroups= */ false);
27✔
5316
                /* If it was requested explicitly and we can't set it up, fail early. Otherwise, continue and let
5317
                 * the actual requested operations fail (or silently continue). */
5318
                if (r < 0 && context->private_users != PRIVATE_USERS_NO) {
27✔
5319
                        *exit_status = EXIT_USER;
×
5320
                        return log_error_errno(r, "Failed to set up user namespacing for unprivileged user: %m");
×
5321
                }
5322
                if (r < 0)
×
5323
                        log_info_errno(r, "Failed to set up user namespacing for unprivileged user, ignoring: %m");
×
5324
                else {
5325
                        assert(r > 0);
27✔
5326
                        userns_set_up = true;
27✔
5327
                        log_debug("Set up unprivileged user namespace");
27✔
5328
                }
5329
        }
5330

5331
        /* Call setup_delegated_namespaces() the first time to unshare all non-delegated namespaces. */
5332
        r = setup_delegated_namespaces(
9,566✔
5333
                        context,
5334
                        params,
5335
                        runtime,
5336
                        /* delegate= */ false,
5337
                        memory_pressure_path,
5338
                        uid,
5339
                        gid,
5340
                        command,
5341
                        needs_sandboxing,
5342
                        have_cap_sys_admin,
5343
                        exit_status);
5344
        if (r < 0)
9,562✔
5345
                return r;
5346

5347
        /* Drop groups as early as possible.
5348
         * This needs to be done after PrivateDevices=yes setup as device nodes should be owned by the host's root.
5349
         * For non-root in a userns, devices will be owned by the user/group before the group change, and nobody. */
5350
        if (needs_setuid) {
9,546✔
5351
                _cleanup_free_ gid_t *gids_to_enforce = NULL;
9,546✔
5352
                int ngids_to_enforce;
9,546✔
5353

5354
                ngids_to_enforce = merge_gid_lists(gids,
9,546✔
5355
                                                   ngids,
5356
                                                   gids_after_pam,
5357
                                                   ngids_after_pam,
5358
                                                   &gids_to_enforce);
5359
                if (ngids_to_enforce < 0) {
9,546✔
5360
                        *exit_status = EXIT_GROUP;
×
5361
                        return log_error_errno(ngids_to_enforce, "Failed to merge group lists. Group membership might be incorrect: %m");
×
5362
                }
5363

5364
                r = enforce_groups(gid, gids_to_enforce, ngids_to_enforce);
9,546✔
5365
                if (r < 0) {
9,546✔
5366
                        *exit_status = EXIT_GROUP;
1✔
5367
                        return log_error_errno(r, "Changing group credentials failed: %m");
1✔
5368
                }
5369
        }
5370

5371
        /* If the user namespace was not set up above, try to do it now.
5372
         * It's preferred to set up the user namespace later (after all other namespaces) so as not to be
5373
         * restricted by rules pertaining to combining user namespaces with other namespaces (e.g. in the
5374
         * case of mount namespaces being less privileged when the mount point list is copied from a
5375
         * different user namespace). */
5376

5377
        if (needs_sandboxing && !userns_set_up) {
9,545✔
5378
                PrivateUsers pu = exec_context_get_effective_private_users(context, params);
9,523✔
5379

5380
                r = setup_private_users(pu, saved_uid, saved_gid, uid, gid,
9,523✔
5381
                                        /* allow_setgroups= */ pu == PRIVATE_USERS_FULL);
5382
                if (r < 0) {
9,523✔
5383
                        *exit_status = EXIT_USER;
×
5384
                        return log_error_errno(r, "Failed to set up user namespacing: %m");
×
5385
                }
5386
                if (r > 0)
9,523✔
5387
                        log_debug("Set up privileged user namespace");
23✔
5388
        }
5389

5390
        /* Call setup_delegated_namespaces() the second time to unshare all delegated namespaces. */
5391
        r = setup_delegated_namespaces(
9,545✔
5392
                        context,
5393
                        params,
5394
                        runtime,
5395
                        /* delegate= */ true,
5396
                        memory_pressure_path,
5397
                        uid,
5398
                        gid,
5399
                        command,
5400
                        needs_sandboxing,
5401
                        have_cap_sys_admin,
5402
                        exit_status);
5403
        if (r < 0)
9,543✔
5404
                return r;
5405

5406
        /* Now that the mount namespace has been set up and privileges adjusted, let's look for the thing we
5407
         * shall execute. */
5408

5409
        _cleanup_free_ char *executable = NULL;
5✔
5410
        _cleanup_close_ int executable_fd = -EBADF;
5✔
5411
        r = find_executable_full(command->path, /* root= */ NULL, context->exec_search_path, false, &executable, &executable_fd);
9,543✔
5412
        if (r < 0) {
9,543✔
5413
                *exit_status = EXIT_EXEC;
1✔
5414
                log_struct_errno(LOG_NOTICE, r,
1✔
5415
                                 LOG_MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED_STR),
5416
                                 LOG_EXEC_MESSAGE(params,
5417
                                                  "Unable to locate executable '%s': %m",
5418
                                                  command->path),
5419
                                 LOG_ITEM("EXECUTABLE=%s", command->path));
5420
                /* If the error will be ignored by manager, tune down the log level here. Missing executable
5421
                 * is very much expected in this case. */
5422
                return r != -ENOMEM && FLAGS_SET(command->flags, EXEC_COMMAND_IGNORE_FAILURE) ? 1 : r;
1✔
5423
        }
5424

5425
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &executable_fd);
9,542✔
5426
        if (r < 0) {
9,542✔
5427
                *exit_status = EXIT_FDS;
×
5428
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
5429
        }
5430

5431
#if HAVE_SELINUX
5432
        if (needs_sandboxing && use_selinux && params->selinux_context_net) {
5433
                int fd = -EBADF;
5434

5435
                if (socket_fd >= 0)
5436
                        fd = socket_fd;
5437
                else if (params->n_socket_fds == 1)
5438
                        /* If stdin is not connected to a socket but we are triggered by exactly one socket unit then we
5439
                         * use context from that fd to compute the label. */
5440
                        fd = params->fds[0];
5441

5442
                if (fd >= 0) {
5443
                        r = mac_selinux_get_child_mls_label(fd, executable, context->selinux_context, &mac_selinux_context_net);
5444
                        if (r < 0) {
5445
                                if (!context->selinux_context_ignore) {
5446
                                        *exit_status = EXIT_SELINUX_CONTEXT;
5447
                                        return log_error_errno(r, "Failed to determine SELinux context: %m");
5448
                                }
5449
                                log_debug_errno(r, "Failed to determine SELinux context, ignoring: %m");
5450
                        }
5451
                }
5452
        }
5453
#endif
5454

5455
        /* We repeat the fd closing here, to make sure that nothing is leaked from the PAM modules. Note that
5456
         * we are more aggressive this time, since we don't need socket_fd and the netns and ipcns fds any
5457
         * more. We do keep exec_fd and handoff_timestamp_fd however, if we have it, since we need to keep
5458
         * them open until the final execve(). But first, close the remaining sockets in the context
5459
         * objects. */
5460

5461
        exec_runtime_close(runtime);
9,542✔
5462
        exec_params_close(params);
9,542✔
5463

5464
        r = close_all_fds(keep_fds, n_keep_fds);
9,542✔
5465
        if (r >= 0)
9,542✔
5466
                r = pack_fds(params->fds, n_fds);
9,542✔
5467
        if (r >= 0)
9,542✔
5468
                r = flag_fds(params->fds, n_socket_fds, n_fds, context->non_blocking);
9,542✔
5469
        if (r < 0) {
9,542✔
5470
                *exit_status = EXIT_FDS;
×
5471
                return log_error_errno(r, "Failed to adjust passed file descriptors: %m");
×
5472
        }
5473

5474
        /* At this point, the fds we want to pass to the program are all ready and set up, with O_CLOEXEC turned off
5475
         * and at the right fd numbers. The are no other fds open, with one exception: the exec_fd if it is defined,
5476
         * and it has O_CLOEXEC set, after all we want it to be closed by the execve(), so that our parent knows we
5477
         * came this far. */
5478

5479
        secure_bits = context->secure_bits;
9,542✔
5480

5481
        if (needs_sandboxing) {
9,542✔
5482
                uint64_t bset;
9,542✔
5483

5484
                /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested.
5485
                 * (Note this is placed after the general resource limit initialization, see above, in order
5486
                 * to take precedence.) */
5487
                if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
9,542✔
5488
                        if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
1,490✔
5489
                                *exit_status = EXIT_LIMITS;
×
5490
                                return log_error_errno(errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m");
×
5491
                        }
5492
                }
5493

5494
#if ENABLE_SMACK
5495
                /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the
5496
                 * process. This is the latest place before dropping capabilities. Other MAC context are set later. */
5497
                if (use_smack) {
9,542✔
5498
                        r = setup_smack(context, params, executable_fd);
×
5499
                        if (r < 0 && !context->smack_process_label_ignore) {
×
5500
                                *exit_status = EXIT_SMACK_PROCESS_LABEL;
×
5501
                                return log_error_errno(r, "Failed to set SMACK process label: %m");
×
5502
                        }
5503
                }
5504
#endif
5505

5506
                bset = context->capability_bounding_set;
9,542✔
5507

5508
#if HAVE_SECCOMP
5509
                /* If the service has any form of a seccomp filter and it allows dropping privileges, we'll
5510
                 * keep the needed privileges to apply it even if we're not root. */
5511
                if (needs_setuid &&
19,084✔
5512
                    uid_is_valid(uid) &&
11,533✔
5513
                    context_has_seccomp(context) &&
2,739✔
5514
                    seccomp_allows_drop_privileges(context)) {
748✔
5515
                        keep_seccomp_privileges = true;
748✔
5516

5517
                        if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
748✔
5518
                                *exit_status = EXIT_USER;
×
5519
                                return log_error_errno(errno, "Failed to enable keep capabilities flag: %m");
×
5520
                        }
5521

5522
                        /* Save the current bounding set so we can restore it after applying the seccomp
5523
                         * filter */
5524
                        saved_bset = bset;
748✔
5525
                        bset |= (UINT64_C(1) << CAP_SYS_ADMIN) |
748✔
5526
                                (UINT64_C(1) << CAP_SETPCAP);
5527
                }
5528
#endif
5529

5530
                if (!cap_test_all(bset)) {
9,542✔
5531
                        r = capability_bounding_set_drop(bset, /* right_now= */ false);
1,616✔
5532
                        if (r < 0) {
1,616✔
5533
                                *exit_status = EXIT_CAPABILITIES;
×
5534
                                return log_error_errno(r, "Failed to drop capabilities: %m");
×
5535
                        }
5536
                }
5537

5538
                /* Ambient capabilities are cleared during setresuid() (in enforce_user()) even with
5539
                 * keep-caps set.
5540
                 *
5541
                 * To be able to raise the ambient capabilities after setresuid() they have to be added to
5542
                 * the inherited set and keep caps has to be set (done in enforce_user()).  After setresuid()
5543
                 * the ambient capabilities can be raised as they are present in the permitted and
5544
                 * inhertiable set. However it is possible that someone wants to set ambient capabilities
5545
                 * without changing the user, so we also set the ambient capabilities here.
5546
                 *
5547
                 * The requested ambient capabilities are raised in the inheritable set if the second
5548
                 * argument is true. */
5549
                if (capability_ambient_set != 0) {
9,542✔
5550
                        r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ true);
743✔
5551
                        if (r < 0) {
743✔
5552
                                *exit_status = EXIT_CAPABILITIES;
×
5553
                                return log_error_errno(r, "Failed to apply ambient capabilities (before UID change): %m");
×
5554
                        }
5555
                }
5556
        }
5557

5558
        /* chroot to root directory first, before we lose the ability to chroot */
5559
        r = apply_root_directory(context, params, runtime, needs_mount_namespace, exit_status);
9,542✔
5560
        if (r < 0)
9,542✔
5561
                return log_error_errno(r, "Chrooting to the requested root directory failed: %m");
×
5562

5563
        if (needs_setuid) {
9,542✔
5564
                if (uid_is_valid(uid)) {
9,542✔
5565
                        r = enforce_user(context, uid, capability_ambient_set);
1,991✔
5566
                        if (r < 0) {
1,991✔
5567
                                *exit_status = EXIT_USER;
×
5568
                                return log_error_errno(r, "Failed to change UID to " UID_FMT ": %m", uid);
×
5569
                        }
5570

5571
                        if (keep_seccomp_privileges) {
1,991✔
5572
                                if (!BIT_SET(capability_ambient_set, CAP_SETUID)) {
748✔
5573
                                        r = drop_capability(CAP_SETUID);
748✔
5574
                                        if (r < 0) {
748✔
5575
                                                *exit_status = EXIT_USER;
×
5576
                                                return log_error_errno(r, "Failed to drop CAP_SETUID: %m");
×
5577
                                        }
5578
                                }
5579

5580
                                r = keep_capability(CAP_SYS_ADMIN);
748✔
5581
                                if (r < 0) {
748✔
5582
                                        *exit_status = EXIT_USER;
×
5583
                                        return log_error_errno(r, "Failed to keep CAP_SYS_ADMIN: %m");
×
5584
                                }
5585

5586
                                r = keep_capability(CAP_SETPCAP);
748✔
5587
                                if (r < 0) {
748✔
5588
                                        *exit_status = EXIT_USER;
×
5589
                                        return log_error_errno(r, "Failed to keep CAP_SETPCAP: %m");
×
5590
                                }
5591
                        }
5592

5593
                        if (capability_ambient_set != 0) {
1,991✔
5594

5595
                                /* Raise the ambient capabilities after user change. */
5596
                                r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ false);
740✔
5597
                                if (r < 0) {
740✔
5598
                                        *exit_status = EXIT_CAPABILITIES;
×
5599
                                        return log_error_errno(r, "Failed to apply ambient capabilities (after UID change): %m");
×
5600
                                }
5601
                        }
5602
                }
5603
        }
5604

5605
        /* Apply working directory here, because the working directory might be on NFS and only the user
5606
         * running this service might have the correct privilege to change to the working directory. Also, it
5607
         * is absolutely 💣 crucial 💣 we applied all mount namespacing rearrangements before this, so that
5608
         * the cwd cannot be used to pin directories outside of the sandbox. */
5609
        r = apply_working_directory(context, params, runtime, pwent_home, accum_env);
9,542✔
5610
        if (r < 0) {
9,542✔
5611
                *exit_status = EXIT_CHDIR;
1✔
5612
                return log_error_errno(r, "Changing to the requested working directory failed: %m");
1✔
5613
        }
5614

5615
        if (needs_sandboxing) {
9,541✔
5616
                /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to
5617
                 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
5618
                 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
5619
                 * are restricted. */
5620

5621
#if HAVE_SELINUX
5622
                if (use_selinux) {
5623
                        char *exec_context = mac_selinux_context_net ?: context->selinux_context;
5624

5625
                        if (exec_context) {
5626
                                r = setexeccon(exec_context);
5627
                                if (r < 0) {
5628
                                        if (!context->selinux_context_ignore) {
5629
                                                *exit_status = EXIT_SELINUX_CONTEXT;
5630
                                                return log_error_errno(r, "Failed to change SELinux context to %s: %m", exec_context);
5631
                                        }
5632
                                        log_debug_errno(r, "Failed to change SELinux context to %s, ignoring: %m", exec_context);
5633
                                }
5634
                        }
5635
                }
5636
#endif
5637

5638
#if HAVE_APPARMOR
5639
                if (use_apparmor && context->apparmor_profile) {
5640
                        r = ASSERT_PTR(sym_aa_change_onexec)(context->apparmor_profile);
5641
                        if (r < 0 && !context->apparmor_profile_ignore) {
5642
                                *exit_status = EXIT_APPARMOR_PROFILE;
5643
                                return log_error_errno(errno, "Failed to prepare AppArmor profile change to %s: %m",
5644
                                                       context->apparmor_profile);
5645
                        }
5646
                }
5647
#endif
5648

5649
                /* PR_GET_SECUREBITS is not privileged, while PR_SET_SECUREBITS is. So to suppress potential
5650
                 * EPERMs we'll try not to call PR_SET_SECUREBITS unless necessary. Setting securebits
5651
                 * requires CAP_SETPCAP. */
5652
                if (prctl(PR_GET_SECUREBITS) != secure_bits) {
9,541✔
5653
                        /* CAP_SETPCAP is required to set securebits. This capability is raised into the
5654
                         * effective set here.
5655
                         *
5656
                         * The effective set is overwritten during execve() with the following values:
5657
                         *
5658
                         * - ambient set (for non-root processes)
5659
                         *
5660
                         * - (inheritable | bounding) set for root processes)
5661
                         *
5662
                         * Hence there is no security impact to raise it in the effective set before execve
5663
                         */
5664
                        r = capability_gain_cap_setpcap(/* ret_before_caps = */ NULL);
800✔
5665
                        if (r < 0) {
800✔
5666
                                *exit_status = EXIT_CAPABILITIES;
×
5667
                                return log_error_errno(r, "Failed to gain CAP_SETPCAP for setting secure bits");
×
5668
                        }
5669
                        if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
800✔
5670
                                *exit_status = EXIT_SECUREBITS;
×
5671
                                return log_error_errno(errno, "Failed to set process secure bits: %m");
×
5672
                        }
5673
                }
5674

5675
                if (context_has_no_new_privileges(context))
9,541✔
5676
                        if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
1,414✔
5677
                                *exit_status = EXIT_NO_NEW_PRIVILEGES;
×
5678
                                return log_error_errno(errno, "Failed to disable new privileges: %m");
×
5679
                        }
5680

5681
#if HAVE_SECCOMP
5682
                r = apply_address_families(context, params);
9,541✔
5683
                if (r < 0) {
9,541✔
5684
                        *exit_status = EXIT_ADDRESS_FAMILIES;
×
5685
                        return log_error_errno(r, "Failed to restrict address families: %m");
×
5686
                }
5687

5688
                r = apply_memory_deny_write_execute(context, params);
9,541✔
5689
                if (r < 0) {
9,541✔
5690
                        *exit_status = EXIT_SECCOMP;
×
5691
                        return log_error_errno(r, "Failed to disable writing to executable memory: %m");
×
5692
                }
5693

5694
                r = apply_restrict_realtime(context, params);
9,541✔
5695
                if (r < 0) {
9,541✔
5696
                        *exit_status = EXIT_SECCOMP;
×
5697
                        return log_error_errno(r, "Failed to apply realtime restrictions: %m");
×
5698
                }
5699

5700
                r = apply_restrict_suid_sgid(context, params);
9,541✔
5701
                if (r < 0) {
9,541✔
5702
                        *exit_status = EXIT_SECCOMP;
×
5703
                        return log_error_errno(r, "Failed to apply SUID/SGID restrictions: %m");
×
5704
                }
5705

5706
                r = apply_restrict_namespaces(context, params);
9,541✔
5707
                if (r < 0) {
9,541✔
5708
                        *exit_status = EXIT_SECCOMP;
×
5709
                        return log_error_errno(r, "Failed to apply namespace restrictions: %m");
×
5710
                }
5711

5712
                r = apply_protect_sysctl(context, params);
9,541✔
5713
                if (r < 0) {
9,541✔
5714
                        *exit_status = EXIT_SECCOMP;
×
5715
                        return log_error_errno(r, "Failed to apply sysctl restrictions: %m");
×
5716
                }
5717

5718
                r = apply_protect_kernel_modules(context, params);
9,541✔
5719
                if (r < 0) {
9,541✔
5720
                        *exit_status = EXIT_SECCOMP;
×
5721
                        return log_error_errno(r, "Failed to apply module loading restrictions: %m");
×
5722
                }
5723

5724
                r = apply_protect_kernel_logs(context, params);
9,541✔
5725
                if (r < 0) {
9,541✔
5726
                        *exit_status = EXIT_SECCOMP;
×
5727
                        return log_error_errno(r, "Failed to apply kernel log restrictions: %m");
×
5728
                }
5729

5730
                r = apply_protect_clock(context, params);
9,541✔
5731
                if (r < 0) {
9,541✔
5732
                        *exit_status = EXIT_SECCOMP;
×
5733
                        return log_error_errno(r, "Failed to apply clock restrictions: %m");
×
5734
                }
5735

5736
                r = apply_private_devices(context, params);
9,541✔
5737
                if (r < 0) {
9,541✔
5738
                        *exit_status = EXIT_SECCOMP;
×
5739
                        return log_error_errno(r, "Failed to set up private devices: %m");
×
5740
                }
5741

5742
                r = apply_syscall_archs(context, params);
9,541✔
5743
                if (r < 0) {
9,541✔
5744
                        *exit_status = EXIT_SECCOMP;
×
5745
                        return log_error_errno(r, "Failed to apply syscall architecture restrictions: %m");
×
5746
                }
5747

5748
                r = apply_lock_personality(context, params);
9,541✔
5749
                if (r < 0) {
9,541✔
5750
                        *exit_status = EXIT_SECCOMP;
×
5751
                        return log_error_errno(r, "Failed to lock personalities: %m");
×
5752
                }
5753

5754
                r = apply_syscall_log(context, params);
9,541✔
5755
                if (r < 0) {
9,541✔
5756
                        *exit_status = EXIT_SECCOMP;
×
5757
                        return log_error_errno(r, "Failed to apply system call log filters: %m");
×
5758
                }
5759
#endif
5760

5761
#if HAVE_LIBBPF
5762
                r = apply_restrict_filesystems(context, params);
9,541✔
5763
                if (r < 0) {
9,541✔
5764
                        *exit_status = EXIT_BPF;
×
5765
                        return log_error_errno(r, "Failed to restrict filesystems: %m");
×
5766
                }
5767
#endif
5768

5769
#if HAVE_SECCOMP
5770
                /* This really should remain as close to the execve() as possible, to make sure our own code is affected
5771
                 * by the filter as little as possible. */
5772
                r = apply_syscall_filter(context, params);
9,541✔
5773
                if (r < 0) {
9,541✔
5774
                        *exit_status = EXIT_SECCOMP;
×
5775
                        return log_error_errno(r, "Failed to apply system call filters: %m");
×
5776
                }
5777

5778
                if (keep_seccomp_privileges) {
9,541✔
5779
                        /* Restore the capability bounding set with what's expected from the service + the
5780
                         * ambient capabilities hack */
5781
                        if (!cap_test_all(saved_bset)) {
747✔
5782
                                r = capability_bounding_set_drop(saved_bset, /* right_now= */ false);
712✔
5783
                                if (r < 0) {
712✔
5784
                                        *exit_status = EXIT_CAPABILITIES;
×
5785
                                        return log_error_errno(r, "Failed to drop bset capabilities: %m");
×
5786
                                }
5787
                        }
5788

5789
                        /* Only drop CAP_SYS_ADMIN if it's not in the bounding set, otherwise we'll break
5790
                         * applications that use it. */
5791
                        if (!BIT_SET(saved_bset, CAP_SYS_ADMIN)) {
747✔
5792
                                r = drop_capability(CAP_SYS_ADMIN);
279✔
5793
                                if (r < 0) {
279✔
5794
                                        *exit_status = EXIT_USER;
×
5795
                                        return log_error_errno(r, "Failed to drop CAP_SYS_ADMIN: %m");
×
5796
                                }
5797
                        }
5798

5799
                        /* Only drop CAP_SETPCAP if it's not in the bounding set, otherwise we'll break
5800
                         * applications that use it. */
5801
                        if (!BIT_SET(saved_bset, CAP_SETPCAP)) {
747✔
5802
                                r = drop_capability(CAP_SETPCAP);
531✔
5803
                                if (r < 0) {
531✔
5804
                                        *exit_status = EXIT_USER;
×
5805
                                        return log_error_errno(r, "Failed to drop CAP_SETPCAP: %m");
×
5806
                                }
5807
                        }
5808

5809
                        if (prctl(PR_SET_KEEPCAPS, 0) < 0) {
747✔
5810
                                *exit_status = EXIT_USER;
×
5811
                                return log_error_errno(errno, "Failed to drop keep capabilities flag: %m");
×
5812
                        }
5813
                }
5814
#endif
5815

5816
        }
5817

5818
        if (!strv_isempty(context->unset_environment)) {
9,541✔
5819
                char **ee = NULL;
269✔
5820

5821
                ee = strv_env_delete(accum_env, 1, context->unset_environment);
269✔
5822
                if (!ee) {
269✔
5823
                        *exit_status = EXIT_MEMORY;
×
5824
                        return log_oom();
5✔
5825
                }
5826

5827
                strv_free_and_replace(accum_env, ee);
269✔
5828
        }
5829

5830
        if (!FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) {
9,541✔
5831
                _cleanup_strv_free_ char **unset_variables = NULL, **bad_variables = NULL;
9,381✔
5832

5833
                r = replace_env_argv(command->argv, accum_env, &replaced_argv, &unset_variables, &bad_variables);
9,381✔
5834
                if (r < 0) {
9,381✔
5835
                        *exit_status = EXIT_MEMORY;
×
5836
                        return log_error_errno(r, "Failed to replace environment variables: %m");
×
5837
                }
5838
                final_argv = replaced_argv;
9,381✔
5839

5840
                if (!strv_isempty(unset_variables)) {
9,381✔
5841
                        _cleanup_free_ char *ju = strv_join(unset_variables, ", ");
10✔
5842
                        log_warning("Referenced but unset environment variable evaluates to an empty string: %s", strna(ju));
5✔
5843
                }
5844

5845
                if (!strv_isempty(bad_variables)) {
9,381✔
5846
                        _cleanup_free_ char *jb = strv_join(bad_variables, ", ");
×
5847
                        log_warning("Invalid environment variable name evaluates to an empty string: %s", strna(jb));
×
5848
                }
5849
        } else
5850
                final_argv = command->argv;
160✔
5851

5852
        log_command_line(context, params, "Executing", executable, final_argv);
9,541✔
5853

5854
        /* We have finished with all our initializations. Let's now let the manager know that. From this
5855
         * point on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */
5856

5857
        r = exec_fd_mark_hot(context, params, /* hot= */ true, exit_status);
9,541✔
5858
        if (r < 0)
9,541✔
5859
                return r;
5860

5861
        /* As last thing before the execve(), let's send the handoff timestamp */
5862
        r = send_handoff_timestamp(context, params, exit_status);
9,541✔
5863
        if (r < 0) {
9,541✔
5864
                /* If this handoff timestamp failed, let's undo the marking as hot */
5865
                (void) exec_fd_mark_hot(context, params, /* hot= */ false, /* reterr_exit_status= */ NULL);
×
5866
                return r;
5867
        }
5868

5869
        /* NB: we leave executable_fd, exec_fd, handoff_timestamp_fd open here. This is safe, because they
5870
         * have O_CLOEXEC set, and the execve() below will thus automatically close them. In fact, for
5871
         * exec_fd this is pretty much the whole raison d'etre. */
5872

5873
        r = fexecve_or_execve(executable_fd, executable, final_argv, accum_env);
9,541✔
5874

5875
        /* The execve() failed, let's undo the marking as hot */
5876
        (void) exec_fd_mark_hot(context, params, /* hot= */ false, /* reterr_exit_status= */ NULL);
3✔
5877

5878
        *exit_status = EXIT_EXEC;
3✔
5879
        return log_error_errno(r, "Failed to execute %s: %m", executable);
3✔
5880
}
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