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

systemd / systemd / 15057632786

15 May 2025 09:01PM UTC coverage: 72.267% (+0.02%) from 72.244%
15057632786

push

github

bluca
man: document how to hook stuff into system wakeup

Fixes: #6364

298523 of 413084 relevant lines covered (72.27%)

738132.88 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 <linux/prctl.h>
4
#include <linux/sched.h>
5
#include <linux/securebits.h>
6
#include <sys/eventfd.h>
7
#include <sys/ioctl.h>
8
#include <sys/mount.h>
9
#include <sys/prctl.h>
10

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

16
#include "sd-messages.h"
17

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

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

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

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

82
        int r;
9,573✔
83

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

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

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

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

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

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

106
        return 0;
107
}
108

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

199
 restore_gid:
8,000✔
200
        if (gid_is_valid(gid))
10,339✔
201
                (void) setegid(oldgid);
2,342✔
202

203
        return r;
204
}
205

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

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

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

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

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

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

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

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

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

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

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

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

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

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

274
        assert(path);
11✔
275

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

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

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

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

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

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

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

309
        return TAKE_FD(fd);
310
}
311

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

317
        ExecInput std_input;
33,051✔
318

319
        assert(context);
33,051✔
320

321
        std_input = context->std_input;
33,051✔
322

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

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

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

332
        return std_input;
333
}
334

335
static int fixup_output(ExecOutput output, int socket_fd) {
33,051✔
336

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

340
        return output;
341
}
342

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

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

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

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

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

364
                return STDIN_FILENO;
538✔
365
        }
366

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

369
        switch (i) {
11,017✔
370

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

456
        assert(context);
11,017✔
457

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

461
        if (e == EXEC_OUTPUT_INHERIT)
11,017✔
462
                return true;
463
        if (e != o)
412✔
464
                return false;
465

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

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

472
        return true;
473
}
474

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

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

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

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

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

502
                return STDOUT_FILENO;
503
        }
504

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

509
                return STDERR_FILENO;
510
        }
511

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

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

518
        if (fileno == STDERR_FILENO) {
22,034✔
519
                ExecOutput e;
11,017✔
520
                e = fixup_output(context->std_error, socket_fd);
11,017✔
521

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

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

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

537
                o = e;
538

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

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

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

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

556
        switch (o) {
11,016✔
557

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

651
        return 1;
652
}
653

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

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

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

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

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

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

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

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

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

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

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

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

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

710
        errno = abs(err);
×
711

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

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

721
        assert(vc);
×
722

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

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

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

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

736
        release_terminal();
×
737

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

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

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

749
        return r;
×
750
}
751

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

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

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

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

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

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

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

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

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

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

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

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

867
        int r;
9,396✔
868

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

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

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

880
        return 0;
9,394✔
881
}
882

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

888
        int r;
11✔
889

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

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

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

900
        return 0;
11✔
901
}
902

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

909
        int r;
11,555✔
910

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

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

926
                keep_groups = true;
927
        }
928

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

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

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

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

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

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

967
                k++;
9✔
968
        }
969

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

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

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

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

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

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

1000
        return 0;
1001
}
1002

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

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

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

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

1019
        return 1;
1020
}
1021

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

1027
        int r;
2,010✔
1028

1029
        assert(context);
2,010✔
1030

1031
        if (!uid_is_valid(uid))
2,010✔
1032
                return 0;
1033

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

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

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

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

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

1057
#if HAVE_PAM
1058

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

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

1065
        free(responses);
×
1066
}
×
1067

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

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

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

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

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

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

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

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

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

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

1115
                                set_credential_env_var = true;
2✔
1116
                        }
1117

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

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

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

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

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

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

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

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

1166
        return PAM_SUCCESS;
5✔
1167
}
1168

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

1172
        assert(handle);
219✔
1173

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1279
        close_session = true;
400✔
1280

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

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

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

1291
        parent_pid = getpid_cached();
400✔
1292

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

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

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

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

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

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

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

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

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

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

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

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

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

1352
                ret = 0;
1353

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

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

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

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

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

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

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

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

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

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

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

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

1406
        assert(path);
11,558✔
1407

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1488
#if HAVE_SECCOMP
1489

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

1494
        assert(c);
748✔
1495

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1644
        return seccomp_memory_deny_write_execute();
×
1645
}
1646

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

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

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

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

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

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

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

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

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

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

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

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

1686
        return seccomp_protect_sysctl();
362✔
1687
}
1688

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1784
#endif
1785

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1855
        return 1;
1856
}
1857

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

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

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

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

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

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

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

1881
        }
1882

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2033
                tty_path = exec_context_tty_path(c);
452✔
2034

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2184
        assert(c->private_var_tmp >= 0 && c->private_var_tmp < _PRIVATE_TMP_MAX);
9,599✔
2185
        if (c->private_tmp != c->private_var_tmp) {
9,599✔
2186
                assert(c->private_tmp == PRIVATE_TMP_DISCONNECTED);
283✔
2187
                assert(c->private_var_tmp == PRIVATE_TMP_NO);
283✔
2188

2189
                /* When private tmpfs is enabled only on /tmp/, then explicitly set $TMPDIR to suggest the
2190
                 * service to use /tmp/. */
2191

2192
                x = strdup("TMPDIR=/tmp");
283✔
2193
                if (!x)
283✔
2194
                        return -ENOMEM;
2195

2196
                our_env[n_env++] = x;
283✔
2197
        }
2198

2199
        assert(n_env < N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
9,599✔
2200
#undef N_ENV_VARS
2201

2202
        *ret = TAKE_PTR(our_env);
9,599✔
2203

2204
        return 0;
9,599✔
2205
}
2206

2207
static int build_pass_environment(const ExecContext *c, char ***ret) {
9,599✔
2208
        _cleanup_strv_free_ char **pass_env = NULL;
9,599✔
2209
        size_t n_env = 0;
9,599✔
2210

2211
        assert(c);
9,599✔
2212
        assert(ret);
9,599✔
2213

2214
        STRV_FOREACH(i, c->pass_environment) {
9,905✔
2215
                _cleanup_free_ char *x = NULL;
×
2216
                char *v;
306✔
2217

2218
                v = getenv(*i);
306✔
2219
                if (!v)
306✔
2220
                        continue;
×
2221
                x = strjoin(*i, "=", v);
306✔
2222
                if (!x)
306✔
2223
                        return -ENOMEM;
2224

2225
                if (!GREEDY_REALLOC(pass_env, n_env + 2))
306✔
2226
                        return -ENOMEM;
2227

2228
                pass_env[n_env++] = TAKE_PTR(x);
306✔
2229
                pass_env[n_env] = NULL;
306✔
2230
        }
2231

2232
        *ret = TAKE_PTR(pass_env);
9,599✔
2233
        return 0;
9,599✔
2234
}
2235

2236
static int setup_private_users(PrivateUsers private_users, uid_t ouid, gid_t ogid, uid_t uid, gid_t gid, bool allow_setgroups) {
9,583✔
2237
        _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
9,583✔
2238
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
9,583✔
2239
        _cleanup_close_ int unshare_ready_fd = -EBADF;
9,583✔
2240
        _cleanup_(sigkill_waitp) pid_t pid = 0;
9,583✔
2241
        uint64_t c = 1;
9,583✔
2242
        ssize_t n;
9,583✔
2243
        int r;
9,583✔
2244

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

2255
        if (private_users == PRIVATE_USERS_NO)
9,583✔
2256
                return 0;
2257

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

2301
        if (private_users == PRIVATE_USERS_IDENTITY) {
52✔
2302
                gid_map = strdup("0 0 65536\n");
4✔
2303
                if (!gid_map)
4✔
2304
                        return -ENOMEM;
2305
        } else if (private_users == PRIVATE_USERS_FULL) {
48✔
2306
                r = asprintf(&gid_map, "0 0 1\n"
5✔
2307
                                       "1 1 " GID_FMT "\n", (gid_t) (UINT32_MAX - 1));
2308
                if (r < 0)
5✔
2309
                        return -ENOMEM;
2310
        /* Can only set up multiple mappings with CAP_SETGID. */
2311
        } else if (have_effective_cap(CAP_SETGID) > 0 && gid != ogid && gid_is_valid(gid)) {
59✔
2312
                r = asprintf(&gid_map,
2✔
2313
                             GID_FMT " " GID_FMT " 1\n"     /* Map $OGID → $OGID */
2314
                             GID_FMT " " GID_FMT " 1\n",    /* Map $GID → $GID */
2315
                             ogid, ogid, gid, gid);
2316
                if (r < 0)
2✔
2317
                        return -ENOMEM;
2318
        } else {
2319
                r = asprintf(&gid_map,
41✔
2320
                             GID_FMT " " GID_FMT " 1\n",    /* Map $OGID -> $OGID */
2321
                             ogid, ogid);
2322
                if (r < 0)
41✔
2323
                        return -ENOMEM;
2324
        }
2325

2326
        /* Create a communication channel so that the parent can tell the child when it finished creating the user
2327
         * namespace. */
2328
        unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
52✔
2329
        if (unshare_ready_fd < 0)
52✔
2330
                return -errno;
×
2331

2332
        /* Create a communication channel so that the child can tell the parent a proper error code in case it
2333
         * failed. */
2334
        if (pipe2(errno_pipe, O_CLOEXEC) < 0)
52✔
2335
                return -errno;
×
2336

2337
        r = safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL, &pid);
52✔
2338
        if (r < 0)
103✔
2339
                return r;
2340
        if (r == 0) {
103✔
2341
                _cleanup_close_ int fd = -EBADF;
×
2342
                const char *a;
51✔
2343
                pid_t ppid;
51✔
2344

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

2348
                ppid = getppid();
51✔
2349
                errno_pipe[0] = safe_close(errno_pipe[0]);
51✔
2350

2351
                /* Wait until the parent unshared the user namespace */
2352
                if (read(unshare_ready_fd, &c, sizeof(c)) < 0)
51✔
2353
                        report_errno_and_exit(errno_pipe[1], -errno);
×
2354

2355
                /* Disable the setgroups() system call in the child user namespace, for good, unless PrivateUsers=full
2356
                 * and using the system service manager. */
2357
                a = procfs_file_alloca(ppid, "setgroups");
51✔
2358
                fd = open(a, O_WRONLY|O_CLOEXEC);
51✔
2359
                if (fd < 0) {
51✔
2360
                        if (errno != ENOENT) {
×
2361
                                r = log_debug_errno(errno, "Failed to open %s: %m", a);
×
2362
                                report_errno_and_exit(errno_pipe[1], r);
×
2363
                        }
2364

2365
                        /* If the file is missing the kernel is too old, let's continue anyway. */
2366
                } else {
2367
                        const char *setgroups = allow_setgroups ? "allow\n" : "deny\n";
51✔
2368
                        if (write(fd, setgroups, strlen(setgroups)) < 0) {
51✔
2369
                                r = log_debug_errno(errno, "Failed to write '%s' to %s: %m", setgroups, a);
×
2370
                                report_errno_and_exit(errno_pipe[1], r);
×
2371
                        }
2372

2373
                        fd = safe_close(fd);
51✔
2374
                }
2375

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

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

2389
                fd = safe_close(fd);
51✔
2390

2391
                /* The write the UID map */
2392
                a = procfs_file_alloca(ppid, "uid_map");
51✔
2393
                fd = open(a, O_WRONLY|O_CLOEXEC);
51✔
2394
                if (fd < 0) {
51✔
2395
                        r = log_debug_errno(errno, "Failed to open %s: %m", a);
×
2396
                        report_errno_and_exit(errno_pipe[1], r);
×
2397
                }
2398

2399
                if (write(fd, uid_map, strlen(uid_map)) < 0) {
51✔
2400
                        r = log_debug_errno(errno, "Failed to write UID map to %s: %m", a);
×
2401
                        report_errno_and_exit(errno_pipe[1], r);
×
2402
                }
2403

2404
                _exit(EXIT_SUCCESS);
51✔
2405
        }
2406

2407
        errno_pipe[1] = safe_close(errno_pipe[1]);
52✔
2408

2409
        if (unshare(CLONE_NEWUSER) < 0)
52✔
2410
                return log_debug_errno(errno, "Failed to unshare user namespace: %m");
×
2411

2412
        /* Let the child know that the namespace is ready now */
2413
        if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
52✔
2414
                return -errno;
×
2415

2416
        /* Try to read an error code from the child */
2417
        n = read(errno_pipe[0], &r, sizeof(r));
52✔
2418
        if (n < 0)
52✔
2419
                return -errno;
×
2420
        if (n == sizeof(r)) { /* an error code was sent to us */
52✔
2421
                if (r < 0)
×
2422
                        return r;
2423
                return -EIO;
×
2424
        }
2425
        if (n != 0) /* on success we should have read 0 bytes */
52✔
2426
                return -EIO;
2427

2428
        r = wait_for_terminate_and_check("(sd-userns)", TAKE_PID(pid), 0);
52✔
2429
        if (r < 0)
52✔
2430
                return r;
2431
        if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
52✔
2432
                return -EIO;
×
2433

2434
        return 1;
2435
}
2436

