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

systemd / systemd / 15232239991

24 May 2025 08:01PM UTC coverage: 72.053% (-0.02%) from 72.07%
15232239991

push

github

web-flow
docs: add man pages for sd_device_enumerator_[new,ref,unref,unrefp] (#37586)

For #20929.

299160 of 415197 relevant lines covered (72.05%)

703671.29 hits per line

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

72.37
/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,597✔
88
                const int fds[],
89
                size_t n_socket_fds,
90
                size_t n_fds,
91
                bool nonblock) {
92

93
        int r;
9,597✔
94

95
        assert(fds || n_fds == 0);
9,597✔
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,176✔
101

102
                if (i < n_socket_fds) {
2,579✔
103
                        r = fd_nonblock(fds[i], nonblock);
2,263✔
104
                        if (r < 0)
2,263✔
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,579✔
113
                if (r < 0)
2,579✔
114
                        return r;
115
        }
116

117
        return 0;
118
}
119

120
static bool is_terminal_input(ExecInput i) {
43,126✔
121
        return IN_SET(i,
43,126✔
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,582✔
128
        return IN_SET(o,
40,582✔
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,364✔
135
        return IN_SET(o,
10,364✔
136
                      EXEC_OUTPUT_KMSG,
137
                      EXEC_OUTPUT_KMSG_AND_CONSOLE);
138
}
139

140
static bool exec_context_needs_term(const ExecContext *c) {
9,623✔
141
        assert(c);
9,623✔
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,623✔
146
                return true;
147

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

202
        r = connect_unix_path(fd, AT_FDCWD, j);
10,364✔
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,364✔
208
                (void) seteuid(olduid);
2,351✔
209

210
 restore_gid:
8,013✔
211
        if (gid_is_valid(gid))
10,364✔
212
                (void) setegid(oldgid);
2,354✔
213

214
        return r;
215
}
216

217
static int connect_logger_as(
10,364✔
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,364✔
227
        int r;
10,364✔
228

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

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

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

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

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

248
        if (dprintf(fd,
19,969✔
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,364✔
257
                params->flags & EXEC_PASS_LOG_UNIT ? params->unit_id : "",
10,364✔
258
                context->syslog_priority,
10,364✔
259
                !!context->syslog_level_prefix,
10,364✔
260
                false,
261
                is_kmsg_output(output),
10,364✔
262
                is_terminal_output(output)) < 0)
10,364✔
263
                return -errno;
×
264

265
        return move_fd(TAKE_FD(fd), nfd, false);
10,364✔
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,105✔
324
                const ExecContext *context,
325
                int socket_fd,
326
                bool apply_tty_stdin) {
327

328
        ExecInput std_input;
33,105✔
329

330
        assert(context);
33,105✔
331

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

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

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

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

343
        return std_input;
344
}
345

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

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

351
        return output;
352
}
353

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

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

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

367
        if (params->stdin_fd >= 0) {
11,579✔
368
                if (dup2(params->stdin_fd, STDIN_FILENO) < 0)
544✔
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)
544✔
373
                        log_debug_errno(errno, "Failed to make standard input TTY our controlling terminal: %m");
2✔
374

375
                return STDIN_FILENO;
544✔
376
        }
377

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

380
        switch (i) {
11,035✔
381

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

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

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

394
                if (tty_is_console(tty_path)) {
358✔
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,
716✔
405
                                          i == EXEC_INPUT_TTY_FAIL  ? ACQUIRE_TERMINAL_TRY :
358✔
406
                                          i == EXEC_INPUT_TTY_FORCE ? ACQUIRE_TERMINAL_FORCE :
407
                                                                      ACQUIRE_TERMINAL_WAIT,
408
                                          USEC_INFINITY);
409
                if (tty_fd < 0)
358✔
410
                        return tty_fd;
411

412
                r = move_fd(tty_fd, STDIN_FILENO, /* cloexec= */ false);
358✔
413
                if (r < 0)
358✔
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,579✔
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,035✔
463
                const ExecContext *context,
464
                ExecOutput o,
465
                ExecOutput e) {
466

467
        assert(context);
11,035✔
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,035✔
473
                return true;
474
        if (e != o)
413✔
475
                return false;
476

477
        if (e == EXEC_OUTPUT_NAMED_FD)
410✔
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))
410✔
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,158✔
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,158✔
499
        ExecInput i;
23,158✔
500
        int r;
23,158✔
501

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

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

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

513
                return STDOUT_FILENO;
514
        }
515

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

520
                return STDERR_FILENO;
521
        }
522

523
        i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
22,070✔
524
        o = fixup_output(context->std_output, socket_fd);
22,070✔
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,070✔
530
                ExecOutput e;
11,035✔
531
                e = fixup_output(context->std_error, socket_fd);
11,035✔
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,035✔
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,035✔
546
                        return RET_NERRNO(dup2(STDOUT_FILENO, fileno));
11,028✔
547

548
                o = e;
549

550
        } else if (o == EXEC_OUTPUT_INHERIT) {
11,035✔
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,034✔
568

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

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

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

578
        case EXEC_OUTPUT_KMSG:
10,364✔
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,364✔
583
                if (r < 0) {
10,364✔
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,364✔
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,364✔
598
                            (*journal_stream_ino == 0 || fileno == STDERR_FILENO)) {
10,364✔
599
                                *journal_stream_dev = st.st_dev;
10,364✔
600
                                *journal_stream_ino = st.st_ino;
10,364✔
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,675✔
649
        int r;
2,675✔
650

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

653
        /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
654
        if (!isatty_safe(fd))
2,675✔
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,408✔
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,408✔
879

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

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

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

891
        return 0;
9,406✔
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,579✔
915
                const ExecContext *c,
916
                const char *user,
917
                gid_t gid,
918
                gid_t **ret_gids) {
919

920
        int r;
11,579✔
921

922
        assert(c);
11,579✔
923
        assert(ret_gids);
11,579✔
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,579✔
932
        if (user && gid_is_valid(gid) && gid != 0) {
14,254✔
933
                /* First step, initialize groups from /etc/groups */
934
                if (initgroups(user, gid) < 0)
2,523✔
935
                        return -errno;
11,579✔
936

937
                keep_groups = true;
938
        }
939

940
        if (strv_isempty(c->supplementary_groups)) {
11,579✔
941
                *ret_gids = NULL;
11,570✔
942
                return 0;
11,570✔
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,603✔
996
        int r;
9,603✔
997

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

1005
        if (gid_is_valid(gid)) {
9,603✔
1006
                /* Then set our gids */
1007
                if (setresgid(gid, gid, gid) < 0)
2,029✔
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,022✔
1034
                const ExecContext *context,
1035
                uid_t uid,
1036
                uint64_t capability_ambient_set) {
1037

1038
        int r;
2,022✔
1039

1040
        assert(context);
2,022✔
1041

1042
        if (!uid_is_valid(uid))
2,022✔
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,022✔
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,022✔
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) {
220✔
1181
        int r, s;
220✔
1182

1183
        assert(handle);
220✔
1184

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

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

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

1197
static int setup_pam(
405✔
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 = {
405✔
1209
                .context = context,
1210
                .params = params,
1211
        };
1212

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

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

1228
        assert(context);
405✔
1229
        assert(params);
405✔
1230
        assert(user);
405✔
1231
        assert(uid_is_valid(uid));
405✔
1232
        assert(gid_is_valid(gid));
405✔
1233
        assert(fds || n_fds == 0);
405✔
1234
        assert(env);
405✔
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);
405✔
1244
        if (r < 0)
405✔
1245
                goto fail;
×
1246

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

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

1256
        if (getttyname_malloc(STDIN_FILENO, &tty) >= 0) {
405✔
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) {
405✔
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,731✔
1273
                pam_code = pam_putenv(handle, *nv);
5,326✔
1274
                if (pam_code != PAM_SUCCESS)
5,326✔
1275
                        goto fail;
×
1276
        }
1277

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

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

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

1290
        close_session = true;
405✔
1291

1292
        e = pam_getenvlist(handle);
405✔
1293
        if (!e) {
405✔
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);
405✔
1301

1302
        parent_pid = getpid_cached();
405✔
1303

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

1310
                /* The child's job is to reset the PAM session on termination */
1311
                barrier_set_role(&barrier, BARRIER_CHILD);
221✔
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);
221✔
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);
221✔
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);
221✔
1327
                if (r < 0)
221✔
1328
                        log_warning_errno(r, "Failed to drop privileges in sd-pam: %m");
×
1329

1330
                (void) ignore_signals(SIGPIPE);
221✔
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)
221✔
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);
221✔
1343

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

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

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

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

1363
                ret = 0;
1364

1365
        child_finish:
221✔
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);
221✔
1369
                _exit(ret);
221✔
1370
        }
1371

1372
        barrier_set_role(&barrier, BARRIER_PARENT);
405✔
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;
405✔
1377

1378
        /* Unblock SIGTERM again in the parent */
1379
        assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0);
405✔
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();
405✔
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))
810✔
1388
                log_error("PAM initialization failed");
×
1389

1390
        return strv_free_and_replace(*env, e);
405✔
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,582✔
1414
        _cleanup_free_ char *buf = NULL;
11,582✔
1415
        const char *p;
11,582✔
1416

1417
        assert(path);
11,582✔
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,582✔
1423
                rename_process("(...)");
×
1424
                return;
×
1425
        }
1426

1427
        size_t l = strlen(buf);
11,582✔
1428
        if (l > 8) {
11,582✔
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,996✔
1432
                l = 8;
7,996✔
1433
        } else
1434
                p = buf;
1435

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

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

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

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

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

1455
        return c->syscall_allow_list ||
12,492✔
1456
                !hashmap_isempty(c->syscall_filter);
11,015✔
1457
}
1458

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

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

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

1469
        /* We need NNP if we have any form of seccomp and are unprivileged */
1470
        return c->lock_personality ||
6,579✔
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,439✔
1484
                context_has_syscall_logs(c);
2,896✔
1485
}
1486

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

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

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

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

1499
#if HAVE_SECCOMP
1500

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

1505
        assert(c);
751✔
1506

1507
        /* No syscall filter, we are allowed to drop privileges */
1508
        if (hashmap_isempty(c->syscall_filter))
751✔
1509
                return true;
751✔
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,901✔
1531
        assert(msg);
14,901✔
1532

1533
        if (is_seccomp_available())
14,901✔
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,596✔
1541
        uint32_t negative_action, default_action, action;
9,596✔
1542
        int r;
9,596✔
1543

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

1547
        if (!context_has_syscall_filters(c))
9,596✔
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,596✔
1574
#ifdef SCMP_ACT_LOG
1575
        uint32_t default_action, action;
9,596✔
1576
#endif
1577

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

1581
        if (!context_has_syscall_logs(c))
9,596✔
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,596✔
1607
        assert(c);
9,596✔
1608
        assert(p);
9,596✔
1609

1610
        if (set_isempty(c->syscall_archs))
9,596✔
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,596✔
1620
        assert(c);
9,596✔
1621
        assert(p);
9,596✔
1622

1623
        if (!context_has_address_families(c))
9,596✔
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,596✔
1633
        int r;
9,596✔
1634

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

1638
        if (!c->memory_deny_write_execute)
9,596✔
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,596✔
1659
        assert(c);
9,596✔
1660
        assert(p);
9,596✔
1661

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

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

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

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

1675
        if (!c->restrict_suid_sgid)
9,596✔
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,596✔
1685
        assert(c);
9,596✔
1686
        assert(p);
9,596✔
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,596✔
1692
                return 0;
1693

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

1697
        return seccomp_protect_sysctl();
363✔
1698
}
1699

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

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

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

1709
        if (skip_seccomp_unavailable("ProtectKernelModules="))
1,130✔
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,130✔
1713
}
1714

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

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

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

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

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

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

1735
        if (skip_seccomp_unavailable("ProtectClock="))
842✔
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);
842✔
1739
}
1740

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

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

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

1750
        if (skip_seccomp_unavailable("PrivateDevices="))
677✔
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);
677✔
1754
}
1755

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

1760
        if (!exec_context_restrict_namespaces_set(c))
9,596✔
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,596✔
1770
        unsigned long personality;
9,596✔
1771
        int r;
9,596✔
1772

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

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

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

1782
        personality = c->personality;
1,492✔
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,492✔
1786

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

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

1795
#endif
1796

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

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

1804
        if (!exec_context_restrict_filesystems_set(c))
9,596✔
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,599✔
1823
        int r;
9,599✔
1824

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

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

1832
        if (namespace_type_supported(NAMESPACE_UTS)) {
665✔
1833
                if (unshare(CLONE_NEWUTS) < 0) {
665✔
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) {
665✔
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) {
665✔
1855
                if (skip_seccomp_unavailable("ProtectHostname="))
659✔
1856
                        return 0;
1857

1858
                r = seccomp_protect_hostname();
659✔
1859
                if (r < 0) {
659✔
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]) {
160✔
1870
        assert(idle_pipe);
160✔
1871

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

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

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

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

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

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

1892
        }
1893

1894
        idle_pipe[3] = safe_close(idle_pipe[3]);
160✔
1895
}
160✔
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,623✔
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,623✔
1926
        size_t n_env = 0;
9,623✔
1927
        char *x;
9,623✔
1928
        int r;
9,623✔
1929

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

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

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

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

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

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

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

1961
        if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) {
9,623✔
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,623✔
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,623✔
1986
                assert(!c->user);
6,793✔
1987

1988
                r = get_fixed_user("root", /* prefer_nss = */ false, &username, NULL, NULL, &home, &shell);
6,793✔
1989
                if (r < 0)
6,793✔
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,623✔
1994

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

2001
                if (set_user_login_env) {
8,818✔
2002
                        x = strjoin("LOGNAME=", username);
2,021✔
2003
                        if (!x)
2,021✔
2004
                                return -ENOMEM;
2005
                        our_env[n_env++] = x;
2,021✔
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,623✔
2013
                x = strjoin("HOME=", home);
418✔
2014
                if (!x)
418✔
2015
                        return -ENOMEM;
2016

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

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

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

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

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

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

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

2044
                tty_path = exec_context_tty_path(c);
450✔
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)
450✔
2051
                        term = getenv("TERM");
390✔
2052
                else if (tty_path && in_charset(skip_dev_prefix(tty_path), ALPHANUMERICAL)) {
60✔
2053
                        _cleanup_free_ char *key = NULL;
44✔
2054

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

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

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

2084
                        our_env[n_env++] = x;
60✔
2085

2086
                        term = default_term_for_tty(tty_path);
60✔
2087
                }
2088

2089
                x = strjoin("TERM=", term);
450✔
2090
                if (!x)
450✔
2091
                        return -ENOMEM;
2092
                our_env[n_env++] = x;
450✔
2093
        }
2094

2095
        if (journal_stream_dev != 0 && journal_stream_ino != 0) {
9,623✔
2096
                if (asprintf(&x, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino) < 0)
8,834✔
2097
                        return -ENOMEM;
2098

2099
                our_env[n_env++] = x;
8,834✔
2100
        }
2101

2102
        if (c->log_namespace) {
9,623✔
2103
                x = strjoin("LOG_NAMESPACE=", c->log_namespace);
2✔
2104
                if (!x)
2✔
2105
                        return -ENOMEM;
2106

2107
                our_env[n_env++] = x;
2✔
2108
        }
2109

2110
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
57,738✔
2111
                _cleanup_free_ char *joined = NULL;
48,115✔
2112
                const char *n;
48,115✔
2113

2114
                if (!p->prefix[t])
48,115✔
2115
                        continue;
×
2116

2117
                if (c->directories[t].n_items == 0)
48,115✔
2118
                        continue;
45,617✔
2119

2120
                n = exec_directory_env_name_to_string(t);
2,498✔
2121
                if (!n)
2,498✔
2122
                        continue;
×
2123

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

2127
                        prefixed = path_join(p->prefix[t], c->directories[t].items[i].path);
2,994✔
2128
                        if (!prefixed)
2,994✔
2129
                                return -ENOMEM;
2130

2131
                        if (!strextend_with_separator(&joined, ":", prefixed))
2,994✔
2132
                                return -ENOMEM;
2133
                }
2134

2135
                x = strjoin(n, "=", joined);
2,498✔
2136
                if (!x)
2,498✔
2137
                        return -ENOMEM;
2138

2139
                our_env[n_env++] = x;
2,498✔
2140
        }
2141

2142
        _cleanup_free_ char *creds_dir = NULL;
9,623✔
2143
        r = exec_context_get_credential_directory(c, p, p->unit_id, &creds_dir);
9,623✔
2144
        if (r < 0)
9,623✔
2145
                return r;
2146
        if (r > 0) {
9,623✔
2147
                x = strjoin("CREDENTIALS_DIRECTORY=", creds_dir);
1,944✔
2148
                if (!x)
1,944✔
2149
                        return -ENOMEM;
2150

2151
                our_env[n_env++] = x;
1,944✔
2152
        }
2153

2154
        if (asprintf(&x, "SYSTEMD_EXEC_PID=" PID_FMT, getpid_cached()) < 0)
9,623✔
2155
                return -ENOMEM;
2156

2157
        our_env[n_env++] = x;
9,623✔
2158

2159
        if (memory_pressure_path) {
9,623✔
2160
                x = strjoin("MEMORY_PRESSURE_WATCH=", memory_pressure_path);
9,221✔
2161
                if (!x)
9,221✔
2162
                        return -ENOMEM;
2163

2164
                our_env[n_env++] = x;
9,221✔
2165

2166
                if (!path_equal(memory_pressure_path, "/dev/null")) {
9,221✔
2167
                        _cleanup_free_ char *b = NULL, *e = NULL;
9,221✔
2168

2169
                        if (asprintf(&b, "%s " USEC_FMT " " USEC_FMT,
9,221✔
2170
                                     MEMORY_PRESSURE_DEFAULT_TYPE,
2171
                                     cgroup_context->memory_pressure_threshold_usec == USEC_INFINITY ? MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC :
9,221✔
2172
                                     CLAMP(cgroup_context->memory_pressure_threshold_usec, 1U, MEMORY_PRESSURE_DEFAULT_WINDOW_USEC),
9,221✔
2173
                                     MEMORY_PRESSURE_DEFAULT_WINDOW_USEC) < 0)
2174
                                return -ENOMEM;
2175

2176
                        if (base64mem(b, strlen(b) + 1, &e) < 0)
9,221✔
2177
                                return -ENOMEM;
2178

2179
                        x = strjoin("MEMORY_PRESSURE_WRITE=", e);
9,221✔
2180
                        if (!x)
9,221✔
2181
                                return -ENOMEM;
2182

2183
                        our_env[n_env++] = x;
9,221✔
2184
                }
2185
        }
2186

2187
        if (p->notify_socket) {
9,623✔
2188
                x = strjoin("NOTIFY_SOCKET=", exec_get_private_notify_socket_path(c, p, needs_sandboxing) ?: p->notify_socket);
1,897✔
2189
                if (!x)
1,897✔
2190
                        return -ENOMEM;
2191

2192
                our_env[n_env++] = x;
1,897✔
2193
        }
2194

2195
        assert(c->private_var_tmp >= 0 && c->private_var_tmp < _PRIVATE_TMP_MAX);
9,623✔
2196
        if (c->private_tmp != c->private_var_tmp) {
9,623✔
2197
                assert(c->private_tmp == PRIVATE_TMP_DISCONNECTED);
284✔
2198
                assert(c->private_var_tmp == PRIVATE_TMP_NO);
284✔
2199

2200
                /* When private tmpfs is enabled only on /tmp/, then explicitly set $TMPDIR to suggest the
2201
                 * service to use /tmp/. */
2202

2203
                x = strdup("TMPDIR=/tmp");
284✔
2204
                if (!x)
284✔
2205
                        return -ENOMEM;
2206

2207
                our_env[n_env++] = x;
284✔
2208
        }
2209

2210
        assert(n_env < N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
9,623✔
2211
#undef N_ENV_VARS
2212

2213
        *ret = TAKE_PTR(our_env);
9,623✔
2214

2215
        return 0;
9,623✔
2216
}
2217

2218
static int build_pass_environment(const ExecContext *c, char ***ret) {
9,623✔
2219
        _cleanup_strv_free_ char **pass_env = NULL;
9,623✔
2220
        size_t n_env = 0;
9,623✔
2221

2222
        assert(c);
9,623✔
2223
        assert(ret);
9,623✔
2224

2225
        STRV_FOREACH(i, c->pass_environment) {
9,929✔
2226
                _cleanup_free_ char *x = NULL;
×
2227
                char *v;
306✔
2228

2229
                v = getenv(*i);
306✔
2230
                if (!v)
306✔
2231
                        continue;
×
2232
                x = strjoin(*i, "=", v);
306✔
2233
                if (!x)
306✔
2234
                        return -ENOMEM;
2235

2236
                if (!GREEDY_REALLOC(pass_env, n_env + 2))
306✔
2237
                        return -ENOMEM;
2238

2239
                pass_env[n_env++] = TAKE_PTR(x);
306✔
2240
                pass_env[n_env] = NULL;
306✔
2241
        }
2242

2243
        *ret = TAKE_PTR(pass_env);
9,623✔
2244
        return 0;
9,623✔
2245
}
2246

2247
static int setup_private_users(PrivateUsers private_users, uid_t ouid, gid_t ogid, uid_t uid, gid_t gid, bool allow_setgroups) {
9,607✔
2248
        _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
9,607✔
2249
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
9,607✔
2250
        _cleanup_close_ int unshare_ready_fd = -EBADF;
9,607✔
2251
        _cleanup_(sigkill_waitp) pid_t pid = 0;
9,607✔
2252
        uint64_t c = 1;
9,607✔
2253
        ssize_t n;
9,607✔
2254
        int r;
9,607✔
2255

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

2266
        if (private_users == PRIVATE_USERS_NO)
9,607✔
2267
                return 0;
2268

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

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

2337
        /* Create a communication channel so that the parent can tell the child when it finished creating the user
2338
         * namespace. */
2339
        unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
52✔
2340
        if (unshare_ready_fd < 0)
52✔
2341
                return -errno;
×
2342

2343
        /* Create a communication channel so that the child can tell the parent a proper error code in case it
2344
         * failed. */
2345
        if (pipe2(errno_pipe, O_CLOEXEC) < 0)
52✔
2346
                return -errno;
×
2347

2348
        r = safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL, &pid);
