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

systemd / systemd / 15336122756

29 May 2025 09:26PM UTC coverage: 72.064% (+0.02%) from 72.04%
15336122756

push

github

yuwata
NEWS: fix typos

299688 of 415863 relevant lines covered (72.06%)

699722.54 hits per line

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

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

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

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

18
#include "sd-messages.h"
19

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

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

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

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

93
        int r;
9,579✔
94

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

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

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

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

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

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

117
        return 0;
118
}
119

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

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

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

140
static bool exec_context_needs_term(const ExecContext *c) {
9,605✔
141
        assert(c);
9,605✔
142

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

145
        if (is_terminal_input(c->std_input))
9,605✔
146
                return true;
147

148
        if (is_terminal_output(c->std_output))
9,433✔
149
                return true;
150

151
        if (is_terminal_output(c->std_error))
9,174✔
152
                return true;
153

154
        return !!c->tty_path;
9,173✔
155
}
156

157
static int open_null_as(int flags, int nfd) {
10,907✔
158
        int fd;
10,907✔
159

160
        assert(nfd >= 0);
10,907✔
161

162
        fd = open("/dev/null", flags|O_NOCTTY);
10,907✔
163
        if (fd < 0)
10,907✔
164
                return -errno;
×
165

166
        return move_fd(fd, nfd, false);
10,907✔
167
}
168

169
static int connect_journal_socket(
10,346✔
170
                int fd,
171
                const char *log_namespace,
172
                uid_t uid,
173
                gid_t gid) {
174

175
        uid_t olduid = UID_INVALID;
10,346✔
176
        gid_t oldgid = GID_INVALID;
10,346✔
177
        const char *j;
10,346✔
178
        int r;
10,346✔
179

180
        assert(fd >= 0);
10,346✔
181

182
        j = journal_stream_path(log_namespace);
10,358✔
183
        if (!j)
2✔
184
                return -EINVAL;
×
185

186
        if (gid_is_valid(gid)) {
10,346✔
187
                oldgid = getgid();
2,352✔
188

189
                if (setegid(gid) < 0)
2,352✔
190
                        return -errno;
×
191
        }
192

193
        if (uid_is_valid(uid)) {
10,346✔
194
                olduid = getuid();
2,349✔
195

196
                if (seteuid(uid) < 0) {
2,349✔
197
                        r = -errno;
×
198
                        goto restore_gid;
×
199
                }
200
        }
201

202
        r = connect_unix_path(fd, AT_FDCWD, j);
10,346✔
203

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

207
        if (uid_is_valid(uid))
10,346✔
208
                (void) seteuid(olduid);
2,349✔
209

210
 restore_gid:
7,997✔
211
        if (gid_is_valid(gid))
10,346✔
212
                (void) setegid(oldgid);
2,352✔
213

214
        return r;
215
}
216

217
static int connect_logger_as(
10,346✔
218
                const ExecContext *context,
219
                const ExecParameters *params,
220
                ExecOutput output,
221
                const char *ident,
222
                int nfd,
223
                uid_t uid,
224
                gid_t gid) {
225

226
        _cleanup_close_ int fd = -EBADF;
10,346✔
227
        int r;
10,346✔
228

229
        assert(context);
10,346✔
230
        assert(params);
10,346✔
231
        assert(output < _EXEC_OUTPUT_MAX);
10,346✔
232
        assert(ident);
10,346✔
233
        assert(nfd >= 0);
10,346✔
234

235
        fd = socket(AF_UNIX, SOCK_STREAM, 0);
10,346✔
236
        if (fd < 0)
10,346✔
237
                return -errno;
×
238

239
        r = connect_journal_socket(fd, context->log_namespace, uid, gid);
10,346✔
240
        if (r < 0)
10,346✔
241
                return r;
242

243
        if (shutdown(fd, SHUT_RD) < 0)
10,346✔
244
                return -errno;
×
245

246
        (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
10,346✔
247

248
        if (dprintf(fd,
19,944✔
249
                "%s\n"
250
                "%s\n"
251
                "%i\n"
252
                "%i\n"
253
                "%i\n"
254
                "%i\n"
255
                "%i\n",
256
                context->syslog_identifier ?: ident,
10,346✔
257
                params->flags & EXEC_PASS_LOG_UNIT ? params->unit_id : "",
10,346✔
258
                context->syslog_priority,
10,346✔
259
                !!context->syslog_level_prefix,
10,346✔
260
                false,
261
                is_kmsg_output(output),
10,346✔
262
                is_terminal_output(output)) < 0)
10,346✔
263
                return -errno;
×
264

265
        return move_fd(TAKE_FD(fd), nfd, false);
10,346✔
266
}
267

268
static int open_terminal_as(const char *path, int flags, int nfd) {
32✔
269
        int fd;
32✔
270

271
        assert(path);
32✔
272
        assert(nfd >= 0);
32✔
273

274
        fd = open_terminal(path, flags | O_NOCTTY);
32✔
275
        if (fd < 0)
32✔
276
                return fd;
277

278
        return move_fd(fd, nfd, false);
32✔
279
}
280

281
static int acquire_path(const char *path, int flags, mode_t mode) {
11✔
282
        _cleanup_close_ int fd = -EBADF;
11✔
283
        int r;
11✔
284

285
        assert(path);
11✔
286

287
        if (IN_SET(flags & O_ACCMODE_STRICT, O_WRONLY, O_RDWR))
11✔
288
                flags |= O_CREAT;
11✔
289

290
        fd = open(path, flags|O_NOCTTY, mode);
11✔
291
        if (fd >= 0)
11✔
292
                return TAKE_FD(fd);
11✔
293

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

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

299
        fd = socket(AF_UNIX, SOCK_STREAM, 0);
×
300
        if (fd < 0)
×
301
                return -errno;
×
302

303
        r = connect_unix_path(fd, AT_FDCWD, path);
×
304
        if (IN_SET(r, -ENOTSOCK, -EINVAL))
×
305
                /* Propagate initial error if we get ENOTSOCK or EINVAL, i.e. we have indication that this
306
                 * wasn't an AF_UNIX socket after all */
307
                return -ENXIO;
308
        if (r < 0)
×
309
                return r;
310

311
        if ((flags & O_ACCMODE_STRICT) == O_RDONLY)
×
312
                r = shutdown(fd, SHUT_WR);
×
313
        else if ((flags & O_ACCMODE_STRICT) == O_WRONLY)
×
314
                r = shutdown(fd, SHUT_RD);
×
315
        else
316
                r = 0;
317
        if (r < 0)
×
318
                return -errno;
×
319

320
        return TAKE_FD(fd);
321
}
322

323
static int fixup_input(
33,024✔
324
                const ExecContext *context,
325
                int socket_fd,
326
                bool apply_tty_stdin) {
327

328
        ExecInput std_input;
33,024✔
329

330
        assert(context);
33,024✔
331

332
        std_input = context->std_input;
33,024✔
333

334
        if (is_terminal_input(std_input) && !apply_tty_stdin)
33,024✔
335
                return EXEC_INPUT_NULL;
336

337
        if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
33,024✔
338
                return EXEC_INPUT_NULL;
339

340
        if (std_input == EXEC_INPUT_DATA && context->stdin_data_size == 0)
33,024✔
341
                return EXEC_INPUT_NULL;
×
342

343
        return std_input;
344
}
345

346
static int fixup_output(ExecOutput output, int socket_fd) {
33,024✔
347

348
        if (output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
33,024✔
349
                return EXEC_OUTPUT_INHERIT;
×
350

351
        return output;
352
}
353

354
static int setup_input(
11,554✔
355
                const ExecContext *context,
356
                const ExecParameters *params,
357
                int socket_fd,
358
                const int named_iofds[static 3]) {
359

360
        ExecInput i;
11,554✔
361
        int r;
11,554✔
362

363
        assert(context);
11,554✔
364
        assert(params);
11,554✔
365
        assert(named_iofds);
11,554✔
366

367
        if (params->stdin_fd >= 0) {
11,554✔
368
                if (dup2(params->stdin_fd, STDIN_FILENO) < 0)
546✔
369
                        return -errno;
×
370

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

375
                return STDIN_FILENO;
546✔
376
        }
377

378
        i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
11,008✔
379

380
        switch (i) {
11,008✔
381

382
        case EXEC_INPUT_NULL:
10,647✔
383
                return open_null_as(O_RDONLY, STDIN_FILENO);
10,647✔
384

385
        case EXEC_INPUT_TTY:
349✔
386
        case EXEC_INPUT_TTY_FORCE:
387
        case EXEC_INPUT_TTY_FAIL: {
388
                _cleanup_close_ int tty_fd = -EBADF;
349✔
389
                _cleanup_free_ char *resolved = NULL;
349✔
390
                const char *tty_path;
349✔
391

392
                tty_path = ASSERT_PTR(exec_context_tty_path(context));
349✔
393

394
                if (tty_is_console(tty_path)) {
349✔
395
                        r = resolve_dev_console(&resolved);
266✔
396
                        if (r < 0)
266✔
397
                                log_debug_errno(r, "Failed to resolve /dev/console, ignoring: %m");
×
398
                        else {
399
                                log_debug("Resolved /dev/console to %s", resolved);
266✔
400
                                tty_path = resolved;
266✔
401
                        }
402
                }
403

404
                tty_fd = acquire_terminal(tty_path,
698✔
405
                                          i == EXEC_INPUT_TTY_FAIL  ? ACQUIRE_TERMINAL_TRY :
349✔
406
                                          i == EXEC_INPUT_TTY_FORCE ? ACQUIRE_TERMINAL_FORCE :
407
                                                                      ACQUIRE_TERMINAL_WAIT,
408
                                          USEC_INFINITY);
409
                if (tty_fd < 0)
349✔
410
                        return tty_fd;
411

412
                r = move_fd(tty_fd, STDIN_FILENO, /* cloexec= */ false);
349✔
413
                if (r < 0)
349✔
414
                        return r;
×
415

416
                TAKE_FD(tty_fd);
417
                return r;
418
        }
419

420
        case EXEC_INPUT_SOCKET:
11✔
421
                assert(socket_fd >= 0);
11✔
422

423
                return RET_NERRNO(dup2(socket_fd, STDIN_FILENO));
11✔
424

425
        case EXEC_INPUT_NAMED_FD:
×
426
                assert(named_iofds[STDIN_FILENO] >= 0);
×
427

428
                (void) fd_nonblock(named_iofds[STDIN_FILENO], false);
×
429
                return RET_NERRNO(dup2(named_iofds[STDIN_FILENO], STDIN_FILENO));
11,554✔
430

431
        case EXEC_INPUT_DATA: {
1✔
432
                int fd;
1✔
433

434
                fd = memfd_new_and_seal("exec-input", context->stdin_data, context->stdin_data_size);
1✔
435
                if (fd < 0)
1✔
436
                        return fd;
437

438
                return move_fd(fd, STDIN_FILENO, false);
1✔
439
        }
440

441
        case EXEC_INPUT_FILE: {
×
442
                bool rw;
×
443
                int fd;
×
444

445
                assert(context->stdio_file[STDIN_FILENO]);
×
446

447
                rw = (context->std_output == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDOUT_FILENO])) ||
×
448
                        (context->std_error == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDERR_FILENO]));
×
449

450
                fd = acquire_path(context->stdio_file[STDIN_FILENO], rw ? O_RDWR : O_RDONLY, 0666 & ~context->umask);
×
451
                if (fd < 0)
×
452
                        return fd;
453

454
                return move_fd(fd, STDIN_FILENO, false);
×
455
        }
456

457
        default:
×
458
                assert_not_reached();
×
459
        }
460
}
461

462
static bool can_inherit_stderr_from_stdout(
11,008✔
463
                const ExecContext *context,
464
                ExecOutput o,
465
                ExecOutput e) {
466

467
        assert(context);
11,008✔
468

469
        /* Returns true, if given the specified STDERR and STDOUT output we can directly dup() the stdout fd to the
470
         * stderr fd */
471

472
        if (e == EXEC_OUTPUT_INHERIT)
11,008✔
473
                return true;
474
        if (e != o)
410✔
475
                return false;
476

477
        if (e == EXEC_OUTPUT_NAMED_FD)
407✔
478
                return streq_ptr(context->stdio_fdname[STDOUT_FILENO], context->stdio_fdname[STDERR_FILENO]);
×
479

480
        if (IN_SET(e, EXEC_OUTPUT_FILE, EXEC_OUTPUT_FILE_APPEND, EXEC_OUTPUT_FILE_TRUNCATE))
407✔
481
                return streq_ptr(context->stdio_file[STDOUT_FILENO], context->stdio_file[STDERR_FILENO]);
4✔
482

483
        return true;
484
}
485

486
static int setup_output(
23,108✔
487
                const ExecContext *context,
488
                const ExecParameters *params,
489
                int fileno,
490
                int socket_fd,
491
                const int named_iofds[static 3],
492
                const char *ident,
493
                uid_t uid,
494
                gid_t gid,
495
                dev_t *journal_stream_dev,
496
                ino_t *journal_stream_ino) {
497

498
        ExecOutput o;
23,108✔
499
        ExecInput i;
23,108✔
500
        int r;
23,108✔
501

502
        assert(context);
23,108✔
503
        assert(params);
23,108✔
504
        assert(ident);
23,108✔
505
        assert(journal_stream_dev);
23,108✔
506
        assert(journal_stream_ino);
23,108✔
507

508
        if (fileno == STDOUT_FILENO && params->stdout_fd >= 0) {
23,108✔
509

510
                if (dup2(params->stdout_fd, STDOUT_FILENO) < 0)
546✔
511
                        return -errno;
×
512

513
                return STDOUT_FILENO;
514
        }
515

516
        if (fileno == STDERR_FILENO && params->stderr_fd >= 0) {
22,562✔
517
                if (dup2(params->stderr_fd, STDERR_FILENO) < 0)
546✔
518
                        return -errno;
×
519

520
                return STDERR_FILENO;
521
        }
522

523
        i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
22,016✔
524
        o = fixup_output(context->std_output, socket_fd);
22,016✔
525

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

529
        if (fileno == STDERR_FILENO) {
22,016✔
530
                ExecOutput e;
11,008✔
531
                e = fixup_output(context->std_error, socket_fd);
11,008✔
532

533
                /* This expects the input and output are already set up */
534

535
                /* Don't change the stderr file descriptor if we inherit all
536
                 * the way and are not on a tty */
537
                if (e == EXEC_OUTPUT_INHERIT &&
11,008✔
538
                    o == EXEC_OUTPUT_INHERIT &&
8✔
539
                    i == EXEC_INPUT_NULL &&
×
540
                    !is_terminal_input(context->std_input) &&
×
541
                    getppid() != 1)
×
542
                        return fileno;
543

544
                /* Duplicate from stdout if possible */
545
                if (can_inherit_stderr_from_stdout(context, o, e))
11,008✔
546
                        return RET_NERRNO(dup2(STDOUT_FILENO, fileno));
11,001✔
547

548
                o = e;
549

550
        } else if (o == EXEC_OUTPUT_INHERIT) {
11,008✔
551
                /* If input got downgraded, inherit the original value */
552
                if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
8✔
553
                        return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
×
554

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

559
                /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
560
                if (getppid() != 1)
×
561
                        return fileno;
562

563
                /* We need to open /dev/null here anew, to get the right access mode. */
564
                return open_null_as(O_WRONLY, fileno);
×
565
        }
566

567
        switch (o) {
11,007✔
568

569
        case EXEC_OUTPUT_NULL:
260✔
570
                return open_null_as(O_WRONLY, fileno);
260✔
571

572
        case EXEC_OUTPUT_TTY:
381✔
573
                if (is_terminal_input(i))
381✔
574
                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));
349✔
575

576
                return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
32✔
577

578
        case EXEC_OUTPUT_KMSG:
10,346✔
579
        case EXEC_OUTPUT_KMSG_AND_CONSOLE:
580
        case EXEC_OUTPUT_JOURNAL:
581
        case EXEC_OUTPUT_JOURNAL_AND_CONSOLE:
582
                r = connect_logger_as(context, params, o, ident, fileno, uid, gid);
10,346✔
583
                if (r < 0) {
10,346✔
584
                        log_warning_errno(r, "Failed to connect %s to the journal socket, ignoring: %m",
×
585
                                          fileno == STDOUT_FILENO ? "stdout" : "stderr");
586
                        r = open_null_as(O_WRONLY, fileno);
×
587
                } else {
588
                        struct stat st;
10,346✔
589

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

597
                        if (fstat(fileno, &st) >= 0 &&
10,346✔
598
                            (*journal_stream_ino == 0 || fileno == STDERR_FILENO)) {
10,346✔
599
                                *journal_stream_dev = st.st_dev;
10,346✔
600
                                *journal_stream_ino = st.st_ino;
10,346✔
601
                        }
602
                }
603
                return r;
604

605
        case EXEC_OUTPUT_SOCKET:
9✔
606
                assert(socket_fd >= 0);
9✔
607

608
                return RET_NERRNO(dup2(socket_fd, fileno));
9✔
609

610
        case EXEC_OUTPUT_NAMED_FD:
×
611
                assert(named_iofds[fileno] >= 0);
×
612

613
                (void) fd_nonblock(named_iofds[fileno], false);
×
614
                return RET_NERRNO(dup2(named_iofds[fileno], fileno));
×
615

616
        case EXEC_OUTPUT_FILE:
11✔
617
        case EXEC_OUTPUT_FILE_APPEND:
618
        case EXEC_OUTPUT_FILE_TRUNCATE: {
619
                bool rw;
11✔
620
                int fd, flags;
11✔
621

622
                assert(context->stdio_file[fileno]);
11✔
623

624
                rw = context->std_input == EXEC_INPUT_FILE &&
11✔
625
                        streq_ptr(context->stdio_file[fileno], context->stdio_file[STDIN_FILENO]);
×
626

627
                if (rw)
11✔
628
                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));
×
629

630
                flags = O_WRONLY;
11✔
631
                if (o == EXEC_OUTPUT_FILE_APPEND)
11✔
632
                        flags |= O_APPEND;
633
                else if (o == EXEC_OUTPUT_FILE_TRUNCATE)
9✔
634
                        flags |= O_TRUNC;
3✔
635

636
                fd = acquire_path(context->stdio_file[fileno], flags, 0666 & ~context->umask);
11✔
637
                if (fd < 0)
11✔
638
                        return fd;
639

640
                return move_fd(fd, fileno, 0);
11✔
641
        }
642

643
        default:
×
644
                assert_not_reached();
×
645
        }
646
}
647

648
static int chown_terminal(int fd, uid_t uid) {
2,674✔
649
        int r;
2,674✔
650

651
        assert(fd >= 0);
2,674✔
652

653
        /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
654
        if (!isatty_safe(fd))
2,674✔
655
                return 0;
656

657
        /* This might fail. What matters are the results. */
658
        r = fchmod_and_chown(fd, TTY_MODE, uid, GID_INVALID);
7✔
659
        if (r < 0)
7✔
660
                return r;
×
661

662
        return 1;
663
}
664

665
static int setup_confirm_stdio(
×
666
                const ExecContext *context,
667
                const char *vc,
668
                int *ret_saved_stdin,
669
                int *ret_saved_stdout) {
670

671
        _cleanup_close_ int fd = -EBADF, saved_stdin = -EBADF, saved_stdout = -EBADF;
×
672
        int r;
×
673

674
        assert(context);
×
675
        assert(ret_saved_stdin);
×
676
        assert(ret_saved_stdout);
×
677

678
        saved_stdin = fcntl(STDIN_FILENO, F_DUPFD_CLOEXEC, 3);
×
679
        if (saved_stdin < 0)
×
680
                return -errno;
×
681

682
        saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD_CLOEXEC, 3);
×
683
        if (saved_stdout < 0)
×
684
                return -errno;
×
685

686
        fd = acquire_terminal(vc, ACQUIRE_TERMINAL_WAIT, DEFAULT_CONFIRM_USEC);
×
687
        if (fd < 0)
×
688
                return fd;
689

690
        _cleanup_close_ int lock_fd = lock_dev_console();
×
691
        if (lock_fd < 0)
×
692
                log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
×
693

694
        r = chown_terminal(fd, getuid());
×
695
        if (r < 0)
×
696
                return r;
697

698
        r = terminal_reset_defensive(fd, TERMINAL_RESET_SWITCH_TO_TEXT);
×
699
        if (r < 0)
×
700
                return r;
701

702
        r = exec_context_apply_tty_size(context, fd, fd, vc);
×
703
        if (r < 0)
×
704
                return r;
705

706
        r = rearrange_stdio(fd, fd, STDERR_FILENO); /* Invalidates 'fd' also on failure */
×
707
        TAKE_FD(fd);
×
708
        if (r < 0)
×
709
                return r;
710

711
        *ret_saved_stdin = TAKE_FD(saved_stdin);
×
712
        *ret_saved_stdout = TAKE_FD(saved_stdout);
×
713
        return 0;
×
714
}
715

716
static void write_confirm_error_fd(int err, int fd, const char *unit_id) {
×
717
        assert(err != 0);
×
718
        assert(fd >= 0);
×
719
        assert(unit_id);
×
720

721
        errno = abs(err);
×
722

723
        if (errno == ETIMEDOUT)
×
724
                dprintf(fd, "Confirmation question timed out for %s, assuming positive response.\n", unit_id);
×
725
        else
726
                dprintf(fd, "Couldn't ask confirmation for %s, assuming positive response: %m\n", unit_id);
×
727
}
×
728

729
static void write_confirm_error(int err, const char *vc, const char *unit_id) {
×
730
        _cleanup_close_ int fd = -EBADF;
×
731

732
        assert(vc);
×
733

734
        fd = open_terminal(vc, O_WRONLY|O_NOCTTY|O_CLOEXEC);
×
735
        if (fd < 0)
×
736
                return;
×
737

738
        write_confirm_error_fd(err, fd, unit_id);
×
739
}
740

741
static int restore_confirm_stdio(int *saved_stdin, int *saved_stdout) {
×
742
        int r = 0;
×
743

744
        assert(saved_stdin);
×
745
        assert(saved_stdout);
×
746

747
        release_terminal();
×
748

749
        if (*saved_stdin >= 0)
×
750
                if (dup2(*saved_stdin, STDIN_FILENO) < 0)
×
751
                        r = -errno;
×
752

753
        if (*saved_stdout >= 0)
×
754
                if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
×
755
                        r = -errno;
×
756

757
        *saved_stdin = safe_close(*saved_stdin);
×
758
        *saved_stdout = safe_close(*saved_stdout);
×
759

760
        return r;
×
761
}
762

763
enum {
764
        CONFIRM_PRETEND_FAILURE = -1,
765
        CONFIRM_PRETEND_SUCCESS =  0,
766
        CONFIRM_EXECUTE = 1,
767
};
768

769
static bool confirm_spawn_disabled(void) {
×
770
        return access("/run/systemd/confirm_spawn_disabled", F_OK) >= 0;
×
771
}
772

773
static int ask_for_confirmation(const ExecContext *context, const ExecParameters *params, const char *cmdline) {
×
774
        int saved_stdout = -EBADF, saved_stdin = -EBADF, r;
×
775
        _cleanup_free_ char *e = NULL;
×
776
        char c;
×
777

778
        assert(context);
×
779
        assert(params);
×
780

781
        /* For any internal errors, assume a positive response. */
782
        r = setup_confirm_stdio(context, params->confirm_spawn, &saved_stdin, &saved_stdout);
×
783
        if (r < 0) {
×
784
                write_confirm_error(r, params->confirm_spawn, params->unit_id);
×
785
                return CONFIRM_EXECUTE;
786
        }
787

788
        /* confirm_spawn might have been disabled while we were sleeping. */
789
        if (!params->confirm_spawn || confirm_spawn_disabled()) {
×
790
                r = 1;
×
791
                goto restore_stdio;
×
792
        }
793

794
        e = ellipsize(cmdline, 60, 100);
×
795
        if (!e) {
×
796
                log_oom();
×
797
                r = CONFIRM_EXECUTE;
×
798
                goto restore_stdio;
×
799
        }
800

801
        for (;;) {
×
802
                r = ask_char(&c, "yfshiDjcn", "Execute %s? [y, f, s – h for help] ", e);
×
803
                if (r < 0) {
×
804
                        write_confirm_error_fd(r, STDOUT_FILENO, params->unit_id);
×
805
                        r = CONFIRM_EXECUTE;
×
806
                        goto restore_stdio;
×
807
                }
808

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

846
                        continue; /* ask again */
×
847
                case 'n':
×
848
                        /* 'n' was removed in favor of 'f'. */
849
                        printf("Didn't understand 'n', did you mean 'f'?\n");
×
850
                        continue; /* ask again */
×
851
                case 's':
×
852
                        printf("Skipping execution.\n");
×
853
                        r = CONFIRM_PRETEND_SUCCESS;
854
                        break;
855
                case 'y':
856
                        r = CONFIRM_EXECUTE;
857
                        break;
858
                default:
×
859
                        assert_not_reached();
×
860
                }
861
                break;
862
        }
863

864
restore_stdio:
×
865
        restore_confirm_stdio(&saved_stdin, &saved_stdout);
×
866
        return r;
867
}
868

869
static int get_fixed_user(
9,400✔
870
                const char *user_or_uid,
871
                bool prefer_nss,
872
                const char **ret_username,
873
                uid_t *ret_uid,
874
                gid_t *ret_gid,
875
                const char **ret_home,
876
                const char **ret_shell) {
877

878
        int r;
9,400✔
879

880
        assert(user_or_uid);
9,400✔
881
        assert(ret_username);
9,400✔
882

883
        r = get_user_creds(&user_or_uid, ret_uid, ret_gid, ret_home, ret_shell,
18,350✔
884
                           USER_CREDS_CLEAN|(prefer_nss ? USER_CREDS_PREFER_NSS : 0));
885
        if (r < 0)
9,400✔
886
                return r;
887

888
        /* user_or_uid is normalized by get_user_creds to username */
889
        *ret_username = user_or_uid;
9,398✔
890

891
        return 0;
9,398✔
892
}
893

894
static int get_fixed_group(
11✔
895
                const char *group_or_gid,
896
                const char **ret_groupname,
897
                gid_t *ret_gid) {
898

899
        int r;
11✔
900

901
        assert(group_or_gid);
11✔
902
        assert(ret_groupname);
11✔
903

904
        r = get_group_creds(&group_or_gid, ret_gid, /* flags = */ 0);
11✔
905
        if (r < 0)
11✔
906
                return r;
907

908
        /* group_or_gid is normalized by get_group_creds to groupname */
909
        *ret_groupname = group_or_gid;
11✔
910

911
        return 0;
11✔
912
}
913

914
static int get_supplementary_groups(
11,554✔
915
                const ExecContext *c,
916
                const char *user,
917
                gid_t gid,
918
                gid_t **ret_gids) {
919

920
        int r;
11,554✔
921

922
        assert(c);
11,554✔
923
        assert(ret_gids);
11,554✔
924

925
        /*
926
         * If user is given, then lookup GID and supplementary groups list.
927
         * We avoid NSS lookups for gid=0. Also we have to initialize groups
928
         * here and as early as possible so we keep the list of supplementary
929
         * groups of the caller.
930
         */
931
        bool keep_groups = false;
11,554✔
932
        if (user && gid_is_valid(gid) && gid != 0) {
14,228✔
933
                /* First step, initialize groups from /etc/groups */
934
                if (initgroups(user, gid) < 0)
2,524✔
935
                        return -errno;
11,554✔
936

937
                keep_groups = true;
938
        }
939

940
        if (strv_isempty(c->supplementary_groups)) {
11,554✔
941
                *ret_gids = NULL;
11,545✔
942
                return 0;
11,545✔
943
        }
944

945
        /*
946
         * If SupplementaryGroups= was passed then NGROUPS_MAX has to
947
         * be positive, otherwise fail.
948
         */
949
        errno = 0;
9✔
950
        int ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
9✔
951
        if (ngroups_max <= 0)
9✔
952
                return errno_or_else(EOPNOTSUPP);
×
953

954
        _cleanup_free_ gid_t *l_gids = new(gid_t, ngroups_max);
18✔
955
        if (!l_gids)
9✔
956
                return -ENOMEM;
957

958
        int k = 0;
9✔
959
        if (keep_groups) {
9✔
960
                /*
961
                 * Lookup the list of groups that the user belongs to, we
962
                 * avoid NSS lookups here too for gid=0.
963
                 */
964
                k = ngroups_max;
9✔
965
                if (getgrouplist(user, gid, l_gids, &k) < 0)
9✔
966
                        return -EINVAL;
967
        }
968

969
        STRV_FOREACH(i, c->supplementary_groups) {
18✔
970
                if (k >= ngroups_max)
9✔
971
                        return -E2BIG;
×
972

973
                const char *g = *i;
9✔
974
                r = get_group_creds(&g, l_gids + k, /* flags = */ 0);
9✔
975
                if (r < 0)
9✔
976
                        return r;
977

978
                k++;
9✔
979
        }
980

981
        if (k == 0) {
9✔
982
                *ret_gids = NULL;
×
983
                return 0;
×
984
        }
985

986
        /* Otherwise get the final list of supplementary groups */
987
        gid_t *groups = newdup(gid_t, l_gids, k);
9✔
988
        if (!groups)
9✔
989
                return -ENOMEM;
990

991
        *ret_gids = groups;
9✔
992
        return k;
9✔
993
}
994

995
static int enforce_groups(gid_t gid, const gid_t *supplementary_gids, int ngids) {
9,584✔
996
        int r;
9,584✔
997

998
        /* Handle SupplementaryGroups= if it is not empty */
999
        if (ngids > 0) {
9,584✔
1000
                r = maybe_setgroups(ngids, supplementary_gids);
270✔
1001
                if (r < 0)
270✔
1002
                        return r;
1003
        }
1004

1005
        if (gid_is_valid(gid)) {
9,584✔
1006
                /* Then set our gids */
1007
                if (setresgid(gid, gid, gid) < 0)
2,027✔
1008
                        return -errno;
1✔
1009
        }
1010

1011
        return 0;
1012
}
1013

1014
static int set_securebits(unsigned bits, unsigned mask) {
743✔
1015
        unsigned applied;
743✔
1016
        int current;
743✔
1017

1018
        current = prctl(PR_GET_SECUREBITS);
743✔
1019
        if (current < 0)
743✔
1020
                return -errno;
×
1021

1022
        /* Clear all securebits defined in mask and set bits */
1023
        applied = ((unsigned) current & ~mask) | bits;
743✔
1024
        if ((unsigned) current == applied)
743✔
1025
                return 0;
1026

1027
        if (prctl(PR_SET_SECUREBITS, applied) < 0)
53✔
1028
                return -errno;
×
1029

1030
        return 1;
1031
}
1032