2437
static int can_mount_proc(void) {
10✔
2438
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
5✔
2439
        _cleanup_(sigkill_waitp) pid_t pid = 0;
×
2440
        ssize_t n;
10✔
2441
        int r;
10✔
2442

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

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

2452
        /* Fork a child process into its own mount and PID namespace. Note safe_fork() already remounts / as SLAVE
2453
         * with FORK_MOUNTNS_SLAVE. */
2454
        r = safe_fork("(sd-proc-check)",
10✔
2455
                      FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE|FORK_NEW_PIDNS, &pid);
2456
        if (r < 0)
10✔
2457
                return log_debug_errno(r, "Failed to fork child process (sd-proc-check): %m");
×
2458
        if (r == 0) {
10✔
2459
                errno_pipe[0] = safe_close(errno_pipe[0]);
5✔
2460

2461
                /* Try mounting /proc on /dev/shm/. No need to clean up the mount since the mount
2462
                 * namespace will be cleaned up once the process exits. */
2463
                r = mount_follow_verbose(LOG_DEBUG, "proc", "/dev/shm/", "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
5✔
2464
                if (r < 0) {
5✔
2465
                        (void) write(errno_pipe[1], &r, sizeof(r));
1✔
2466
                        _exit(EXIT_FAILURE);
1✔
2467
                }
2468

2469
                _exit(EXIT_SUCCESS);
4✔
2470
        }
2471

2472
        errno_pipe[1] = safe_close(errno_pipe[1]);
5✔
2473

2474
        /* Try to read an error code from the child */
2475
        n = read(errno_pipe[0], &r, sizeof(r));
5✔
2476
        if (n < 0)
5✔
2477
                return log_debug_errno(errno, "Failed to read errno from pipe with child process (sd-proc-check): %m");
×
2478
        if (n == sizeof(r)) { /* an error code was sent to us */
5✔
2479
                /* This is the expected case where proc cannot be mounted due to permissions. */
2480
                if (ERRNO_IS_NEG_PRIVILEGE(r))
5✔
2481
                        return 0;
2482
                if (r < 0)
×
2483
                        return r;
2484

2485
                return -EIO;
×
2486
        }
2487
        if (n != 0) /* on success we should have read 0 bytes */
4✔
2488
                return -EIO;
2489

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

2496
        return 1;
2497
}
2498

2499
static int setup_private_pids(const ExecContext *c, ExecParameters *p) {
9✔
2500
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
×
2501
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
6✔
2502
        ssize_t n;
9✔
2503
        int r, q;
9✔
2504

2505
        assert(c);
9✔
2506
        assert(p);
9✔
2507
        assert(p->pidref_transport_fd >= 0);
9✔
2508

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

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

2519
        /* Set FORK_DETACH to immediately re-parent the child process to the invoking manager process. */
2520
        r = pidref_safe_fork("(sd-pidns-child)", FORK_NEW_PIDNS|FORK_DETACH, &pidref);
9✔
2521
        if (r < 0)
15✔
2522
                return log_debug_errno(r, "Failed to fork child into new pid namespace: %m");
×
2523
        if (r > 0) {
15✔
2524
                errno_pipe[0] = safe_close(errno_pipe[0]);
9✔
2525

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

2542
        errno_pipe[1] = safe_close(errno_pipe[1]);
6✔
2543
        p->pidref_transport_fd = safe_close(p->pidref_transport_fd);
6✔
2544

2545
        /* Try to read an error code from the parent. Note a child process cannot wait for the parent so we always
2546
         * receive an errno even on success. */
2547
        n = read(errno_pipe[0], &r, sizeof(r));
6✔
2548
        if (n < 0)
6✔
2549
                return log_debug_errno(errno, "Failed to read errno from pipe with parent process: %m");
×
2550
        if (n != sizeof(r))
6✔
2551
                return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to read enough bytes from pipe with parent process");
×
2552
        if (r < 0)
6✔
2553
                return log_debug_errno(r, "Failed to send child pidref to manager: %m");
×
2554

2555
        /* NOTE! This function returns in the child process only. */
2556
        return r;
2557
}
2558

2559
static int create_many_symlinks(const char *root, const char *source, char **symlinks) {
1,530✔
2560
        _cleanup_free_ char *src_abs = NULL;
1,530✔
2561
        int r;
1,530✔
2562

2563
        assert(source);
1,530✔
2564

2565
        src_abs = path_join(root, source);
1,530✔
2566
        if (!src_abs)
1,530✔
2567
                return -ENOMEM;
2568

2569
        STRV_FOREACH(dst, symlinks) {
1,543✔
2570
                _cleanup_free_ char *dst_abs = NULL;
13✔
2571

2572
                dst_abs = path_join(root, *dst);
13✔
2573
                if (!dst_abs)
13✔
2574
                        return -ENOMEM;
2575

2576
                r = mkdir_parents_label(dst_abs, 0755);
13✔
2577
                if (r < 0)
13✔
2578
                        return r;
2579

2580
                r = symlink_idempotent(src_abs, dst_abs, true);
13✔
2581
                if (r < 0)
13✔
2582
                        return r;
2583
        }
2584

2585
        return 0;
2586
}
2587

2588
static int setup_exec_directory(
57,761✔
2589
                const ExecContext *context,
2590
                const ExecParameters *params,
2591
                uid_t uid,
2592
                gid_t gid,
2593
                ExecDirectoryType type,
2594
                bool needs_mount_namespace,
2595
                int *exit_status) {
2596

2597
        static const int exit_status_table[_EXEC_DIRECTORY_TYPE_MAX] = {
57,761✔
2598
                [EXEC_DIRECTORY_RUNTIME]       = EXIT_RUNTIME_DIRECTORY,
2599
                [EXEC_DIRECTORY_STATE]         = EXIT_STATE_DIRECTORY,
2600
                [EXEC_DIRECTORY_CACHE]         = EXIT_CACHE_DIRECTORY,
2601
                [EXEC_DIRECTORY_LOGS]          = EXIT_LOGS_DIRECTORY,
2602
                [EXEC_DIRECTORY_CONFIGURATION] = EXIT_CONFIGURATION_DIRECTORY,
2603
        };
2604
        int r;
57,761✔
2605

2606
        assert(context);
57,761✔
2607
        assert(params);
57,761✔
2608
        assert(type >= 0 && type < _EXEC_DIRECTORY_TYPE_MAX);
57,761✔
2609
        assert(exit_status);
57,761✔
2610

2611
        if (!params->prefix[type])
57,761✔
2612
                return 0;
2613

2614
        if (params->flags & EXEC_CHOWN_DIRECTORIES) {
57,761✔
2615
                if (!uid_is_valid(uid))
53,806✔
2616
                        uid = 0;
40,506✔
2617
                if (!gid_is_valid(gid))
53,806✔
2618
                        gid = 0;
40,486✔
2619
        }
2620

2621
        FOREACH_ARRAY(i, context->directories[type].items, context->directories[type].n_items) {
61,464✔
2622
                _cleanup_free_ char *p = NULL, *pp = NULL;
3,704✔
2623

2624
                p = path_join(params->prefix[type], i->path);
3,704✔
2625
                if (!p) {
3,704✔
2626
                        r = -ENOMEM;
×
2627
                        goto fail;
×
2628
                }
2629

2630
                r = mkdir_parents_label(p, 0755);
3,704✔
2631
                if (r < 0)
3,704✔
2632
                        goto fail;
×
2633

2634
                if (IN_SET(type, EXEC_DIRECTORY_STATE, EXEC_DIRECTORY_LOGS) && params->runtime_scope == RUNTIME_SCOPE_USER) {
3,704✔
2635

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

2649
                        /* this assumes the state dir is always created before the configuration dir */
2650
                        assert_cc(EXEC_DIRECTORY_STATE < EXEC_DIRECTORY_LOGS);
7✔
2651
                        assert_cc(EXEC_DIRECTORY_LOGS < EXEC_DIRECTORY_CONFIGURATION);
7✔
2652

2653
                        r = access_nofollow(p, F_OK);
7✔
2654
                        if (r == -ENOENT) {
7✔
2655
                                _cleanup_free_ char *q = NULL;
3✔
2656

2657
                                /* OK, we know that the state dir does not exist. Let's see if the dir exists
2658
                                 * under the configuration hierarchy. */
2659

2660
                                if (type == EXEC_DIRECTORY_STATE)
3✔
2661
                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], i->path);
3✔
2662
                                else if (type == EXEC_DIRECTORY_LOGS)
×
2663
                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], "log", i->path);
×
2664
                                else
2665
                                        assert_not_reached();
×
2666
                                if (!q) {
3✔
2667
                                        r = -ENOMEM;
×
2668
                                        goto fail;
×
2669
                                }
2670

2671
                                r = access_nofollow(q, F_OK);
3✔
2672
                                if (r >= 0) {
3✔
2673
                                        /* It does exist! This hence looks like an update. Symlink the
2674
                                         * configuration directory into the state directory. */
2675

2676
                                        r = symlink_idempotent(q, p, /* make_relative= */ true);
1✔
2677
                                        if (r < 0)
1✔
2678
                                                goto fail;
×
2679

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

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

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

2715
                        pp = path_join(params->prefix[type], "private");
13✔
2716
                        if (!pp) {
13✔
2717
                                r = -ENOMEM;
×
2718
                                goto fail;
×
2719
                        }
2720

2721
                        /* First set up private root if it doesn't exist yet, with access mode 0700 and owned by root:root */
2722
                        r = mkdir_safe_label(pp, 0700, 0, 0, MKDIR_WARN_MODE);
13✔
2723
                        if (r < 0)
13✔
2724
                                goto fail;
×
2725

2726
                        if (!path_extend(&pp, i->path)) {
13✔
2727
                                r = -ENOMEM;
×
2728
                                goto fail;
×
2729
                        }
2730

2731
                        /* Create all directories between the configured directory and this private root, and mark them 0755 */
2732
                        r = mkdir_parents_label(pp, 0755);
13✔
2733
                        if (r < 0)
13✔
2734
                                goto fail;
×
2735

2736
                        if (is_dir(p, false) > 0 &&
13✔
2737
                            (access_nofollow(pp, F_OK) == -ENOENT)) {
×
2738

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

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

2747
                                r = RET_NERRNO(rename(p, pp));
×
2748
                                if (r < 0)
×
2749
                                        goto fail;
×
2750
                        } else {
2751
                                /* Otherwise, create the actual directory for the service */
2752

2753
                                r = mkdir_label(pp, context->directories[type].mode);
13✔
2754
                                if (r < 0 && r != -EEXIST)
13✔
2755
                                        goto fail;
×
2756
                        }
2757

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

2777
                } else {
2778
                        _cleanup_free_ char *target = NULL;
3,690✔
2779

2780
                        if (EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type) &&
7,340✔
2781
                            readlink_and_make_absolute(p, &target) >= 0) {
3,650✔
2782
                                _cleanup_free_ char *q = NULL, *q_resolved = NULL, *target_resolved = NULL;
11✔
2783

2784
                                /* This already exists and is a symlink? Interesting. Maybe it's one created
2785
                                 * by DynamicUser=1 (see above)?
2786
                                 *
2787
                                 * We do this for all directory types except for ConfigurationDirectory=,
2788
                                 * since they all support the private/ symlink logic at least in some
2789
                                 * configurations, see above. */
2790

2791
                                r = chase(target, NULL, 0, &target_resolved, NULL);
11✔
2792
                                if (r < 0)
11✔
2793
                                        goto fail;
×
2794

2795
                                q = path_join(params->prefix[type], "private", i->path);
11✔
2796
                                if (!q) {
11✔
2797
                                        r = -ENOMEM;
×
2798
                                        goto fail;
×
2799
                                }
2800

2801
                                /* /var/lib or friends may be symlinks. So, let's chase them also. */
2802
                                r = chase(q, NULL, CHASE_NONEXISTENT, &q_resolved, NULL);
11✔
2803
                                if (r < 0)
11✔
2804
                                        goto fail;
×
2805

2806
                                if (path_equal(q_resolved, target_resolved)) {
11✔
2807

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

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

2815
                                        r = RET_NERRNO(unlink(p));
8✔
2816
                                        if (r < 0)
×
2817
                                                goto fail;
×
2818

2819
                                        r = RET_NERRNO(rename(q, p));
11✔
2820
                                        if (r < 0)
×
2821
                                                goto fail;
×
2822
                                }
2823
                        }
2824

2825
                        r = mkdir_label(p, context->directories[type].mode);
3,690✔
2826
                        if (r < 0) {
3,690✔
2827
                                if (r != -EEXIST)
2,640✔
2828
                                        goto fail;
×
2829

2830
                                if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type)) {
2,640✔
2831
                                        struct stat st;
27✔
2832

2833
                                        /* Don't change the owner/access mode of the configuration directory,
2834
                                         * as in the common case it is not written to by a service, and shall
2835
                                         * not be writable. */
2836

2837
                                        r = RET_NERRNO(stat(p, &st));
27✔
2838
                                        if (r < 0)
×
2839
                                                goto fail;
×
2840

2841
                                        /* Still complain if the access mode doesn't match */
2842
                                        if (((st.st_mode ^ context->directories[type].mode) & 07777) != 0)
27✔
2843
                                                log_warning("%s \'%s\' already exists but the mode is different. "
×
2844
                                                            "(File system: %o %sMode: %o)",
2845
                                                            exec_directory_type_to_string(type), i->path,
2846
                                                            st.st_mode & 07777, exec_directory_type_to_string(type), context->directories[type].mode & 07777);
2847

2848
                                        continue;
27✔
2849
                                }
2850
                        }
2851
                }
2852

2853
                /* Lock down the access mode (we use chmod_and_chown() to make this idempotent. We don't
2854
                 * specify UID/GID here, so that path_chown_recursive() can optimize things depending on the
2855
                 * current UID/GID ownership.) */
2856
                const char *target_dir = pp ?: p;
3,676✔
2857
                r = chmod_and_chown(target_dir, context->directories[type].mode, UID_INVALID, GID_INVALID);
3,676✔
2858
                if (r < 0)
3,676✔
2859
                        goto fail;
×
2860

2861
                /* Skip the rest (which deals with ownership) in user mode, since ownership changes are not
2862
                 * available to user code anyway */
2863
                if (params->runtime_scope != RUNTIME_SCOPE_SYSTEM)
3,676✔
2864
                        continue;
9✔
2865

2866
                int idmapping_supported = is_idmapping_supported(target_dir);
3,667✔
2867
                if (idmapping_supported < 0) {
3,667✔
2868
                        r = log_debug_errno(idmapping_supported, "Unable to determine if ID mapping is supported on mount '%s': %m", target_dir);
×
2869
                        goto fail;
×
2870
                }
2871

2872
                log_debug("ID-mapping is%ssupported for exec directory %s", idmapping_supported ? " " : " not ", target_dir);
3,673✔
2873

2874
                /* Change the ownership of the whole tree, if necessary. When dynamic users are used we
2875
                 * drop the suid/sgid bits, since we really don't want SUID/SGID files for dynamic UID/GID
2876
                 * assignments to exist. */
2877
                uid_t chown_uid = uid;
3,667✔
2878
                gid_t chown_gid = gid;
3,667✔
2879
                bool do_chown = false;
3,667✔
2880

2881
                if (uid == 0 || gid == 0 || !idmapping_supported) {
3,667✔
2882
                        do_chown = true;
1,432✔
2883
                        i->idmapped = false;
1,432✔
2884
                } else {
2885
                        /* Use 'nobody' uid/gid for exec directories if ID-mapping is supported. For backward compatibility,
2886
                         * continue doing chmod/chown if the directory was chmod/chowned before (if uid/gid is not 'nobody') */
2887
                        struct stat st;
2,235✔
2888
                        r = RET_NERRNO(stat(target_dir, &st));
2,235✔
2889
                        if (r < 0)
×
2890
                                goto fail;
×
2891

2892
                        if (st.st_uid == UID_NOBODY && st.st_gid == GID_NOBODY) {
2,235✔
2893
                                do_chown = false;
7✔
2894
                                i->idmapped = true;
7✔
2895
                       } else if (exec_directory_is_private(context, type) && st.st_uid == 0 && st.st_gid == 0) {
2,228✔
2896
                                chown_uid = UID_NOBODY;
6✔
2897
                                chown_gid = GID_NOBODY;
6✔
2898
                                do_chown = true;
6✔
2899
                                i->idmapped = true;
6✔
2900
                        } else {
2901
                                do_chown = true;
2,222✔
2902
                                i->idmapped = false;
2,222✔
2903
                        }
2904
                }
2905

2906
                if (do_chown) {
3,667✔
2907
                        r = path_chown_recursive(target_dir, chown_uid, chown_gid, context->dynamic_user ? 01777 : 07777, AT_SYMLINK_FOLLOW);
7,311✔
2908
                        if (r < 0)
3,660✔
2909
                                goto fail;
1✔
2910
                }
2911
        }
2912

2913
        /* If we are not going to run in a namespace, set up the symlinks - otherwise
2914
         * they are set up later, to allow configuring empty var/run/etc. */
2915
        if (!needs_mount_namespace)
57,760✔
2916
                FOREACH_ARRAY(i, context->directories[type].items, context->directories[type].n_items) {
46,165✔
2917
                        r = create_many_symlinks(params->prefix[type], i->path, i->symlinks);
1,530✔
2918
                        if (r < 0)
1,530✔
2919
                                goto fail;
×
2920
                }
2921

2922
        return 0;
2923

2924
fail:
1✔
2925
        *exit_status = exit_status_table[type];
1✔
2926
        return r;
1✔
2927
}
2928

2929
#if ENABLE_SMACK
2930
static int setup_smack(
×
2931
                const ExecContext *context,
2932
                const ExecParameters *params,
2933
                int executable_fd) {
2934
        int r;
×
2935

2936
        assert(context);
×
2937
        assert(params);
×
2938
        assert(executable_fd >= 0);
×
2939

2940
        if (context->smack_process_label) {
×
2941
                r = mac_smack_apply_pid(0, context->smack_process_label);
×
2942
                if (r < 0)
×
2943
                        return r;
×
2944
        } else if (params->fallback_smack_process_label) {
×
2945
                _cleanup_free_ char *exec_label = NULL;
×
2946

2947
                r = mac_smack_read_fd(executable_fd, SMACK_ATTR_EXEC, &exec_label);
×
2948
                if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
×
2949
                        return r;
2950

2951
                r = mac_smack_apply_pid(0, exec_label ?: params->fallback_smack_process_label);
×
2952
                if (r < 0)
×
2953
                        return r;
2954
        }
2955

2956
        return 0;
2957
}
2958
#endif
2959

2960
static int compile_bind_mounts(
2,007✔
2961
                const ExecContext *context,
2962
                const ExecParameters *params,
2963
                uid_t exec_directory_uid, /* only used for id-mapped mounts Exec directories */
2964
                gid_t exec_directory_gid, /* only used for id-mapped mounts Exec directories */
2965
                BindMount **ret_bind_mounts,
2966
                size_t *ret_n_bind_mounts,
2967
                char ***ret_empty_directories) {
2968

2969
        _cleanup_strv_free_ char **empty_directories = NULL;
2,007✔
2970
        BindMount *bind_mounts = NULL;
2,007✔
2971
        size_t n, h = 0;
2,007✔
2972
        int r;
2,007✔
2973

2974
        assert(context);
2,007✔
2975
        assert(params);
2,007✔
2976
        assert(ret_bind_mounts);
2,007✔
2977
        assert(ret_n_bind_mounts);
2,007✔
2978
        assert(ret_empty_directories);
2,007✔
2979

2980
        CLEANUP_ARRAY(bind_mounts, h, bind_mount_free_many);
2,007✔
2981

2982
        n = context->n_bind_mounts;
2,007✔
2983
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
12,042✔
2984
                if (!params->prefix[t])
10,035✔
2985
                        continue;
×
2986

2987
                FOREACH_ARRAY(i, context->directories[t].items, context->directories[t].n_items)
11,620✔
2988
                        n += !FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE) || FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY);
1,585✔
2989
        }
2990

2991
        if (n <= 0) {
2,007✔
2992
                *ret_bind_mounts = NULL;
1,088✔
2993
                *ret_n_bind_mounts = 0;
1,088✔
2994
                *ret_empty_directories = NULL;
1,088✔
2995
                return 0;
1,088✔
2996
        }
2997

2998
        bind_mounts = new(BindMount, n);
919✔
2999
        if (!bind_mounts)
919✔
3000
                return -ENOMEM;
3001

3002
        FOREACH_ARRAY(item, context->bind_mounts, context->n_bind_mounts) {
939✔
3003
                r = bind_mount_add(&bind_mounts, &h, item);
20✔
3004
                if (r < 0)
20✔
3005
                        return r;
3006
        }
3007

3008
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
5,514✔
3009
                if (!params->prefix[t])
4,595✔
3010
                        continue;
×
3011

3012
                if (context->directories[t].n_items == 0)
4,595✔
3013
                        continue;
3,466✔
3014

3015
                if (exec_directory_is_private(context, t) &&
1,142✔
3016
                    !exec_context_with_rootfs(context)) {
13✔
3017
                        char *private_root;
13✔
3018

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

3023
                        private_root = path_join(params->prefix[t], "private");
13✔
3024
                        if (!private_root)
13✔
3025
                                return -ENOMEM;
3026

3027
                        r = strv_consume(&empty_directories, private_root);
13✔
3028
                        if (r < 0)
13✔
3029
                                return r;
3030
                }
3031

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

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

3042
                        if (exec_directory_is_private(context, t))
1,585✔
3043
                                s = path_join(params->prefix[t], "private", i->path);
13✔
3044
                        else
3045
                                s = path_join(params->prefix[t], i->path);
1,572✔
3046
                        if (!s)
1,585✔
3047
                                return -ENOMEM;
3048

3049
                        if (exec_directory_is_private(context, t) &&
1,598✔
3050
                            exec_context_with_rootfs(context))
13✔
3051
                                /* When RootDirectory= or RootImage= are set, then the symbolic link to the private
3052
                                 * directory is not created on the root directory. So, let's bind-mount the directory
3053
                                 * on the 'non-private' place. */
3054
                                d = path_join(params->prefix[t], i->path);
×
3055
                        else
3056
                                d = strdup(s);
1,585✔
3057
                        if (!d)
1,585✔
3058
                                return -ENOMEM;
3059

3060
                        bind_mounts[h++] = (BindMount) {
1,585✔
3061
                                .source = TAKE_PTR(s),
1,585✔
3062
                                .destination = TAKE_PTR(d),
1,585✔
3063
                                .nosuid = context->dynamic_user, /* don't allow suid/sgid when DynamicUser= is on */
1,585✔
3064
                                .recursive = true,
3065
                                .read_only = FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY),
1,585✔
3066
                                .idmapped = i->idmapped,
1,585✔
3067
                                .uid = exec_directory_uid,
3068
                                .gid = exec_directory_gid,
3069
                        };
3070
                }
3071
        }
3072

3073
        assert(h == n);
919✔
3074

3075
        *ret_bind_mounts = TAKE_PTR(bind_mounts);
919✔
3076
        *ret_n_bind_mounts = n;
919✔
3077
        *ret_empty_directories = TAKE_PTR(empty_directories);
919✔
3078

3079
        return (int) n;
919✔
3080
}
3081

3082
/* ret_symlinks will contain a list of pairs src:dest that describes
3083
 * the symlinks to create later on. For example, the symlinks needed
3084
 * to safely give private directories to DynamicUser=1 users. */
3085
static int compile_symlinks(
2,007✔
3086
                const ExecContext *context,
3087
                const ExecParameters *params,
3088
                bool setup_os_release_symlink,
3089
                char ***ret_symlinks) {
3090

3091
        _cleanup_strv_free_ char **symlinks = NULL;
2,007✔
3092
        int r;
2,007✔
3093

3094
        assert(context);
2,007✔
3095
        assert(params);
2,007✔
3096
        assert(ret_symlinks);
2,007✔
3097

3098
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++)
12,042✔
3099
                FOREACH_ARRAY(i, context->directories[dt].items, context->directories[dt].n_items) {
11,620✔
3100
                        _cleanup_free_ char *private_path = NULL, *path = NULL;
1,572✔
3101

3102
                        STRV_FOREACH(symlink, i->symlinks) {
1,711✔
3103
                                _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;
126✔
3104

3105
                                src_abs = path_join(params->prefix[dt], i->path);
126✔
3106
                                dst_abs = path_join(params->prefix[dt], *symlink);
126✔
3107
                                if (!src_abs || !dst_abs)
126✔
3108
                                        return -ENOMEM;
3109

3110
                                r = strv_consume_pair(&symlinks, TAKE_PTR(src_abs), TAKE_PTR(dst_abs));
126✔
3111
                                if (r < 0)
126✔
3112
                                        return r;
3113
                        }
3114

3115
                        if (!exec_directory_is_private(context, dt) ||
1,598✔
3116
                            exec_context_with_rootfs(context) ||
13✔
3117
                            FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE))