52✔
2349
        if (r < 0)
103✔
2350
                return r;
2351
        if (r == 0) {
103✔
2352
                _cleanup_close_ int fd = -EBADF;
×
2353
                const char *a;
51✔
2354
                pid_t ppid;
51✔
2355

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

2359
                ppid = getppid();
51✔
2360
                errno_pipe[0] = safe_close(errno_pipe[0]);
51✔
2361

2362
                /* Wait until the parent unshared the user namespace */
2363
                if (read(unshare_ready_fd, &c, sizeof(c)) < 0)
51✔
2364
                        report_errno_and_exit(errno_pipe[1], -errno);
×
2365

2366
                /* Disable the setgroups() system call in the child user namespace, for good, unless PrivateUsers=full
2367
                 * and using the system service manager. */
2368
                a = procfs_file_alloca(ppid, "setgroups");
51✔
2369
                fd = open(a, O_WRONLY|O_CLOEXEC);
51✔
2370
                if (fd < 0) {
51✔
2371
                        if (errno != ENOENT) {
×
2372
                                r = log_debug_errno(errno, "Failed to open %s: %m", a);
×
2373
                                report_errno_and_exit(errno_pipe[1], r);
×
2374
                        }
2375

2376
                        /* If the file is missing the kernel is too old, let's continue anyway. */
2377
                } else {
2378
                        const char *setgroups = allow_setgroups ? "allow\n" : "deny\n";
51✔
2379
                        if (write(fd, setgroups, strlen(setgroups)) < 0) {
51✔
2380
                                r = log_debug_errno(errno, "Failed to write '%s' to %s: %m", setgroups, a);
×
2381
                                report_errno_and_exit(errno_pipe[1], r);
×
2382
                        }
2383

2384
                        fd = safe_close(fd);
51✔
2385
                }
2386

2387
                /* First write the GID map */
2388
                a = procfs_file_alloca(ppid, "gid_map");
51✔
2389
                fd = open(a, O_WRONLY|O_CLOEXEC);
51✔
2390
                if (fd < 0) {
51✔
2391
                        r = log_debug_errno(errno, "Failed to open %s: %m", a);
×
2392
                        report_errno_and_exit(errno_pipe[1], r);
×
2393
                }
2394

2395
                if (write(fd, gid_map, strlen(gid_map)) < 0) {
51✔
2396
                        r = log_debug_errno(errno, "Failed to write GID map to %s: %m", a);
×
2397
                        report_errno_and_exit(errno_pipe[1], r);
×
2398
                }
2399

2400
                fd = safe_close(fd);
51✔
2401

2402
                /* The write the UID map */
2403
                a = procfs_file_alloca(ppid, "uid_map");
51✔
2404
                fd = open(a, O_WRONLY|O_CLOEXEC);
51✔
2405
                if (fd < 0) {
51✔
2406
                        r = log_debug_errno(errno, "Failed to open %s: %m", a);
×
2407
                        report_errno_and_exit(errno_pipe[1], r);
×
2408
                }
2409

2410
                if (write(fd, uid_map, strlen(uid_map)) < 0) {
51✔
2411
                        r = log_debug_errno(errno, "Failed to write UID map to %s: %m", a);
×
2412
                        report_errno_and_exit(errno_pipe[1], r);
×
2413
                }
2414

2415
                _exit(EXIT_SUCCESS);
51✔
2416
        }
2417

2418
        errno_pipe[1] = safe_close(errno_pipe[1]);
52✔
2419

2420
        if (unshare(CLONE_NEWUSER) < 0)
52✔
2421
                return log_debug_errno(errno, "Failed to unshare user namespace: %m");
×
2422

2423
        /* Let the child know that the namespace is ready now */
2424
        if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
52✔
2425
                return -errno;
×
2426

2427
        /* Try to read an error code from the child */
2428
        n = read(errno_pipe[0], &r, sizeof(r));
52✔
2429
        if (n < 0)
52✔
2430
                return -errno;
×
2431
        if (n == sizeof(r)) { /* an error code was sent to us */
52✔
2432
                if (r < 0)
×
2433
                        return r;
2434
                return -EIO;
×
2435
        }
2436
        if (n != 0) /* on success we should have read 0 bytes */
52✔
2437
                return -EIO;
2438

2439
        r = wait_for_terminate_and_check("(sd-userns)", TAKE_PID(pid), 0);
52✔
2440
        if (r < 0)
52✔
2441
                return r;
2442
        if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
52✔
2443
                return -EIO;
×
2444

2445
        return 1;
2446
}
2447

2448
static int can_mount_proc(void) {
10✔
2449
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
5✔
2450
        _cleanup_(sigkill_waitp) pid_t pid = 0;
×
2451
        ssize_t n;
10✔
2452
        int r;
10✔
2453

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

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

2463
        /* Fork a child process into its own mount and PID namespace. Note safe_fork() already remounts / as SLAVE
2464
         * with FORK_MOUNTNS_SLAVE. */
2465
        r = safe_fork("(sd-proc-check)",
10✔
2466
                      FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE|FORK_NEW_PIDNS, &pid);
2467
        if (r < 0)
10✔
2468
                return log_debug_errno(r, "Failed to fork child process (sd-proc-check): %m");
×
2469
        if (r == 0) {
10✔
2470
                errno_pipe[0] = safe_close(errno_pipe[0]);
5✔
2471

2472
                /* Try mounting /proc on /dev/shm/. No need to clean up the mount since the mount
2473
                 * namespace will be cleaned up once the process exits. */
2474
                r = mount_follow_verbose(LOG_DEBUG, "proc", "/dev/shm/", "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
5✔
2475
                if (r < 0) {
5✔
2476
                        (void) write(errno_pipe[1], &r, sizeof(r));
1✔
2477
                        _exit(EXIT_FAILURE);
1✔
2478
                }
2479

2480
                _exit(EXIT_SUCCESS);
4✔
2481
        }
2482

2483
        errno_pipe[1] = safe_close(errno_pipe[1]);
5✔
2484

2485
        /* Try to read an error code from the child */
2486
        n = read(errno_pipe[0], &r, sizeof(r));
5✔
2487
        if (n < 0)
5✔
2488
                return log_debug_errno(errno, "Failed to read errno from pipe with child process (sd-proc-check): %m");
×
2489
        if (n == sizeof(r)) { /* an error code was sent to us */
5✔
2490
                /* This is the expected case where proc cannot be mounted due to permissions. */
2491
                if (ERRNO_IS_NEG_PRIVILEGE(r))
5✔
2492
                        return 0;
2493
                if (r < 0)
×
2494
                        return r;
2495

2496
                return -EIO;
×
2497
        }
2498
        if (n != 0) /* on success we should have read 0 bytes */
4✔
2499
                return -EIO;
2500

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

2507
        return 1;
2508
}
2509

2510
static int setup_private_pids(const ExecContext *c, ExecParameters *p) {
9✔
2511
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
×
2512
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
6✔
2513
        ssize_t n;
9✔
2514
        int r, q;
9✔
2515

2516
        assert(c);
9✔
2517
        assert(p);
9✔
2518
        assert(p->pidref_transport_fd >= 0);
9✔
2519

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

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

2530
        /* Set FORK_DETACH to immediately re-parent the child process to the invoking manager process. */
2531
        r = pidref_safe_fork("(sd-pidns-child)", FORK_NEW_PIDNS|FORK_DETACH, &pidref);
9✔
2532
        if (r < 0)
15✔
2533
                return log_debug_errno(r, "Failed to fork child into new pid namespace: %m");
×
2534
        if (r > 0) {
15✔
2535
                errno_pipe[0] = safe_close(errno_pipe[0]);
9✔
2536

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

2553
        errno_pipe[1] = safe_close(errno_pipe[1]);
6✔
2554
        p->pidref_transport_fd = safe_close(p->pidref_transport_fd);
6✔
2555

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

2566
        /* NOTE! This function returns in the child process only. */
2567
        return r;
2568
}
2569

2570
static int create_many_symlinks(const char *root, const char *source, char **symlinks) {
1,530✔
2571
        _cleanup_free_ char *src_abs = NULL;
1,530✔
2572
        int r;
1,530✔
2573

2574
        assert(source);
1,530✔
2575

2576
        src_abs = path_join(root, source);
1,530✔
2577
        if (!src_abs)
1,530✔
2578
                return -ENOMEM;
2579

2580
        STRV_FOREACH(dst, symlinks) {
1,543✔
2581
                _cleanup_free_ char *dst_abs = NULL;
13✔
2582

2583
                dst_abs = path_join(root, *dst);
13✔
2584
                if (!dst_abs)
13✔
2585
                        return -ENOMEM;
2586

2587
                r = mkdir_parents_label(dst_abs, 0755);
13✔
2588
                if (r < 0)
13✔
2589
                        return r;
2590

2591
                r = symlink_idempotent(src_abs, dst_abs, true);
13✔
2592
                if (r < 0)
13✔
2593
                        return r;
2594
        }
2595

2596
        return 0;
2597
}
2598

2599
static int setup_exec_directory(
57,881✔
2600
                const ExecContext *context,
2601
                const ExecParameters *params,
2602
                uid_t uid,
2603
                gid_t gid,
2604
                ExecDirectoryType type,
2605
                bool needs_mount_namespace,
2606
                int *exit_status) {
2607

2608
        static const int exit_status_table[_EXEC_DIRECTORY_TYPE_MAX] = {
57,881✔
2609
                [EXEC_DIRECTORY_RUNTIME]       = EXIT_RUNTIME_DIRECTORY,
2610
                [EXEC_DIRECTORY_STATE]         = EXIT_STATE_DIRECTORY,
2611
                [EXEC_DIRECTORY_CACHE]         = EXIT_CACHE_DIRECTORY,
2612
                [EXEC_DIRECTORY_LOGS]          = EXIT_LOGS_DIRECTORY,
2613
                [EXEC_DIRECTORY_CONFIGURATION] = EXIT_CONFIGURATION_DIRECTORY,
2614
        };
2615
        int r;
57,881✔
2616

2617
        assert(context);
57,881✔
2618
        assert(params);
57,881✔
2619
        assert(type >= 0 && type < _EXEC_DIRECTORY_TYPE_MAX);
57,881✔
2620
        assert(exit_status);
57,881✔
2621

2622
        if (!params->prefix[type])
57,881✔
2623
                return 0;
2624

2625
        if (params->flags & EXEC_CHOWN_DIRECTORIES) {
57,881✔
2626
                if (!uid_is_valid(uid))
53,851✔
2627
                        uid = 0;
40,476✔
2628
                if (!gid_is_valid(gid))
53,851✔
2629
                        gid = 0;
40,456✔
2630
        }
2631

2632
        FOREACH_ARRAY(i, context->directories[type].items, context->directories[type].n_items) {
61,590✔
2633
                _cleanup_free_ char *p = NULL, *pp = NULL;
3,710✔
2634

2635
                p = path_join(params->prefix[type], i->path);
3,710✔
2636
                if (!p) {
3,710✔
2637
                        r = -ENOMEM;
×
2638
                        goto fail;
×
2639
                }
2640

2641
                r = mkdir_parents_label(p, 0755);
3,710✔
2642
                if (r < 0)
3,710✔
2643
                        goto fail;
×
2644

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

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

2660
                        /* this assumes the state dir is always created before the configuration dir */
2661
                        assert_cc(EXEC_DIRECTORY_STATE < EXEC_DIRECTORY_LOGS);
7✔
2662
                        assert_cc(EXEC_DIRECTORY_LOGS < EXEC_DIRECTORY_CONFIGURATION);
7✔
2663

2664
                        r = access_nofollow(p, F_OK);
7✔
2665
                        if (r == -ENOENT) {
7✔
2666
                                _cleanup_free_ char *q = NULL;
3✔
2667

2668
                                /* OK, we know that the state dir does not exist. Let's see if the dir exists
2669
                                 * under the configuration hierarchy. */
2670

2671
                                if (type == EXEC_DIRECTORY_STATE)
3✔
2672
                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], i->path);
3✔
2673
                                else if (type == EXEC_DIRECTORY_LOGS)
×
2674
                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], "log", i->path);
×
2675
                                else
2676
                                        assert_not_reached();
×
2677
                                if (!q) {
3✔
2678
                                        r = -ENOMEM;
×
2679
                                        goto fail;
×
2680
                                }
2681

2682
                                r = access_nofollow(q, F_OK);
3✔
2683
                                if (r >= 0) {
3✔
2684
                                        /* It does exist! This hence looks like an update. Symlink the
2685
                                         * configuration directory into the state directory. */
2686

2687
                                        r = symlink_idempotent(q, p, /* make_relative= */ true);
1✔
2688
                                        if (r < 0)
1✔
2689
                                                goto fail;
×
2690

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

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

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

2726
                        pp = path_join(params->prefix[type], "private");
13✔
2727
                        if (!pp) {
13✔
2728
                                r = -ENOMEM;
×
2729
                                goto fail;
×
2730
                        }
2731

2732
                        /* First set up private root if it doesn't exist yet, with access mode 0700 and owned by root:root */
2733
                        r = mkdir_safe_label(pp, 0700, 0, 0, MKDIR_WARN_MODE);
13✔
2734
                        if (r < 0)
13✔
2735
                                goto fail;
×
2736

2737
                        if (!path_extend(&pp, i->path)) {
13✔
2738
                                r = -ENOMEM;
×
2739
                                goto fail;
×
2740
                        }
2741

2742
                        /* Create all directories between the configured directory and this private root, and mark them 0755 */
2743
                        r = mkdir_parents_label(pp, 0755);
13✔
2744
                        if (r < 0)
13✔
2745
                                goto fail;
×
2746

2747
                        if (is_dir(p, false) > 0 &&
13✔
2748
                            (access_nofollow(pp, F_OK) == -ENOENT)) {
×
2749

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

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

2758
                                r = RET_NERRNO(rename(p, pp));
×
2759
                                if (r < 0)
×
2760
                                        goto fail;
×
2761
                        } else {
2762
                                /* Otherwise, create the actual directory for the service */
2763

2764
                                r = mkdir_label(pp, context->directories[type].mode);
13✔
2765
                                if (r < 0 && r != -EEXIST)
13✔
2766
                                        goto fail;
×
2767
                        }
2768

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

2788
                } else {
2789
                        _cleanup_free_ char *target = NULL;
3,696✔
2790

2791
                        if (EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type) &&
7,352✔
2792
                            readlink_and_make_absolute(p, &target) >= 0) {
3,656✔
2793
                                _cleanup_free_ char *q = NULL, *q_resolved = NULL, *target_resolved = NULL;
11✔
2794

2795
                                /* This already exists and is a symlink? Interesting. Maybe it's one created
2796
                                 * by DynamicUser=1 (see above)?
2797
                                 *
2798
                                 * We do this for all directory types except for ConfigurationDirectory=,
2799
                                 * since they all support the private/ symlink logic at least in some
2800
                                 * configurations, see above. */
2801

2802
                                r = chase(target, NULL, 0, &target_resolved, NULL);
11✔
2803
                                if (r < 0)
11✔
2804
                                        goto fail;
×
2805

2806
                                q = path_join(params->prefix[type], "private", i->path);
11✔
2807
                                if (!q) {
11✔
2808
                                        r = -ENOMEM;
×
2809
                                        goto fail;
×
2810
                                }
2811

2812
                                /* /var/lib or friends may be symlinks. So, let's chase them also. */
2813
                                r = chase(q, NULL, CHASE_NONEXISTENT, &q_resolved, NULL);
11✔
2814
                                if (r < 0)
11✔
2815
                                        goto fail;
×
2816

2817
                                if (path_equal(q_resolved, target_resolved)) {
11✔
2818

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

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

2826
                                        r = RET_NERRNO(unlink(p));
8✔
2827
                                        if (r < 0)
×
2828
                                                goto fail;
×
2829

2830
                                        r = RET_NERRNO(rename(q, p));
11✔
2831
                                        if (r < 0)
×
2832
                                                goto fail;
×
2833
                                }
2834
                        }
2835

2836
                        r = mkdir_label(p, context->directories[type].mode);
3,696✔
2837
                        if (r < 0) {
3,696✔
2838
                                if (r != -EEXIST)
2,651✔
2839
                                        goto fail;
×
2840

2841
                                if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type)) {
2,651✔
2842
                                        struct stat st;
27✔
2843

2844
                                        /* Don't change the owner/access mode of the configuration directory,
2845
                                         * as in the common case it is not written to by a service, and shall
2846
                                         * not be writable. */
2847

2848
                                        r = RET_NERRNO(stat(p, &st));
27✔
2849
                                        if (r < 0)
×
2850
                                                goto fail;
×
2851

2852
                                        /* Still complain if the access mode doesn't match */
2853
                                        if (((st.st_mode ^ context->directories[type].mode) & 07777) != 0)
27✔
2854
                                                log_warning("%s \'%s\' already exists but the mode is different. "
×
2855
                                                            "(File system: %o %sMode: %o)",
2856
                                                            exec_directory_type_to_string(type), i->path,
2857
                                                            st.st_mode & 07777, exec_directory_type_to_string(type), context->directories[type].mode & 07777);
2858

2859
                                        continue;
27✔
2860
                                }
2861
                        }
2862
                }
2863

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

2872
                /* Skip the rest (which deals with ownership) in user mode, since ownership changes are not
2873
                 * available to user code anyway */
2874
                if (params->runtime_scope != RUNTIME_SCOPE_SYSTEM)
3,682✔
2875
                        continue;
9✔
2876

2877
                int idmapping_supported = is_idmapping_supported(target_dir);
3,673✔
2878
                if (idmapping_supported < 0) {
3,673✔
2879
                        r = log_debug_errno(idmapping_supported, "Unable to determine if ID mapping is supported on mount '%s': %m", target_dir);
×
2880
                        goto fail;
×
2881
                }
2882

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

2885
                /* Change the ownership of the whole tree, if necessary. When dynamic users are used we
2886
                 * drop the suid/sgid bits, since we really don't want SUID/SGID files for dynamic UID/GID
2887
                 * assignments to exist. */
2888
                uid_t chown_uid = uid;
3,673✔
2889
                gid_t chown_gid = gid;
3,673✔
2890
                bool do_chown = false;
3,673✔
2891

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

2903
                        if (st.st_uid == UID_NOBODY && st.st_gid == GID_NOBODY) {
2,245✔
2904
                                do_chown = false;
7✔
2905
                                i->idmapped = true;
7✔
2906
                       } else if (exec_directory_is_private(context, type) && st.st_uid == 0 && st.st_gid == 0) {
2,238✔
2907
                                chown_uid = UID_NOBODY;
6✔
2908
                                chown_gid = GID_NOBODY;
6✔
2909
                                do_chown = true;
6✔
2910
                                i->idmapped = true;
6✔
2911
                        } else {
2912
                                do_chown = true;
2,232✔
2913
                                i->idmapped = false;
2,232✔
2914
                        }
2915
                }
2916

2917
                if (do_chown) {
3,673✔
2918
                        r = path_chown_recursive(target_dir, chown_uid, chown_gid, context->dynamic_user ? 01777 : 07777, AT_SYMLINK_FOLLOW);
7,323✔
2919
                        if (r < 0)
3,666✔
2920
                                goto fail;
1✔
2921
                }
2922
        }
2923

2924
        /* If we are not going to run in a namespace, set up the symlinks - otherwise
2925
         * they are set up later, to allow configuring empty var/run/etc. */
2926
        if (!needs_mount_namespace)
57,880✔
2927
                FOREACH_ARRAY(i, context->directories[type].items, context->directories[type].n_items) {
46,235✔
2928
                        r = create_many_symlinks(params->prefix[type], i->path, i->symlinks);
1,530✔
2929
                        if (r < 0)
1,530✔
2930
                                goto fail;
×
2931
                }
2932

2933
        return 0;
2934

2935
fail:
1✔
2936
        *exit_status = exit_status_table[type];
1✔
2937
        return r;
1✔
2938
}
2939

2940
#if ENABLE_SMACK
2941
static int setup_smack(
×
2942
                const ExecContext *context,
2943
                const ExecParameters *params,
2944
                int executable_fd) {
2945
        int r;
×
2946

2947
        assert(context);
×
2948
        assert(params);
×
2949
        assert(executable_fd >= 0);
×
2950

2951
        if (context->smack_process_label) {
×
2952
                r = mac_smack_apply_pid(0, context->smack_process_label);
×
2953
                if (r < 0)
×
2954
                        return r;
×
2955
        } else if (params->fallback_smack_process_label) {
×
2956
                _cleanup_free_ char *exec_label = NULL;
×
2957

2958
                r = mac_smack_read_fd(executable_fd, SMACK_ATTR_EXEC, &exec_label);
×
2959
                if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
×
2960
                        return r;
2961

2962
                r = mac_smack_apply_pid(0, exec_label ?: params->fallback_smack_process_label);
×
2963
                if (r < 0)
×
2964
                        return r;
2965
        }
2966

2967
        return 0;
2968
}
2969
#endif
2970

2971
static int compile_bind_mounts(
2,014✔
2972
                const ExecContext *context,
2973
                const ExecParameters *params,
2974
                uid_t exec_directory_uid, /* only used for id-mapped mounts Exec directories */
2975
                gid_t exec_directory_gid, /* only used for id-mapped mounts Exec directories */
2976
                BindMount **ret_bind_mounts,
2977
                size_t *ret_n_bind_mounts,
2978
                char ***ret_empty_directories) {
2979

2980
        _cleanup_strv_free_ char **empty_directories = NULL;
2,014✔
2981
        BindMount *bind_mounts = NULL;
2,014✔
2982
        size_t n, h = 0;
2,014✔
2983
        int r;
2,014✔
2984

2985
        assert(context);
2,014✔
2986
        assert(params);
2,014✔
2987
        assert(ret_bind_mounts);
2,014✔
2988
        assert(ret_n_bind_mounts);
2,014✔
2989
        assert(ret_empty_directories);
2,014✔
2990

2991
        CLEANUP_ARRAY(bind_mounts, h, bind_mount_free_many);
2,014✔
2992

2993
        n = context->n_bind_mounts;
2,014✔
2994
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
12,084✔
2995
                if (!params->prefix[t])
10,070✔
2996
                        continue;
×
2997

2998
                FOREACH_ARRAY(i, context->directories[t].items, context->directories[t].n_items)
11,658✔
2999
                        n += !FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE) || FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY);