1033
static int enforce_user(
2,020✔
1034
                const ExecContext *context,
1035
                uid_t uid,
1036
                uint64_t capability_ambient_set) {
1037

1038
        int r;
2,020✔
1039

1040
        assert(context);
2,020✔
1041

1042
        if (!uid_is_valid(uid))
2,020✔
1043
                return 0;
1044

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

1049
        if ((capability_ambient_set != 0 || context->secure_bits != 0) && uid != 0) {
2,020✔
1050

1051
                /* First step: If we need to keep capabilities but drop privileges we need to make sure we
1052
                 * keep our caps, while we drop privileges. Add KEEP_CAPS to the securebits */
1053
                r = set_securebits(1U << SECURE_KEEP_CAPS, 0);
743✔
1054
                if (r < 0)
743✔
1055
                        return r;
1056
        }
1057

1058
        /* Second step: actually set the uids */
1059
        if (setresuid(uid, uid, uid) < 0)
2,020✔
1060
                return -errno;
×
1061

1062
        /* At this point we should have all necessary capabilities but are otherwise a normal user. However,
1063
         * the caps might got corrupted due to the setresuid() so we need clean them up later. This is done
1064
         * outside of this call. */
1065
        return 0;
1066
}
1067

1068
#if HAVE_PAM
1069

1070
static void pam_response_free_array(struct pam_response *responses, size_t n_responses) {
×
1071
        assert(responses || n_responses == 0);
×
1072

1073
        FOREACH_ARRAY(resp, responses, n_responses)
×
1074
                erase_and_free(resp->resp);
×
1075

1076
        free(responses);
×
1077
}
×
1078

1079
typedef struct AskPasswordConvData {
1080
        const ExecContext *context;
1081
        const ExecParameters *params;
1082
} AskPasswordConvData;
1083

1084
static int ask_password_conv(
5✔
1085
                int num_msg,
1086
                const struct pam_message *msg[],
1087
                struct pam_response **ret,
1088
                void *userdata) {
1089

1090
        AskPasswordConvData *data = ASSERT_PTR(userdata);
5✔
1091
        bool set_credential_env_var = false;
5✔
1092
        int r;
5✔
1093

1094
        assert(num_msg >= 0);
5✔
1095
        assert(msg);
5✔
1096
        assert(data->context);
5✔
1097
        assert(data->params);
5✔
1098

1099
        size_t n = num_msg;
5✔
1100
        struct pam_response *responses = new0(struct pam_response, n);
5✔
1101
        if (!responses)
5✔
1102
                return PAM_BUF_ERR;
5✔
1103
        CLEANUP_ARRAY(responses, n, pam_response_free_array);
5✔
1104

1105
        for (size_t i = 0; i < n; i++) {
10✔
1106
                const struct pam_message *mi = *msg + i;
5✔
1107

1108
                switch (mi->msg_style) {
5✔
1109

1110
                case PAM_PROMPT_ECHO_ON:
2✔
1111
                case PAM_PROMPT_ECHO_OFF: {
1112

1113
                        /* Locally set the $CREDENTIALS_DIRECTORY to the credentials directory we just populated */
1114
                        if (!set_credential_env_var) {
2✔
1115
                                _cleanup_free_ char *creds_dir = NULL;
2✔
1116
                                r = exec_context_get_credential_directory(data->context, data->params, data->params->unit_id, &creds_dir);
2✔
1117
                                if (r < 0)
2✔
1118
                                        return log_error_errno(r, "Failed to determine credentials directory: %m");
×
1119

1120
                                if (creds_dir) {
2✔
1121
                                        if (setenv("CREDENTIALS_DIRECTORY", creds_dir, /* overwrite= */ true) < 0)
2✔
1122
                                                return log_error_errno(r, "Failed to set $CREDENTIALS_DIRECTORY: %m");
×
1123
                                } else
1124
                                        (void) unsetenv("CREDENTIALS_DIRECTORY");
×
1125

1126
                                set_credential_env_var = true;
2✔
1127
                        }
1128

1129
                        _cleanup_free_ char *credential_name = strjoin("pam.authtok.", data->context->pam_name);
4✔
1130
                        if (!credential_name)
2✔
1131
                                return log_oom();
×
1132

1133
                        AskPasswordRequest req = {
4✔
1134
                                .message = mi->msg,
2✔
1135
                                .credential = credential_name,
1136
                                .tty_fd = -EBADF,
1137
                                .hup_fd = -EBADF,
1138
                                .until = usec_add(now(CLOCK_MONOTONIC), 15 * USEC_PER_SEC),
2✔
1139
                        };
1140

1141
                        _cleanup_strv_free_erase_ char **acquired = NULL;
×
1142
                        r = ask_password_auto(
2✔
1143
                                        &req,
1144
                                        ASK_PASSWORD_ACCEPT_CACHED|
1145
                                        ASK_PASSWORD_NO_TTY|
1146
                                        (mi->msg_style == PAM_PROMPT_ECHO_ON ? ASK_PASSWORD_ECHO : 0),
2✔
1147
                                        &acquired);
1148
                        if (r < 0) {
2✔
1149
                                log_error_errno(r, "Failed to query for password: %m");
×
1150
                                return PAM_CONV_ERR;
×
1151
                        }
1152

1153
                        responses[i].resp = strdup(ASSERT_PTR(acquired[0]));
2✔
1154
                        if (!responses[i].resp) {
2✔
1155
                                log_oom();
×
1156
                                return PAM_BUF_ERR;
1157
                        }
1158
                        break;
2✔
1159
                }
1160

1161
                case PAM_ERROR_MSG:
1162
                        log_error("PAM: %s", mi->msg);
×
1163
                        break;
1164

1165
                case PAM_TEXT_INFO:
1166
                        log_info("PAM: %s", mi->msg);
3✔
1167
                        break;
1168

1169
                default:
1170
                        return PAM_CONV_ERR;
1171
                }
1172
        }
1173

1174
        *ret = TAKE_PTR(responses);
5✔
1175
        n = 0;
5✔
1176

1177
        return PAM_SUCCESS;
5✔
1178
}
1179

1180
static int pam_close_session_and_delete_credentials(pam_handle_t *handle, int flags) {
221✔
1181
        int r, s;
221✔
1182

1183
        assert(handle);
221✔
1184

1185
        r = pam_close_session(handle, flags);
221✔
1186
        if (r != PAM_SUCCESS)
221✔
1187
                log_debug("pam_close_session() failed: %s", pam_strerror(handle, r));
48✔
1188

1189
        s = pam_setcred(handle, PAM_DELETE_CRED | flags);
221✔
1190
        if (s != PAM_SUCCESS)
221✔
1191
                log_debug("pam_setcred(PAM_DELETE_CRED) failed: %s", pam_strerror(handle, s));
154✔
1192

1193
        return r != PAM_SUCCESS ? r : s;
221✔
1194
}
1195
#endif
1196

1197
static int setup_pam(
402✔
1198
                const ExecContext *context,
1199
                ExecParameters *params,
1200
                const char *user,
1201
                uid_t uid,
1202
                gid_t gid,
1203
                char ***env, /* updated on success */
1204
                const int fds[], size_t n_fds,
1205
                int exec_fd) {
1206

1207
#if HAVE_PAM
1208
        AskPasswordConvData conv_data = {
402✔
1209
                .context = context,
1210
                .params = params,
1211
        };
1212

1213
        const struct pam_conv conv = {
402✔
1214
                .conv = ask_password_conv,
1215
                .appdata_ptr = &conv_data,
1216
        };
1217

1218
        _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
402✔
1219
        _cleanup_strv_free_ char **e = NULL;
×
1220
        _cleanup_free_ char *tty = NULL;
402✔
1221
        pam_handle_t *handle = NULL;
402✔
1222
        sigset_t old_ss;
402✔
1223
        int pam_code = PAM_SUCCESS, r;
402✔
1224
        bool close_session = false;
402✔
1225
        pid_t parent_pid;
402✔
1226
        int flags = 0;
402✔
1227

1228
        assert(context);
402✔
1229
        assert(params);
402✔
1230
        assert(user);
402✔
1231
        assert(uid_is_valid(uid));
402✔
1232
        assert(gid_is_valid(gid));
402✔
1233
        assert(fds || n_fds == 0);
402✔
1234
        assert(env);
402✔
1235

1236
        /* We set up PAM in the parent process, then fork. The child
1237
         * will then stay around until killed via PR_GET_PDEATHSIG or
1238
         * systemd via the cgroup logic. It will then remove the PAM
1239
         * session again. The parent process will exec() the actual
1240
         * daemon. We do things this way to ensure that the main PID
1241
         * of the daemon is the one we initially fork()ed. */
1242

1243
        r = barrier_create(&barrier);
402✔
1244
        if (r < 0)
402✔
1245
                goto fail;
×
1246

1247
        if (log_get_max_level() < LOG_DEBUG)
402✔
1248
                flags |= PAM_SILENT;
3✔
1249

1250
        pam_code = pam_start(context->pam_name, user, &conv, &handle);
402✔
1251
        if (pam_code != PAM_SUCCESS) {
402✔
1252
                handle = NULL;
×
1253
                goto fail;
×
1254
        }
1255

1256
        if (getttyname_malloc(STDIN_FILENO, &tty) >= 0) {
402✔
1257
                _cleanup_free_ char *q = path_join("/dev", tty);
6✔
1258
                if (!q) {
6✔
1259
                        r = -ENOMEM;
×
1260
                        goto fail;
×
1261
                }
1262

1263
                free_and_replace(tty, q);
6✔
1264
        }
1265

1266
        if (tty) {
402✔
1267
                pam_code = pam_set_item(handle, PAM_TTY, tty);
6✔
1268
                if (pam_code != PAM_SUCCESS)
6✔
1269
                        goto fail;
×
1270
        }
1271

1272
        STRV_FOREACH(nv, *env) {
5,694✔
1273
                pam_code = pam_putenv(handle, *nv);
5,292✔
1274
                if (pam_code != PAM_SUCCESS)
5,292✔
1275
                        goto fail;
×
1276
        }
1277

1278
        pam_code = pam_acct_mgmt(handle, flags);
402✔
1279
        if (pam_code != PAM_SUCCESS)
402✔
1280
                goto fail;
×
1281

1282
        pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | flags);
402✔
1283
        if (pam_code != PAM_SUCCESS)
402✔
1284
                log_debug("pam_setcred(PAM_ESTABLISH_CRED) failed, ignoring: %s", pam_strerror(handle, pam_code));
330✔
1285

1286
        pam_code = pam_open_session(handle, flags);
402✔
1287
        if (pam_code != PAM_SUCCESS)
402✔
1288
                goto fail;
×
1289

1290
        close_session = true;
402✔
1291

1292
        e = pam_getenvlist(handle);
402✔
1293
        if (!e) {
402✔
1294
                pam_code = PAM_BUF_ERR;
×
1295
                goto fail;
×
1296
        }
1297

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

1300
        assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM) >= 0);
402✔
1301

1302
        parent_pid = getpid_cached();
402✔
1303

1304
        r = safe_fork("(sd-pam)", 0, NULL);
402✔
1305
        if (r < 0)
624✔
1306
                goto fail;
×
1307
        if (r == 0) {
624✔
1308
                int ret = EXIT_PAM;
222✔
1309

1310
                /* The child's job is to reset the PAM session on termination */
1311
                barrier_set_role(&barrier, BARRIER_CHILD);
222✔
1312

1313
                /* Make sure we don't keep open the passed fds in this child. We assume that otherwise only
1314
                 * those fds are open here that have been opened by PAM. */
1315
                (void) close_many(fds, n_fds);
222✔
1316

1317
                /* Also close the 'exec_fd' in the child, since the service manager waits for the EOF induced
1318
                 * by the execve() to wait for completion, and if we'd keep the fd open here in the child
1319
                 * we'd never signal completion. */
1320
                exec_fd = safe_close(exec_fd);
222✔
1321

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

1326
                r = fully_set_uid_gid(uid, gid, /* supplementary_gids= */ NULL, /* n_supplementary_gids= */ 0);
222✔
1327
                if (r < 0)
222✔
1328
                        log_warning_errno(r, "Failed to drop privileges in sd-pam: %m");
×
1329

1330
                (void) ignore_signals(SIGPIPE);
222✔
1331

1332
                /* Wait until our parent died. This will only work if the above setresuid() succeeds,
1333
                 * otherwise the kernel will not allow unprivileged parents kill their privileged children
1334
                 * this way. We rely on the control groups kill logic to do the rest for us. */
1335
                if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
222✔
1336
                        goto child_finish;
×
1337

1338
                /* Tell the parent that our setup is done. This is especially important regarding dropping
1339
                 * privileges. Otherwise, unit setup might race against our setresuid(2) call.
1340
                 *
1341
                 * If the parent aborted, we'll detect this below, hence ignore return failure here. */
1342
                (void) barrier_place(&barrier);
222✔
1343

1344
                /* Check if our parent process might already have died? */
1345
                if (getppid() == parent_pid) {
222✔
1346
                        sigset_t ss;
222✔
1347
                        int sig;
222✔
1348

1349
                        assert_se(sigemptyset(&ss) >= 0);
222✔
1350
                        assert_se(sigaddset(&ss, SIGTERM) >= 0);
222✔
1351

1352
                        assert_se(sigwait(&ss, &sig) == 0);
222✔
1353
                        assert(sig == SIGTERM);
222✔
1354
                }
1355

1356
                /* If our parent died we'll end the session */
1357
                if (getppid() != parent_pid) {
222✔
1358
                        pam_code = pam_close_session_and_delete_credentials(handle, flags);
221✔
1359
                        if (pam_code != PAM_SUCCESS)
221✔
1360
                                goto child_finish;
154✔
1361
                }
1362

1363
                ret = 0;
1364

1365
        child_finish:
222✔
1366
                /* NB: pam_end() when called in child processes should set PAM_DATA_SILENT to let the module
1367
                 * know about this. See pam_end(3) */
1368
                (void) pam_end(handle, pam_code | flags | PAM_DATA_SILENT);
222✔
1369
                _exit(ret);
222✔
1370
        }
1371

1372
        barrier_set_role(&barrier, BARRIER_PARENT);
402✔
1373

1374
        /* If the child was forked off successfully it will do all the cleanups, so forget about the handle
1375
         * here. */
1376
        handle = NULL;
402✔
1377

1378
        /* Unblock SIGTERM again in the parent */
1379
        assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0);
402✔
1380

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

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

1390
        return strv_free_and_replace(*env, e);
402✔
1391

1392
fail:
×
1393
        if (pam_code != PAM_SUCCESS) {
×
1394
                log_error("PAM failed: %s", pam_strerror(handle, pam_code));
×
1395
                r = -EPERM;  /* PAM errors do not map to errno */
1396
        } else
1397
                log_error_errno(r, "PAM failed: %m");
×
1398

1399
        if (handle) {
×
1400
                if (close_session)
×
1401
                        pam_code = pam_close_session_and_delete_credentials(handle, flags);
×
1402

1403
                (void) pam_end(handle, pam_code | flags);
×
1404
        }
1405

1406
        closelog();
×
1407
        return r;
1408
#else
1409
        return 0;
1410
#endif
1411
}
1412

1413
static void rename_process_from_path(const char *path) {
11,557✔
1414
        _cleanup_free_ char *buf = NULL;
11,557✔
1415
        const char *p;
11,557✔
1416

1417
        assert(path);
11,557✔
1418

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

1422
        if (path_extract_filename(path, &buf) < 0) {
11,557✔
1423
                rename_process("(...)");
×
1424
                return;
×
1425
        }
1426

1427
        size_t l = strlen(buf);
11,557✔
1428
        if (l > 8) {
11,557✔
1429
                /* The end of the process name is usually more interesting, since the first bit might just be
1430
                 * "systemd-" */
1431
                p = buf + l - 8;
7,980✔
1432
                l = 8;
7,980✔
1433
        } else
1434
                p = buf;
1435

1436
        char process_name[11];
11,557✔
1437
        process_name[0] = '(';
11,557✔
1438
        memcpy(process_name+1, p, l);
11,557✔
1439
        process_name[1+l] = ')';
11,557✔
1440
        process_name[1+l+1] = 0;
11,557✔
1441

1442
        (void) rename_process(process_name);
11,557✔
1443
}
1444

1445
static bool context_has_address_families(const ExecContext *c) {
12,509✔
1446
        assert(c);
12,509✔
1447

1448
        return c->address_families_allow_list ||
12,509✔
1449
                !set_isempty(c->address_families);
11,017✔
1450
}
1451

1452
static bool context_has_syscall_filters(const ExecContext *c) {
12,473✔
1453
        assert(c);
12,473✔
1454

1455
        return c->syscall_allow_list ||
12,473✔
1456
                !hashmap_isempty(c->syscall_filter);
10,996✔
1457
}
1458

1459
static bool context_has_syscall_logs(const ExecContext *c) {
12,473✔
1460
        assert(c);
12,473✔
1461

1462
        return c->syscall_log_allow_list ||
12,473✔
1463
                !hashmap_isempty(c->syscall_log);
12,473✔
1464
}
1465

1466
static bool context_has_seccomp(const ExecContext *c) {
3,648✔
1467
        assert(c);
3,648✔
1468

1469
        /* We need NNP if we have any form of seccomp and are unprivileged */
1470
        return c->lock_personality ||
6,580✔
1471
                c->memory_deny_write_execute ||
2,932✔
1472
                c->private_devices ||
2,932✔
1473
                c->protect_clock ||
2,932✔
1474
                c->protect_hostname == PROTECT_HOSTNAME_YES ||
2,932✔
1475
                c->protect_kernel_tunables ||
2,932✔
1476
                c->protect_kernel_modules ||
2,932✔
1477
                c->protect_kernel_logs ||
5,864✔
1478
                context_has_address_families(c) ||
5,864✔
1479
                exec_context_restrict_namespaces_set(c) ||
2,932✔
1480
                c->restrict_realtime ||
2,932✔
1481
                c->restrict_suid_sgid ||
2,932✔
1482
                !set_isempty(c->syscall_archs) ||
5,792✔
1483
                context_has_syscall_filters(c) ||
9,440✔
1484
                context_has_syscall_logs(c);
2,896✔
1485
}
1486

1487
static bool context_has_no_new_privileges(const ExecContext *c) {
9,577✔
1488
        assert(c);
9,577✔
1489

1490
        if (c->no_new_privileges)
9,577✔
1491
                return true;
1492

1493
        if (have_effective_cap(CAP_SYS_ADMIN) > 0) /* if we are privileged, we don't need NNP */
8,161✔
1494
                return false;
1495

1496
        return context_has_seccomp(c);
1,628✔
1497
}
1498

1499
#if HAVE_SECCOMP
1500

1501
static bool seccomp_allows_drop_privileges(const ExecContext *c) {
752✔
1502
        void *id, *val;
752✔
1503
        bool have_capget = false, have_capset = false, have_prctl = false;
752✔
1504

1505
        assert(c);
752✔
1506

1507
        /* No syscall filter, we are allowed to drop privileges */
1508
        if (hashmap_isempty(c->syscall_filter))
752✔
1509
                return true;
752✔
1510

1511
        HASHMAP_FOREACH_KEY(val, id, c->syscall_filter) {
272,261✔
1512
                _cleanup_free_ char *name = NULL;
271,562✔
1513

1514
                name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
271,562✔
1515

1516
                if (streq(name, "capget"))
271,562✔
1517
                        have_capget = true;
1518
                else if (streq(name, "capset"))
270,863✔
1519
                        have_capset = true;
1520
                else if (streq(name, "prctl"))
270,164✔
1521
                        have_prctl = true;
699✔
1522
        }
1523

1524
        if (c->syscall_allow_list)
699✔
1525
                return have_capget && have_capset && have_prctl;
699✔
1526
        else
1527
                return !(have_capget || have_capset || have_prctl);
×
1528
}
1529

1530
static bool skip_seccomp_unavailable(const char *msg) {
14,909✔
1531
        assert(msg);
14,909✔
1532

1533
        if (is_seccomp_available())
14,909✔
1534
                return false;
1535

1536
        log_debug("SECCOMP features not detected in the kernel, skipping %s", msg);
×
1537
        return true;
1538
}
1539

1540
static int apply_syscall_filter(const ExecContext *c, const ExecParameters *p) {
9,577✔
1541
        uint32_t negative_action, default_action, action;
9,577✔
1542
        int r;
9,577✔
1543

1544
        assert(c);
9,577✔
1545
        assert(p);
9,577✔
1546

1547
        if (!context_has_syscall_filters(c))
9,577✔
1548
                return 0;
1549

1550
        if (skip_seccomp_unavailable("SystemCallFilter="))
1,478✔
1551
                return 0;
1552

1553
        negative_action = c->syscall_errno == SECCOMP_ERROR_NUMBER_KILL ? scmp_act_kill_process() : SCMP_ACT_ERRNO(c->syscall_errno);
1,478✔
1554

1555
        if (c->syscall_allow_list) {
1,478✔
1556
                default_action = negative_action;
1557
                action = SCMP_ACT_ALLOW;
1558
        } else {
1559
                default_action = SCMP_ACT_ALLOW;
1✔
1560
                action = negative_action;
1✔
1561
        }
1562

1563
        /* Sending over exec_fd or handoff_timestamp_fd requires write() syscall. */
1564
        if (p->exec_fd >= 0 || p->handoff_timestamp_fd >= 0) {
1,478✔
1565
                r = seccomp_filter_set_add_by_name(c->syscall_filter, c->syscall_allow_list, "write");
1,478✔
1566
                if (r < 0)
1,478✔
1567
                        return r;
1568
        }
1569

1570
        return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_filter, action, false);
1,478✔
1571
}
1572

1573
static int apply_syscall_log(const ExecContext *c, const ExecParameters *p) {
9,577✔
1574
#ifdef SCMP_ACT_LOG
1575
        uint32_t default_action, action;
9,577✔
1576
#endif
1577

1578
        assert(c);
9,577✔
1579
        assert(p);
9,577✔
1580

1581
        if (!context_has_syscall_logs(c))
9,577✔
1582
                return 0;
1583

1584
#ifdef SCMP_ACT_LOG
1585
        if (skip_seccomp_unavailable("SystemCallLog="))
×
1586
                return 0;
1587

1588
        if (c->syscall_log_allow_list) {
×
1589
                /* Log nothing but the ones listed */
1590
                default_action = SCMP_ACT_ALLOW;
1591
                action = SCMP_ACT_LOG;
1592
        } else {
1593
                /* Log everything but the ones listed */
1594
                default_action = SCMP_ACT_LOG;
×
1595
                action = SCMP_ACT_ALLOW;
×
1596
        }
1597

1598
        return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_log, action, false);
×
1599
#else
1600
        /* old libseccomp */
1601
        log_debug( "SECCOMP feature SCMP_ACT_LOG not available, skipping SystemCallLog=");
1602
        return 0;
1603
#endif
1604
}
1605

1606
static int apply_syscall_archs(const ExecContext *c, const ExecParameters *p) {
9,577✔
1607
        assert(c);
9,577✔
1608
        assert(p);
9,577✔
1609

1610
        if (set_isempty(c->syscall_archs))
9,577✔
1611
                return 0;
1612

1613
        if (skip_seccomp_unavailable("SystemCallArchitectures="))
1,495✔
1614
                return 0;
1615

1616
        return seccomp_restrict_archs(c->syscall_archs);
1,495✔
1617
}
1618

1619
static int apply_address_families(const ExecContext *c, const ExecParameters *p) {
9,577✔
1620
        assert(c);
9,577✔
1621
        assert(p);
9,577✔
1622

1623
        if (!context_has_address_families(c))
9,577✔
1624
                return 0;
1625

1626
        if (skip_seccomp_unavailable("RestrictAddressFamilies="))
1,492✔
1627
                return 0;
1628

1629
        return seccomp_restrict_address_families(c->address_families, c->address_families_allow_list);
1,492✔
1630
}
1631

1632
static int apply_memory_deny_write_execute(const ExecContext *c, const ExecParameters *p) {
9,577✔
1633
        int r;
9,577✔
1634

1635
        assert(c);
9,577✔
1636
        assert(p);
9,577✔
1637

1638
        if (!c->memory_deny_write_execute)
9,577✔
1639
                return 0;
1640

1641
        /* use prctl() if kernel supports it (6.3) */
1642
        r = prctl(PR_SET_MDWE, PR_MDWE_REFUSE_EXEC_GAIN, 0, 0, 0);
1,492✔
1643
        if (r == 0) {
1,492✔
1644
                log_debug("Enabled MemoryDenyWriteExecute= with PR_SET_MDWE");
1,492✔
1645
                return 0;
1,492✔
1646
        }
1647
        if (r < 0 && errno != EINVAL)
×
1648
                return log_debug_errno(errno, "Failed to enable MemoryDenyWriteExecute= with PR_SET_MDWE: %m");
×
1649
        /* else use seccomp */
1650
        log_debug("Kernel doesn't support PR_SET_MDWE: falling back to seccomp");
×
1651

1652
        if (skip_seccomp_unavailable("MemoryDenyWriteExecute="))
×
1653
                return 0;
1654

1655
        return seccomp_memory_deny_write_execute();
×
1656
}
1657

1658
static int apply_restrict_realtime(const ExecContext *c, const ExecParameters *p) {
9,577✔
1659
        assert(c);
9,577✔
1660
        assert(p);
9,577✔
1661

1662
        if (!c->restrict_realtime)
9,577✔
1663
                return 0;
1664

1665
        if (skip_seccomp_unavailable("RestrictRealtime="))
1,493✔
1666
                return 0;
1667

1668
        return seccomp_restrict_realtime();
1,493✔
1669
}
1670

1671
static int apply_restrict_suid_sgid(const ExecContext *c, const ExecParameters *p) {
9,577✔
1672
        assert(c);
9,577✔
1673
        assert(p);
9,577✔
1674

1675
        if (!c->restrict_suid_sgid)
9,577✔
1676
                return 0;
1677

1678
        if (skip_seccomp_unavailable("RestrictSUIDSGID="))
1,413✔
1679
                return 0;
1680

1681
        return seccomp_restrict_suid_sgid();
1,413✔
1682
}
1683

1684
static int apply_protect_sysctl(const ExecContext *c, const ExecParameters *p) {
9,577✔
1685
        assert(c);
9,577✔
1686
        assert(p);
9,577✔
1687

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

1691
        if (!c->protect_kernel_tunables)
9,577✔
1692
                return 0;
1693

1694
        if (skip_seccomp_unavailable("ProtectKernelTunables="))
364✔
1695
                return 0;
1696

1697
        return seccomp_protect_sysctl();
364✔
1698
}
1699

1700
static int apply_protect_kernel_modules(const ExecContext *c, const ExecParameters *p) {
9,577✔
1701
        assert(c);
9,577✔
1702
        assert(p);
9,577✔
1703

1704
        /* Turn off module syscalls on ProtectKernelModules=yes */
1705

1706
        if (!c->protect_kernel_modules)
9,577✔
1707
                return 0;
1708

1709
        if (skip_seccomp_unavailable("ProtectKernelModules="))
1,131✔
1710
                return 0;
1711

1712
        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_MODULE, SCMP_ACT_ERRNO(EPERM), false);
1,131✔
1713
}
1714

1715
static int apply_protect_kernel_logs(const ExecContext *c, const ExecParameters *p) {
9,577✔
1716
        assert(c);
9,577✔
1717
        assert(p);
9,577✔
1718

1719
        if (!c->protect_kernel_logs)
9,577✔
1720
                return 0;
1721

1722
        if (skip_seccomp_unavailable("ProtectKernelLogs="))
1,131✔
1723
                return 0;
1724

1725
        return seccomp_protect_syslog();
1,131✔
1726
}
1727

1728
static int apply_protect_clock(const ExecContext *c, const ExecParameters *p) {
9,577✔
1729
        assert(c);
9,577✔
1730
        assert(p);
9,577✔
1731

1732
        if (!c->protect_clock)
9,577✔
1733
                return 0;
1734

1735
        if (skip_seccomp_unavailable("ProtectClock="))
843✔
1736
                return 0;
1737

1738
        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_CLOCK, SCMP_ACT_ERRNO(EPERM), false);
843✔
1739
}
1740

1741
static int apply_private_devices(const ExecContext *c, const ExecParameters *p) {
9,577✔
1742
        assert(c);
9,577✔
1743
        assert(p);
9,577✔
1744

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

1747
        if (!c->private_devices)
9,577✔
1748
                return 0;
1749

1750
        if (skip_seccomp_unavailable("PrivateDevices="))
678✔
1751
                return 0;
1752

1753
        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_RAW_IO, SCMP_ACT_ERRNO(EPERM), false);
678✔
1754
}
1755

1756
static int apply_restrict_namespaces(const ExecContext *c, const ExecParameters *p) {
9,577✔
1757
        assert(c);
9,577✔
1758
        assert(p);
9,577✔
1759

1760
        if (!exec_context_restrict_namespaces_set(c))
9,577✔
1761
                return 0;
1762

1763
        if (skip_seccomp_unavailable("RestrictNamespaces="))
1,238✔
1764
                return 0;
1765

1766
        return seccomp_restrict_namespaces(c->restrict_namespaces);
1,238✔
1767
}
1768

1769
static int apply_lock_personality(const ExecContext *c, const ExecParameters *p) {
9,577✔
1770
        unsigned long personality;
9,577✔
1771
        int r;
9,577✔
1772

1773
        assert(c);
9,577✔
1774
        assert(p);
9,577✔
1775

1776
        if (!c->lock_personality)
9,577✔
1777
                return 0;
9,577✔
1778

1779
        if (skip_seccomp_unavailable("LockPersonality="))
1,493✔
1780
                return 0;
1781

1782
        personality = c->personality;
1,493✔
1783

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

1787
                r = opinionated_personality(&personality);
1,493✔
1788
                if (r < 0)
1,493✔
1789
                        return r;
1790
        }
1791

1792
        return seccomp_lock_personality(personality);
1,493✔
1793
}
1794

1795
#endif
1796

1797
#if HAVE_LIBBPF
1798
static int apply_restrict_filesystems(const ExecContext *c, const ExecParameters *p) {
9,577✔
1799
        int r;
9,577✔
1800

1801
        assert(c);
9,577✔
1802
        assert(p);
9,577✔
1803

1804
        if (!exec_context_restrict_filesystems_set(c))
9,577✔
1805
                return 0;
1806

1807
        if (p->bpf_restrict_fs_map_fd < 0) {
×
1808
                /* LSM BPF is unsupported or lsm_bpf_setup failed */
1809
                log_debug("LSM BPF not supported, skipping RestrictFileSystems=");
×
1810
                return 0;
×
1811
        }
1812

1813
        /* We are in a new binary, so dl-open again */
1814
        r = dlopen_bpf();
×
1815
        if (r < 0)
×
1816
                return r;
1817

1818
        return bpf_restrict_fs_update(c->restrict_filesystems, p->cgroup_id, p->bpf_restrict_fs_map_fd, c->restrict_filesystems_allow_list);
×
1819
}
1820
#endif
1821