13✔
3118
                                continue;
1,572✔
3119

3120
                        private_path = path_join(params->prefix[dt], "private", i->path);
13✔
3121
                        if (!private_path)
13✔
3122
                                return -ENOMEM;
3123

3124
                        path = path_join(params->prefix[dt], i->path);
13✔
3125
                        if (!path)
13✔
3126
                                return -ENOMEM;
3127

3128
                        r = strv_consume_pair(&symlinks, TAKE_PTR(private_path), TAKE_PTR(path));
13✔
3129
                        if (r < 0)
13✔
3130
                                return r;
3131
                }
3132

3133
        /* We make the host's os-release available via a symlink, so that we can copy it atomically
3134
         * and readers will never get a half-written version. Note that, while the paths specified here are
3135
         * absolute, when they are processed in namespace.c they will be made relative automatically, i.e.:
3136
         * 'os-release -> .os-release-stage/os-release' is what will be created. */
3137
        if (setup_os_release_symlink) {
2,007✔
3138
                r = strv_extend_many(
7✔
3139
                                &symlinks,
3140
                                "/run/host/.os-release-stage/os-release",
3141
                                "/run/host/os-release");
3142
                if (r < 0)
7✔
3143
                        return r;
3144
        }
3145

3146
        *ret_symlinks = TAKE_PTR(symlinks);
2,007✔
3147

3148
        return 0;
2,007✔
3149
}
3150

3151
static bool insist_on_sandboxing(
×
3152
                const ExecContext *context,
3153
                const char *root_dir,
3154
                const char *root_image,
3155
                const BindMount *bind_mounts,
3156
                size_t n_bind_mounts) {
3157

3158
        assert(context);
×
3159
        assert(n_bind_mounts == 0 || bind_mounts);
×
3160

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

3165
        if (context->n_temporary_filesystems > 0)
×
3166
                return true;
3167

3168
        if (root_dir || root_image)
×
3169
                return true;
3170

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

3174
        if (context->dynamic_user)
×
3175
                return true;
3176

3177
        if (context->n_extension_images > 0 || !strv_isempty(context->extension_directories))
×
3178
                return true;
3179

3180
        /* If there are any bind mounts set that don't map back onto themselves, fs namespacing becomes
3181
         * essential. */
3182
        FOREACH_ARRAY(i, bind_mounts, n_bind_mounts)
×
3183
                if (!path_equal(i->source, i->destination))
×
3184
                        return true;
3185

3186
        if (context->log_namespace)
×
3187
                return true;
×
3188

3189
        return false;
3190
}
3191

3192
static int setup_ephemeral(
2,007✔
3193
                const ExecContext *context,
3194
                ExecRuntime *runtime,
3195
                char **root_image,            /* both input and output! modified if ephemeral logic enabled */
3196
                char **root_directory,        /* ditto */
3197
                char **reterr_path) {
3198

3199
        _cleanup_close_ int fd = -EBADF;
2,007✔
3200
        _cleanup_free_ char *new_root = NULL;
2,007✔
3201
        int r;
2,007✔
3202

3203
        assert(context);
2,007✔
3204
        assert(runtime);
2,007✔
3205
        assert(root_image);
2,007✔
3206
        assert(root_directory);
2,007✔
3207

3208
        if (!*root_image && !*root_directory)
2,007✔
3209
                return 0;
3210

3211
        if (!runtime->ephemeral_copy)
8✔
3212
                return 0;
3213

3214
        assert(runtime->ephemeral_storage_socket[0] >= 0);
×
3215
        assert(runtime->ephemeral_storage_socket[1] >= 0);
×
3216

3217
        new_root = strdup(runtime->ephemeral_copy);
×
3218
        if (!new_root)
×
3219
                return log_oom_debug();
×
3220

3221
        r = posix_lock(runtime->ephemeral_storage_socket[0], LOCK_EX);
×
3222
        if (r < 0)
×
3223
                return log_debug_errno(r, "Failed to lock ephemeral storage socket: %m");
×
3224

3225
        CLEANUP_POSIX_UNLOCK(runtime->ephemeral_storage_socket[0]);
×
3226

3227
        fd = receive_one_fd(runtime->ephemeral_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
×
3228
        if (fd >= 0)
×
3229
                /* We got an fd! That means ephemeral has already been set up, so nothing to do here. */
3230
                return 0;
3231
        if (fd != -EAGAIN)
×
3232
                return log_debug_errno(fd, "Failed to receive file descriptor queued on ephemeral storage socket: %m");
×
3233

3234
        if (*root_image) {
×
3235
                log_debug("Making ephemeral copy of %s to %s", *root_image, new_root);
×
3236

3237
                fd = copy_file(*root_image, new_root, O_EXCL, 0600,
×
3238
                               COPY_LOCK_BSD|COPY_REFLINK|COPY_CRTIME|COPY_NOCOW_AFTER);
3239
                if (fd < 0) {
×
3240
                        *reterr_path = strdup(*root_image);
×
3241
                        return log_debug_errno(fd, "Failed to copy image %s to %s: %m",
×
3242
                                               *root_image, new_root);
3243
                }
3244
        } else {
3245
                assert(*root_directory);
×
3246

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

3249
                fd = btrfs_subvol_snapshot_at(
×
3250
                                AT_FDCWD, *root_directory,
3251
                                AT_FDCWD, new_root,
3252
                                BTRFS_SNAPSHOT_FALLBACK_COPY |
3253
                                BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
3254
                                BTRFS_SNAPSHOT_RECURSIVE |
3255
                                BTRFS_SNAPSHOT_LOCK_BSD);
3256
                if (fd < 0) {
×
3257
                        *reterr_path = strdup(*root_directory);
×
3258
                        return log_debug_errno(fd, "Failed to snapshot directory %s to %s: %m",
×
3259
                                               *root_directory, new_root);
3260
                }
3261
        }
3262

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

3267
        if (*root_image)
×
3268
                free_and_replace(*root_image, new_root);
×
3269
        else {
3270
                assert(*root_directory);
×
3271
                free_and_replace(*root_directory, new_root);
×
3272
        }
3273

3274
        return 1;
3275
}
3276

3277
static int verity_settings_prepare(
7✔
3278
                VeritySettings *verity,
3279
                const char *root_image,
3280
                const void *root_hash,
3281
                size_t root_hash_size,
3282
                const char *root_hash_path,
3283
                const void *root_hash_sig,
3284
                size_t root_hash_sig_size,
3285
                const char *root_hash_sig_path,
3286
                const char *verity_data_path) {
3287

3288
        int r;
7✔
3289

3290
        assert(verity);
7✔
3291

3292
        if (root_hash) {
7✔
3293
                void *d;
4✔
3294

3295
                d = memdup(root_hash, root_hash_size);
4✔
3296
                if (!d)
4✔
3297
                        return -ENOMEM;
7✔
3298

3299
                free_and_replace(verity->root_hash, d);
4✔
3300
                verity->root_hash_size = root_hash_size;
4✔
3301
                verity->designator = PARTITION_ROOT;
4✔
3302
        }
3303

3304
        if (root_hash_sig) {
7✔
3305
                void *d;
×
3306

3307
                d = memdup(root_hash_sig, root_hash_sig_size);
×
3308
                if (!d)
×
3309
                        return -ENOMEM;
7✔
3310

3311
                free_and_replace(verity->root_hash_sig, d);
×
3312
                verity->root_hash_sig_size = root_hash_sig_size;
×
3313
                verity->designator = PARTITION_ROOT;
×
3314
        }
3315

3316
        if (verity_data_path) {
7✔
3317
                r = free_and_strdup(&verity->data_path, verity_data_path);
×
3318
                if (r < 0)
×
3319
                        return r;
3320
        }
3321

3322
        r = verity_settings_load(
7✔
3323
                        verity,
3324
                        root_image,
3325
                        root_hash_path,
3326
                        root_hash_sig_path);
3327
        if (r < 0)
7✔
3328
                return log_debug_errno(r, "Failed to load root hash: %m");
×
3329

3330
        return 0;
3331
}
3332

3333
static int pick_versions(
2,009✔
3334
                const ExecContext *context,
3335
                const ExecParameters *params,
3336
                char **ret_root_image,
3337
                char **ret_root_directory,
3338
                char **reterr_path) {
3339

3340
        int r;
2,009✔
3341

3342
        assert(context);
2,009✔
3343
        assert(params);
2,009✔
3344
        assert(ret_root_image);
2,009✔
3345
        assert(ret_root_directory);
2,009✔
3346

3347
        if (context->root_image) {
2,009✔
3348
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
8✔
3349

3350
                r = path_pick(/* toplevel_path= */ NULL,
16✔
3351
                              /* toplevel_fd= */ AT_FDCWD,
3352
                              context->root_image,
8✔
3353
                              &pick_filter_image_raw,
3354
                              PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3355
                              &result);
3356
                if (r < 0) {
8✔
3357
                        *reterr_path = strdup(context->root_image);
1✔
3358
                        return r;
1✔
3359
                }
3360

3361
                if (!result.path) {
7✔
3362
                        *reterr_path = strdup(context->root_image);
×
3363
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_image);
×
3364
                }
3365

3366
                *ret_root_image = TAKE_PTR(result.path);
7✔
3367
                *ret_root_directory = NULL;
7✔
3368
                return r;
7✔
3369
        }
3370

3371
        if (context->root_directory) {
2,001✔
3372
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
2✔
3373

3374
                r = path_pick(/* toplevel_path= */ NULL,
4✔
3375
                              /* toplevel_fd= */ AT_FDCWD,
3376
                              context->root_directory,
2✔
3377
                              &pick_filter_image_dir,
3378
                              PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3379
                              &result);
3380
                if (r < 0) {
2✔
3381
                        *reterr_path = strdup(context->root_directory);
×
3382
                        return r;
×
3383
                }
3384

3385
                if (!result.path) {
2✔
3386
                        *reterr_path = strdup(context->root_directory);
1✔
3387
                        return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_directory);
1✔
3388
                }
3389

3390
                *ret_root_image = NULL;
1✔
3391
                *ret_root_directory = TAKE_PTR(result.path);
1✔
3392
                return r;
1✔
3393
        }
3394

3395
        *ret_root_image = *ret_root_directory = NULL;
1,999✔
3396
        return 0;
1,999✔
3397
}
3398

3399
static int apply_mount_namespace(
2,009✔
3400
                ExecCommandFlags command_flags,
3401
                const ExecContext *context,
3402
                const ExecParameters *params,
3403
                ExecRuntime *runtime,
3404
                const char *memory_pressure_path,
3405
                bool needs_sandboxing,
3406
                char **reterr_path,
3407
                uid_t exec_directory_uid,
3408
                gid_t exec_directory_gid) {
3409

3410
        _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
2,009✔
3411
        _cleanup_strv_free_ char **empty_directories = NULL, **symlinks = NULL,
2,009✔
3412
                        **read_write_paths_cleanup = NULL;
×
3413
        _cleanup_free_ char *creds_path = NULL, *incoming_dir = NULL, *propagate_dir = NULL,
×
3414
                *private_namespace_dir = NULL, *host_os_release_stage = NULL, *root_image = NULL, *root_dir = NULL;
2,009✔
3415
        const char *tmp_dir = NULL, *var_tmp_dir = NULL;
2,009✔
3416
        char **read_write_paths;
2,009✔
3417
        bool setup_os_release_symlink;
2,009✔
3418
        BindMount *bind_mounts = NULL;
2,009✔
3419
        size_t n_bind_mounts = 0;
2,009✔
3420
        int r;
2,009✔
3421

3422
        assert(context);
2,009✔
3423
        assert(params);
2,009✔
3424
        assert(runtime);
2,009✔
3425

3426
        CLEANUP_ARRAY(bind_mounts, n_bind_mounts, bind_mount_free_many);
2,009✔
3427

3428
        if (params->flags & EXEC_APPLY_CHROOT) {
2,009✔
3429
                r = pick_versions(
2,009✔
3430
                                context,
3431
                                params,
3432
                                &root_image,
3433
                                &root_dir,
3434
                                reterr_path);
3435
                if (r < 0)
2,009✔
3436
                        return r;
3437

3438
                r = setup_ephemeral(
2,007✔
3439
                                context,
3440
                                runtime,
3441
                                &root_image,
3442
                                &root_dir,
3443
                                reterr_path);
3444
                if (r < 0)
2,007✔
3445
                        return r;
3446
        }
3447

3448
        r = compile_bind_mounts(context, params, exec_directory_uid, exec_directory_gid, &bind_mounts, &n_bind_mounts, &empty_directories);
2,007✔
3449
        if (r < 0)
2,007✔
3450
                return r;
3451

3452
        /* We need to make the pressure path writable even if /sys/fs/cgroups is made read-only, as the
3453
         * service will need to write to it in order to start the notifications. */
3454
        if (exec_is_cgroup_mount_read_only(context) && memory_pressure_path && !streq(memory_pressure_path, "/dev/null")) {
2,007✔
3455
                read_write_paths_cleanup = strv_copy(context->read_write_paths);
1,134✔
3456
                if (!read_write_paths_cleanup)
1,134✔
3457
                        return -ENOMEM;
3458

3459
                r = strv_extend(&read_write_paths_cleanup, memory_pressure_path);
1,134✔
3460
                if (r < 0)
1,134✔
3461
                        return r;
3462

3463
                read_write_paths = read_write_paths_cleanup;
1,134✔
3464
        } else
3465
                read_write_paths = context->read_write_paths;
873✔
3466

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

3472
                if (context->private_tmp == PRIVATE_TMP_CONNECTED && runtime->shared) {
2,007✔
3473
                        if (streq_ptr(runtime->shared->tmp_dir, RUN_SYSTEMD_EMPTY))
323✔
3474
                                tmp_dir = runtime->shared->tmp_dir;
3475
                        else if (runtime->shared->tmp_dir)
323✔
3476
                                tmp_dir = strjoina(runtime->shared->tmp_dir, "/tmp");
1,615✔
3477

3478
                        if (streq_ptr(runtime->shared->var_tmp_dir, RUN_SYSTEMD_EMPTY))
323✔
3479
                                var_tmp_dir = runtime->shared->var_tmp_dir;
3480
                        else if (runtime->shared->var_tmp_dir)
323✔
3481
                                var_tmp_dir = strjoina(runtime->shared->var_tmp_dir, "/tmp");
1,615✔
3482
                }
3483
        }
3484

3485
        /* Symlinks (exec dirs, os-release) are set up after other mounts, before they are made read-only. */
3486
        setup_os_release_symlink = needs_sandboxing && exec_context_get_effective_mount_apivfs(context) && (root_dir || root_image);
2,007✔
3487
        r = compile_symlinks(context, params, setup_os_release_symlink, &symlinks);
2,007✔
3488
        if (r < 0)
2,007✔
3489
                return r;
3490

3491
        if (context->mount_propagation_flag == MS_SHARED)
2,007✔
3492
                log_debug("shared mount propagation hidden by other fs namespacing unit settings: ignoring");
×
3493

3494
        r = exec_context_get_credential_directory(context, params, params->unit_id, &creds_path);
2,007✔
3495
        if (r < 0)
2,007✔
3496
                return r;
3497

3498
        if (params->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
2,007✔
3499
                propagate_dir = path_join("/run/systemd/propagate/", params->unit_id);
1,980✔
3500
                if (!propagate_dir)
1,980✔
3501
                        return -ENOMEM;
3502

3503
                incoming_dir = strdup("/run/systemd/incoming");
1,980✔
3504
                if (!incoming_dir)
1,980✔
3505
                        return -ENOMEM;
3506

3507
                private_namespace_dir = strdup("/run/systemd");
1,980✔
3508
                if (!private_namespace_dir)
1,980✔
3509
                        return -ENOMEM;
3510

3511
                /* If running under a different root filesystem, propagate the host's os-release. We make a
3512
                 * copy rather than just bind mounting it, so that it can be updated on soft-reboot. */
3513
                if (setup_os_release_symlink) {
1,980✔
3514
                        host_os_release_stage = strdup("/run/systemd/propagate/.os-release-stage");
7✔
3515
                        if (!host_os_release_stage)
7✔
3516
                                return -ENOMEM;
3517
                }
3518
        } else {
3519
                assert(params->runtime_scope == RUNTIME_SCOPE_USER);
27✔
3520

3521
                if (asprintf(&private_namespace_dir, "/run/user/" UID_FMT "/systemd", geteuid()) < 0)
27✔
3522
                        return -ENOMEM;
3523

3524
                if (setup_os_release_symlink) {
27✔
3525
                        if (asprintf(&host_os_release_stage,
×
3526
                                     "/run/user/" UID_FMT "/systemd/propagate/.os-release-stage",
3527
                                     geteuid()) < 0)
3528
                                return -ENOMEM;
3529
                }
3530
        }
3531

3532
        if (root_image) {
2,007✔
3533
                r = verity_settings_prepare(
14✔
3534
                        &verity,
3535
                        root_image,
3536
                        context->root_hash, context->root_hash_size, context->root_hash_path,
7✔
3537
                        context->root_hash_sig, context->root_hash_sig_size, context->root_hash_sig_path,
7✔
3538
                        context->root_verity);
7✔
3539
                if (r < 0)
7✔
3540
                        return r;
3541
        }
3542