1,588✔
3000
        }
3001

3002
        if (n <= 0) {
2,014✔
3003
                *ret_bind_mounts = NULL;
1,090✔
3004
                *ret_n_bind_mounts = 0;
1,090✔
3005
                *ret_empty_directories = NULL;
1,090✔
3006
                return 0;
1,090✔
3007
        }
3008

3009
        bind_mounts = new(BindMount, n);
924✔
3010
        if (!bind_mounts)
924✔
3011
                return -ENOMEM;
3012

3013
        FOREACH_ARRAY(item, context->bind_mounts, context->n_bind_mounts) {
946✔
3014
                r = bind_mount_add(&bind_mounts, &h, item);
22✔
3015
                if (r < 0)
22✔
3016
                        return r;
3017
        }
3018

3019
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
5,544✔
3020
                if (!params->prefix[t])
4,620✔
3021
                        continue;
×
3022

3023
                if (context->directories[t].n_items == 0)
4,620✔
3024
                        continue;
3,488✔
3025

3026
                if (exec_directory_is_private(context, t) &&
1,145✔
3027
                    !exec_context_with_rootfs(context)) {
13✔
3028
                        char *private_root;
13✔
3029

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

3034
                        private_root = path_join(params->prefix[t], "private");
13✔
3035
                        if (!private_root)
13✔
3036
                                return -ENOMEM;
3037

3038
                        r = strv_consume(&empty_directories, private_root);
13✔
3039
                        if (r < 0)
13✔
3040
                                return r;
3041
                }
3042

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

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

3053
                        if (exec_directory_is_private(context, t))
1,588✔
3054
                                s = path_join(params->prefix[t], "private", i->path);
13✔
3055
                        else
3056
                                s = path_join(params->prefix[t], i->path);
1,575✔
3057
                        if (!s)
1,588✔
3058
                                return -ENOMEM;
3059

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

3071
                        bind_mounts[h++] = (BindMount) {
1,588✔
3072
                                .source = TAKE_PTR(s),
1,588✔
3073
                                .destination = TAKE_PTR(d),
1,588✔
3074
                                .nosuid = context->dynamic_user, /* don't allow suid/sgid when DynamicUser= is on */
1,588✔
3075
                                .recursive = true,
3076
                                .read_only = FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY),
1,588✔
3077
                                .idmapped = i->idmapped,
1,588✔
3078
                                .uid = exec_directory_uid,
3079
                                .gid = exec_directory_gid,
3080
                        };
3081
                }
3082
        }
3083

3084
        assert(h == n);
924✔
3085

3086
        *ret_bind_mounts = TAKE_PTR(bind_mounts);
924✔
3087
        *ret_n_bind_mounts = n;
924✔
3088
        *ret_empty_directories = TAKE_PTR(empty_directories);
924✔
3089

3090
        return (int) n;
924✔
3091
}
3092

3093
/* ret_symlinks will contain a list of pairs src:dest that describes
3094
 * the symlinks to create later on. For example, the symlinks needed
3095
 * to safely give private directories to DynamicUser=1 users. */
3096
static int compile_symlinks(
2,014✔
3097
                const ExecContext *context,
3098
                const ExecParameters *params,
3099
                bool setup_os_release_symlink,
3100
                char ***ret_symlinks) {
3101

3102
        _cleanup_strv_free_ char **symlinks = NULL;
2,014✔
3103
        int r;
2,014✔
3104

3105
        assert(context);
2,014✔
3106
        assert(params);
2,014✔
3107
        assert(ret_symlinks);
2,014✔
3108

3109
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++)
12,084✔
3110
                FOREACH_ARRAY(i, context->directories[dt].items, context->directories[dt].n_items) {
11,658✔
3111
                        _cleanup_free_ char *private_path = NULL, *path = NULL;
1,575✔
3112

3113
                        STRV_FOREACH(symlink, i->symlinks) {
1,714✔
3114
                                _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;
126✔
3115

3116
                                src_abs = path_join(params->prefix[dt], i->path);
126✔
3117
                                dst_abs = path_join(params->prefix[dt], *symlink);
126✔
3118
                                if (!src_abs || !dst_abs)
126✔
3119
                                        return -ENOMEM;
3120

3121
                                r = strv_consume_pair(&symlinks, TAKE_PTR(src_abs), TAKE_PTR(dst_abs));
126✔
3122
                                if (r < 0)
126✔
3123
                                        return r;
3124
                        }
3125

3126
                        if (!exec_directory_is_private(context, dt) ||
1,601✔
3127
                            exec_context_with_rootfs(context) ||
13✔
3128
                            FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE))
13✔
3129
                                continue;
1,575✔
3130

3131
                        private_path = path_join(params->prefix[dt], "private", i->path);
13✔
3132
                        if (!private_path)
13✔
3133
                                return -ENOMEM;
3134

3135
                        path = path_join(params->prefix[dt], i->path);
13✔
3136
                        if (!path)
13✔
3137
                                return -ENOMEM;
3138

3139
                        r = strv_consume_pair(&symlinks, TAKE_PTR(private_path), TAKE_PTR(path));
13✔
3140
                        if (r < 0)
13✔
3141
                                return r;
3142
                }
3143

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

3157
        *ret_symlinks = TAKE_PTR(symlinks);
2,014✔
3158

3159
        return 0;
2,014✔
3160
}
3161

3162
static bool insist_on_sandboxing(
×
3163
                const ExecContext *context,
3164
                const char *root_dir,
3165
                const char *root_image,
3166
                const BindMount *bind_mounts,
3167
                size_t n_bind_mounts) {
3168

3169
        assert(context);
×
3170
        assert(n_bind_mounts == 0 || bind_mounts);
×
3171

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

3176
        if (context->n_temporary_filesystems > 0)
×
3177
                return true;
3178

3179
        if (root_dir || root_image)
×
3180
                return true;
3181

3182
        if (context->n_mount_images > 0)
×
3183
                return true;
3184

3185
        if (context->dynamic_user)
×
3186
                return true;
3187

3188
        if (context->n_extension_images > 0 || !strv_isempty(context->extension_directories))
×
3189
                return true;
3190

3191
        /* If there are any bind mounts set that don't map back onto themselves, fs namespacing becomes
3192
         * essential. */
3193
        FOREACH_ARRAY(i, bind_mounts, n_bind_mounts)
×
3194
                if (!path_equal(i->source, i->destination))
×
3195
                        return true;
3196

3197
        if (context->log_namespace)
×
3198
                return true;
×
3199

3200
        return false;
3201
}
3202

3203
static int setup_ephemeral(
2,014✔
3204
                const ExecContext *context,
3205
                ExecRuntime *runtime,
3206
                char **root_image,            /* both input and output! modified if ephemeral logic enabled */
3207
                char **root_directory,        /* ditto */
3208
                char **reterr_path) {
3209

3210
        _cleanup_close_ int fd = -EBADF;
2,014✔
3211
        _cleanup_free_ char *new_root = NULL;
2,014✔
3212
        int r;
2,014✔
3213

3214
        assert(context);
2,014✔
3215
        assert(runtime);
2,014✔
3216
        assert(root_image);
2,014✔
3217
        assert(root_directory);
2,014✔
3218

3219
        if (!*root_image && !*root_directory)
2,014✔
3220
                return 0;
3221

3222
        if (!runtime->ephemeral_copy)
8✔
3223
                return 0;
3224

3225
        assert(runtime->ephemeral_storage_socket[0] >= 0);
×
3226
        assert(runtime->ephemeral_storage_socket[1] >= 0);
×
3227

3228
        new_root = strdup(runtime->ephemeral_copy);
×
3229
        if (!new_root)
×
3230
                return log_oom_debug();
×
3231

3232
        r = posix_lock(runtime->ephemeral_storage_socket[0], LOCK_EX);
×
3233
        if (r < 0)
×
3234
                return log_debug_errno(r, "Failed to lock ephemeral storage socket: %m");
×
3235

3236
        CLEANUP_POSIX_UNLOCK(runtime->ephemeral_storage_socket[0]);
×
3237

3238
        fd = receive_one_fd(runtime->ephemeral_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
×
3239
        if (fd >= 0)
×
3240
                /* We got an fd! That means ephemeral has already been set up, so nothing to do here. */
3241
                return 0;
3242
        if (fd != -EAGAIN)
×
3243
                return log_debug_errno(fd, "Failed to receive file descriptor queued on ephemeral storage socket: %m");
×
3244

3245
        if (*root_image) {
×
3246
                log_debug("Making ephemeral copy of %s to %s", *root_image, new_root);
×
3247

3248
                fd = copy_file(*root_image, new_root, O_EXCL, 0600,
×
3249
                               COPY_LOCK_BSD|COPY_REFLINK|COPY_CRTIME|COPY_NOCOW_AFTER);
3250
                if (fd < 0) {
×
3251
                        *reterr_path = strdup(*root_image);
×
3252
                        return log_debug_errno(fd, "Failed to copy image %s to %s: %m",
×
3253
                                               *root_image, new_root);
3254
                }
3255
        } else {
3256
                assert(*root_directory);
×
3257

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

3260
                fd = btrfs_subvol_snapshot_at(
×
3261
                                AT_FDCWD, *root_directory,
3262
                                AT_FDCWD, new_root,
3263
                                BTRFS_SNAPSHOT_FALLBACK_COPY |
3264
                                BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
3265
                                BTRFS_SNAPSHOT_RECURSIVE |
3266
                                BTRFS_SNAPSHOT_LOCK_BSD);
3267
                if (fd < 0) {
×
3268
                        *reterr_path = strdup(*root_directory);
×
3269
                        return log_debug_errno(fd, "Failed to snapshot directory %s to %s: %m",
×
3270
                                               *root_directory, new_root);
3271
                }
3272
        }
3273

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

3278
        if (*root_image)
×
3279
                free_and_replace(*root_image, new_root);
×
3280
        else {
3281
                assert(*root_directory);
×
3282
                free_and_replace(*root_directory, new_root);
×
3283
        }
3284

3285
        return 1;
3286
}
3287

3288
static int verity_settings_prepare(
7✔
3289
                VeritySettings *verity,
3290
                const char *root_image,
3291
                const void *root_hash,
3292
                size_t root_hash_size,
3293
                const char *root_hash_path,
3294
                const void *root_hash_sig,
3295
                size_t root_hash_sig_size,
3296
                const char *root_hash_sig_path,
3297
                const char *verity_data_path) {
3298

3299
        int r;
7✔
3300

3301
        assert(verity);
7✔
3302

3303
        if (root_hash) {
7✔
3304
                void *d;
4✔
3305

3306
                d = memdup(root_hash, root_hash_size);
4✔
3307
                if (!d)
4✔
3308
                        return -ENOMEM;
7✔
3309

3310
                free_and_replace(verity->root_hash, d);
4✔
3311
                verity->root_hash_size = root_hash_size;
4✔
3312
                verity->designator = PARTITION_ROOT;
4✔
3313
        }
3314

3315
        if (root_hash_sig) {
7✔
3316
                void *d;
×
3317

3318
                d = memdup(root_hash_sig, root_hash_sig_size);
×
3319
                if (!d)
×
3320
                        return -ENOMEM;
7✔
3321

3322
                free_and_replace(verity->root_hash_sig, d);
×
3323
                verity->root_hash_sig_size = root_hash_sig_size;
×
3324
                verity->designator = PARTITION_ROOT;
×
3325
        }
3326

3327
        if (verity_data_path) {
7✔
3328
                r = free_and_strdup(&verity->data_path, verity_data_path);
×
3329
                if (r < 0)
×
3330
                        return r;
3331
        }
3332

3333
        r = verity_settings_load(
7✔
3334
                        verity,
3335
                        root_image,
3336
                        root_hash_path,
3337
                        root_hash_sig_path);
3338
        if (r < 0)
7✔
3339
                return log_debug_errno(r, "Failed to load root hash: %m");
×
3340

3341
        return 0;
3342
}
3343

3344
static int pick_versions(
2,016✔
3345
                const ExecContext *context,
3346
                const ExecParameters *params,
3347
                char **ret_root_image,
3348
                char **ret_root_directory,
3349
                char **reterr_path) {
3350

3351
        int r;
2,016✔
3352

3353
        assert(context);
2,016✔
3354
        assert(params);
2,016✔
3355
        assert(ret_root_image);
2,016✔
3356
        assert(ret_root_directory);
2,016✔
3357

3358
        if (context->root_image) {
2,016✔
3359
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
8✔
3360

3361
                r = path_pick(/* toplevel_path= */ NULL,
16✔
3362
                              /* toplevel_fd= */ AT_FDCWD,
3363
                              context->root_image,
8✔
3364
                              &pick_filter_image_raw,
3365
                              PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3366
                              &result);
3367
                if (r < 0) {
8✔
3368
                        *reterr_path = strdup(context->root_image);
1✔
3369
                        return r;
1✔
3370
                }
3371

3372
                if (!result.path) {
7✔
3373
                        *reterr_path = strdup(context->root_image);
×
3374
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_image);
×
3375
                }
3376

3377
                *ret_root_image = TAKE_PTR(result.path);
7✔
3378
                *ret_root_directory = NULL;
7✔
3379
                return r;
7✔
3380
        }
3381

3382
        if (context->root_directory) {
2,008✔
3383
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
2✔
3384

3385
                r = path_pick(/* toplevel_path= */ NULL,
4✔
3386
                              /* toplevel_fd= */ AT_FDCWD,
3387
                              context->root_directory,
2✔
3388
                              &pick_filter_image_dir,
3389
                              PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3390
                              &result);
3391
                if (r < 0) {
2✔
3392
                        *reterr_path = strdup(context->root_directory);
×
3393
                        return r;
×
3394
                }
3395

3396
                if (!result.path) {
2✔
3397
                        *reterr_path = strdup(context->root_directory);
1✔
3398
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_directory);
1✔
3399
                }
3400

3401
                *ret_root_image = NULL;
1✔
3402
                *ret_root_directory = TAKE_PTR(result.path);
1✔
3403
                return r;
1✔
3404
        }
3405

3406
        *ret_root_image = *ret_root_directory = NULL;
2,006✔
3407
        return 0;
2,006✔
3408
}
3409

3410
static int apply_mount_namespace(
2,016✔
3411
                ExecCommandFlags command_flags,
3412
                const ExecContext *context,
3413
                const ExecParameters *params,
3414
                ExecRuntime *runtime,
3415
                const char *memory_pressure_path,
3416
                bool needs_sandboxing,
3417
                char **reterr_path,
3418
                uid_t exec_directory_uid,
3419
                gid_t exec_directory_gid) {
3420

3421
        _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
2,016✔
3422
        _cleanup_strv_free_ char **empty_directories = NULL, **symlinks = NULL,
2,016✔
3423
                        **read_write_paths_cleanup = NULL;
×
3424
        _cleanup_free_ char *creds_path = NULL, *incoming_dir = NULL, *propagate_dir = NULL,
×
3425
                *private_namespace_dir = NULL, *host_os_release_stage = NULL, *root_image = NULL, *root_dir = NULL;
2,016✔
3426
        const char *tmp_dir = NULL, *var_tmp_dir = NULL;
2,016✔
3427
        char **read_write_paths;
2,016✔
3428
        bool setup_os_release_symlink;
2,016✔
3429
        BindMount *bind_mounts = NULL;
2,016✔
3430
        size_t n_bind_mounts = 0;
2,016✔
3431
        int r;
2,016✔
3432

3433
        assert(context);
2,016✔
3434
        assert(params);
2,016✔
3435
        assert(runtime);
2,016✔
3436

3437
        CLEANUP_ARRAY(bind_mounts, n_bind_mounts, bind_mount_free_many);
2,016✔
3438

3439
        if (params->flags & EXEC_APPLY_CHROOT) {
2,016✔
3440
                r = pick_versions(
2,016✔
3441
                                context,
3442
                                params,
3443
                                &root_image,
3444
                                &root_dir,
3445
                                reterr_path);
3446
                if (r < 0)
2,016✔
3447
                        return r;
3448

3449
                r = setup_ephemeral(
2,014✔
3450
                                context,
3451
                                runtime,
3452
                                &root_image,
3453
                                &root_dir,
3454
                                reterr_path);
3455
                if (r < 0)
2,014✔
3456
                        return r;
3457
        }
3458

3459
        r = compile_bind_mounts(context, params, exec_directory_uid, exec_directory_gid, &bind_mounts, &n_bind_mounts, &empty_directories);
2,014✔
3460
        if (r < 0)
2,014✔
3461
                return r;
3462

3463
        /* We need to make the pressure path writable even if /sys/fs/cgroups is made read-only, as the
3464
         * service will need to write to it in order to start the notifications. */
3465
        if (exec_is_cgroup_mount_read_only(context) && memory_pressure_path && !streq(memory_pressure_path, "/dev/null")) {
2,014✔
3466
                read_write_paths_cleanup = strv_copy(context->read_write_paths);
1,137✔
3467
                if (!read_write_paths_cleanup)
1,137✔
3468
                        return -ENOMEM;
3469

3470
                r = strv_extend(&read_write_paths_cleanup, memory_pressure_path);
1,137✔
3471
                if (r < 0)
1,137✔
3472
                        return r;
3473

3474
                read_write_paths = read_write_paths_cleanup;
1,137✔
3475
        } else
3476
                read_write_paths = context->read_write_paths;
877✔
3477

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

3483
                if (context->private_tmp == PRIVATE_TMP_CONNECTED && runtime->shared) {
2,014✔
3484
                        if (streq_ptr(runtime->shared->tmp_dir, RUN_SYSTEMD_EMPTY))
323✔
3485
                                tmp_dir = runtime->shared->tmp_dir;
3486
                        else if (runtime->shared->tmp_dir)
323✔
3487
                                tmp_dir = strjoina(runtime->shared->tmp_dir, "/tmp");
1,615✔
3488

3489
                        if (streq_ptr(runtime->shared->var_tmp_dir, RUN_SYSTEMD_EMPTY))
323✔
3490
                                var_tmp_dir = runtime->shared->var_tmp_dir;
3491
                        else if (runtime->shared->var_tmp_dir)
323✔
3492
                                var_tmp_dir = strjoina(runtime->shared->var_tmp_dir, "/tmp");
1,615✔
3493
                }
3494
        }
3495

3496
        /* Symlinks (exec dirs, os-release) are set up after other mounts, before they are made read-only. */
3497
        setup_os_release_symlink = needs_sandboxing && exec_context_get_effective_mount_apivfs(context) && (root_dir || root_image);
2,014✔
3498
        r = compile_symlinks(context, params, setup_os_release_symlink, &symlinks);
2,014✔
3499
        if (r < 0)
2,014✔
3500
                return r;
3501

3502
        if (context->mount_propagation_flag == MS_SHARED)
2,014✔
3503
                log_debug("shared mount propagation hidden by other fs namespacing unit settings: ignoring");
×
3504

3505
        r = exec_context_get_credential_directory(context, params, params->unit_id, &creds_path);
2,014✔
3506
        if (r < 0)
2,014✔
3507
                return r;
3508

3509
        if (params->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
2,014✔
3510
                propagate_dir = path_join("/run/systemd/propagate/", params->unit_id);
1,987✔
3511
                if (!propagate_dir)
1,987✔
3512
                        return -ENOMEM;
3513

3514
                incoming_dir = strdup("/run/systemd/incoming");
1,987✔
3515
                if (!incoming_dir)
1,987✔
3516
                        return -ENOMEM;
3517

3518
                private_namespace_dir = strdup("/run/systemd");
1,987✔
3519
                if (!private_namespace_dir)
1,987✔
3520
                        return -ENOMEM;
3521

3522
                /* If running under a different root filesystem, propagate the host's os-release. We make a
3523
                 * copy rather than just bind mounting it, so that it can be updated on soft-reboot. */
3524
                if (setup_os_release_symlink) {
1,987✔
3525
                        host_os_release_stage = strdup("/run/systemd/propagate/.os-release-stage");
7✔
3526
                        if (!host_os_release_stage)
7✔
3527
                                return -ENOMEM;
3528
                }
3529
        } else {
3530
                assert(params->runtime_scope == RUNTIME_SCOPE_USER);
27✔
3531

3532
                if (asprintf(&private_namespace_dir, "/run/user/" UID_FMT "/systemd", geteuid()) < 0)
27✔
3533
                        return -ENOMEM;
3534

3535
                if (setup_os_release_symlink) {
27✔
3536
                        if (asprintf(&host_os_release_stage,
×
3537
                                     "/run/user/" UID_FMT "/systemd/propagate/.os-release-stage",
3538
                                     geteuid()) < 0)
3539
                                return -ENOMEM;
3540
                }
3541
        }
3542

3543
        if (root_image) {
2,014✔
3544
                r = verity_settings_prepare(
14✔
3545
                        &verity,
3546
                        root_image,
3547
                        context->root_hash, context->root_hash_size, context->root_hash_path,
7✔
3548
                        context->root_hash_sig, context->root_hash_sig_size, context->root_hash_sig_path,
7✔
3549
                        context->root_verity);
7✔
3550
                if (r < 0)
7✔
3551
                        return r;
3552
        }
3553