1822
static int apply_protect_hostname(const ExecContext *c, const ExecParameters *p, int *ret_exit_status) {
9,580✔
1823
        int r;
9,580✔
1824

1825
        assert(c);
9,580✔
1826
        assert(p);
9,580✔
1827
        assert(ret_exit_status);
9,580✔
1828

1829
        if (c->protect_hostname == PROTECT_HOSTNAME_NO)
9,580✔
1830
                return 0;
1831

1832
        if (namespace_type_supported(NAMESPACE_UTS)) {
666✔
1833
                if (unshare(CLONE_NEWUTS) < 0) {
666✔
1834
                        if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno)) {
×
1835
                                *ret_exit_status = EXIT_NAMESPACE;
×
1836
                                return log_error_errno(errno, "Failed to set up UTS namespacing: %m");
×
1837
                        }
1838

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

1842
                } else if (c->private_hostname) {
666✔
1843
                        r = sethostname_idempotent(c->private_hostname);
4✔
1844
                        if (r < 0) {
4✔
1845
                                *ret_exit_status = EXIT_NAMESPACE;
×
1846
                                return log_error_errno(r, "Failed to set private hostname '%s': %m", c->private_hostname);
×
1847
                        }
1848
                }
1849
        } else
1850
                log_warning("ProtectHostname=%s is configured, but the kernel does not support UTS namespaces, ignoring namespace setup.",
×
1851
                            protect_hostname_to_string(c->protect_hostname));
1852

1853
#if HAVE_SECCOMP
1854
        if (c->protect_hostname == PROTECT_HOSTNAME_YES) {
666✔
1855
                if (skip_seccomp_unavailable("ProtectHostname="))
660✔
1856
                        return 0;
1857

1858
                r = seccomp_protect_hostname();
660✔
1859
                if (r < 0) {
660✔
1860
                        *ret_exit_status = EXIT_SECCOMP;
×
1861
                        return log_error_errno(r, "Failed to apply hostname restrictions: %m");
×
1862
                }
1863
        }
1864
#endif
1865

1866
        return 1;
1867
}
1868

1869
static void do_idle_pipe_dance(int idle_pipe[static 4]) {
151✔
1870
        assert(idle_pipe);
151✔
1871

1872
        idle_pipe[1] = safe_close(idle_pipe[1]);
151✔
1873
        idle_pipe[2] = safe_close(idle_pipe[2]);
151✔
1874

1875
        if (idle_pipe[0] >= 0) {
151✔
1876
                int r;
151✔
1877

1878
                r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
151✔
1879

1880
                if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
151✔
1881
                        ssize_t n;
110✔
1882

1883
                        /* Signal systemd that we are bored and want to continue. */
1884
                        n = write(idle_pipe[3], "x", 1);
110✔
1885
                        if (n > 0)
110✔
1886
                                /* Wait for systemd to react to the signal above. */
1887
                                (void) fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
110✔
1888
                }
1889

1890
                idle_pipe[0] = safe_close(idle_pipe[0]);
151✔
1891

1892
        }
1893

1894
        idle_pipe[3] = safe_close(idle_pipe[3]);
151✔
1895
}
151✔
1896

1897
static const char *exec_directory_env_name_to_string(ExecDirectoryType t);
1898

1899
/* And this table also maps ExecDirectoryType, to the environment variable we pass the selected directory to
1900
 * the service payload in. */
1901
static const char* const exec_directory_env_name_table[_EXEC_DIRECTORY_TYPE_MAX] = {
1902
        [EXEC_DIRECTORY_RUNTIME]       = "RUNTIME_DIRECTORY",
1903
        [EXEC_DIRECTORY_STATE]         = "STATE_DIRECTORY",
1904
        [EXEC_DIRECTORY_CACHE]         = "CACHE_DIRECTORY",
1905
        [EXEC_DIRECTORY_LOGS]          = "LOGS_DIRECTORY",
1906
        [EXEC_DIRECTORY_CONFIGURATION] = "CONFIGURATION_DIRECTORY",
1907
};
1908

1909
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(exec_directory_env_name, ExecDirectoryType);
2,498✔
1910

1911
static int build_environment(
9,605✔
1912
                const ExecContext *c,
1913
                const ExecParameters *p,
1914
                const CGroupContext *cgroup_context,
1915
                size_t n_fds,
1916
                const char *home,
1917
                const char *username,
1918
                const char *shell,
1919
                dev_t journal_stream_dev,
1920
                ino_t journal_stream_ino,
1921
                const char *memory_pressure_path,
1922
                bool needs_sandboxing,
1923
                char ***ret) {
1924

1925
        _cleanup_strv_free_ char **our_env = NULL;
9,605✔
1926
        size_t n_env = 0;
9,605✔
1927
        char *x;
9,605✔
1928
        int r;
9,605✔
1929

1930
        assert(c);
9,605✔
1931
        assert(p);
9,605✔
1932
        assert(cgroup_context);
9,605✔
1933
        assert(ret);
9,605✔
1934

1935
#define N_ENV_VARS 22
1936
        our_env = new0(char*, N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
9,605✔
1937
        if (!our_env)
9,605✔
1938
                return -ENOMEM;
1939

1940
        if (n_fds > 0) {
9,605✔
1941
                _cleanup_free_ char *joined = NULL;
1,537✔
1942

1943
                if (asprintf(&x, "LISTEN_PID="PID_FMT, getpid_cached()) < 0)
1,537✔
1944
                        return -ENOMEM;
1945
                our_env[n_env++] = x;
1,537✔
1946

1947
                if (asprintf(&x, "LISTEN_FDS=%zu", n_fds) < 0)
1,537✔
1948
                        return -ENOMEM;
1949
                our_env[n_env++] = x;
1,537✔
1950

1951
                joined = strv_join(p->fd_names, ":");
1,537✔
1952
                if (!joined)
1,537✔
1953
                        return -ENOMEM;
1954

1955
                x = strjoin("LISTEN_FDNAMES=", joined);
1,537✔
1956
                if (!x)
1,537✔
1957
                        return -ENOMEM;
1958
                our_env[n_env++] = x;
1,537✔
1959
        }
1960

1961
        if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) {
9,605✔
1962
                if (asprintf(&x, "WATCHDOG_PID="PID_FMT, getpid_cached()) < 0)
1,486✔
1963
                        return -ENOMEM;
1964
                our_env[n_env++] = x;
1,486✔
1965

1966
                if (asprintf(&x, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec) < 0)
1,486✔
1967
                        return -ENOMEM;
1968
                our_env[n_env++] = x;
1,486✔
1969
        }
1970

1971
        /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use blocking
1972
         * Varlink calls back to us for look up dynamic users in PID 1. Break the deadlock between D-Bus and
1973
         * PID 1 by disabling use of PID1' NSS interface for looking up dynamic users. */
1974
        if (p->flags & EXEC_NSS_DYNAMIC_BYPASS) {
9,605✔
1975
                x = strdup("SYSTEMD_NSS_DYNAMIC_BYPASS=1");
121✔
1976
                if (!x)
121✔
1977
                        return -ENOMEM;
1978
                our_env[n_env++] = x;
121✔
1979
        }
1980

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

1988
                r = get_fixed_user("root", /* prefer_nss = */ false, &username, NULL, NULL, &home, &shell);
6,786✔
1989
                if (r < 0)
6,786✔
1990
                        return log_debug_errno(r, "Failed to determine user credentials for root: %m");
×
1991
        }
1992

1993
        bool set_user_login_env = exec_context_get_set_login_environment(c);
9,605✔
1994

1995
        if (username) {
9,605✔
1996
                x = strjoin("USER=", username);
8,810✔
1997
                if (!x)
8,810✔
1998
                        return -ENOMEM;
1999
                our_env[n_env++] = x;
8,810✔
2000

2001
                if (set_user_login_env) {
8,810✔
2002
                        x = strjoin("LOGNAME=", username);
2,020✔
2003
                        if (!x)
2,020✔
2004
                                return -ENOMEM;
2005
                        our_env[n_env++] = x;
2,020✔
2006
                }
2007
        }
2008

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

2012
        if (home && set_user_login_env && !empty_or_root(home)) {
9,605✔
2013
                x = strjoin("HOME=", home);
417✔
2014
                if (!x)
417✔
2015
                        return -ENOMEM;
2016

2017
                path_simplify(x + 5);
417✔
2018
                our_env[n_env++] = x;
417✔
2019
        }
2020

2021
        if (shell && set_user_login_env && !shell_is_placeholder(shell)) {
9,605✔
2022
                x = strjoin("SHELL=", shell);
419✔
2023
                if (!x)
419✔
2024
                        return -ENOMEM;
2025

2026
                path_simplify(x + 6);
419✔
2027
                our_env[n_env++] = x;
419✔
2028
        }
2029

2030
        if (!sd_id128_is_null(p->invocation_id)) {
9,605✔
2031
                assert(p->invocation_id_string);
9,605✔
2032

2033
                x = strjoin("INVOCATION_ID=", p->invocation_id_string);
9,605✔
2034
                if (!x)
9,605✔
2035
                        return -ENOMEM;
2036

2037
                our_env[n_env++] = x;
9,605✔
2038
        }
2039

2040
        if (exec_context_needs_term(c)) {
9,605✔
2041
                _cleanup_free_ char *cmdline = NULL, *dcs_term = NULL;
448✔
2042
                const char *tty_path, *term = NULL;
448✔
2043

2044
                tty_path = exec_context_tty_path(c);
448✔
2045

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

2050
                if (path_equal(tty_path, "/dev/console") && getppid() == 1)
448✔
2051
                        term = getenv("TERM");
391✔
2052
                else if (tty_path && in_charset(skip_dev_prefix(tty_path), ALPHANUMERICAL)) {
57✔
2053
                        _cleanup_free_ char *key = NULL;
41✔
2054

2055
                        key = strjoin("systemd.tty.term.", skip_dev_prefix(tty_path));
41✔
2056
                        if (!key)
41✔
2057
                                return -ENOMEM;
×
2058

2059
                        r = proc_cmdline_get_key(key, 0, &cmdline);
41✔
2060
                        if (r < 0)
41✔
2061
                                log_debug_errno(r, "Failed to read %s from kernel cmdline, ignoring: %m", key);
41✔
2062
                        else if (r > 0)
41✔
2063
                                term = cmdline;
×
2064
                }
2065

2066
                if (!term && tty_path) {
448✔
2067
                        /* This handles real virtual terminals (returning "linux") and
2068
                         * any terminals which support the DCS +q query sequence. */
2069
                        r = query_term_for_tty(tty_path, &dcs_term);
41✔
2070
                        if (r >= 0)
41✔
2071
                                term = dcs_term;
41✔
2072
                }
2073

2074
                if (!term) {
448✔
2075
                        /* If $TERM is not known and we pick a fallback default, then let's also set
2076
                         * $COLORTERM=truecolor. That's because our fallback default is vt220, which is
2077
                         * generally a safe bet (as it supports PageUp/PageDown unlike vt100, and is quite
2078
                         * universally available in terminfo/termcap), except for the fact that real DEC
2079
                         * vt220 gear never actually supported color. Most tools these days generate color on
2080
                         * vt220 anyway, ignoring the physical capabilities of the real hardware, but some
2081
                         * tools actually believe in the historical truth. Which is unfortunate since *we*
2082
                         * *don't* care about the historical truth, we just want sane defaults if nothing
2083
                         * better is explicitly configured. It's 2025 after all, at the time of writing,
2084
                         * pretty much all terminal emulators actually *do* support color, hence if we don't
2085
                         * know any better let's explicitly claim color support via $COLORTERM. Or in other
2086
                         * words: we now explicitly claim to be connected to a franken-vt220 with true color
2087
                         * support. */
2088
                        x = strdup("COLORTERM=truecolor");
16✔
2089
                        if (!x)
16✔
2090
                                return -ENOMEM;
2091

2092
                        our_env[n_env++] = x;
16✔
2093

2094
                        term = FALLBACK_TERM;
16✔
2095
                }
2096

2097
                x = strjoin("TERM=", term);
448✔
2098
                if (!x)
448✔
2099
                        return -ENOMEM;
2100
                our_env[n_env++] = x;
448✔
2101
        }
2102

2103
        if (journal_stream_dev != 0 && journal_stream_ino != 0) {
9,605✔
2104
                if (asprintf(&x, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino) < 0)
8,816✔
2105
                        return -ENOMEM;
2106

2107
                our_env[n_env++] = x;
8,816✔
2108
        }
2109

2110
        if (c->log_namespace) {
9,605✔
2111
                x = strjoin("LOG_NAMESPACE=", c->log_namespace);
2✔
2112
                if (!x)
2✔
2113
                        return -ENOMEM;
2114

2115
                our_env[n_env++] = x;
2✔
2116
        }
2117

2118
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
57,630✔
2119
                _cleanup_free_ char *joined = NULL;
48,025✔
2120
                const char *n;
48,025✔
2121

2122
                if (!p->prefix[t])
48,025✔
2123
                        continue;
×
2124

2125
                if (c->directories[t].n_items == 0)
48,025✔
2126
                        continue;
45,527✔
2127

2128
                n = exec_directory_env_name_to_string(t);
2,498✔
2129
                if (!n)
2,498✔
2130
                        continue;
×
2131

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

2135
                        prefixed = path_join(p->prefix[t], c->directories[t].items[i].path);
2,994✔
2136
                        if (!prefixed)
2,994✔
2137
                                return -ENOMEM;
2138

2139
                        if (!strextend_with_separator(&joined, ":", prefixed))
2,994✔
2140
                                return -ENOMEM;
2141
                }
2142

2143
                x = strjoin(n, "=", joined);
2,498✔
2144
                if (!x)
2,498✔
2145
                        return -ENOMEM;
2146

2147
                our_env[n_env++] = x;
2,498✔
2148
        }
2149

2150
        _cleanup_free_ char *creds_dir = NULL;
9,605✔
2151
        r = exec_context_get_credential_directory(c, p, p->unit_id, &creds_dir);
9,605✔
2152
        if (r < 0)
9,605✔
2153
                return r;
2154
        if (r > 0) {
9,605✔
2155
                x = strjoin("CREDENTIALS_DIRECTORY=", creds_dir);
1,942✔
2156
                if (!x)
1,942✔
2157
                        return -ENOMEM;
2158

2159
                our_env[n_env++] = x;
1,942✔
2160
        }
2161

2162
        if (asprintf(&x, "SYSTEMD_EXEC_PID=" PID_FMT, getpid_cached()) < 0)
9,605✔
2163
                return -ENOMEM;
2164

2165
        our_env[n_env++] = x;
9,605✔
2166

2167
        if (memory_pressure_path) {
9,605✔
2168
                x = strjoin("MEMORY_PRESSURE_WATCH=", memory_pressure_path);
9,207✔
2169
                if (!x)
9,207✔
2170
                        return -ENOMEM;
2171

2172
                our_env[n_env++] = x;
9,207✔
2173

2174
                if (!path_equal(memory_pressure_path, "/dev/null")) {
9,207✔
2175
                        _cleanup_free_ char *b = NULL, *e = NULL;
9,207✔
2176

2177
                        if (asprintf(&b, "%s " USEC_FMT " " USEC_FMT,
9,207✔
2178
                                     MEMORY_PRESSURE_DEFAULT_TYPE,
2179
                                     cgroup_context->memory_pressure_threshold_usec == USEC_INFINITY ? MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC :
9,207✔
2180
                                     CLAMP(cgroup_context->memory_pressure_threshold_usec, 1U, MEMORY_PRESSURE_DEFAULT_WINDOW_USEC),
9,207✔
2181
                                     MEMORY_PRESSURE_DEFAULT_WINDOW_USEC) < 0)
2182
                                return -ENOMEM;
2183

2184
                        if (base64mem(b, strlen(b) + 1, &e) < 0)
9,207✔
2185
                                return -ENOMEM;
2186

2187
                        x = strjoin("MEMORY_PRESSURE_WRITE=", e);
9,207✔
2188
                        if (!x)
9,207✔
2189
                                return -ENOMEM;
2190

2191
                        our_env[n_env++] = x;
9,207✔
2192
                }
2193
        }
2194

2195
        if (p->notify_socket) {
9,605✔
2196
                x = strjoin("NOTIFY_SOCKET=", exec_get_private_notify_socket_path(c, p, needs_sandboxing) ?: p->notify_socket);
1,893✔
2197
                if (!x)
1,893✔
2198
                        return -ENOMEM;
2199

2200
                our_env[n_env++] = x;
1,893✔
2201
        }
2202

2203
        assert(c->private_var_tmp >= 0 && c->private_var_tmp < _PRIVATE_TMP_MAX);
9,605✔
2204
        if (needs_sandboxing && c->private_tmp != c->private_var_tmp) {
9,605✔
2205
                assert(c->private_tmp == PRIVATE_TMP_DISCONNECTED);
284✔
2206
                assert(c->private_var_tmp == PRIVATE_TMP_NO);
284✔
2207

2208
                /* When private tmpfs is enabled only on /tmp/, then explicitly set $TMPDIR to suggest the
2209
                 * service to use /tmp/. */
2210

2211
                x = strdup("TMPDIR=/tmp");
284✔
2212
                if (!x)
284✔
2213
                        return -ENOMEM;
2214

2215
                our_env[n_env++] = x;
284✔
2216
        }
2217

2218
        assert(n_env < N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
9,605✔
2219
#undef N_ENV_VARS
2220

2221
        *ret = TAKE_PTR(our_env);
9,605✔
2222

2223
        return 0;
9,605✔
2224
}
2225

2226
static int build_pass_environment(const ExecContext *c, char ***ret) {
9,605✔
2227
        _cleanup_strv_free_ char **pass_env = NULL;
9,605✔
2228
        size_t n_env = 0;
9,605✔
2229

2230
        assert(c);
9,605✔
2231
        assert(ret);
9,605✔
2232

2233
        STRV_FOREACH(i, c->pass_environment) {
9,907✔
2234
                _cleanup_free_ char *x = NULL;
×
2235
                char *v;
302✔
2236

2237
                v = getenv(*i);
302✔
2238
                if (!v)
302✔
2239
                        continue;
×
2240
                x = strjoin(*i, "=", v);
302✔
2241
                if (!x)
302✔
2242
                        return -ENOMEM;
2243

2244
                if (!GREEDY_REALLOC(pass_env, n_env + 2))
302✔
2245
                        return -ENOMEM;
2246

2247
                pass_env[n_env++] = TAKE_PTR(x);
302✔
2248
                pass_env[n_env] = NULL;
302✔
2249
        }
2250

2251
        *ret = TAKE_PTR(pass_env);
9,605✔
2252
        return 0;
9,605✔
2253
}
2254

2255
static int setup_private_users(PrivateUsers private_users, uid_t ouid, gid_t ogid, uid_t uid, gid_t gid, bool allow_setgroups) {
9,588✔
2256
        _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
9,588✔
2257
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
9,588✔
2258
        _cleanup_close_ int unshare_ready_fd = -EBADF;
9,588✔
2259
        _cleanup_(sigkill_waitp) pid_t pid = 0;
9,588✔
2260
        uint64_t c = 1;
9,588✔
2261
        ssize_t n;
9,588✔
2262
        int r;
9,588✔
2263

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

2274
        if (private_users == PRIVATE_USERS_NO)
9,588✔
2275
                return 0;
2276

2277
        if (private_users == PRIVATE_USERS_IDENTITY) {
52✔
2278
                uid_map = strdup("0 0 65536\n");
4✔
2279
                if (!uid_map)
4✔
2280
                        return -ENOMEM;
2281
        } else if (private_users == PRIVATE_USERS_FULL) {
48✔
2282
                /* Map all UID/GID from original to new user namespace. We can't use `0 0 UINT32_MAX` because
2283
                 * this is the same UID/GID map as the init user namespace and systemd's running_in_userns()
2284
                 * checks whether its in a user namespace by comparing uid_map/gid_map to `0 0 UINT32_MAX`.
2285
                 * Thus, we still map all UIDs/GIDs but do it using two extents to differentiate the new user
2286
                 * namespace from the init namespace:
2287
                 *   0 0 1
2288
                 *   1 1 UINT32_MAX - 1
2289
                 *
2290
                 * systemd will remove the heuristic in running_in_userns() and use namespace inodes in version 258
2291
                 * (PR #35382). But some users may be running a container image with older systemd < 258 so we keep
2292
                 * this uid_map/gid_map hack until version 259 for version N-1 compatibility.
2293
                 *
2294
                 * TODO: Switch to `0 0 UINT32_MAX` in systemd v259.
2295
                 *
2296
                 * Note the kernel defines the UID range between 0 and UINT32_MAX so we map all UIDs even though
2297
                 * the UID range beyond INT32_MAX (e.g. i.e. the range above the signed 32-bit range) is
2298
                 * icky. For example, setfsuid() returns the old UID as signed integer. But units can decide to
2299
                 * use these UIDs/GIDs so we need to map them. */
2300
                r = asprintf(&uid_map, "0 0 1\n"
5✔
2301
                                       "1 1 " UID_FMT "\n", (uid_t) (UINT32_MAX - 1));
2302
                if (r < 0)
5✔
2303
                        return -ENOMEM;
2304
        /* Can only set up multiple mappings with CAP_SETUID. */
2305
        } else if (have_effective_cap(CAP_SETUID) > 0 && uid != ouid && uid_is_valid(uid)) {
43✔
2306
                r = asprintf(&uid_map,
2✔
2307
                             UID_FMT " " UID_FMT " 1\n"     /* Map $OUID → $OUID */
2308
                             UID_FMT " " UID_FMT " 1\n",    /* Map $UID → $UID */
2309
                             ouid, ouid, uid, uid);
2310
                if (r < 0)
2✔
2311
                        return -ENOMEM;
2312
        } else {
2313
                r = asprintf(&uid_map,
41✔
2314
                             UID_FMT " " UID_FMT " 1\n",    /* Map $OUID → $OUID */
2315
                             ouid, ouid);
2316
                if (r < 0)
41✔
2317
                        return -ENOMEM;
2318
        }
2319

2320
        if (private_users == PRIVATE_USERS_IDENTITY) {
52✔
2321
                gid_map = strdup("0 0 65536\n");
4✔
2322
                if (!gid_map)
4✔
2323
                        return -ENOMEM;
2324
        } else if (private_users == PRIVATE_USERS_FULL) {
48✔
2325
                r = asprintf(&gid_map, "0 0 1\n"
5✔
2326
                                       "1 1 " GID_FMT "\n", (gid_t) (UINT32_MAX - 1));
2327
                if (r < 0)
5✔
2328
                        return -ENOMEM;
2329
        /* Can only set up multiple mappings with CAP_SETGID. */
2330
        } else if (have_effective_cap(CAP_SETGID) > 0 && gid != ogid && gid_is_valid(gid)) {
59✔
2331
                r = asprintf(&gid_map,
2✔
2332
                             GID_FMT " " GID_FMT " 1\n"     /* Map $OGID → $OGID */
2333
                             GID_FMT " " GID_FMT " 1\n",    /* Map $GID → $GID */
2334
                             ogid, ogid, gid, gid);
2335
                if (r < 0)
2✔
2336
                        return -ENOMEM;
2337
        } else {
2338
                r = asprintf(&gid_map,
41✔
2339
                             GID_FMT " " GID_FMT " 1\n",    /* Map $OGID -> $OGID */
2340
                             ogid, ogid);
2341
                if (r < 0)
41✔
2342
                        return -ENOMEM;
2343
        }
2344

2345
        /* Create a communication channel so that the parent can tell the child when it finished creating the user
2346
         * namespace. */
2347
        unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
52✔
2348
        if (unshare_ready_fd < 0)
52✔
2349
                return -errno;
×
2350

2351
        /* Create a communication channel so that the child can tell the parent a proper error code in case it
2352
         * failed. */
2353
        if (pipe2(errno_pipe, O_CLOEXEC) < 0)
52✔
2354
                return -errno;
×
2355

2356
        r = safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL, &pid);
52✔
2357
        if (r < 0)
103✔
2358
                return r;
2359
        if (r == 0) {
103✔
2360
                _cleanup_close_ int fd = -EBADF;
×
2361
                const char *a;
51✔
2362
                pid_t ppid;
51✔
2363

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

2367
                ppid = getppid();
51✔
2368
                errno_pipe[0] = safe_close(errno_pipe[0]);
51✔
2369

2370
                /* Wait until the parent unshared the user namespace */
2371
                if (read(unshare_ready_fd, &c, sizeof(c)) < 0)
51✔
2372
                        report_errno_and_exit(errno_pipe[1], -errno);
×
2373

2374
                /* Disable the setgroups() system call in the child user namespace, for good, unless PrivateUsers=full
2375
                 * and using the system service manager. */
2376
                a = procfs_file_alloca(ppid, "setgroups");
51✔
2377
                fd = open(a, O_WRONLY|O_CLOEXEC);
51✔
2378
                if (fd < 0) {
51✔
2379
                        if (errno != ENOENT) {
×
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 the file is missing the kernel is too old, let's continue anyway. */
2385
                } else {
2386
                        const char *setgroups = allow_setgroups ? "allow\n" : "deny\n";
51✔
2387
                        if (write(fd, setgroups, strlen(setgroups)) < 0) {
51✔
2388
                                r = log_debug_errno(errno, "Failed to write '%s' to %s: %m", setgroups, a);
×
2389
                                report_errno_and_exit(errno_pipe[1], r);
×
2390
                        }
2391

2392
                        fd = safe_close(fd);
51✔
2393
                }
2394

2395
                /* First write the GID map */
2396
                a = procfs_file_alloca(ppid, "gid_map");
51✔
2397
                fd = open(a, O_WRONLY|O_CLOEXEC);
51✔
2398
                if (fd < 0) {
51✔
2399
                        r = log_debug_errno(errno, "Failed to open %s: %m", a);
×
2400
                        report_errno_and_exit(errno_pipe[1], r);
×
2401
                }
2402

2403
                if (write(fd, gid_map, strlen(gid_map)) < 0) {
51✔
2404
                        r = log_debug_errno(errno, "Failed to write GID map to %s: %m", a);
×
2405
                        report_errno_and_exit(errno_pipe[1], r);
×
2406
                }
2407

2408
                fd = safe_close(fd);
51✔
2409

2410
                /* The write the UID map */
2411
                a = procfs_file_alloca(ppid, "uid_map");
51✔
2412
                fd = open(a, O_WRONLY|O_CLOEXEC);
51✔
2413
                if (fd < 0) {
51✔
2414
                        r = log_debug_errno(errno, "Failed to open %s: %m", a);
×
2415
                        report_errno_and_exit(errno_pipe[1], r);
×
2416
                }
2417

2418
                if (write(fd, uid_map, strlen(uid_map)) < 0) {
51✔
2419
                        r = log_debug_errno(errno, "Failed to write UID map to %s: %m", a);
×
2420
                        report_errno_and_exit(errno_pipe[1], r);
×
2421
                }
2422

2423
                _exit(EXIT_SUCCESS);
51✔
2424
        }
2425

2426
        errno_pipe[1] = safe_close(errno_pipe[1]);
52✔
2427

2428
        if (unshare(CLONE_NEWUSER) < 0)
52✔
2429
                return log_debug_errno(errno, "Failed to unshare user namespace: %m");
×
2430

2431
        /* Let the child know that the namespace is ready now */
2432
        if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
52✔
2433
                return -errno;
×
2434

2435
        /* Try to read an error code from the child */
2436
        n = read(errno_pipe[0], &r, sizeof(r));
52✔
2437
        if (n < 0)
52✔
2438
                return -errno;
×
2439
        if (n == sizeof(r)) { /* an error code was sent to us */
52✔
2440
                if (r < 0)
×
2441
                        return r;
2442
                return -EIO;
×
2443
        }
2444
        if (n != 0) /* on success we should have read 0 bytes */
52✔
2445
                return -EIO;
2446

2447
        r = wait_for_terminate_and_check("(sd-userns)", TAKE_PID(pid), 0);
52✔
2448
        if (r < 0)
52✔
2449
                return r;
2450
        if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
52✔
2451
                return -EIO;
×
2452

2453
        return 1;
2454
}
2455