3543
        NamespaceParameters parameters = {
×
3544
                .runtime_scope = params->runtime_scope,
2,007✔
3545

3546
                .root_directory = root_dir,
3547
                .root_image = root_image,
3548
                .root_image_options = context->root_image_options,
2,007✔
3549
                .root_image_policy = context->root_image_policy ?: &image_policy_service,
2,007✔
3550

3551
                .read_write_paths = read_write_paths,
3552
                .read_only_paths = needs_sandboxing ? context->read_only_paths : NULL,
2,007✔
3553
                .inaccessible_paths = needs_sandboxing ? context->inaccessible_paths : NULL,
2,007✔
3554

3555
                .exec_paths = needs_sandboxing ? context->exec_paths : NULL,
2,007✔
3556
                .no_exec_paths = needs_sandboxing ? context->no_exec_paths : NULL,
2,007✔
3557

3558
                .empty_directories = empty_directories,
3559
                .symlinks = symlinks,
3560

3561
                .bind_mounts = bind_mounts,
3562
                .n_bind_mounts = n_bind_mounts,
3563

3564
                .temporary_filesystems = context->temporary_filesystems,
2,007✔
3565
                .n_temporary_filesystems = context->n_temporary_filesystems,
2,007✔
3566

3567
                .mount_images = context->mount_images,
2,007✔
3568
                .n_mount_images = context->n_mount_images,
2,007✔
3569
                .mount_image_policy = context->mount_image_policy ?: &image_policy_service,
2,007✔
3570

3571
                .tmp_dir = tmp_dir,
3572
                .var_tmp_dir = var_tmp_dir,
3573

3574
                .creds_path = creds_path,
3575
                .log_namespace = context->log_namespace,
2,007✔
3576
                .mount_propagation_flag = context->mount_propagation_flag,
2,007✔
3577

3578
                .verity = &verity,
3579

3580
                .extension_images = context->extension_images,
2,007✔
3581
                .n_extension_images = context->n_extension_images,
2,007✔
3582
                .extension_image_policy = context->extension_image_policy ?: &image_policy_sysext,
2,007✔
3583
                .extension_directories = context->extension_directories,
2,007✔
3584

3585
                .propagate_dir = propagate_dir,
3586
                .incoming_dir = incoming_dir,
3587
                .private_namespace_dir = private_namespace_dir,
3588
                .host_notify_socket = params->notify_socket,
2,007✔
3589
                .notify_socket_path = exec_get_private_notify_socket_path(context, params, needs_sandboxing),
2,007✔
3590
                .host_os_release_stage = host_os_release_stage,
3591

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

3597
                .protect_control_groups = needs_sandboxing ? exec_get_protect_control_groups(context) : PROTECT_CONTROL_GROUPS_NO,
2,007✔
3598
                .protect_kernel_tunables = needs_sandboxing && context->protect_kernel_tunables,
2,007✔
3599
                .protect_kernel_modules = needs_sandboxing && context->protect_kernel_modules,
2,007✔
3600
                .protect_kernel_logs = needs_sandboxing && context->protect_kernel_logs,
2,007✔
3601

3602
                .private_dev = needs_sandboxing && context->private_devices,
2,007✔
3603
                .private_network = needs_sandboxing && exec_needs_network_namespace(context),
2,007✔
3604
                .private_ipc = needs_sandboxing && exec_needs_ipc_namespace(context),
2,007✔
3605
                .private_pids = needs_sandboxing && exec_needs_pid_namespace(context) ? context->private_pids : PRIVATE_PIDS_NO,
2,007✔
3606
                .private_tmp = needs_sandboxing ? context->private_tmp : PRIVATE_TMP_NO,
2,007✔
3607
                .private_var_tmp = needs_sandboxing ? context->private_var_tmp : PRIVATE_TMP_NO,
2,007✔
3608

3609
                .mount_apivfs = needs_sandboxing && exec_context_get_effective_mount_apivfs(context),
2,007✔
3610
                .bind_log_sockets = needs_sandboxing && exec_context_get_effective_bind_log_sockets(context),
2,007✔
3611

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

3615
                .protect_home = needs_sandboxing ? context->protect_home : PROTECT_HOME_NO,
2,007✔
3616
                .protect_hostname = needs_sandboxing ? context->protect_hostname : PROTECT_HOSTNAME_NO,
2,007✔
3617
                .protect_system = needs_sandboxing ? context->protect_system : PROTECT_SYSTEM_NO,
2,007✔
3618
                .protect_proc = needs_sandboxing ? context->protect_proc : PROTECT_PROC_DEFAULT,
2,007✔
3619
                .proc_subset = needs_sandboxing ? context->proc_subset : PROC_SUBSET_ALL,
2,007✔
3620
        };
3621

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

3643
                log_debug("Failed to set up namespace, assuming containerized execution and ignoring.");
×
3644
                return 0;
×
3645
        }
3646

3647
        return r;
3648
}
3649

3650
static int apply_working_directory(
9,573✔
3651
                const ExecContext *context,
3652
                const ExecParameters *params,
3653
                ExecRuntime *runtime,
3654
                const char *pwent_home,
3655
                char * const *env) {
3656

3657
        const char *wd;
9,573✔
3658
        int r;
9,573✔
3659

3660
        assert(context);
9,573✔
3661
        assert(params);
9,573✔
3662
        assert(runtime);
9,573✔
3663

3664
        if (context->working_directory_home) {
9,573✔
3665
                /* Preferably use the data from $HOME, in case it was updated by a PAM module */
3666
                wd = strv_env_get(env, "HOME");
102✔
3667
                if (!wd) {
102✔
3668
                        /* If that's not available, use the data from the struct passwd entry: */
3669
                        if (!pwent_home)
1✔
3670
                                return -ENXIO;
3671

3672
                        wd = pwent_home;
3673
                }
3674
        } else
3675
                wd = empty_to_root(context->working_directory);
9,471✔
3676

3677
        if (params->flags & EXEC_APPLY_CHROOT)
9,573✔
3678
                r = RET_NERRNO(chdir(wd));
9,573✔
3679
        else {
3680
                _cleanup_close_ int dfd = -EBADF;
×
3681

3682
                r = chase(wd,
×
3683
                          runtime->ephemeral_copy ?: context->root_directory,
×
3684
                          CHASE_PREFIX_ROOT|CHASE_AT_RESOLVE_IN_ROOT,
3685
                          /* ret_path= */ NULL,
3686
                          &dfd);
3687
                if (r >= 0)
×
3688
                        r = RET_NERRNO(fchdir(dfd));
×
3689
        }
3690
        return context->working_directory_missing_ok ? 0 : r;
9,573✔
3691
}
3692

3693
static int apply_root_directory(
9,573✔
3694
                const ExecContext *context,
3695
                const ExecParameters *params,
3696
                ExecRuntime *runtime,
3697
                const bool needs_mount_ns,
3698
                int *exit_status) {
3699

3700
        assert(context);
9,573✔
3701
        assert(params);
9,573✔
3702
        assert(runtime);
9,573✔
3703
        assert(exit_status);
9,573✔
3704

3705
        if (params->flags & EXEC_APPLY_CHROOT)
9,573✔
3706
                if (!needs_mount_ns && context->root_directory)
9,573✔
3707
                        if (chroot(runtime->ephemeral_copy ?: context->root_directory) < 0) {
×
3708
                                *exit_status = EXIT_CHROOT;
×
3709
                                return -errno;
×
3710
                        }
3711

3712
        return 0;
3713
}
3714

3715
static int setup_keyring(
9,599✔
3716
                const ExecContext *context,
3717
                const ExecParameters *p,
3718
                uid_t uid,
3719
                gid_t gid) {
3720

3721
        key_serial_t keyring;
9,599✔
3722
        int r = 0;
9,599✔
3723
        uid_t saved_uid;
9,599✔
3724
        gid_t saved_gid;
9,599✔
3725

3726
        assert(context);
9,599✔
3727
        assert(p);
9,599✔
3728

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

3736
        if (context->keyring_mode == EXEC_KEYRING_INHERIT)
9,599✔
3737
                return 0;
3738

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

3744
        saved_uid = getuid();
8,634✔
3745
        saved_gid = getgid();
8,634✔
3746

3747
        if (gid_is_valid(gid) && gid != saved_gid) {
8,634✔
3748
                if (setregid(gid, -1) < 0)
1,752✔
3749
                        return log_error_errno(errno, "Failed to change GID for user keyring: %m");
×
3750
        }
3751

3752
        if (uid_is_valid(uid) && uid != saved_uid) {
8,634✔
3753
                if (setreuid(uid, -1) < 0) {
1,749✔
3754
                        r = log_error_errno(errno, "Failed to change UID for user keyring: %m");
×
3755
                        goto out;
×
3756
                }
3757
        }
3758

3759
        keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
8,634✔
3760
        if (keyring == -1) {
8,634✔
3761
                if (errno == ENOSYS)
×
3762
                        log_debug_errno(errno, "Kernel keyring not supported, ignoring.");
×
3763
                else if (ERRNO_IS_PRIVILEGE(errno))
×
3764
                        log_debug_errno(errno, "Kernel keyring access prohibited, ignoring.");
×
3765
                else if (errno == EDQUOT)
×
3766
                        log_debug_errno(errno, "Out of kernel keyrings to allocate, ignoring.");
×
3767
                else
3768
                        r = log_error_errno(errno, "Setting up kernel keyring failed: %m");
×
3769

3770
                goto out;
×
3771
        }
3772

3773
        /* When requested link the user keyring into the session keyring. */
3774
        if (context->keyring_mode == EXEC_KEYRING_SHARED) {
8,634✔
3775

3776
                if (keyctl(KEYCTL_LINK,
935✔
3777
                           KEY_SPEC_USER_KEYRING,
3778
                           KEY_SPEC_SESSION_KEYRING, 0, 0) < 0) {
3779
                        r = log_error_errno(errno, "Failed to link user keyring into session keyring: %m");
×
3780
                        goto out;
×
3781
                }
3782
        }
3783

3784
        /* Restore uid/gid back */
3785
        if (uid_is_valid(uid) && uid != saved_uid) {
8,634✔
3786
                if (setreuid(saved_uid, -1) < 0) {
1,749✔
3787
                        r = log_error_errno(errno, "Failed to change UID back for user keyring: %m");
×
3788
                        goto out;
×
3789
                }
3790
        }
3791

3792
        if (gid_is_valid(gid) && gid != saved_gid) {
8,634✔
3793
                if (setregid(saved_gid, -1) < 0)
1,752✔
3794
                        return log_error_errno(errno, "Failed to change GID back for user keyring: %m");
×
3795
        }
3796

3797
        /* Populate they keyring with the invocation ID by default, as original saved_uid. */
3798
        if (!sd_id128_is_null(p->invocation_id)) {
8,634✔
3799
                key_serial_t key;
8,634✔
3800

3801
                key = add_key("user",
17,268✔
3802
                              "invocation_id",
3803
                              &p->invocation_id,
8,634✔
3804
                              sizeof(p->invocation_id),
3805
                              KEY_SPEC_SESSION_KEYRING);
3806
                if (key == -1)
8,634✔
3807
                        log_debug_errno(errno, "Failed to add invocation ID to keyring, ignoring: %m");
×
3808
                else {
3809
                        if (keyctl(KEYCTL_SETPERM, key,
8,634✔
3810
                                   KEY_POS_VIEW|KEY_POS_READ|KEY_POS_SEARCH|
3811
                                   KEY_USR_VIEW|KEY_USR_READ|KEY_USR_SEARCH, 0, 0) < 0)
3812
                                r = log_error_errno(errno, "Failed to restrict invocation ID permission: %m");
×
3813
                }
3814
        }
3815

3816
out:
8,634✔
3817
        /* Revert back uid & gid for the last time, and exit */
3818
        /* no extra logging, as only the first already reported error matters */
3819
        if (getuid() != saved_uid)
8,634✔
3820
                (void) setreuid(saved_uid, -1);
×
3821

3822
        if (getgid() != saved_gid)
8,634✔
3823
                (void) setregid(saved_gid, -1);
×
3824

3825
        return r;
3826
}
3827

3828
static void append_socket_pair(int *array, size_t *n, const int pair[static 2]) {
34,795✔
3829
        assert(array);
34,795✔
3830
        assert(n);
34,795✔
3831
        assert(pair);
34,795✔
3832

3833
        if (pair[0] >= 0)
34,795✔
3834
                array[(*n)++] = pair[0];
190✔
3835
        if (pair[1] >= 0)
34,795✔
3836
                array[(*n)++] = pair[1];
190✔
3837
}
34,795✔
3838

3839
static int close_remaining_fds(
11,557✔
3840
                const ExecParameters *params,
3841
                const ExecRuntime *runtime,
3842
                int socket_fd,
3843
                const int *fds,
3844
                size_t n_fds) {
11,557✔
3845

3846
        size_t n_dont_close = 0;
11,557✔
3847
        int dont_close[n_fds + 17];
11,557✔
3848

3849
        assert(params);
11,557✔
3850
        assert(runtime);
11,557✔
3851

3852
        if (params->stdin_fd >= 0)
11,557✔
3853
                dont_close[n_dont_close++] = params->stdin_fd;
538✔
3854
        if (params->stdout_fd >= 0)
11,557✔
3855
                dont_close[n_dont_close++] = params->stdout_fd;
538✔
3856
        if (params->stderr_fd >= 0)
11,557✔
3857
                dont_close[n_dont_close++] = params->stderr_fd;
538✔
3858

3859
        if (socket_fd >= 0)
11,557✔
3860
                dont_close[n_dont_close++] = socket_fd;
17✔
3861
        if (n_fds > 0) {
11,557✔
3862
                memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
11,557✔
3863
                n_dont_close += n_fds;
11,557✔
3864
        }
3865

3866
        append_socket_pair(dont_close, &n_dont_close, runtime->ephemeral_storage_socket);
11,557✔
3867

3868
        if (runtime->shared) {
11,557✔
3869
                append_socket_pair(dont_close, &n_dont_close, runtime->shared->netns_storage_socket);
11,557✔
3870
                append_socket_pair(dont_close, &n_dont_close, runtime->shared->ipcns_storage_socket);
11,557✔
3871
        }
3872

3873
        if (runtime->dynamic_creds) {
11,557✔
3874
                if (runtime->dynamic_creds->user)
11,557✔
3875
                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->user->storage_socket);
62✔
3876
                if (runtime->dynamic_creds->group)
11,557✔
3877
                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->group->storage_socket);
62✔
3878
        }
3879

3880
        if (params->user_lookup_fd >= 0)
11,557✔
3881
                dont_close[n_dont_close++] = params->user_lookup_fd;
11,557✔
3882

3883
        if (params->handoff_timestamp_fd >= 0)
11,557✔
3884
                dont_close[n_dont_close++] = params->handoff_timestamp_fd;
11,557✔
3885

3886
        if (params->pidref_transport_fd >= 0)
11,557✔
3887
                dont_close[n_dont_close++] = params->pidref_transport_fd;
10,505✔
3888

3889
        assert(n_dont_close <= ELEMENTSOF(dont_close));
11,557✔
3890

3891
        return close_all_fds(dont_close, n_dont_close);
11,557✔
3892
}
3893

3894
static int send_user_lookup(
11,555✔
3895
                const char *unit_id,
3896
                int user_lookup_fd,
3897
                uid_t uid,
3898
                gid_t gid) {
3899

3900
        assert(unit_id);
11,555✔
3901

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

3906
        if (user_lookup_fd < 0)
11,555✔
3907
                return 0;
3908

3909
        if (!uid_is_valid(uid) && !gid_is_valid(gid))
11,555✔
3910
                return 0;
3911

3912
        if (writev(user_lookup_fd,
2,665✔
3913
               (struct iovec[]) {
2,665✔
3914
                           IOVEC_MAKE(&uid, sizeof(uid)),
3915
                           IOVEC_MAKE(&gid, sizeof(gid)),
3916
                           IOVEC_MAKE_STRING(unit_id) }, 3) < 0)
2,665✔
3917
                return -errno;
×
3918

3919
        return 0;
2,665✔
3920
}
3921

3922
static int acquire_home(const ExecContext *c, const char **home, char **ret_buf) {
11,555✔
3923
        int r;
11,555✔
3924

3925
        assert(c);
11,555✔
3926
        assert(home);
11,555✔
3927
        assert(ret_buf);
11,555✔
3928

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

3931
        if (*home) /* Already acquired from get_fixed_user()? */
11,555✔
3932
                return 0;
3933

3934
        if (!c->working_directory_home)
8,957✔
3935
                return 0;
3936

3937
        if (c->dynamic_user || (c->user && is_this_me(c->user) <= 0))
×
3938
                return -EADDRNOTAVAIL;
×
3939

3940
        r = get_home_dir(ret_buf);
×
3941
        if (r < 0)
×
3942
                return r;
3943

3944
        *home = *ret_buf;
×
3945
        return 1;
×
3946
}
3947

3948
static int compile_suggested_paths(const ExecContext *c, const ExecParameters *p, char ***ret) {
62✔
3949
        _cleanup_strv_free_ char ** list = NULL;
62✔
3950
        int r;
62✔
3951

3952
        assert(c);
62✔
3953
        assert(p);
62✔
3954
        assert(ret);
62✔
3955

3956
        assert(c->dynamic_user);
62✔
3957

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

3962
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
372✔
3963

3964
                if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(t))
310✔
3965
                        continue;
62✔
3966

3967
                if (!p->prefix[t])
248✔
3968
                        continue;
×
3969

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

3973
                        if (exec_directory_is_private(c, t))
15✔
3974
                                e = path_join(p->prefix[t], "private", c->directories[t].items[i].path);
13✔
3975
                        else
3976
                                e = path_join(p->prefix[t], c->directories[t].items[i].path);
2✔
3977
                        if (!e)
15✔
3978
                                return -ENOMEM;
3979

3980
                        r = strv_consume(&list, e);
15✔
3981
                        if (r < 0)
15✔
3982
                                return r;
3983
                }
3984
        }
3985

3986
        *ret = TAKE_PTR(list);
62✔
3987

3988
        return 0;
62✔
3989
}
3990

3991
static int exec_context_cpu_affinity_from_numa(const ExecContext *c, CPUSet *ret) {
2✔
3992
        _cleanup_(cpu_set_reset) CPUSet s = {};
2✔
3993
        int r;
2✔
3994

3995
        assert(c);
2✔
3996
        assert(ret);
2✔
3997

3998
        if (!c->numa_policy.nodes.set) {
2✔
3999
                log_debug("Can't derive CPU affinity mask from NUMA mask because NUMA mask is not set, ignoring");
×
4000
                return 0;
×
4001
        }
4002

4003
        r = numa_to_cpu_set(&c->numa_policy, &s);
2✔
4004
        if (r < 0)
2✔
4005
                return r;
4006

4007
        cpu_set_reset(ret);
2✔
4008

4009
        return cpu_set_add_all(ret, &s);
2✔
4010
}
4011

4012
static int add_shifted_fd(int *fds, size_t fds_size, size_t *n_fds, int *fd) {
44,244✔
4013
        int r;
44,244✔
4014

4015
        assert(fds);
44,244✔
4016
        assert(n_fds);
44,244✔
4017
        assert(*n_fds < fds_size);
44,244✔
4018
        assert(fd);
44,244✔
4019

4020
        if (*fd < 0)
44,244✔
4021
               return 0;
44,244✔
4022

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

4027
                r = fcntl(*fd, F_DUPFD_CLOEXEC, 3 + (int) *n_fds);
9,573✔
4028
                if (r < 0)
9,573✔
4029
                        return -errno;
×
4030

4031
                close_and_replace(*fd, r);
9,573✔
4032
        }
4033

4034
        fds[(*n_fds)++] = *fd;
21,525✔
4035
        return 1;
21,525✔
4036
}
4037