3554
        NamespaceParameters parameters = {
×
3555
                .runtime_scope = params->runtime_scope,
2,014✔
3556

3557
                .root_directory = root_dir,
3558
                .root_image = root_image,
3559
                .root_image_options = context->root_image_options,
2,014✔
3560
                .root_image_policy = context->root_image_policy ?: &image_policy_service,
2,014✔
3561

3562
                .read_write_paths = read_write_paths,
3563
                .read_only_paths = needs_sandboxing ? context->read_only_paths : NULL,
2,014✔
3564
                .inaccessible_paths = needs_sandboxing ? context->inaccessible_paths : NULL,
2,014✔
3565

3566
                .exec_paths = needs_sandboxing ? context->exec_paths : NULL,
2,014✔
3567
                .no_exec_paths = needs_sandboxing ? context->no_exec_paths : NULL,
2,014✔
3568

3569
                .empty_directories = empty_directories,
3570
                .symlinks = symlinks,
3571

3572
                .bind_mounts = bind_mounts,
3573
                .n_bind_mounts = n_bind_mounts,
3574

3575
                .temporary_filesystems = context->temporary_filesystems,
2,014✔
3576
                .n_temporary_filesystems = context->n_temporary_filesystems,
2,014✔
3577

3578
                .mount_images = context->mount_images,
2,014✔
3579
                .n_mount_images = context->n_mount_images,
2,014✔
3580
                .mount_image_policy = context->mount_image_policy ?: &image_policy_service,
2,014✔
3581

3582
                .tmp_dir = tmp_dir,
3583
                .var_tmp_dir = var_tmp_dir,
3584

3585
                .creds_path = creds_path,
3586
                .log_namespace = context->log_namespace,
2,014✔
3587
                .mount_propagation_flag = context->mount_propagation_flag,
2,014✔
3588

3589
                .verity = &verity,
3590

3591
                .extension_images = context->extension_images,
2,014✔
3592
                .n_extension_images = context->n_extension_images,
2,014✔
3593
                .extension_image_policy = context->extension_image_policy ?: &image_policy_sysext,
2,014✔
3594
                .extension_directories = context->extension_directories,
2,014✔
3595

3596
                .propagate_dir = propagate_dir,
3597
                .incoming_dir = incoming_dir,
3598
                .private_namespace_dir = private_namespace_dir,
3599
                .host_notify_socket = params->notify_socket,
2,014✔
3600
                .notify_socket_path = exec_get_private_notify_socket_path(context, params, needs_sandboxing),
2,014✔
3601
                .host_os_release_stage = host_os_release_stage,
3602

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

3608
                .protect_control_groups = needs_sandboxing ? exec_get_protect_control_groups(context) : PROTECT_CONTROL_GROUPS_NO,
2,014✔
3609
                .protect_kernel_tunables = needs_sandboxing && context->protect_kernel_tunables,
2,014✔
3610
                .protect_kernel_modules = needs_sandboxing && context->protect_kernel_modules,
2,014✔
3611
                .protect_kernel_logs = needs_sandboxing && context->protect_kernel_logs,
2,014✔
3612

3613
                .private_dev = needs_sandboxing && context->private_devices,
2,014✔
3614
                .private_network = needs_sandboxing && exec_needs_network_namespace(context),
2,014✔
3615
                .private_ipc = needs_sandboxing && exec_needs_ipc_namespace(context),
2,014✔
3616
                .private_pids = needs_sandboxing && exec_needs_pid_namespace(context) ? context->private_pids : PRIVATE_PIDS_NO,
2,014✔
3617
                .private_tmp = needs_sandboxing ? context->private_tmp : PRIVATE_TMP_NO,
2,014✔
3618
                .private_var_tmp = needs_sandboxing ? context->private_var_tmp : PRIVATE_TMP_NO,
2,014✔
3619

3620
                .mount_apivfs = needs_sandboxing && exec_context_get_effective_mount_apivfs(context),
2,014✔
3621
                .bind_log_sockets = needs_sandboxing && exec_context_get_effective_bind_log_sockets(context),
2,014✔
3622

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

3626
                .protect_home = needs_sandboxing ? context->protect_home : PROTECT_HOME_NO,
2,014✔
3627
                .protect_hostname = needs_sandboxing ? context->protect_hostname : PROTECT_HOSTNAME_NO,
2,014✔
3628
                .protect_system = needs_sandboxing ? context->protect_system : PROTECT_SYSTEM_NO,
2,014✔
3629
                .protect_proc = needs_sandboxing ? context->protect_proc : PROTECT_PROC_DEFAULT,
2,014✔
3630
                .proc_subset = needs_sandboxing ? context->proc_subset : PROC_SUBSET_ALL,
2,014✔
3631
        };
3632

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

3654
                log_debug("Failed to set up namespace, assuming containerized execution and ignoring.");
×
3655
                return 0;
×
3656
        }
3657

3658
        return r;
3659
}
3660

3661
static int apply_working_directory(
9,597✔
3662
                const ExecContext *context,
3663
                const ExecParameters *params,
3664
                ExecRuntime *runtime,
3665
                const char *pwent_home,
3666
                char * const *env) {
3667

3668
        const char *wd;
9,597✔
3669
        int r;
9,597✔
3670

3671
        assert(context);
9,597✔
3672
        assert(params);
9,597✔
3673
        assert(runtime);
9,597✔
3674

3675
        if (context->working_directory_home) {
9,597✔
3676
                /* Preferably use the data from $HOME, in case it was updated by a PAM module */
3677
                wd = strv_env_get(env, "HOME");
102✔
3678
                if (!wd) {
102✔
3679
                        /* If that's not available, use the data from the struct passwd entry: */
3680
                        if (!pwent_home)
1✔
3681
                                return -ENXIO;
3682

3683
                        wd = pwent_home;
3684
                }
3685
        } else
3686
                wd = empty_to_root(context->working_directory);
9,495✔
3687

3688
        if (params->flags & EXEC_APPLY_CHROOT)
9,597✔
3689
                r = RET_NERRNO(chdir(wd));
9,597✔
3690
        else {
3691
                _cleanup_close_ int dfd = -EBADF;
×
3692

3693
                r = chase(wd,
×
3694
                          runtime->ephemeral_copy ?: context->root_directory,
×
3695
                          CHASE_PREFIX_ROOT|CHASE_AT_RESOLVE_IN_ROOT,
3696
                          /* ret_path= */ NULL,
3697
                          &dfd);
3698
                if (r >= 0)
×
3699
                        r = RET_NERRNO(fchdir(dfd));
×
3700
        }
3701
        return context->working_directory_missing_ok ? 0 : r;
9,597✔
3702
}
3703

3704
static int apply_root_directory(
9,597✔
3705
                const ExecContext *context,
3706
                const ExecParameters *params,
3707
                ExecRuntime *runtime,
3708
                const bool needs_mount_ns,
3709
                int *exit_status) {
3710

3711
        assert(context);
9,597✔
3712
        assert(params);
9,597✔
3713
        assert(runtime);
9,597✔
3714
        assert(exit_status);
9,597✔
3715

3716
        if (params->flags & EXEC_APPLY_CHROOT)
9,597✔
3717
                if (!needs_mount_ns && context->root_directory)
9,597✔
3718
                        if (chroot(runtime->ephemeral_copy ?: context->root_directory) < 0) {
×
3719
                                *exit_status = EXIT_CHROOT;
×
3720
                                return -errno;
×
3721
                        }
3722

3723
        return 0;
3724
}
3725

3726
static int setup_keyring(
9,623✔
3727
                const ExecContext *context,
3728
                const ExecParameters *p,
3729
                uid_t uid,
3730
                gid_t gid) {
3731

3732
        key_serial_t keyring;
9,623✔
3733
        int r = 0;
9,623✔
3734
        uid_t saved_uid;
9,623✔
3735
        gid_t saved_gid;
9,623✔
3736

3737
        assert(context);
9,623✔
3738
        assert(p);
9,623✔
3739

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

3747
        if (context->keyring_mode == EXEC_KEYRING_INHERIT)
9,623✔
3748
                return 0;
3749

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

3755
        saved_uid = getuid();
8,641✔
3756
        saved_gid = getgid();
8,641✔
3757

3758
        if (gid_is_valid(gid) && gid != saved_gid) {
8,641✔
3759
                if (setregid(gid, -1) < 0)
1,762✔
3760
                        return log_error_errno(errno, "Failed to change GID for user keyring: %m");
×
3761
        }
3762

3763
        if (uid_is_valid(uid) && uid != saved_uid) {
8,641✔
3764
                if (setreuid(uid, -1) < 0) {
1,759✔
3765
                        r = log_error_errno(errno, "Failed to change UID for user keyring: %m");
×
3766
                        goto out;
×
3767
                }
3768
        }
3769

3770
        keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
8,641✔
3771
        if (keyring == -1) {
8,641✔
3772
                if (errno == ENOSYS)
×
3773
                        log_debug_errno(errno, "Kernel keyring not supported, ignoring.");
×
3774
                else if (ERRNO_IS_PRIVILEGE(errno))
×
3775
                        log_debug_errno(errno, "Kernel keyring access prohibited, ignoring.");
×
3776
                else if (errno == EDQUOT)
×
3777
                        log_debug_errno(errno, "Out of kernel keyrings to allocate, ignoring.");
×
3778
                else
3779
                        r = log_error_errno(errno, "Setting up kernel keyring failed: %m");
×
3780

3781
                goto out;
×
3782
        }
3783

3784
        /* When requested link the user keyring into the session keyring. */
3785
        if (context->keyring_mode == EXEC_KEYRING_SHARED) {
8,641✔
3786

3787
                if (keyctl(KEYCTL_LINK,
931✔
3788
                           KEY_SPEC_USER_KEYRING,
3789
                           KEY_SPEC_SESSION_KEYRING, 0, 0) < 0) {
3790
                        r = log_error_errno(errno, "Failed to link user keyring into session keyring: %m");
×
3791
                        goto out;
×
3792
                }
3793
        }
3794

3795
        /* Restore uid/gid back */
3796
        if (uid_is_valid(uid) && uid != saved_uid) {
8,641✔
3797
                if (setreuid(saved_uid, -1) < 0) {
1,759✔
3798
                        r = log_error_errno(errno, "Failed to change UID back for user keyring: %m");
×
3799
                        goto out;
×
3800
                }
3801
        }
3802

3803
        if (gid_is_valid(gid) && gid != saved_gid) {
8,641✔
3804
                if (setregid(saved_gid, -1) < 0)
1,762✔
3805
                        return log_error_errno(errno, "Failed to change GID back for user keyring: %m");
×
3806
        }
3807

3808
        /* Populate they keyring with the invocation ID by default, as original saved_uid. */
3809
        if (!sd_id128_is_null(p->invocation_id)) {
8,641✔
3810
                key_serial_t key;
8,641✔
3811

3812
                key = add_key("user",
17,282✔
3813
                              "invocation_id",
3814
                              &p->invocation_id,
8,641✔
3815
                              sizeof(p->invocation_id),
3816
                              KEY_SPEC_SESSION_KEYRING);
3817
                if (key == -1)
8,641✔
3818
                        log_debug_errno(errno, "Failed to add invocation ID to keyring, ignoring: %m");
×
3819
                else {
3820
                        if (keyctl(KEYCTL_SETPERM, key,
8,641✔
3821
                                   KEY_POS_VIEW|KEY_POS_READ|KEY_POS_SEARCH|
3822
                                   KEY_USR_VIEW|KEY_USR_READ|KEY_USR_SEARCH, 0, 0) < 0)
3823
                                r = log_error_errno(errno, "Failed to restrict invocation ID permission: %m");
×
3824
                }
3825
        }
3826

3827
out:
8,641✔
3828
        /* Revert back uid & gid for the last time, and exit */
3829
        /* no extra logging, as only the first already reported error matters */
3830
        if (getuid() != saved_uid)
8,641✔
3831
                (void) setreuid(saved_uid, -1);
×
3832

3833
        if (getgid() != saved_gid)
8,641✔
3834
                (void) setregid(saved_gid, -1);
×
3835

3836
        return r;
3837
}
3838

3839
static void append_socket_pair(int *array, size_t *n, const int pair[static 2]) {
34,867✔
3840
        assert(array);
34,867✔
3841
        assert(n);
34,867✔
3842
        assert(pair);
34,867✔
3843

3844
        if (pair[0] >= 0)
34,867✔
3845
                array[(*n)++] = pair[0];
190✔
3846
        if (pair[1] >= 0)
34,867✔
3847
                array[(*n)++] = pair[1];
190✔
3848
}
34,867✔
3849

3850
static int close_remaining_fds(
11,581✔
3851
                const ExecParameters *params,
3852
                const ExecRuntime *runtime,
3853
                int socket_fd,
3854
                const int *fds,
3855
                size_t n_fds) {
11,581✔
3856

3857
        size_t n_dont_close = 0;
11,581✔
3858
        int dont_close[n_fds + 17];
11,581✔
3859

3860
        assert(params);
11,581✔
3861
        assert(runtime);
11,581✔
3862

3863
        if (params->stdin_fd >= 0)
11,581✔
3864
                dont_close[n_dont_close++] = params->stdin_fd;
544✔
3865
        if (params->stdout_fd >= 0)
11,581✔
3866
                dont_close[n_dont_close++] = params->stdout_fd;
544✔
3867
        if (params->stderr_fd >= 0)
11,581✔
3868
                dont_close[n_dont_close++] = params->stderr_fd;
544✔
3869

3870
        if (socket_fd >= 0)
11,581✔
3871
                dont_close[n_dont_close++] = socket_fd;
17✔
3872
        if (n_fds > 0) {
11,581✔
3873
                memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
11,581✔
3874
                n_dont_close += n_fds;
11,581✔
3875
        }
3876

3877
        append_socket_pair(dont_close, &n_dont_close, runtime->ephemeral_storage_socket);
11,581✔
3878

3879
        if (runtime->shared) {
11,581✔
3880
                append_socket_pair(dont_close, &n_dont_close, runtime->shared->netns_storage_socket);
11,581✔
3881
                append_socket_pair(dont_close, &n_dont_close, runtime->shared->ipcns_storage_socket);
11,581✔
3882
        }
3883

3884
        if (runtime->dynamic_creds) {
11,581✔
3885
                if (runtime->dynamic_creds->user)
11,581✔
3886
                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->user->storage_socket);
62✔
3887
                if (runtime->dynamic_creds->group)
11,581✔
3888
                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->group->storage_socket);
62✔
3889
        }
3890

3891
        if (params->user_lookup_fd >= 0)
11,581✔
3892
                dont_close[n_dont_close++] = params->user_lookup_fd;
11,581✔
3893

3894
        if (params->handoff_timestamp_fd >= 0)
11,581✔
3895
                dont_close[n_dont_close++] = params->handoff_timestamp_fd;
11,581✔
3896

3897
        if (params->pidref_transport_fd >= 0)
11,581✔
3898
                dont_close[n_dont_close++] = params->pidref_transport_fd;
10,530✔
3899

3900
        assert(n_dont_close <= ELEMENTSOF(dont_close));
11,581✔
3901

3902
        return close_all_fds(dont_close, n_dont_close);
11,581✔
3903
}
3904

3905
static int send_user_lookup(
11,579✔
3906
                const char *unit_id,
3907
                int user_lookup_fd,
3908
                uid_t uid,
3909
                gid_t gid) {
3910

3911
        assert(unit_id);
11,579✔
3912

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

3917
        if (user_lookup_fd < 0)
11,579✔
3918
                return 0;
3919

3920
        if (!uid_is_valid(uid) && !gid_is_valid(gid))
11,579✔
3921
                return 0;
3922

3923
        if (writev(user_lookup_fd,
2,680✔
3924
               (struct iovec[]) {
2,680✔
3925
                           IOVEC_MAKE(&uid, sizeof(uid)),
3926
                           IOVEC_MAKE(&gid, sizeof(gid)),
3927
                           IOVEC_MAKE_STRING(unit_id) }, 3) < 0)
2,680✔
3928
                return -errno;
×
3929

3930
        return 0;
2,680✔
3931
}
3932

3933
static int acquire_home(const ExecContext *c, const char **home, char **ret_buf) {
11,579✔
3934
        int r;
11,579✔
3935

3936
        assert(c);
11,579✔
3937
        assert(home);
11,579✔
3938
        assert(ret_buf);
11,579✔
3939

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

3942
        if (*home) /* Already acquired from get_fixed_user()? */
11,579✔
3943
                return 0;
3944

3945
        if (!c->working_directory_home)
8,966✔
3946
                return 0;
3947

3948
        if (c->dynamic_user || (c->user && is_this_me(c->user) <= 0))
×
3949
                return -EADDRNOTAVAIL;
×
3950

3951
        r = get_home_dir(ret_buf);
×
3952
        if (r < 0)
×
3953
                return r;
3954

3955
        *home = *ret_buf;
×
3956
        return 1;
×
3957
}
3958

3959
static int compile_suggested_paths(const ExecContext *c, const ExecParameters *p, char ***ret) {
62✔
3960
        _cleanup_strv_free_ char ** list = NULL;
62✔
3961
        int r;
62✔
3962

3963
        assert(c);
62✔
3964
        assert(p);
62✔
3965
        assert(ret);
62✔
3966

3967
        assert(c->dynamic_user);
62✔
3968

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

3973
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
372✔
3974

3975
                if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(t))
310✔
3976
                        continue;
62✔
3977

3978
                if (!p->prefix[t])
248✔
3979
                        continue;
×
3980

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

3984
                        if (exec_directory_is_private(c, t))
15✔
3985
                                e = path_join(p->prefix[t], "private", c->directories[t].items[i].path);
13✔
3986
                        else
3987
                                e = path_join(p->prefix[t], c->directories[t].items[i].path);
2✔
3988
                        if (!e)
15✔
3989
                                return -ENOMEM;
3990

3991
                        r = strv_consume(&list, e);
15✔
3992
                        if (r < 0)
15✔
3993
                                return r;
3994
                }
3995
        }
3996

3997
        *ret = TAKE_PTR(list);
62✔
3998

3999
        return 0;
62✔
4000
}
4001

4002
static int exec_context_cpu_affinity_from_numa(const ExecContext *c, CPUSet *ret) {
2✔
4003
        _cleanup_(cpu_set_reset) CPUSet s = {};
2✔
4004
        int r;
2✔
4005

4006
        assert(c);
2✔
4007
        assert(ret);
2✔
4008

4009
        if (!c->numa_policy.nodes.set) {
2✔
4010
                log_debug("Can't derive CPU affinity mask from NUMA mask because NUMA mask is not set, ignoring");
×
4011
                return 0;
×
4012
        }
4013

4014
        r = numa_to_cpu_set(&c->numa_policy, &s);
2✔
4015
        if (r < 0)
2✔
4016
                return r;
4017

4018
        cpu_set_reset(ret);
2✔
4019

4020
        return cpu_set_add_all(ret, &s);
2✔
4021
}
4022

4023
static int add_shifted_fd(int *fds, size_t fds_size, size_t *n_fds, int *fd) {
44,340✔
4024
        int r;
44,340✔
4025

4026
        assert(fds);
44,340✔
4027
        assert(n_fds);
44,340✔
4028
        assert(*n_fds < fds_size);
44,340✔
4029
        assert(fd);
44,340✔
4030

4031
        if (*fd < 0)
44,340✔
4032
               return 0;
44,340✔
4033

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

4038
                r = fcntl(*fd, F_DUPFD_CLOEXEC, 3 + (int) *n_fds);
9,597✔
4039
                if (r < 0)
9,597✔
4040
                        return -errno;
×
4041

4042
                close_and_replace(*fd, r);
9,597✔
4043
        }
4044

4045
        fds[(*n_fds)++] = *fd;
21,573✔
4046
        return 1;
21,573✔
4047
}
4048