2456
static int can_mount_proc(void) {
10✔
2457
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
5✔
2458
        _cleanup_(sigkill_waitp) pid_t pid = 0;
×
2459
        ssize_t n;
10✔
2460
        int r;
10✔
2461

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

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

2471
        /* Fork a child process into its own mount and PID namespace. Note safe_fork() already remounts / as SLAVE
2472
         * with FORK_MOUNTNS_SLAVE. */
2473
        r = safe_fork("(sd-proc-check)",
10✔
2474
                      FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE|FORK_NEW_PIDNS, &pid);
2475
        if (r < 0)
10✔
2476
                return log_debug_errno(r, "Failed to fork child process (sd-proc-check): %m");
×
2477
        if (r == 0) {
10✔
2478
                errno_pipe[0] = safe_close(errno_pipe[0]);
5✔
2479

2480
                /* Try mounting /proc on /dev/shm/. No need to clean up the mount since the mount
2481
                 * namespace will be cleaned up once the process exits. */
2482
                r = mount_follow_verbose(LOG_DEBUG, "proc", "/dev/shm/", "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
5✔
2483
                if (r < 0) {
5✔
2484
                        (void) write(errno_pipe[1], &r, sizeof(r));
1✔
2485
                        _exit(EXIT_FAILURE);
1✔
2486
                }
2487

2488
                _exit(EXIT_SUCCESS);
4✔
2489
        }
2490

2491
        errno_pipe[1] = safe_close(errno_pipe[1]);
5✔
2492

2493
        /* Try to read an error code from the child */
2494
        n = read(errno_pipe[0], &r, sizeof(r));
5✔
2495
        if (n < 0)
5✔
2496
                return log_debug_errno(errno, "Failed to read errno from pipe with child process (sd-proc-check): %m");
×
2497
        if (n == sizeof(r)) { /* an error code was sent to us */
5✔
2498
                /* This is the expected case where proc cannot be mounted due to permissions. */
2499
                if (ERRNO_IS_NEG_PRIVILEGE(r))
5✔
2500
                        return 0;
2501
                if (r < 0)
×
2502
                        return r;
2503

2504
                return -EIO;
×
2505
        }
2506
        if (n != 0) /* on success we should have read 0 bytes */
4✔
2507
                return -EIO;
2508

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

2515
        return 1;
2516
}
2517

2518
static int setup_private_pids(const ExecContext *c, ExecParameters *p) {
9✔
2519
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
×
2520
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
6✔
2521
        ssize_t n;
9✔
2522
        int r, q;
9✔
2523

2524
        assert(c);
9✔
2525
        assert(p);
9✔
2526
        assert(p->pidref_transport_fd >= 0);
9✔
2527

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

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

2538
        /* Set FORK_DETACH to immediately re-parent the child process to the invoking manager process. */
2539
        r = pidref_safe_fork("(sd-pidns-child)", FORK_NEW_PIDNS|FORK_DETACH, &pidref);
9✔
2540
        if (r < 0)
15✔
2541
                return log_debug_errno(r, "Failed to fork child into new pid namespace: %m");
×
2542
        if (r > 0) {
15✔
2543
                errno_pipe[0] = safe_close(errno_pipe[0]);
9✔
2544

2545
                /* In the parent process, we send the child pidref to the manager and exit.
2546
                 * If PIDFD is not supported, only the child PID is sent. The server then
2547
                 * uses the child PID to set the new exec main process. */
2548
                q = send_one_fd_iov(
9✔
2549
                                p->pidref_transport_fd,
2550
                                pidref.fd,
2551
                                &IOVEC_MAKE(&pidref.pid, sizeof(pidref.pid)),
2552
                                /*iovlen=*/ 1,
2553
                                /*flags=*/ 0);
2554
                /* Send error code to child process. */
2555
                (void) write(errno_pipe[1], &q, sizeof(q));
9✔
2556
                /* Exit here so we only go through the destructors in exec_invoke only once - in the child - as
2557
                 * some destructors have external effects. The main codepaths continue in the child process. */
2558
                _exit(q < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
9✔
2559
        }
2560

2561
        errno_pipe[1] = safe_close(errno_pipe[1]);
6✔
2562
        p->pidref_transport_fd = safe_close(p->pidref_transport_fd);
6✔
2563

2564
        /* Try to read an error code from the parent. Note a child process cannot wait for the parent so we always
2565
         * receive an errno even on success. */
2566
        n = read(errno_pipe[0], &r, sizeof(r));
6✔
2567
        if (n < 0)
6✔
2568
                return log_debug_errno(errno, "Failed to read errno from pipe with parent process: %m");
×
2569
        if (n != sizeof(r))
6✔
2570
                return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to read enough bytes from pipe with parent process");
×
2571
        if (r < 0)
6✔
2572
                return log_debug_errno(r, "Failed to send child pidref to manager: %m");
×
2573

2574
        /* NOTE! This function returns in the child process only. */
2575
        return r;
2576
}
2577

2578
static int create_many_symlinks(const char *root, const char *source, char **symlinks) {
1,530✔
2579
        _cleanup_free_ char *src_abs = NULL;
1,530✔
2580
        int r;
1,530✔
2581

2582
        assert(source);
1,530✔
2583

2584
        src_abs = path_join(root, source);
1,530✔
2585
        if (!src_abs)
1,530✔
2586
                return -ENOMEM;
2587

2588
        STRV_FOREACH(dst, symlinks) {
1,543✔
2589
                _cleanup_free_ char *dst_abs = NULL;
13✔
2590

2591
                dst_abs = path_join(root, *dst);
13✔
2592
                if (!dst_abs)
13✔
2593
                        return -ENOMEM;
2594

2595
                r = mkdir_parents_label(dst_abs, 0755);
13✔
2596
                if (r < 0)
13✔
2597
                        return r;
2598

2599
                r = symlink_idempotent(src_abs, dst_abs, true);
13✔
2600
                if (r < 0)
13✔
2601
                        return r;
2602
        }
2603

2604
        return 0;
2605
}
2606

2607
static int setup_exec_directory(
57,756✔
2608
                const ExecContext *context,
2609
                const ExecParameters *params,
2610
                uid_t uid,
2611
                gid_t gid,
2612
                ExecDirectoryType type,
2613
                bool needs_mount_namespace,
2614
                int *exit_status) {
2615

2616
        static const int exit_status_table[_EXEC_DIRECTORY_TYPE_MAX] = {
57,756✔
2617
                [EXEC_DIRECTORY_RUNTIME]       = EXIT_RUNTIME_DIRECTORY,
2618
                [EXEC_DIRECTORY_STATE]         = EXIT_STATE_DIRECTORY,
2619
                [EXEC_DIRECTORY_CACHE]         = EXIT_CACHE_DIRECTORY,
2620
                [EXEC_DIRECTORY_LOGS]          = EXIT_LOGS_DIRECTORY,
2621
                [EXEC_DIRECTORY_CONFIGURATION] = EXIT_CONFIGURATION_DIRECTORY,
2622
        };
2623
        int r;
57,756✔
2624

2625
        assert(context);
57,756✔
2626
        assert(params);
57,756✔
2627
        assert(type >= 0 && type < _EXEC_DIRECTORY_TYPE_MAX);
57,756✔
2628
        assert(exit_status);
57,756✔
2629

2630
        if (!params->prefix[type])
57,756✔
2631
                return 0;
2632

2633
        if (params->flags & EXEC_CHOWN_DIRECTORIES) {
57,756✔
2634
                if (!uid_is_valid(uid))
53,776✔
2635
                        uid = 0;
40,406✔
2636
                if (!gid_is_valid(gid))
53,776✔
2637
                        gid = 0;
40,386✔
2638
        }
2639

2640
        FOREACH_ARRAY(i, context->directories[type].items, context->directories[type].n_items) {
61,465✔
2641
                _cleanup_free_ char *p = NULL, *pp = NULL;
3,710✔
2642

2643
                p = path_join(params->prefix[type], i->path);
3,710✔
2644
                if (!p) {
3,710✔
2645
                        r = -ENOMEM;
×
2646
                        goto fail;
×
2647
                }
2648

2649
                r = mkdir_parents_label(p, 0755);
3,710✔
2650
                if (r < 0)
3,710✔
2651
                        goto fail;
×
2652

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

2655
                        /* If we are in user mode, and a configuration directory exists but a state directory
2656
                         * doesn't exist, then we likely are upgrading from an older systemd version that
2657
                         * didn't know the more recent addition to the xdg-basedir spec: the $XDG_STATE_HOME
2658
                         * directory. In older systemd versions EXEC_DIRECTORY_STATE was aliased to
2659
                         * EXEC_DIRECTORY_CONFIGURATION, with the advent of $XDG_STATE_HOME it is now
2660
                         * separated. If a service has both dirs configured but only the configuration dir
2661
                         * exists and the state dir does not, we assume we are looking at an update
2662
                         * situation. Hence, create a compatibility symlink, so that all expectations are
2663
                         * met.
2664
                         *
2665
                         * (We also do something similar with the log directory, which still doesn't exist in
2666
                         * the xdg basedir spec. We'll make it a subdir of the state dir.) */
2667

2668
                        /* this assumes the state dir is always created before the configuration dir */
2669
                        assert_cc(EXEC_DIRECTORY_STATE < EXEC_DIRECTORY_LOGS);
7✔
2670
                        assert_cc(EXEC_DIRECTORY_LOGS < EXEC_DIRECTORY_CONFIGURATION);
7✔
2671

2672
                        r = access_nofollow(p, F_OK);
7✔
2673
                        if (r == -ENOENT) {
7✔
2674
                                _cleanup_free_ char *q = NULL;
3✔
2675

2676
                                /* OK, we know that the state dir does not exist. Let's see if the dir exists
2677
                                 * under the configuration hierarchy. */
2678

2679
                                if (type == EXEC_DIRECTORY_STATE)
3✔
2680
                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], i->path);
3✔
2681
                                else if (type == EXEC_DIRECTORY_LOGS)
×
2682
                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], "log", i->path);
×
2683
                                else
2684
                                        assert_not_reached();
×
2685
                                if (!q) {
3✔
2686
                                        r = -ENOMEM;
×
2687
                                        goto fail;
×
2688
                                }
2689

2690
                                r = access_nofollow(q, F_OK);
3✔
2691
                                if (r >= 0) {
3✔
2692
                                        /* It does exist! This hence looks like an update. Symlink the
2693
                                         * configuration directory into the state directory. */
2694

2695
                                        r = symlink_idempotent(q, p, /* make_relative= */ true);
1✔
2696
                                        if (r < 0)
1✔
2697
                                                goto fail;
×
2698

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

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

2708
                if (exec_directory_is_private(context, type)) {
3,709✔
2709
                        /* So, here's one extra complication when dealing with DynamicUser=1 units. In that
2710
                         * case we want to avoid leaving a directory around fully accessible that is owned by
2711
                         * a dynamic user whose UID is later on reused. To lock this down we use the same
2712
                         * trick used by container managers to prohibit host users to get access to files of
2713
                         * the same UID in containers: we place everything inside a directory that has an
2714
                         * access mode of 0700 and is owned root:root, so that it acts as security boundary
2715
                         * for unprivileged host code. We then use fs namespacing to make this directory
2716
                         * permeable for the service itself.
2717
                         *
2718
                         * Specifically: for a service which wants a special directory "foo/" we first create
2719
                         * a directory "private/" with access mode 0700 owned by root:root. Then we place
2720
                         * "foo" inside of that directory (i.e. "private/foo/"), and make "foo" a symlink to
2721
                         * "private/foo". This way, privileged host users can access "foo/" as usual, but
2722
                         * unprivileged host users can't look into it. Inside of the namespace of the unit
2723
                         * "private/" is replaced by a more liberally accessible tmpfs, into which the host's
2724
                         * "private/foo/" is mounted under the same name, thus disabling the access boundary
2725
                         * for the service and making sure it only gets access to the dirs it needs but no
2726
                         * others. Tricky? Yes, absolutely, but it works!
2727
                         *
2728
                         * Note that we don't do this for EXEC_DIRECTORY_CONFIGURATION as that's assumed not
2729
                         * to be owned by the service itself.
2730
                         *
2731
                         * Also, note that we don't do this for EXEC_DIRECTORY_RUNTIME as that's often used
2732
                         * for sharing files or sockets with other services. */
2733

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

2740
                        /* First set up private root if it doesn't exist yet, with access mode 0700 and owned by root:root */
2741
                        r = mkdir_safe_label(pp, 0700, 0, 0, MKDIR_WARN_MODE);
13✔
2742
                        if (r < 0)
13✔
2743
                                goto fail;
×
2744

2745
                        if (!path_extend(&pp, i->path)) {
13✔
2746
                                r = -ENOMEM;
×
2747
                                goto fail;
×
2748
                        }
2749

2750
                        /* Create all directories between the configured directory and this private root, and mark them 0755 */
2751
                        r = mkdir_parents_label(pp, 0755);
13✔
2752
                        if (r < 0)
13✔
2753
                                goto fail;
×
2754

2755
                        if (is_dir(p, false) > 0 &&
13✔
2756
                            (access_nofollow(pp, F_OK) == -ENOENT)) {
×
2757

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

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

2766
                                r = RET_NERRNO(rename(p, pp));
×
2767
                                if (r < 0)
×
2768
                                        goto fail;
×
2769
                        } else {
2770
                                /* Otherwise, create the actual directory for the service */
2771

2772
                                r = mkdir_label(pp, context->directories[type].mode);
13✔
2773
                                if (r < 0 && r != -EEXIST)
13✔
2774
                                        goto fail;
×
2775
                        }
2776

2777
                        if (!FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE)) {
13✔
2778
                                /* And link it up from the original place.
2779
                                 * Notes
2780
                                 * 1) If a mount namespace is going to be used, then this symlink remains on
2781
                                 *    the host, and a new one for the child namespace will be created later.
2782
                                 * 2) It is not necessary to create this symlink when one of its parent
2783
                                 *    directories is specified and already created. E.g.
2784
                                 *        StateDirectory=foo foo/bar
2785
                                 *    In that case, the inode points to pp and p for "foo/bar" are the same:
2786
                                 *        pp = "/var/lib/private/foo/bar"
2787
                                 *        p = "/var/lib/foo/bar"
2788
                                 *    and, /var/lib/foo is a symlink to /var/lib/private/foo. So, not only
2789
                                 *    we do not need to create the symlink, but we cannot create the symlink.
2790
                                 *    See issue #24783. */
2791
                                r = symlink_idempotent(pp, p, true);
13✔
2792
                                if (r < 0)
13✔
2793
                                        goto fail;
×
2794
                        }
2795

2796
                } else {
2797
                        _cleanup_free_ char *target = NULL;
3,696✔
2798

2799
                        if (EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type) &&
7,352✔
2800
                            readlink_and_make_absolute(p, &target) >= 0) {
3,656✔
2801
                                _cleanup_free_ char *q = NULL, *q_resolved = NULL, *target_resolved = NULL;
11✔
2802

2803
                                /* This already exists and is a symlink? Interesting. Maybe it's one created
2804
                                 * by DynamicUser=1 (see above)?
2805
                                 *
2806
                                 * We do this for all directory types except for ConfigurationDirectory=,
2807
                                 * since they all support the private/ symlink logic at least in some
2808
                                 * configurations, see above. */
2809

2810
                                r = chase(target, NULL, 0, &target_resolved, NULL);
11✔
2811
                                if (r < 0)
11✔
2812
                                        goto fail;
×
2813

2814
                                q = path_join(params->prefix[type], "private", i->path);
11✔
2815
                                if (!q) {
11✔
2816
                                        r = -ENOMEM;
×
2817
                                        goto fail;
×
2818
                                }
2819

2820
                                /* /var/lib or friends may be symlinks. So, let's chase them also. */
2821
                                r = chase(q, NULL, CHASE_NONEXISTENT, &q_resolved, NULL);
11✔
2822
                                if (r < 0)
11✔
2823
                                        goto fail;
×
2824

2825
                                if (path_equal(q_resolved, target_resolved)) {
11✔
2826

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

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

2834
                                        r = RET_NERRNO(unlink(p));
8✔
2835
                                        if (r < 0)
×
2836
                                                goto fail;
×
2837

2838
                                        r = RET_NERRNO(rename(q, p));
11✔
2839
                                        if (r < 0)
×
2840
                                                goto fail;
×
2841
                                }
2842
                        }
2843

2844
                        r = mkdir_label(p, context->directories[type].mode);
3,696✔
2845
                        if (r < 0) {
3,696✔
2846
                                if (r != -EEXIST)
2,649✔
2847
                                        goto fail;
×
2848

2849
                                if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type)) {
2,649✔
2850
                                        struct stat st;
27✔
2851

2852
                                        /* Don't change the owner/access mode of the configuration directory,
2853
                                         * as in the common case it is not written to by a service, and shall
2854
                                         * not be writable. */
2855

2856
                                        r = RET_NERRNO(stat(p, &st));
27✔
2857
                                        if (r < 0)
×
2858
                                                goto fail;
×
2859

2860
                                        /* Still complain if the access mode doesn't match */
2861
                                        if (((st.st_mode ^ context->directories[type].mode) & 07777) != 0)
27✔
2862
                                                log_warning("%s \'%s\' already exists but the mode is different. "
×
2863
                                                            "(File system: %o %sMode: %o)",
2864
                                                            exec_directory_type_to_string(type), i->path,
2865
                                                            st.st_mode & 07777, exec_directory_type_to_string(type), context->directories[type].mode & 07777);
2866

2867
                                        continue;
27✔
2868
                                }
2869
                        }
2870
                }
2871

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

2880
                /* Skip the rest (which deals with ownership) in user mode, since ownership changes are not
2881
                 * available to user code anyway */
2882
                if (params->runtime_scope != RUNTIME_SCOPE_SYSTEM)
3,682✔
2883
                        continue;
9✔
2884

2885
                int idmapping_supported = is_idmapping_supported(target_dir);
3,673✔
2886
                if (idmapping_supported < 0) {
3,673✔
2887
                        r = log_debug_errno(idmapping_supported, "Unable to determine if ID mapping is supported on mount '%s': %m", target_dir);
×
2888
                        goto fail;
×
2889
                }
2890

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

2893
                /* Change the ownership of the whole tree, if necessary. When dynamic users are used we
2894
                 * drop the suid/sgid bits, since we really don't want SUID/SGID files for dynamic UID/GID
2895
                 * assignments to exist. */
2896
                uid_t chown_uid = uid;
3,673✔
2897
                gid_t chown_gid = gid;
3,673✔
2898
                bool do_chown = false;
3,673✔
2899

2900
                if (uid == 0 || gid == 0 || !idmapping_supported) {
3,673✔
2901
                        do_chown = true;
1,428✔
2902
                        i->idmapped = false;
1,428✔
2903
                } else {
2904
                        /* Use 'nobody' uid/gid for exec directories if ID-mapping is supported. For backward compatibility,
2905
                         * continue doing chmod/chown if the directory was chmod/chowned before (if uid/gid is not 'nobody') */
2906
                        struct stat st;
2,245✔
2907
                        r = RET_NERRNO(stat(target_dir, &st));
2,245✔
2908
                        if (r < 0)
×
2909
                                goto fail;
×
2910

2911
                        if (st.st_uid == UID_NOBODY && st.st_gid == GID_NOBODY) {
2,245✔
2912
                                do_chown = false;
7✔
2913
                                i->idmapped = true;
7✔
2914
                       } else if (exec_directory_is_private(context, type) && st.st_uid == 0 && st.st_gid == 0) {
2,238✔
2915
                                chown_uid = UID_NOBODY;
6✔
2916
                                chown_gid = GID_NOBODY;
6✔
2917
                                do_chown = true;
6✔
2918
                                i->idmapped = true;
6✔
2919
                        } else {
2920
                                do_chown = true;
2,232✔
2921
                                i->idmapped = false;
2,232✔
2922
                        }
2923
                }
2924

2925
                if (do_chown) {
3,673✔
2926
                        r = path_chown_recursive(target_dir, chown_uid, chown_gid, context->dynamic_user ? 01777 : 07777, AT_SYMLINK_FOLLOW);
7,323✔
2927
                        if (r < 0)
3,666✔
2928
                                goto fail;
1✔
2929
                }
2930
        }
2931

2932
        /* If we are not going to run in a namespace, set up the symlinks - otherwise
2933
         * they are set up later, to allow configuring empty var/run/etc. */
2934
        if (!needs_mount_namespace)
57,755✔
2935
                FOREACH_ARRAY(i, context->directories[type].items, context->directories[type].n_items) {
46,095✔
2936
                        r = create_many_symlinks(params->prefix[type], i->path, i->symlinks);
1,530✔
2937
                        if (r < 0)
1,530✔
2938
                                goto fail;
×
2939
                }
2940

2941
        return 0;
2942

2943
fail:
1✔
2944
        *exit_status = exit_status_table[type];
1✔
2945
        return r;
1✔
2946
}
2947

2948
#if ENABLE_SMACK
2949
static int setup_smack(
×
2950
                const ExecContext *context,
2951
                const ExecParameters *params,
2952
                int executable_fd) {
2953
        int r;
×
2954

2955
        assert(context);
×
2956
        assert(params);
×
2957
        assert(executable_fd >= 0);
×
2958

2959
        if (context->smack_process_label) {
×
2960
                r = mac_smack_apply_pid(0, context->smack_process_label);
×
2961
                if (r < 0)
×
2962
                        return r;
×
2963
        } else if (params->fallback_smack_process_label) {
×
2964
                _cleanup_free_ char *exec_label = NULL;
×
2965

2966
                r = mac_smack_read_fd(executable_fd, SMACK_ATTR_EXEC, &exec_label);
×
2967
                if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
×
2968
                        return r;
2969

2970
                r = mac_smack_apply_pid(0, exec_label ?: params->fallback_smack_process_label);
×
2971
                if (r < 0)
×
2972
                        return r;
2973
        }
2974

2975
        return 0;
2976
}
2977
#endif
2978

2979
static int compile_bind_mounts(
2,017✔
2980
                const ExecContext *context,
2981
                const ExecParameters *params,
2982
                uid_t exec_directory_uid, /* only used for id-mapped mounts Exec directories */
2983
                gid_t exec_directory_gid, /* only used for id-mapped mounts Exec directories */
2984
                BindMount **ret_bind_mounts,
2985
                size_t *ret_n_bind_mounts,
2986
                char ***ret_empty_directories) {
2987

2988
        _cleanup_strv_free_ char **empty_directories = NULL;
2,017✔
2989
        BindMount *bind_mounts = NULL;
2,017✔
2990
        size_t n, h = 0;
2,017✔
2991
        int r;
2,017✔
2992

2993
        assert(context);
2,017✔
2994
        assert(params);
2,017✔
2995
        assert(ret_bind_mounts);
2,017✔
2996
        assert(ret_n_bind_mounts);
2,017✔
2997
        assert(ret_empty_directories);
2,017✔
2998

2999
        CLEANUP_ARRAY(bind_mounts, h, bind_mount_free_many);
2,017✔
3000

3001
        n = context->n_bind_mounts;
2,017✔
3002
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
12,102✔
3003
                if (!params->prefix[t])
10,085✔
3004
                        continue;
×
3005

3006
                FOREACH_ARRAY(i, context->directories[t].items, context->directories[t].n_items)
11,673✔
3007
                        n += !FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE) || FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY);
1,588✔
3008
        }
3009

3010
        if (n <= 0) {
2,017✔
3011
                *ret_bind_mounts = NULL;
1,093✔
3012
                *ret_n_bind_mounts = 0;
1,093✔
3013
                *ret_empty_directories = NULL;
1,093✔
3014
                return 0;
1,093✔
3015
        }
3016

3017
        bind_mounts = new(BindMount, n);
924✔
3018
        if (!bind_mounts)
924✔
3019
                return -ENOMEM;
3020

3021
        FOREACH_ARRAY(item, context->bind_mounts, context->n_bind_mounts) {
946✔
3022
                r = bind_mount_add(&bind_mounts, &h, item);
22✔
3023
                if (r < 0)
22✔
3024
                        return r;
3025
        }
3026

3027
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
5,544✔
3028
                if (!params->prefix[t])
4,620✔
3029
                        continue;
×
3030

3031
                if (context->directories[t].n_items == 0)
4,620✔
3032
                        continue;
3,488✔
3033

3034
                if (exec_directory_is_private(context, t) &&
1,145✔
3035
                    !exec_context_with_rootfs(context)) {
13✔
3036
                        char *private_root;
13✔
3037

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

3042
                        private_root = path_join(params->prefix[t], "private");
13✔
3043
                        if (!private_root)
13✔
3044
                                return -ENOMEM;
3045

3046
                        r = strv_consume(&empty_directories, private_root);
13✔
3047
                        if (r < 0)
13✔
3048
                                return r;
3049
                }
3050

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

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

3061
                        if (exec_directory_is_private(context, t))
1,588✔
3062
                                s = path_join(params->prefix[t], "private", i->path);
13✔
3063
                        else
3064
                                s = path_join(params->prefix[t], i->path);
1,575✔
3065
                        if (!s)
1,588✔
3066
                                return -ENOMEM;
3067

3068
                        if (exec_directory_is_private(context, t) &&
1,601✔
3069
                            exec_context_with_rootfs(context))
13✔
3070
                                /* When RootDirectory= or RootImage= are set, then the symbolic link to the private
3071
                                 * directory is not created on the root directory. So, let's bind-mount the directory
3072
                                 * on the 'non-private' place. */
3073
                                d = path_join(params->prefix[t], i->path);
×
3074
                        else
3075
                                d = strdup(s);
1,588✔
3076
                        if (!d)
1,588✔
3077
                                return -ENOMEM;
3078

3079
                        bind_mounts[h++] = (BindMount) {
1,588✔
3080
                                .source = TAKE_PTR(s),
1,588✔
3081
                                .destination = TAKE_PTR(d),
1,588✔
3082
                                .nosuid = context->dynamic_user, /* don't allow suid/sgid when DynamicUser= is on */
1,588✔
3083
                                .recursive = true,
3084
                                .read_only = FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY),
1,588✔
3085
                                .idmapped = i->idmapped,
1,588✔
3086
                                .uid = exec_directory_uid,
3087
                                .gid = exec_directory_gid,
3088
                        };
3089
                }
3090
        }
3091

3092
        assert(h == n);
924✔
3093

3094
        *ret_bind_mounts = TAKE_PTR(bind_mounts);
924✔
3095
        *ret_n_bind_mounts = n;
924✔
3096
        *ret_empty_directories = TAKE_PTR(empty_directories);
924✔
3097

3098
        return (int) n;
924✔
3099
}
3100

3101
/* ret_symlinks will contain a list of pairs src:dest that describes
3102
 * the symlinks to create later on. For example, the symlinks needed
3103
 * to safely give private directories to DynamicUser=1 users. */
3104
static int compile_symlinks(
2,017✔
3105
                const ExecContext *context,
3106
                const ExecParameters *params,
3107
                bool setup_os_release_symlink,
3108
                char ***ret_symlinks) {
3109

3110
        _cleanup_strv_free_ char **symlinks = NULL;
2,017✔
3111
        int r;
2,017✔
3112

3113
        assert(context);
2,017✔
3114
        assert(params);
2,017✔
3115
        assert(ret_symlinks);
2,017✔
3116

3117
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++)
12,102✔
3118
                FOREACH_ARRAY(i, context->directories[dt].items, context->directories[dt].n_items) {
11,673✔
3119
                        _cleanup_free_ char *private_path = NULL, *path = NULL;
1,575✔
3120

3121
                        STRV_FOREACH(symlink, i->symlinks) {
1,714✔
3122
                                _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;
126✔
3123

3124
                                src_abs = path_join(params->prefix[dt], i->path);
126✔
3125
                                dst_abs = path_join(params->prefix[dt], *symlink);
126✔
3126
                                if (!src_abs || !dst_abs)
126✔
3127
                                        return -ENOMEM;
3128

3129
                                r = strv_consume_pair(&symlinks, TAKE_PTR(src_abs), TAKE_PTR(dst_abs));
126✔
3130
                                if (r < 0)
126✔
3131
                                        return r;
3132
                        }
3133

3134
                        if (!exec_directory_is_private(context, dt) ||
1,601✔
3135
                            exec_context_with_rootfs(context) ||
13✔
3136
                            FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE))
13✔
3137
                                continue;
1,575✔
3138

3139
                        private_path = path_join(params->prefix[dt], "private", i->path);
13✔
3140
                        if (!private_path)
13✔
3141
                                return -ENOMEM;
3142

3143
                        path = path_join(params->prefix[dt], i->path);
13✔
3144
                        if (!path)
13✔
3145
                                return -ENOMEM;
3146

3147
                        r = strv_consume_pair(&symlinks, TAKE_PTR(private_path), TAKE_PTR(path));
13✔
3148
                        if (r < 0)
13✔
3149
                                return r;
3150
                }
3151

3152
        /* We make the host's os-release available via a symlink, so that we can copy it atomically
3153
         * and readers will never get a half-written version. Note that, while the paths specified here are
3154
         * absolute, when they are processed in namespace.c they will be made relative automatically, i.e.:
3155
         * 'os-release -> .os-release-stage/os-release' is what will be created. */
3156
        if (setup_os_release_symlink) {
2,017✔
3157
                r = strv_extend_many(
7✔
3158
                                &symlinks,
3159
                                "/run/host/.os-release-stage/os-release",
3160
                                "/run/host/os-release");
3161
                if (r < 0)
7✔
3162
                        return r;
3163
        }
3164

3165
        *ret_symlinks = TAKE_PTR(symlinks);
2,017✔
3166

3167
        return 0;
2,017✔
3168
}
3169

3170
static bool insist_on_sandboxing(
×
3171
                const ExecContext *context,
3172
                const char *root_dir,
3173
                const char *root_image,
3174
                const BindMount *bind_mounts,
3175
                size_t n_bind_mounts) {
3176

3177
        assert(context);
×
3178
        assert(n_bind_mounts == 0 || bind_mounts);
×
3179

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

3184
        if (context->n_temporary_filesystems > 0)
×
3185
                return true;
3186

3187
        if (root_dir || root_image)
×
3188
                return true;
3189

3190
        if (context->n_mount_images > 0)
×
3191
                return true;
3192

3193
        if (context->dynamic_user)
×
3194
                return true;
3195

3196
        if (context->n_extension_images > 0 || !strv_isempty(context->extension_directories))
×
3197
                return true;
3198

3199
        /* If there are any bind mounts set that don't map back onto themselves, fs namespacing becomes
3200
         * essential. */
3201
        FOREACH_ARRAY(i, bind_mounts, n_bind_mounts)
×
3202
                if (!path_equal(i->source, i->destination))
×
3203
                        return true;
3204

3205
        if (context->log_namespace)
×
3206
                return true;
×
3207

3208
        return false;
3209
}
3210