4038
static int connect_unix_harder(const OpenFile *of, int ofd) {
1✔
4039
        static const int socket_types[] = { SOCK_DGRAM, SOCK_STREAM, SOCK_SEQPACKET };
1✔
4040

4041
        union sockaddr_union addr = {
1✔
4042
                .un.sun_family = AF_UNIX,
4043
        };
4044
        socklen_t sa_len;
1✔
4045
        int r;
1✔
4046

4047
        assert(of);
1✔
4048
        assert(ofd >= 0);
1✔
4049

4050
        r = sockaddr_un_set_path(&addr.un, FORMAT_PROC_FD_PATH(ofd));
1✔
4051
        if (r < 0)
1✔
4052
                return log_debug_errno(r, "Failed to set sockaddr for '%s': %m", of->path);
×
4053
        sa_len = r;
1✔
4054

4055
        FOREACH_ELEMENT(i, socket_types) {
2✔
4056
                _cleanup_close_ int fd = -EBADF;
2✔
4057

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

4062
                r = RET_NERRNO(connect(fd, &addr.sa, sa_len));
2✔
4063
                if (r >= 0)
1✔
4064
                        return TAKE_FD(fd);
1✔
4065
                if (r != -EPROTOTYPE)
1✔
4066
                        return log_debug_errno(r, "Failed to connect to socket for '%s': %m", of->path);
×
4067
        }
4068

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

4072
static int get_open_file_fd(const OpenFile *of) {
5✔
4073
        _cleanup_close_ int fd = -EBADF, ofd = -EBADF;
5✔
4074
        struct stat st;
5✔
4075

4076
        assert(of);
5✔
4077

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

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

4085
        if (S_ISSOCK(st.st_mode)) {
3✔
4086
                fd = connect_unix_harder(of, ofd);
1✔
4087
                if (fd < 0)
1✔
4088
                        return fd;
4089

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

4093
                log_debug("Opened socket '%s' as fd %d.", of->path, fd);
1✔
4094
        } else {
4095
                int flags = FLAGS_SET(of->flags, OPENFILE_READ_ONLY) ? O_RDONLY : O_RDWR;
2✔
4096
                if (FLAGS_SET(of->flags, OPENFILE_APPEND))
2✔
4097
                        flags |= O_APPEND;
×
4098
                else if (FLAGS_SET(of->flags, OPENFILE_TRUNCATE))
2✔
4099
                        flags |= O_TRUNC;
×
4100

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

4105
                log_debug("Opened file '%s' as fd %d.", of->path, fd);
2✔
4106
        }
4107

4108
        return TAKE_FD(fd);
4109
}
4110

4111
static int collect_open_file_fds(ExecParameters *p, size_t *n_fds) {
11,558✔
4112
        assert(p);
11,558✔
4113
        assert(n_fds);
11,558✔
4114

4115
        LIST_FOREACH(open_files, of, p->open_files) {
11,558✔
4116
                _cleanup_close_ int fd = -EBADF;
11,563✔
4117

4118
                fd = get_open_file_fd(of);
5✔
4119
                if (fd < 0) {
5✔
4120
                        if (FLAGS_SET(of->flags, OPENFILE_GRACEFUL)) {
2✔
4121
                                log_full_errno(fd == -ENOENT || ERRNO_IS_NEG_PRIVILEGE(fd) ? LOG_DEBUG : LOG_WARNING,
1✔
4122
                                               fd,
4123
                                               "Failed to get OpenFile= file descriptor for '%s', ignoring: %m",
4124
                                               of->path);
4125
                                continue;
1✔
4126
                        }
4127

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

4131
                if (!GREEDY_REALLOC(p->fds, *n_fds + 1))
3✔
4132
                        return log_oom();
×
4133

4134
                if (strv_extend(&p->fd_names, of->fdname) < 0)
3✔
4135
                        return log_oom();
×
4136

4137
                p->fds[(*n_fds)++] = TAKE_FD(fd);
3✔
4138
        }
4139

4140
        return 0;
4141
}
4142

4143
static void log_command_line(
9,572✔
4144
                const ExecContext *context,
4145
                const ExecParameters *params,
4146
                const char *msg,
4147
                const char *executable,
4148
                char **argv) {
4149

4150
        assert(context);
9,572✔
4151
        assert(params);
9,572✔
4152
        assert(msg);
9,572✔
4153
        assert(executable);
9,572✔
4154

4155
        if (!DEBUG_LOGGING)
9,572✔
4156
                return;
9,572✔
4157

4158
        _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);
18,494✔
4159

4160
        log_struct(LOG_DEBUG,
17,709✔
4161
                   LOG_ITEM("EXECUTABLE=%s", executable),
4162
                   LOG_EXEC_MESSAGE(params, "%s: %s", msg, strnull(cmdline)),
4163
                   LOG_EXEC_INVOCATION_ID(params));
4164
}
4165

4166
static bool exec_context_needs_cap_sys_admin(const ExecContext *context) {
1,641✔
4167
        assert(context);
1,641✔
4168

4169
        return context->private_users != PRIVATE_USERS_NO ||
3,269✔
4170
               context->private_tmp != PRIVATE_TMP_NO ||
1,628✔
4171
               context->private_devices ||
1,613✔
4172
               context->private_network ||
1,606✔
4173
               context->network_namespace_path ||
1,599✔
4174
               context->private_ipc ||
1,599✔
4175
               context->ipc_namespace_path ||
1,599✔
4176
               context->private_mounts > 0 ||
1,599✔
4177
               context->mount_apivfs > 0 ||
1,589✔
4178
               context->bind_log_sockets > 0 ||
1,589✔
4179
               context->n_bind_mounts > 0 ||
1,589✔
4180
               context->n_temporary_filesystems > 0 ||
1,584✔
4181
               context->root_directory ||
1,584✔
4182
               !strv_isempty(context->extension_directories) ||
1,584✔
4183
               context->protect_system != PROTECT_SYSTEM_NO ||
1,584✔
4184
               context->protect_home != PROTECT_HOME_NO ||
3,153✔
4185
               exec_needs_pid_namespace(context) ||
1,569✔
4186
               context->protect_kernel_tunables ||
1,547✔
4187
               context->protect_kernel_modules ||
1,542✔
4188
               context->protect_kernel_logs ||
3,074✔
4189
               exec_needs_cgroup_mount(context) ||
1,537✔
4190
               context->protect_clock ||
1,537✔
4191
               context->protect_hostname != PROTECT_HOSTNAME_NO ||
1,532✔
4192
               !strv_isempty(context->read_write_paths) ||
1,527✔
4193
               !strv_isempty(context->read_only_paths) ||
1,512✔
4194
               !strv_isempty(context->inaccessible_paths) ||
1,512✔
4195
               !strv_isempty(context->exec_paths) ||
1,512✔
4196
               !strv_isempty(context->no_exec_paths) ||
3,153✔
4197
               context->delegate_namespaces != NAMESPACE_FLAGS_INITIAL;
1,512✔
4198
}
4199

4200
static PrivateUsers exec_context_get_effective_private_users(
9,583✔
4201
                const ExecContext *context,
4202
                const ExecParameters *params) {
4203

4204
        assert(context);
9,583✔
4205
        assert(params);
9,583✔
4206

4207
        if (context->private_users != PRIVATE_USERS_NO)
9,583✔
4208
                return context->private_users;
4209

4210
        /* If any namespace is delegated with DelegateNamespaces=, always set up a user namespace. */
4211
        if (context->delegate_namespaces != NAMESPACE_FLAGS_INITIAL)
9,557✔
4212
                return PRIVATE_USERS_SELF;
3✔
4213

4214
        return PRIVATE_USERS_NO;
4215
}
4216

4217
static bool exec_namespace_is_delegated(
23,339✔
4218
                const ExecContext *context,
4219
                const ExecParameters *params,
4220
                bool have_cap_sys_admin,
4221
                unsigned long namespace) {
4222

4223
        assert(context);
23,339✔
4224
        assert(params);
23,339✔
4225
        assert(namespace != CLONE_NEWUSER);
23,339✔
4226

4227
        /* If we need unprivileged private users, we've already unshared a user namespace by the time we call
4228
         * setup_delegated_namespaces() for the first time so let's make sure we do all other namespace
4229
         * unsharing in the first call to setup_delegated_namespaces() by returning false here. */
4230
        if (!have_cap_sys_admin && exec_context_needs_cap_sys_admin(context))
23,339✔
4231
                return false;
4232

4233
        if (context->delegate_namespaces == NAMESPACE_FLAGS_INITIAL)
23,237✔
4234
                return params->runtime_scope == RUNTIME_SCOPE_USER;
23,169✔
4235

4236
        if (FLAGS_SET(context->delegate_namespaces, namespace))
68✔
4237
                return true;
4238

4239
        /* Various namespaces imply mountns for private procfs/sysfs/cgroupfs instances, which means when
4240
         * those are delegated mountns must be deferred too.
4241
         *
4242
         * The list should stay in sync with exec_needs_mount_namespace(). */
4243
        if (namespace == CLONE_NEWNS)
16✔
4244
                return context->delegate_namespaces & (CLONE_NEWPID|CLONE_NEWCGROUP|CLONE_NEWNET);
4✔
4245

4246
        return false;
4247
}
4248

4249
static int setup_delegated_namespaces(
19,177✔
4250
                const ExecContext *context,
4251
                ExecParameters *params,
4252
                ExecRuntime *runtime,
4253
                bool delegate,
4254
                const char *memory_pressure_path,
4255
                uid_t uid,
4256
                uid_t gid,
4257
                const ExecCommand *command,
4258
                bool needs_sandboxing,
4259
                bool have_cap_sys_admin,
4260
                int *reterr_exit_status) {
4261

4262
        int r;
19,177✔
4263

4264
        /* This function is called twice, once before unsharing the user namespace, and once after unsharing
4265
         * the user namespace. When called before unsharing the user namespace, "delegate" is set to "false".
4266
         * When called after unsharing the user namespace, "delegate" is set to "true". The net effect is
4267
         * that all namespaces that should not be delegated are unshared when this function is called the
4268
         * first time and all namespaces that should be delegated are unshared when this function is called
4269
         * the second time. */
4270

4271
        assert(context);
19,177✔
4272
        assert(params);
19,177✔
4273
        assert(runtime);
19,177✔
4274
        assert(reterr_exit_status);
19,177✔
4275

4276
        if (exec_needs_network_namespace(context) &&
19,296✔
4277
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWNET) == delegate &&
119✔
4278
            runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
60✔
4279

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

4301
        if (exec_needs_ipc_namespace(context) &&
19,188✔
4302
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWIPC) == delegate &&
11✔
4303
            runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
6✔
4304

4305
                if (namespace_type_supported(NAMESPACE_IPC)) {
6✔
4306
                        r = setup_shareable_ns(runtime->shared->ipcns_storage_socket, CLONE_NEWIPC);
6✔
4307
                        if (ERRNO_IS_NEG_PRIVILEGE(r))
6✔
4308
                                log_warning_errno(r, "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m");
×
4309
                        else if (r < 0) {
6✔
4310
                                *reterr_exit_status = EXIT_NAMESPACE;
×
4311
                                return log_error_errno(r, "Failed to set up IPC namespacing: %m");
×
4312
                        } else
4313
                                log_debug("Set up %sIPC namespace", delegate ? "delegated " : "");
8✔
4314
                } else if (context->ipc_namespace_path) {
×
4315
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4316
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "IPCNamespacePath= is not supported, refusing.");
×
4317
                } else
4318
                        log_warning("PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring.");
×
4319
        }
4320

4321
        if (needs_sandboxing && exec_needs_cgroup_namespace(context) &&
19,202✔
4322
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWCGROUP) == delegate) {
25✔
4323
                if (unshare(CLONE_NEWCGROUP) < 0) {
13✔
4324
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4325
                        return log_error_errno(errno, "Failed to set up cgroup namespacing: %m");
×
4326
                }
4327

4328
                log_debug("Set up %scgroup namespace", delegate ? "delegated " : "");
22✔
4329
        }
4330

4331
        /* Unshare a new PID namespace before setting up mounts to ensure /proc/ is mounted with only processes in PID namespace visible.
4332
         * Note PrivatePIDs=yes implies MountAPIVFS=yes so we'll always ensure procfs is remounted. */
4333
        if (needs_sandboxing && exec_needs_pid_namespace(context) &&
19,202✔
4334
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWPID) == delegate) {
25✔
4335
                if (params->pidref_transport_fd < 0) {
15✔
4336
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4337
                        return log_error_errno(SYNTHETIC_ERRNO(ENOTCONN), "PidRef socket is not set up: %m");
×
4338
                }
4339

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

4359
                r = setup_private_pids(context, params);
9✔
4360
                if (r < 0) {
6✔
4361
                        *reterr_exit_status = EXIT_NAMESPACE;
×
4362
                        return log_error_errno(r, "Failed to set up pid namespace: %m");
×
4363
                }
4364

4365
                log_debug("Set up %spid namespace", delegate ? "delegated " : "");
12✔
4366
        }
4367

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

4370
        if (exec_needs_mount_namespace(context, params, runtime) &&
23,174✔
4371
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWNS) == delegate) {
4,006✔
4372
                _cleanup_free_ char *error_path = NULL;
2,009✔
4373

4374
                r = apply_mount_namespace(command->flags,
2,009✔
4375
                                          context,
4376
                                          params,
4377
                                          runtime,
4378
                                          memory_pressure_path,
4379
                                          needs_sandboxing,
4380
                                          &error_path,
4381
                                          uid,
4382
                                          gid);
4383
                if (r < 0) {
2,009✔
4384
                        *reterr_exit_status = EXIT_NAMESPACE;
15✔
4385
                        return log_error_errno(r, "Failed to set up mount namespacing%s%s: %m",
29✔
4386
                                               error_path ? ": " : "", strempty(error_path));
4387
                }
4388

4389
                log_debug("Set up %smount namespace", delegate ? "delegated " : "");
3,960✔
4390
        }
4391

4392
        if (needs_sandboxing &&
38,306✔
4393
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWUTS) == delegate) {
19,153✔
4394
                r = apply_protect_hostname(context, params, reterr_exit_status);
9,575✔
4395
                if (r < 0)
9,575✔
4396
                        return r;
4397
                if (r > 0)
9,575✔
4398
                        log_debug("Set up %sUTS namespace", delegate ? "delegated " : "");
1,325✔
4399
        }
4400

4401
        return 0;
4402
}
4403

4404
static bool exec_context_shall_confirm_spawn(const ExecContext *context) {
×
4405
        assert(context);
×
4406

4407
        if (confirm_spawn_disabled())
×
4408
                return false;
4409

4410
        /* For some reasons units remaining in the same process group
4411
         * as PID 1 fail to acquire the console even if it's not used
4412
         * by any process. So skip the confirmation question for them. */
4413
        return !context->same_pgrp;
×
4414
}
4415

4416
static int exec_context_named_iofds(
11,558✔
4417
                const ExecContext *c,
4418
                const ExecParameters *p,
4419
                int named_iofds[static 3]) {
4420

4421
        size_t targets;
11,558✔
4422
        const char* stdio_fdname[3];
11,558✔
4423
        size_t n_fds;
11,558✔
4424

4425
        assert(c);
11,558✔
4426
        assert(p);
11,558✔
4427
        assert(named_iofds);
11,558✔
4428

4429
        targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
11,558✔
4430
                  (c->std_output == EXEC_OUTPUT_NAMED_FD) +
11,558✔
4431
                  (c->std_error == EXEC_OUTPUT_NAMED_FD);
11,558✔
4432

4433
        for (size_t i = 0; i < 3; i++)
46,232✔
4434
                stdio_fdname[i] = exec_context_fdname(c, i);
34,674✔
4435

4436
        n_fds = p->n_storage_fds + p->n_socket_fds + p->n_extra_fds;
11,558✔
4437

4438
        for (size_t i = 0; i < n_fds  && targets > 0; i++)
11,558✔
4439
                if (named_iofds[STDIN_FILENO] < 0 &&
×
4440
                    c->std_input == EXEC_INPUT_NAMED_FD &&
×
4441
                    stdio_fdname[STDIN_FILENO] &&
×
4442
                    streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
×
4443

4444
                        named_iofds[STDIN_FILENO] = p->fds[i];
×
4445
                        targets--;
×
4446

4447
                } else if (named_iofds[STDOUT_FILENO] < 0 &&
×
4448
                           c->std_output == EXEC_OUTPUT_NAMED_FD &&
×
4449
                           stdio_fdname[STDOUT_FILENO] &&
×
4450
                           streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
×
4451

4452
                        named_iofds[STDOUT_FILENO] = p->fds[i];
×
4453
                        targets--;
×
4454

4455
                } else if (named_iofds[STDERR_FILENO] < 0 &&
×
4456
                           c->std_error == EXEC_OUTPUT_NAMED_FD &&
×
4457
                           stdio_fdname[STDERR_FILENO] &&
×
4458
                           streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
×
4459

4460
                        named_iofds[STDERR_FILENO] = p->fds[i];
×
4461
                        targets--;
×
4462
                }
4463

4464
        return targets == 0 ? 0 : -ENOENT;
11,558✔
4465
}
4466

4467
static void exec_shared_runtime_close(ExecSharedRuntime *shared) {
9,573✔
4468
        if (!shared)
9,573✔
4469
                return;
4470

4471
        safe_close_pair(shared->netns_storage_socket);
9,573✔
4472
        safe_close_pair(shared->ipcns_storage_socket);
9,573✔
4473
}
4474

4475
static void exec_runtime_close(ExecRuntime *rt) {
9,573✔
4476
        if (!rt)
9,573✔
4477
                return;
4478

4479
        safe_close_pair(rt->ephemeral_storage_socket);
9,573✔
4480

4481
        exec_shared_runtime_close(rt->shared);
9,573✔
4482
        dynamic_creds_close(rt->dynamic_creds);
9,573✔
4483
}
4484

4485
static void exec_params_close(ExecParameters *p) {
9,573✔
4486
        if (!p)
9,573✔
4487
                return;
4488

4489
        p->stdin_fd = safe_close(p->stdin_fd);
9,573✔
4490
        p->stdout_fd = safe_close(p->stdout_fd);
9,573✔
4491
        p->stderr_fd = safe_close(p->stderr_fd);
9,573✔
4492
}
4493

4494
static int exec_fd_mark_hot(
9,575✔
4495
                const ExecContext *c,
4496
                ExecParameters *p,
4497
                bool hot,
4498
                int *reterr_exit_status) {
4499

4500
        assert(c);
9,575✔
4501
        assert(p);
9,575✔
4502

4503
        if (p->exec_fd < 0)
9,575✔
4504
                return 0;
9,575✔
4505

4506
        uint8_t x = hot;
286✔
4507

4508
        if (write(p->exec_fd, &x, sizeof(x)) < 0) {
286✔
4509
                if (reterr_exit_status)
×
4510
                        *reterr_exit_status = EXIT_EXEC;
×
4511
                return log_error_errno(errno, "Failed to mark exec_fd as %s: %m", hot ? "hot" : "cold");
×
4512
        }
4513

4514
        return 1;
4515
}
4516

4517
static int send_handoff_timestamp(
9,572✔
4518
                const ExecContext *c,
4519
                ExecParameters *p,
4520
                int *reterr_exit_status) {
4521

4522
        assert(c);
9,572✔
4523
        assert(p);
9,572✔
4524

4525
        if (p->handoff_timestamp_fd < 0)
9,572✔
4526
                return 0;
9,572✔
4527

4528
        dual_timestamp dt;
9,572✔
4529
        dual_timestamp_now(&dt);
9,572✔
4530

4531
        if (write(p->handoff_timestamp_fd, (const usec_t[2]) { dt.realtime, dt.monotonic }, sizeof(usec_t) * 2) < 0) {
9,572✔
4532
                if (reterr_exit_status)
×
4533
                        *reterr_exit_status = EXIT_EXEC;
×
4534
                return log_error_errno(errno, "Failed to send handoff timestamp: %m");
×
4535
        }
4536

4537
        return 1;
9,572✔
4538
}
4539