4049
static int connect_unix_harder(const OpenFile *of, int ofd) {
1✔
4050
        static const int socket_types[] = { SOCK_DGRAM, SOCK_STREAM, SOCK_SEQPACKET };
1✔
4051

4052
        union sockaddr_union addr = {
1✔
4053
                .un.sun_family = AF_UNIX,
4054
        };
4055
        socklen_t sa_len;
1✔
4056
        int r;
1✔
4057

4058
        assert(of);
1✔
4059
        assert(ofd >= 0);
1✔
4060

4061
        r = sockaddr_un_set_path(&addr.un, FORMAT_PROC_FD_PATH(ofd));
1✔
4062
        if (r < 0)
1✔
4063
                return log_debug_errno(r, "Failed to set sockaddr for '%s': %m", of->path);
×
4064
        sa_len = r;
1✔
4065

4066
        FOREACH_ELEMENT(i, socket_types) {
2✔
4067
                _cleanup_close_ int fd = -EBADF;
2✔
4068

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

4073
                r = RET_NERRNO(connect(fd, &addr.sa, sa_len));
2✔
4074
                if (r >= 0)
1✔
4075
                        return TAKE_FD(fd);
1✔
4076
                if (r != -EPROTOTYPE)
1✔
4077
                        return log_debug_errno(r, "Failed to connect to socket for '%s': %m", of->path);
×
4078
        }
4079

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

4083
static int get_open_file_fd(const OpenFile *of) {
5✔
4084
        _cleanup_close_ int fd = -EBADF, ofd = -EBADF;
5✔
4085
        struct stat st;
5✔
4086

4087
        assert(of);
5✔
4088

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

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

4096
        if (S_ISSOCK(st.st_mode)) {
3✔
4097
                fd = connect_unix_harder(of, ofd);
1✔
4098
                if (fd < 0)
1✔
4099
                        return fd;
4100

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

4104
                log_debug("Opened socket '%s' as fd %d.", of->path, fd);
1✔
4105
        } else {
4106
                int flags = FLAGS_SET(of->flags, OPENFILE_READ_ONLY) ? O_RDONLY : O_RDWR;
2✔
4107
                if (FLAGS_SET(of->flags, OPENFILE_APPEND))
2✔
4108
                        flags |= O_APPEND;
×
4109
                else if (FLAGS_SET(of->flags, OPENFILE_TRUNCATE))
2✔
4110
                        flags |= O_TRUNC;
×
4111

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

4116
                log_debug("Opened file '%s' as fd %d.", of->path, fd);
2✔
4117
        }
4118

4119
        return TAKE_FD(fd);
4120
}
4121

4122
static int collect_open_file_fds(ExecParameters *p, size_t *n_fds) {
11,582✔
4123
        assert(p);
11,582✔
4124
        assert(n_fds);
11,582✔
4125

4126
        LIST_FOREACH(open_files, of, p->open_files) {
11,582✔
4127
                _cleanup_close_ int fd = -EBADF;
11,587✔
4128

4129
                fd = get_open_file_fd(of);
5✔
4130
                if (fd < 0) {
5✔
4131
                        if (FLAGS_SET(of->flags, OPENFILE_GRACEFUL)) {
2✔
4132
                                log_full_errno(fd == -ENOENT || ERRNO_IS_NEG_PRIVILEGE(fd) ? LOG_DEBUG : LOG_WARNING,
1✔
4133
                                               fd,
4134
                                               "Failed to get OpenFile= file descriptor for '%s', ignoring: %m",
4135
                                               of->path);
4136
                                continue;
1✔
4137
                        }
4138

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

4142
                if (!GREEDY_REALLOC(p->fds, *n_fds + 1))
3✔
4143
                        return log_oom();
×
4144

4145
                if (strv_extend(&p->fd_names, of->fdname) < 0)
3✔
4146
                        return log_oom();
×
4147

4148
                p->fds[(*n_fds)++] = TAKE_FD(fd);
3✔
4149
        }
4150

4151
        return 0;
4152
}
4153

4154
static void log_command_line(
9,596✔
4155
                const ExecContext *context,
4156
                const ExecParameters *params,
4157
                const char *msg,
4158
                const char *executable,
4159
                char **argv) {
4160

4161
        assert(context);
9,596✔
4162
        assert(params);
9,596✔
4163
        assert(msg);
9,596✔
4164
        assert(executable);
9,596✔
4165

4166
        if (!DEBUG_LOGGING)
9,596✔
4167
                return;
9,596✔
4168

4169
        _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);
18,546✔
4170

4171
        log_struct(LOG_DEBUG,
17,746✔
4172
                   LOG_ITEM("EXECUTABLE=%s", executable),
4173
                   LOG_EXEC_MESSAGE(params, "%s: %s", msg, strnull(cmdline)),
4174
                   LOG_EXEC_INVOCATION_ID(params));
4175
}
4176

4177
static bool exec_context_needs_cap_sys_admin(const ExecContext *context) {
1,650✔
4178
        assert(context);
1,650✔
4179

4180
        return context->private_users != PRIVATE_USERS_NO ||
3,287✔
4181
               context->private_tmp != PRIVATE_TMP_NO ||
1,637✔
4182
               context->private_devices ||
1,622✔
4183
               context->private_network ||
1,615✔
4184
               context->network_namespace_path ||
1,608✔
4185
               context->private_ipc ||
1,608✔
4186
               context->ipc_namespace_path ||
1,608✔
4187
               context->private_mounts > 0 ||
1,608✔
4188
               context->mount_apivfs > 0 ||
1,598✔
4189
               context->bind_log_sockets > 0 ||
1,598✔
4190
               context->n_bind_mounts > 0 ||
1,598✔
4191
               context->n_temporary_filesystems > 0 ||
1,593✔
4192
               context->root_directory ||
1,593✔
4193
               !strv_isempty(context->extension_directories) ||
1,593✔
4194
               context->protect_system != PROTECT_SYSTEM_NO ||
1,593✔
4195
               context->protect_home != PROTECT_HOME_NO ||
3,171✔
4196
               exec_needs_pid_namespace(context) ||
1,578✔
4197
               context->protect_kernel_tunables ||
1,556✔
4198
               context->protect_kernel_modules ||
1,551✔
4199
               context->protect_kernel_logs ||
3,092✔
4200
               exec_needs_cgroup_mount(context) ||
1,546✔
4201
               context->protect_clock ||
1,546✔
4202
               context->protect_hostname != PROTECT_HOSTNAME_NO ||
1,541✔
4203
               !strv_isempty(context->read_write_paths) ||
1,536✔
4204
               !strv_isempty(context->read_only_paths) ||
1,521✔
4205
               !strv_isempty(context->inaccessible_paths) ||
1,521✔
4206
               !strv_isempty(context->exec_paths) ||
1,521✔
4207
               !strv_isempty(context->no_exec_paths) ||
3,171✔
4208
               context->delegate_namespaces != NAMESPACE_FLAGS_INITIAL;
1,521✔
4209
}
4210

4211
static PrivateUsers exec_context_get_effective_private_users(
9,607✔
4212
                const ExecContext *context,
4213
                const ExecParameters *params) {
4214

4215
        assert(context);
9,607✔
4216
        assert(params);
9,607✔
4217

4218
        if (context->private_users != PRIVATE_USERS_NO)
9,607✔
4219
                return context->private_users;
4220

4221
        /* If any namespace is delegated with DelegateNamespaces=, always set up a user namespace. */
4222
        if (context->delegate_namespaces != NAMESPACE_FLAGS_INITIAL)
9,581✔
4223
                return PRIVATE_USERS_SELF;
3✔
4224

4225
        return PRIVATE_USERS_NO;
4226
}
4227

4228
static bool exec_namespace_is_delegated(
23,401✔
4229
                const ExecContext *context,
4230
                const ExecParameters *params,
4231
                bool have_cap_sys_admin,
4232
                unsigned long namespace) {
4233

4234
        assert(context);
23,401✔
4235
        assert(params);
23,401✔
4236
        assert(namespace != CLONE_NEWUSER);
23,401✔
4237

4238
        /* If we need unprivileged private users, we've already unshared a user namespace by the time we call
4239
         * setup_delegated_namespaces() for the first time so let's make sure we do all other namespace
4240
         * unsharing in the first call to setup_delegated_namespaces() by returning false here. */
4241
        if (!have_cap_sys_admin && exec_context_needs_cap_sys_admin(context))
23,401✔
4242
                return false;
4243

4244
        if (context->delegate_namespaces == NAMESPACE_FLAGS_INITIAL)
23,299✔
4245
                return params->runtime_scope == RUNTIME_SCOPE_USER;
23,231✔
4246

4247
        if (FLAGS_SET(context->delegate_namespaces, namespace))
68✔
4248
                return true;
4249

4250
        /* Various namespaces imply mountns for private procfs/sysfs/cgroupfs instances, which means when
4251
         * those are delegated mountns must be deferred too.
4252
         *
4253
         * The list should stay in sync with exec_needs_mount_namespace(). */
4254
        if (namespace == CLONE_NEWNS)
16✔
4255
                return context->delegate_namespaces & (CLONE_NEWPID|CLONE_NEWCGROUP|CLONE_NEWNET);
4✔
4256

4257
        return false;
4258
}
4259

4260
static int setup_delegated_namespaces(
19,225✔
4261
                const ExecContext *context,
4262
                ExecParameters *params,
4263
                ExecRuntime *runtime,
4264
                bool delegate,
4265
                const char *memory_pressure_path,
4266
                uid_t uid,
4267
                uid_t gid,
4268
                const ExecCommand *command,
4269
                bool needs_sandboxing,
4270
                bool have_cap_sys_admin,
4271
                int *reterr_exit_status) {
4272

4273
        int r;
19,225✔
4274

4275
        /* This function is called twice, once before unsharing the user namespace, and once after unsharing
4276
         * the user namespace. When called before unsharing the user namespace, "delegate" is set to "false".
4277
         * When called after unsharing the user namespace, "delegate" is set to "true". The net effect is
4278
         * that all namespaces that should not be delegated are unshared when this function is called the
4279
         * first time and all namespaces that should be delegated are unshared when this function is called
4280
         * the second time. */
4281

4282
        assert(context);
19,225✔
4283
        assert(params);
19,225✔
4284
        assert(runtime);
19,225✔
4285
        assert(reterr_exit_status);
19,225✔
4286

4287
        if (exec_needs_network_namespace(context) &&
19,344✔
4288
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWNET) == delegate &&
119✔
4289
            runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
60✔
4290

4291
                /* Try to enable network namespacing if network namespacing is available and we have
4292
                 * CAP_NET_ADMIN in the current user namespace (either the system manager one or the unit's
4293
                 * own user namespace). We need CAP_NET_ADMIN to be able to configure the loopback device in
4294
                 * the new network namespace. And if we don't have that, then we could only create a network
4295
                 * namespace without the ability to set up "lo". Hence gracefully skip things then. */
4296
                if (namespace_type_supported(NAMESPACE_NET) && have_effective_cap(CAP_NET_ADMIN) > 0) {
60✔
4297
                        r = setup_shareable_ns(runtime->shared->netns_storage_socket, CLONE_NEWNET);
60✔
4298
                        if (ERRNO_IS_NEG_PRIVILEGE(r))
60✔
4299
                                log_notice_errno(r, "PrivateNetwork=yes is configured, but network namespace setup not permitted, proceeding without: %m");
×
4300
                        else if (r < 0) {
60✔
4301
                                *reterr_exit_status = EXIT_NETWORK;
×
4302
                                return log_error_errno(r, "Failed to set up network namespacing: %m");
×
4303
                        } else
4304
                                log_debug("Set up %snetwork namespace", delegate ? "delegated " : "");
115✔
4305
                } else if (context->network_namespace_path) {
×
4306
                        *reterr_exit_status = EXIT_NETWORK;
×
4307
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "NetworkNamespacePath= is not supported, refusing.");
×
4308
                } else
4309
                        log_notice("PrivateNetwork=yes is configured, but the kernel does not support or we lack privileges for network namespace, proceeding without.");
×
4310
        }
4311

4312
        if (exec_needs_ipc_namespace(context) &&
19,236✔
4313
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWIPC) == delegate &&
11✔
4314
            runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
6✔
4315

4316
                if (namespace_type_supported(NAMESPACE_IPC)) {
6✔
4317
                        r = setup_shareable_ns(runtime->shared->ipcns_storage_socket, CLONE_NEWIPC);
6✔
4318
                        if (ERRNO_IS_NEG_PRIVILEGE(r))
6✔
4319
                                log_warning_errno(r, "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m");
×
4320
                        else if (r < 0) {
6✔
4321
                                *reterr_exit_status = EXIT_NAMESPACE;
×
4322
                                return log_error_errno(r, "Failed to set up IPC namespacing: %m");
×
4323
                        } else
4324
                                log_debug("Set up %sIPC namespace", delegate ? "delegated " : "");
8✔
4325
                } else if (context->ipc_namespace_path) {
×
4326
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4327
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "IPCNamespacePath= is not supported, refusing.");
×
4328
                } else
4329
                        log_warning("PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring.");
×
4330
        }
4331

4332
        if (needs_sandboxing && exec_needs_cgroup_namespace(context) &&
19,250✔
4333
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWCGROUP) == delegate) {
25✔
4334
                if (unshare(CLONE_NEWCGROUP) < 0) {
13✔
4335
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4336
                        return log_error_errno(errno, "Failed to set up cgroup namespacing: %m");
×
4337
                }
4338

4339
                log_debug("Set up %scgroup namespace", delegate ? "delegated " : "");
22✔
4340
        }
4341

4342
        /* Unshare a new PID namespace before setting up mounts to ensure /proc/ is mounted with only processes in PID namespace visible.
4343
         * Note PrivatePIDs=yes implies MountAPIVFS=yes so we'll always ensure procfs is remounted. */
4344
        if (needs_sandboxing && exec_needs_pid_namespace(context) &&
19,250✔
4345
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWPID) == delegate) {
25✔
4346
                if (params->pidref_transport_fd < 0) {
15✔
4347
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4348
                        return log_error_errno(SYNTHETIC_ERRNO(ENOTCONN), "PidRef socket is not set up: %m");
×
4349
                }
4350

4351
                /* If we had CAP_SYS_ADMIN prior to joining the user namespace, then we are privileged and don't need
4352
                 * to check if we can mount /proc/.
4353
                 *
4354
                 * We need to check prior to entering the user namespace because if we're running unprivileged or in a
4355
                 * system without CAP_SYS_ADMIN, then we can have CAP_SYS_ADMIN in the current user namespace but not
4356
                 * once we unshare a mount namespace. */
4357
                if (!have_cap_sys_admin || delegate) {
15✔
4358
                        r = can_mount_proc();
10✔
4359
                        if (r < 0) {
5✔
4360
                                *reterr_exit_status = EXIT_NAMESPACE;
×
4361
                                return log_error_errno(r, "Failed to detect if /proc/ can be remounted: %m");
×
4362
                        }
4363
                        if (r == 0) {
5✔
4364
                                *reterr_exit_status = EXIT_NAMESPACE;
1✔
4365
                                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
1✔
4366
                                                       "PrivatePIDs=yes is configured, but /proc/ cannot be re-mounted due to lack of privileges, refusing.");
4367
                        }
4368
                }
4369

4370
                r = setup_private_pids(context, params);
9✔
4371
                if (r < 0) {
6✔
4372
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4373
                        return log_error_errno(r, "Failed to set up pid namespace: %m");
×
4374
                }
4375

4376
                log_debug("Set up %spid namespace", delegate ? "delegated " : "");
12✔
4377
        }
4378

4379
        /* If PrivatePIDs= yes is configured, we're now running as pid 1 in a pid namespace! */
4380

4381
        if (exec_needs_mount_namespace(context, params, runtime) &&
23,236✔
4382
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWNS) == delegate) {
4,020✔
4383
                _cleanup_free_ char *error_path = NULL;
2,016✔
4384

4385
                r = apply_mount_namespace(command->flags,
2,016✔
4386
                                          context,
4387
                                          params,
4388
                                          runtime,
4389
                                          memory_pressure_path,
4390
                                          needs_sandboxing,
4391
                                          &error_path,
4392
                                          uid,
4393
                                          gid);
4394
                if (r < 0) {
2,016✔
4395
                        *reterr_exit_status = EXIT_NAMESPACE;
15✔
4396
                        return log_error_errno(r, "Failed to set up mount namespacing%s%s: %m",
29✔
4397
                                               error_path ? ": " : "", strempty(error_path));
4398
                }
4399

4400
                log_debug("Set up %smount namespace", delegate ? "delegated " : "");
3,974✔
4401
        }
4402

4403
        if (needs_sandboxing &&
38,402✔
4404
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWUTS) == delegate) {
19,201✔
4405
                r = apply_protect_hostname(context, params, reterr_exit_status);
9,599✔
4406
                if (r < 0)
9,599✔
4407
                        return r;
4408
                if (r > 0)
9,599✔
4409
                        log_debug("Set up %sUTS namespace", delegate ? "delegated " : "");
1,325✔
4410
        }
4411

4412
        return 0;
4413
}
4414

4415
static bool exec_context_shall_confirm_spawn(const ExecContext *context) {
×
4416
        assert(context);
×
4417

4418
        if (confirm_spawn_disabled())
×
4419
                return false;
4420

4421
        /* For some reasons units remaining in the same process group
4422
         * as PID 1 fail to acquire the console even if it's not used
4423
         * by any process. So skip the confirmation question for them. */
4424
        return !context->same_pgrp;
×
4425
}
4426

4427
static int exec_context_named_iofds(
11,582✔
4428
                const ExecContext *c,
4429
                const ExecParameters *p,
4430
                int named_iofds[static 3]) {
4431

4432
        size_t targets;
11,582✔
4433
        const char* stdio_fdname[3];
11,582✔
4434
        size_t n_fds;
11,582✔
4435

4436
        assert(c);
11,582✔
4437
        assert(p);
11,582✔
4438
        assert(named_iofds);
11,582✔
4439

4440
        targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
11,582✔
4441
                  (c->std_output == EXEC_OUTPUT_NAMED_FD) +
11,582✔
4442
                  (c->std_error == EXEC_OUTPUT_NAMED_FD);
11,582✔
4443

4444
        for (size_t i = 0; i < 3; i++)
46,328✔
4445
                stdio_fdname[i] = exec_context_fdname(c, i);
34,746✔
4446

4447
        n_fds = p->n_storage_fds + p->n_socket_fds + p->n_extra_fds;
11,582✔
4448

4449
        for (size_t i = 0; i < n_fds  && targets > 0; i++)
11,582✔
4450
                if (named_iofds[STDIN_FILENO] < 0 &&
×
4451
                    c->std_input == EXEC_INPUT_NAMED_FD &&
×
4452
                    stdio_fdname[STDIN_FILENO] &&
×
4453
                    streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
×
4454

4455
                        named_iofds[STDIN_FILENO] = p->fds[i];
×
4456
                        targets--;
×
4457

4458
                } else if (named_iofds[STDOUT_FILENO] < 0 &&
×
4459
                           c->std_output == EXEC_OUTPUT_NAMED_FD &&
×
4460
                           stdio_fdname[STDOUT_FILENO] &&
×
4461
                           streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
×
4462

4463
                        named_iofds[STDOUT_FILENO] = p->fds[i];
×
4464
                        targets--;
×
4465

4466
                } else if (named_iofds[STDERR_FILENO] < 0 &&
×
4467
                           c->std_error == EXEC_OUTPUT_NAMED_FD &&
×
4468
                           stdio_fdname[STDERR_FILENO] &&
×
4469
                           streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
×
4470

4471
                        named_iofds[STDERR_FILENO] = p->fds[i];
×
4472
                        targets--;
×
4473
                }
4474

4475
        return targets == 0 ? 0 : -ENOENT;
11,582✔
4476
}
4477

4478
static void exec_shared_runtime_close(ExecSharedRuntime *shared) {
9,597✔
4479
        if (!shared)
9,597✔
4480
                return;
4481

4482
        safe_close_pair(shared->netns_storage_socket);
9,597✔
4483
        safe_close_pair(shared->ipcns_storage_socket);
9,597✔
4484
}
4485

4486
static void exec_runtime_close(ExecRuntime *rt) {
9,597✔
4487
        if (!rt)
9,597✔
4488
                return;
4489

4490
        safe_close_pair(rt->ephemeral_storage_socket);
9,597✔
4491

4492
        exec_shared_runtime_close(rt->shared);
9,597✔
4493
        dynamic_creds_close(rt->dynamic_creds);
9,597✔
4494
}
4495

4496
static void exec_params_close(ExecParameters *p) {
9,597✔
4497
        if (!p)
9,597✔
4498
                return;
4499

4500
        p->stdin_fd = safe_close(p->stdin_fd);
9,597✔
4501
        p->stdout_fd = safe_close(p->stdout_fd);
9,597✔
4502
        p->stderr_fd = safe_close(p->stderr_fd);
9,597✔
4503
}
4504

4505
static int exec_fd_mark_hot(
9,599✔
4506
                const ExecContext *c,
4507
                ExecParameters *p,
4508
                bool hot,
4509
                int *reterr_exit_status) {
4510

4511
        assert(c);
9,599✔
4512
        assert(p);
9,599✔
4513

4514
        if (p->exec_fd < 0)
9,599✔
4515
                return 0;
9,599✔
4516

4517
        uint8_t x = hot;
286✔
4518

4519
        if (write(p->exec_fd, &x, sizeof(x)) < 0) {
286✔
4520
                if (reterr_exit_status)
×
4521
                        *reterr_exit_status = EXIT_EXEC;
×
4522
                return log_error_errno(errno, "Failed to mark exec_fd as %s: %m", hot ? "hot" : "cold");
×
4523
        }
4524

4525
        return 1;
4526
}
4527

4528
static int send_handoff_timestamp(
9,596✔
4529
                const ExecContext *c,
4530
                ExecParameters *p,
4531
                int *reterr_exit_status) {
4532

4533
        assert(c);
9,596✔
4534
        assert(p);
9,596✔
4535

4536
        if (p->handoff_timestamp_fd < 0)
9,596✔
4537
                return 0;
9,596✔
4538

4539
        dual_timestamp dt;
9,596✔
4540
        dual_timestamp_now(&dt);
9,596✔
4541

4542
        if (write(p->handoff_timestamp_fd, (const usec_t[2]) { dt.realtime, dt.monotonic }, sizeof(usec_t) * 2) < 0) {
9,596✔
4543
                if (reterr_exit_status)
×
4544
                        *reterr_exit_status = EXIT_EXEC;
×
4545
                return log_error_errno(errno, "Failed to send handoff timestamp: %m");
×
4546
        }
4547

4548
        return 1;
9,596✔
4549
}
4550

4551
static void prepare_terminal(
11,579✔
4552
                const ExecContext *context,
4553
                ExecParameters *p) {
4554

4555
        _cleanup_close_ int lock_fd = -EBADF;
11,579✔
4556

4557
        /* This is the "constructive" reset, i.e. is about preparing things for our invocation rather than
4558
         * cleaning up things from older invocations. */
4559

4560
        assert(context);
11,579✔
4561
        assert(p);
11,579✔
4562

4563
        /* We only try to reset things if we there's the chance our stdout points to a TTY */
4564
        if (!(is_terminal_output(context->std_output) ||
11,579✔
4565
              (context->std_output == EXEC_OUTPUT_INHERIT && is_terminal_input(context->std_input)) ||
10,962✔
4566
              context->std_output == EXEC_OUTPUT_NAMED_FD ||
4567
              p->stdout_fd >= 0))
10,962✔
4568
                return;
10,418✔
4569

4570
        /* Let's explicitly determine whether to reset via ANSI sequences or not, taking our ExecContext
4571
         * information into account */
4572
        bool use_ansi = exec_context_shall_ansi_seq_reset(context);
1,161✔
4573

4574
        if (context->tty_reset) {
1,161✔
4575
                /* When we are resetting the TTY, then let's create a lock first, to synchronize access. This
4576
                 * in particular matters as concurrent resets and the TTY size ANSI DSR logic done by the
4577
                 * exec_context_apply_tty_size() below might interfere */
4578
                lock_fd = lock_dev_console();
163✔
4579
                if (lock_fd < 0)
163✔
4580
                        log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
×
4581

4582
                /* We explicitly control whether to send ansi sequences or not here, since we want to consult
4583
                 * the env vars explicitly configured in the ExecContext, rather than our own environment
4584
                 * block. */
4585
                (void) terminal_reset_defensive(STDOUT_FILENO, use_ansi ? TERMINAL_RESET_FORCE_ANSI_SEQ : TERMINAL_RESET_AVOID_ANSI_SEQ);
166✔
4586
        }
4587

4588
        (void) exec_context_apply_tty_size(context, STDIN_FILENO, STDOUT_FILENO, /* tty_path= */ NULL);
1,161✔
4589

4590
        if (use_ansi)
1,161✔
4591
                (void) osc_context_open_service(p->unit_id, p->invocation_id, /* ret_seq= */ NULL);
160✔
4592
}
4593