3211
static int setup_ephemeral(
2,017✔
3212
                const ExecContext *context,
3213
                ExecRuntime *runtime,
3214
                char **root_image,            /* both input and output! modified if ephemeral logic enabled */
3215
                char **root_directory,        /* ditto */
3216
                char **reterr_path) {
3217

3218
        _cleanup_close_ int fd = -EBADF;
2,017✔
3219
        _cleanup_free_ char *new_root = NULL;
2,017✔
3220
        int r;
2,017✔
3221

3222
        assert(context);
2,017✔
3223
        assert(runtime);
2,017✔
3224
        assert(root_image);
2,017✔
3225
        assert(root_directory);
2,017✔
3226

3227
        if (!*root_image && !*root_directory)
2,017✔
3228
                return 0;
3229

3230
        if (!runtime->ephemeral_copy)
8✔
3231
                return 0;
3232

3233
        assert(runtime->ephemeral_storage_socket[0] >= 0);
×
3234
        assert(runtime->ephemeral_storage_socket[1] >= 0);
×
3235

3236
        new_root = strdup(runtime->ephemeral_copy);
×
3237
        if (!new_root)
×
3238
                return log_oom_debug();
×
3239

3240
        r = posix_lock(runtime->ephemeral_storage_socket[0], LOCK_EX);
×
3241
        if (r < 0)
×
3242
                return log_debug_errno(r, "Failed to lock ephemeral storage socket: %m");
×
3243

3244
        CLEANUP_POSIX_UNLOCK(runtime->ephemeral_storage_socket[0]);
×
3245

3246
        fd = receive_one_fd(runtime->ephemeral_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
×
3247
        if (fd >= 0)
×
3248
                /* We got an fd! That means ephemeral has already been set up, so nothing to do here. */
3249
                return 0;
3250
        if (fd != -EAGAIN)
×
3251
                return log_debug_errno(fd, "Failed to receive file descriptor queued on ephemeral storage socket: %m");
×
3252

3253
        if (*root_image) {
×
3254
                log_debug("Making ephemeral copy of %s to %s", *root_image, new_root);
×
3255

3256
                fd = copy_file(*root_image, new_root, O_EXCL, 0600,
×
3257
                               COPY_LOCK_BSD|COPY_REFLINK|COPY_CRTIME|COPY_NOCOW_AFTER);
3258
                if (fd < 0) {
×
3259
                        *reterr_path = strdup(*root_image);
×
3260
                        return log_debug_errno(fd, "Failed to copy image %s to %s: %m",
×
3261
                                               *root_image, new_root);
3262
                }
3263
        } else {
3264
                assert(*root_directory);
×
3265

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

3268
                fd = btrfs_subvol_snapshot_at(
×
3269
                                AT_FDCWD, *root_directory,
3270
                                AT_FDCWD, new_root,
3271
                                BTRFS_SNAPSHOT_FALLBACK_COPY |
3272
                                BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
3273
                                BTRFS_SNAPSHOT_RECURSIVE |
3274
                                BTRFS_SNAPSHOT_LOCK_BSD);
3275
                if (fd < 0) {
×
3276
                        *reterr_path = strdup(*root_directory);
×
3277
                        return log_debug_errno(fd, "Failed to snapshot directory %s to %s: %m",
×
3278
                                               *root_directory, new_root);
3279
                }
3280
        }
3281

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

3286
        if (*root_image)
×
3287
                free_and_replace(*root_image, new_root);
×
3288
        else {
3289
                assert(*root_directory);
×
3290
                free_and_replace(*root_directory, new_root);
×
3291
        }
3292

3293
        return 1;
3294
}
3295

3296
static int verity_settings_prepare(
7✔
3297
                VeritySettings *verity,
3298
                const char *root_image,
3299
                const void *root_hash,
3300
                size_t root_hash_size,
3301
                const char *root_hash_path,
3302
                const void *root_hash_sig,
3303
                size_t root_hash_sig_size,
3304
                const char *root_hash_sig_path,
3305
                const char *verity_data_path) {
3306

3307
        int r;
7✔
3308

3309
        assert(verity);
7✔
3310

3311
        if (root_hash) {
7✔
3312
                void *d;
4✔
3313

3314
                d = memdup(root_hash, root_hash_size);
4✔
3315
                if (!d)
4✔
3316
                        return -ENOMEM;
7✔
3317

3318
                free_and_replace(verity->root_hash, d);
4✔
3319
                verity->root_hash_size = root_hash_size;
4✔
3320
                verity->designator = PARTITION_ROOT;
4✔
3321
        }
3322

3323
        if (root_hash_sig) {
7✔
3324
                void *d;
×
3325

3326
                d = memdup(root_hash_sig, root_hash_sig_size);
×
3327
                if (!d)
×
3328
                        return -ENOMEM;
7✔
3329

3330
                free_and_replace(verity->root_hash_sig, d);
×
3331
                verity->root_hash_sig_size = root_hash_sig_size;
×
3332
                verity->designator = PARTITION_ROOT;
×
3333
        }
3334

3335
        if (verity_data_path) {
7✔
3336
                r = free_and_strdup(&verity->data_path, verity_data_path);
×
3337
                if (r < 0)
×
3338
                        return r;
3339
        }
3340

3341
        r = verity_settings_load(
7✔
3342
                        verity,
3343
                        root_image,
3344
                        root_hash_path,
3345
                        root_hash_sig_path);
3346
        if (r < 0)
7✔
3347
                return log_debug_errno(r, "Failed to load root hash: %m");
×
3348

3349
        return 0;
3350
}
3351

3352
static int pick_versions(
2,019✔
3353
                const ExecContext *context,
3354
                const ExecParameters *params,
3355
                char **ret_root_image,
3356
                char **ret_root_directory,
3357
                char **reterr_path) {
3358

3359
        int r;
2,019✔
3360

3361
        assert(context);
2,019✔
3362
        assert(params);
2,019✔
3363
        assert(ret_root_image);
2,019✔
3364
        assert(ret_root_directory);
2,019✔
3365

3366
        if (context->root_image) {
2,019✔
3367
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
8✔
3368

3369
                r = path_pick(/* toplevel_path= */ NULL,
16✔
3370
                              /* toplevel_fd= */ AT_FDCWD,
3371
                              context->root_image,
8✔
3372
                              &pick_filter_image_raw,
3373
                              PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3374
                              &result);
3375
                if (r < 0) {
8✔
3376
                        *reterr_path = strdup(context->root_image);
1✔
3377
                        return r;
1✔
3378
                }
3379

3380
                if (!result.path) {
7✔
3381
                        *reterr_path = strdup(context->root_image);
×
3382
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_image);
×
3383
                }
3384

3385
                *ret_root_image = TAKE_PTR(result.path);
7✔
3386
                *ret_root_directory = NULL;
7✔
3387
                return r;
7✔
3388
        }
3389

3390
        if (context->root_directory) {
2,011✔
3391
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
2✔
3392

3393
                r = path_pick(/* toplevel_path= */ NULL,
4✔
3394
                              /* toplevel_fd= */ AT_FDCWD,
3395
                              context->root_directory,
2✔
3396
                              &pick_filter_image_dir,
3397
                              PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3398
                              &result);
3399
                if (r < 0) {
2✔
3400
                        *reterr_path = strdup(context->root_directory);
×
3401
                        return r;
×
3402
                }
3403

3404
                if (!result.path) {
2✔
3405
                        *reterr_path = strdup(context->root_directory);
1✔
3406
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_directory);
1✔
3407
                }
3408

3409
                *ret_root_image = NULL;
1✔
3410
                *ret_root_directory = TAKE_PTR(result.path);
1✔
3411
                return r;
1✔
3412
        }
3413

3414
        *ret_root_image = *ret_root_directory = NULL;
2,009✔
3415
        return 0;
2,009✔
3416
}
3417

3418
static int apply_mount_namespace(
2,019✔
3419
                ExecCommandFlags command_flags,
3420
                const ExecContext *context,
3421
                const ExecParameters *params,
3422
                ExecRuntime *runtime,
3423
                const char *memory_pressure_path,
3424
                bool needs_sandboxing,
3425
                char **reterr_path,
3426
                uid_t exec_directory_uid,
3427
                gid_t exec_directory_gid) {
3428

3429
        _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
2,019✔
3430
        _cleanup_strv_free_ char **empty_directories = NULL, **symlinks = NULL,
2,019✔
3431
                        **read_write_paths_cleanup = NULL;
×
3432
        _cleanup_free_ char *creds_path = NULL, *incoming_dir = NULL, *propagate_dir = NULL,
×
3433
                *private_namespace_dir = NULL, *host_os_release_stage = NULL, *root_image = NULL, *root_dir = NULL;
2,019✔
3434
        const char *tmp_dir = NULL, *var_tmp_dir = NULL;
2,019✔
3435
        char **read_write_paths;
2,019✔
3436
        bool setup_os_release_symlink;
2,019✔
3437
        BindMount *bind_mounts = NULL;
2,019✔
3438
        size_t n_bind_mounts = 0;
2,019✔
3439
        int r;
2,019✔
3440

3441
        assert(context);
2,019✔
3442
        assert(params);
2,019✔
3443
        assert(runtime);
2,019✔
3444

3445
        CLEANUP_ARRAY(bind_mounts, n_bind_mounts, bind_mount_free_many);
2,019✔
3446

3447
        if (params->flags & EXEC_APPLY_CHROOT) {
2,019✔
3448
                r = pick_versions(
2,019✔
3449
                                context,
3450
                                params,
3451
                                &root_image,
3452
                                &root_dir,
3453
                                reterr_path);
3454
                if (r < 0)
2,019✔
3455
                        return r;
3456

3457
                r = setup_ephemeral(
2,017✔
3458
                                context,
3459
                                runtime,
3460
                                &root_image,
3461
                                &root_dir,
3462
                                reterr_path);
3463
                if (r < 0)
2,017✔
3464
                        return r;
3465
        }
3466

3467
        r = compile_bind_mounts(context, params, exec_directory_uid, exec_directory_gid, &bind_mounts, &n_bind_mounts, &empty_directories);
2,017✔
3468
        if (r < 0)
2,017✔
3469
                return r;
3470

3471
        /* We need to make the pressure path writable even if /sys/fs/cgroups is made read-only, as the
3472
         * service will need to write to it in order to start the notifications. */
3473
        if (exec_is_cgroup_mount_read_only(context) && memory_pressure_path && !streq(memory_pressure_path, "/dev/null")) {
2,017✔
3474
                read_write_paths_cleanup = strv_copy(context->read_write_paths);
1,139✔
3475
                if (!read_write_paths_cleanup)
1,139✔
3476
                        return -ENOMEM;
3477

3478
                r = strv_extend(&read_write_paths_cleanup, memory_pressure_path);
1,139✔
3479
                if (r < 0)
1,139✔
3480
                        return r;
3481

3482
                read_write_paths = read_write_paths_cleanup;
1,139✔
3483
        } else
3484
                read_write_paths = context->read_write_paths;
878✔
3485

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

3491
                if (context->private_tmp == PRIVATE_TMP_CONNECTED && runtime->shared) {
2,016✔
3492
                        if (streq_ptr(runtime->shared->tmp_dir, RUN_SYSTEMD_EMPTY))
324✔
3493
                                tmp_dir = runtime->shared->tmp_dir;
3494
                        else if (runtime->shared->tmp_dir)
324✔
3495
                                tmp_dir = strjoina(runtime->shared->tmp_dir, "/tmp");
1,620✔
3496

3497
                        if (streq_ptr(runtime->shared->var_tmp_dir, RUN_SYSTEMD_EMPTY))
324✔
3498
                                var_tmp_dir = runtime->shared->var_tmp_dir;
3499
                        else if (runtime->shared->var_tmp_dir)
324✔
3500
                                var_tmp_dir = strjoina(runtime->shared->var_tmp_dir, "/tmp");
1,620✔
3501
                }
3502
        }
3503

3504
        /* Symlinks (exec dirs, os-release) are set up after other mounts, before they are made read-only. */
3505
        setup_os_release_symlink = needs_sandboxing && exec_context_get_effective_mount_apivfs(context) && (root_dir || root_image);
2,016✔
3506
        r = compile_symlinks(context, params, setup_os_release_symlink, &symlinks);
2,017✔
3507
        if (r < 0)
2,017✔
3508
                return r;
3509

3510
        if (context->mount_propagation_flag == MS_SHARED)
2,017✔
3511
                log_debug("shared mount propagation hidden by other fs namespacing unit settings: ignoring");
×
3512

3513
        r = exec_context_get_credential_directory(context, params, params->unit_id, &creds_path);
2,017✔
3514
        if (r < 0)
2,017✔
3515
                return r;
3516

3517
        if (params->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
2,017✔
3518
                propagate_dir = path_join("/run/systemd/propagate/", params->unit_id);
1,990✔
3519
                if (!propagate_dir)
1,990✔
3520
                        return -ENOMEM;
3521

3522
                incoming_dir = strdup("/run/systemd/incoming");
1,990✔
3523
                if (!incoming_dir)
1,990✔
3524
                        return -ENOMEM;
3525

3526
                private_namespace_dir = strdup("/run/systemd");
1,990✔
3527
                if (!private_namespace_dir)
1,990✔
3528
                        return -ENOMEM;
3529

3530
                /* If running under a different root filesystem, propagate the host's os-release. We make a
3531
                 * copy rather than just bind mounting it, so that it can be updated on soft-reboot. */
3532
                if (setup_os_release_symlink) {
1,990✔
3533
                        host_os_release_stage = strdup("/run/systemd/propagate/.os-release-stage");
7✔
3534
                        if (!host_os_release_stage)
7✔
3535
                                return -ENOMEM;
3536
                }
3537
        } else {
3538
                assert(params->runtime_scope == RUNTIME_SCOPE_USER);
27✔
3539

3540
                if (asprintf(&private_namespace_dir, "/run/user/" UID_FMT "/systemd", geteuid()) < 0)
27✔
3541
                        return -ENOMEM;
3542

3543
                if (setup_os_release_symlink) {
27✔
3544
                        if (asprintf(&host_os_release_stage,
×
3545
                                     "/run/user/" UID_FMT "/systemd/propagate/.os-release-stage",
3546
                                     geteuid()) < 0)
3547
                                return -ENOMEM;
3548
                }
3549
        }
3550

3551
        if (root_image) {
2,017✔
3552
                r = verity_settings_prepare(
14✔
3553
                        &verity,
3554
                        root_image,
3555
                        context->root_hash, context->root_hash_size, context->root_hash_path,
7✔
3556
                        context->root_hash_sig, context->root_hash_sig_size, context->root_hash_sig_path,
7✔
3557
                        context->root_verity);
7✔
3558
                if (r < 0)
7✔
3559
                        return r;
3560
        }
3561

3562
        NamespaceParameters parameters = {
1✔
3563
                .runtime_scope = params->runtime_scope,
2,017✔
3564

3565
                .root_directory = root_dir,
3566
                .root_image = root_image,
3567
                .root_image_options = context->root_image_options,
2,017✔
3568
                .root_image_policy = context->root_image_policy ?: &image_policy_service,
2,017✔
3569

3570
                .read_write_paths = read_write_paths,
3571
                .read_only_paths = needs_sandboxing ? context->read_only_paths : NULL,
2,017✔
3572
                .inaccessible_paths = needs_sandboxing ? context->inaccessible_paths : NULL,
2,016✔
3573

3574
                .exec_paths = needs_sandboxing ? context->exec_paths : NULL,
2,016✔
3575
                .no_exec_paths = needs_sandboxing ? context->no_exec_paths : NULL,
2,016✔
3576

3577
                .empty_directories = empty_directories,
3578
                .symlinks = symlinks,
3579

3580
                .bind_mounts = bind_mounts,
3581
                .n_bind_mounts = n_bind_mounts,
3582

3583
                .temporary_filesystems = context->temporary_filesystems,
2,017✔
3584
                .n_temporary_filesystems = context->n_temporary_filesystems,
2,017✔
3585

3586
                .mount_images = context->mount_images,
2,017✔
3587
                .n_mount_images = context->n_mount_images,
2,017✔
3588
                .mount_image_policy = context->mount_image_policy ?: &image_policy_service,
2,017✔
3589

3590
                .tmp_dir = tmp_dir,
3591
                .var_tmp_dir = var_tmp_dir,
3592

3593
                .creds_path = creds_path,
3594
                .log_namespace = context->log_namespace,
2,017✔
3595
                .mount_propagation_flag = context->mount_propagation_flag,
2,017✔
3596

3597
                .verity = &verity,
3598

3599
                .extension_images = context->extension_images,
2,017✔
3600
                .n_extension_images = context->n_extension_images,
2,017✔
3601
                .extension_image_policy = context->extension_image_policy ?: &image_policy_sysext,
2,017✔
3602
                .extension_directories = context->extension_directories,
2,017✔
3603

3604
                .propagate_dir = propagate_dir,
3605
                .incoming_dir = incoming_dir,
3606
                .private_namespace_dir = private_namespace_dir,
3607
                .host_notify_socket = params->notify_socket,
2,017✔
3608
                .notify_socket_path = exec_get_private_notify_socket_path(context, params, needs_sandboxing),
2,017✔
3609
                .host_os_release_stage = host_os_release_stage,
3610

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

3616
                .protect_control_groups = needs_sandboxing ? exec_get_protect_control_groups(context) : PROTECT_CONTROL_GROUPS_NO,
2,016✔
3617
                .protect_kernel_tunables = needs_sandboxing && context->protect_kernel_tunables,
2,016✔
3618
                .protect_kernel_modules = needs_sandboxing && context->protect_kernel_modules,
2,016✔
3619
                .protect_kernel_logs = needs_sandboxing && context->protect_kernel_logs,
2,016✔
3620

3621
                .private_dev = needs_sandboxing && context->private_devices,
2,016✔
3622
                .private_network = needs_sandboxing && exec_needs_network_namespace(context),
2,016✔
3623
                .private_ipc = needs_sandboxing && exec_needs_ipc_namespace(context),
2,016✔
3624
                .private_pids = needs_sandboxing && exec_needs_pid_namespace(context) ? context->private_pids : PRIVATE_PIDS_NO,
2,016✔
3625
                .private_tmp = needs_sandboxing ? context->private_tmp : PRIVATE_TMP_NO,
2,016✔
3626
                .private_var_tmp = needs_sandboxing ? context->private_var_tmp : PRIVATE_TMP_NO,
2,016✔
3627

3628
                .mount_apivfs = needs_sandboxing && exec_context_get_effective_mount_apivfs(context),
2,016✔
3629
                .bind_log_sockets = needs_sandboxing && exec_context_get_effective_bind_log_sockets(context),
2,016✔
3630

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

3634
                .protect_home = needs_sandboxing ? context->protect_home : PROTECT_HOME_NO,
2,016✔
3635
                .protect_hostname = needs_sandboxing ? context->protect_hostname : PROTECT_HOSTNAME_NO,
2,016✔
3636
                .protect_system = needs_sandboxing ? context->protect_system : PROTECT_SYSTEM_NO,
2,016✔
3637
                .protect_proc = needs_sandboxing ? context->protect_proc : PROTECT_PROC_DEFAULT,
2,016✔
3638
                .proc_subset = needs_sandboxing ? context->proc_subset : PROC_SUBSET_ALL,
2,016✔
3639
        };
3640

3641
        r = setup_namespace(&parameters, reterr_path);
2,017✔
3642
        /* If we couldn't set up the namespace this is probably due to a missing capability. setup_namespace() reports
3643
         * that with a special, recognizable error ENOANO. In this case, silently proceed, but only if exclusively
3644
         * sandboxing options were used, i.e. nothing such as RootDirectory= or BindMount= that would result in a
3645
         * completely different execution environment. */
3646
        if (r == -ENOANO) {
2,017✔
3647
                if (insist_on_sandboxing(
×
3648
                                    context,
3649
                                    root_dir, root_image,
3650
                                    bind_mounts,
3651
                                    n_bind_mounts))
3652
                        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
×
3653
                                               "Failed to set up namespace, and refusing to continue since "
3654
                                               "the selected namespacing options alter mount environment non-trivially.\n"
3655
                                               "Bind mounts: %zu, temporary filesystems: %zu, root directory: %s, root image: %s, dynamic user: %s",
3656
                                               n_bind_mounts,
3657
                                               context->n_temporary_filesystems,
3658
                                               yes_no(root_dir),
3659
                                               yes_no(root_image),
3660
                                               yes_no(context->dynamic_user));
3661

3662
                log_debug("Failed to set up namespace, assuming containerized execution and ignoring.");
×
3663
                return 0;
×
3664
        }
3665

3666
        return r;
3667
}
3668

3669
static int apply_working_directory(
9,579✔
3670
                const ExecContext *context,
3671
                const ExecParameters *params,
3672
                ExecRuntime *runtime,
3673
                const char *pwent_home,
3674
                char * const *env) {
3675

3676
        const char *wd;
9,579✔
3677
        int r;
9,579✔
3678

3679
        assert(context);
9,579✔
3680
        assert(params);
9,579✔
3681
        assert(runtime);
9,579✔
3682

3683
        if (context->working_directory_home) {
9,579✔
3684
                /* Preferably use the data from $HOME, in case it was updated by a PAM module */
3685
                wd = strv_env_get(env, "HOME");
103✔
3686
                if (!wd) {
103✔
3687
                        /* If that's not available, use the data from the struct passwd entry: */
3688
                        if (!pwent_home)
1✔
3689
                                return -ENXIO;
3690

3691
                        wd = pwent_home;
3692
                }
3693
        } else
3694
                wd = empty_to_root(context->working_directory);
9,476✔
3695

3696
        if (params->flags & EXEC_APPLY_CHROOT)
9,579✔
3697
                r = RET_NERRNO(chdir(wd));
9,579✔
3698
        else {
3699
                _cleanup_close_ int dfd = -EBADF;
×
3700

3701
                r = chase(wd,
×
3702
                          runtime->ephemeral_copy ?: context->root_directory,
×
3703
                          CHASE_PREFIX_ROOT|CHASE_AT_RESOLVE_IN_ROOT,
3704
                          /* ret_path= */ NULL,
3705
                          &dfd);
3706
                if (r >= 0)
×
3707
                        r = RET_NERRNO(fchdir(dfd));
×
3708
        }
3709
        return context->working_directory_missing_ok ? 0 : r;
9,579✔
3710
}
3711

3712
static int apply_root_directory(
9,579✔
3713
                const ExecContext *context,
3714
                const ExecParameters *params,
3715
                ExecRuntime *runtime,
3716
                const bool needs_mount_ns,
3717
                int *exit_status) {
3718

3719
        assert(context);
9,579✔
3720
        assert(params);
9,579✔
3721
        assert(runtime);
9,579✔
3722
        assert(exit_status);
9,579✔
3723

3724
        if (params->flags & EXEC_APPLY_CHROOT)
9,579✔
3725
                if (!needs_mount_ns && context->root_directory)
9,579✔
3726
                        if (chroot(runtime->ephemeral_copy ?: context->root_directory) < 0) {
×
3727
                                *exit_status = EXIT_CHROOT;
×
3728
                                return -errno;
×
3729
                        }
3730

3731
        return 0;
3732
}
3733

3734
static int setup_keyring(
9,605✔
3735
                const ExecContext *context,
3736
                const ExecParameters *p,
3737
                uid_t uid,
3738
                gid_t gid) {
3739

3740
        key_serial_t keyring;
9,605✔
3741
        int r = 0;
9,605✔
3742
        uid_t saved_uid;
9,605✔
3743
        gid_t saved_gid;
9,605✔
3744

3745
        assert(context);
9,605✔
3746
        assert(p);
9,605✔
3747

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

3755
        if (context->keyring_mode == EXEC_KEYRING_INHERIT)
9,605✔
3756
                return 0;
3757

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

3763
        saved_uid = getuid();
8,637✔
3764
        saved_gid = getgid();
8,637✔
3765

3766
        if (gid_is_valid(gid) && gid != saved_gid) {
8,637✔
3767
                if (setregid(gid, -1) < 0)
1,763✔
3768
                        return log_error_errno(errno, "Failed to change GID for user keyring: %m");
×
3769
        }
3770

3771
        if (uid_is_valid(uid) && uid != saved_uid) {
8,637✔
3772
                if (setreuid(uid, -1) < 0) {
1,760✔
3773
                        r = log_error_errno(errno, "Failed to change UID for user keyring: %m");
×
3774
                        goto out;
×
3775
                }
3776
        }
3777

3778
        keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
8,637✔
3779
        if (keyring == -1) {
8,637✔
3780
                if (errno == ENOSYS)
×
3781
                        log_debug_errno(errno, "Kernel keyring not supported, ignoring.");
×
3782
                else if (ERRNO_IS_PRIVILEGE(errno))
×
3783
                        log_debug_errno(errno, "Kernel keyring access prohibited, ignoring.");
×
3784
                else if (errno == EDQUOT)
×
3785
                        log_debug_errno(errno, "Out of kernel keyrings to allocate, ignoring.");
×
3786
                else
3787
                        r = log_error_errno(errno, "Setting up kernel keyring failed: %m");
×
3788

3789
                goto out;
×
3790
        }
3791

3792
        /* When requested link the user keyring into the session keyring. */
3793
        if (context->keyring_mode == EXEC_KEYRING_SHARED) {
8,637✔
3794

3795
                if (keyctl(KEYCTL_LINK,
932✔
3796
                           KEY_SPEC_USER_KEYRING,
3797
                           KEY_SPEC_SESSION_KEYRING, 0, 0) < 0) {
3798
                        r = log_error_errno(errno, "Failed to link user keyring into session keyring: %m");
×
3799
                        goto out;
×
3800
                }
3801
        }
3802

3803
        /* Restore uid/gid back */
3804
        if (uid_is_valid(uid) && uid != saved_uid) {
8,637✔
3805
                if (setreuid(saved_uid, -1) < 0) {
1,760✔
3806
                        r = log_error_errno(errno, "Failed to change UID back for user keyring: %m");
×
3807
                        goto out;
×
3808
                }
3809
        }
3810

3811
        if (gid_is_valid(gid) && gid != saved_gid) {
8,637✔
3812
                if (setregid(saved_gid, -1) < 0)
1,763✔
3813
                        return log_error_errno(errno, "Failed to change GID back for user keyring: %m");
×
3814
        }
3815

3816
        /* Populate they keyring with the invocation ID by default, as original saved_uid. */
3817
        if (!sd_id128_is_null(p->invocation_id)) {
8,637✔
3818
                key_serial_t key;
8,637✔
3819

3820
                key = add_key("user",
17,274✔
3821
                              "invocation_id",
3822
                              &p->invocation_id,
8,637✔
3823
                              sizeof(p->invocation_id),
3824
                              KEY_SPEC_SESSION_KEYRING);
3825
                if (key == -1)
8,637✔
3826
                        log_debug_errno(errno, "Failed to add invocation ID to keyring, ignoring: %m");
×
3827
                else {
3828
                        if (keyctl(KEYCTL_SETPERM, key,
8,637✔
3829
                                   KEY_POS_VIEW|KEY_POS_READ|KEY_POS_SEARCH|
3830
                                   KEY_USR_VIEW|KEY_USR_READ|KEY_USR_SEARCH, 0, 0) < 0)
3831
                                r = log_error_errno(errno, "Failed to restrict invocation ID permission: %m");
×
3832
                }
3833
        }
3834

3835
out:
8,637✔
3836
        /* Revert back uid & gid for the last time, and exit */
3837
        /* no extra logging, as only the first already reported error matters */
3838
        if (getuid() != saved_uid)
8,637✔
3839
                (void) setreuid(saved_uid, -1);
×
3840

3841
        if (getgid() != saved_gid)
8,637✔
3842
                (void) setregid(saved_gid, -1);
×
3843

3844
        return r;
3845
}
3846

3847
static void append_socket_pair(int *array, size_t *n, const int pair[static 2]) {
34,792✔
3848
        assert(array);
34,792✔
3849
        assert(n);
34,792✔
3850
        assert(pair);
34,792✔
3851

3852
        if (pair[0] >= 0)
34,792✔
3853
                array[(*n)++] = pair[0];
190✔
3854
        if (pair[1] >= 0)
34,792✔
3855
                array[(*n)++] = pair[1];
190✔
3856
}
34,792✔
3857

3858
static int close_remaining_fds(
11,556✔
3859
                const ExecParameters *params,
3860
                const ExecRuntime *runtime,
3861
                int socket_fd,
3862
                const int *fds,
3863
                size_t n_fds) {
11,556✔
3864

3865
        size_t n_dont_close = 0;
11,556✔
3866
        int dont_close[n_fds + 17];
11,556✔
3867

3868
        assert(params);
11,556✔
3869
        assert(runtime);
11,556✔
3870

3871
        if (params->stdin_fd >= 0)
11,556✔
3872
                dont_close[n_dont_close++] = params->stdin_fd;
546✔
3873
        if (params->stdout_fd >= 0)
11,556✔
3874
                dont_close[n_dont_close++] = params->stdout_fd;
546✔
3875
        if (params->stderr_fd >= 0)
11,556✔
3876
                dont_close[n_dont_close++] = params->stderr_fd;
546✔
3877

3878
        if (socket_fd >= 0)
11,556✔
3879
                dont_close[n_dont_close++] = socket_fd;
17✔
3880
        if (n_fds > 0) {
11,556✔
3881
                memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
11,556✔
3882
                n_dont_close += n_fds;
11,556✔
3883
        }
3884

3885
        append_socket_pair(dont_close, &n_dont_close, runtime->ephemeral_storage_socket);
11,556✔
3886

3887
        if (runtime->shared) {
11,556✔
3888
                append_socket_pair(dont_close, &n_dont_close, runtime->shared->netns_storage_socket);
11,556✔
3889
                append_socket_pair(dont_close, &n_dont_close, runtime->shared->ipcns_storage_socket);
11,556✔
3890
        }
3891

3892
        if (runtime->dynamic_creds) {
11,556✔
3893
                if (runtime->dynamic_creds->user)
11,556✔
3894
                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->user->storage_socket);
62✔
3895
                if (runtime->dynamic_creds->group)
11,556✔
3896
                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->group->storage_socket);
62✔
3897
        }
3898

3899
        if (params->user_lookup_fd >= 0)
11,556✔
3900
                dont_close[n_dont_close++] = params->user_lookup_fd;
11,556✔
3901

3902
        if (params->handoff_timestamp_fd >= 0)
11,556✔
3903
                dont_close[n_dont_close++] = params->handoff_timestamp_fd;
11,556✔
3904

3905
        if (params->pidref_transport_fd >= 0)
11,556✔
3906
                dont_close[n_dont_close++] = params->pidref_transport_fd;
10,507✔
3907

3908
        assert(n_dont_close <= ELEMENTSOF(dont_close));
11,556✔
3909

3910
        return close_all_fds(dont_close, n_dont_close);
11,556✔
3911
}
3912

3913
static int send_user_lookup(
11,554✔
3914
                const char *unit_id,
3915
                int user_lookup_fd,
3916
                uid_t uid,
3917
                gid_t gid) {
3918

3919
        assert(unit_id);
11,554✔
3920

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

3925
        if (user_lookup_fd < 0)
11,554✔
3926
                return 0;
3927

3928
        if (!uid_is_valid(uid) && !gid_is_valid(gid))
11,554✔
3929
                return 0;
3930

3931
        if (writev(user_lookup_fd,
2,679✔
3932
               (struct iovec[]) {
2,679✔
3933
                           IOVEC_MAKE(&uid, sizeof(uid)),
3934
                           IOVEC_MAKE(&gid, sizeof(gid)),
3935
                           IOVEC_MAKE_STRING(unit_id) }, 3) < 0)
2,679✔
3936
                return -errno;
×
3937

3938
        return 0;
2,679✔
3939
}
3940

3941
static int acquire_home(const ExecContext *c, const char **home, char **ret_buf) {
11,554✔
3942
        int r;
11,554✔
3943

3944
        assert(c);
11,554✔
3945
        assert(home);
11,554✔
3946
        assert(ret_buf);
11,554✔
3947

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

3950
        if (*home) /* Already acquired from get_fixed_user()? */
11,554✔
3951
                return 0;
3952

3953
        if (!c->working_directory_home)
8,942✔
3954
                return 0;
3955

3956
        if (c->dynamic_user || (c->user && is_this_me(c->user) <= 0))
×
3957
                return -EADDRNOTAVAIL;
×
3958

3959
        r = get_home_dir(ret_buf);
×
3960
        if (r < 0)
×
3961
                return r;
3962

3963
        *home = *ret_buf;
×
3964
        return 1;
×
3965
}
3966

3967
static int compile_suggested_paths(const ExecContext *c, const ExecParameters *p, char ***ret) {
62✔
3968
        _cleanup_strv_free_ char ** list = NULL;
62✔
3969
        int r;
62✔
3970

3971
        assert(c);
62✔
3972
        assert(p);
62✔
3973
        assert(ret);
62✔
3974

3975
        assert(c->dynamic_user);
62✔
3976

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

3981
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
372✔
3982

3983
                if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(t))
310✔
3984
                        continue;
62✔
3985

3986
                if (!p->prefix[t])
248✔
3987
                        continue;
×
3988

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

3992
                        if (exec_directory_is_private(c, t))
15✔
3993
                                e = path_join(p->prefix[t], "private", c->directories[t].items[i].path);
13✔
3994
                        else
3995
                                e = path_join(p->prefix[t], c->directories[t].items[i].path);
2✔
3996
                        if (!e)
15✔
3997
                                return -ENOMEM;
3998

3999
                        r = strv_consume(&list, e);
15✔
4000
                        if (r < 0)
15✔
4001
                                return r;
4002
                }
4003
        }
4004

4005
        *ret = TAKE_PTR(list);
62✔
4006

4007
        return 0;
62✔
4008
}
4009