4540
static void prepare_terminal(
11,555✔
4541
                const ExecContext *context,
4542
                ExecParameters *p) {
4543

4544
        _cleanup_close_ int lock_fd = -EBADF;
11,555✔
4545

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

4549
        assert(context);
11,555✔
4550
        assert(p);
11,555✔
4551

4552
        /* We only try to reset things if we there's the chance our stdout points to a TTY */
4553
        if (!(is_terminal_output(context->std_output) ||
11,555✔
4554
              (context->std_output == EXEC_OUTPUT_INHERIT && is_terminal_input(context->std_input)) ||
10,935✔
4555
              context->std_output == EXEC_OUTPUT_NAMED_FD ||
4556
              p->stdout_fd >= 0))
10,935✔
4557
                return;
10,397✔
4558

4559
        /* Let's explicitly determine whether to reset via ANSI sequences or not, taking our ExecContext
4560
         * information into account */
4561
        bool use_ansi = exec_context_shall_ansi_seq_reset(context);
1,158✔
4562

4563
        if (context->tty_reset) {
1,158✔
4564
                /* When we are resetting the TTY, then let's create a lock first, to synchronize access. This
4565
                 * in particular matters as concurrent resets and the TTY size ANSI DSR logic done by the
4566
                 * exec_context_apply_tty_size() below might interfere */
4567
                lock_fd = lock_dev_console();
164✔
4568
                if (lock_fd < 0)
164✔
4569
                        log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
×
4570

4571
                /* We explicitly control whether to send ansi sequences or not here, since we want to consult
4572
                 * the env vars explicitly configured in the ExecContext, rather than our own environment
4573
                 * block. */
4574
                (void) terminal_reset_defensive(STDOUT_FILENO, use_ansi ? TERMINAL_RESET_FORCE_ANSI_SEQ : TERMINAL_RESET_AVOID_ANSI_SEQ);
167✔
4575
        }
4576

4577
        (void) exec_context_apply_tty_size(context, STDIN_FILENO, STDOUT_FILENO, /* tty_path= */ NULL);
1,158✔
4578

4579
        if (use_ansi)
1,158✔
4580
                (void) osc_context_open_service(p->unit_id, p->invocation_id, /* ret_seq= */ NULL);
161✔
4581
}
4582

4583
int exec_invoke(
11,558✔
4584
                const ExecCommand *command,
4585
                const ExecContext *context,
4586
                ExecParameters *params,
4587
                ExecRuntime *runtime,
4588
                const CGroupContext *cgroup_context,
4589
                int *exit_status) {
11,558✔
4590

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

4629
        assert(command);
11,558✔
4630
        assert(context);
11,558✔
4631
        assert(params);
11,558✔
4632
        assert(runtime);
11,558✔
4633
        assert(cgroup_context);
11,558✔
4634
        assert(exit_status);
11,558✔
4635

4636
        LOG_CONTEXT_PUSH_EXEC(context, params);
33,120✔
4637

4638
        /* Explicitly test for CVE-2021-4034 inspired invocations */
4639
        if (!command->path || strv_isempty(command->argv)) {
11,558✔
4640
                *exit_status = EXIT_EXEC;
×
4641
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid command line arguments.");
×
4642
        }
4643

4644
        if (context->std_input == EXEC_INPUT_SOCKET ||
11,558✔
4645
            context->std_output == EXEC_OUTPUT_SOCKET ||
11,547✔
4646
            context->std_error == EXEC_OUTPUT_SOCKET) {
11,541✔
4647

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

4651
                if (params->n_socket_fds == 0)
17✔
4652
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Got no socket.");
×
4653

4654
                socket_fd = params->fds[0];
17✔
4655
                n_storage_fds = n_socket_fds = n_extra_fds = 0;
17✔
4656
        } else {
4657
                n_socket_fds = params->n_socket_fds;
11,541✔
4658
                n_storage_fds = params->n_storage_fds;
11,541✔
4659
                n_extra_fds = params->n_extra_fds;
11,541✔
4660
        }
4661
        n_fds = n_socket_fds + n_storage_fds + n_extra_fds;
11,558✔
4662

4663
        r = exec_context_named_iofds(context, params, named_iofds);
11,558✔
4664
        if (r < 0)
11,558✔
4665
                return log_error_errno(r, "Failed to load a named file descriptor: %m");
×
4666

4667
        rename_process_from_path(command->path);
11,558✔
4668

4669
        /* We reset exactly these signals, since they are the only ones we set to SIG_IGN in the main
4670
         * daemon. All others we leave untouched because we set them to SIG_DFL or a valid handler initially,
4671
         * both of which will be demoted to SIG_DFL. */
4672
        (void) default_signals(SIGNALS_CRASH_HANDLER,
11,558✔
4673
                               SIGNALS_IGNORE);
4674

4675
        if (context->ignore_sigpipe)
11,558✔
4676
                (void) ignore_signals(SIGPIPE);
11,189✔
4677

4678
        r = reset_signal_mask();
11,558✔
4679
        if (r < 0) {
11,558✔
4680
                *exit_status = EXIT_SIGNAL_MASK;
×
4681
                return log_error_errno(r, "Failed to set process signal mask: %m");
×
4682
        }
4683

4684
        if (params->idle_pipe)
11,558✔
4685
                do_idle_pipe_dance(params->idle_pipe);
161✔
4686

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

4692
        log_forget_fds();
11,558✔
4693
        log_set_open_when_needed(true);
11,558✔
4694
        log_settle_target();
11,558✔
4695

4696
        /* In case anything used libc syslog(), close this here, too */
4697
        closelog();
11,558✔
4698

4699
        r = collect_open_file_fds(params, &n_fds);
11,558✔
4700
        if (r < 0) {
11,558✔
4701
                *exit_status = EXIT_FDS;
1✔
4702
                return log_error_errno(r, "Failed to get OpenFile= file descriptors: %m");
1✔
4703
        }
4704

4705
        int keep_fds[n_fds + 4];
11,557✔
4706
        memcpy_safe(keep_fds, params->fds, n_fds * sizeof(int));
11,557✔
4707
        n_keep_fds = n_fds;
11,557✔
4708

4709
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->exec_fd);
11,557✔
4710
        if (r < 0) {
11,557✔
4711
                *exit_status = EXIT_FDS;
×
4712
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
4713
        }
4714

4715
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->handoff_timestamp_fd);
11,557✔
4716
        if (r < 0) {
11,557✔
4717
                *exit_status = EXIT_FDS;
×
4718
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
4719
        }
4720

4721
#if HAVE_LIBBPF
4722
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->bpf_restrict_fs_map_fd);
11,557✔
4723
        if (r < 0) {
11,557✔
4724
                *exit_status = EXIT_FDS;
×
4725
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
4726
        }
4727
#endif
4728

4729
        r = close_remaining_fds(params, runtime, socket_fd, keep_fds, n_keep_fds);
11,557✔
4730
        if (r < 0) {
11,557✔
4731
                *exit_status = EXIT_FDS;
×
4732
                return log_error_errno(r, "Failed to close unwanted file descriptors: %m");
×
4733
        }
4734

4735
        if (!context->same_pgrp &&
22,245✔
4736
            setsid() < 0) {
10,688✔
4737
                *exit_status = EXIT_SETSID;
×
4738
                return log_error_errno(errno, "Failed to create new process session: %m");
×
4739
        }
4740

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

4750
        if (params->shall_confirm_spawn && exec_context_shall_confirm_spawn(context)) {
11,557✔
4751
                _cleanup_free_ char *cmdline = NULL;
×
4752

4753
                cmdline = quote_command_line(command->argv, SHELL_ESCAPE_EMPTY);
×
4754
                if (!cmdline) {
×
4755
                        *exit_status = EXIT_MEMORY;
×
4756
                        return log_oom();
×
4757
                }
4758

4759
                r = ask_for_confirmation(context, params, cmdline);
×
4760
                if (r != CONFIRM_EXECUTE) {
×
4761
                        if (r == CONFIRM_PRETEND_SUCCESS) {
×
4762
                                *exit_status = EXIT_SUCCESS;
×
4763
                                return 0;
×
4764
                        }
4765

4766
                        *exit_status = EXIT_CONFIRM;
×
4767
                        return log_error_errno(SYNTHETIC_ERRNO(ECANCELED), "Execution cancelled by the user.");
×
4768
                }
4769
        }
4770

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

4782
        if (context->dynamic_user && runtime->dynamic_creds) {
11,619✔
4783
                _cleanup_strv_free_ char **suggested_paths = NULL;
62✔
4784

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

4792
                r = compile_suggested_paths(context, params, &suggested_paths);
62✔
4793
                if (r < 0) {
62✔
4794
                        *exit_status = EXIT_MEMORY;
×
4795
                        return log_oom();
×
4796
                }
4797

4798
                r = dynamic_creds_realize(runtime->dynamic_creds, suggested_paths, &uid, &gid);
62✔
4799
                if (r < 0) {
62✔
4800
                        *exit_status = EXIT_USER;
×
4801
                        if (r == -EILSEQ)
×
4802
                                return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
×
4803
                                                       "Failed to update dynamic user credentials: User or group with specified name already exists.");
4804
                        return log_error_errno(r, "Failed to update dynamic user credentials: %m");
×
4805
                }
4806

4807
                if (!uid_is_valid(uid)) {
62✔
4808
                        *exit_status = EXIT_USER;
×
4809
                        return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "UID validation failed for \""UID_FMT"\".", uid);
×
4810
                }
4811

4812
                if (!gid_is_valid(gid)) {
62✔
4813
                        *exit_status = EXIT_USER;
×
4814
                        return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "GID validation failed for \""GID_FMT"\".", gid);
×
4815
                }
4816

4817
                if (runtime->dynamic_creds->user)
62✔
4818
                        username = runtime->dynamic_creds->user->name;
62✔
4819

4820
        } else {
4821
                const char *u;
11,495✔
4822

4823
                if (context->user)
11,495✔
4824
                        u = context->user;
4825
                else if (context->pam_name || FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL)) {
8,960✔
4826
                        /* If PAM is enabled but no user name is explicitly selected, then use our own one. */
4827
                        own_user = getusername_malloc();
65✔
4828
                        if (!own_user) {
65✔
4829
                                *exit_status = EXIT_USER;
×
4830
                                return log_error_errno(r, "Failed to determine my own user ID: %m");
×
4831
                        }
4832
                        u = own_user;
4833
                } else
4834
                        u = NULL;
4835

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

4851
                if (context->group) {
11,493✔
4852
                        r = get_fixed_group(context->group, &groupname, &gid);
11✔
4853
                        if (r < 0) {
11✔
4854
                                *exit_status = EXIT_GROUP;
×
4855
                                return log_error_errno(r, "Failed to determine group credentials: %m");
×
4856
                        }
4857
                }
4858
        }
4859

4860
        /* Initialize user supplementary groups and get SupplementaryGroups= ones */
4861
        ngids = get_supplementary_groups(context, username, gid, &gids);
11,555✔
4862
        if (ngids < 0) {
11,555✔
4863
                *exit_status = EXIT_GROUP;
×
4864
                return log_error_errno(ngids, "Failed to determine supplementary groups: %m");
×
4865
        }
4866

4867
        r = send_user_lookup(params->unit_id, params->user_lookup_fd, uid, gid);
11,555✔
4868
        if (r < 0) {
11,555✔
4869
                *exit_status = EXIT_USER;
×
4870
                return log_error_errno(r, "Failed to send user credentials to PID1: %m");
×
4871
        }
4872

4873
        params->user_lookup_fd = safe_close(params->user_lookup_fd);
11,555✔
4874

4875
        r = acquire_home(context, &pwent_home, &home_buffer);
11,555✔
4876
        if (r < 0) {
11,555✔
4877
                *exit_status = EXIT_CHDIR;
×
4878
                return log_error_errno(r, "Failed to determine $HOME for the invoking user: %m");
×
4879
        }
4880

4881
        /* If a socket is connected to STDIN/STDOUT/STDERR, we must drop O_NONBLOCK */
4882
        if (socket_fd >= 0)
11,555✔
4883
                (void) fd_nonblock(socket_fd, false);
17✔
4884

4885
        /* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields.
4886
         * Hence we need to migrate to the target cgroup from init.scope before connecting to journald */
4887
        if (params->cgroup_path) {
11,555✔
4888
                _cleanup_free_ char *p = NULL;
11,555✔
4889

4890
                r = exec_params_get_cgroup_path(params, cgroup_context, &p);
11,555✔
4891
                if (r < 0) {
11,555✔
4892
                        *exit_status = EXIT_CGROUP;
×
4893
                        return log_error_errno(r, "Failed to acquire cgroup path: %m");
×
4894
                }
4895

4896
                r = cg_attach(p, 0);
11,555✔
4897
                if (r == -EUCLEAN) {
11,555✔
4898
                        *exit_status = EXIT_CGROUP;
×
4899
                        return log_error_errno(r,
×
4900
                                               "Failed to attach process to cgroup '%s', "
4901
                                               "because the cgroup or one of its parents or "
4902
                                               "siblings is in the threaded mode.", p);
4903
                }
4904
                if (r < 0) {
11,555✔
4905
                        *exit_status = EXIT_CGROUP;
×
4906
                        return log_error_errno(r, "Failed to attach to cgroup %s: %m", p);
×
4907
                }
4908
        }
4909

4910
        if (context->network_namespace_path && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
11,555✔
4911
                r = open_shareable_ns_path(runtime->shared->netns_storage_socket, context->network_namespace_path, CLONE_NEWNET);
×
4912
                if (r < 0) {
×
4913
                        *exit_status = EXIT_NETWORK;
×
4914
                        return log_error_errno(r, "Failed to open network namespace path %s: %m", context->network_namespace_path);
×
4915
                }
4916
        }
4917

4918
        if (context->ipc_namespace_path && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
11,555✔
4919
                r = open_shareable_ns_path(runtime->shared->ipcns_storage_socket, context->ipc_namespace_path, CLONE_NEWIPC);
×
4920
                if (r < 0) {
×
4921
                        *exit_status = EXIT_NAMESPACE;
×
4922
                        return log_error_errno(r, "Failed to open IPC namespace path %s: %m", context->ipc_namespace_path);
×
4923
                }
4924
        }
4925

4926
        r = setup_input(context, params, socket_fd, named_iofds);
11,555✔
4927
        if (r < 0) {
11,555✔
4928
                *exit_status = EXIT_STDIN;
×
4929
                return log_error_errno(r, "Failed to set up standard input: %m");
×
4930
        }
4931

4932
        _cleanup_free_ char *fname = NULL;
25✔
4933
        r = path_extract_filename(command->path, &fname);
11,555✔
4934
        if (r < 0) {
11,555✔
4935
                *exit_status = EXIT_STDOUT;
×
4936
                return log_error_errno(r, "Failed to extract filename from path %s: %m", command->path);
×
4937
        }
4938

4939
        r = setup_output(context, params, STDOUT_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
11,555✔
4940
        if (r < 0) {
11,555✔
4941
                *exit_status = EXIT_STDOUT;
×
4942
                return log_error_errno(r, "Failed to set up standard output: %m");
×
4943
        }
4944

4945
        r = setup_output(context, params, STDERR_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
11,555✔
4946
        if (r < 0) {
11,555✔
4947
                *exit_status = EXIT_STDERR;
×
4948
                return log_error_errno(r, "Failed to set up standard error output: %m");
×
4949
        }
4950

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

4957
        if (context->oom_score_adjust_set) {
11,555✔
4958
                /* When we can't make this change due to EPERM, then let's silently skip over it. User
4959
                 * namespaces prohibit write access to this file, and we shouldn't trip up over that. */
4960
                r = set_oom_score_adjust(context->oom_score_adjust);
1,308✔
4961
                if (ERRNO_IS_NEG_PRIVILEGE(r))
1,308✔
4962
                        log_debug_errno(r, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
×
4963
                else if (r < 0) {
1,308✔
4964
                        *exit_status = EXIT_OOM_ADJUST;
×
4965
                        return log_error_errno(r, "Failed to adjust OOM setting: %m");
×
4966
                }
4967
        }
4968

4969
        if (context->coredump_filter_set) {
11,555✔
4970
                r = set_coredump_filter(context->coredump_filter);
2✔
4971
                if (ERRNO_IS_NEG_PRIVILEGE(r))
2✔
4972
                        log_debug_errno(r, "Failed to adjust coredump_filter, ignoring: %m");
×
4973
                else if (r < 0) {
2✔
4974
                        *exit_status = EXIT_LIMITS;
×
4975
                        return log_error_errno(r, "Failed to adjust coredump_filter: %m");
×
4976
                }
4977
        }
4978

4979
        if (context->cpu_sched_set) {
11,555✔
4980
                struct sched_attr attr = {
×
4981
                        .size = sizeof(attr),
4982
                        .sched_policy = context->cpu_sched_policy,
×
4983
                        .sched_priority = context->cpu_sched_priority,
×
4984
                        .sched_flags = context->cpu_sched_reset_on_fork ? SCHED_FLAG_RESET_ON_FORK : 0,
×
4985
                };
4986

4987
                r = sched_setattr(/* pid= */ 0, &attr, /* flags= */ 0);
×
4988
                if (r < 0) {
×
4989
                        *exit_status = EXIT_SETSCHEDULER;
×
4990
                        return log_error_errno(errno, "Failed to set up CPU scheduling: %m");
×
4991
                }
4992
        }
4993

4994
        /*
4995
         * Set nice value _after_ the call to sched_setattr() because struct sched_attr includes sched_nice
4996
         * which we do not set, thus it will clobber any previously set nice value. Scheduling policy might
4997
         * be reasonably set together with nice value e.g. in case of SCHED_BATCH (see sched(7)).
4998
         * It would be ideal to set both with the same call, but we cannot easily do so because of all the
4999
         * extra logic in setpriority_closest().
5000
         */
5001
        if (context->nice_set) {
11,555✔
5002
                r = setpriority_closest(context->nice);
15✔
5003
                if (r < 0) {
15✔
5004
                        *exit_status = EXIT_NICE;
×
5005
                        return log_error_errno(r, "Failed to set up process scheduling priority (nice level): %m");
×
5006
                }
5007
        }
5008

5009
        if (context->cpu_affinity_from_numa || context->cpu_set.set) {
11,555✔
5010
                _cleanup_(cpu_set_reset) CPUSet converted_cpu_set = {};
2✔
5011
                const CPUSet *cpu_set;
2✔
5012

5013
                if (context->cpu_affinity_from_numa) {
2✔
5014
                        r = exec_context_cpu_affinity_from_numa(context, &converted_cpu_set);
2✔
5015
                        if (r < 0) {
2✔
5016
                                *exit_status = EXIT_CPUAFFINITY;
×
5017
                                return log_error_errno(r, "Failed to derive CPU affinity mask from NUMA mask: %m");
×
5018
                        }
5019

5020
                        cpu_set = &converted_cpu_set;
5021
                } else
5022
                        cpu_set = &context->cpu_set;
×
5023

5024
                if (sched_setaffinity(0, cpu_set->allocated, cpu_set->set) < 0) {
2✔
5025
                        *exit_status = EXIT_CPUAFFINITY;
×
5026
                        return log_error_errno(errno, "Failed to set up CPU affinity: %m");
×
5027
                }
5028
        }
5029

5030
        if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) {
11,555✔
5031
                r = apply_numa_policy(&context->numa_policy);
19✔
5032
                if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
19✔
5033
                        log_debug_errno(r, "NUMA support not available, ignoring.");
×
5034
                else if (r < 0) {
19✔
5035
                        *exit_status = EXIT_NUMA_POLICY;
2✔
5036
                        return log_error_errno(r, "Failed to set NUMA memory policy: %m");
2✔
5037
                }
5038
        }
5039

5040
        if (context->ioprio_set)
11,553✔
5041
                if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
7✔
5042
                        *exit_status = EXIT_IOPRIO;
×
5043
                        return log_error_errno(errno, "Failed to set up IO scheduling priority: %m");
×
5044
                }
5045

5046
        if (context->timer_slack_nsec != NSEC_INFINITY)
11,553✔
5047
                if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
×
5048
                        *exit_status = EXIT_TIMERSLACK;
×
5049
                        return log_error_errno(errno, "Failed to set up timer slack: %m");
×
5050
                }