4594
int exec_invoke(
11,582✔
4595
                const ExecCommand *command,
4596
                const ExecContext *context,
4597
                ExecParameters *params,
4598
                ExecRuntime *runtime,
4599
                const CGroupContext *cgroup_context,
4600
                int *exit_status) {
11,582✔
4601

4602
        _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **joined_exec_search_path = NULL, **accum_env = NULL;
28✔
4603
        int r;
11,582✔
4604
        const char *username = NULL, *groupname = NULL;
11,582✔
4605
        _cleanup_free_ char *home_buffer = NULL, *memory_pressure_path = NULL, *own_user = NULL;
×
4606
        const char *pwent_home = NULL, *shell = NULL;
11,582✔
4607
        dev_t journal_stream_dev = 0;
11,582✔
4608
        ino_t journal_stream_ino = 0;
11,582✔
4609
        bool needs_sandboxing,          /* Do we need to set up full sandboxing? (i.e. all namespacing, all MAC stuff, caps, yadda yadda */
11,582✔
4610
                needs_setuid,           /* Do we need to do the actual setresuid()/setresgid() calls? */
4611
                needs_mount_namespace,  /* Do we need to set up a mount namespace for this kernel? */
4612
                have_cap_sys_admin,
4613
                userns_set_up = false,
11,582✔
4614
                keep_seccomp_privileges = false;
11,582✔
4615
#if HAVE_SELINUX
4616
        _cleanup_free_ char *mac_selinux_context_net = NULL;
4617
        bool use_selinux = false;
4618
#endif
4619
#if ENABLE_SMACK
4620
        bool use_smack = false;
11,582✔
4621
#endif
4622
#if HAVE_APPARMOR
4623
        bool use_apparmor = false;
4624
#endif
4625
#if HAVE_SECCOMP
4626
        uint64_t saved_bset = 0;
11,582✔
4627
#endif
4628
        uid_t saved_uid = getuid();
11,582✔
4629
        gid_t saved_gid = getgid();
11,582✔
4630
        uid_t uid = UID_INVALID;
11,582✔
4631
        gid_t gid = GID_INVALID;
11,582✔
4632
        size_t n_fds, /* fds to pass to the child */
11,582✔
4633
               n_keep_fds; /* total number of fds not to close */
4634
        int secure_bits;
11,582✔
4635
        _cleanup_free_ gid_t *gids = NULL, *gids_after_pam = NULL;
28✔
4636
        int ngids = 0, ngids_after_pam = 0;
11,582✔
4637
        int socket_fd = -EBADF, named_iofds[3] = EBADF_TRIPLET;
11,582✔
4638
        size_t n_storage_fds, n_socket_fds, n_extra_fds;
11,582✔
4639

4640
        assert(command);
11,582✔
4641
        assert(context);
11,582✔
4642
        assert(params);
11,582✔
4643
        assert(runtime);
11,582✔
4644
        assert(cgroup_context);
11,582✔
4645
        assert(exit_status);
11,582✔
4646

4647
        LOG_CONTEXT_PUSH_EXEC(context, params);
33,162✔
4648

4649
        /* Explicitly test for CVE-2021-4034 inspired invocations */
4650
        if (!command->path || strv_isempty(command->argv)) {
11,582✔
4651
                *exit_status = EXIT_EXEC;
×
4652
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid command line arguments.");
×
4653
        }
4654

4655
        if (context->std_input == EXEC_INPUT_SOCKET ||
11,582✔
4656
            context->std_output == EXEC_OUTPUT_SOCKET ||
11,571✔
4657
            context->std_error == EXEC_OUTPUT_SOCKET) {
11,565✔
4658

4659
                if (params->n_socket_fds > 1)
17✔
4660
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Got more than one socket.");
×
4661

4662
                if (params->n_socket_fds == 0)
17✔
4663
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Got no socket.");
×
4664

4665
                socket_fd = params->fds[0];
17✔
4666
                n_storage_fds = n_socket_fds = n_extra_fds = 0;
17✔
4667
        } else {
4668
                n_socket_fds = params->n_socket_fds;
11,565✔
4669
                n_storage_fds = params->n_storage_fds;
11,565✔
4670
                n_extra_fds = params->n_extra_fds;
11,565✔
4671
        }
4672
        n_fds = n_socket_fds + n_storage_fds + n_extra_fds;
11,582✔
4673

4674
        r = exec_context_named_iofds(context, params, named_iofds);
11,582✔
4675
        if (r < 0)
11,582✔
4676
                return log_error_errno(r, "Failed to load a named file descriptor: %m");
×
4677

4678
        rename_process_from_path(command->path);
11,582✔
4679

4680
        /* We reset exactly these signals, since they are the only ones we set to SIG_IGN in the main
4681
         * daemon. All others we leave untouched because we set them to SIG_DFL or a valid handler initially,
4682
         * both of which will be demoted to SIG_DFL. */
4683
        (void) default_signals(SIGNALS_CRASH_HANDLER,
11,582✔
4684
                               SIGNALS_IGNORE);
4685

4686
        if (context->ignore_sigpipe)
11,582✔
4687
                (void) ignore_signals(SIGPIPE);
11,214✔
4688

4689
        r = reset_signal_mask();
11,582✔
4690
        if (r < 0) {
11,582✔
4691
                *exit_status = EXIT_SIGNAL_MASK;
×
4692
                return log_error_errno(r, "Failed to set process signal mask: %m");
×
4693
        }
4694

4695
        if (params->idle_pipe)
11,582✔
4696
                do_idle_pipe_dance(params->idle_pipe);
160✔
4697

4698
        /* Close fds we don't need very early to make sure we don't block init reexecution because it cannot bind its
4699
         * sockets. Among the fds we close are the logging fds, and we want to keep them closed, so that we don't have
4700
         * any fds open we don't really want open during the transition. In order to make logging work, we switch the
4701
         * log subsystem into open_when_needed mode, so that it reopens the logs on every single log call. */
4702

4703
        log_forget_fds();
11,582✔
4704
        log_set_open_when_needed(true);
11,582✔
4705
        log_settle_target();
11,582✔
4706

4707
        /* In case anything used libc syslog(), close this here, too */
4708
        closelog();
11,582✔
4709

4710
        r = collect_open_file_fds(params, &n_fds);
11,582✔
4711
        if (r < 0) {
11,582✔
4712
                *exit_status = EXIT_FDS;
1✔
4713
                return log_error_errno(r, "Failed to get OpenFile= file descriptors: %m");
1✔
4714
        }
4715

4716
        int keep_fds[n_fds + 4];
11,581✔
4717
        memcpy_safe(keep_fds, params->fds, n_fds * sizeof(int));
11,581✔
4718
        n_keep_fds = n_fds;
11,581✔
4719

4720
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->exec_fd);
11,581✔
4721
        if (r < 0) {
11,581✔
4722
                *exit_status = EXIT_FDS;
×
4723
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
4724
        }
4725

4726
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->handoff_timestamp_fd);
11,581✔
4727
        if (r < 0) {
11,581✔
4728
                *exit_status = EXIT_FDS;
×
4729
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
4730
        }
4731

4732
#if HAVE_LIBBPF
4733
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->bpf_restrict_fs_map_fd);
11,581✔
4734
        if (r < 0) {
11,581✔
4735
                *exit_status = EXIT_FDS;
×
4736
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
4737
        }
4738
#endif
4739

4740
        r = close_remaining_fds(params, runtime, socket_fd, keep_fds, n_keep_fds);
11,581✔
4741
        if (r < 0) {
11,581✔
4742
                *exit_status = EXIT_FDS;
×
4743
                return log_error_errno(r, "Failed to close unwanted file descriptors: %m");
×
4744
        }
4745

4746
        if (!context->same_pgrp &&
22,297✔
4747
            setsid() < 0) {
10,716✔
4748
                *exit_status = EXIT_SETSID;
×
4749
                return log_error_errno(errno, "Failed to create new process session: %m");
×
4750
        }
4751

4752
        /* Now, reset the TTY associated to this service "destructively" (i.e. possibly even hang up or
4753
         * disallocate the VT), to get rid of any prior uses of the device. Note that we do not keep any fd
4754
         * open here, hence some of the settings made here might vanish again, depending on the TTY driver
4755
         * used. A 2nd ("constructive") initialization after we opened the input/output fds we actually want
4756
         * will fix this. Note that we pass a NULL invocation ID here – as exec_context_tty_reset() expects
4757
         * the invocation ID associated with the OSC 3008 context ID to close. But we don't want to close any
4758
         * OSC 3008 context here, and opening a fresh OSC 3008 context happens a bit further down. */
4759
        exec_context_tty_reset(context, params, /* invocation_id= */ SD_ID128_NULL);
11,581✔
4760

4761
        if (params->shall_confirm_spawn && exec_context_shall_confirm_spawn(context)) {
11,581✔
4762
                _cleanup_free_ char *cmdline = NULL;
×
4763

4764
                cmdline = quote_command_line(command->argv, SHELL_ESCAPE_EMPTY);
×
4765
                if (!cmdline) {
×
4766
                        *exit_status = EXIT_MEMORY;
×
4767
                        return log_oom();
×
4768
                }
4769

4770
                r = ask_for_confirmation(context, params, cmdline);
×
4771
                if (r != CONFIRM_EXECUTE) {
×
4772
                        if (r == CONFIRM_PRETEND_SUCCESS) {
×
4773
                                *exit_status = EXIT_SUCCESS;
×
4774
                                return 0;
×
4775
                        }
4776

4777
                        *exit_status = EXIT_CONFIRM;
×
4778
                        return log_error_errno(SYNTHETIC_ERRNO(ECANCELED), "Execution cancelled by the user.");
×
4779
                }
4780
        }
4781

4782
        /* We are about to invoke NSS and PAM modules. Let's tell them what we are doing here, maybe they care. This is
4783
         * used by nss-resolve to disable itself when we are about to start systemd-resolved, to avoid deadlocks. Note
4784
         * that these env vars do not survive the execve(), which means they really only apply to the PAM and NSS
4785
         * invocations themselves. Also note that while we'll only invoke NSS modules involved in user management they
4786
         * might internally call into other NSS modules that are involved in hostname resolution, we never know. */
4787
        if (setenv("SYSTEMD_ACTIVATION_UNIT", params->unit_id, true) != 0 ||
23,162✔
4788
            setenv("SYSTEMD_ACTIVATION_SCOPE", runtime_scope_to_string(params->runtime_scope), true) != 0) {
11,581✔
4789
                *exit_status = EXIT_MEMORY;
×
4790
                return log_error_errno(errno, "Failed to update environment: %m");
×
4791
        }
4792

4793
        if (context->dynamic_user && runtime->dynamic_creds) {
11,643✔
4794
                _cleanup_strv_free_ char **suggested_paths = NULL;
62✔
4795

4796
                /* On top of that, make sure we bypass our own NSS module nss-systemd comprehensively for any NSS
4797
                 * checks, if DynamicUser=1 is used, as we shouldn't create a feedback loop with ourselves here. */
4798
                if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
62✔
4799
                        *exit_status = EXIT_USER;
×
4800
                        return log_error_errno(errno, "Failed to update environment: %m");
×
4801
                }
4802

4803
                r = compile_suggested_paths(context, params, &suggested_paths);
62✔
4804
                if (r < 0) {
62✔
4805
                        *exit_status = EXIT_MEMORY;
×
4806
                        return log_oom();
×
4807
                }
4808

4809
                r = dynamic_creds_realize(runtime->dynamic_creds, suggested_paths, &uid, &gid);
62✔
4810
                if (r < 0) {
62✔
4811
                        *exit_status = EXIT_USER;
×
4812
                        if (r == -EILSEQ)
×
4813
                                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
×
4814
                                                       "Failed to update dynamic user credentials: User or group with specified name already exists.");
4815
                        return log_error_errno(r, "Failed to update dynamic user credentials: %m");
×
4816
                }
4817

4818
                if (!uid_is_valid(uid)) {
62✔
4819
                        *exit_status = EXIT_USER;
×
4820
                        return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "UID validation failed for \""UID_FMT"\".", uid);
×
4821
                }
4822

4823
                if (!gid_is_valid(gid)) {
62✔
4824
                        *exit_status = EXIT_USER;
×
4825
                        return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "GID validation failed for \""GID_FMT"\".", gid);
×
4826
                }
4827

4828
                if (runtime->dynamic_creds->user)
62✔
4829
                        username = runtime->dynamic_creds->user->name;
62✔
4830

4831
        } else {
4832
                const char *u;
11,519✔
4833

4834
                if (context->user)
11,519✔
4835
                        u = context->user;
4836
                else if (context->pam_name || FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL)) {
8,969✔
4837
                        /* If PAM is enabled but no user name is explicitly selected, then use our own one. */
4838
                        own_user = getusername_malloc();
65✔
4839
                        if (!own_user) {
65✔
4840
                                *exit_status = EXIT_USER;
×
4841
                                return log_error_errno(r, "Failed to determine my own user ID: %m");
×
4842
                        }
4843
                        u = own_user;
4844
                } else
4845
                        u = NULL;
4846

4847
                if (u) {
4848
                        /* We can't use nss unconditionally for root without risking deadlocks if some IPC services
4849
                         * will be started by pid1 and are ordered after us. But if SetLoginEnvironment= is
4850
                         * enabled *explicitly* (i.e. no exec_context_get_set_login_environment() here),
4851
                         * or PAM shall be invoked, let's consult NSS even for root, so that the user
4852
                         * gets accurate $SHELL in session(-like) contexts. */
4853
                        r = get_fixed_user(u,
2,615✔
4854
                                           /* prefer_nss = */ context->set_login_environment > 0 || context->pam_name,
2,615✔
4855
                                           &username, &uid, &gid, &pwent_home, &shell);
4856
                        if (r < 0) {
2,615✔
4857
                                *exit_status = EXIT_USER;
2✔
4858
                                return log_error_errno(r, "Failed to determine user credentials: %m");
2✔
4859
                        }
4860
                }
4861

4862
                if (context->group) {
11,517✔
4863
                        r = get_fixed_group(context->group, &groupname, &gid);
11✔
4864
                        if (r < 0) {
11✔
4865
                                *exit_status = EXIT_GROUP;
×
4866
                                return log_error_errno(r, "Failed to determine group credentials: %m");
×
4867
                        }
4868
                }
4869
        }
4870

4871
        /* Initialize user supplementary groups and get SupplementaryGroups= ones */
4872
        ngids = get_supplementary_groups(context, username, gid, &gids);
11,579✔
4873
        if (ngids < 0) {
11,579✔
4874
                *exit_status = EXIT_GROUP;
×
4875
                return log_error_errno(ngids, "Failed to determine supplementary groups: %m");
×
4876
        }
4877

4878
        r = send_user_lookup(params->unit_id, params->user_lookup_fd, uid, gid);
11,579✔
4879
        if (r < 0) {
11,579✔
4880
                *exit_status = EXIT_USER;
×
4881
                return log_error_errno(r, "Failed to send user credentials to PID1: %m");
×
4882
        }
4883

4884
        params->user_lookup_fd = safe_close(params->user_lookup_fd);
11,579✔
4885

4886
        r = acquire_home(context, &pwent_home, &home_buffer);
11,579✔
4887
        if (r < 0) {
11,579✔
4888
                *exit_status = EXIT_CHDIR;
×
4889
                return log_error_errno(r, "Failed to determine $HOME for the invoking user: %m");
×
4890
        }
4891

4892
        /* If a socket is connected to STDIN/STDOUT/STDERR, we must drop O_NONBLOCK */
4893
        if (socket_fd >= 0)
11,579✔
4894
                (void) fd_nonblock(socket_fd, false);
17✔
4895

4896
        /* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields.
4897
         * Hence we need to migrate to the target cgroup from init.scope before connecting to journald */
4898
        if (params->cgroup_path) {
11,579✔
4899
                _cleanup_free_ char *p = NULL;
11,579✔
4900

4901
                r = exec_params_get_cgroup_path(params, cgroup_context, &p);
11,579✔
4902
                if (r < 0) {
11,579✔
4903
                        *exit_status = EXIT_CGROUP;
×
4904
                        return log_error_errno(r, "Failed to acquire cgroup path: %m");
×
4905
                }
4906

4907
                r = cg_attach(p, 0);
11,579✔
4908
                if (r == -EUCLEAN) {
11,579✔
4909
                        *exit_status = EXIT_CGROUP;
×
4910
                        return log_error_errno(r,
×
4911
                                               "Failed to attach process to cgroup '%s', "
4912
                                               "because the cgroup or one of its parents or "
4913
                                               "siblings is in the threaded mode.", p);
4914
                }
4915
                if (r < 0) {
11,579✔
4916
                        *exit_status = EXIT_CGROUP;
×
4917
                        return log_error_errno(r, "Failed to attach to cgroup %s: %m", p);
×
4918
                }
4919
        }
4920

4921
        if (context->network_namespace_path && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
11,579✔
4922
                r = open_shareable_ns_path(runtime->shared->netns_storage_socket, context->network_namespace_path, CLONE_NEWNET);
×
4923
                if (r < 0) {
×
4924
                        *exit_status = EXIT_NETWORK;
×
4925
                        return log_error_errno(r, "Failed to open network namespace path %s: %m", context->network_namespace_path);
×
4926
                }
4927
        }
4928

4929
        if (context->ipc_namespace_path && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
11,579✔
4930
                r = open_shareable_ns_path(runtime->shared->ipcns_storage_socket, context->ipc_namespace_path, CLONE_NEWIPC);
×
4931
                if (r < 0) {
×
4932
                        *exit_status = EXIT_NAMESPACE;
×
4933
                        return log_error_errno(r, "Failed to open IPC namespace path %s: %m", context->ipc_namespace_path);
×
4934
                }
4935
        }
4936

4937
        r = setup_input(context, params, socket_fd, named_iofds);
11,579✔
4938
        if (r < 0) {
11,579✔
4939
                *exit_status = EXIT_STDIN;
×
4940
                return log_error_errno(r, "Failed to set up standard input: %m");
×
4941
        }
4942

4943
        _cleanup_free_ char *fname = NULL;
25✔
4944
        r = path_extract_filename(command->path, &fname);
11,579✔
4945
        if (r < 0) {
11,579✔
4946
                *exit_status = EXIT_STDOUT;
×
4947
                return log_error_errno(r, "Failed to extract filename from path %s: %m", command->path);
×
4948
        }
4949

4950
        r = setup_output(context, params, STDOUT_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
11,579✔
4951
        if (r < 0) {
11,579✔
4952
                *exit_status = EXIT_STDOUT;
×
4953
                return log_error_errno(r, "Failed to set up standard output: %m");
×
4954
        }
4955

4956
        r = setup_output(context, params, STDERR_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
11,579✔
4957
        if (r < 0) {
11,579✔
4958
                *exit_status = EXIT_STDERR;
×
4959
                return log_error_errno(r, "Failed to set up standard error output: %m");
×
4960
        }
4961

4962
        /* Now that stdin/stdout are definiely opened, properly initialize it with our desired
4963
         * settings. Note: this is a "constructive" reset, it prepares things for us to use. This is
4964
         * different from the "destructive" TTY reset further up. Also note: we apply this on stdin/stdout in
4965
         * case this is a tty, regardless if we opened it ourselves or got it passed in pre-opened. */
4966
        prepare_terminal(context, params);
11,579✔
4967

4968
        if (context->oom_score_adjust_set) {
11,579✔
4969
                /* When we can't make this change due to EPERM, then let's silently skip over it. User
4970
                 * namespaces prohibit write access to this file, and we shouldn't trip up over that. */
4971
                r = set_oom_score_adjust(context->oom_score_adjust);
1,309✔
4972
                if (ERRNO_IS_NEG_PRIVILEGE(r))
1,309✔
4973
                        log_debug_errno(r, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
×
4974
                else if (r < 0) {
1,309✔
4975
                        *exit_status = EXIT_OOM_ADJUST;
×
4976
                        return log_error_errno(r, "Failed to adjust OOM setting: %m");
×
4977
                }
4978
        }
4979

4980
        if (context->coredump_filter_set) {
11,579✔
4981
                r = set_coredump_filter(context->coredump_filter);
2✔
4982
                if (ERRNO_IS_NEG_PRIVILEGE(r))
2✔
4983
                        log_debug_errno(r, "Failed to adjust coredump_filter, ignoring: %m");
×
4984
                else if (r < 0) {
2✔
4985
                        *exit_status = EXIT_LIMITS;
×
4986
                        return log_error_errno(r, "Failed to adjust coredump_filter: %m");
×
4987
                }
4988
        }
4989

4990
        if (context->cpu_sched_set) {
11,579✔
4991
                struct sched_attr attr = {
×
4992
                        .size = sizeof(attr),
4993
                        .sched_policy = context->cpu_sched_policy,
×
4994
                        .sched_priority = context->cpu_sched_priority,
×
4995
                        .sched_flags = context->cpu_sched_reset_on_fork ? SCHED_FLAG_RESET_ON_FORK : 0,
×
4996
                };
4997

4998
                r = sched_setattr(/* pid= */ 0, &attr, /* flags= */ 0);
×
4999
                if (r < 0) {
×
5000
                        *exit_status = EXIT_SETSCHEDULER;
×
5001
                        return log_error_errno(errno, "Failed to set up CPU scheduling: %m");
×
5002
                }
5003
        }
5004

5005
        /*
5006
         * Set nice value _after_ the call to sched_setattr() because struct sched_attr includes sched_nice
5007
         * which we do not set, thus it will clobber any previously set nice value. Scheduling policy might
5008
         * be reasonably set together with nice value e.g. in case of SCHED_BATCH (see sched(7)).
5009
         * It would be ideal to set both with the same call, but we cannot easily do so because of all the
5010
         * extra logic in setpriority_closest().
5011
         */
5012
        if (context->nice_set) {
11,579✔
5013
                r = setpriority_closest(context->nice);
15✔
5014
                if (r < 0) {
15✔
5015
                        *exit_status = EXIT_NICE;
×
5016
                        return log_error_errno(r, "Failed to set up process scheduling priority (nice level): %m");
×
5017
                }
5018
        }
5019

5020
        if (context->cpu_affinity_from_numa || context->cpu_set.set) {
11,579✔
5021
                _cleanup_(cpu_set_reset) CPUSet converted_cpu_set = {};
2✔
5022
                const CPUSet *cpu_set;
2✔
5023

5024
                if (context->cpu_affinity_from_numa) {
2✔
5025
                        r = exec_context_cpu_affinity_from_numa(context, &converted_cpu_set);
2✔
5026
                        if (r < 0) {
2✔
5027
                                *exit_status = EXIT_CPUAFFINITY;
×
5028
                                return log_error_errno(r, "Failed to derive CPU affinity mask from NUMA mask: %m");
×
5029
                        }
5030

5031
                        cpu_set = &converted_cpu_set;
5032
                } else
5033
                        cpu_set = &context->cpu_set;
×
5034

5035
                if (sched_setaffinity(0, cpu_set->allocated, cpu_set->set) < 0) {
2✔
5036
                        *exit_status = EXIT_CPUAFFINITY;
×
5037
                        return log_error_errno(errno, "Failed to set up CPU affinity: %m");
×
5038
                }
5039
        }
5040

5041
        if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) {
11,579✔
5042
                r = apply_numa_policy(&context->numa_policy);
19✔
5043
                if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
19✔
5044
                        log_debug_errno(r, "NUMA support not available, ignoring.");
×
5045
                else if (r < 0) {
19✔
5046
                        *exit_status = EXIT_NUMA_POLICY;
2✔
5047
                        return log_error_errno(r, "Failed to set NUMA memory policy: %m");
2✔
5048
                }
5049
        }
5050

5051
        if (context->ioprio_set)
11,577✔
5052
                if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
6✔
5053
                        *exit_status = EXIT_IOPRIO;
×
5054
                        return log_error_errno(errno, "Failed to set up IO scheduling priority: %m");
×
5055
                }
5056

5057
        if (context->timer_slack_nsec != NSEC_INFINITY)
11,577✔
5058
                if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
×
5059
                        *exit_status = EXIT_TIMERSLACK;
×
5060
                        return log_error_errno(errno, "Failed to set up timer slack: %m");
×
5061
                }