4010
static int exec_context_cpu_affinity_from_numa(const ExecContext *c, CPUSet *ret) {
2✔
4011
        _cleanup_(cpu_set_reset) CPUSet s = {};
2✔
4012
        int r;
2✔
4013

4014
        assert(c);
2✔
4015
        assert(ret);
2✔
4016

4017
        if (!c->numa_policy.nodes.set) {
2✔
4018
                log_debug("Can't derive CPU affinity mask from NUMA mask because NUMA mask is not set, ignoring");
×
4019
                return 0;
×
4020
        }
4021

4022
        r = numa_to_cpu_set(&c->numa_policy, &s);
2✔
4023
        if (r < 0)
2✔
4024
                return r;
4025

4026
        cpu_set_reset(ret);
2✔
4027

4028
        return cpu_set_add_all(ret, &s);
2✔
4029
}
4030

4031
static int add_shifted_fd(int *fds, size_t fds_size, size_t *n_fds, int *fd) {
44,247✔
4032
        int r;
44,247✔
4033

4034
        assert(fds);
44,247✔
4035
        assert(n_fds);
44,247✔
4036
        assert(*n_fds < fds_size);
44,247✔
4037
        assert(fd);
44,247✔
4038

4039
        if (*fd < 0)
44,247✔
4040
               return 0;
44,247✔
4041

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

4046
                r = fcntl(*fd, F_DUPFD_CLOEXEC, 3 + (int) *n_fds);
9,579✔
4047
                if (r < 0)
9,579✔
4048
                        return -errno;
×
4049

4050
                close_and_replace(*fd, r);
9,579✔
4051
        }
4052

4053
        fds[(*n_fds)++] = *fd;
21,531✔
4054
        return 1;
21,531✔
4055
}
4056

4057
static int connect_unix_harder(const OpenFile *of, int ofd) {
1✔
4058
        static const int socket_types[] = { SOCK_DGRAM, SOCK_STREAM, SOCK_SEQPACKET };
1✔
4059

4060
        union sockaddr_union addr = {
1✔
4061
                .un.sun_family = AF_UNIX,
4062
        };
4063
        socklen_t sa_len;
1✔
4064
        int r;
1✔
4065

4066
        assert(of);
1✔
4067
        assert(ofd >= 0);
1✔
4068

4069
        r = sockaddr_un_set_path(&addr.un, FORMAT_PROC_FD_PATH(ofd));
1✔
4070
        if (r < 0)
1✔
4071
                return log_debug_errno(r, "Failed to set sockaddr for '%s': %m", of->path);
×
4072
        sa_len = r;
1✔
4073

4074
        FOREACH_ELEMENT(i, socket_types) {
2✔
4075
                _cleanup_close_ int fd = -EBADF;
2✔
4076

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

4081
                r = RET_NERRNO(connect(fd, &addr.sa, sa_len));
2✔
4082
                if (r >= 0)
1✔
4083
                        return TAKE_FD(fd);
1✔
4084
                if (r != -EPROTOTYPE)
1✔
4085
                        return log_debug_errno(r, "Failed to connect to socket for '%s': %m", of->path);
×
4086
        }
4087

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

4091
static int get_open_file_fd(const OpenFile *of) {
5✔
4092
        _cleanup_close_ int fd = -EBADF, ofd = -EBADF;
5✔
4093
        struct stat st;
5✔
4094

4095
        assert(of);
5✔
4096

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

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

4104
        if (S_ISSOCK(st.st_mode)) {
3✔
4105
                fd = connect_unix_harder(of, ofd);
1✔
4106
                if (fd < 0)
1✔
4107
                        return fd;
4108

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

4112
                log_debug("Opened socket '%s' as fd %d.", of->path, fd);
1✔
4113
        } else {
4114
                int flags = FLAGS_SET(of->flags, OPENFILE_READ_ONLY) ? O_RDONLY : O_RDWR;
2✔
4115
                if (FLAGS_SET(of->flags, OPENFILE_APPEND))
2✔
4116
                        flags |= O_APPEND;
×
4117
                else if (FLAGS_SET(of->flags, OPENFILE_TRUNCATE))
2✔
4118
                        flags |= O_TRUNC;
×
4119

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

4124
                log_debug("Opened file '%s' as fd %d.", of->path, fd);
2✔
4125
        }
4126

4127
        return TAKE_FD(fd);
4128
}
4129

4130
static int collect_open_file_fds(ExecParameters *p, size_t *n_fds) {
11,557✔
4131
        assert(p);
11,557✔
4132
        assert(n_fds);
11,557✔
4133

4134
        LIST_FOREACH(open_files, of, p->open_files) {
11,557✔
4135
                _cleanup_close_ int fd = -EBADF;
11,562✔
4136

4137
                fd = get_open_file_fd(of);
5✔
4138
                if (fd < 0) {
5✔
4139
                        if (FLAGS_SET(of->flags, OPENFILE_GRACEFUL)) {
2✔
4140
                                log_full_errno(fd == -ENOENT || ERRNO_IS_NEG_PRIVILEGE(fd) ? LOG_DEBUG : LOG_WARNING,
1✔
4141
                                               fd,
4142
                                               "Failed to get OpenFile= file descriptor for '%s', ignoring: %m",
4143
                                               of->path);
4144
                                continue;
1✔
4145
                        }
4146

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

4150
                if (!GREEDY_REALLOC(p->fds, *n_fds + 1))
3✔
4151
                        return log_oom();
×
4152

4153
                if (strv_extend(&p->fd_names, of->fdname) < 0)
3✔
4154
                        return log_oom();
×
4155

4156
                p->fds[(*n_fds)++] = TAKE_FD(fd);
3✔
4157
        }
4158

4159
        return 0;
4160
}
4161

4162
static void log_command_line(
9,578✔
4163
                const ExecContext *context,
4164
                const ExecParameters *params,
4165
                const char *msg,
4166
                const char *executable,
4167
                char **argv) {
4168

4169
        assert(context);
9,578✔
4170
        assert(params);
9,578✔
4171
        assert(msg);
9,578✔
4172
        assert(executable);
9,578✔
4173

4174
        if (!DEBUG_LOGGING)
9,578✔
4175
                return;
9,578✔
4176

4177
        _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);
18,510✔
4178

4179
        log_struct(LOG_DEBUG,
17,720✔
4180
                   LOG_ITEM("EXECUTABLE=%s", executable),
4181
                   LOG_EXEC_MESSAGE(params, "%s: %s", msg, strnull(cmdline)),
4182
                   LOG_EXEC_INVOCATION_ID(params));
4183
}
4184

4185
static bool exec_context_needs_cap_sys_admin(const ExecContext *context) {
1,656✔
4186
        assert(context);
1,656✔
4187

4188
        return context->private_users != PRIVATE_USERS_NO ||
3,299✔
4189
               context->private_tmp != PRIVATE_TMP_NO ||
1,643✔
4190
               context->private_devices ||
1,628✔
4191
               context->private_network ||
1,621✔
4192
               context->network_namespace_path ||
1,614✔
4193
               context->private_ipc ||
1,614✔
4194
               context->ipc_namespace_path ||
1,614✔
4195
               context->private_mounts > 0 ||
1,614✔
4196
               context->mount_apivfs > 0 ||
1,604✔
4197
               context->bind_log_sockets > 0 ||
1,604✔
4198
               context->n_bind_mounts > 0 ||
1,604✔
4199
               context->n_temporary_filesystems > 0 ||
1,599✔
4200
               context->root_directory ||
1,599✔
4201
               !strv_isempty(context->extension_directories) ||
1,599✔
4202
               context->protect_system != PROTECT_SYSTEM_NO ||
1,599✔
4203
               context->protect_home != PROTECT_HOME_NO ||
3,183✔
4204
               exec_needs_pid_namespace(context) ||
1,584✔
4205
               context->protect_kernel_tunables ||
1,562✔
4206
               context->protect_kernel_modules ||
1,557✔
4207
               context->protect_kernel_logs ||
3,104✔
4208
               exec_needs_cgroup_mount(context) ||
1,552✔
4209
               context->protect_clock ||
1,552✔
4210
               context->protect_hostname != PROTECT_HOSTNAME_NO ||
1,547✔
4211
               !strv_isempty(context->read_write_paths) ||
1,542✔
4212
               !strv_isempty(context->read_only_paths) ||
1,527✔
4213
               !strv_isempty(context->inaccessible_paths) ||
1,527✔
4214
               !strv_isempty(context->exec_paths) ||
1,527✔
4215
               !strv_isempty(context->no_exec_paths) ||
3,183✔
4216
               context->delegate_namespaces != NAMESPACE_FLAGS_INITIAL;
1,527✔
4217
}
4218

4219
static PrivateUsers exec_context_get_effective_private_users(
9,588✔
4220
                const ExecContext *context,
4221
                const ExecParameters *params) {
4222

4223
        assert(context);
9,588✔
4224
        assert(params);
9,588✔
4225

4226
        if (context->private_users != PRIVATE_USERS_NO)
9,588✔
4227
                return context->private_users;
4228

4229
        /* If any namespace is delegated with DelegateNamespaces=, always set up a user namespace. */
4230
        if (context->delegate_namespaces != NAMESPACE_FLAGS_INITIAL)
9,562✔
4231
                return PRIVATE_USERS_SELF;
3✔
4232

4233
        return PRIVATE_USERS_NO;
4234
}
4235

4236
static bool exec_namespace_is_delegated(
23,369✔
4237
                const ExecContext *context,
4238
                const ExecParameters *params,
4239
                bool have_cap_sys_admin,
4240
                unsigned long namespace) {
4241

4242
        assert(context);
23,369✔
4243
        assert(params);
23,369✔
4244
        assert(namespace != CLONE_NEWUSER);
23,369✔
4245

4246
        /* If we need unprivileged private users, we've already unshared a user namespace by the time we call
4247
         * setup_delegated_namespaces() for the first time so let's make sure we do all other namespace
4248
         * unsharing in the first call to setup_delegated_namespaces() by returning false here. */
4249
        if (!have_cap_sys_admin && exec_context_needs_cap_sys_admin(context))
23,369✔
4250
                return false;
4251

4252
        if (context->delegate_namespaces == NAMESPACE_FLAGS_INITIAL)
23,267✔
4253
                return params->runtime_scope == RUNTIME_SCOPE_USER;
23,199✔
4254

4255
        if (FLAGS_SET(context->delegate_namespaces, namespace))
68✔
4256
                return true;
4257

4258
        /* Various namespaces imply mountns for private procfs/sysfs/cgroupfs instances, which means when
4259
         * those are delegated mountns must be deferred too.
4260
         *
4261
         * The list should stay in sync with exec_needs_mount_namespace(). */
4262
        if (namespace == CLONE_NEWNS)
16✔
4263
                return context->delegate_namespaces & (CLONE_NEWPID|CLONE_NEWCGROUP|CLONE_NEWNET);
4✔
4264

4265
        return false;
4266
}
4267

4268
static int setup_delegated_namespaces(
19,189✔
4269
                const ExecContext *context,
4270
                ExecParameters *params,
4271
                ExecRuntime *runtime,
4272
                bool delegate,
4273
                const char *memory_pressure_path,
4274
                uid_t uid,
4275
                uid_t gid,
4276
                const ExecCommand *command,
4277
                bool needs_sandboxing,
4278
                bool have_cap_sys_admin,
4279
                int *reterr_exit_status) {
4280

4281
        int r;
19,189✔
4282

4283
        /* This function is called twice, once before unsharing the user namespace, and once after unsharing
4284
         * the user namespace. When called before unsharing the user namespace, "delegate" is set to "false".
4285
         * When called after unsharing the user namespace, "delegate" is set to "true". The net effect is
4286
         * that all namespaces that should not be delegated are unshared when this function is called the
4287
         * first time and all namespaces that should be delegated are unshared when this function is called
4288
         * the second time. */
4289

4290
        assert(context);
19,189✔
4291
        assert(params);
19,189✔
4292
        assert(runtime);
19,189✔
4293
        assert(reterr_exit_status);
19,189✔
4294

4295
        if (exec_needs_network_namespace(context) &&
19,308✔
4296
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWNET) == delegate &&
119✔
4297
            runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
60✔
4298

4299
                /* Try to enable network namespacing if network namespacing is available and we have
4300
                 * CAP_NET_ADMIN in the current user namespace (either the system manager one or the unit's
4301
                 * own user namespace). We need CAP_NET_ADMIN to be able to configure the loopback device in
4302
                 * the new network namespace. And if we don't have that, then we could only create a network
4303
                 * namespace without the ability to set up "lo". Hence gracefully skip things then. */
4304
                if (namespace_type_supported(NAMESPACE_NET) && have_effective_cap(CAP_NET_ADMIN) > 0) {
60✔
4305
                        r = setup_shareable_ns(runtime->shared->netns_storage_socket, CLONE_NEWNET);
60✔
4306
                        if (ERRNO_IS_NEG_PRIVILEGE(r))
60✔
4307
                                log_notice_errno(r, "PrivateNetwork=yes is configured, but network namespace setup not permitted, proceeding without: %m");
×
4308
                        else if (r < 0) {
60✔
4309
                                *reterr_exit_status = EXIT_NETWORK;
×
4310
                                return log_error_errno(r, "Failed to set up network namespacing: %m");
×
4311
                        } else
4312
                                log_debug("Set up %snetwork namespace", delegate ? "delegated " : "");
115✔
4313
                } else if (context->network_namespace_path) {
×
4314
                        *reterr_exit_status = EXIT_NETWORK;
×
4315
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "NetworkNamespacePath= is not supported, refusing.");
×
4316
                } else
4317
                        log_notice("PrivateNetwork=yes is configured, but the kernel does not support or we lack privileges for network namespace, proceeding without.");
×
4318
        }
4319

4320
        if (exec_needs_ipc_namespace(context) &&
19,200✔
4321
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWIPC) == delegate &&
11✔
4322
            runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
6✔
4323

4324
                if (namespace_type_supported(NAMESPACE_IPC)) {
6✔
4325
                        r = setup_shareable_ns(runtime->shared->ipcns_storage_socket, CLONE_NEWIPC);
6✔
4326
                        if (ERRNO_IS_NEG_PRIVILEGE(r))
6✔
4327
                                log_warning_errno(r, "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m");
×
4328
                        else if (r < 0) {
6✔
4329
                                *reterr_exit_status = EXIT_NAMESPACE;
×
4330
                                return log_error_errno(r, "Failed to set up IPC namespacing: %m");
×
4331
                        } else
4332
                                log_debug("Set up %sIPC namespace", delegate ? "delegated " : "");
8✔
4333
                } else if (context->ipc_namespace_path) {
×
4334
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4335
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "IPCNamespacePath= is not supported, refusing.");
×
4336
                } else
4337
                        log_warning("PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring.");
×
4338
        }
4339

4340
        if (needs_sandboxing && exec_needs_cgroup_namespace(context) &&
19,214✔
4341
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWCGROUP) == delegate) {
25✔
4342
                if (unshare(CLONE_NEWCGROUP) < 0) {
13✔
4343
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4344
                        return log_error_errno(errno, "Failed to set up cgroup namespacing: %m");
×
4345
                }
4346

4347
                log_debug("Set up %scgroup namespace", delegate ? "delegated " : "");
22✔
4348
        }
4349

4350
        /* Unshare a new PID namespace before setting up mounts to ensure /proc/ is mounted with only processes in PID namespace visible.
4351
         * Note PrivatePIDs=yes implies MountAPIVFS=yes so we'll always ensure procfs is remounted. */
4352
        if (needs_sandboxing && exec_needs_pid_namespace(context) &&
19,212✔
4353
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWPID) == delegate) {
25✔
4354
                if (params->pidref_transport_fd < 0) {
15✔
4355
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4356
                        return log_error_errno(SYNTHETIC_ERRNO(ENOTCONN), "PidRef socket is not set up: %m");
×
4357
                }
4358

4359
                /* If we had CAP_SYS_ADMIN prior to joining the user namespace, then we are privileged and don't need
4360
                 * to check if we can mount /proc/.
4361
                 *
4362
                 * We need to check prior to entering the user namespace because if we're running unprivileged or in a
4363
                 * system without CAP_SYS_ADMIN, then we can have CAP_SYS_ADMIN in the current user namespace but not
4364
                 * once we unshare a mount namespace. */
4365
                if (!have_cap_sys_admin || delegate) {
15✔
4366
                        r = can_mount_proc();
10✔
4367
                        if (r < 0) {
5✔
4368
                                *reterr_exit_status = EXIT_NAMESPACE;
×
4369
                                return log_error_errno(r, "Failed to detect if /proc/ can be remounted: %m");
×
4370
                        }
4371
                        if (r == 0) {
5✔
4372
                                *reterr_exit_status = EXIT_NAMESPACE;
1✔
4373
                                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
1✔
4374
                                                       "PrivatePIDs=yes is configured, but /proc/ cannot be re-mounted due to lack of privileges, refusing.");
4375
                        }
4376
                }
4377

4378
                r = setup_private_pids(context, params);
9✔
4379
                if (r < 0) {
6✔
4380
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4381
                        return log_error_errno(r, "Failed to set up pid namespace: %m");
×
4382
                }
4383

4384
                log_debug("Set up %spid namespace", delegate ? "delegated " : "");
12✔
4385
        }
4386

4387
        /* If PrivatePIDs= yes is configured, we're now running as pid 1 in a pid namespace! */
4388

4389
        if (exec_needs_mount_namespace(context, params, runtime) &&
23,206✔
4390
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWNS) == delegate) {
4,026✔
4391
                _cleanup_free_ char *error_path = NULL;
2,019✔
4392

4393
                r = apply_mount_namespace(command->flags,
2,019✔
4394
                                          context,
4395
                                          params,
4396
                                          runtime,
4397
                                          memory_pressure_path,
4398
                                          needs_sandboxing,
4399
                                          &error_path,
4400
                                          uid,
4401
                                          gid);
4402
                if (r < 0) {
2,019✔
4403
                        *reterr_exit_status = EXIT_NAMESPACE;
15✔
4404
                        return log_error_errno(r, "Failed to set up mount namespacing%s%s: %m",
29✔
4405
                                               error_path ? ": " : "", strempty(error_path));
4406
                }
4407

4408
                log_debug("Set up %smount namespace", delegate ? "delegated " : "");
3,980✔
4409
        }
4410

4411
        if (needs_sandboxing &&
38,328✔
4412
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWUTS) == delegate) {
19,163✔
4413
                r = apply_protect_hostname(context, params, reterr_exit_status);
9,580✔
4414
                if (r < 0)
9,580✔
4415
                        return r;
4416
                if (r > 0)
9,580✔
4417
                        log_debug("Set up %sUTS namespace", delegate ? "delegated " : "");
1,327✔
4418
        }
4419

4420
        return 0;
4421
}
4422

4423
static bool exec_context_shall_confirm_spawn(const ExecContext *context) {
×
4424
        assert(context);
×
4425

4426
        if (confirm_spawn_disabled())
×
4427
                return false;
4428

4429
        /* For some reasons units remaining in the same process group
4430
         * as PID 1 fail to acquire the console even if it's not used
4431
         * by any process. So skip the confirmation question for them. */
4432
        return !context->same_pgrp;
×
4433
}
4434

4435
static int exec_context_named_iofds(
11,557✔
4436
                const ExecContext *c,
4437
                const ExecParameters *p,
4438
                int named_iofds[static 3]) {
4439

4440
        size_t targets;
11,557✔
4441
        const char* stdio_fdname[3];
11,557✔
4442
        size_t n_fds;
11,557✔
4443

4444
        assert(c);
11,557✔
4445
        assert(p);
11,557✔
4446
        assert(named_iofds);
11,557✔
4447

4448
        targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
11,557✔
4449
                  (c->std_output == EXEC_OUTPUT_NAMED_FD) +
11,557✔
4450
                  (c->std_error == EXEC_OUTPUT_NAMED_FD);
11,557✔
4451

4452
        for (size_t i = 0; i < 3; i++)
46,228✔
4453
                stdio_fdname[i] = exec_context_fdname(c, i);
34,671✔
4454

4455
        n_fds = p->n_storage_fds + p->n_socket_fds + p->n_extra_fds;
11,557✔
4456

4457
        for (size_t i = 0; i < n_fds  && targets > 0; i++)
11,557✔
4458
                if (named_iofds[STDIN_FILENO] < 0 &&
×
4459
                    c->std_input == EXEC_INPUT_NAMED_FD &&
×
4460
                    stdio_fdname[STDIN_FILENO] &&
×
4461
                    streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
×
4462

4463
                        named_iofds[STDIN_FILENO] = p->fds[i];
×
4464
                        targets--;
×
4465

4466
                } else if (named_iofds[STDOUT_FILENO] < 0 &&
×
4467
                           c->std_output == EXEC_OUTPUT_NAMED_FD &&
×
4468
                           stdio_fdname[STDOUT_FILENO] &&
×
4469
                           streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
×
4470

4471
                        named_iofds[STDOUT_FILENO] = p->fds[i];
×
4472
                        targets--;
×
4473

4474
                } else if (named_iofds[STDERR_FILENO] < 0 &&
×
4475
                           c->std_error == EXEC_OUTPUT_NAMED_FD &&
×
4476
                           stdio_fdname[STDERR_FILENO] &&
×
4477
                           streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
×
4478

4479
                        named_iofds[STDERR_FILENO] = p->fds[i];
×
4480
                        targets--;
×
4481
                }
4482

4483
        return targets == 0 ? 0 : -ENOENT;
11,557✔
4484
}
4485

4486
static void exec_shared_runtime_close(ExecSharedRuntime *shared) {
9,579✔
4487
        if (!shared)
9,579✔
4488
                return;
4489

4490
        safe_close_pair(shared->netns_storage_socket);
9,579✔
4491
        safe_close_pair(shared->ipcns_storage_socket);
9,579✔
4492
}
4493

4494
static void exec_runtime_close(ExecRuntime *rt) {
9,579✔
4495
        if (!rt)
9,579✔
4496
                return;
4497

4498
        safe_close_pair(rt->ephemeral_storage_socket);
9,579✔
4499

4500
        exec_shared_runtime_close(rt->shared);
9,579✔
4501
        dynamic_creds_close(rt->dynamic_creds);
9,579✔
4502
}
4503

4504
static void exec_params_close(ExecParameters *p) {
9,579✔
4505
        if (!p)
9,579✔
4506
                return;
4507

4508
        p->stdin_fd = safe_close(p->stdin_fd);
9,579✔
4509
        p->stdout_fd = safe_close(p->stdout_fd);
9,579✔
4510
        p->stderr_fd = safe_close(p->stderr_fd);
9,579✔
4511
}
4512

4513
static int exec_fd_mark_hot(
9,581✔
4514
                const ExecContext *c,
4515
                ExecParameters *p,
4516
                bool hot,
4517
                int *reterr_exit_status) {
4518

4519
        assert(c);
9,581✔
4520
        assert(p);
9,581✔
4521

4522
        if (p->exec_fd < 0)
9,581✔
4523
                return 0;
9,581✔
4524

4525
        uint8_t x = hot;
287✔
4526

4527
        if (write(p->exec_fd, &x, sizeof(x)) < 0) {
287✔
4528
                if (reterr_exit_status)
×
4529
                        *reterr_exit_status = EXIT_EXEC;
×
4530
                return log_error_errno(errno, "Failed to mark exec_fd as %s: %m", hot ? "hot" : "cold");
×
4531
        }
4532

4533
        return 1;
4534
}
4535

4536
static int send_handoff_timestamp(
9,578✔
4537
                const ExecContext *c,
4538
                ExecParameters *p,
4539
                int *reterr_exit_status) {
4540

4541
        assert(c);
9,578✔
4542
        assert(p);
9,578✔
4543

4544
        if (p->handoff_timestamp_fd < 0)
9,578✔
4545
                return 0;
9,578✔
4546

4547
        dual_timestamp dt;
9,578✔
4548
        dual_timestamp_now(&dt);
9,578✔
4549

4550
        if (write(p->handoff_timestamp_fd, (const usec_t[2]) { dt.realtime, dt.monotonic }, sizeof(usec_t) * 2) < 0) {
9,578✔
4551
                if (reterr_exit_status)
×
4552
                        *reterr_exit_status = EXIT_EXEC;
×
4553
                return log_error_errno(errno, "Failed to send handoff timestamp: %m");
×
4554
        }
4555

4556
        return 1;
9,578✔
4557
}
4558

4559
static void prepare_terminal(
11,554✔
4560
                const ExecContext *context,
4561
                ExecParameters *p) {
4562

4563
        _cleanup_close_ int lock_fd = -EBADF;
11,554✔
4564

4565
        /* This is the "constructive" reset, i.e. is about preparing things for our invocation rather than
4566
         * cleaning up things from older invocations. */
4567

4568
        assert(context);
11,554✔
4569
        assert(p);
11,554✔
4570

4571
        /* We only try to reset things if we there's the chance our stdout points to a TTY */
4572
        if (!(is_terminal_output(context->std_output) ||
11,554✔
4573
              (context->std_output == EXEC_OUTPUT_INHERIT && is_terminal_input(context->std_input)) ||
10,946✔
4574
              context->std_output == EXEC_OUTPUT_NAMED_FD ||
4575
              p->stdout_fd >= 0))
10,946✔
4576
                return;
10,400✔
4577

4578
        /* Let's explicitly determine whether to reset via ANSI sequences or not, taking our ExecContext
4579
         * information into account */
4580
        bool use_ansi = exec_context_shall_ansi_seq_reset(context);
1,154✔
4581

4582
        if (context->tty_reset) {
1,154✔
4583
                /* When we are resetting the TTY, then let's create a lock first, to synchronize access. This
4584
                 * in particular matters as concurrent resets and the TTY size ANSI DSR logic done by the
4585
                 * exec_context_apply_tty_size() below might interfere */
4586
                lock_fd = lock_dev_console();
154✔
4587
                if (lock_fd < 0)
154✔
4588
                        log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
×
4589

4590
                /* We explicitly control whether to send ansi sequences or not here, since we want to consult
4591
                 * the env vars explicitly configured in the ExecContext, rather than our own environment
4592
                 * block. */
4593
                (void) terminal_reset_defensive(STDOUT_FILENO, use_ansi ? TERMINAL_RESET_FORCE_ANSI_SEQ : TERMINAL_RESET_AVOID_ANSI_SEQ);
157✔
4594
        }
4595

4596
        (void) exec_context_apply_tty_size(context, STDIN_FILENO, STDOUT_FILENO, /* tty_path= */ NULL);
1,154✔
4597

4598
        if (use_ansi)
1,154✔
4599
                (void) osc_context_open_service(p->unit_id, p->invocation_id, /* ret_seq= */ NULL);
151✔
4600
}
4601

4602
int exec_invoke(
11,557✔
4603
                const ExecCommand *command,
4604
                const ExecContext *context,
4605
                ExecParameters *params,
4606
                ExecRuntime *runtime,
4607
                const CGroupContext *cgroup_context,
4608
                int *exit_status) {
11,557✔
4609

4610
        _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **joined_exec_search_path = NULL, **accum_env = NULL;
28✔
4611
        int r;
11,557✔
4612
        const char *username = NULL, *groupname = NULL;
11,557✔
4613
        _cleanup_free_ char *home_buffer = NULL, *memory_pressure_path = NULL, *own_user = NULL;
×
4614
        const char *pwent_home = NULL, *shell = NULL;
11,557✔
4615
        dev_t journal_stream_dev = 0;
11,557✔
4616
        ino_t journal_stream_ino = 0;
11,557✔
4617
        bool needs_sandboxing,          /* Do we need to set up full sandboxing? (i.e. all namespacing, all MAC stuff, caps, yadda yadda */
11,557✔
4618
                needs_setuid,           /* Do we need to do the actual setresuid()/setresgid() calls? */
4619
                needs_mount_namespace,  /* Do we need to set up a mount namespace for this kernel? */
4620
                have_cap_sys_admin,
4621
                userns_set_up = false,
11,557✔
4622
                keep_seccomp_privileges = false;
11,557✔
4623
#if HAVE_SELINUX
4624
        _cleanup_free_ char *mac_selinux_context_net = NULL;
4625
        bool use_selinux = false;
4626
#endif
4627
#if ENABLE_SMACK
4628
        bool use_smack = false;
11,557✔
4629
#endif
4630
#if HAVE_APPARMOR
4631
        bool use_apparmor = false;
4632
#endif
4633
#if HAVE_SECCOMP
4634
        uint64_t saved_bset = 0;
11,557✔
4635
#endif
4636
        uid_t saved_uid = getuid();
11,557✔
4637
        gid_t saved_gid = getgid();
11,557✔
4638
        uid_t uid = UID_INVALID;
11,557✔
4639
        gid_t gid = GID_INVALID;
11,557✔
4640
        size_t n_fds, /* fds to pass to the child */
11,557✔
4641
               n_keep_fds; /* total number of fds not to close */
4642
        int secure_bits;
11,557✔
4643
        _cleanup_free_ gid_t *gids = NULL, *gids_after_pam = NULL;
28✔
4644
        int ngids = 0, ngids_after_pam = 0;
11,557✔
4645
        int socket_fd = -EBADF, named_iofds[3] = EBADF_TRIPLET;
11,557✔
4646
        size_t n_storage_fds, n_socket_fds, n_extra_fds;
11,557✔
4647

4648
        assert(command);
11,557✔
4649
        assert(context);
11,557✔
4650
        assert(params);
11,557✔
4651
        assert(runtime);
11,557✔
4652
        assert(cgroup_context);
11,557✔
4653
        assert(exit_status);
11,557✔
4654

4655
        LOG_CONTEXT_PUSH_EXEC(context, params);
33,107✔
4656

4657
        /* Explicitly test for CVE-2021-4034 inspired invocations */
4658
        if (!command->path || strv_isempty(command->argv)) {
11,557✔
4659
                *exit_status = EXIT_EXEC;
×
4660
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid command line arguments.");
×
4661
        }
4662

4663
        if (context->std_input == EXEC_INPUT_SOCKET ||
11,557✔
4664
            context->std_output == EXEC_OUTPUT_SOCKET ||
11,546✔
4665
            context->std_error == EXEC_OUTPUT_SOCKET) {
11,540✔
4666

4667
                if (params->n_socket_fds > 1)
17✔
4668
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Got more than one socket.");
×
4669

4670
                if (params->n_socket_fds == 0)
17✔
4671
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Got no socket.");
×
4672

4673
                socket_fd = params->fds[0];
17✔
4674
                n_storage_fds = n_socket_fds = n_extra_fds = 0;
17✔
4675
        } else {
4676
                n_socket_fds = params->n_socket_fds;
11,540✔
4677
                n_storage_fds = params->n_storage_fds;
11,540✔
4678
                n_extra_fds = params->n_extra_fds;
11,540✔
4679
        }
4680
        n_fds = n_socket_fds + n_storage_fds + n_extra_fds;
11,557✔
4681

4682
        r = exec_context_named_iofds(context, params, named_iofds);
11,557✔
4683
        if (r < 0)
11,557✔
4684
                return log_error_errno(r, "Failed to load a named file descriptor: %m");
×
4685

4686
        rename_process_from_path(command->path);
11,557✔
4687

4688
        /* We reset exactly these signals, since they are the only ones we set to SIG_IGN in the main
4689
         * daemon. All others we leave untouched because we set them to SIG_DFL or a valid handler initially,
4690
         * both of which will be demoted to SIG_DFL. */
4691
        (void) default_signals(SIGNALS_CRASH_HANDLER,
11,557✔
4692
                               SIGNALS_IGNORE);
4693

4694
        if (context->ignore_sigpipe)
11,557✔
4695
                (void) ignore_signals(SIGPIPE);
11,197✔
4696

4697
        r = reset_signal_mask();
11,557✔
4698
        if (r < 0) {
11,557✔
4699
                *exit_status = EXIT_SIGNAL_MASK;
×
4700
                return log_error_errno(r, "Failed to set process signal mask: %m");
×
4701
        }
4702

4703
        if (params->idle_pipe)
11,557✔
4704
                do_idle_pipe_dance(params->idle_pipe);
151✔
4705

4706
        /* Close fds we don't need very early to make sure we don't block init reexecution because it cannot bind its
4707
         * sockets. Among the fds we close are the logging fds, and we want to keep them closed, so that we don't have
4708
         * any fds open we don't really want open during the transition. In order to make logging work, we switch the
4709
         * log subsystem into open_when_needed mode, so that it reopens the logs on every single log call. */
4710

4711
        log_forget_fds();
11,557✔
4712
        log_set_open_when_needed(true);
11,557✔
4713
        log_settle_target();
11,557✔
4714

4715
        /* In case anything used libc syslog(), close this here, too */
4716
        closelog();
11,557✔
4717

4718
        r = collect_open_file_fds(params, &n_fds);
11,557✔
4719
        if (r < 0) {
11,557✔
4720
                *exit_status = EXIT_FDS;
1✔
4721
                return log_error_errno(r, "Failed to get OpenFile= file descriptors: %m");
1✔
4722
        }
4723

4724
        int keep_fds[n_fds + 4];
11,556✔
4725
        memcpy_safe(keep_fds, params->fds, n_fds * sizeof(int));
11,556✔
4726
        n_keep_fds = n_fds;
11,556✔
4727

4728
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->exec_fd);
11,556✔
4729
        if (r < 0) {
11,556✔
4730
                *exit_status = EXIT_FDS;
×
4731
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
4732
        }