5051

5052
        if (context->personality != PERSONALITY_INVALID) {
11,553✔
5053
                r = safe_personality(context->personality);
×
5054
                if (r < 0) {
×
5055
                        *exit_status = EXIT_PERSONALITY;
×
5056
                        return log_error_errno(r, "Failed to set up execution domain (personality): %m");
×
5057
                }
5058
        }
5059

5060
        if (context->memory_ksm >= 0)
11,553✔
5061
                if (prctl(PR_SET_MEMORY_MERGE, context->memory_ksm, 0, 0, 0) < 0) {
×
5062
                        if (ERRNO_IS_NOT_SUPPORTED(errno))
×
5063
                                log_debug_errno(errno, "KSM support not available, ignoring.");
×
5064
                        else {
5065
                                *exit_status = EXIT_KSM;
×
5066
                                return log_error_errno(errno, "Failed to set KSM: %m");
×
5067
                        }
5068
                }
5069

5070
#if ENABLE_UTMP
5071
        if (context->utmp_id) {
11,553✔
5072
                _cleanup_free_ char *username_alloc = NULL;
166✔
5073

5074
                if (!username && context->utmp_mode == EXEC_UTMP_USER) {
166✔
5075
                        username_alloc = uid_to_name(uid_is_valid(uid) ? uid : saved_uid);
1✔
5076
                        if (!username_alloc) {
1✔
5077
                                *exit_status = EXIT_USER;
×
5078
                                return log_oom();
×
5079
                        }
5080
                }
5081

5082
                const char *line = context->tty_path ?
×
5083
                        (path_startswith(context->tty_path, "/dev/") ?: context->tty_path) :
166✔
5084
                        NULL;
5085
                utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
166✔
5086
                                      line,
5087
                                      context->utmp_mode == EXEC_UTMP_INIT  ? INIT_PROCESS :
166✔
5088
                                      context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
7✔
5089
                                      USER_PROCESS,
5090
                                      username ?: username_alloc);
166✔
5091
        }
5092
#endif
5093

5094
        if (uid_is_valid(uid)) {
11,553✔
5095
                r = chown_terminal(STDIN_FILENO, uid);
2,660✔
5096
                if (r < 0) {
2,660✔
5097
                        *exit_status = EXIT_STDIN;
×
5098
                        return log_error_errno(r, "Failed to change ownership of terminal: %m");
×
5099
                }
5100
        }
5101

5102
        /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted
5103
         * from it. */
5104
        needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
11,553✔
5105

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

5112
                if (params->flags & EXEC_CGROUP_DELEGATE) {
11,553✔
5113
                        _cleanup_free_ char *p = NULL;
669✔
5114

5115
                        r = cg_set_access(params->cgroup_path, uid, gid);
669✔
5116
                        if (r < 0) {
669✔
5117
                                *exit_status = EXIT_CGROUP;
×
5118
                                return log_error_errno(r, "Failed to adjust control group access: %m");
×
5119
                        }
5120

5121
                        r = exec_params_get_cgroup_path(params, cgroup_context, &p);
669✔
5122
                        if (r < 0) {
669✔
5123
                                *exit_status = EXIT_CGROUP;
×
5124
                                return log_error_errno(r, "Failed to acquire cgroup path: %m");
×
5125
                        }
5126
                        if (r > 0) {
669✔
5127
                                r = cg_set_access_recursive(p, uid, gid);
328✔
5128
                                if (r < 0) {
328✔
5129
                                        *exit_status = EXIT_CGROUP;
×
5130
                                        return log_error_errno(r, "Failed to adjust control subgroup access: %m");
×
5131
                                }
5132
                        }
5133
                }
5134

5135
                if (is_pressure_supported() > 0) {
11,553✔
5136
                        if (cgroup_context_want_memory_pressure(cgroup_context)) {
11,553✔
5137
                                r = cg_get_path("memory", params->cgroup_path, "memory.pressure", &memory_pressure_path);
11,154✔
5138
                                if (r < 0) {
11,154✔
5139
                                        *exit_status = EXIT_MEMORY;
×
5140
                                        return log_oom();
×
5141
                                }
5142

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

5171
        needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
11,553✔
5172

5173
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
69,313✔
5174
                r = setup_exec_directory(context, params, uid, gid, dt, needs_mount_namespace, exit_status);
57,761✔
5175
                if (r < 0)
57,761✔
5176
                        return log_error_errno(r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
1✔
5177
        }
5178

5179
        r = exec_setup_credentials(context, params, params->unit_id, uid, gid);
11,552✔
5180
        if (r < 0) {
9,599✔
5181
                *exit_status = EXIT_CREDENTIALS;
×
5182
                return log_error_errno(r, "Failed to set up credentials: %m");
×
5183
        }
5184

5185
        r = build_environment(
9,599✔
5186
                        context,
5187
                        params,
5188
                        cgroup_context,
5189
                        n_fds,
5190
                        pwent_home,
5191
                        username,
5192
                        shell,
5193
                        journal_stream_dev,
5194
                        journal_stream_ino,
5195
                        memory_pressure_path,
5196
                        needs_sandboxing,
5197
                        &our_env);
5198
        if (r < 0) {
9,599✔
5199
                *exit_status = EXIT_MEMORY;
×
5200
                return log_oom();
×
5201
        }
5202

5203
        r = build_pass_environment(context, &pass_env);
9,599✔
5204
        if (r < 0) {
9,599✔
5205
                *exit_status = EXIT_MEMORY;
×
5206
                return log_oom();
×
5207
        }
5208

5209
        /* The $PATH variable is set to the default path in params->environment. However, this is overridden
5210
         * if user-specified fields have $PATH set. The intention is to also override $PATH if the unit does
5211
         * not specify PATH but the unit has ExecSearchPath. */
5212
        if (!strv_isempty(context->exec_search_path)) {
9,599✔
5213
                _cleanup_free_ char *joined = NULL;
×
5214

5215
                joined = strv_join(context->exec_search_path, ":");
×
5216
                if (!joined) {
×
5217
                        *exit_status = EXIT_MEMORY;
×
5218
                        return log_oom();
×
5219
                }
5220

5221
                r = strv_env_assign(&joined_exec_search_path, "PATH", joined);
×
5222
                if (r < 0) {
×
5223
                        *exit_status = EXIT_MEMORY;
×
5224
                        return log_oom();
×
5225
                }
5226
        }
5227

5228
        accum_env = strv_env_merge(params->environment,
9,599✔
5229
                                   our_env,
5230
                                   joined_exec_search_path,
5231
                                   pass_env,
5232
                                   context->environment,
5233
                                   params->files_env);
5234
        if (!accum_env) {
9,599✔
5235
                *exit_status = EXIT_MEMORY;
×
5236
                return log_oom();
×
5237
        }
5238
        accum_env = strv_env_clean(accum_env);
9,599✔
5239

5240
        (void) umask(context->umask);
9,599✔
5241

5242
        r = setup_keyring(context, params, uid, gid);
9,599✔
5243
        if (r < 0) {
9,599✔
5244
                *exit_status = EXIT_KEYRING;
×
5245
                return log_error_errno(r, "Failed to set up kernel keyring: %m");
×
5246
        }
5247

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

5252
        uint64_t capability_ambient_set = context->capability_ambient_set;
9,599✔
5253

5254
        /* Check CAP_SYS_ADMIN before we enter user namespace to see if we can mount /proc even though its masked. */
5255
        have_cap_sys_admin = have_effective_cap(CAP_SYS_ADMIN) > 0;
9,599✔
5256

5257
        if (needs_sandboxing) {
9,599✔
5258
                /* MAC enablement checks need to be done before a new mount ns is created, as they rely on
5259
                 * /sys being present. The actual MAC context application will happen later, as late as
5260
                 * possible, to avoid impacting our own code paths. */
5261

5262
#if HAVE_SELINUX
5263
                use_selinux = mac_selinux_use();
5264
#endif
5265
#if ENABLE_SMACK
5266
                use_smack = mac_smack_use();
9,599✔
5267
#endif
5268
#if HAVE_APPARMOR
5269
                if (mac_apparmor_use()) {
5270
                        r = dlopen_libapparmor();
5271
                        if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r))
5272
                                log_warning_errno(r, "Failed to load libapparmor, ignoring: %m");
5273
                        use_apparmor = r >= 0;
5274
                }
5275
#endif
5276
        }
5277

5278
        if (needs_sandboxing) {
9,599✔
5279
                int which_failed;
9,599✔
5280

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

5284
                r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed);
9,599✔
5285
                if (r < 0) {
9,599✔
5286
                        *exit_status = EXIT_LIMITS;
×
5287
                        return log_error_errno(r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
×
5288
                }
5289
        }
5290

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

5295
                /* All fds passed in the fds array will be closed in the pam child process. */
5296
                r = setup_pam(context, params, username, uid, gid, &accum_env, params->fds, n_fds, params->exec_fd);
400✔
5297
                if (r < 0) {
400✔
5298
                        *exit_status = EXIT_PAM;
×
5299
                        return log_error_errno(r, "Failed to set up PAM session: %m");
×
5300
                }
5301

5302
                /* PAM modules might have set some ambient caps. Query them here and merge them into
5303
                 * the caps we want to set in the end, so that we don't end up unsetting them. */
5304
                uint64_t ambient_after_pam;
400✔
5305
                r = capability_get_ambient(&ambient_after_pam);
400✔
5306
                if (r < 0) {
400✔
5307
                        *exit_status = EXIT_CAPABILITIES;
×
5308
                        return log_error_errno(r, "Failed to query ambient caps: %m");
×
5309
                }
5310

5311
                capability_ambient_set |= ambient_after_pam;
400✔
5312

5313
                ngids_after_pam = getgroups_alloc(&gids_after_pam);
400✔
5314
                if (ngids_after_pam < 0) {
400✔
5315
                        *exit_status = EXIT_GROUP;
×
5316
                        return log_error_errno(ngids_after_pam, "Failed to obtain groups after setting up PAM: %m");
×
5317
                }
5318
        }
5319

5320
        if (needs_sandboxing && !have_cap_sys_admin && exec_context_needs_cap_sys_admin(context)) {
9,599✔
5321
                /* If we're unprivileged, set up the user namespace first to enable use of the other namespaces.
5322
                 * Users with CAP_SYS_ADMIN can set up user namespaces last because they will be able to
5323
                 * set up all of the other namespaces (i.e. network, mount, UTS) without a user namespace. */
5324
                PrivateUsers pu = exec_context_get_effective_private_users(context, params);
27✔
5325
                if (pu == PRIVATE_USERS_NO)
27✔
5326
                        pu = PRIVATE_USERS_SELF;
23✔
5327

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

5346
        /* Call setup_delegated_namespaces() the first time to unshare all non-delegated namespaces. */
5347
        r = setup_delegated_namespaces(
9,599✔
5348
                        context,
5349
                        params,
5350
                        runtime,
5351
                        /* delegate= */ false,
5352
                        memory_pressure_path,
5353
                        uid,
5354
                        gid,
5355
                        command,
5356
                        needs_sandboxing,
5357
                        have_cap_sys_admin,
5358
                        exit_status);
5359
        if (r < 0)
9,595✔
5360
                return r;
5361

5362
        /* Drop groups as early as possible.
5363
         * This needs to be done after PrivateDevices=yes setup as device nodes should be owned by the host's root.
5364
         * For non-root in a userns, devices will be owned by the user/group before the group change, and nobody. */
5365
        if (needs_setuid) {
9,579✔
5366
                _cleanup_free_ gid_t *gids_to_enforce = NULL;
9,579✔
5367
                int ngids_to_enforce;
9,579✔
5368

5369
                ngids_to_enforce = merge_gid_lists(gids,
9,579✔
5370
                                                   ngids,
5371
                                                   gids_after_pam,
5372
                                                   ngids_after_pam,
5373
                                                   &gids_to_enforce);
5374
                if (ngids_to_enforce < 0) {
9,579✔
5375
                        *exit_status = EXIT_GROUP;
×
5376
                        return log_error_errno(ngids_to_enforce, "Failed to merge group lists. Group membership might be incorrect: %m");
×
5377
                }
5378

5379
                r = enforce_groups(gid, gids_to_enforce, ngids_to_enforce);
9,579✔
5380
                if (r < 0) {
9,579✔
5381
                        *exit_status = EXIT_GROUP;
1✔
5382
                        return log_error_errno(r, "Changing group credentials failed: %m");
1✔
5383
                }
5384
        }
5385

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

5392
        if (needs_sandboxing && !userns_set_up) {
9,578✔
5393
                PrivateUsers pu = exec_context_get_effective_private_users(context, params);
9,556✔
5394

5395
                r = setup_private_users(pu, saved_uid, saved_gid, uid, gid,
9,556✔
5396
                                        /* allow_setgroups= */ pu == PRIVATE_USERS_FULL);
5397
                if (r < 0) {
9,556✔
5398
                        *exit_status = EXIT_USER;
×
5399
                        return log_error_errno(r, "Failed to set up user namespacing: %m");
×
5400
                }
5401
                if (r > 0)
9,556✔
5402
                        log_debug("Set up privileged user namespace");
25✔
5403
        }
5404

5405
        /* Call setup_delegated_namespaces() the second time to unshare all delegated namespaces. */
5406
        r = setup_delegated_namespaces(
9,578✔
5407
                        context,
5408
                        params,
5409
                        runtime,
5410
                        /* delegate= */ true,
5411
                        memory_pressure_path,
5412
                        uid,
5413
                        gid,
5414
                        command,
5415
                        needs_sandboxing,
5416
                        have_cap_sys_admin,
5417
                        exit_status);
5418
        if (r < 0)
9,574✔
5419
                return r;
5420

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

5424
        const char *path = command->path;
9,574✔
5425

5426
        if (FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL)) {
9,574✔
5427
                if (shell_is_placeholder(shell)) {
13✔
5428
                        log_debug("Shell prefixing requested for user without default shell, using /bin/sh: %s",
2✔
5429
                                  strna(username));
5430
                        assert(streq(path, _PATH_BSHELL));
2✔
5431
                } else
5432
                        path = shell;
11✔
5433
        }
5434

5435
        _cleanup_free_ char *executable = NULL;
5✔
5436
        _cleanup_close_ int executable_fd = -EBADF;
5✔
5437
        r = find_executable_full(path, /* root= */ NULL, context->exec_search_path, false, &executable, &executable_fd);
9,574✔
5438
        if (r < 0) {
9,574✔
5439
                *exit_status = EXIT_EXEC;
1✔
5440
                log_struct_errno(LOG_NOTICE, r,
1✔
5441
                                 LOG_MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED_STR),
5442
                                 LOG_EXEC_MESSAGE(params, "Unable to locate executable '%s': %m", path),
5443
                                 LOG_ITEM("EXECUTABLE=%s", path));
5444
                /* If the error will be ignored by manager, tune down the log level here. Missing executable
5445
                 * is very much expected in this case. */
5446
                return r != -ENOMEM && FLAGS_SET(command->flags, EXEC_COMMAND_IGNORE_FAILURE) ? 1 : r;
1✔
5447
        }
5448

5449
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &executable_fd);
9,573✔
5450
        if (r < 0) {
9,573✔
5451
                *exit_status = EXIT_FDS;
×
5452
                return log_error_errno(r, "Failed to collect shifted fd: %m");
×
5453
        }
5454

5455
#if HAVE_SELINUX
5456
        if (needs_sandboxing && use_selinux && params->selinux_context_net) {
5457
                int fd = -EBADF;
5458

5459
                if (socket_fd >= 0)
5460
                        fd = socket_fd;
5461
                else if (params->n_socket_fds == 1)
5462
                        /* If stdin is not connected to a socket but we are triggered by exactly one socket unit then we
5463
                         * use context from that fd to compute the label. */
5464
                        fd = params->fds[0];
5465

5466
                if (fd >= 0) {
5467
                        r = mac_selinux_get_child_mls_label(fd, executable, context->selinux_context, &mac_selinux_context_net);
5468
                        if (r < 0) {
5469
                                if (!context->selinux_context_ignore) {
5470
                                        *exit_status = EXIT_SELINUX_CONTEXT;
5471
                                        return log_error_errno(r, "Failed to determine SELinux context: %m");
5472
                                }
5473
                                log_debug_errno(r, "Failed to determine SELinux context, ignoring: %m");
5474
                        }
5475
                }
5476
        }
5477
#endif
5478

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

5485
        exec_runtime_close(runtime);
9,573✔
5486
        exec_params_close(params);
9,573✔
5487

5488
        r = close_all_fds(keep_fds, n_keep_fds);
9,573✔
5489
        if (r >= 0)
9,573✔
5490
                r = pack_fds(params->fds, n_fds);
9,573✔
5491
        if (r >= 0)
9,573✔
5492
                r = flag_fds(params->fds, n_socket_fds, n_fds, context->non_blocking);
9,573✔
5493
        if (r < 0) {
9,573✔
5494
                *exit_status = EXIT_FDS;
×
5495
                return log_error_errno(r, "Failed to adjust passed file descriptors: %m");
×
5496
        }
5497

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

5503
        secure_bits = context->secure_bits;
9,573✔
5504