5062

5063
        if (context->personality != PERSONALITY_INVALID) {
11,577✔
5064
                r = safe_personality(context->personality);
×
5065
                if (r < 0) {
×
5066
                        *exit_status = EXIT_PERSONALITY;
×
5067
                        return log_error_errno(r, "Failed to set up execution domain (personality): %m");
×
5068
                }
5069
        }
5070

5071
        if (context->memory_ksm >= 0)
11,577✔
5072
                if (prctl(PR_SET_MEMORY_MERGE, context->memory_ksm, 0, 0, 0) < 0) {
×
5073
                        if (ERRNO_IS_NOT_SUPPORTED(errno))
×
5074
                                log_debug_errno(errno, "KSM support not available, ignoring.");
×
5075
                        else {
5076
                                *exit_status = EXIT_KSM;
×
5077
                                return log_error_errno(errno, "Failed to set KSM: %m");
×
5078
                        }
5079
                }
5080

5081
#if ENABLE_UTMP
5082
        if (context->utmp_id) {
11,577✔
5083
                _cleanup_free_ char *username_alloc = NULL;
165✔
5084

5085
                if (!username && context->utmp_mode == EXEC_UTMP_USER) {
165✔
5086
                        username_alloc = uid_to_name(uid_is_valid(uid) ? uid : saved_uid);
1✔
5087
                        if (!username_alloc) {
1✔
5088
                                *exit_status = EXIT_USER;
×
5089
                                return log_oom();
×
5090
                        }
5091
                }
5092

5093
                const char *line = context->tty_path ?
×
5094
                        (path_startswith(context->tty_path, "/dev/") ?: context->tty_path) :
165✔
5095
                        NULL;
5096
                utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
165✔
5097
                                      line,
5098
                                      context->utmp_mode == EXEC_UTMP_INIT  ? INIT_PROCESS :
165✔
5099
                                      context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
7✔
5100
                                      USER_PROCESS,
5101
                                      username ?: username_alloc);
165✔
5102
        }
5103
#endif
5104

5105
        if (uid_is_valid(uid)) {
11,577✔
5106
                r = chown_terminal(STDIN_FILENO, uid);
2,675✔
5107
                if (r < 0) {
2,675✔
5108
                        *exit_status = EXIT_STDIN;
×
5109
                        return log_error_errno(r, "Failed to change ownership of terminal: %m");
×
5110
                }
5111
        }
5112

5113
        /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted
5114
         * from it. */
5115
        needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
11,577✔
5116

5117
        if (params->cgroup_path) {
11,577✔
5118
                /* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1
5119
                 * this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not
5120
                 * safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only
5121
                 * touch a single hierarchy too. */
5122

5123
                if (params->flags & EXEC_CGROUP_DELEGATE) {
11,577✔
5124
                        _cleanup_free_ char *p = NULL;
671✔
5125

5126
                        r = cg_set_access(params->cgroup_path, uid, gid);
671✔
5127
                        if (r < 0) {
671✔
5128
                                *exit_status = EXIT_CGROUP;
×
5129
                                return log_error_errno(r, "Failed to adjust control group access: %m");
×
5130
                        }
5131

5132
                        r = exec_params_get_cgroup_path(params, cgroup_context, &p);
671✔
5133
                        if (r < 0) {
671✔
5134
                                *exit_status = EXIT_CGROUP;
×
5135
                                return log_error_errno(r, "Failed to acquire cgroup path: %m");
×
5136
                        }
5137
                        if (r > 0) {
671✔
5138
                                r = cg_set_access_recursive(p, uid, gid);
330✔
5139
                                if (r < 0) {
330✔
5140
                                        *exit_status = EXIT_CGROUP;
×
5141
                                        return log_error_errno(r, "Failed to adjust control subgroup access: %m");
×
5142
                                }
5143
                        }
5144
                }
5145

5146
                if (is_pressure_supported() > 0) {
11,577✔
5147
                        if (cgroup_context_want_memory_pressure(cgroup_context)) {
11,577✔
5148
                                r = cg_get_path("memory", params->cgroup_path, "memory.pressure", &memory_pressure_path);
11,176✔
5149
                                if (r < 0) {
11,176✔
5150
                                        *exit_status = EXIT_MEMORY;
×
5151
                                        return log_oom();
×
5152
                                }
5153

5154
                                r = chmod_and_chown(memory_pressure_path, 0644, uid, gid);
11,176✔
5155
                                if (r < 0) {
11,176✔
5156
                                        log_full_errno(r == -ENOENT || ERRNO_IS_PRIVILEGE(r) ? LOG_DEBUG : LOG_WARNING, r,
2✔
5157
                                                       "Failed to adjust ownership of '%s', ignoring: %m", memory_pressure_path);
5158
                                        memory_pressure_path = mfree(memory_pressure_path);
1✔
5159
                                }
5160
                                /* First we use the current cgroup path to chmod and chown the memory pressure path, then pass the path relative
5161
                                 * to the cgroup namespace to environment variables and mounts. If chown/chmod fails, we should not pass memory
5162
                                 * pressure path environment variable or read-write mount to the unit. This is why we check if
5163
                                 * memory_pressure_path != NULL in the conditional below. */
5164
                                if (memory_pressure_path && needs_sandboxing && exec_needs_cgroup_namespace(context)) {
11,176✔
5165
                                        memory_pressure_path = mfree(memory_pressure_path);
13✔
5166
                                        r = cg_get_path("memory", "", "memory.pressure", &memory_pressure_path);
13✔
5167
                                        if (r < 0) {
13✔
5168
                                                *exit_status = EXIT_MEMORY;
×
5169
                                                return log_oom();
×
5170
                                        }
5171
                                }
5172
                        } else if (cgroup_context->memory_pressure_watch == CGROUP_PRESSURE_WATCH_NO) {
401✔
5173
                                memory_pressure_path = strdup("/dev/null"); /* /dev/null is explicit indicator for turning of memory pressure watch */
×
5174
                                if (!memory_pressure_path) {
×
5175
                                        *exit_status = EXIT_MEMORY;
×
5176
                                        return log_oom();
×
5177
                                }
5178
                        }
5179
                }
5180
        }
5181

5182
        needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
11,577✔
5183

5184
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
69,457✔
5185
                r = setup_exec_directory(context, params, uid, gid, dt, needs_mount_namespace, exit_status);
57,881✔
5186
                if (r < 0)
57,881✔
5187
                        return log_error_errno(r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
1✔
5188
        }
5189

5190
        r = exec_setup_credentials(context, params, params->unit_id, uid, gid);
11,576✔
5191
        if (r < 0) {
9,623✔
5192
                *exit_status = EXIT_CREDENTIALS;
×
5193
                return log_error_errno(r, "Failed to set up credentials: %m");
×
5194
        }
5195

5196
        r = build_environment(
9,623✔
5197
                        context,
5198
                        params,
5199
                        cgroup_context,
5200
                        n_fds,
5201
                        pwent_home,
5202
                        username,
5203
                        shell,
5204
                        journal_stream_dev,
5205
                        journal_stream_ino,
5206
                        memory_pressure_path,
5207
                        needs_sandboxing,
5208
                        &our_env);
5209
        if (r < 0) {
9,623✔
5210
                *exit_status = EXIT_MEMORY;
×
5211
                return log_oom();
×
5212
        }
5213

5214
        r = build_pass_environment(context, &pass_env);
9,623✔
5215
        if (r < 0) {
9,623✔
5216
                *exit_status = EXIT_MEMORY;
×
5217
                return log_oom();
×
5218
        }
5219

5220
        /* The $PATH variable is set to the default path in params->environment. However, this is overridden
5221
         * if user-specified fields have $PATH set. The intention is to also override $PATH if the unit does
5222
         * not specify PATH but the unit has ExecSearchPath. */
5223
        if (!strv_isempty(context->exec_search_path)) {
9,623✔
5224
                _cleanup_free_ char *joined = NULL;
×
5225

5226
                joined = strv_join(context->exec_search_path, ":");
×
5227
                if (!joined) {
×
5228
                        *exit_status = EXIT_MEMORY;
×
5229
                        return log_oom();
×
5230
                }
5231

5232
                r = strv_env_assign(&joined_exec_search_path, "PATH", joined);
×
5233
                if (r < 0) {
×
5234
                        *exit_status = EXIT_MEMORY;
×
5235
                        return log_oom();
×
5236
                }
5237
        }
5238

5239
        accum_env = strv_env_merge(params->environment,
9,623✔
5240
                                   our_env,
5241
                                   joined_exec_search_path,
5242
                                   pass_env,
5243
                                   context->environment,
5244
                                   params->files_env);
5245
        if (!accum_env) {
9,623✔
5246
                *exit_status = EXIT_MEMORY;
×
5247
                return log_oom();
×
5248
        }
5249
        accum_env = strv_env_clean(accum_env);
9,623✔
5250

5251
        (void) umask(context->umask);
9,623✔
5252

5253
        r = setup_keyring(context, params, uid, gid);
9,623✔
5254
        if (r < 0) {
9,623✔
5255
                *exit_status = EXIT_KEYRING;
×
5256
                return log_error_errno(r, "Failed to set up kernel keyring: %m");
×
5257
        }
5258

5259
        /* We need setresuid() if the caller asked us to apply sandboxing and the command isn't explicitly
5260
         * excepted from either whole sandboxing or just setresuid() itself. */
5261
        needs_setuid = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & (EXEC_COMMAND_FULLY_PRIVILEGED|EXEC_COMMAND_NO_SETUID));
9,623✔
5262

5263
        uint64_t capability_ambient_set = context->capability_ambient_set;
9,623✔
5264

5265
        /* Check CAP_SYS_ADMIN before we enter user namespace to see if we can mount /proc even though its masked. */
5266
        have_cap_sys_admin = have_effective_cap(CAP_SYS_ADMIN) > 0;
9,623✔
5267

5268
        if (needs_sandboxing) {
9,623✔
5269
                /* MAC enablement checks need to be done before a new mount ns is created, as they rely on
5270
                 * /sys being present. The actual MAC context application will happen later, as late as
5271
                 * possible, to avoid impacting our own code paths. */
5272

5273
#if HAVE_SELINUX
5274
                use_selinux = mac_selinux_use();
5275
#endif
5276
#if ENABLE_SMACK
5277
                use_smack = mac_smack_use();
9,623✔
5278
#endif
5279
#if HAVE_APPARMOR
5280
                if (mac_apparmor_use()) {
5281
                        r = dlopen_libapparmor();
5282
                        if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r))
5283
                                log_warning_errno(r, "Failed to load libapparmor, ignoring: %m");
5284
                        use_apparmor = r >= 0;
5285
                }
5286
#endif
5287
        }
5288

5289
        if (needs_sandboxing) {
9,623✔
5290
                int which_failed;
9,623✔
5291

5292
                /* Let's set the resource limits before we call into PAM, so that pam_limits wins over what
5293
                 * is set here. (See below.) */
5294

5295
                r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed);
9,623✔
5296
                if (r < 0) {
9,623✔
5297
                        *exit_status = EXIT_LIMITS;
×
5298
                        return log_error_errno(r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
×
5299
                }
5300
        }
5301

5302
        if (needs_setuid && context->pam_name && username) {
9,623✔
5303
                /* Let's call into PAM after we set up our own idea of resource limits so that pam_limits
5304
                 * wins here. (See above.) */
5305

5306
                /* All fds passed in the fds array will be closed in the pam child process. */
5307
                r = setup_pam(context, params, username, uid, gid, &accum_env, params->fds, n_fds, params->exec_fd);
405✔
5308
                if (r < 0) {
405✔
5309
                        *exit_status = EXIT_PAM;
×
5310
                        return log_error_errno(r, "Failed to set up PAM session: %m");
×
5311
                }
5312

5313
                /* PAM modules might have set some ambient caps. Query them here and merge them into
5314
                 * the caps we want to set in the end, so that we don't end up unsetting them. */
5315
                uint64_t ambient_after_pam;
405✔
5316
                r = capability_get_ambient(&ambient_after_pam);
405✔
5317
                if (r < 0) {
405✔
5318
                        *exit_status = EXIT_CAPABILITIES;
×
5319
                        return log_error_errno(r, "Failed to query ambient caps: %m");
×
5320
                }
5321

5322
                capability_ambient_set |= ambient_after_pam;
405✔
5323

5324
                ngids_after_pam = getgroups_alloc(&gids_after_pam);
405✔
5325
                if (ngids_after_pam < 0) {
405✔
5326
                        *exit_status = EXIT_GROUP;
×
5327
                        return log_error_errno(ngids_after_pam, "Failed to obtain groups after setting up PAM: %m");
×
5328
                }
5329
        }
5330

5331
        if (needs_sandboxing && !have_cap_sys_admin && exec_context_needs_cap_sys_admin(context)) {
9,623✔
5332
                /* If we're unprivileged, set up the user namespace first to enable use of the other namespaces.
5333
                 * Users with CAP_SYS_ADMIN can set up user namespaces last because they will be able to
5334
                 * set up all of the other namespaces (i.e. network, mount, UTS) without a user namespace. */
5335
                PrivateUsers pu = exec_context_get_effective_private_users(context, params);
27✔
5336
                if (pu == PRIVATE_USERS_NO)
27✔
5337
                        pu = PRIVATE_USERS_SELF;
23✔
5338

5339
                /* The kernel requires /proc/pid/setgroups be set to "deny" prior to writing /proc/pid/gid_map in
5340
                 * unprivileged user namespaces. */
5341
                r = setup_private_users(pu, saved_uid, saved_gid, uid, gid, /* allow_setgroups= */ false);
27✔
5342
                /* If it was requested explicitly and we can't set it up, fail early. Otherwise, continue and let
5343
                 * the actual requested operations fail (or silently continue). */
5344
                if (r < 0 && context->private_users != PRIVATE_USERS_NO) {
27✔
5345
                        *exit_status = EXIT_USER;
×
5346
                        return log_error_errno(r, "Failed to set up user namespacing for unprivileged user: %m");
×
5347
                }
5348
                if (r < 0)
×
5349
                        log_info_errno(r, "Failed to set up user namespacing for unprivileged user, ignoring: %m");
×
5350
                else {
5351
                        assert(r > 0);
27✔
5352
                        userns_set_up = true;
27✔
5353
                        log_debug("Set up unprivileged user namespace");
27✔
5354
                }
5355
        }
5356

5357
        /* Call setup_delegated_namespaces() the first time to unshare all non-delegated namespaces. */
5358
        r = setup_delegated_namespaces(
9,623✔
5359
                        context,
5360
                        params,
5361
                        runtime,
5362
                        /* delegate= */ false,
5363
                        memory_pressure_path,
5364
                        uid,
5365
                        gid,
5366
                        command,
5367
                        needs_sandboxing,
5368
                        have_cap_sys_admin,
5369
                        exit_status);
5370
        if (r < 0)
9,619✔
5371
                return r;
5372

5373
        /* Drop groups as early as possible.
5374
         * This needs to be done after PrivateDevices=yes setup as device nodes should be owned by the host's root.
5375
         * For non-root in a userns, devices will be owned by the user/group before the group change, and nobody. */
5376
        if (needs_setuid) {
9,603✔
5377
                _cleanup_free_ gid_t *gids_to_enforce = NULL;
9,603✔
5378
                int ngids_to_enforce;
9,603✔
5379

5380
                ngids_to_enforce = merge_gid_lists(gids,
9,603✔
5381
                                                   ngids,
5382
                                                   gids_after_pam,
5383
                                                   ngids_after_pam,
5384
                                                   &gids_to_enforce);
5385
                if (ngids_to_enforce < 0) {
9,603✔
5386
                        *exit_status = EXIT_GROUP;
×
5387
                        return log_error_errno(ngids_to_enforce, "Failed to merge group lists. Group membership might be incorrect: %m");
×
5388
                }
5389

5390
                r = enforce_groups(gid, gids_to_enforce, ngids_to_enforce);
9,603✔
5391
                if (r < 0) {
9,603✔
5392
                        *exit_status = EXIT_GROUP;
1✔
5393
                        return log_error_errno(r, "Changing group credentials failed: %m");
1✔
5394
                }
5395
        }
5396

5397
        /* If the user namespace was not set up above, try to do it now.
5398
         * It's preferred to set up the user namespace later (after all other namespaces) so as not to be
5399
         * restricted by rules pertaining to combining user namespaces with other namespaces (e.g. in the
5400
         * case of mount namespaces being less privileged when the mount point list is copied from a
5401
         * different user namespace). */
5402

5403
        if (needs_sandboxing && !userns_set_up) {
9,602✔
5404
                PrivateUsers pu = exec_context_get_effective_private_users(context, params);
9,580✔
5405

5406
                r = setup_private_users(pu, saved_uid, saved_gid, uid, gid,
9,580✔
5407
                                        /* allow_setgroups= */ pu == PRIVATE_USERS_FULL);
5408
                if (r < 0) {
9,580✔
5409
                        *exit_status = EXIT_USER;
×
5410
                        return log_error_errno(r, "Failed to set up user namespacing: %m");
×
5411
                }
5412
                if (r > 0)
9,580✔
5413
                        log_debug("Set up privileged user namespace");
25✔
5414
        }
5415

5416
        /* Call setup_delegated_namespaces() the second time to unshare all delegated namespaces. */
5417
        r = setup_delegated_namespaces(
9,602✔
5418
                        context,
5419
                        params,
5420
                        runtime,
5421
                        /* delegate= */ true,
5422
                        memory_pressure_path,
5423
                        uid,
5424
                        gid,
5425
                        command,
5426
                        needs_sandboxing,
5427
                        have_cap_sys_admin,
5428
                        exit_status);
5429
        if (r < 0)
9,598✔
5430
                return r;
5431

5432
        /* Now that the mount namespace has been set up and privileges adjusted, let's look for the thing we
5433
         * shall execute. */
5434

5435
        const char *path = command->path;
9,598✔
5436

5437
        if (FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL)) {
9,598✔
5438
                if (shell_is_placeholder(shell)) {
13✔
5439
                        log_debug("Shell prefixing requested for user without default shell, using /bin/sh: %s",
2✔
5440
                                  strna(username));
5441
                        assert(streq(path, _PATH_BSHELL));
2✔
5442
                } else
5443
                        path = shell;
11✔
5444
        }
5445

5446
        _cleanup_free_ char *executable = NULL;
5✔
5447
        _cleanup_close_ int executable_fd = -EBADF;
5✔
5448
        r = find_executable_full(path, /* root= */ NULL, context->exec_search_path, false, &executable, &executable_fd);
9,598✔
5449
        if (r < 0) {
9,598✔
5450
                *exit_status = EXIT_EXEC;
1✔
5451
                log_struct_errno(LOG_NOTICE, r,
1✔
5452
                                 LOG_MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED_STR),
5453
                                 LOG_EXEC_MESSAGE(params, "Unable to locate executable '%s': %m", path),
5454
                                 LOG_ITEM("EXECUTABLE=%s", path));
5455
                /* If the error will be ignored by manager, tune down the log level here. Missing executable
5456
                 * is very much expected in this case. */
5457
                return r != -ENOMEM && FLAGS_SET(command->flags, EXEC_COMMAND_IGNORE_FAILURE) ? 1 : r;
1✔
5458
        }
5459

5460
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &executable_fd);
9,597✔
5461
        if (r < 0) {
9,597✔
5462
                *exit_status = EXIT_FDS;
×
5463
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
5464
        }
5465

5466
#if HAVE_SELINUX
5467
        if (needs_sandboxing && use_selinux && params->selinux_context_net) {
5468
                int fd = -EBADF;
5469

5470
                if (socket_fd >= 0)
5471
                        fd = socket_fd;
5472
                else if (params->n_socket_fds == 1)
5473
                        /* If stdin is not connected to a socket but we are triggered by exactly one socket unit then we
5474
                         * use context from that fd to compute the label. */
5475
                        fd = params->fds[0];
5476

5477
                if (fd >= 0) {
5478
                        r = mac_selinux_get_child_mls_label(fd, executable, context->selinux_context, &mac_selinux_context_net);
5479
                        if (r < 0) {
5480
                                if (!context->selinux_context_ignore) {
5481
                                        *exit_status = EXIT_SELINUX_CONTEXT;
5482
                                        return log_error_errno(r, "Failed to determine SELinux context: %m");
5483
                                }
5484
                                log_debug_errno(r, "Failed to determine SELinux context, ignoring: %m");
5485
                        }
5486
                }
5487
        }