4733

4734
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->handoff_timestamp_fd);
11,556✔
4735
        if (r < 0) {
11,556✔
4736
                *exit_status = EXIT_FDS;
×
4737
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
4738
        }
4739

4740
#if HAVE_LIBBPF
4741
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->bpf_restrict_fs_map_fd);
11,556✔
4742
        if (r < 0) {
11,556✔
4743
                *exit_status = EXIT_FDS;
×
4744
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
4745
        }
4746
#endif
4747

4748
        r = close_remaining_fds(params, runtime, socket_fd, keep_fds, n_keep_fds);
11,556✔
4749
        if (r < 0) {
11,556✔
4750
                *exit_status = EXIT_FDS;
×
4751
                return log_error_errno(r, "Failed to close unwanted file descriptors: %m");
×
4752
        }
4753

4754
        if (!context->same_pgrp &&
22,246✔
4755
            setsid() < 0) {
10,690✔
4756
                *exit_status = EXIT_SETSID;
×
4757
                return log_error_errno(errno, "Failed to create new process session: %m");
×
4758
        }
4759

4760
        /* Now, reset the TTY associated to this service "destructively" (i.e. possibly even hang up or
4761
         * disallocate the VT), to get rid of any prior uses of the device. Note that we do not keep any fd
4762
         * open here, hence some of the settings made here might vanish again, depending on the TTY driver
4763
         * used. A 2nd ("constructive") initialization after we opened the input/output fds we actually want
4764
         * will fix this. Note that we pass a NULL invocation ID here – as exec_context_tty_reset() expects
4765
         * the invocation ID associated with the OSC 3008 context ID to close. But we don't want to close any
4766
         * OSC 3008 context here, and opening a fresh OSC 3008 context happens a bit further down. */
4767
        exec_context_tty_reset(context, params, /* invocation_id= */ SD_ID128_NULL);
11,556✔
4768

4769
        if (params->shall_confirm_spawn && exec_context_shall_confirm_spawn(context)) {
11,556✔
4770
                _cleanup_free_ char *cmdline = NULL;
×
4771

4772
                cmdline = quote_command_line(command->argv, SHELL_ESCAPE_EMPTY);
×
4773
                if (!cmdline) {
×
4774
                        *exit_status = EXIT_MEMORY;
×
4775
                        return log_oom();
×
4776
                }
4777

4778
                r = ask_for_confirmation(context, params, cmdline);
×
4779
                if (r != CONFIRM_EXECUTE) {
×
4780
                        if (r == CONFIRM_PRETEND_SUCCESS) {
×
4781
                                *exit_status = EXIT_SUCCESS;
×
4782
                                return 0;
×
4783
                        }
4784

4785
                        *exit_status = EXIT_CONFIRM;
×
4786
                        return log_error_errno(SYNTHETIC_ERRNO(ECANCELED), "Execution cancelled by the user.");
×
4787
                }
4788
        }
4789

4790
        /* We are about to invoke NSS and PAM modules. Let's tell them what we are doing here, maybe they care. This is
4791
         * used by nss-resolve to disable itself when we are about to start systemd-resolved, to avoid deadlocks. Note
4792
         * that these env vars do not survive the execve(), which means they really only apply to the PAM and NSS
4793
         * invocations themselves. Also note that while we'll only invoke NSS modules involved in user management they
4794
         * might internally call into other NSS modules that are involved in hostname resolution, we never know. */
4795
        if (setenv("SYSTEMD_ACTIVATION_UNIT", params->unit_id, true) != 0 ||
23,112✔
4796
            setenv("SYSTEMD_ACTIVATION_SCOPE", runtime_scope_to_string(params->runtime_scope), true) != 0) {
11,556✔
4797
                *exit_status = EXIT_MEMORY;
×
4798
                return log_error_errno(errno, "Failed to update environment: %m");
×
4799
        }
4800

4801
        if (context->dynamic_user && runtime->dynamic_creds) {
11,618✔
4802
                _cleanup_strv_free_ char **suggested_paths = NULL;
62✔
4803

4804
                /* On top of that, make sure we bypass our own NSS module nss-systemd comprehensively for any NSS
4805
                 * checks, if DynamicUser=1 is used, as we shouldn't create a feedback loop with ourselves here. */
4806
                if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
62✔
4807
                        *exit_status = EXIT_USER;
×
4808
                        return log_error_errno(errno, "Failed to update environment: %m");
×
4809
                }
4810

4811
                r = compile_suggested_paths(context, params, &suggested_paths);
62✔
4812
                if (r < 0) {
62✔
4813
                        *exit_status = EXIT_MEMORY;
×
4814
                        return log_oom();
×
4815
                }
4816

4817
                r = dynamic_creds_realize(runtime->dynamic_creds, suggested_paths, &uid, &gid);
62✔
4818
                if (r < 0) {
62✔
4819
                        *exit_status = EXIT_USER;
×
4820
                        if (r == -EILSEQ)
×
4821
                                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
×
4822
                                                       "Failed to update dynamic user credentials: User or group with specified name already exists.");
4823
                        return log_error_errno(r, "Failed to update dynamic user credentials: %m");
×
4824
                }
4825

4826
                if (!uid_is_valid(uid)) {
62✔
4827
                        *exit_status = EXIT_USER;
×
4828
                        return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "UID validation failed for \""UID_FMT"\".", uid);
×
4829
                }
4830

4831
                if (!gid_is_valid(gid)) {
62✔
4832
                        *exit_status = EXIT_USER;
×
4833
                        return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "GID validation failed for \""GID_FMT"\".", gid);
×
4834
                }
4835

4836
                if (runtime->dynamic_creds->user)
62✔
4837
                        username = runtime->dynamic_creds->user->name;
62✔
4838

4839
        } else {
4840
                const char *u;
11,494✔
4841

4842
                if (context->user)
11,494✔
4843
                        u = context->user;
4844
                else if (context->pam_name || FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL)) {
8,945✔
4845
                        /* If PAM is enabled but no user name is explicitly selected, then use our own one. */
4846
                        own_user = getusername_malloc();
65✔
4847
                        if (!own_user) {
65✔
4848
                                *exit_status = EXIT_USER;
×
4849
                                return log_error_errno(r, "Failed to determine my own user ID: %m");
×
4850
                        }
4851
                        u = own_user;
4852
                } else
4853
                        u = NULL;
4854

4855
                if (u) {
4856
                        /* We can't use nss unconditionally for root without risking deadlocks if some IPC services
4857
                         * will be started by pid1 and are ordered after us. But if SetLoginEnvironment= is
4858
                         * enabled *explicitly* (i.e. no exec_context_get_set_login_environment() here),
4859
                         * or PAM shall be invoked, let's consult NSS even for root, so that the user
4860
                         * gets accurate $SHELL in session(-like) contexts. */
4861
                        r = get_fixed_user(u,
2,614✔
4862
                                           /* prefer_nss = */ context->set_login_environment > 0 || context->pam_name,
2,614✔
4863
                                           &username, &uid, &gid, &pwent_home, &shell);
4864
                        if (r < 0) {
2,614✔
4865
                                *exit_status = EXIT_USER;
2✔
4866
                                return log_error_errno(r, "Failed to determine user credentials: %m");
2✔
4867
                        }
4868
                }
4869

4870
                if (context->group) {
11,492✔
4871
                        r = get_fixed_group(context->group, &groupname, &gid);
11✔
4872
                        if (r < 0) {
11✔
4873
                                *exit_status = EXIT_GROUP;
×
4874
                                return log_error_errno(r, "Failed to determine group credentials: %m");
×
4875
                        }
4876
                }
4877
        }
4878

4879
        /* Initialize user supplementary groups and get SupplementaryGroups= ones */
4880
        ngids = get_supplementary_groups(context, username, gid, &gids);
11,554✔
4881
        if (ngids < 0) {
11,554✔
4882
                *exit_status = EXIT_GROUP;
×
4883
                return log_error_errno(ngids, "Failed to determine supplementary groups: %m");
×
4884
        }
4885

4886
        r = send_user_lookup(params->unit_id, params->user_lookup_fd, uid, gid);
11,554✔
4887
        if (r < 0) {
11,554✔
4888
                *exit_status = EXIT_USER;
×
4889
                return log_error_errno(r, "Failed to send user credentials to PID1: %m");
×
4890
        }
4891

4892
        params->user_lookup_fd = safe_close(params->user_lookup_fd);
11,554✔
4893

4894
        r = acquire_home(context, &pwent_home, &home_buffer);
11,554✔
4895
        if (r < 0) {
11,554✔
4896
                *exit_status = EXIT_CHDIR;
×
4897
                return log_error_errno(r, "Failed to determine $HOME for the invoking user: %m");
×
4898
        }
4899

4900
        /* If a socket is connected to STDIN/STDOUT/STDERR, we must drop O_NONBLOCK */
4901
        if (socket_fd >= 0)
11,554✔
4902
                (void) fd_nonblock(socket_fd, false);
17✔
4903

4904
        /* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields.
4905
         * Hence we need to migrate to the target cgroup from init.scope before connecting to journald */
4906
        if (params->cgroup_path) {
11,554✔
4907
                _cleanup_free_ char *p = NULL;
11,554✔
4908

4909
                r = exec_params_get_cgroup_path(params, cgroup_context, &p);
11,554✔
4910
                if (r < 0) {
11,554✔
4911
                        *exit_status = EXIT_CGROUP;
×
4912
                        return log_error_errno(r, "Failed to acquire cgroup path: %m");
×
4913
                }
4914

4915
                r = cg_attach(p, 0);
11,554✔
4916
                if (r == -EUCLEAN) {
11,554✔
4917
                        *exit_status = EXIT_CGROUP;
×
4918
                        return log_error_errno(r,
×
4919
                                               "Failed to attach process to cgroup '%s', "
4920
                                               "because the cgroup or one of its parents or "
4921
                                               "siblings is in the threaded mode.", p);
4922
                }
4923
                if (r < 0) {
11,554✔
4924
                        *exit_status = EXIT_CGROUP;
×
4925
                        return log_error_errno(r, "Failed to attach to cgroup %s: %m", p);
×
4926
                }
4927
        }
4928

4929
        if (context->network_namespace_path && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
11,554✔
4930
                r = open_shareable_ns_path(runtime->shared->netns_storage_socket, context->network_namespace_path, CLONE_NEWNET);
×
4931
                if (r < 0) {
×
4932
                        *exit_status = EXIT_NETWORK;
×
4933
                        return log_error_errno(r, "Failed to open network namespace path %s: %m", context->network_namespace_path);
×
4934
                }
4935
        }
4936

4937
        if (context->ipc_namespace_path && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
11,554✔
4938
                r = open_shareable_ns_path(runtime->shared->ipcns_storage_socket, context->ipc_namespace_path, CLONE_NEWIPC);
×
4939
                if (r < 0) {
×
4940
                        *exit_status = EXIT_NAMESPACE;
×
4941
                        return log_error_errno(r, "Failed to open IPC namespace path %s: %m", context->ipc_namespace_path);
×
4942
                }
4943
        }
4944

4945
        r = setup_input(context, params, socket_fd, named_iofds);
11,554✔
4946
        if (r < 0) {
11,554✔
4947
                *exit_status = EXIT_STDIN;
×
4948
                return log_error_errno(r, "Failed to set up standard input: %m");
×
4949
        }
4950

4951
        _cleanup_free_ char *fname = NULL;
25✔
4952
        r = path_extract_filename(command->path, &fname);
11,554✔
4953
        if (r < 0) {
11,554✔
4954
                *exit_status = EXIT_STDOUT;
×
4955
                return log_error_errno(r, "Failed to extract filename from path %s: %m", command->path);
×
4956
        }
4957

4958
        r = setup_output(context, params, STDOUT_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
11,554✔
4959
        if (r < 0) {
11,554✔
4960
                *exit_status = EXIT_STDOUT;
×
4961
                return log_error_errno(r, "Failed to set up standard output: %m");
×
4962
        }
4963

4964
        r = setup_output(context, params, STDERR_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
11,554✔
4965
        if (r < 0) {
11,554✔
4966
                *exit_status = EXIT_STDERR;
×
4967
                return log_error_errno(r, "Failed to set up standard error output: %m");
×
4968
        }
4969

4970
        /* Now that stdin/stdout are definiely opened, properly initialize it with our desired
4971
         * settings. Note: this is a "constructive" reset, it prepares things for us to use. This is
4972
         * different from the "destructive" TTY reset further up. Also note: we apply this on stdin/stdout in
4973
         * case this is a tty, regardless if we opened it ourselves or got it passed in pre-opened. */
4974
        prepare_terminal(context, params);
11,554✔
4975

4976
        if (context->oom_score_adjust_set) {
11,554✔
4977
                /* When we can't make this change due to EPERM, then let's silently skip over it. User
4978
                 * namespaces prohibit write access to this file, and we shouldn't trip up over that. */
4979
                r = set_oom_score_adjust(context->oom_score_adjust);
1,307✔
4980
                if (ERRNO_IS_NEG_PRIVILEGE(r))
1,307✔
4981
                        log_debug_errno(r, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
×
4982
                else if (r < 0) {
1,307✔
4983
                        *exit_status = EXIT_OOM_ADJUST;
×
4984
                        return log_error_errno(r, "Failed to adjust OOM setting: %m");
×
4985
                }
4986
        }
4987

4988
        if (context->coredump_filter_set) {
11,554✔
4989
                r = set_coredump_filter(context->coredump_filter);
2✔
4990
                if (ERRNO_IS_NEG_PRIVILEGE(r))
2✔
4991
                        log_debug_errno(r, "Failed to adjust coredump_filter, ignoring: %m");
×
4992
                else if (r < 0) {
2✔
4993
                        *exit_status = EXIT_LIMITS;
×
4994
                        return log_error_errno(r, "Failed to adjust coredump_filter: %m");
×
4995
                }
4996
        }
4997

4998
        if (context->cpu_sched_set) {
11,554✔
4999
                struct sched_attr attr = {
×
5000
                        .size = sizeof(attr),
5001
                        .sched_policy = context->cpu_sched_policy,
×
5002
                        .sched_priority = context->cpu_sched_priority,
×
5003
                        .sched_flags = context->cpu_sched_reset_on_fork ? SCHED_FLAG_RESET_ON_FORK : 0,
×
5004
                };
5005

5006
                r = sched_setattr(/* pid= */ 0, &attr, /* flags= */ 0);
×
5007
                if (r < 0) {
×
5008
                        *exit_status = EXIT_SETSCHEDULER;
×
5009
                        return log_error_errno(errno, "Failed to set up CPU scheduling: %m");
×
5010
                }
5011
        }
5012

5013
        /*
5014
         * Set nice value _after_ the call to sched_setattr() because struct sched_attr includes sched_nice
5015
         * which we do not set, thus it will clobber any previously set nice value. Scheduling policy might
5016
         * be reasonably set together with nice value e.g. in case of SCHED_BATCH (see sched(7)).
5017
         * It would be ideal to set both with the same call, but we cannot easily do so because of all the
5018
         * extra logic in setpriority_closest().
5019
         */
5020
        if (context->nice_set) {
11,554✔
5021
                r = setpriority_closest(context->nice);
17✔
5022
                if (r < 0) {
17✔
5023
                        *exit_status = EXIT_NICE;
×
5024
                        return log_error_errno(r, "Failed to set up process scheduling priority (nice level): %m");
×
5025
                }
5026
        }
5027

5028
        if (context->cpu_affinity_from_numa || context->cpu_set.set) {
11,554✔
5029
                _cleanup_(cpu_set_reset) CPUSet converted_cpu_set = {};
2✔
5030
                const CPUSet *cpu_set;
2✔
5031

5032
                if (context->cpu_affinity_from_numa) {
2✔
5033
                        r = exec_context_cpu_affinity_from_numa(context, &converted_cpu_set);
2✔
5034
                        if (r < 0) {
2✔
5035
                                *exit_status = EXIT_CPUAFFINITY;
×
5036
                                return log_error_errno(r, "Failed to derive CPU affinity mask from NUMA mask: %m");
×
5037
                        }
5038

5039
                        cpu_set = &converted_cpu_set;
5040
                } else
5041
                        cpu_set = &context->cpu_set;
×
5042

5043
                if (sched_setaffinity(0, cpu_set->allocated, cpu_set->set) < 0) {
2✔
5044
                        *exit_status = EXIT_CPUAFFINITY;
×
5045
                        return log_error_errno(errno, "Failed to set up CPU affinity: %m");
×
5046
                }
5047
        }
5048

5049
        if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) {
11,554✔
5050
                r = apply_numa_policy(&context->numa_policy);
19✔
5051
                if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
19✔
5052
                        log_debug_errno(r, "NUMA support not available, ignoring.");
×
5053
                else if (r < 0) {
19✔
5054
                        *exit_status = EXIT_NUMA_POLICY;
2✔
5055
                        return log_error_errno(r, "Failed to set NUMA memory policy: %m");
2✔
5056
                }
5057
        }
5058

5059
        if (context->ioprio_set)
11,552✔
5060
                if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
9✔
5061
                        *exit_status = EXIT_IOPRIO;
×
5062
                        return log_error_errno(errno, "Failed to set up IO scheduling priority: %m");
×
5063
                }
5064

5065
        if (context->timer_slack_nsec != NSEC_INFINITY)
11,552✔
5066
                if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
×
5067
                        *exit_status = EXIT_TIMERSLACK;
×
5068
                        return log_error_errno(errno, "Failed to set up timer slack: %m");
×
5069
                }
5070

5071
        if (context->personality != PERSONALITY_INVALID) {
11,552✔
5072
                r = safe_personality(context->personality);
×
5073
                if (r < 0) {
×
5074
                        *exit_status = EXIT_PERSONALITY;
×
5075
                        return log_error_errno(r, "Failed to set up execution domain (personality): %m");
×
5076
                }
5077
        }
5078

5079
        if (context->memory_ksm >= 0)
11,552✔
5080
                if (prctl(PR_SET_MEMORY_MERGE, context->memory_ksm, 0, 0, 0) < 0) {
×
5081
                        if (ERRNO_IS_NOT_SUPPORTED(errno))
×
5082
                                log_debug_errno(errno, "KSM support not available, ignoring.");
×
5083
                        else {
5084
                                *exit_status = EXIT_KSM;
×
5085
                                return log_error_errno(errno, "Failed to set KSM: %m");
×
5086
                        }
5087
                }
5088

5089
#if ENABLE_UTMP
5090
        if (context->utmp_id) {
11,552✔
5091
                _cleanup_free_ char *username_alloc = NULL;
156✔
5092

5093
                if (!username && context->utmp_mode == EXEC_UTMP_USER) {
156✔
5094
                        username_alloc = uid_to_name(uid_is_valid(uid) ? uid : saved_uid);
1✔
5095
                        if (!username_alloc) {
1✔
5096
                                *exit_status = EXIT_USER;
×
5097
                                return log_oom();
×
5098
                        }
5099
                }
5100

5101
                const char *line = context->tty_path ?
×
5102
                        (path_startswith(context->tty_path, "/dev/") ?: context->tty_path) :
156✔
5103
                        NULL;
5104
                utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
156✔
5105
                                      line,
5106
                                      context->utmp_mode == EXEC_UTMP_INIT  ? INIT_PROCESS :
156✔
5107
                                      context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
7✔
5108
                                      USER_PROCESS,
5109
                                      username ?: username_alloc);
156✔
5110
        }
5111
#endif
5112

5113
        if (uid_is_valid(uid)) {
11,552✔
5114
                r = chown_terminal(STDIN_FILENO, uid);
2,674✔
5115
                if (r < 0) {
2,674✔
5116
                        *exit_status = EXIT_STDIN;
×
5117
                        return log_error_errno(r, "Failed to change ownership of terminal: %m");
×
5118
                }
5119
        }
5120

5121
        /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted
5122
         * from it. */
5123
        needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
11,552✔
5124

5125
        if (params->cgroup_path) {
11,552✔
5126
                /* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1
5127
                 * this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not
5128
                 * safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only
5129
                 * touch a single hierarchy too. */
5130

5131
                if (params->flags & EXEC_CGROUP_DELEGATE) {
11,552✔
5132
                        _cleanup_free_ char *p = NULL;
667✔
5133

5134
                        r = cg_set_access(params->cgroup_path, uid, gid);
667✔
5135
                        if (r < 0) {
667✔
5136
                                *exit_status = EXIT_CGROUP;
×
5137
                                return log_error_errno(r, "Failed to adjust control group access: %m");
×
5138
                        }
5139

5140
                        r = exec_params_get_cgroup_path(params, cgroup_context, &p);
667✔
5141
                        if (r < 0) {
667✔
5142
                                *exit_status = EXIT_CGROUP;
×
5143
                                return log_error_errno(r, "Failed to acquire cgroup path: %m");
×
5144
                        }
5145
                        if (r > 0) {
667✔
5146
                                r = cg_set_access_recursive(p, uid, gid);
326✔
5147
                                if (r < 0) {
326✔
5148
                                        *exit_status = EXIT_CGROUP;
×
5149
                                        return log_error_errno(r, "Failed to adjust control subgroup access: %m");
×
5150
                                }
5151
                        }
5152
                }
5153

5154
                if (is_pressure_supported() > 0) {
11,552✔
5155
                        if (cgroup_context_want_memory_pressure(cgroup_context)) {
11,552✔
5156
                                r = cg_get_path("memory", params->cgroup_path, "memory.pressure", &memory_pressure_path);
11,155✔
5157
                                if (r < 0) {
11,155✔
5158
                                        *exit_status = EXIT_MEMORY;
×
5159
                                        return log_oom();
×
5160
                                }
5161

5162
                                r = chmod_and_chown(memory_pressure_path, 0644, uid, gid);
11,155✔
5163
                                if (r < 0) {
11,155✔
5164
                                        log_full_errno(r == -ENOENT || ERRNO_IS_PRIVILEGE(r) ? LOG_DEBUG : LOG_WARNING, r,
2✔
5165
                                                       "Failed to adjust ownership of '%s', ignoring: %m", memory_pressure_path);
5166
                                        memory_pressure_path = mfree(memory_pressure_path);
1✔
5167
                                }
5168
                                /* First we use the current cgroup path to chmod and chown the memory pressure path, then pass the path relative
5169
                                 * to the cgroup namespace to environment variables and mounts. If chown/chmod fails, we should not pass memory
5170
                                 * pressure path environment variable or read-write mount to the unit. This is why we check if
5171
                                 * memory_pressure_path != NULL in the conditional below. */
5172
                                if (memory_pressure_path && needs_sandboxing && exec_needs_cgroup_namespace(context)) {
11,155✔
5173
                                        memory_pressure_path = mfree(memory_pressure_path);
13✔
5174
                                        r = cg_get_path("memory", "", "memory.pressure", &memory_pressure_path);
13✔
5175
                                        if (r < 0) {
13✔
5176
                                                *exit_status = EXIT_MEMORY;
×
5177
                                                return log_oom();
×
5178
                                        }
5179
                                }
5180
                        } else if (cgroup_context->memory_pressure_watch == CGROUP_PRESSURE_WATCH_NO) {
397✔
5181
                                memory_pressure_path = strdup("/dev/null"); /* /dev/null is explicit indicator for turning of memory pressure watch */
×
5182
                                if (!memory_pressure_path) {
×
5183
                                        *exit_status = EXIT_MEMORY;
×
5184
                                        return log_oom();
×
5185
                                }
5186
                        }
5187
                }
5188
        }
5189

5190
        needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
11,552✔
5191

5192
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
69,307✔
5193
                r = setup_exec_directory(context, params, uid, gid, dt, needs_mount_namespace, exit_status);
57,756✔
5194
                if (r < 0)
57,756✔
5195
                        return log_error_errno(r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
1✔
5196
        }
5197

5198
        r = exec_setup_credentials(context, params, params->unit_id, uid, gid);
11,551✔
5199
        if (r < 0) {
9,605✔
5200
                *exit_status = EXIT_CREDENTIALS;
×
5201
                return log_error_errno(r, "Failed to set up credentials: %m");
×
5202
        }
5203

5204
        r = build_environment(
9,605✔
5205
                        context,
5206
                        params,
5207
                        cgroup_context,
5208
                        n_fds,
5209
                        pwent_home,
5210
                        username,
5211
                        shell,
5212
                        journal_stream_dev,
5213
                        journal_stream_ino,
5214
                        memory_pressure_path,
5215
                        needs_sandboxing,
5216
                        &our_env);
5217
        if (r < 0) {
9,605✔
5218
                *exit_status = EXIT_MEMORY;
×
5219
                return log_oom();
×
5220
        }
5221

5222
        r = build_pass_environment(context, &pass_env);
9,605✔
5223
        if (r < 0) {
9,605✔
5224
                *exit_status = EXIT_MEMORY;
×
5225
                return log_oom();
×
5226
        }
5227

5228
        /* The $PATH variable is set to the default path in params->environment. However, this is overridden
5229
         * if user-specified fields have $PATH set. The intention is to also override $PATH if the unit does
5230
         * not specify PATH but the unit has ExecSearchPath. */
5231
        if (!strv_isempty(context->exec_search_path)) {
9,605✔
5232
                _cleanup_free_ char *joined = NULL;
×
5233

5234
                joined = strv_join(context->exec_search_path, ":");
×
5235
                if (!joined) {
×
5236
                        *exit_status = EXIT_MEMORY;
×
5237
                        return log_oom();
×
5238
                }
5239

5240
                r = strv_env_assign(&joined_exec_search_path, "PATH", joined);
×
5241
                if (r < 0) {
×
5242
                        *exit_status = EXIT_MEMORY;
×
5243
                        return log_oom();
×
5244
                }
5245
        }
5246

5247
        accum_env = strv_env_merge(params->environment,
9,605✔
5248
                                   our_env,
5249
                                   joined_exec_search_path,
5250
                                   pass_env,
5251
                                   context->environment,
5252
                                   params->files_env);
5253
        if (!accum_env) {
9,605✔
5254
                *exit_status = EXIT_MEMORY;
×
5255
                return log_oom();
×
5256
        }
5257
        accum_env = strv_env_clean(accum_env);
9,605✔
5258

5259
        (void) umask(context->umask);
9,605✔
5260

5261
        r = setup_keyring(context, params, uid, gid);
9,605✔
5262
        if (r < 0) {
9,605✔
5263
                *exit_status = EXIT_KEYRING;
×
5264
                return log_error_errno(r, "Failed to set up kernel keyring: %m");
×
5265
        }
5266

5267
        /* We need setresuid() if the caller asked us to apply sandboxing and the command isn't explicitly
5268
         * excepted from either whole sandboxing or just setresuid() itself. */
5269
        needs_setuid = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & (EXEC_COMMAND_FULLY_PRIVILEGED|EXEC_COMMAND_NO_SETUID));
9,605✔
5270

5271
        uint64_t capability_ambient_set = context->capability_ambient_set;
9,605✔
5272

5273
        /* Check CAP_SYS_ADMIN before we enter user namespace to see if we can mount /proc even though its masked. */
5274
        have_cap_sys_admin = have_effective_cap(CAP_SYS_ADMIN) > 0;
9,605✔
5275

5276
        if (needs_sandboxing) {
9,605✔
5277
                /* MAC enablement checks need to be done before a new mount ns is created, as they rely on
5278
                 * /sys being present. The actual MAC context application will happen later, as late as
5279
                 * possible, to avoid impacting our own code paths. */
5280

5281
#if HAVE_SELINUX
5282
                use_selinux = mac_selinux_use();
5283
#endif
5284
#if ENABLE_SMACK
5285
                use_smack = mac_smack_use();
9,604✔
5286
#endif
5287
#if HAVE_APPARMOR
5288
                if (mac_apparmor_use()) {
5289
                        r = dlopen_libapparmor();
5290
                        if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r))
5291
                                log_warning_errno(r, "Failed to load libapparmor, ignoring: %m");
5292
                        use_apparmor = r >= 0;
5293
                }
5294
#endif
5295
        }
5296

5297
        if (needs_sandboxing) {
9,604✔
5298
                int which_failed;
9,604✔
5299

5300
                /* Let's set the resource limits before we call into PAM, so that pam_limits wins over what
5301
                 * is set here. (See below.) */
5302

5303
                r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed);
9,604✔
5304
                if (r < 0) {
9,604✔
5305
                        *exit_status = EXIT_LIMITS;
×
5306
                        return log_error_errno(r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
×
5307
                }
5308
        }
5309