5505
        if (needs_sandboxing) {
9,573✔
5506
                uint64_t bset;
9,573✔
5507

5508
                /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested.
5509
                 * (Note this is placed after the general resource limit initialization, see above, in order
5510
                 * to take precedence.) */
5511
                if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
9,573✔
5512
                        if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
1,491✔
5513
                                *exit_status = EXIT_LIMITS;
×
5514
                                return log_error_errno(errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m");
×
5515
                        }
5516
                }
5517

5518
#if ENABLE_SMACK
5519
                /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the
5520
                 * process. This is the latest place before dropping capabilities. Other MAC context are set later. */
5521
                if (use_smack) {
9,573✔
5522
                        r = setup_smack(context, params, executable_fd);
×
5523
                        if (r < 0 && !context->smack_process_label_ignore) {
×
5524
                                *exit_status = EXIT_SMACK_PROCESS_LABEL;
×
5525
                                return log_error_errno(r, "Failed to set SMACK process label: %m");
×
5526
                        }
5527
                }
5528
#endif
5529

5530
                bset = context->capability_bounding_set;
9,573✔
5531

5532
#if HAVE_SECCOMP
5533
                /* If the service has any form of a seccomp filter and it allows dropping privileges, we'll
5534
                 * keep the needed privileges to apply it even if we're not root. */
5535
                if (needs_setuid &&
19,146✔
5536
                    uid_is_valid(uid) &&
11,583✔
5537
                    context_has_seccomp(context) &&
2,758✔
5538
                    seccomp_allows_drop_privileges(context)) {
748✔
5539
                        keep_seccomp_privileges = true;
748✔
5540

5541
                        if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
748✔
5542
                                *exit_status = EXIT_USER;
×
5543
                                return log_error_errno(errno, "Failed to enable keep capabilities flag: %m");
×
5544
                        }
5545

5546
                        /* Save the current bounding set so we can restore it after applying the seccomp
5547
                         * filter */
5548
                        saved_bset = bset;
748✔
5549
                        bset |= (UINT64_C(1) << CAP_SYS_ADMIN) |
748✔
5550
                                (UINT64_C(1) << CAP_SETPCAP);
5551
                }
5552
#endif
5553

5554
                if (!cap_test_all(bset)) {
9,573✔
5555
                        r = capability_bounding_set_drop(bset, /* right_now= */ false);
1,617✔
5556
                        if (r < 0) {
1,617✔
5557
                                *exit_status = EXIT_CAPABILITIES;
×
5558
                                return log_error_errno(r, "Failed to drop capabilities: %m");
×
5559
                        }
5560
                }
5561

5562
                /* Ambient capabilities are cleared during setresuid() (in enforce_user()) even with
5563
                 * keep-caps set.
5564
                 *
5565
                 * To be able to raise the ambient capabilities after setresuid() they have to be added to
5566
                 * the inherited set and keep caps has to be set (done in enforce_user()).  After setresuid()
5567
                 * the ambient capabilities can be raised as they are present in the permitted and
5568
                 * inhertiable set. However it is possible that someone wants to set ambient capabilities
5569
                 * without changing the user, so we also set the ambient capabilities here.
5570
                 *
5571
                 * The requested ambient capabilities are raised in the inheritable set if the second
5572
                 * argument is true. */
5573
                if (capability_ambient_set != 0) {
9,573✔
5574
                        r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ true);
743✔
5575
                        if (r < 0) {
743✔
5576
                                *exit_status = EXIT_CAPABILITIES;
×
5577
                                return log_error_errno(r, "Failed to apply ambient capabilities (before UID change): %m");
×
5578
                        }
5579
                }
5580
        }
5581

5582
        /* chroot to root directory first, before we lose the ability to chroot */
5583
        r = apply_root_directory(context, params, runtime, needs_mount_namespace, exit_status);
9,573✔
5584
        if (r < 0)
9,573✔
5585
                return log_error_errno(r, "Chrooting to the requested root directory failed: %m");
×
5586

5587
        if (needs_setuid) {
9,573✔
5588
                if (uid_is_valid(uid)) {
9,573✔
5589
                        r = enforce_user(context, uid, capability_ambient_set);
2,010✔
5590
                        if (r < 0) {
2,010✔
5591
                                *exit_status = EXIT_USER;
×
5592
                                return log_error_errno(r, "Failed to change UID to " UID_FMT ": %m", uid);
×
5593
                        }
5594

5595
                        if (keep_seccomp_privileges) {
2,010✔
5596
                                if (!BIT_SET(capability_ambient_set, CAP_SETUID)) {
748✔
5597
                                        r = drop_capability(CAP_SETUID);
748✔
5598
                                        if (r < 0) {
748✔
5599
                                                *exit_status = EXIT_USER;
×
5600
                                                return log_error_errno(r, "Failed to drop CAP_SETUID: %m");
×
5601
                                        }
5602
                                }
5603

5604
                                r = keep_capability(CAP_SYS_ADMIN);
748✔
5605
                                if (r < 0) {
748✔
5606
                                        *exit_status = EXIT_USER;
×
5607
                                        return log_error_errno(r, "Failed to keep CAP_SYS_ADMIN: %m");
×
5608
                                }
5609

5610
                                r = keep_capability(CAP_SETPCAP);
748✔
5611
                                if (r < 0) {
748✔
5612
                                        *exit_status = EXIT_USER;
×
5613
                                        return log_error_errno(r, "Failed to keep CAP_SETPCAP: %m");
×
5614
                                }
5615
                        }
5616

5617
                        if (capability_ambient_set != 0) {
2,010✔
5618

5619
                                /* Raise the ambient capabilities after user change. */
5620
                                r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ false);
740✔
5621
                                if (r < 0) {
740✔
5622
                                        *exit_status = EXIT_CAPABILITIES;
×
5623
                                        return log_error_errno(r, "Failed to apply ambient capabilities (after UID change): %m");
×
5624
                                }
5625
                        }
5626
                }
5627
        }
5628

5629
        /* Apply working directory here, because the working directory might be on NFS and only the user
5630
         * running this service might have the correct privilege to change to the working directory. Also, it
5631
         * is absolutely 💣 crucial 💣 we applied all mount namespacing rearrangements before this, so that
5632
         * the cwd cannot be used to pin directories outside of the sandbox. */
5633
        r = apply_working_directory(context, params, runtime, pwent_home, accum_env);
9,573✔
5634
        if (r < 0) {
9,573✔
5635
                *exit_status = EXIT_CHDIR;
1✔
5636
                return log_error_errno(r, "Changing to the requested working directory failed: %m");
1✔
5637
        }
5638

5639
        if (needs_sandboxing) {
9,572✔
5640
                /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to
5641
                 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
5642
                 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
5643
                 * are restricted. */
5644

5645
#if HAVE_SELINUX
5646
                if (use_selinux) {
5647
                        char *exec_context = mac_selinux_context_net ?: context->selinux_context;
5648

5649
                        if (exec_context) {
5650
                                r = setexeccon(exec_context);
5651
                                if (r < 0) {
5652
                                        if (!context->selinux_context_ignore) {
5653
                                                *exit_status = EXIT_SELINUX_CONTEXT;
5654
                                                return log_error_errno(r, "Failed to change SELinux context to %s: %m", exec_context);
5655
                                        }
5656
                                        log_debug_errno(r, "Failed to change SELinux context to %s, ignoring: %m", exec_context);
5657
                                }
5658
                        }
5659
                }
5660
#endif
5661

5662
#if HAVE_APPARMOR
5663
                if (use_apparmor && context->apparmor_profile) {
5664
                        r = ASSERT_PTR(sym_aa_change_onexec)(context->apparmor_profile);
5665
                        if (r < 0 && !context->apparmor_profile_ignore) {
5666
                                *exit_status = EXIT_APPARMOR_PROFILE;
5667
                                return log_error_errno(errno, "Failed to prepare AppArmor profile change to %s: %m",
5668
                                                       context->apparmor_profile);
5669
                        }
5670
                }
5671
#endif
5672

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

5699
                if (context_has_no_new_privileges(context))
9,572✔
5700
                        if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
1,415✔
5701
                                *exit_status = EXIT_NO_NEW_PRIVILEGES;
×
5702
                                return log_error_errno(errno, "Failed to disable new privileges: %m");
×
5703
                        }
5704

5705
#if HAVE_SECCOMP
5706
                r = apply_address_families(context, params);
9,572✔
5707
                if (r < 0) {
9,572✔
5708
                        *exit_status = EXIT_ADDRESS_FAMILIES;
×
5709
                        return log_error_errno(r, "Failed to restrict address families: %m");
×
5710
                }
5711

5712
                r = apply_memory_deny_write_execute(context, params);
9,572✔
5713
                if (r < 0) {
9,572✔
5714
                        *exit_status = EXIT_SECCOMP;
×
5715
                        return log_error_errno(r, "Failed to disable writing to executable memory: %m");
×
5716
                }
5717

5718
                r = apply_restrict_realtime(context, params);
9,572✔
5719
                if (r < 0) {
9,572✔
5720
                        *exit_status = EXIT_SECCOMP;
×
5721
                        return log_error_errno(r, "Failed to apply realtime restrictions: %m");
×
5722
                }
5723

5724
                r = apply_restrict_suid_sgid(context, params);
9,572✔
5725
                if (r < 0) {
9,572✔
5726
                        *exit_status = EXIT_SECCOMP;
×
5727
                        return log_error_errno(r, "Failed to apply SUID/SGID restrictions: %m");
×
5728
                }
5729

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

5736
                r = apply_protect_sysctl(context, params);
9,572✔
5737
                if (r < 0) {
9,572✔
5738
                        *exit_status = EXIT_SECCOMP;
×
5739
                        return log_error_errno(r, "Failed to apply sysctl restrictions: %m");
×
5740
                }
5741

5742
                r = apply_protect_kernel_modules(context, params);
9,572✔
5743
                if (r < 0) {
9,572✔
5744
                        *exit_status = EXIT_SECCOMP;
×
5745
                        return log_error_errno(r, "Failed to apply module loading restrictions: %m");
×
5746
                }
5747

5748
                r = apply_protect_kernel_logs(context, params);
9,572✔
5749
                if (r < 0) {
9,572✔
5750
                        *exit_status = EXIT_SECCOMP;
×
5751
                        return log_error_errno(r, "Failed to apply kernel log restrictions: %m");
×
5752
                }
5753

5754
                r = apply_protect_clock(context, params);
9,572✔
5755
                if (r < 0) {
9,572✔
5756
                        *exit_status = EXIT_SECCOMP;
×
5757
                        return log_error_errno(r, "Failed to apply clock restrictions: %m");
×
5758
                }
5759

5760
                r = apply_private_devices(context, params);
9,572✔
5761
                if (r < 0) {
9,572✔
5762
                        *exit_status = EXIT_SECCOMP;
×
5763
                        return log_error_errno(r, "Failed to set up private devices: %m");
×
5764
                }
5765

5766
                r = apply_syscall_archs(context, params);
9,572✔
5767
                if (r < 0) {
9,572✔
5768
                        *exit_status = EXIT_SECCOMP;
×
5769
                        return log_error_errno(r, "Failed to apply syscall architecture restrictions: %m");
×
5770
                }
5771

5772
                r = apply_lock_personality(context, params);
9,572✔
5773
                if (r < 0) {
9,572✔
5774
                        *exit_status = EXIT_SECCOMP;
×
5775
                        return log_error_errno(r, "Failed to lock personalities: %m");
×
5776
                }
5777

5778
                r = apply_syscall_log(context, params);
9,572✔
5779
                if (r < 0) {
9,572✔
5780
                        *exit_status = EXIT_SECCOMP;
×
5781
                        return log_error_errno(r, "Failed to apply system call log filters: %m");
×
5782
                }
5783
#endif
5784

5785
#if HAVE_LIBBPF
5786
                r = apply_restrict_filesystems(context, params);
9,572✔
5787
                if (r < 0) {
9,572✔
5788
                        *exit_status = EXIT_BPF;
×
5789
                        return log_error_errno(r, "Failed to restrict filesystems: %m");
×
5790
                }
5791
#endif
5792

5793
#if HAVE_SECCOMP
5794
                /* This really should remain as close to the execve() as possible, to make sure our own code is affected
5795
                 * by the filter as little as possible. */
5796
                r = apply_syscall_filter(context, params);
9,572✔
5797
                if (r < 0) {
9,572✔
5798
                        *exit_status = EXIT_SECCOMP;
×
5799
                        return log_error_errno(r, "Failed to apply system call filters: %m");
×
5800
                }
5801

5802
                if (keep_seccomp_privileges) {
9,572✔
5803
                        /* Restore the capability bounding set with what's expected from the service + the
5804
                         * ambient capabilities hack */
5805
                        if (!cap_test_all(saved_bset)) {
747✔
5806
                                r = capability_bounding_set_drop(saved_bset, /* right_now= */ false);
712✔
5807
                                if (r < 0) {
712✔
5808
                                        *exit_status = EXIT_CAPABILITIES;
×
5809
                                        return log_error_errno(r, "Failed to drop bset capabilities: %m");
×
5810
                                }
5811
                        }
5812

5813
                        /* Only drop CAP_SYS_ADMIN if it's not in the bounding set, otherwise we'll break
5814
                         * applications that use it. */
5815
                        if (!BIT_SET(saved_bset, CAP_SYS_ADMIN)) {
747✔
5816
                                r = drop_capability(CAP_SYS_ADMIN);
279✔
5817
                                if (r < 0) {
279✔
5818
                                        *exit_status = EXIT_USER;
×
5819
                                        return log_error_errno(r, "Failed to drop CAP_SYS_ADMIN: %m");
×
5820
                                }
5821
                        }
5822

5823
                        /* Only drop CAP_SETPCAP if it's not in the bounding set, otherwise we'll break
5824
                         * applications that use it. */
5825
                        if (!BIT_SET(saved_bset, CAP_SETPCAP)) {
747✔
5826
                                r = drop_capability(CAP_SETPCAP);
531✔
5827
                                if (r < 0) {
531✔
5828
                                        *exit_status = EXIT_USER;
×
5829
                                        return log_error_errno(r, "Failed to drop CAP_SETPCAP: %m");
×
5830
                                }
5831
                        }
5832

5833
                        if (prctl(PR_SET_KEEPCAPS, 0) < 0) {
747✔
5834
                                *exit_status = EXIT_USER;
×
5835
                                return log_error_errno(errno, "Failed to drop keep capabilities flag: %m");
×
5836
                        }
5837
                }
5838
#endif
5839

5840
        }
5841

5842
        if (!strv_isempty(context->unset_environment)) {
9,572✔
5843
                char **ee = NULL;
274✔
5844

5845
                ee = strv_env_delete(accum_env, 1, context->unset_environment);
274✔
5846
                if (!ee) {
274✔
5847
                        *exit_status = EXIT_MEMORY;
×
5848
                        return log_oom();
5✔
5849
                }
5850

5851
                strv_free_and_replace(accum_env, ee);
274✔
5852
        }
5853

5854
        _cleanup_strv_free_ char **replaced_argv = NULL, **argv_via_shell = NULL;
3✔
5855
        char **final_argv = FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL) ? strv_skip(command->argv, 1) : command->argv;
9,572✔
5856

5857
        if (final_argv && !FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) {
9,572✔
5858
                _cleanup_strv_free_ char **unset_variables = NULL, **bad_variables = NULL;
9,400✔
5859

5860
                r = replace_env_argv(final_argv, accum_env, &replaced_argv, &unset_variables, &bad_variables);
9,400✔
5861
                if (r < 0) {
9,400✔
5862
                        *exit_status = EXIT_MEMORY;
×
5863
                        return log_error_errno(r, "Failed to replace environment variables: %m");
×
5864
                }
5865
                final_argv = replaced_argv;
9,400✔
5866

5867
                if (!strv_isempty(unset_variables)) {
9,400✔
5868
                        _cleanup_free_ char *ju = strv_join(unset_variables, ", ");
10✔
5869
                        log_warning("Referenced but unset environment variable evaluates to an empty string: %s", strna(ju));
5✔
5870
                }
5871

5872
                if (!strv_isempty(bad_variables)) {
9,400✔
5873
                        _cleanup_free_ char *jb = strv_join(bad_variables, ", ");
×
5874
                        log_warning("Invalid environment variable name evaluates to an empty string: %s", strna(jb));
×
5875
                }
5876
        }
5877

5878
        if (FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL)) {
9,572✔
5879
                r = strv_extendf(&argv_via_shell, "%s%s", command->argv[0][0] == '-' ? "-" : "", path);
17✔
5880
                if (r < 0) {
13✔
5881
                        *exit_status = EXIT_MEMORY;
×
5882
                        return log_oom();
×
5883
                }
5884

5885
                if (!strv_isempty(final_argv)) {
13✔
5886
                        _cleanup_free_ char *cmdline_joined = NULL;
13✔
5887

5888
                        cmdline_joined = strv_join(final_argv, " ");
13✔
5889
                        if (!cmdline_joined) {
13✔
5890
                                *exit_status = EXIT_MEMORY;
×
5891
                                return log_oom();
×
5892
                        }
5893

5894
                        r = strv_extend_many(&argv_via_shell, "-c", cmdline_joined);
13✔
5895
                        if (r < 0) {
13✔
5896
                                *exit_status = EXIT_MEMORY;
×
5897
                                return log_oom();
×
5898
                        }
5899
                }
5900

5901
                final_argv = argv_via_shell;
13✔
5902
        }
5903

5904
        log_command_line(context, params, "Executing", executable, final_argv);
9,572✔
5905

5906
        /* We have finished with all our initializations. Let's now let the manager know that. From this
5907
         * point on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */
5908

5909
        r = exec_fd_mark_hot(context, params, /* hot= */ true, exit_status);
9,572✔
5910
        if (r < 0)
9,572✔
5911
                return r;
5912

5913
        /* As last thing before the execve(), let's send the handoff timestamp */
5914
        r = send_handoff_timestamp(context, params, exit_status);
9,572✔
5915
        if (r < 0) {
9,572✔
5916
                /* If this handoff timestamp failed, let's undo the marking as hot */
5917
                (void) exec_fd_mark_hot(context, params, /* hot= */ false, /* reterr_exit_status= */ NULL);
×
5918
                return r;
5919
        }
5920

5921
        /* NB: we leave executable_fd, exec_fd, handoff_timestamp_fd open here. This is safe, because they
5922
         * have O_CLOEXEC set, and the execve() below will thus automatically close them. In fact, for
5923
         * exec_fd this is pretty much the whole raison d'etre. */
5924

5925
        r = fexecve_or_execve(executable_fd, executable, final_argv, accum_env);
9,572✔
5926

5927
        /* The execve() failed, let's undo the marking as hot */
5928
        (void) exec_fd_mark_hot(context, params, /* hot= */ false, /* reterr_exit_status= */ NULL);
3✔
5929

5930
        *exit_status = EXIT_EXEC;
3✔
5931
        return log_error_errno(r, "Failed to execute %s: %m", executable);
3✔
5932
}
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