5488
#endif
5489

5490
        /* We repeat the fd closing here, to make sure that nothing is leaked from the PAM modules. Note that
5491
         * we are more aggressive this time, since we don't need socket_fd and the netns and ipcns fds any
5492
         * more. We do keep exec_fd and handoff_timestamp_fd however, if we have it, since we need to keep
5493
         * them open until the final execve(). But first, close the remaining sockets in the context
5494
         * objects. */
5495

5496
        exec_runtime_close(runtime);
9,597✔
5497
        exec_params_close(params);
9,597✔
5498

5499
        r = close_all_fds(keep_fds, n_keep_fds);
9,597✔
5500
        if (r >= 0)
9,597✔
5501
                r = pack_fds(params->fds, n_fds);
9,597✔
5502
        if (r >= 0)
9,597✔
5503
                r = flag_fds(params->fds, n_socket_fds, n_fds, context->non_blocking);
9,597✔
5504
        if (r < 0) {
9,597✔
5505
                *exit_status = EXIT_FDS;
×
5506
                return log_error_errno(r, "Failed to adjust passed file descriptors: %m");
×
5507
        }
5508

5509
        /* At this point, the fds we want to pass to the program are all ready and set up, with O_CLOEXEC turned off
5510
         * and at the right fd numbers. The are no other fds open, with one exception: the exec_fd if it is defined,
5511
         * and it has O_CLOEXEC set, after all we want it to be closed by the execve(), so that our parent knows we
5512
         * came this far. */
5513

5514
        secure_bits = context->secure_bits;
9,597✔
5515

5516
        if (needs_sandboxing) {
9,597✔
5517
                uint64_t bset;
9,597✔
5518

5519
                /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested.
5520
                 * (Note this is placed after the general resource limit initialization, see above, in order
5521
                 * to take precedence.) */
5522
                if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
9,597✔
5523
                        if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
1,492✔
5524
                                *exit_status = EXIT_LIMITS;
×
5525
                                return log_error_errno(errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m");
×
5526
                        }
5527
                }
5528

5529
#if ENABLE_SMACK
5530
                /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the
5531
                 * process. This is the latest place before dropping capabilities. Other MAC context are set later. */
5532
                if (use_smack) {
9,597✔
5533
                        r = setup_smack(context, params, executable_fd);
×
5534
                        if (r < 0 && !context->smack_process_label_ignore) {
×
5535
                                *exit_status = EXIT_SMACK_PROCESS_LABEL;
×
5536
                                return log_error_errno(r, "Failed to set SMACK process label: %m");
×
5537
                        }
5538
                }
5539
#endif
5540

5541
                bset = context->capability_bounding_set;
9,597✔
5542

5543
#if HAVE_SECCOMP
5544
                /* If the service has any form of a seccomp filter and it allows dropping privileges, we'll
5545
                 * keep the needed privileges to apply it even if we're not root. */
5546
                if (needs_setuid &&
19,194✔
5547
                    uid_is_valid(uid) &&
11,619✔
5548
                    context_has_seccomp(context) &&
2,773✔
5549
                    seccomp_allows_drop_privileges(context)) {
751✔
5550
                        keep_seccomp_privileges = true;
751✔
5551

5552
                        if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
751✔
5553
                                *exit_status = EXIT_USER;
×
5554
                                return log_error_errno(errno, "Failed to enable keep capabilities flag: %m");
×
5555
                        }
5556

5557
                        /* Save the current bounding set so we can restore it after applying the seccomp
5558
                         * filter */
5559
                        saved_bset = bset;
751✔
5560
                        bset |= (UINT64_C(1) << CAP_SYS_ADMIN) |
751✔
5561
                                (UINT64_C(1) << CAP_SETPCAP);
5562
                }
5563
#endif
5564

5565
                if (!cap_test_all(bset)) {
9,597✔
5566
                        r = capability_bounding_set_drop(bset, /* right_now= */ false);
1,618✔
5567
                        if (r < 0) {
1,618✔
5568
                                *exit_status = EXIT_CAPABILITIES;
×
5569
                                return log_error_errno(r, "Failed to drop capabilities: %m");
×
5570
                        }
5571
                }
5572

5573
                /* Ambient capabilities are cleared during setresuid() (in enforce_user()) even with
5574
                 * keep-caps set.
5575
                 *
5576
                 * To be able to raise the ambient capabilities after setresuid() they have to be added to
5577
                 * the inherited set and keep caps has to be set (done in enforce_user()).  After setresuid()
5578
                 * the ambient capabilities can be raised as they are present in the permitted and
5579
                 * inhertiable set. However it is possible that someone wants to set ambient capabilities
5580
                 * without changing the user, so we also set the ambient capabilities here.
5581
                 *
5582
                 * The requested ambient capabilities are raised in the inheritable set if the second
5583
                 * argument is true. */
5584
                if (capability_ambient_set != 0) {
9,597✔
5585
                        r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ true);
746✔
5586
                        if (r < 0) {
746✔
5587
                                *exit_status = EXIT_CAPABILITIES;
×
5588
                                return log_error_errno(r, "Failed to apply ambient capabilities (before UID change): %m");
×
5589
                        }
5590
                }
5591
        }
5592

5593
        /* chroot to root directory first, before we lose the ability to chroot */
5594
        r = apply_root_directory(context, params, runtime, needs_mount_namespace, exit_status);
9,597✔
5595
        if (r < 0)
9,597✔
5596
                return log_error_errno(r, "Chrooting to the requested root directory failed: %m");
×
5597

5598
        if (needs_setuid) {
9,597✔
5599
                if (uid_is_valid(uid)) {
9,597✔
5600
                        r = enforce_user(context, uid, capability_ambient_set);
2,022✔
5601
                        if (r < 0) {
2,022✔
5602
                                *exit_status = EXIT_USER;
×
5603
                                return log_error_errno(r, "Failed to change UID to " UID_FMT ": %m", uid);
×
5604
                        }
5605

5606
                        if (keep_seccomp_privileges) {
2,022✔
5607
                                if (!BIT_SET(capability_ambient_set, CAP_SETUID)) {
751✔
5608
                                        r = drop_capability(CAP_SETUID);
751✔
5609
                                        if (r < 0) {
751✔
5610
                                                *exit_status = EXIT_USER;
×
5611
                                                return log_error_errno(r, "Failed to drop CAP_SETUID: %m");
×
5612
                                        }
5613
                                }
5614

5615
                                r = keep_capability(CAP_SYS_ADMIN);
751✔
5616
                                if (r < 0) {
751✔
5617
                                        *exit_status = EXIT_USER;
×
5618
                                        return log_error_errno(r, "Failed to keep CAP_SYS_ADMIN: %m");
×
5619
                                }
5620

5621
                                r = keep_capability(CAP_SETPCAP);
751✔
5622
                                if (r < 0) {
751✔
5623
                                        *exit_status = EXIT_USER;
×
5624
                                        return log_error_errno(r, "Failed to keep CAP_SETPCAP: %m");
×
5625
                                }
5626
                        }
5627

5628
                        if (capability_ambient_set != 0) {
2,022✔
5629

5630
                                /* Raise the ambient capabilities after user change. */
5631
                                r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ false);
743✔
5632
                                if (r < 0) {
743✔
5633
                                        *exit_status = EXIT_CAPABILITIES;
×
5634
                                        return log_error_errno(r, "Failed to apply ambient capabilities (after UID change): %m");
×
5635
                                }
5636
                        }
5637
                }
5638
        }
5639

5640
        /* Apply working directory here, because the working directory might be on NFS and only the user
5641
         * running this service might have the correct privilege to change to the working directory. Also, it
5642
         * is absolutely 💣 crucial 💣 we applied all mount namespacing rearrangements before this, so that
5643
         * the cwd cannot be used to pin directories outside of the sandbox. */
5644
        r = apply_working_directory(context, params, runtime, pwent_home, accum_env);
9,597✔
5645
        if (r < 0) {
9,597✔
5646
                *exit_status = EXIT_CHDIR;
1✔
5647
                return log_error_errno(r, "Changing to the requested working directory failed: %m");
1✔
5648
        }
5649

5650
        if (needs_sandboxing) {
9,596✔
5651
                /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to
5652
                 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
5653
                 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
5654
                 * are restricted. */
5655

5656
#if HAVE_SELINUX
5657
                if (use_selinux) {
5658
                        char *exec_context = mac_selinux_context_net ?: context->selinux_context;
5659

5660
                        if (exec_context) {
5661
                                r = setexeccon(exec_context);
5662
                                if (r < 0) {
5663
                                        if (!context->selinux_context_ignore) {
5664
                                                *exit_status = EXIT_SELINUX_CONTEXT;
5665
                                                return log_error_errno(r, "Failed to change SELinux context to %s: %m", exec_context);
5666
                                        }
5667
                                        log_debug_errno(r, "Failed to change SELinux context to %s, ignoring: %m", exec_context);
5668
                                }
5669
                        }
5670
                }
5671
#endif
5672

5673
#if HAVE_APPARMOR
5674
                if (use_apparmor && context->apparmor_profile) {
5675
                        r = ASSERT_PTR(sym_aa_change_onexec)(context->apparmor_profile);
5676
                        if (r < 0 && !context->apparmor_profile_ignore) {
5677
                                *exit_status = EXIT_APPARMOR_PROFILE;
5678
                                return log_error_errno(errno, "Failed to prepare AppArmor profile change to %s: %m",
5679
                                                       context->apparmor_profile);
5680
                        }
5681
                }
5682
#endif
5683

5684
                /* PR_GET_SECUREBITS is not privileged, while PR_SET_SECUREBITS is. So to suppress potential
5685
                 * EPERMs we'll try not to call PR_SET_SECUREBITS unless necessary. Setting securebits
5686
                 * requires CAP_SETPCAP. */
5687
                if (prctl(PR_GET_SECUREBITS) != secure_bits) {
9,596✔
5688
                        /* CAP_SETPCAP is required to set securebits. This capability is raised into the
5689
                         * effective set here.
5690
                         *
5691
                         * The effective set is overwritten during execve() with the following values:
5692
                         *
5693
                         * - ambient set (for non-root processes)
5694
                         *
5695
                         * - (inheritable | bounding) set for root processes)
5696
                         *
5697
                         * Hence there is no security impact to raise it in the effective set before execve
5698
                         */
5699
                        r = capability_gain_cap_setpcap(/* ret_before_caps = */ NULL);
803✔
5700
                        if (r < 0) {
803✔
5701
                                *exit_status = EXIT_CAPABILITIES;
×
5702
                                return log_error_errno(r, "Failed to gain CAP_SETPCAP for setting secure bits");
×
5703
                        }
5704
                        if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
803✔
5705
                                *exit_status = EXIT_SECUREBITS;
×
5706
                                return log_error_errno(errno, "Failed to set process secure bits: %m");
×
5707
                        }
5708
                }
5709

5710
                if (context_has_no_new_privileges(context))
9,596✔
5711
                        if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
1,416✔
5712
                                *exit_status = EXIT_NO_NEW_PRIVILEGES;
×
5713
                                return log_error_errno(errno, "Failed to disable new privileges: %m");
×
5714
                        }
5715

5716
#if HAVE_SECCOMP
5717
                r = apply_address_families(context, params);
9,596✔
5718
                if (r < 0) {
9,596✔
5719
                        *exit_status = EXIT_ADDRESS_FAMILIES;
×
5720
                        return log_error_errno(r, "Failed to restrict address families: %m");
×
5721
                }
5722

5723
                r = apply_memory_deny_write_execute(context, params);
9,596✔
5724
                if (r < 0) {
9,596✔
5725
                        *exit_status = EXIT_SECCOMP;
×
5726
                        return log_error_errno(r, "Failed to disable writing to executable memory: %m");
×
5727
                }
5728

5729
                r = apply_restrict_realtime(context, params);
9,596✔
5730
                if (r < 0) {
9,596✔
5731
                        *exit_status = EXIT_SECCOMP;
×
5732
                        return log_error_errno(r, "Failed to apply realtime restrictions: %m");
×
5733
                }
5734

5735
                r = apply_restrict_suid_sgid(context, params);
9,596✔
5736
                if (r < 0) {
9,596✔
5737
                        *exit_status = EXIT_SECCOMP;
×
5738
                        return log_error_errno(r, "Failed to apply SUID/SGID restrictions: %m");
×
5739
                }
5740

5741
                r = apply_restrict_namespaces(context, params);
9,596✔
5742
                if (r < 0) {
9,596✔
5743
                        *exit_status = EXIT_SECCOMP;
×
5744
                        return log_error_errno(r, "Failed to apply namespace restrictions: %m");
×
5745
                }
5746

5747
                r = apply_protect_sysctl(context, params);
9,596✔
5748
                if (r < 0) {
9,596✔
5749
                        *exit_status = EXIT_SECCOMP;
×
5750
                        return log_error_errno(r, "Failed to apply sysctl restrictions: %m");
×
5751
                }
5752

5753
                r = apply_protect_kernel_modules(context, params);
9,596✔
5754
                if (r < 0) {
9,596✔
5755
                        *exit_status = EXIT_SECCOMP;
×
5756
                        return log_error_errno(r, "Failed to apply module loading restrictions: %m");
×
5757
                }
5758

5759
                r = apply_protect_kernel_logs(context, params);
9,596✔
5760
                if (r < 0) {
9,596✔
5761
                        *exit_status = EXIT_SECCOMP;
×
5762
                        return log_error_errno(r, "Failed to apply kernel log restrictions: %m");
×
5763
                }
5764

5765
                r = apply_protect_clock(context, params);
9,596✔
5766
                if (r < 0) {
9,596✔
5767
                        *exit_status = EXIT_SECCOMP;
×
5768
                        return log_error_errno(r, "Failed to apply clock restrictions: %m");
×
5769
                }
5770

5771
                r = apply_private_devices(context, params);
9,596✔
5772
                if (r < 0) {
9,596✔
5773
                        *exit_status = EXIT_SECCOMP;
×
5774
                        return log_error_errno(r, "Failed to set up private devices: %m");
×
5775
                }
5776

5777
                r = apply_syscall_archs(context, params);
9,596✔
5778
                if (r < 0) {
9,596✔
5779
                        *exit_status = EXIT_SECCOMP;
×
5780
                        return log_error_errno(r, "Failed to apply syscall architecture restrictions: %m");
×
5781
                }
5782

5783
                r = apply_lock_personality(context, params);
9,596✔
5784
                if (r < 0) {
9,596✔
5785
                        *exit_status = EXIT_SECCOMP;
×
5786
                        return log_error_errno(r, "Failed to lock personalities: %m");
×
5787
                }
5788

5789
                r = apply_syscall_log(context, params);
9,596✔
5790
                if (r < 0) {
9,596✔
5791
                        *exit_status = EXIT_SECCOMP;
×
5792
                        return log_error_errno(r, "Failed to apply system call log filters: %m");
×
5793
                }
5794
#endif
5795

5796
#if HAVE_LIBBPF
5797
                r = apply_restrict_filesystems(context, params);
9,596✔
5798
                if (r < 0) {
9,596✔
5799
                        *exit_status = EXIT_BPF;
×
5800
                        return log_error_errno(r, "Failed to restrict filesystems: %m");
×
5801
                }
5802
#endif
5803

5804
#if HAVE_SECCOMP
5805
                /* This really should remain as close to the execve() as possible, to make sure our own code is affected
5806
                 * by the filter as little as possible. */
5807
                r = apply_syscall_filter(context, params);
9,596✔
5808
                if (r < 0) {
9,596✔
5809
                        *exit_status = EXIT_SECCOMP;
×
5810
                        return log_error_errno(r, "Failed to apply system call filters: %m");
×
5811
                }
5812

5813
                if (keep_seccomp_privileges) {
9,596✔
5814
                        /* Restore the capability bounding set with what's expected from the service + the
5815
                         * ambient capabilities hack */
5816
                        if (!cap_test_all(saved_bset)) {
750✔
5817
                                r = capability_bounding_set_drop(saved_bset, /* right_now= */ false);
715✔
5818
                                if (r < 0) {
715✔
5819
                                        *exit_status = EXIT_CAPABILITIES;
×
5820
                                        return log_error_errno(r, "Failed to drop bset capabilities: %m");
×
5821
                                }
5822
                        }
5823

5824
                        /* Only drop CAP_SYS_ADMIN if it's not in the bounding set, otherwise we'll break
5825
                         * applications that use it. */
5826
                        if (!BIT_SET(saved_bset, CAP_SYS_ADMIN)) {
750✔
5827
                                r = drop_capability(CAP_SYS_ADMIN);
280✔
5828
                                if (r < 0) {
280✔
5829
                                        *exit_status = EXIT_USER;
×
5830
                                        return log_error_errno(r, "Failed to drop CAP_SYS_ADMIN: %m");
×
5831
                                }
5832
                        }
5833

5834
                        /* Only drop CAP_SETPCAP if it's not in the bounding set, otherwise we'll break
5835
                         * applications that use it. */
5836
                        if (!BIT_SET(saved_bset, CAP_SETPCAP)) {
750✔
5837
                                r = drop_capability(CAP_SETPCAP);
533✔
5838
                                if (r < 0) {
533✔
5839
                                        *exit_status = EXIT_USER;
×
5840
                                        return log_error_errno(r, "Failed to drop CAP_SETPCAP: %m");
×
5841
                                }
5842
                        }
5843

5844
                        if (prctl(PR_SET_KEEPCAPS, 0) < 0) {
750✔
5845
                                *exit_status = EXIT_USER;
×
5846
                                return log_error_errno(errno, "Failed to drop keep capabilities flag: %m");
×
5847
                        }
5848
                }
5849
#endif
5850

5851
        }
5852

5853
        if (!strv_isempty(context->unset_environment)) {
9,596✔
5854
                char **ee = NULL;
272✔
5855

5856
                ee = strv_env_delete(accum_env, 1, context->unset_environment);
272✔
5857
                if (!ee) {
272✔
5858
                        *exit_status = EXIT_MEMORY;
×
5859
                        return log_oom();
5✔
5860
                }
5861

5862
                strv_free_and_replace(accum_env, ee);
272✔
5863
        }
5864

5865
        _cleanup_strv_free_ char **replaced_argv = NULL, **argv_via_shell = NULL;
3✔
5866
        char **final_argv = FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL) ? strv_skip(command->argv, 1) : command->argv;
9,596✔
5867

5868
        if (final_argv && !FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) {
9,596✔
5869
                _cleanup_strv_free_ char **unset_variables = NULL, **bad_variables = NULL;
9,424✔
5870

5871
                r = replace_env_argv(final_argv, accum_env, &replaced_argv, &unset_variables, &bad_variables);
9,424✔
5872
                if (r < 0) {
9,424✔
5873
                        *exit_status = EXIT_MEMORY;
×
5874
                        return log_error_errno(r, "Failed to replace environment variables: %m");
×
5875
                }
5876
                final_argv = replaced_argv;
9,424✔
5877

5878
                if (!strv_isempty(unset_variables)) {
9,424✔
5879
                        _cleanup_free_ char *ju = strv_join(unset_variables, ", ");
10✔
5880
                        log_warning("Referenced but unset environment variable evaluates to an empty string: %s", strna(ju));
5✔
5881
                }
5882

5883
                if (!strv_isempty(bad_variables)) {
9,424✔
5884
                        _cleanup_free_ char *jb = strv_join(bad_variables, ", ");
×
5885
                        log_warning("Invalid environment variable name evaluates to an empty string: %s", strna(jb));
×
5886
                }
5887
        }
5888

5889
        if (FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL)) {
9,596✔
5890
                r = strv_extendf(&argv_via_shell, "%s%s", command->argv[0][0] == '-' ? "-" : "", path);
17✔
5891
                if (r < 0) {
13✔
5892
                        *exit_status = EXIT_MEMORY;
×
5893
                        return log_oom();
×
5894
                }
5895

5896
                if (!strv_isempty(final_argv)) {
13✔
5897
                        _cleanup_free_ char *cmdline_joined = NULL;
13✔
5898

5899
                        cmdline_joined = strv_join(final_argv, " ");
13✔
5900
                        if (!cmdline_joined) {
13✔
5901
                                *exit_status = EXIT_MEMORY;
×
5902
                                return log_oom();
×
5903
                        }
5904

5905
                        r = strv_extend_many(&argv_via_shell, "-c", cmdline_joined);
13✔
5906
                        if (r < 0) {
13✔
5907
                                *exit_status = EXIT_MEMORY;
×
5908
                                return log_oom();
×
5909
                        }
5910
                }
5911

5912
                final_argv = argv_via_shell;
13✔
5913
        }
5914

5915
        log_command_line(context, params, "Executing", executable, final_argv);
9,596✔
5916

5917
        /* We have finished with all our initializations. Let's now let the manager know that. From this
5918
         * point on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */
5919

5920
        r = exec_fd_mark_hot(context, params, /* hot= */ true, exit_status);
9,596✔
5921
        if (r < 0)
9,596✔
5922
                return r;
5923

5924
        /* As last thing before the execve(), let's send the handoff timestamp */
5925
        r = send_handoff_timestamp(context, params, exit_status);
9,596✔
5926
        if (r < 0) {
9,596✔
5927
                /* If this handoff timestamp failed, let's undo the marking as hot */
5928
                (void) exec_fd_mark_hot(context, params, /* hot= */ false, /* reterr_exit_status= */ NULL);
×
5929
                return r;
5930
        }
5931

5932
        /* NB: we leave executable_fd, exec_fd, handoff_timestamp_fd open here. This is safe, because they
5933
         * have O_CLOEXEC set, and the execve() below will thus automatically close them. In fact, for
5934
         * exec_fd this is pretty much the whole raison d'etre. */
5935

5936
        r = fexecve_or_execve(executable_fd, executable, final_argv, accum_env);
9,596✔
5937

5938
        /* The execve() failed, let's undo the marking as hot */
5939
        (void) exec_fd_mark_hot(context, params, /* hot= */ false, /* reterr_exit_status= */ NULL);
3✔
5940

5941
        *exit_status = EXIT_EXEC;
3✔
5942
        return log_error_errno(r, "Failed to execute %s: %m", executable);
3✔
5943
}
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