5310
        if (needs_setuid && context->pam_name && username) {
9,605✔
5311
                /* Let's call into PAM after we set up our own idea of resource limits so that pam_limits
5312
                 * wins here. (See above.) */
5313

5314
                /* All fds passed in the fds array will be closed in the pam child process. */
5315
                r = setup_pam(context, params, username, uid, gid, &accum_env, params->fds, n_fds, params->exec_fd);
402✔
5316
                if (r < 0) {
402✔
5317
                        *exit_status = EXIT_PAM;
×
5318
                        return log_error_errno(r, "Failed to set up PAM session: %m");
×
5319
                }
5320

5321
                /* PAM modules might have set some ambient caps. Query them here and merge them into
5322
                 * the caps we want to set in the end, so that we don't end up unsetting them. */
5323
                uint64_t ambient_after_pam;
402✔
5324
                r = capability_get_ambient(&ambient_after_pam);
402✔
5325
                if (r < 0) {
402✔
5326
                        *exit_status = EXIT_CAPABILITIES;
×
5327
                        return log_error_errno(r, "Failed to query ambient caps: %m");
×
5328
                }
5329

5330
                capability_ambient_set |= ambient_after_pam;
402✔
5331

5332
                ngids_after_pam = getgroups_alloc(&gids_after_pam);
402✔
5333
                if (ngids_after_pam < 0) {
402✔
5334
                        *exit_status = EXIT_GROUP;
×
5335
                        return log_error_errno(ngids_after_pam, "Failed to obtain groups after setting up PAM: %m");
×
5336
                }
5337
        }
5338

5339
        if (needs_sandboxing && !have_cap_sys_admin && exec_context_needs_cap_sys_admin(context)) {
9,605✔
5340
                /* If we're unprivileged, set up the user namespace first to enable use of the other namespaces.
5341
                 * Users with CAP_SYS_ADMIN can set up user namespaces last because they will be able to
5342
                 * set up all of the other namespaces (i.e. network, mount, UTS) without a user namespace. */
5343
                PrivateUsers pu = exec_context_get_effective_private_users(context, params);
27✔
5344
                if (pu == PRIVATE_USERS_NO)
27✔
5345
                        pu = PRIVATE_USERS_SELF;
23✔
5346

5347
                /* The kernel requires /proc/pid/setgroups be set to "deny" prior to writing /proc/pid/gid_map in
5348
                 * unprivileged user namespaces. */
5349
                r = setup_private_users(pu, saved_uid, saved_gid, uid, gid, /* allow_setgroups= */ false);
27✔
5350
                /* If it was requested explicitly and we can't set it up, fail early. Otherwise, continue and let
5351
                 * the actual requested operations fail (or silently continue). */
5352
                if (r < 0 && context->private_users != PRIVATE_USERS_NO) {
27✔
5353
                        *exit_status = EXIT_USER;
×
5354
                        return log_error_errno(r, "Failed to set up user namespacing for unprivileged user: %m");
×
5355
                }
5356
                if (r < 0)
×
5357
                        log_info_errno(r, "Failed to set up user namespacing for unprivileged user, ignoring: %m");
×
5358
                else {
5359
                        assert(r > 0);
27✔
5360
                        userns_set_up = true;
27✔
5361
                        log_debug("Set up unprivileged user namespace");
27✔
5362
                }
5363
        }
5364

5365
        /* Call setup_delegated_namespaces() the first time to unshare all non-delegated namespaces. */
5366
        r = setup_delegated_namespaces(
9,605✔
5367
                        context,
5368
                        params,
5369
                        runtime,
5370
                        /* delegate= */ false,
5371
                        memory_pressure_path,
5372
                        uid,
5373
                        gid,
5374
                        command,
5375
                        needs_sandboxing,
5376
                        have_cap_sys_admin,
5377
                        exit_status);
5378
        if (r < 0)
9,601✔
5379
                return r;
5380

5381
        /* Drop groups as early as possible.
5382
         * This needs to be done after PrivateDevices=yes setup as device nodes should be owned by the host's root.
5383
         * For non-root in a userns, devices will be owned by the user/group before the group change, and nobody. */
5384
        if (needs_setuid) {
9,585✔
5385
                _cleanup_free_ gid_t *gids_to_enforce = NULL;
9,584✔
5386
                int ngids_to_enforce;
9,584✔
5387

5388
                ngids_to_enforce = merge_gid_lists(gids,
9,584✔
5389
                                                   ngids,
5390
                                                   gids_after_pam,
5391
                                                   ngids_after_pam,
5392
                                                   &gids_to_enforce);
5393
                if (ngids_to_enforce < 0) {
9,584✔
5394
                        *exit_status = EXIT_GROUP;
×
5395
                        return log_error_errno(ngids_to_enforce, "Failed to merge group lists. Group membership might be incorrect: %m");
×
5396
                }
5397

5398
                r = enforce_groups(gid, gids_to_enforce, ngids_to_enforce);
9,584✔
5399
                if (r < 0) {
9,584✔
5400
                        *exit_status = EXIT_GROUP;
1✔
5401
                        return log_error_errno(r, "Changing group credentials failed: %m");
1✔
5402
                }
5403
        }
5404

5405
        /* If the user namespace was not set up above, try to do it now.
5406
         * It's preferred to set up the user namespace later (after all other namespaces) so as not to be
5407
         * restricted by rules pertaining to combining user namespaces with other namespaces (e.g. in the
5408
         * case of mount namespaces being less privileged when the mount point list is copied from a
5409
         * different user namespace). */
5410

5411
        if (needs_sandboxing && !userns_set_up) {
9,584✔
5412
                PrivateUsers pu = exec_context_get_effective_private_users(context, params);
9,561✔
5413

5414
                r = setup_private_users(pu, saved_uid, saved_gid, uid, gid,
9,561✔
5415
                                        /* allow_setgroups= */ pu == PRIVATE_USERS_FULL);
5416
                if (r < 0) {
9,561✔
5417
                        *exit_status = EXIT_USER;
×
5418
                        return log_error_errno(r, "Failed to set up user namespacing: %m");
×
5419
                }
5420
                if (r > 0)
9,561✔
5421
                        log_debug("Set up privileged user namespace");
25✔
5422
        }
5423

5424
        /* Call setup_delegated_namespaces() the second time to unshare all delegated namespaces. */
5425
        r = setup_delegated_namespaces(
9,584✔
5426
                        context,
5427
                        params,
5428
                        runtime,
5429
                        /* delegate= */ true,
5430
                        memory_pressure_path,
5431
                        uid,
5432
                        gid,
5433
                        command,
5434
                        needs_sandboxing,
5435
                        have_cap_sys_admin,
5436
                        exit_status);
5437
        if (r < 0)
9,580✔
5438
                return r;
5439

5440
        /* Now that the mount namespace has been set up and privileges adjusted, let's look for the thing we
5441
         * shall execute. */
5442

5443
        const char *path = command->path;
9,580✔
5444

5445
        if (FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL)) {
9,580✔
5446
                if (shell_is_placeholder(shell)) {
13✔
5447
                        log_debug("Shell prefixing requested for user without default shell, using /bin/sh: %s",
2✔
5448
                                  strna(username));
5449
                        assert(streq(path, _PATH_BSHELL));
2✔
5450
                } else
5451
                        path = shell;
5452
        }
5453

5454
        _cleanup_free_ char *executable = NULL;
5✔
5455
        _cleanup_close_ int executable_fd = -EBADF;
5✔
5456
        r = find_executable_full(path, /* root= */ NULL, context->exec_search_path, false, &executable, &executable_fd);
9,580✔
5457
        if (r < 0) {
9,580✔
5458
                *exit_status = EXIT_EXEC;
1✔
5459
                log_struct_errno(LOG_NOTICE, r,
1✔
5460
                                 LOG_MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED_STR),
5461
                                 LOG_EXEC_MESSAGE(params, "Unable to locate executable '%s': %m", path),
5462
                                 LOG_ITEM("EXECUTABLE=%s", path));
5463
                /* If the error will be ignored by manager, tune down the log level here. Missing executable
5464
                 * is very much expected in this case. */
5465
                return r != -ENOMEM && FLAGS_SET(command->flags, EXEC_COMMAND_IGNORE_FAILURE) ? 1 : r;
1✔
5466
        }
5467

5468
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &executable_fd);
9,579✔
5469
        if (r < 0) {
9,579✔
5470
                *exit_status = EXIT_FDS;
×
5471
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
5472
        }
5473

5474
#if HAVE_SELINUX
5475
        if (needs_sandboxing && use_selinux && params->selinux_context_net) {
5476
                int fd = -EBADF;
5477

5478
                if (socket_fd >= 0)
5479
                        fd = socket_fd;
5480
                else if (params->n_socket_fds == 1)
5481
                        /* If stdin is not connected to a socket but we are triggered by exactly one socket unit then we
5482
                         * use context from that fd to compute the label. */
5483
                        fd = params->fds[0];
5484

5485
                if (fd >= 0) {
5486
                        r = mac_selinux_get_child_mls_label(fd, executable, context->selinux_context, &mac_selinux_context_net);
5487
                        if (r < 0) {
5488
                                if (!context->selinux_context_ignore) {
5489
                                        *exit_status = EXIT_SELINUX_CONTEXT;
5490
                                        return log_error_errno(r, "Failed to determine SELinux context: %m");
5491
                                }
5492
                                log_debug_errno(r, "Failed to determine SELinux context, ignoring: %m");
5493
                        }
5494
                }
5495
        }
5496
#endif
5497

5498
        /* We repeat the fd closing here, to make sure that nothing is leaked from the PAM modules. Note that
5499
         * we are more aggressive this time, since we don't need socket_fd and the netns and ipcns fds any
5500
         * more. We do keep exec_fd and handoff_timestamp_fd however, if we have it, since we need to keep
5501
         * them open until the final execve(). But first, close the remaining sockets in the context
5502
         * objects. */
5503

5504
        exec_runtime_close(runtime);
9,579✔
5505
        exec_params_close(params);
9,579✔
5506

5507
        r = close_all_fds(keep_fds, n_keep_fds);
9,579✔
5508
        if (r >= 0)
9,579✔
5509
                r = pack_fds(params->fds, n_fds);
9,579✔
5510
        if (r >= 0)
9,579✔
5511
                r = flag_fds(params->fds, n_socket_fds, n_fds, context->non_blocking);
9,579✔
5512
        if (r < 0) {
9,579✔
5513
                *exit_status = EXIT_FDS;
×
5514
                return log_error_errno(r, "Failed to adjust passed file descriptors: %m");
×
5515
        }
5516

5517
        /* At this point, the fds we want to pass to the program are all ready and set up, with O_CLOEXEC turned off
5518
         * and at the right fd numbers. The are no other fds open, with one exception: the exec_fd if it is defined,
5519
         * and it has O_CLOEXEC set, after all we want it to be closed by the execve(), so that our parent knows we
5520
         * came this far. */
5521

5522
        secure_bits = context->secure_bits;
9,579✔
5523

5524
        if (needs_sandboxing) {
9,579✔
5525
                uint64_t bset;
9,578✔
5526

5527
                /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested.
5528
                 * (Note this is placed after the general resource limit initialization, see above, in order
5529
                 * to take precedence.) */
5530
                if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
9,578✔
5531
                        if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
1,493✔
5532
                                *exit_status = EXIT_LIMITS;
×
5533
                                return log_error_errno(errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m");
×
5534
                        }
5535
                }
5536

5537
#if ENABLE_SMACK
5538
                /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the
5539
                 * process. This is the latest place before dropping capabilities. Other MAC context are set later. */
5540
                if (use_smack) {
9,578✔
5541
                        r = setup_smack(context, params, executable_fd);
×
5542
                        if (r < 0 && !context->smack_process_label_ignore) {
×
5543
                                *exit_status = EXIT_SMACK_PROCESS_LABEL;
×
5544
                                return log_error_errno(r, "Failed to set SMACK process label: %m");
×
5545
                        }
5546
                }
5547
#endif
5548

5549
                bset = context->capability_bounding_set;
9,578✔
5550

5551
#if HAVE_SECCOMP
5552
                /* If the service has any form of a seccomp filter and it allows dropping privileges, we'll
5553
                 * keep the needed privileges to apply it even if we're not root. */
5554
                if (needs_setuid &&
19,156✔
5555
                    uid_is_valid(uid) &&
11,598✔
5556
                    context_has_seccomp(context) &&
2,772✔
5557
                    seccomp_allows_drop_privileges(context)) {
752✔
5558
                        keep_seccomp_privileges = true;
752✔
5559

5560
                        if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
752✔
5561
                                *exit_status = EXIT_USER;
×
5562
                                return log_error_errno(errno, "Failed to enable keep capabilities flag: %m");
×
5563
                        }
5564

5565
                        /* Save the current bounding set so we can restore it after applying the seccomp
5566
                         * filter */
5567
                        saved_bset = bset;
752✔
5568
                        bset |= (UINT64_C(1) << CAP_SYS_ADMIN) |
752✔
5569
                                (UINT64_C(1) << CAP_SETPCAP);
5570
                }
5571
#endif
5572

5573
                if (!cap_test_all(bset)) {
9,578✔
5574
                        r = capability_bounding_set_drop(bset, /* right_now= */ false);
1,619✔
5575
                        if (r < 0) {
1,619✔
5576
                                *exit_status = EXIT_CAPABILITIES;
×
5577
                                return log_error_errno(r, "Failed to drop capabilities: %m");
×
5578
                        }
5579
                }
5580

5581
                /* Ambient capabilities are cleared during setresuid() (in enforce_user()) even with
5582
                 * keep-caps set.
5583
                 *
5584
                 * To be able to raise the ambient capabilities after setresuid() they have to be added to
5585
                 * the inherited set and keep caps has to be set (done in enforce_user()).  After setresuid()
5586
                 * the ambient capabilities can be raised as they are present in the permitted and
5587
                 * inhertiable set. However it is possible that someone wants to set ambient capabilities
5588
                 * without changing the user, so we also set the ambient capabilities here.
5589
                 *
5590
                 * The requested ambient capabilities are raised in the inheritable set if the second
5591
                 * argument is true. */
5592
                if (capability_ambient_set != 0) {
9,578✔
5593
                        r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ true);
746✔
5594
                        if (r < 0) {
746✔
5595
                                *exit_status = EXIT_CAPABILITIES;
×
5596
                                return log_error_errno(r, "Failed to apply ambient capabilities (before UID change): %m");
×
5597
                        }
5598
                }
5599
        }
5600

5601
        /* chroot to root directory first, before we lose the ability to chroot */
5602
        r = apply_root_directory(context, params, runtime, needs_mount_namespace, exit_status);
9,579✔
5603
        if (r < 0)
9,579✔
5604
                return log_error_errno(r, "Chrooting to the requested root directory failed: %m");
×
5605

5606
        if (needs_setuid) {
9,579✔
5607
                if (uid_is_valid(uid)) {
9,578✔
5608
                        r = enforce_user(context, uid, capability_ambient_set);
2,020✔
5609
                        if (r < 0) {
2,020✔
5610
                                *exit_status = EXIT_USER;
×
5611
                                return log_error_errno(r, "Failed to change UID to " UID_FMT ": %m", uid);
×
5612
                        }
5613

5614
                        if (keep_seccomp_privileges) {
2,020✔
5615
                                if (!BIT_SET(capability_ambient_set, CAP_SETUID)) {
752✔
5616
                                        r = drop_capability(CAP_SETUID);
752✔
5617
                                        if (r < 0) {
752✔
5618
                                                *exit_status = EXIT_USER;
×
5619
                                                return log_error_errno(r, "Failed to drop CAP_SETUID: %m");
×
5620
                                        }
5621
                                }
5622

5623
                                r = keep_capability(CAP_SYS_ADMIN);
752✔
5624
                                if (r < 0) {
752✔
5625
                                        *exit_status = EXIT_USER;
×
5626
                                        return log_error_errno(r, "Failed to keep CAP_SYS_ADMIN: %m");
×
5627
                                }
5628

5629
                                r = keep_capability(CAP_SETPCAP);
752✔
5630
                                if (r < 0) {
752✔
5631
                                        *exit_status = EXIT_USER;
×
5632
                                        return log_error_errno(r, "Failed to keep CAP_SETPCAP: %m");
×
5633
                                }
5634
                        }
5635

5636
                        if (capability_ambient_set != 0) {
2,020✔
5637

5638
                                /* Raise the ambient capabilities after user change. */
5639
                                r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ false);
743✔
5640
                                if (r < 0) {
743✔
5641
                                        *exit_status = EXIT_CAPABILITIES;
×
5642
                                        return log_error_errno(r, "Failed to apply ambient capabilities (after UID change): %m");
×
5643
                                }
5644
                        }
5645
                }
5646
        }
5647

5648
        /* Apply working directory here, because the working directory might be on NFS and only the user
5649
         * running this service might have the correct privilege to change to the working directory. Also, it
5650
         * is absolutely 💣 crucial 💣 we applied all mount namespacing rearrangements before this, so that
5651
         * the cwd cannot be used to pin directories outside of the sandbox. */
5652
        r = apply_working_directory(context, params, runtime, pwent_home, accum_env);
9,579✔
5653
        if (r < 0) {
9,579✔
5654
                *exit_status = EXIT_CHDIR;
1✔
5655
                return log_error_errno(r, "Changing to the requested working directory failed: %m");
1✔
5656
        }
5657

5658
        if (needs_sandboxing) {
9,578✔
5659
                /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to
5660
                 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
5661
                 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
5662
                 * are restricted. */
5663

5664
#if HAVE_SELINUX
5665
                if (use_selinux) {
5666
                        char *exec_context = mac_selinux_context_net ?: context->selinux_context;
5667

5668
                        if (exec_context) {
5669
                                r = setexeccon(exec_context);
5670
                                if (r < 0) {
5671
                                        if (!context->selinux_context_ignore) {
5672
                                                *exit_status = EXIT_SELINUX_CONTEXT;
5673
                                                return log_error_errno(r, "Failed to change SELinux context to %s: %m", exec_context);
5674
                                        }
5675
                                        log_debug_errno(r, "Failed to change SELinux context to %s, ignoring: %m", exec_context);
5676
                                }
5677
                        }
5678
                }
5679
#endif
5680

5681
#if HAVE_APPARMOR
5682
                if (use_apparmor && context->apparmor_profile) {
5683
                        r = ASSERT_PTR(sym_aa_change_onexec)(context->apparmor_profile);
5684
                        if (r < 0 && !context->apparmor_profile_ignore) {
5685
                                *exit_status = EXIT_APPARMOR_PROFILE;
5686
                                return log_error_errno(errno, "Failed to prepare AppArmor profile change to %s: %m",
5687
                                                       context->apparmor_profile);
5688
                        }
5689
                }
5690
#endif
5691

5692
                /* PR_GET_SECUREBITS is not privileged, while PR_SET_SECUREBITS is. So to suppress potential
5693
                 * EPERMs we'll try not to call PR_SET_SECUREBITS unless necessary. Setting securebits
5694
                 * requires CAP_SETPCAP. */
5695
                if (prctl(PR_GET_SECUREBITS) != secure_bits) {
9,577✔
5696
                        /* CAP_SETPCAP is required to set securebits. This capability is raised into the
5697
                         * effective set here.
5698
                         *
5699
                         * The effective set is overwritten during execve() with the following values:
5700
                         *
5701
                         * - ambient set (for non-root processes)
5702
                         *
5703
                         * - (inheritable | bounding) set for root processes)
5704
                         *
5705
                         * Hence there is no security impact to raise it in the effective set before execve
5706
                         */
5707
                        r = capability_gain_cap_setpcap(/* ret_before_caps = */ NULL);
804✔
5708
                        if (r < 0) {
804✔
5709
                                *exit_status = EXIT_CAPABILITIES;
×
5710
                                return log_error_errno(r, "Failed to gain CAP_SETPCAP for setting secure bits");
×
5711
                        }
5712
                        if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
804✔
5713
                                *exit_status = EXIT_SECUREBITS;
×
5714
                                return log_error_errno(errno, "Failed to set process secure bits: %m");
×
5715
                        }
5716
                }
5717

5718
                if (context_has_no_new_privileges(context))
9,577✔
5719
                        if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
1,416✔
5720
                                *exit_status = EXIT_NO_NEW_PRIVILEGES;
×
5721
                                return log_error_errno(errno, "Failed to disable new privileges: %m");
×
5722
                        }
5723

5724
#if HAVE_SECCOMP
5725
                r = apply_address_families(context, params);
9,577✔
5726
                if (r < 0) {
9,577✔
5727
                        *exit_status = EXIT_ADDRESS_FAMILIES;
×
5728
                        return log_error_errno(r, "Failed to restrict address families: %m");
×
5729
                }
5730

5731
                r = apply_memory_deny_write_execute(context, params);
9,577✔
5732
                if (r < 0) {
9,577✔
5733
                        *exit_status = EXIT_SECCOMP;
×
5734
                        return log_error_errno(r, "Failed to disable writing to executable memory: %m");
×
5735
                }
5736

5737
                r = apply_restrict_realtime(context, params);
9,577✔
5738
                if (r < 0) {
9,577✔
5739
                        *exit_status = EXIT_SECCOMP;
×
5740
                        return log_error_errno(r, "Failed to apply realtime restrictions: %m");
×
5741
                }
5742

5743
                r = apply_restrict_suid_sgid(context, params);
9,577✔
5744
                if (r < 0) {
9,577✔
5745
                        *exit_status = EXIT_SECCOMP;
×
5746
                        return log_error_errno(r, "Failed to apply SUID/SGID restrictions: %m");
×
5747
                }
5748

5749
                r = apply_restrict_namespaces(context, params);
9,577✔
5750
                if (r < 0) {
9,577✔
5751
                        *exit_status = EXIT_SECCOMP;
×
5752
                        return log_error_errno(r, "Failed to apply namespace restrictions: %m");
×
5753
                }
5754

5755
                r = apply_protect_sysctl(context, params);
9,577✔
5756
                if (r < 0) {
9,577✔
5757
                        *exit_status = EXIT_SECCOMP;
×
5758
                        return log_error_errno(r, "Failed to apply sysctl restrictions: %m");
×
5759
                }
5760

5761
                r = apply_protect_kernel_modules(context, params);
9,577✔
5762
                if (r < 0) {
9,577✔
5763
                        *exit_status = EXIT_SECCOMP;
×
5764
                        return log_error_errno(r, "Failed to apply module loading restrictions: %m");
×
5765
                }
5766

5767
                r = apply_protect_kernel_logs(context, params);
9,577✔
5768
                if (r < 0) {
9,577✔
5769
                        *exit_status = EXIT_SECCOMP;
×
5770
                        return log_error_errno(r, "Failed to apply kernel log restrictions: %m");
×
5771
                }
5772

5773
                r = apply_protect_clock(context, params);
9,577✔
5774
                if (r < 0) {
9,577✔
5775
                        *exit_status = EXIT_SECCOMP;
×
5776
                        return log_error_errno(r, "Failed to apply clock restrictions: %m");
×
5777
                }
5778

5779
                r = apply_private_devices(context, params);
9,577✔
5780
                if (r < 0) {
9,577✔
5781
                        *exit_status = EXIT_SECCOMP;
×
5782
                        return log_error_errno(r, "Failed to set up private devices: %m");
×
5783
                }
5784

5785
                r = apply_syscall_archs(context, params);
9,577✔
5786
                if (r < 0) {
9,577✔
5787
                        *exit_status = EXIT_SECCOMP;
×
5788
                        return log_error_errno(r, "Failed to apply syscall architecture restrictions: %m");
×
5789
                }
5790

5791
                r = apply_lock_personality(context, params);
9,577✔
5792
                if (r < 0) {
9,577✔
5793
                        *exit_status = EXIT_SECCOMP;
×
5794
                        return log_error_errno(r, "Failed to lock personalities: %m");
×
5795
                }
5796

5797
                r = apply_syscall_log(context, params);
9,577✔
5798
                if (r < 0) {
9,577✔
5799
                        *exit_status = EXIT_SECCOMP;
×
5800
                        return log_error_errno(r, "Failed to apply system call log filters: %m");
×
5801
                }
5802
#endif
5803

5804
#if HAVE_LIBBPF
5805
                r = apply_restrict_filesystems(context, params);
9,577✔
5806
                if (r < 0) {
9,577✔
5807
                        *exit_status = EXIT_BPF;
×
5808
                        return log_error_errno(r, "Failed to restrict filesystems: %m");
×
5809
                }
5810
#endif
5811

5812
#if HAVE_SECCOMP
5813
                /* This really should remain as close to the execve() as possible, to make sure our own code is affected
5814
                 * by the filter as little as possible. */
5815
                r = apply_syscall_filter(context, params);
9,577✔
5816
                if (r < 0) {
9,577✔
5817
                        *exit_status = EXIT_SECCOMP;
×
5818
                        return log_error_errno(r, "Failed to apply system call filters: %m");
×
5819
                }
5820

5821
                if (keep_seccomp_privileges) {
9,577✔
5822
                        /* Restore the capability bounding set with what's expected from the service + the
5823
                         * ambient capabilities hack */
5824
                        if (!cap_test_all(saved_bset)) {
751✔
5825
                                r = capability_bounding_set_drop(saved_bset, /* right_now= */ false);
716✔
5826
                                if (r < 0) {
716✔
5827
                                        *exit_status = EXIT_CAPABILITIES;
×
5828
                                        return log_error_errno(r, "Failed to drop bset capabilities: %m");
×
5829
                                }
5830
                        }
5831

5832
                        /* Only drop CAP_SYS_ADMIN if it's not in the bounding set, otherwise we'll break
5833
                         * applications that use it. */
5834
                        if (!BIT_SET(saved_bset, CAP_SYS_ADMIN)) {
751✔
5835
                                r = drop_capability(CAP_SYS_ADMIN);
280✔
5836
                                if (r < 0) {
280✔
5837
                                        *exit_status = EXIT_USER;
×
5838
                                        return log_error_errno(r, "Failed to drop CAP_SYS_ADMIN: %m");
×
5839
                                }
5840
                        }
5841

5842
                        /* Only drop CAP_SETPCAP if it's not in the bounding set, otherwise we'll break
5843
                         * applications that use it. */
5844
                        if (!BIT_SET(saved_bset, CAP_SETPCAP)) {
751✔
5845
                                r = drop_capability(CAP_SETPCAP);
533✔
5846
                                if (r < 0) {
533✔
5847
                                        *exit_status = EXIT_USER;
×
5848
                                        return log_error_errno(r, "Failed to drop CAP_SETPCAP: %m");
×
5849
                                }
5850
                        }
5851

5852
                        if (prctl(PR_SET_KEEPCAPS, 0) < 0) {
751✔
5853
                                *exit_status = EXIT_USER;
×
5854
                                return log_error_errno(errno, "Failed to drop keep capabilities flag: %m");
×
5855
                        }
5856
                }
5857
#endif
5858

5859
        }
5860

5861
        if (!strv_isempty(context->unset_environment)) {
9,578✔
5862
                char **ee = NULL;
269✔
5863

5864
                ee = strv_env_delete(accum_env, 1, context->unset_environment);
269✔
5865
                if (!ee) {
269✔
5866
                        *exit_status = EXIT_MEMORY;
×
5867
                        return log_oom();
5✔
5868
                }
5869

5870
                strv_free_and_replace(accum_env, ee);
269✔
5871
        }
5872

5873
        _cleanup_strv_free_ char **replaced_argv = NULL, **argv_via_shell = NULL;
3✔
5874
        char **final_argv = FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL) ? strv_skip(command->argv, 1) : command->argv;
9,578✔
5875

5876
        if (final_argv && !FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) {
9,578✔
5877
                _cleanup_strv_free_ char **unset_variables = NULL, **bad_variables = NULL;
9,405✔
5878

5879
                r = replace_env_argv(final_argv, accum_env, &replaced_argv, &unset_variables, &bad_variables);
9,405✔
5880
                if (r < 0) {
9,405✔
5881
                        *exit_status = EXIT_MEMORY;
×
5882
                        return log_error_errno(r, "Failed to replace environment variables: %m");
×
5883
                }
5884
                final_argv = replaced_argv;
9,405✔
5885

5886
                if (!strv_isempty(unset_variables)) {
9,405✔
5887
                        _cleanup_free_ char *ju = strv_join(unset_variables, ", ");
10✔
5888
                        log_warning("Referenced but unset environment variable evaluates to an empty string: %s", strna(ju));
5✔
5889
                }
5890

5891
                if (!strv_isempty(bad_variables)) {
9,405✔
5892
                        _cleanup_free_ char *jb = strv_join(bad_variables, ", ");
×
5893
                        log_warning("Invalid environment variable name evaluates to an empty string: %s", strna(jb));
×
5894
                }
5895
        }
5896

5897
        if (FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL)) {
9,578✔
5898
                r = strv_extendf(&argv_via_shell, "%s%s", command->argv[0][0] == '-' ? "-" : "", path);
17✔
5899
                if (r < 0) {
13✔
5900
                        *exit_status = EXIT_MEMORY;
×
5901
                        return log_oom();
×
5902
                }
5903

5904
                if (!strv_isempty(final_argv)) {
13✔
5905
                        _cleanup_free_ char *cmdline_joined = NULL;
13✔
5906

5907
                        cmdline_joined = strv_join(final_argv, " ");
13✔
5908
                        if (!cmdline_joined) {
13✔
5909
                                *exit_status = EXIT_MEMORY;
×
5910
                                return log_oom();
×
5911
                        }
5912

5913
                        r = strv_extend_many(&argv_via_shell, "-c", cmdline_joined);
13✔
5914
                        if (r < 0) {
13✔
5915
                                *exit_status = EXIT_MEMORY;
×
5916
                                return log_oom();
×
5917
                        }
5918
                }
5919

5920
                final_argv = argv_via_shell;
13✔
5921
        }
5922

5923
        log_command_line(context, params, "Executing", executable, final_argv);
9,578✔
5924

5925
        /* We have finished with all our initializations. Let's now let the manager know that. From this
5926
         * point on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */
5927

5928
        r = exec_fd_mark_hot(context, params, /* hot= */ true, exit_status);
9,578✔
5929
        if (r < 0)
9,578✔
5930
                return r;
5931

5932
        /* As last thing before the execve(), let's send the handoff timestamp */
5933
        r = send_handoff_timestamp(context, params, exit_status);
9,578✔
5934
        if (r < 0) {
9,578✔
5935
                /* If this handoff timestamp failed, let's undo the marking as hot */
5936
                (void) exec_fd_mark_hot(context, params, /* hot= */ false, /* reterr_exit_status= */ NULL);
×
5937
                return r;
5938
        }
5939

5940
        /* NB: we leave executable_fd, exec_fd, handoff_timestamp_fd open here. This is safe, because they
5941
         * have O_CLOEXEC set, and the execve() below will thus automatically close them. In fact, for
5942
         * exec_fd this is pretty much the whole raison d'etre. */
5943

5944
        r = fexecve_or_execve(executable_fd, executable, final_argv, accum_env);
9,578✔
5945

5946
        /* The execve() failed, let's undo the marking as hot */
5947
        (void) exec_fd_mark_hot(context, params, /* hot= */ false, /* reterr_exit_status= */ NULL);
3✔
5948

5949
        *exit_status = EXIT_EXEC;
3✔
5950
        return log_error_errno(r, "Failed to execute %s: %m", executable);
3✔
5951
}
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