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

systemd / systemd / 13533485051

25 Feb 2025 10:20PM UTC coverage: 71.818% (+0.04%) from 71.774%
13533485051

push

github

web-flow
make integritysetup/veritysetup more alike cryptsetup when it comes to remote operation (#36501)

Let's address some asymmetries here.

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

96 existing lines in 30 files now uncovered.

294319 of 409813 relevant lines covered (71.82%)

716680.45 hits per line

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

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

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

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

14
#include "sd-messages.h"
15

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

64
#define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
65
#define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
66

67
#define SNDBUF_SIZE (8*1024*1024)
68

69
static int flag_fds(
11,065✔
70
                const int fds[],
71
                size_t n_socket_fds,
72
                size_t n_fds,
73
                bool nonblock) {
74

75
        int r;
11,065✔
76

77
        assert(fds || n_fds == 0);
11,065✔
78

79
        /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags.
80
         * O_NONBLOCK only applies to socket activation though. */
81

82
        for (size_t i = 0; i < n_fds; i++) {
13,631✔
83

84
                if (i < n_socket_fds) {
2,566✔
85
                        r = fd_nonblock(fds[i], nonblock);
2,386✔
86
                        if (r < 0)
2,386✔
87
                                return r;
88
                }
89

90
                /* We unconditionally drop FD_CLOEXEC from the fds,
91
                 * since after all we want to pass these fds to our
92
                 * children */
93

94
                r = fd_cloexec(fds[i], false);
2,566✔
95
                if (r < 0)
2,566✔
96
                        return r;
97
        }
98

99
        return 0;
100
}
101

102
static bool is_terminal_input(ExecInput i) {
50,587✔
103
        return IN_SET(i,
50,587✔
104
                      EXEC_INPUT_TTY,
105
                      EXEC_INPUT_TTY_FORCE,
106
                      EXEC_INPUT_TTY_FAIL);
107
}
108

109
static bool is_terminal_output(ExecOutput o) {
47,295✔
110
        return IN_SET(o,
47,295✔
111
                      EXEC_OUTPUT_TTY,
112
                      EXEC_OUTPUT_KMSG_AND_CONSOLE,
113
                      EXEC_OUTPUT_JOURNAL_AND_CONSOLE);
114
}
115

116
static bool is_kmsg_output(ExecOutput o) {
12,254✔
117
        return IN_SET(o,
12,254✔
118
                      EXEC_OUTPUT_KMSG,
119
                      EXEC_OUTPUT_KMSG_AND_CONSOLE);
120
}
121

122
static bool exec_context_needs_term(const ExecContext *c) {
11,086✔
123
        assert(c);
11,086✔
124

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

127
        if (is_terminal_input(c->std_input))
11,086✔
128
                return true;
129

130
        if (is_terminal_output(c->std_output))
10,910✔
131
                return true;
132

133
        if (is_terminal_output(c->std_error))
10,650✔
134
                return true;
135

136
        return !!c->tty_path;
10,649✔
137
}
138

139
static int open_null_as(int flags, int nfd) {
13,031✔
140
        int fd;
13,031✔
141

142
        assert(nfd >= 0);
13,031✔
143

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

148
        return move_fd(fd, nfd, false);
13,031✔
149
}
150

151
static int connect_journal_socket(
12,254✔
152
                int fd,
153
                const char *log_namespace,
154
                uid_t uid,
155
                gid_t gid) {
156

157
        uid_t olduid = UID_INVALID;
12,254✔
158
        gid_t oldgid = GID_INVALID;
12,254✔
159
        const char *j;
12,254✔
160
        int r;
12,254✔
161

162
        assert(fd >= 0);
12,254✔
163

164
        j = journal_stream_path(log_namespace);
12,266✔
165
        if (!j)
2✔
166
                return -EINVAL;
×
167

168
        if (gid_is_valid(gid)) {
12,254✔
169
                oldgid = getgid();
2,438✔
170

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

175
        if (uid_is_valid(uid)) {
12,254✔
176
                olduid = getuid();
2,435✔
177

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

184
        r = connect_unix_path(fd, AT_FDCWD, j);
12,254✔
185

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

189
        if (uid_is_valid(uid))
12,254✔
190
                (void) seteuid(olduid);
2,435✔
191

192
 restore_gid:
9,819✔
193
        if (gid_is_valid(gid))
12,254✔
194
                (void) setegid(oldgid);
2,438✔
195

196
        return r;
197
}
198

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

208
        _cleanup_close_ int fd = -EBADF;
12,254✔
209
        int r;
12,254✔
210

211
        assert(context);
12,254✔
212
        assert(params);
12,254✔
213
        assert(output < _EXEC_OUTPUT_MAX);
12,254✔
214
        assert(ident);
12,254✔
215
        assert(nfd >= 0);
12,254✔
216

217
        fd = socket(AF_UNIX, SOCK_STREAM, 0);
12,254✔
218
        if (fd < 0)
12,254✔
219
                return -errno;
×
220

221
        r = connect_journal_socket(fd, context->log_namespace, uid, gid);
12,254✔
222
        if (r < 0)
12,254✔
223
                return r;
224

225
        if (shutdown(fd, SHUT_RD) < 0)
12,254✔
226
                return -errno;
×
227

228
        (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
12,254✔
229

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

247
        return move_fd(TAKE_FD(fd), nfd, false);
12,254✔
248
}
249

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

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

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

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

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

267
        assert(path);
11✔
268

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

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

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

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

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

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

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

302
        return TAKE_FD(fd);
303
}
304

305
static int fixup_input(
39,102✔
306
                const ExecContext *context,
307
                int socket_fd,
308
                bool apply_tty_stdin) {
309

310
        ExecInput std_input;
39,102✔
311

312
        assert(context);
39,102✔
313

314
        std_input = context->std_input;
39,102✔
315

316
        if (is_terminal_input(std_input) && !apply_tty_stdin)
39,102✔
317
                return EXEC_INPUT_NULL;
318

319
        if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
39,102✔
320
                return EXEC_INPUT_NULL;
321

322
        if (std_input == EXEC_INPUT_DATA && context->stdin_data_size == 0)
39,102✔
323
                return EXEC_INPUT_NULL;
×
324

325
        return std_input;
326
}
327

328
static int fixup_output(ExecOutput output, int socket_fd) {
39,102✔
329

330
        if (output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
39,102✔
331
                return EXEC_OUTPUT_INHERIT;
×
332

333
        return output;
334
}
335

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

342
        ExecInput i;
13,481✔
343
        int r;
13,481✔
344

345
        assert(context);
13,481✔
346
        assert(params);
13,481✔
347
        assert(named_iofds);
13,481✔
348

349
        if (params->stdin_fd >= 0) {
13,481✔
350
                if (dup2(params->stdin_fd, STDIN_FILENO) < 0)
447✔
351
                        return -errno;
×
352

353
                /* Try to make this the controlling tty, if it is a tty */
354
                if (isatty_safe(STDIN_FILENO))
447✔
355
                        (void) ioctl(STDIN_FILENO, TIOCSCTTY, context->std_input == EXEC_INPUT_TTY_FORCE);
16✔
356

357
                return STDIN_FILENO;
447✔
358
        }
359

360
        i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
13,034✔
361

362
        switch (i) {
13,034✔
363

364
        case EXEC_INPUT_NULL:
12,663✔
365
                return open_null_as(O_RDONLY, STDIN_FILENO);
12,663✔
366

367
        case EXEC_INPUT_TTY:
359✔
368
        case EXEC_INPUT_TTY_FORCE:
369
        case EXEC_INPUT_TTY_FAIL: {
370
                _cleanup_close_ int tty_fd = -EBADF;
13,840✔
371
                const char *tty_path;
359✔
372

373
                tty_path = ASSERT_PTR(exec_context_tty_path(context));
359✔
374

375
                tty_fd = acquire_terminal(tty_path,
718✔
376
                                          i == EXEC_INPUT_TTY_FAIL  ? ACQUIRE_TERMINAL_TRY :
359✔
377
                                          i == EXEC_INPUT_TTY_FORCE ? ACQUIRE_TERMINAL_FORCE :
378
                                                                      ACQUIRE_TERMINAL_WAIT,
379
                                          USEC_INFINITY);
380
                if (tty_fd < 0)
359✔
381
                        return tty_fd;
382

383
                r = move_fd(tty_fd, STDIN_FILENO, /* cloexec= */ false);
359✔
384
                if (r < 0)
359✔
385
                        return r;
×
386

387
                TAKE_FD(tty_fd);
388
                return r;
389
        }
390

391
        case EXEC_INPUT_SOCKET:
11✔
392
                assert(socket_fd >= 0);
11✔
393

394
                return RET_NERRNO(dup2(socket_fd, STDIN_FILENO));
11✔
395

396
        case EXEC_INPUT_NAMED_FD:
×
397
                assert(named_iofds[STDIN_FILENO] >= 0);
×
398

399
                (void) fd_nonblock(named_iofds[STDIN_FILENO], false);
×
400
                return RET_NERRNO(dup2(named_iofds[STDIN_FILENO], STDIN_FILENO));
13,481✔
401

402
        case EXEC_INPUT_DATA: {
1✔
403
                int fd;
1✔
404

405
                fd = memfd_new_and_seal("exec-input", context->stdin_data, context->stdin_data_size);
1✔
406
                if (fd < 0)
1✔
407
                        return fd;
408

409
                return move_fd(fd, STDIN_FILENO, false);
1✔
410
        }
411

412
        case EXEC_INPUT_FILE: {
×
413
                bool rw;
×
414
                int fd;
×
415

416
                assert(context->stdio_file[STDIN_FILENO]);
×
417

418
                rw = (context->std_output == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDOUT_FILENO])) ||
×
419
                        (context->std_error == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDERR_FILENO]));
×
420

421
                fd = acquire_path(context->stdio_file[STDIN_FILENO], rw ? O_RDWR : O_RDONLY, 0666 & ~context->umask);
×
422
                if (fd < 0)
×
423
                        return fd;
424

425
                return move_fd(fd, STDIN_FILENO, false);
×
426
        }
427

428
        default:
×
429
                assert_not_reached();
×
430
        }
431
}
432

433
static bool can_inherit_stderr_from_stdout(
13,034✔
434
                const ExecContext *context,
435
                ExecOutput o,
436
                ExecOutput e) {
437

438
        assert(context);
13,034✔
439

440
        /* Returns true, if given the specified STDERR and STDOUT output we can directly dup() the stdout fd to the
441
         * stderr fd */
442

443
        if (e == EXEC_OUTPUT_INHERIT)
13,034✔
444
                return true;
445
        if (e != o)
375✔
446
                return false;
447

448
        if (e == EXEC_OUTPUT_NAMED_FD)
372✔
449
                return streq_ptr(context->stdio_fdname[STDOUT_FILENO], context->stdio_fdname[STDERR_FILENO]);
×
450

451
        if (IN_SET(e, EXEC_OUTPUT_FILE, EXEC_OUTPUT_FILE_APPEND, EXEC_OUTPUT_FILE_TRUNCATE))
372✔
452
                return streq_ptr(context->stdio_file[STDOUT_FILENO], context->stdio_file[STDERR_FILENO]);
4✔
453

454
        return true;
455
}
456

457
static int setup_output(
26,962✔
458
                const ExecContext *context,
459
                const ExecParameters *params,
460
                int fileno,
461
                int socket_fd,
462
                const int named_iofds[static 3],
463
                const char *ident,
464
                uid_t uid,
465
                gid_t gid,
466
                dev_t *journal_stream_dev,
467
                ino_t *journal_stream_ino) {
468

469
        ExecOutput o;
26,962✔
470
        ExecInput i;
26,962✔
471
        int r;
26,962✔
472

473
        assert(context);
26,962✔
474
        assert(params);
26,962✔
475
        assert(ident);
26,962✔
476
        assert(journal_stream_dev);
26,962✔
477
        assert(journal_stream_ino);
26,962✔
478

479
        if (fileno == STDOUT_FILENO && params->stdout_fd >= 0) {
26,962✔
480

481
                if (dup2(params->stdout_fd, STDOUT_FILENO) < 0)
447✔
482
                        return -errno;
×
483

484
                return STDOUT_FILENO;
485
        }
486

487
        if (fileno == STDERR_FILENO && params->stderr_fd >= 0) {
26,515✔
488
                if (dup2(params->stderr_fd, STDERR_FILENO) < 0)
447✔
489
                        return -errno;
×
490

491
                return STDERR_FILENO;
492
        }
493

494
        i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
26,068✔
495
        o = fixup_output(context->std_output, socket_fd);
26,068✔
496

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

500
        if (fileno == STDERR_FILENO) {
26,068✔
501
                ExecOutput e;
13,034✔
502
                e = fixup_output(context->std_error, socket_fd);
13,034✔
503

504
                /* This expects the input and output are already set up */
505

506
                /* Don't change the stderr file descriptor if we inherit all
507
                 * the way and are not on a tty */
508
                if (e == EXEC_OUTPUT_INHERIT &&
13,034✔
509
                    o == EXEC_OUTPUT_INHERIT &&
8✔
510
                    i == EXEC_INPUT_NULL &&
×
511
                    !is_terminal_input(context->std_input) &&
×
512
                    getppid() != 1)
×
513
                        return fileno;
514

515
                /* Duplicate from stdout if possible */
516
                if (can_inherit_stderr_from_stdout(context, o, e))
13,034✔
517
                        return RET_NERRNO(dup2(STDOUT_FILENO, fileno));
13,027✔
518

519
                o = e;
520

521
        } else if (o == EXEC_OUTPUT_INHERIT) {
13,034✔
522
                /* If input got downgraded, inherit the original value */
523
                if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
8✔
524
                        return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
×
525

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

530
                /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
531
                if (getppid() != 1)
×
532
                        return fileno;
533

534
                /* We need to open /dev/null here anew, to get the right access mode. */
535
                return open_null_as(O_WRONLY, fileno);
×
536
        }
537

538
        switch (o) {
13,033✔
539

540
        case EXEC_OUTPUT_NULL:
368✔
541
                return open_null_as(O_WRONLY, fileno);
368✔
542

543
        case EXEC_OUTPUT_TTY:
391✔
544
                if (is_terminal_input(i))
391✔
545
                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));
359✔
546

547
                return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
32✔
548

549
        case EXEC_OUTPUT_KMSG:
12,254✔
550
        case EXEC_OUTPUT_KMSG_AND_CONSOLE:
551
        case EXEC_OUTPUT_JOURNAL:
552
        case EXEC_OUTPUT_JOURNAL_AND_CONSOLE:
553
                r = connect_logger_as(context, params, o, ident, fileno, uid, gid);
12,254✔
554
                if (r < 0) {
12,254✔
555
                        log_exec_warning_errno(context,
×
556
                                               params,
557
                                               r,
558
                                               "Failed to connect %s to the journal socket, ignoring: %m",
559
                                               fileno == STDOUT_FILENO ? "stdout" : "stderr");
560
                        r = open_null_as(O_WRONLY, fileno);
×
561
                } else {
562
                        struct stat st;
12,254✔
563

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

571
                        if (fstat(fileno, &st) >= 0 &&
12,254✔
572
                            (*journal_stream_ino == 0 || fileno == STDERR_FILENO)) {
12,254✔
573
                                *journal_stream_dev = st.st_dev;
12,254✔
574
                                *journal_stream_ino = st.st_ino;
12,254✔
575
                        }
576
                }
577
                return r;
578

579
        case EXEC_OUTPUT_SOCKET:
9✔
580
                assert(socket_fd >= 0);
9✔
581

582
                return RET_NERRNO(dup2(socket_fd, fileno));
9✔
583

584
        case EXEC_OUTPUT_NAMED_FD:
×
585
                assert(named_iofds[fileno] >= 0);
×
586

587
                (void) fd_nonblock(named_iofds[fileno], false);
×
588
                return RET_NERRNO(dup2(named_iofds[fileno], fileno));
26,962✔
589

590
        case EXEC_OUTPUT_FILE:
11✔
591
        case EXEC_OUTPUT_FILE_APPEND:
592
        case EXEC_OUTPUT_FILE_TRUNCATE: {
593
                bool rw;
11✔
594
                int fd, flags;
11✔
595

596
                assert(context->stdio_file[fileno]);
11✔
597

598
                rw = context->std_input == EXEC_INPUT_FILE &&
11✔
599
                        streq_ptr(context->stdio_file[fileno], context->stdio_file[STDIN_FILENO]);
×
600

601
                if (rw)
11✔
602
                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));
×
603

604
                flags = O_WRONLY;
11✔
605
                if (o == EXEC_OUTPUT_FILE_APPEND)
11✔
606
                        flags |= O_APPEND;
607
                else if (o == EXEC_OUTPUT_FILE_TRUNCATE)
9✔
608
                        flags |= O_TRUNC;
3✔
609

610
                fd = acquire_path(context->stdio_file[fileno], flags, 0666 & ~context->umask);
11✔
611
                if (fd < 0)
11✔
612
                        return fd;
613

614
                return move_fd(fd, fileno, 0);
11✔
615
        }
616

617
        default:
×
618
                assert_not_reached();
×
619
        }
620
}
621

622
static int chown_terminal(int fd, uid_t uid) {
2,678✔
623
        int r;
2,678✔
624

625
        assert(fd >= 0);
2,678✔
626

627
        /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
628
        if (!isatty_safe(fd))
2,678✔
629
                return 0;
630

631
        /* This might fail. What matters are the results. */
632
        r = fchmod_and_chown(fd, TTY_MODE, uid, GID_INVALID);
7✔
633
        if (r < 0)
7✔
634
                return r;
×
635

636
        return 1;
637
}
638

639
static int setup_confirm_stdio(
×
640
                const ExecContext *context,
641
                const char *vc,
642
                int *ret_saved_stdin,
643
                int *ret_saved_stdout) {
644

645
        _cleanup_close_ int fd = -EBADF, saved_stdin = -EBADF, saved_stdout = -EBADF;
×
646
        int r;
×
647

648
        assert(ret_saved_stdin);
×
649
        assert(ret_saved_stdout);
×
650

651
        saved_stdin = fcntl(STDIN_FILENO, F_DUPFD_CLOEXEC, 3);
×
652
        if (saved_stdin < 0)
×
653
                return -errno;
×
654

655
        saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD_CLOEXEC, 3);
×
656
        if (saved_stdout < 0)
×
657
                return -errno;
×
658

659
        fd = acquire_terminal(vc, ACQUIRE_TERMINAL_WAIT, DEFAULT_CONFIRM_USEC);
×
660
        if (fd < 0)
×
661
                return fd;
662

663
        _cleanup_close_ int lock_fd = lock_dev_console();
×
664
        if (lock_fd < 0)
×
665
                log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
×
666

667
        r = chown_terminal(fd, getuid());
×
668
        if (r < 0)
×
669
                return r;
670

671
        r = terminal_reset_defensive(fd, /* switch_to_text= */ true);
×
672
        if (r < 0)
×
673
                return r;
674

675
        r = exec_context_apply_tty_size(context, fd, fd, vc);
×
676
        if (r < 0)
×
677
                return r;
678

679
        r = rearrange_stdio(fd, fd, STDERR_FILENO); /* Invalidates 'fd' also on failure */
×
680
        TAKE_FD(fd);
×
681
        if (r < 0)
×
682
                return r;
683

684
        *ret_saved_stdin = TAKE_FD(saved_stdin);
×
685
        *ret_saved_stdout = TAKE_FD(saved_stdout);
×
686
        return 0;
×
687
}
688

689
static void write_confirm_error_fd(int err, int fd, const char *unit_id) {
×
690
        assert(err != 0);
×
691
        assert(fd >= 0);
×
692
        assert(unit_id);
×
693

694
        errno = abs(err);
×
695

696
        if (errno == ETIMEDOUT)
×
697
                dprintf(fd, "Confirmation question timed out for %s, assuming positive response.\n", unit_id);
×
698
        else
699
                dprintf(fd, "Couldn't ask confirmation for %s, assuming positive response: %m\n", unit_id);
×
700
}
×
701

702
static void write_confirm_error(int err, const char *vc, const char *unit_id) {
×
703
        _cleanup_close_ int fd = -EBADF;
×
704

705
        assert(vc);
×
706

707
        fd = open_terminal(vc, O_WRONLY|O_NOCTTY|O_CLOEXEC);
×
708
        if (fd < 0)
×
709
                return;
×
710

711
        write_confirm_error_fd(err, fd, unit_id);
×
712
}
713

714
static int restore_confirm_stdio(int *saved_stdin, int *saved_stdout) {
×
715
        int r = 0;
×
716

717
        assert(saved_stdin);
×
718
        assert(saved_stdout);
×
719

720
        release_terminal();
×
721

722
        if (*saved_stdin >= 0)
×
723
                if (dup2(*saved_stdin, STDIN_FILENO) < 0)
×
724
                        r = -errno;
×
725

726
        if (*saved_stdout >= 0)
×
727
                if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
×
728
                        r = -errno;
×
729

730
        *saved_stdin = safe_close(*saved_stdin);
×
731
        *saved_stdout = safe_close(*saved_stdout);
×
732

733
        return r;
×
734
}
735

736
enum {
737
        CONFIRM_PRETEND_FAILURE = -1,
738
        CONFIRM_PRETEND_SUCCESS =  0,
739
        CONFIRM_EXECUTE = 1,
740
};
741

742
static bool confirm_spawn_disabled(void) {
×
743
        return access("/run/systemd/confirm_spawn_disabled", F_OK) >= 0;
×
744
}
745

746
static int ask_for_confirmation(const ExecContext *context, const ExecParameters *params, const char *cmdline) {
×
747
        int saved_stdout = -EBADF, saved_stdin = -EBADF, r;
×
748
        _cleanup_free_ char *e = NULL;
×
749
        char c;
×
750

751
        assert(context);
×
752
        assert(params);
×
753

754
        /* For any internal errors, assume a positive response. */
755
        r = setup_confirm_stdio(context, params->confirm_spawn, &saved_stdin, &saved_stdout);
×
756
        if (r < 0) {
×
757
                write_confirm_error(r, params->confirm_spawn, params->unit_id);
×
758
                return CONFIRM_EXECUTE;
759
        }
760

761
        /* confirm_spawn might have been disabled while we were sleeping. */
762
        if (!params->confirm_spawn || confirm_spawn_disabled()) {
×
763
                r = 1;
×
764
                goto restore_stdio;
×
765
        }
766

767
        e = ellipsize(cmdline, 60, 100);
×
768
        if (!e) {
×
769
                log_oom();
×
770
                r = CONFIRM_EXECUTE;
×
771
                goto restore_stdio;
×
772
        }
773

774
        for (;;) {
×
775
                r = ask_char(&c, "yfshiDjcn", "Execute %s? [y, f, s – h for help] ", e);
×
776
                if (r < 0) {
×
777
                        write_confirm_error_fd(r, STDOUT_FILENO, params->unit_id);
×
778
                        r = CONFIRM_EXECUTE;
×
779
                        goto restore_stdio;
×
780
                }
781

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

819
                        continue; /* ask again */
×
820
                case 'n':
×
821
                        /* 'n' was removed in favor of 'f'. */
822
                        printf("Didn't understand 'n', did you mean 'f'?\n");
×
823
                        continue; /* ask again */
×
824
                case 's':
×
825
                        printf("Skipping execution.\n");
×
826
                        r = CONFIRM_PRETEND_SUCCESS;
827
                        break;
828
                case 'y':
829
                        r = CONFIRM_EXECUTE;
830
                        break;
831
                default:
×
832
                        assert_not_reached();
×
833
                }
834
                break;
835
        }
836

837
restore_stdio:
×
838
        restore_confirm_stdio(&saved_stdin, &saved_stdout);
×
839
        return r;
840
}
841

842
static int get_fixed_user(
11,124✔
843
                const char *user_or_uid,
844
                const char **ret_username,
845
                uid_t *ret_uid,
846
                gid_t *ret_gid,
847
                const char **ret_home,
848
                const char **ret_shell) {
849

850
        int r;
11,124✔
851

852
        assert(user_or_uid);
11,124✔
853
        assert(ret_username);
11,124✔
854

855
        r = get_user_creds(&user_or_uid, ret_uid, ret_gid, ret_home, ret_shell, USER_CREDS_CLEAN);
11,124✔
856
        if (r < 0)
11,124✔
857
                return r;
858

859
        /* user_or_uid is normalized by get_user_creds to username */
860
        *ret_username = user_or_uid;
11,122✔
861

862
        return 0;
11,122✔
863
}
864

865
static int get_fixed_group(
9✔
866
                const char *group_or_gid,
867
                const char **ret_groupname,
868
                gid_t *ret_gid) {
869

870
        int r;
9✔
871

872
        assert(group_or_gid);
9✔
873
        assert(ret_groupname);
9✔
874

875
        r = get_group_creds(&group_or_gid, ret_gid, /* flags = */ 0);
9✔
876
        if (r < 0)
9✔
877
                return r;
878

879
        /* group_or_gid is normalized by get_group_creds to groupname */
880
        *ret_groupname = group_or_gid;
9✔
881

882
        return 0;
9✔
883
}
884

885
static int get_supplementary_groups(const ExecContext *c, const char *user,
13,481✔
886
                                    const char *group, gid_t gid,
887
                                    gid_t **supplementary_gids, int *ngids) {
888
        int r, k = 0;
13,481✔
889
        int ngroups_max;
13,481✔
890
        bool keep_groups = false;
13,481✔
891
        gid_t *groups = NULL;
13,481✔
892
        _cleanup_free_ gid_t *l_gids = NULL;
13,481✔
893

894
        assert(c);
13,481✔
895

896
        /*
897
         * If user is given, then lookup GID and supplementary groups list.
898
         * We avoid NSS lookups for gid=0. Also we have to initialize groups
899
         * here and as early as possible so we keep the list of supplementary
900
         * groups of the caller.
901
         */
902
        if (user && gid_is_valid(gid) && gid != 0) {
16,159✔
903
                /* First step, initialize groups from /etc/groups */
904
                if (initgroups(user, gid) < 0)
2,577✔
905
                        return -errno;
×
906

907
                keep_groups = true;
908
        }
909

910
        if (strv_isempty(c->supplementary_groups))
13,489✔
911
                return 0;
912

913
        /*
914
         * If SupplementaryGroups= was passed then NGROUPS_MAX has to
915
         * be positive, otherwise fail.
916
         */
917
        errno = 0;
8✔
918
        ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
8✔
919
        if (ngroups_max <= 0)
8✔
920
                return errno_or_else(EOPNOTSUPP);
×
921

922
        l_gids = new(gid_t, ngroups_max);
8✔
923
        if (!l_gids)
8✔
924
                return -ENOMEM;
925

926
        if (keep_groups) {
8✔
927
                /*
928
                 * Lookup the list of groups that the user belongs to, we
929
                 * avoid NSS lookups here too for gid=0.
930
                 */
931
                k = ngroups_max;
8✔
932
                if (getgrouplist(user, gid, l_gids, &k) < 0)
8✔
933
                        return -EINVAL;
934
        } else
935
                k = 0;
×
936

937
        STRV_FOREACH(i, c->supplementary_groups) {
16✔
938
                const char *g;
8✔
939

940
                if (k >= ngroups_max)
8✔
941
                        return -E2BIG;
×
942

943
                g = *i;
8✔
944
                r = get_group_creds(&g, l_gids+k, 0);
8✔
945
                if (r < 0)
8✔
946
                        return r;
947

948
                k++;
8✔
949
        }
950

951
        /*
952
         * Sets ngids to zero to drop all supplementary groups, happens
953
         * when we are under root and SupplementaryGroups= is empty.
954
         */
955
        if (k == 0) {
8✔
956
                *ngids = 0;
×
957
                return 0;
×
958
        }
959

960
        /* Otherwise get the final list of supplementary groups */
961
        groups = memdup(l_gids, sizeof(gid_t) * k);
8✔
962
        if (!groups)
8✔
963
                return -ENOMEM;
964

965
        *supplementary_gids = groups;
8✔
966
        *ngids = k;
8✔
967

968
        groups = NULL;
8✔
969

970
        return 0;
8✔
971
}
972

973
static int enforce_groups(gid_t gid, const gid_t *supplementary_gids, int ngids) {
11,067✔
974
        int r;
11,067✔
975

976
        /* Handle SupplementaryGroups= if it is not empty */
977
        if (ngids > 0) {
11,067✔
978
                r = maybe_setgroups(ngids, supplementary_gids);
217✔
979
                if (r < 0)
217✔
980
                        return r;
981
        }
982

983
        if (gid_is_valid(gid)) {
11,067✔
984
                /* Then set our gids */
985
                if (setresgid(gid, gid, gid) < 0)
2,009✔
986
                        return -errno;
1✔
987
        }
988

989
        return 0;
990
}
991

992
static int set_securebits(unsigned bits, unsigned mask) {
843✔
993
        unsigned applied;
843✔
994
        int current;
843✔
995

996
        current = prctl(PR_GET_SECUREBITS);
843✔
997
        if (current < 0)
843✔
998
                return -errno;
×
999

1000
        /* Clear all securebits defined in mask and set bits */
1001
        applied = ((unsigned) current & ~mask) | bits;
843✔
1002
        if ((unsigned) current == applied)
843✔
1003
                return 0;
1004

1005
        if (prctl(PR_SET_SECUREBITS, applied) < 0)
54✔
1006
                return -errno;
×
1007

1008
        return 1;
1009
}
1010

1011
static int enforce_user(
2,004✔
1012
                const ExecContext *context,
1013
                uid_t uid,
1014
                uint64_t capability_ambient_set) {
1015
        assert(context);
2,004✔
1016
        int r;
2,004✔
1017

1018
        if (!uid_is_valid(uid))
2,004✔
1019
                return 0;
1020

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

1025
        if ((capability_ambient_set != 0 || context->secure_bits != 0) && uid != 0) {
2,004✔
1026

1027
                /* First step: If we need to keep capabilities but drop privileges we need to make sure we
1028
                 * keep our caps, while we drop privileges. Add KEEP_CAPS to the securebits */
1029
                r = set_securebits(1U << SECURE_KEEP_CAPS, 0);
843✔
1030
                if (r < 0)
843✔
1031
                        return r;
1032
        }
1033

1034
        /* Second step: actually set the uids */
1035
        if (setresuid(uid, uid, uid) < 0)
2,004✔
1036
                return -errno;
×
1037

1038
        /* At this point we should have all necessary capabilities but are otherwise a normal user. However,
1039
         * the caps might got corrupted due to the setresuid() so we need clean them up later. This is done
1040
         * outside of this call. */
1041
        return 0;
1042
}
1043

1044
#if HAVE_PAM
1045

1046
static void pam_response_free_array(struct pam_response *responses, size_t n_responses) {
×
1047
        assert(responses || n_responses == 0);
×
1048

1049
        FOREACH_ARRAY(resp, responses, n_responses)
×
1050
                erase_and_free(resp->resp);
×
1051

1052
        free(responses);
×
1053
}
×
1054

1055
typedef struct AskPasswordConvData {
1056
        const ExecContext *context;
1057
        const ExecParameters *params;
1058
} AskPasswordConvData;
1059

1060
static int ask_password_conv(
2✔
1061
                int num_msg,
1062
                const struct pam_message *msg[],
1063
                struct pam_response **ret,
1064
                void *userdata) {
1065

1066
        AskPasswordConvData *data = ASSERT_PTR(userdata);
2✔
1067
        bool set_credential_env_var = false;
2✔
1068
        int r;
2✔
1069

1070
        assert(num_msg >= 0);
2✔
1071
        assert(msg);
2✔
1072
        assert(data->context);
2✔
1073
        assert(data->params);
2✔
1074

1075
        size_t n = num_msg;
2✔
1076
        struct pam_response *responses = new0(struct pam_response, n);
2✔
1077
        if (!responses)
2✔
1078
                return PAM_BUF_ERR;
2✔
1079
        CLEANUP_ARRAY(responses, n, pam_response_free_array);
2✔
1080

1081
        for (size_t i = 0; i < n; i++) {
4✔
1082
                const struct pam_message *mi = *msg + i;
2✔
1083

1084
                switch (mi->msg_style) {
2✔
1085

1086
                case PAM_PROMPT_ECHO_ON:
1✔
1087
                case PAM_PROMPT_ECHO_OFF: {
1088

1089
                        /* Locally set the $CREDENTIALS_DIRECTORY to the credentials directory we just populated */
1090
                        if (!set_credential_env_var) {
1✔
1091
                                _cleanup_free_ char *creds_dir = NULL;
1✔
1092
                                r = exec_context_get_credential_directory(data->context, data->params, data->params->unit_id, &creds_dir);
1✔
1093
                                if (r < 0)
1✔
1094
                                        return log_exec_error_errno(data->context, data->params, r, "Failed to determine credentials directory: %m");
×
1095

1096
                                if (creds_dir) {
1✔
1097
                                        if (setenv("CREDENTIALS_DIRECTORY", creds_dir, /* overwrite= */ true) < 0)
1✔
1098
                                                return log_exec_error_errno(data->context, data->params, r, "Failed to set $CREDENTIALS_DIRECTORY: %m");
×
1099
                                } else
1100
                                        (void) unsetenv("CREDENTIALS_DIRECTORY");
×
1101

1102
                                set_credential_env_var = true;
1✔
1103
                        }
1104

1105
                        _cleanup_free_ char *credential_name = strjoin("pam.authtok.", data->context->pam_name);
2✔
1106
                        if (!credential_name)
1✔
1107
                                return log_oom();
×
1108

1109
                        AskPasswordRequest req = {
2✔
1110
                                .message = mi->msg,
1✔
1111
                                .credential = credential_name,
1112
                                .tty_fd = -EBADF,
1113
                                .hup_fd = -EBADF,
1114
                                .until = usec_add(now(CLOCK_MONOTONIC), 15 * USEC_PER_SEC),
1✔
1115
                        };
1116

1117
                        _cleanup_strv_free_erase_ char **acquired = NULL;
×
1118
                        r = ask_password_auto(
1✔
1119
                                        &req,
1120
                                        ASK_PASSWORD_ACCEPT_CACHED|
1121
                                        ASK_PASSWORD_NO_TTY|
1122
                                        (mi->msg_style == PAM_PROMPT_ECHO_ON ? ASK_PASSWORD_ECHO : 0),
1✔
1123
                                        &acquired);
1124
                        if (r < 0) {
1✔
1125
                                log_exec_error_errno(data->context, data->params, r, "Failed to query for password: %m");
×
1126
                                return PAM_CONV_ERR;
×
1127
                        }
1128

1129
                        responses[i].resp = strdup(ASSERT_PTR(acquired[0]));
1✔
1130
                        if (!responses[i].resp) {
1✔
1131
                                log_oom();
×
1132
                                return PAM_BUF_ERR;
1133
                        }
1134
                        break;
1✔
1135
                }
1136

1137
                case PAM_ERROR_MSG:
×
1138
                        log_exec_error(data->context, data->params, "PAM: %s", mi->msg);
×
1139
                        break;
×
1140

1141
                case PAM_TEXT_INFO:
1✔
1142
                        log_exec_info(data->context, data->params, "PAM: %s", mi->msg);
3✔
1143
                        break;
1✔
1144

1145
                default:
1146
                        return PAM_CONV_ERR;
1147
                }
1148
        }
1149

1150
        *ret = TAKE_PTR(responses);
2✔
1151
        n = 0;
2✔
1152

1153
        return PAM_SUCCESS;
2✔
1154
}
1155

1156
static int pam_close_session_and_delete_credentials(pam_handle_t *handle, int flags) {
166✔
1157
        int r, s;
166✔
1158

1159
        assert(handle);
166✔
1160

1161
        r = pam_close_session(handle, flags);
166✔
1162
        if (r != PAM_SUCCESS)
166✔
1163
                log_debug("pam_close_session() failed: %s", pam_strerror(handle, r));
26✔
1164

1165
        s = pam_setcred(handle, PAM_DELETE_CRED | flags);
166✔
1166
        if (s != PAM_SUCCESS)
166✔
1167
                log_debug("pam_setcred(PAM_DELETE_CRED) failed: %s", pam_strerror(handle, s));
110✔
1168

1169
        return r != PAM_SUCCESS ? r : s;
166✔
1170
}
1171
#endif
1172

1173
static int setup_pam(
307✔
1174
                const ExecContext *context,
1175
                ExecParameters *params,
1176
                const char *user,
1177
                uid_t uid,
1178
                gid_t gid,
1179
                char ***env, /* updated on success */
1180
                const int fds[], size_t n_fds,
1181
                int exec_fd) {
1182

1183
#if HAVE_PAM
1184
        AskPasswordConvData conv_data = {
307✔
1185
                .context = context,
1186
                .params = params,
1187
        };
1188

1189
        const struct pam_conv conv = {
307✔
1190
                .conv = ask_password_conv,
1191
                .appdata_ptr = &conv_data,
1192
        };
1193

1194
        _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
307✔
1195
        _cleanup_strv_free_ char **e = NULL;
307✔
1196
        pam_handle_t *handle = NULL;
307✔
1197
        sigset_t old_ss;
307✔
1198
        int pam_code = PAM_SUCCESS, r;
307✔
1199
        bool close_session = false;
307✔
1200
        pid_t parent_pid;
307✔
1201
        int flags = 0;
307✔
1202

1203
        assert(context);
307✔
1204
        assert(params);
307✔
1205
        assert(user);
307✔
1206
        assert(uid_is_valid(uid));
307✔
1207
        assert(gid_is_valid(gid));
307✔
1208
        assert(fds || n_fds == 0);
307✔
1209
        assert(env);
307✔
1210

1211
        /* We set up PAM in the parent process, then fork. The child
1212
         * will then stay around until killed via PR_GET_PDEATHSIG or
1213
         * systemd via the cgroup logic. It will then remove the PAM
1214
         * session again. The parent process will exec() the actual
1215
         * daemon. We do things this way to ensure that the main PID
1216
         * of the daemon is the one we initially fork()ed. */
1217

1218
        r = barrier_create(&barrier);
307✔
1219
        if (r < 0)
307✔
1220
                goto fail;
×
1221

1222
        if (log_get_max_level() < LOG_DEBUG)
307✔
1223
                flags |= PAM_SILENT;
2✔
1224

1225
        pam_code = pam_start(context->pam_name, user, &conv, &handle);
307✔
1226
        if (pam_code != PAM_SUCCESS) {
307✔
1227
                handle = NULL;
×
1228
                goto fail;
×
1229
        }
1230

1231
        const char *tty = context->tty_path;
307✔
1232
        if (!tty) {
307✔
1233
                _cleanup_free_ char *q = NULL;
×
1234

1235
                /* Hmm, so no TTY was explicitly passed, but an fd passed to us directly might be a TTY. Let's figure
1236
                 * out if that's the case, and read the TTY off it. */
1237

1238
                if (getttyname_malloc(STDIN_FILENO, &q) >= 0)
300✔
1239
                        tty = strjoina("/dev/", q);
×
1240
        }
1241

1242
        if (tty) {
300✔
1243
                pam_code = pam_set_item(handle, PAM_TTY, tty);
7✔
1244
                if (pam_code != PAM_SUCCESS)
7✔
1245
                        goto fail;
×
1246
        }
1247

1248
        STRV_FOREACH(nv, *env) {
4,318✔
1249
                pam_code = pam_putenv(handle, *nv);
4,011✔
1250
                if (pam_code != PAM_SUCCESS)
4,011✔
1251
                        goto fail;
×
1252
        }
1253

1254
        pam_code = pam_acct_mgmt(handle, flags);
307✔
1255
        if (pam_code != PAM_SUCCESS)
307✔
1256
                goto fail;
×
1257

1258
        pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | flags);
307✔
1259
        if (pam_code != PAM_SUCCESS)
307✔
1260
                log_debug("pam_setcred(PAM_ESTABLISH_CRED) failed, ignoring: %s", pam_strerror(handle, pam_code));
247✔
1261

1262
        pam_code = pam_open_session(handle, flags);
307✔
1263
        if (pam_code != PAM_SUCCESS)
307✔
1264
                goto fail;
×
1265

1266
        close_session = true;
307✔
1267

1268
        e = pam_getenvlist(handle);
307✔
1269
        if (!e) {
307✔
1270
                pam_code = PAM_BUF_ERR;
×
1271
                goto fail;
×
1272
        }
1273

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

1276
        assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM) >= 0);
307✔
1277

1278
        parent_pid = getpid_cached();
307✔
1279

1280
        r = safe_fork("(sd-pam)", 0, NULL);
307✔
1281
        if (r < 0)
473✔
1282
                goto fail;
×
1283
        if (r == 0) {
473✔
1284
                int ret = EXIT_PAM;
166✔
1285

1286
                /* The child's job is to reset the PAM session on termination */
1287
                barrier_set_role(&barrier, BARRIER_CHILD);
166✔
1288

1289
                /* Make sure we don't keep open the passed fds in this child. We assume that otherwise only
1290
                 * those fds are open here that have been opened by PAM. */
1291
                (void) close_many(fds, n_fds);
166✔
1292

1293
                /* Also close the 'exec_fd' in the child, since the service manager waits for the EOF induced
1294
                 * by the execve() to wait for completion, and if we'd keep the fd open here in the child
1295
                 * we'd never signal completion. */
1296
                exec_fd = safe_close(exec_fd);
166✔
1297

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

1302
                r = fully_set_uid_gid(uid, gid, /* supplementary_gids= */ NULL, /* n_supplementary_gids= */ 0);
166✔
1303
                if (r < 0)
166✔
1304
                        log_warning_errno(r, "Failed to drop privileges in sd-pam: %m");
×
1305

1306
                (void) ignore_signals(SIGPIPE);
166✔
1307

1308
                /* Wait until our parent died. This will only work if the above setresuid() succeeds,
1309
                 * otherwise the kernel will not allow unprivileged parents kill their privileged children
1310
                 * this way. We rely on the control groups kill logic to do the rest for us. */
1311
                if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
166✔
1312
                        goto child_finish;
×
1313

1314
                /* Tell the parent that our setup is done. This is especially important regarding dropping
1315
                 * privileges. Otherwise, unit setup might race against our setresuid(2) call.
1316
                 *
1317
                 * If the parent aborted, we'll detect this below, hence ignore return failure here. */
1318
                (void) barrier_place(&barrier);
166✔
1319

1320
                /* Check if our parent process might already have died? */
1321
                if (getppid() == parent_pid) {
166✔
1322
                        sigset_t ss;
166✔
1323
                        int sig;
166✔
1324

1325
                        assert_se(sigemptyset(&ss) >= 0);
166✔
1326
                        assert_se(sigaddset(&ss, SIGTERM) >= 0);
166✔
1327

1328
                        assert_se(sigwait(&ss, &sig) == 0);
166✔
1329
                        assert(sig == SIGTERM);
166✔
1330
                }
1331

1332
                /* If our parent died we'll end the session */
1333
                if (getppid() != parent_pid) {
166✔
1334
                        pam_code = pam_close_session_and_delete_credentials(handle, flags);
166✔
1335
                        if (pam_code != PAM_SUCCESS)
166✔
1336
                                goto child_finish;
110✔
1337
                }
1338

1339
                ret = 0;
1340

1341
        child_finish:
166✔
1342
                /* NB: pam_end() when called in child processes should set PAM_DATA_SILENT to let the module
1343
                 * know about this. See pam_end(3) */
1344
                (void) pam_end(handle, pam_code | flags | PAM_DATA_SILENT);
166✔
1345
                _exit(ret);
166✔
1346
        }
1347

1348
        barrier_set_role(&barrier, BARRIER_PARENT);
307✔
1349

1350
        /* If the child was forked off successfully it will do all the cleanups, so forget about the handle
1351
         * here. */
1352
        handle = NULL;
307✔
1353

1354
        /* Unblock SIGTERM again in the parent */
1355
        assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0);
307✔
1356

1357
        /* We close the log explicitly here, since the PAM modules might have opened it, but we don't want
1358
         * this fd around. */
1359
        closelog();
307✔
1360

1361
        /* Synchronously wait for the child to initialize. We don't care for errors as we cannot
1362
         * recover. However, warn loudly if it happens. */
1363
        if (!barrier_place_and_sync(&barrier))
614✔
1364
                log_error("PAM initialization failed");
×
1365

1366
        return strv_free_and_replace(*env, e);
307✔
1367

1368
fail:
×
1369
        if (pam_code != PAM_SUCCESS) {
×
1370
                log_error("PAM failed: %s", pam_strerror(handle, pam_code));
×
1371
                r = -EPERM;  /* PAM errors do not map to errno */
1372
        } else
1373
                log_error_errno(r, "PAM failed: %m");
×
1374

1375
        if (handle) {
×
1376
                if (close_session)
×
1377
                        pam_code = pam_close_session_and_delete_credentials(handle, flags);
×
1378

1379
                (void) pam_end(handle, pam_code | flags);
×
1380
        }
1381

1382
        closelog();
×
1383
        return r;
1384
#else
1385
        return 0;
1386
#endif
1387
}
1388

1389
static void rename_process_from_path(const char *path) {
13,484✔
1390
        _cleanup_free_ char *buf = NULL;
13,484✔
1391
        const char *p;
13,484✔
1392

1393
        assert(path);
13,484✔
1394

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

1398
        if (path_extract_filename(path, &buf) < 0) {
13,484✔
1399
                rename_process("(...)");
×
1400
                return;
×
1401
        }
1402

1403
        size_t l = strlen(buf);
13,484✔
1404
        if (l > 8) {
13,484✔
1405
                /* The end of the process name is usually more interesting, since the first bit might just be
1406
                 * "systemd-" */
1407
                p = buf + l - 8;
9,490✔
1408
                l = 8;
9,490✔
1409
        } else
1410
                p = buf;
1411

1412
        char process_name[11];
13,484✔
1413
        process_name[0] = '(';
13,484✔
1414
        memcpy(process_name+1, p, l);
13,484✔
1415
        process_name[1+l] = ')';
13,484✔
1416
        process_name[1+l+1] = 0;
13,484✔
1417

1418
        (void) rename_process(process_name);
13,484✔
1419
}
1420

1421
static bool context_has_address_families(const ExecContext *c) {
13,790✔
1422
        assert(c);
13,790✔
1423

1424
        return c->address_families_allow_list ||
13,790✔
1425
                !set_isempty(c->address_families);
11,738✔
1426
}
1427

1428
static bool context_has_syscall_filters(const ExecContext *c) {
13,754✔
1429
        assert(c);
13,754✔
1430

1431
        return c->syscall_allow_list ||
13,754✔
1432
                !hashmap_isempty(c->syscall_filter);
11,715✔
1433
}
1434

1435
static bool context_has_syscall_logs(const ExecContext *c) {
13,754✔
1436
        assert(c);
13,754✔
1437

1438
        return c->syscall_log_allow_list ||
13,754✔
1439
                !hashmap_isempty(c->syscall_log);
13,754✔
1440
}
1441

1442
static bool context_has_seccomp(const ExecContext *c) {
3,538✔
1443
        /* We need NNP if we have any form of seccomp and are unprivileged */
1444
        return c->lock_personality ||
3,538✔
1445
                c->memory_deny_write_execute ||
2,726✔
1446
                c->private_devices ||
2,726✔
1447
                c->protect_clock ||
2,726✔
1448
                c->protect_hostname == PROTECT_HOSTNAME_YES ||
2,726✔
1449
                c->protect_kernel_tunables ||
1450
                c->protect_kernel_modules ||
2,726✔
1451
                c->protect_kernel_logs ||
2,726✔
1452
                context_has_address_families(c) ||
5,452✔
1453
                exec_context_restrict_namespaces_set(c) ||
2,726✔
1454
                c->restrict_realtime ||
2,726✔
1455
                c->restrict_suid_sgid ||
2,690✔
1456
                !set_isempty(c->syscall_archs) ||
5,380✔
1457
                context_has_syscall_filters(c) ||
8,918✔
1458
                context_has_syscall_logs(c);
2,690✔
1459
}
1460

1461
static bool context_has_no_new_privileges(const ExecContext *c) {
11,064✔
1462
        assert(c);
11,064✔
1463

1464
        if (c->no_new_privileges)
11,064✔
1465
                return true;
1466

1467
        if (have_effective_cap(CAP_SYS_ADMIN) > 0) /* if we are privileged, we don't need NNP */
9,138✔
1468
                return false;
1469

1470
        return context_has_seccomp(c);
1,534✔
1471
}
1472

1473
#if HAVE_SECCOMP
1474

1475
static bool seccomp_allows_drop_privileges(const ExecContext *c) {
848✔
1476
        void *id, *val;
848✔
1477
        bool has_capget = false, has_capset = false, has_prctl = false;
848✔
1478

1479
        assert(c);
848✔
1480

1481
        /* No syscall filter, we are allowed to drop privileges */
1482
        if (hashmap_isempty(c->syscall_filter))
848✔
1483
                return true;
848✔
1484

1485
        HASHMAP_FOREACH_KEY(val, id, c->syscall_filter) {
303,810✔
1486
                _cleanup_free_ char *name = NULL;
303,012✔
1487

1488
                name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
303,012✔
1489

1490
                if (streq(name, "capget"))
303,012✔
1491
                        has_capget = true;
1492
                else if (streq(name, "capset"))
302,214✔
1493
                        has_capset = true;
1494
                else if (streq(name, "prctl"))
301,416✔
1495
                        has_prctl = true;
798✔
1496
        }
1497

1498
        if (c->syscall_allow_list)
798✔
1499
                return has_capget && has_capset && has_prctl;
798✔
1500
        else
1501
                return !(has_capget || has_capset || has_prctl);
×
1502
}
1503

1504
static bool skip_seccomp_unavailable(const ExecContext *c, const ExecParameters *p, const char* msg) {
21,047✔
1505

1506
        if (is_seccomp_available())
21,047✔
1507
                return false;
1508

1509
        log_exec_debug(c, p, "SECCOMP features not detected in the kernel, skipping %s", msg);
×
1510
        return true;
×
1511
}
1512

1513
static int apply_syscall_filter(const ExecContext *c, const ExecParameters *p) {
11,064✔
1514
        uint32_t negative_action, default_action, action;
11,064✔
1515
        int r;
11,064✔
1516

1517
        assert(c);
11,064✔
1518
        assert(p);
11,064✔
1519

1520
        if (!context_has_syscall_filters(c))
11,064✔
1521
                return 0;
1522

1523
        if (skip_seccomp_unavailable(c, p, "SystemCallFilter="))
2,040✔
1524
                return 0;
1525

1526
        negative_action = c->syscall_errno == SECCOMP_ERROR_NUMBER_KILL ? scmp_act_kill_process() : SCMP_ACT_ERRNO(c->syscall_errno);
2,040✔
1527

1528
        if (c->syscall_allow_list) {
2,040✔
1529
                default_action = negative_action;
1530
                action = SCMP_ACT_ALLOW;
1531
        } else {
1532
                default_action = SCMP_ACT_ALLOW;
1✔
1533
                action = negative_action;
1✔
1534
        }
1535

1536
        /* Sending over exec_fd or handoff_timestamp_fd requires write() syscall. */
1537
        if (p->exec_fd >= 0 || p->handoff_timestamp_fd >= 0) {
2,040✔
1538
                r = seccomp_filter_set_add_by_name(c->syscall_filter, c->syscall_allow_list, "write");
2,040✔
1539
                if (r < 0)
2,040✔
1540
                        return r;
1541
        }
1542

1543
        return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_filter, action, false);
2,040✔
1544
}
1545

1546
static int apply_syscall_log(const ExecContext *c, const ExecParameters *p) {
11,064✔
1547
#ifdef SCMP_ACT_LOG
1548
        uint32_t default_action, action;
11,064✔
1549
#endif
1550

1551
        assert(c);
11,064✔
1552
        assert(p);
11,064✔
1553

1554
        if (!context_has_syscall_logs(c))
11,064✔
1555
                return 0;
1556

1557
#ifdef SCMP_ACT_LOG
1558
        if (skip_seccomp_unavailable(c, p, "SystemCallLog="))
×
1559
                return 0;
1560

1561
        if (c->syscall_log_allow_list) {
×
1562
                /* Log nothing but the ones listed */
1563
                default_action = SCMP_ACT_ALLOW;
1564
                action = SCMP_ACT_LOG;
1565
        } else {
1566
                /* Log everything but the ones listed */
1567
                default_action = SCMP_ACT_LOG;
×
1568
                action = SCMP_ACT_ALLOW;
×
1569
        }
1570

1571
        return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_log, action, false);
×
1572
#else
1573
        /* old libseccomp */
1574
        log_exec_debug(c, p, "SECCOMP feature SCMP_ACT_LOG not available, skipping SystemCallLog=");
1575
        return 0;
1576
#endif
1577
}
1578

1579
static int apply_syscall_archs(const ExecContext *c, const ExecParameters *p) {
11,064✔
1580
        assert(c);
11,064✔
1581
        assert(p);
11,064✔
1582

1583
        if (set_isempty(c->syscall_archs))
11,064✔
1584
                return 0;
1585

1586
        if (skip_seccomp_unavailable(c, p, "SystemCallArchitectures="))
2,055✔
1587
                return 0;
1588

1589
        return seccomp_restrict_archs(c->syscall_archs);
2,055✔
1590
}
1591

1592
static int apply_address_families(const ExecContext *c, const ExecParameters *p) {
11,064✔
1593
        assert(c);
11,064✔
1594
        assert(p);
11,064✔
1595

1596
        if (!context_has_address_families(c))
11,064✔
1597
                return 0;
1598

1599
        if (skip_seccomp_unavailable(c, p, "RestrictAddressFamilies="))
2,052✔
1600
                return 0;
1601

1602
        return seccomp_restrict_address_families(c->address_families, c->address_families_allow_list);
2,052✔
1603
}
1604

1605
static int apply_memory_deny_write_execute(const ExecContext *c, const ExecParameters *p) {
11,064✔
1606
        int r;
11,064✔
1607

1608
        assert(c);
11,064✔
1609
        assert(p);
11,064✔
1610

1611
        if (!c->memory_deny_write_execute)
11,064✔
1612
                return 0;
1613

1614
        /* use prctl() if kernel supports it (6.3) */
1615
        r = prctl(PR_SET_MDWE, PR_MDWE_REFUSE_EXEC_GAIN, 0, 0, 0);
2,052✔
1616
        if (r == 0) {
2,052✔
1617
                log_exec_debug(c, p, "Enabled MemoryDenyWriteExecute= with PR_SET_MDWE");
6,156✔
1618
                return 0;
2,052✔
1619
        }
1620
        if (r < 0 && errno != EINVAL)
×
1621
                return log_exec_debug_errno(c,
×
1622
                                            p,
1623
                                            errno,
1624
                                            "Failed to enable MemoryDenyWriteExecute= with PR_SET_MDWE: %m");
1625
        /* else use seccomp */
1626
        log_exec_debug(c, p, "Kernel doesn't support PR_SET_MDWE: falling back to seccomp");
×
1627

1628
        if (skip_seccomp_unavailable(c, p, "MemoryDenyWriteExecute="))
×
1629
                return 0;
1630

1631
        return seccomp_memory_deny_write_execute();
×
1632
}
1633

1634
static int apply_restrict_realtime(const ExecContext *c, const ExecParameters *p) {
11,064✔
1635
        assert(c);
11,064✔
1636
        assert(p);
11,064✔
1637

1638
        if (!c->restrict_realtime)
11,064✔
1639
                return 0;
1640

1641
        if (skip_seccomp_unavailable(c, p, "RestrictRealtime="))
2,052✔
1642
                return 0;
1643

1644
        return seccomp_restrict_realtime();
2,052✔
1645
}
1646

1647
static int apply_restrict_suid_sgid(const ExecContext *c, const ExecParameters *p) {
11,064✔
1648
        assert(c);
11,064✔
1649
        assert(p);
11,064✔
1650

1651
        if (!c->restrict_suid_sgid)
11,064✔
1652
                return 0;
1653

1654
        if (skip_seccomp_unavailable(c, p, "RestrictSUIDSGID="))
1,971✔
1655
                return 0;
1656

1657
        return seccomp_restrict_suid_sgid();
1,971✔
1658
}
1659

1660
static int apply_protect_sysctl(const ExecContext *c, const ExecParameters *p) {
11,064✔
1661
        assert(c);
11,064✔
1662
        assert(p);
11,064✔
1663

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

1667
        if (!c->protect_kernel_tunables)
11,064✔
1668
                return 0;
1669

1670
        if (skip_seccomp_unavailable(c, p, "ProtectKernelTunables="))
714✔
1671
                return 0;
1672

1673
        return seccomp_protect_sysctl();
714✔
1674
}
1675

1676
static int apply_protect_kernel_modules(const ExecContext *c, const ExecParameters *p) {
11,064✔
1677
        assert(c);
11,064✔
1678
        assert(p);
11,064✔
1679

1680
        /* Turn off module syscalls on ProtectKernelModules=yes */
1681

1682
        if (!c->protect_kernel_modules)
11,064✔
1683
                return 0;
1684

1685
        if (skip_seccomp_unavailable(c, p, "ProtectKernelModules="))
1,584✔
1686
                return 0;
1687

1688
        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_MODULE, SCMP_ACT_ERRNO(EPERM), false);
1,584✔
1689
}
1690

1691
static int apply_protect_kernel_logs(const ExecContext *c, const ExecParameters *p) {
11,064✔
1692
        assert(c);
11,064✔
1693
        assert(p);
11,064✔
1694

1695
        if (!c->protect_kernel_logs)
11,064✔
1696
                return 0;
1697

1698
        if (skip_seccomp_unavailable(c, p, "ProtectKernelLogs="))
1,584✔
1699
                return 0;
1700

1701
        return seccomp_protect_syslog();
1,584✔
1702
}
1703

1704
static int apply_protect_clock(const ExecContext *c, const ExecParameters *p) {
11,064✔
1705
        assert(c);
11,064✔
1706
        assert(p);
11,064✔
1707

1708
        if (!c->protect_clock)
11,064✔
1709
                return 0;
1710

1711
        if (skip_seccomp_unavailable(c, p, "ProtectClock="))
940✔
1712
                return 0;
1713

1714
        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_CLOCK, SCMP_ACT_ERRNO(EPERM), false);
940✔
1715
}
1716

1717
static int apply_private_devices(const ExecContext *c, const ExecParameters *p) {
11,064✔
1718
        assert(c);
11,064✔
1719
        assert(p);
11,064✔
1720

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

1723
        if (!c->private_devices)
11,064✔
1724
                return 0;
1725

1726
        if (skip_seccomp_unavailable(c, p, "PrivateDevices="))
1,189✔
1727
                return 0;
1728

1729
        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_RAW_IO, SCMP_ACT_ERRNO(EPERM), false);
1,189✔
1730
}
1731

1732
static int apply_restrict_namespaces(const ExecContext *c, const ExecParameters *p) {
11,064✔
1733
        assert(c);
11,064✔
1734
        assert(p);
11,064✔
1735

1736
        if (!exec_context_restrict_namespaces_set(c))
11,064✔
1737
                return 0;
1738

1739
        if (skip_seccomp_unavailable(c, p, "RestrictNamespaces="))
1,693✔
1740
                return 0;
1741

1742
        return seccomp_restrict_namespaces(c->restrict_namespaces);
1,693✔
1743
}
1744

1745
static int apply_lock_personality(const ExecContext *c, const ExecParameters *p) {
11,064✔
1746
        unsigned long personality;
11,064✔
1747
        int r;
11,064✔
1748

1749
        assert(c);
11,064✔
1750
        assert(p);
11,064✔
1751

1752
        if (!c->lock_personality)
11,064✔
1753
                return 0;
11,064✔
1754

1755
        if (skip_seccomp_unavailable(c, p, "LockPersonality="))
2,052✔
1756
                return 0;
1757

1758
        personality = c->personality;
2,052✔
1759

1760
        /* If personality is not specified, use either PER_LINUX or PER_LINUX32 depending on what is currently set. */
1761
        if (personality == PERSONALITY_INVALID) {
2,052✔
1762

1763
                r = opinionated_personality(&personality);
2,052✔
1764
                if (r < 0)
2,052✔
1765
                        return r;
1766
        }
1767

1768
        return seccomp_lock_personality(personality);
2,052✔
1769
}
1770

1771
#endif
1772

1773
#if HAVE_LIBBPF
1774
static int apply_restrict_filesystems(const ExecContext *c, const ExecParameters *p) {
11,064✔
1775
        int r;
11,064✔
1776

1777
        assert(c);
11,064✔
1778
        assert(p);
11,064✔
1779

1780
        if (!exec_context_restrict_filesystems_set(c))
11,064✔
1781
                return 0;
1782

1783
        if (p->bpf_restrict_fs_map_fd < 0) {
×
1784
                /* LSM BPF is unsupported or lsm_bpf_setup failed */
1785
                log_exec_debug(c, p, "LSM BPF not supported, skipping RestrictFileSystems=");
×
1786
                return 0;
×
1787
        }
1788

1789
        /* We are in a new binary, so dl-open again */
1790
        r = dlopen_bpf();
×
1791
        if (r < 0)
×
1792
                return r;
1793

1794
        return bpf_restrict_fs_update(c->restrict_filesystems, p->cgroup_id, p->bpf_restrict_fs_map_fd, c->restrict_filesystems_allow_list);
×
1795
}
1796
#endif
1797

1798
static int apply_protect_hostname(const ExecContext *c, const ExecParameters *p, int *ret_exit_status) {
11,067✔
1799
        int r;
11,067✔
1800

1801
        assert(c);
11,067✔
1802
        assert(p);
11,067✔
1803

1804
        if (c->protect_hostname == PROTECT_HOSTNAME_NO)
11,067✔
1805
                return 0;
1806

1807
        if (ns_type_supported(NAMESPACE_UTS)) {
1,125✔
1808
                if (unshare(CLONE_NEWUTS) < 0) {
1,125✔
1809
                        if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno)) {
×
1810
                                *ret_exit_status = EXIT_NAMESPACE;
×
1811
                                return log_exec_error_errno(c, p, errno, "Failed to set up UTS namespacing: %m");
×
1812
                        }
1813

1814
                        log_exec_warning(c, p,
×
1815
                                         "ProtectHostname=%s is configured, but UTS namespace setup is prohibited (container manager?), ignoring namespace setup.",
1816
                                         protect_hostname_to_string(c->protect_hostname));
1817

1818
                } else if (c->private_hostname) {
1,125✔
1819
                        r = sethostname_idempotent(c->private_hostname);
4✔
1820
                        if (r < 0) {
4✔
1821
                                *ret_exit_status = EXIT_NAMESPACE;
×
1822
                                return log_exec_error_errno(c, p, r, "Failed to set private hostname '%s': %m", c->private_hostname);
×
1823
                        }
1824
                }
1825
        } else
1826
                log_exec_warning(c, p,
×
1827
                                 "ProtectHostname=%s is configured, but the kernel does not support UTS namespaces, ignoring namespace setup.",
1828
                                 protect_hostname_to_string(c->protect_hostname));
1829

1830
#if HAVE_SECCOMP
1831
        if (c->protect_hostname == PROTECT_HOSTNAME_YES) {
1,125✔
1832
                if (skip_seccomp_unavailable(c, p, "ProtectHostname="))
1,121✔
1833
                        return 0;
1834

1835
                r = seccomp_protect_hostname();
1,121✔
1836
                if (r < 0) {
1,121✔
1837
                        *ret_exit_status = EXIT_SECCOMP;
×
1838
                        return log_exec_error_errno(c, p, r, "Failed to apply hostname restrictions: %m");
×
1839
                }
1840
        }
1841
#endif
1842

1843
        return 0;
1844
}
1845

1846
static void do_idle_pipe_dance(int idle_pipe[static 4]) {
159✔
1847
        assert(idle_pipe);
159✔
1848

1849
        idle_pipe[1] = safe_close(idle_pipe[1]);
159✔
1850
        idle_pipe[2] = safe_close(idle_pipe[2]);
159✔
1851

1852
        if (idle_pipe[0] >= 0) {
159✔
1853
                int r;
159✔
1854

1855
                r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
159✔
1856

1857
                if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
159✔
1858
                        ssize_t n;
112✔
1859

1860
                        /* Signal systemd that we are bored and want to continue. */
1861
                        n = write(idle_pipe[3], "x", 1);
112✔
1862
                        if (n > 0)
112✔
1863
                                /* Wait for systemd to react to the signal above. */
1864
                                (void) fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
112✔
1865
                }
1866

1867
                idle_pipe[0] = safe_close(idle_pipe[0]);
159✔
1868

1869
        }
1870

1871
        idle_pipe[3] = safe_close(idle_pipe[3]);
159✔
1872
}
159✔
1873

1874
static const char *exec_directory_env_name_to_string(ExecDirectoryType t);
1875

1876
/* And this table also maps ExecDirectoryType, to the environment variable we pass the selected directory to
1877
 * the service payload in. */
1878
static const char* const exec_directory_env_name_table[_EXEC_DIRECTORY_TYPE_MAX] = {
1879
        [EXEC_DIRECTORY_RUNTIME]       = "RUNTIME_DIRECTORY",
1880
        [EXEC_DIRECTORY_STATE]         = "STATE_DIRECTORY",
1881
        [EXEC_DIRECTORY_CACHE]         = "CACHE_DIRECTORY",
1882
        [EXEC_DIRECTORY_LOGS]          = "LOGS_DIRECTORY",
1883
        [EXEC_DIRECTORY_CONFIGURATION] = "CONFIGURATION_DIRECTORY",
1884
};
1885

1886
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(exec_directory_env_name, ExecDirectoryType);
2,692✔
1887

1888
static int build_environment(
11,086✔
1889
                const ExecContext *c,
1890
                const ExecParameters *p,
1891
                const CGroupContext *cgroup_context,
1892
                size_t n_fds,
1893
                const char *home,
1894
                const char *username,
1895
                const char *shell,
1896
                dev_t journal_stream_dev,
1897
                ino_t journal_stream_ino,
1898
                const char *memory_pressure_path,
1899
                bool needs_sandboxing,
1900
                char ***ret) {
1901

1902
        _cleanup_strv_free_ char **our_env = NULL;
11,086✔
1903
        size_t n_env = 0;
11,086✔
1904
        char *x;
11,086✔
1905
        int r;
11,086✔
1906

1907
        assert(c);
11,086✔
1908
        assert(p);
11,086✔
1909
        assert(ret);
11,086✔
1910

1911
#define N_ENV_VARS 20
1912
        our_env = new0(char*, N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
11,086✔
1913
        if (!our_env)
11,086✔
1914
                return -ENOMEM;
1915

1916
        if (n_fds > 0) {
11,086✔
1917
                _cleanup_free_ char *joined = NULL;
1,572✔
1918

1919
                if (asprintf(&x, "LISTEN_PID="PID_FMT, getpid_cached()) < 0)
1,572✔
1920
                        return -ENOMEM;
1921
                our_env[n_env++] = x;
1,572✔
1922

1923
                if (asprintf(&x, "LISTEN_FDS=%zu", n_fds) < 0)
1,572✔
1924
                        return -ENOMEM;
1925
                our_env[n_env++] = x;
1,572✔
1926

1927
                joined = strv_join(p->fd_names, ":");
1,572✔
1928
                if (!joined)
1,572✔
1929
                        return -ENOMEM;
1930

1931
                x = strjoin("LISTEN_FDNAMES=", joined);
1,572✔
1932
                if (!x)
1,572✔
1933
                        return -ENOMEM;
1934
                our_env[n_env++] = x;
1,572✔
1935
        }
1936

1937
        if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) {
11,086✔
1938
                if (asprintf(&x, "WATCHDOG_PID="PID_FMT, getpid_cached()) < 0)
2,044✔
1939
                        return -ENOMEM;
1940
                our_env[n_env++] = x;
2,044✔
1941

1942
                if (asprintf(&x, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec) < 0)
2,044✔
1943
                        return -ENOMEM;
1944
                our_env[n_env++] = x;
2,044✔
1945
        }
1946

1947
        /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use blocking
1948
         * Varlink calls back to us for look up dynamic users in PID 1. Break the deadlock between D-Bus and
1949
         * PID 1 by disabling use of PID1' NSS interface for looking up dynamic users. */
1950
        if (p->flags & EXEC_NSS_DYNAMIC_BYPASS) {
11,086✔
1951
                x = strdup("SYSTEMD_NSS_DYNAMIC_BYPASS=1");
175✔
1952
                if (!x)
175✔
1953
                        return -ENOMEM;
1954
                our_env[n_env++] = x;
175✔
1955
        }
1956

1957
        /* We query "root" if this is a system unit and User= is not specified. $USER is always set. $HOME
1958
         * could cause problem for e.g. getty, since login doesn't override $HOME, and $LOGNAME and $SHELL don't
1959
         * really make much sense since we're not logged in. Hence we conditionalize the three based on
1960
         * SetLoginEnvironment= switch. */
1961
        if (!c->user && !c->dynamic_user && p->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
11,086✔
1962
                r = get_fixed_user("root", &username, NULL, NULL, &home, &shell);
8,505✔
1963
                if (r < 0)
8,505✔
1964
                        return log_exec_debug_errno(c,
×
1965
                                                    p,
1966
                                                    r,
1967
                                                    "Failed to determine user credentials for root: %m");
1968
        }
1969

1970
        bool set_user_login_env = exec_context_get_set_login_environment(c);
11,086✔
1971

1972
        if (username) {
11,086✔
1973
                x = strjoin("USER=", username);
10,451✔
1974
                if (!x)
10,451✔
1975
                        return -ENOMEM;
1976
                our_env[n_env++] = x;
10,451✔
1977

1978
                if (set_user_login_env) {
10,451✔
1979
                        x = strjoin("LOGNAME=", username);
2,005✔
1980
                        if (!x)
2,005✔
1981
                                return -ENOMEM;
1982
                        our_env[n_env++] = x;
2,005✔
1983
                }
1984
        }
1985

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

1989
        if (home && set_user_login_env && !empty_or_root(home)) {
11,086✔
1990
                x = strjoin("HOME=", home);
319✔
1991
                if (!x)
319✔
1992
                        return -ENOMEM;
1993

1994
                path_simplify(x + 5);
319✔
1995
                our_env[n_env++] = x;
319✔
1996
        }
1997

1998
        if (shell && set_user_login_env && !shell_is_placeholder(shell)) {
11,086✔
1999
                x = strjoin("SHELL=", shell);
320✔
2000
                if (!x)
320✔
2001
                        return -ENOMEM;
2002

2003
                path_simplify(x + 6);
320✔
2004
                our_env[n_env++] = x;
320✔
2005
        }
2006

2007
        if (!sd_id128_is_null(p->invocation_id)) {
11,086✔
2008
                assert(p->invocation_id_string);
11,086✔
2009

2010
                x = strjoin("INVOCATION_ID=", p->invocation_id_string);
11,086✔
2011
                if (!x)
11,086✔
2012
                        return -ENOMEM;
2013

2014
                our_env[n_env++] = x;
11,086✔
2015
        }
2016

2017
        if (exec_context_needs_term(c)) {
11,086✔
2018
                _cleanup_free_ char *cmdline = NULL;
453✔
2019
                const char *tty_path, *term = NULL;
453✔
2020

2021
                tty_path = exec_context_tty_path(c);
453✔
2022

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

2027
                if (path_equal(tty_path, "/dev/console") && getppid() == 1)
453✔
2028
                        term = getenv("TERM");
393✔
2029
                else if (tty_path && in_charset(skip_dev_prefix(tty_path), ALPHANUMERICAL)) {
60✔
2030
                        _cleanup_free_ char *key = NULL;
44✔
2031

2032
                        key = strjoin("systemd.tty.term.", skip_dev_prefix(tty_path));
44✔
2033
                        if (!key)
44✔
2034
                                return -ENOMEM;
×
2035

2036
                        r = proc_cmdline_get_key(key, 0, &cmdline);
44✔
2037
                        if (r < 0)
44✔
2038
                                log_exec_debug_errno(c,
×
2039
                                                     p,
2040
                                                     r,
2041
                                                     "Failed to read %s from kernel cmdline, ignoring: %m",
2042
                                                     key);
2043
                        else if (r > 0)
44✔
2044
                                term = cmdline;
×
2045
                }
2046

2047
                if (!term)
437✔
2048
                        term = default_term_for_tty(tty_path);
60✔
2049

2050
                x = strjoin("TERM=", term);
453✔
2051
                if (!x)
453✔
2052
                        return -ENOMEM;
2053
                our_env[n_env++] = x;
453✔
2054
        }
2055

2056
        if (journal_stream_dev != 0 && journal_stream_ino != 0) {
11,086✔
2057
                if (asprintf(&x, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino) < 0)
10,316✔
2058
                        return -ENOMEM;
2059

2060
                our_env[n_env++] = x;
10,316✔
2061
        }
2062

2063
        if (c->log_namespace) {
11,086✔
2064
                x = strjoin("LOG_NAMESPACE=", c->log_namespace);
2✔
2065
                if (!x)
2✔
2066
                        return -ENOMEM;
2067

2068
                our_env[n_env++] = x;
2✔
2069
        }
2070

2071
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
66,516✔
2072
                _cleanup_free_ char *joined = NULL;
55,430✔
2073
                const char *n;
55,430✔
2074

2075
                if (!p->prefix[t])
55,430✔
2076
                        continue;
×
2077

2078
                if (c->directories[t].n_items == 0)
55,430✔
2079
                        continue;
52,738✔
2080

2081
                n = exec_directory_env_name_to_string(t);
2,692✔
2082
                if (!n)
2,692✔
2083
                        continue;
×
2084

2085
                for (size_t i = 0; i < c->directories[t].n_items; i++) {
5,880✔
2086
                        _cleanup_free_ char *prefixed = NULL;
3,188✔
2087

2088
                        prefixed = path_join(p->prefix[t], c->directories[t].items[i].path);
3,188✔
2089
                        if (!prefixed)
3,188✔
2090
                                return -ENOMEM;
2091

2092
                        if (!strextend_with_separator(&joined, ":", prefixed))
3,188✔
2093
                                return -ENOMEM;
2094
                }
2095

2096
                x = strjoin(n, "=", joined);
2,692✔
2097
                if (!x)
2,692✔
2098
                        return -ENOMEM;
2099

2100
                our_env[n_env++] = x;
2,692✔
2101
        }
2102

2103
        _cleanup_free_ char *creds_dir = NULL;
11,086✔
2104
        r = exec_context_get_credential_directory(c, p, p->unit_id, &creds_dir);
11,086✔
2105
        if (r < 0)
11,086✔
2106
                return r;
2107
        if (r > 0) {
11,086✔
2108
                x = strjoin("CREDENTIALS_DIRECTORY=", creds_dir);
2,386✔
2109
                if (!x)
2,386✔
2110
                        return -ENOMEM;
2111

2112
                our_env[n_env++] = x;
2,386✔
2113
        }
2114

2115
        if (asprintf(&x, "SYSTEMD_EXEC_PID=" PID_FMT, getpid_cached()) < 0)
11,086✔
2116
                return -ENOMEM;
2117

2118
        our_env[n_env++] = x;
11,086✔
2119

2120
        if (memory_pressure_path) {
11,086✔
2121
                x = strjoin("MEMORY_PRESSURE_WATCH=", memory_pressure_path);
10,731✔
2122
                if (!x)
10,731✔
2123
                        return -ENOMEM;
2124

2125
                our_env[n_env++] = x;
10,731✔
2126

2127
                if (cgroup_context && !path_equal(memory_pressure_path, "/dev/null")) {
21,462✔
2128
                        _cleanup_free_ char *b = NULL, *e = NULL;
10,731✔
2129

2130
                        if (asprintf(&b, "%s " USEC_FMT " " USEC_FMT,
10,731✔
2131
                                     MEMORY_PRESSURE_DEFAULT_TYPE,
2132
                                     cgroup_context->memory_pressure_threshold_usec == USEC_INFINITY ? MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC :
10,731✔
2133
                                     CLAMP(cgroup_context->memory_pressure_threshold_usec, 1U, MEMORY_PRESSURE_DEFAULT_WINDOW_USEC),
10,731✔
2134
                                     MEMORY_PRESSURE_DEFAULT_WINDOW_USEC) < 0)
2135
                                return -ENOMEM;
2136

2137
                        if (base64mem(b, strlen(b) + 1, &e) < 0)
10,731✔
2138
                                return -ENOMEM;
2139

2140
                        x = strjoin("MEMORY_PRESSURE_WRITE=", e);
10,731✔
2141
                        if (!x)
10,731✔
2142
                                return -ENOMEM;
2143

2144
                        our_env[n_env++] = x;
10,731✔
2145
                }
2146
        }
2147

2148
        if (p->notify_socket) {
11,086✔
2149
                x = strjoin("NOTIFY_SOCKET=", exec_get_private_notify_socket_path(c, p, needs_sandboxing) ?: p->notify_socket);
2,454✔
2150
                if (!x)
2,454✔
2151
                        return -ENOMEM;
2152

2153
                our_env[n_env++] = x;
2,454✔
2154
        }
2155

2156
        assert(n_env < N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
11,086✔
2157
#undef N_ENV_VARS
2158

2159
        *ret = TAKE_PTR(our_env);
11,086✔
2160

2161
        return 0;
11,086✔
2162
}
2163

2164
static int build_pass_environment(const ExecContext *c, char ***ret) {
11,086✔
2165
        _cleanup_strv_free_ char **pass_env = NULL;
11,086✔
2166
        size_t n_env = 0;
11,086✔
2167

2168
        STRV_FOREACH(i, c->pass_environment) {
11,405✔
2169
                _cleanup_free_ char *x = NULL;
×
2170
                char *v;
319✔
2171

2172
                v = getenv(*i);
319✔
2173
                if (!v)
319✔
2174
                        continue;
×
2175
                x = strjoin(*i, "=", v);
319✔
2176
                if (!x)
319✔
2177
                        return -ENOMEM;
2178

2179
                if (!GREEDY_REALLOC(pass_env, n_env + 2))
319✔
2180
                        return -ENOMEM;
2181

2182
                pass_env[n_env++] = TAKE_PTR(x);
319✔
2183
                pass_env[n_env] = NULL;
319✔
2184
        }
2185

2186
        *ret = TAKE_PTR(pass_env);
11,086✔
2187

2188
        return 0;
11,086✔
2189
}
2190

2191
static int setup_private_users(PrivateUsers private_users, uid_t ouid, gid_t ogid, uid_t uid, gid_t gid, bool allow_setgroups) {
11,070✔
2192
        _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
11,070✔
2193
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
11,070✔
2194
        _cleanup_close_ int unshare_ready_fd = -EBADF;
11,070✔
2195
        _cleanup_(sigkill_waitp) pid_t pid = 0;
11,070✔
2196
        uint64_t c = 1;
11,070✔
2197
        ssize_t n;
11,070✔
2198
        int r;
11,070✔
2199

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

2210
        if (private_users == PRIVATE_USERS_NO)
11,070✔
2211
                return 0;
2212

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

2256
        if (private_users == PRIVATE_USERS_IDENTITY) {
35✔
2257
                gid_map = strdup("0 0 65536\n");
2✔
2258
                if (!gid_map)
2✔
2259
                        return -ENOMEM;
2260
        } else if (private_users == PRIVATE_USERS_FULL) {
33✔
2261
                r = asprintf(&gid_map, "0 0 1\n"
3✔
2262
                                       "1 1 " GID_FMT "\n", (gid_t) (UINT32_MAX - 1));
2263
                if (r < 0)
3✔
2264
                        return -ENOMEM;
2265
        /* Can only set up multiple mappings with CAP_SETGID. */
2266
        } else if (have_effective_cap(CAP_SETGID) > 0 && gid != ogid && gid_is_valid(gid)) {
36✔
2267
                r = asprintf(&gid_map,
×
2268
                             GID_FMT " " GID_FMT " 1\n"     /* Map $OGID → $OGID */
2269
                             GID_FMT " " GID_FMT " 1\n",    /* Map $GID → $GID */
2270
                             ogid, ogid, gid, gid);
2271
                if (r < 0)
×
2272
                        return -ENOMEM;
2273
        } else {
2274
                r = asprintf(&gid_map,
30✔
2275
                             GID_FMT " " GID_FMT " 1\n",    /* Map $OGID -> $OGID */
2276
                             ogid, ogid);
2277
                if (r < 0)
30✔
2278
                        return -ENOMEM;
2279
        }
2280

2281
        /* Create a communication channel so that the parent can tell the child when it finished creating the user
2282
         * namespace. */
2283
        unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
35✔
2284
        if (unshare_ready_fd < 0)
35✔
2285
                return -errno;
×
2286

2287
        /* Create a communication channel so that the child can tell the parent a proper error code in case it
2288
         * failed. */
2289
        if (pipe2(errno_pipe, O_CLOEXEC) < 0)
35✔
2290
                return -errno;
×
2291

2292
        r = safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL, &pid);
35✔
2293
        if (r < 0)
72✔
2294
                return r;
2295
        if (r == 0) {
72✔
2296
                _cleanup_close_ int fd = -EBADF;
×
2297
                const char *a;
37✔
2298
                pid_t ppid;
37✔
2299

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

2303
                ppid = getppid();
37✔
2304
                errno_pipe[0] = safe_close(errno_pipe[0]);
37✔
2305

2306
                /* Wait until the parent unshared the user namespace */
2307
                if (read(unshare_ready_fd, &c, sizeof(c)) < 0)
37✔
2308
                        report_errno_and_exit(errno_pipe[1], -errno);
×
2309

2310
                /* Disable the setgroups() system call in the child user namespace, for good, unless PrivateUsers=full
2311
                 * and using the system service manager. */
2312
                a = procfs_file_alloca(ppid, "setgroups");
37✔
2313
                fd = open(a, O_WRONLY|O_CLOEXEC);
37✔
2314
                if (fd < 0) {
37✔
2315
                        if (errno != ENOENT) {
×
2316
                                r = log_debug_errno(errno, "Failed to open %s: %m", a);
×
2317
                                report_errno_and_exit(errno_pipe[1], r);
×
2318
                        }
2319

2320
                        /* If the file is missing the kernel is too old, let's continue anyway. */
2321
                } else {
2322
                        const char *setgroups = allow_setgroups ? "allow\n" : "deny\n";
37✔
2323
                        if (write(fd, setgroups, strlen(setgroups)) < 0) {
37✔
2324
                                r = log_debug_errno(errno, "Failed to write '%s' to %s: %m", setgroups, a);
×
2325
                                report_errno_and_exit(errno_pipe[1], r);
×
2326
                        }
2327

2328
                        fd = safe_close(fd);
37✔
2329
                }
2330

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

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

2344
                fd = safe_close(fd);
37✔
2345

2346
                /* The write the UID map */
2347
                a = procfs_file_alloca(ppid, "uid_map");
37✔
2348
                fd = open(a, O_WRONLY|O_CLOEXEC);
37✔
2349
                if (fd < 0) {
37✔
2350
                        r = log_debug_errno(errno, "Failed to open %s: %m", a);
×
2351
                        report_errno_and_exit(errno_pipe[1], r);
×
2352
                }
2353

2354
                if (write(fd, uid_map, strlen(uid_map)) < 0) {
37✔
2355
                        r = log_debug_errno(errno, "Failed to write UID map to %s: %m", a);
×
2356
                        report_errno_and_exit(errno_pipe[1], r);
×
2357
                }
2358

2359
                _exit(EXIT_SUCCESS);
37✔
2360
        }
2361

2362
        errno_pipe[1] = safe_close(errno_pipe[1]);
35✔
2363

2364
        if (unshare(CLONE_NEWUSER) < 0)
35✔
2365
                return log_debug_errno(errno, "Failed to unshare user namespace: %m");
×
2366

2367
        /* Let the child know that the namespace is ready now */
2368
        if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
35✔
2369
                return -errno;
×
2370

2371
        /* Try to read an error code from the child */
2372
        n = read(errno_pipe[0], &r, sizeof(r));
35✔
2373
        if (n < 0)
35✔
2374
                return -errno;
×
2375
        if (n == sizeof(r)) { /* an error code was sent to us */
35✔
2376
                if (r < 0)
×
2377
                        return r;
2378
                return -EIO;
×
2379
        }
2380
        if (n != 0) /* on success we should have read 0 bytes */
35✔
2381
                return -EIO;
2382

2383
        r = wait_for_terminate_and_check("(sd-userns)", TAKE_PID(pid), 0);
35✔
2384
        if (r < 0)
35✔
2385
                return r;
2386
        if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
35✔
2387
                return -EIO;
×
2388

2389
        return 1;
2390
}
2391

2392
static int can_mount_proc(const ExecContext *c, ExecParameters *p) {
5✔
2393
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
3✔
2394
        _cleanup_(sigkill_waitp) pid_t pid = 0;
×
2395
        ssize_t n;
5✔
2396
        int r;
5✔
2397

2398
        assert(c);
5✔
2399
        assert(p);
5✔
2400

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

2405
        /* Create a communication channel so that the child can tell the parent a proper error code in case it
2406
         * failed. */
2407
        if (pipe2(errno_pipe, O_CLOEXEC) < 0)
5✔
2408
                return log_exec_debug_errno(c, p, errno, "Failed to create pipe for communicating with child process (sd-proc-check): %m");
×
2409

2410
        /* Fork a child process into its own mount and PID namespace. Note safe_fork() already remounts / as SLAVE
2411
         * with FORK_MOUNTNS_SLAVE. */
2412
        r = safe_fork("(sd-proc-check)",
5✔
2413
                      FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE|FORK_NEW_PIDNS, &pid);
2414
        if (r < 0)
5✔
2415
                return log_exec_debug_errno(c, p, r, "Failed to fork child process (sd-proc-check): %m");
×
2416
        if (r == 0) {
5✔
2417
                errno_pipe[0] = safe_close(errno_pipe[0]);
2✔
2418

2419
                /* Try mounting /proc on /dev/shm/. No need to clean up the mount since the mount
2420
                 * namespace will be cleaned up once the process exits. */
2421
                r = mount_follow_verbose(LOG_DEBUG, "proc", "/dev/shm/", "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
2✔
2422
                if (r < 0) {
2✔
2423
                        (void) write(errno_pipe[1], &r, sizeof(r));
×
2424
                        _exit(EXIT_FAILURE);
×
2425
                }
2426

2427
                _exit(EXIT_SUCCESS);
2✔
2428
        }
2429

2430
        errno_pipe[1] = safe_close(errno_pipe[1]);
3✔
2431

2432
        /* Try to read an error code from the child */
2433
        n = read(errno_pipe[0], &r, sizeof(r));
3✔
2434
        if (n < 0)
3✔
2435
                return log_exec_debug_errno(c, p, errno, "Failed to read errno from pipe with child process (sd-proc-check): %m");
×
2436
        if (n == sizeof(r)) { /* an error code was sent to us */
3✔
2437
                /* This is the expected case where proc cannot be mounted due to permissions. */
2438
                if (ERRNO_IS_NEG_PRIVILEGE(r))
3✔
2439
                        return 0;
2440
                if (r < 0)
×
2441
                        return r;
2442

2443
                return -EIO;
×
2444
        }
2445
        if (n != 0) /* on success we should have read 0 bytes */
2✔
2446
                return -EIO;
2447

2448
        r = wait_for_terminate_and_check("(sd-proc-check)", TAKE_PID(pid), 0 /* flags= */);
2✔
2449
        if (r < 0)
2✔
2450
                return log_exec_debug_errno(c, p, r, "Failed to wait for (sd-proc-check) child process to terminate: %m");
×
2451
        if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
2✔
2452
                return log_exec_debug_errno(c, p, SYNTHETIC_ERRNO(EIO), "Child process (sd-proc-check) exited with unexpected exit status '%d'.", r);
×
2453

2454
        return 1;
2455
}
2456

2457
static int setup_private_pids(const ExecContext *c, ExecParameters *p) {
7✔
2458
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
×
2459
        _cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
6✔
2460
        ssize_t n;
7✔
2461
        int r, q;
7✔
2462

2463
        assert(c);
7✔
2464
        assert(p);
7✔
2465
        assert(p->pidref_transport_fd >= 0);
7✔
2466

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

2472
        /* Create a communication channel so that the parent can tell the child a proper error code in case it
2473
         * failed to send child pidref to the manager. */
2474
        if (pipe2(errno_pipe, O_CLOEXEC) < 0)
7✔
2475
                return log_exec_debug_errno(c, p, errno, "Failed to create pipe for communicating with parent process: %m");
×
2476

2477
        /* Set FORK_DETACH to immediately re-parent the child process to the invoking manager process. */
2478
        r = pidref_safe_fork("(sd-pidns-child)", FORK_NEW_PIDNS|FORK_DETACH, &pidref);
7✔
2479
        if (r < 0)
13✔
2480
                return log_exec_debug_errno(c, p, r, "Failed to fork child into new pid namespace: %m");
×
2481
        if (r > 0) {
13✔
2482
                errno_pipe[0] = safe_close(errno_pipe[0]);
7✔
2483

2484
                /* In the parent process, we send the child pidref to the manager and exit.
2485
                 * If PIDFD is not supported, only the child PID is sent. The server then
2486
                 * uses the child PID to set the new exec main process. */
2487
                q = send_one_fd_iov(
7✔
2488
                                p->pidref_transport_fd,
2489
                                pidref.fd,
2490
                                &IOVEC_MAKE(&pidref.pid, sizeof(pidref.pid)),
2491
                                /*iovlen=*/ 1,
2492
                                /*flags=*/ 0);
2493
                /* Send error code to child process. */
2494
                (void) write(errno_pipe[1], &q, sizeof(q));
7✔
2495
                /* Exit here so we only go through the destructors in exec_invoke only once - in the child - as
2496
                 * some destructors have external effects. The main codepaths continue in the child process. */
2497
                _exit(q < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
7✔
2498
        }
2499

2500
        errno_pipe[1] = safe_close(errno_pipe[1]);
6✔
2501
        p->pidref_transport_fd = safe_close(p->pidref_transport_fd);
6✔
2502

2503
        /* Try to read an error code from the parent. Note a child process cannot wait for the parent so we always
2504
         * receive an errno even on success. */
2505
        n = read(errno_pipe[0], &r, sizeof(r));
6✔
2506
        if (n < 0)
6✔
2507
                return log_exec_debug_errno(c, p, errno, "Failed to read errno from pipe with parent process: %m");
×
2508
        if (n != sizeof(r))
6✔
2509
                return log_exec_debug_errno(c, p, SYNTHETIC_ERRNO(EIO), "Failed to read enough bytes from pipe with parent process");
×
2510
        if (r < 0)
6✔
2511
                return log_exec_debug_errno(c, p, r, "Failed to send child pidref to manager: %m");
×
2512

2513
        /* NOTE! This function returns in the child process only. */
2514
        return r;
2515
}
2516

2517
static int create_many_symlinks(const char *root, const char *source, char **symlinks) {
1,630✔
2518
        _cleanup_free_ char *src_abs = NULL;
1,630✔
2519
        int r;
1,630✔
2520

2521
        assert(source);
1,630✔
2522

2523
        src_abs = path_join(root, source);
1,630✔
2524
        if (!src_abs)
1,630✔
2525
                return -ENOMEM;
2526

2527
        STRV_FOREACH(dst, symlinks) {
1,643✔
2528
                _cleanup_free_ char *dst_abs = NULL;
13✔
2529

2530
                dst_abs = path_join(root, *dst);
13✔
2531
                if (!dst_abs)
13✔
2532
                        return -ENOMEM;
2533

2534
                r = mkdir_parents_label(dst_abs, 0755);
13✔
2535
                if (r < 0)
13✔
2536
                        return r;
2537

2538
                r = symlink_idempotent(src_abs, dst_abs, true);
13✔
2539
                if (r < 0)
13✔
2540
                        return r;
2541
        }
2542

2543
        return 0;
2544
}
2545

2546
static int setup_exec_directory(
67,391✔
2547
                const ExecContext *context,
2548
                const ExecParameters *params,
2549
                uid_t uid,
2550
                gid_t gid,
2551
                ExecDirectoryType type,
2552
                bool needs_mount_namespace,
2553
                int *exit_status) {
2554

2555
        static const int exit_status_table[_EXEC_DIRECTORY_TYPE_MAX] = {
67,391✔
2556
                [EXEC_DIRECTORY_RUNTIME]       = EXIT_RUNTIME_DIRECTORY,
2557
                [EXEC_DIRECTORY_STATE]         = EXIT_STATE_DIRECTORY,
2558
                [EXEC_DIRECTORY_CACHE]         = EXIT_CACHE_DIRECTORY,
2559
                [EXEC_DIRECTORY_LOGS]          = EXIT_LOGS_DIRECTORY,
2560
                [EXEC_DIRECTORY_CONFIGURATION] = EXIT_CONFIGURATION_DIRECTORY,
2561
        };
2562
        int r;
67,391✔
2563

2564
        assert(context);
67,391✔
2565
        assert(params);
67,391✔
2566
        assert(type >= 0 && type < _EXEC_DIRECTORY_TYPE_MAX);
67,391✔
2567
        assert(exit_status);
67,391✔
2568

2569
        if (!params->prefix[type])
67,391✔
2570
                return 0;
2571

2572
        if (params->flags & EXEC_CHOWN_DIRECTORIES) {
67,391✔
2573
                if (!uid_is_valid(uid))
64,211✔
2574
                        uid = 0;
50,821✔
2575
                if (!gid_is_valid(gid))
64,211✔
2576
                        gid = 0;
50,801✔
2577
        }
2578

2579
        FOREACH_ARRAY(i, context->directories[type].items, context->directories[type].n_items) {
71,393✔
2580
                _cleanup_free_ char *p = NULL, *pp = NULL;
4,003✔
2581

2582
                p = path_join(params->prefix[type], i->path);
4,003✔
2583
                if (!p) {
4,003✔
2584
                        r = -ENOMEM;
×
2585
                        goto fail;
×
2586
                }
2587

2588
                r = mkdir_parents_label(p, 0755);
4,003✔
2589
                if (r < 0)
4,003✔
2590
                        goto fail;
×
2591

2592
                if (IN_SET(type, EXEC_DIRECTORY_STATE, EXEC_DIRECTORY_LOGS) && params->runtime_scope == RUNTIME_SCOPE_USER) {
4,003✔
2593

2594
                        /* If we are in user mode, and a configuration directory exists but a state directory
2595
                         * doesn't exist, then we likely are upgrading from an older systemd version that
2596
                         * didn't know the more recent addition to the xdg-basedir spec: the $XDG_STATE_HOME
2597
                         * directory. In older systemd versions EXEC_DIRECTORY_STATE was aliased to
2598
                         * EXEC_DIRECTORY_CONFIGURATION, with the advent of $XDG_STATE_HOME it is now
2599
                         * separated. If a service has both dirs configured but only the configuration dir
2600
                         * exists and the state dir does not, we assume we are looking at an update
2601
                         * situation. Hence, create a compatibility symlink, so that all expectations are
2602
                         * met.
2603
                         *
2604
                         * (We also do something similar with the log directory, which still doesn't exist in
2605
                         * the xdg basedir spec. We'll make it a subdir of the state dir.) */
2606

2607
                        /* this assumes the state dir is always created before the configuration dir */
2608
                        assert_cc(EXEC_DIRECTORY_STATE < EXEC_DIRECTORY_LOGS);
7✔
2609
                        assert_cc(EXEC_DIRECTORY_LOGS < EXEC_DIRECTORY_CONFIGURATION);
7✔
2610

2611
                        r = access_nofollow(p, F_OK);
7✔
2612
                        if (r == -ENOENT) {
3✔
2613
                                _cleanup_free_ char *q = NULL;
3✔
2614

2615
                                /* OK, we know that the state dir does not exist. Let's see if the dir exists
2616
                                 * under the configuration hierarchy. */
2617

2618
                                if (type == EXEC_DIRECTORY_STATE)
3✔
2619
                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], i->path);
3✔
2620
                                else if (type == EXEC_DIRECTORY_LOGS)
×
2621
                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], "log", i->path);
×
2622
                                else
2623
                                        assert_not_reached();
×
2624
                                if (!q) {
3✔
2625
                                        r = -ENOMEM;
×
2626
                                        goto fail;
×
2627
                                }
2628

2629
                                r = access_nofollow(q, F_OK);
3✔
2630
                                if (r >= 0) {
2✔
2631
                                        /* It does exist! This hence looks like an update. Symlink the
2632
                                         * configuration directory into the state directory. */
2633

2634
                                        r = symlink_idempotent(q, p, /* make_relative= */ true);
1✔
2635
                                        if (r < 0)
1✔
2636
                                                goto fail;
×
2637

2638
                                        log_exec_notice(context, params, "Unit state directory %s missing but matching configuration directory %s exists, assuming update from systemd 253 or older, creating compatibility symlink.", p, q);
1✔
2639
                                        continue;
1✔
2640
                                } else if (r != -ENOENT)
2✔
2641
                                        log_exec_warning_errno(context, params, r, "Unable to detect whether unit configuration directory '%s' exists, assuming not: %m", q);
×
2642

2643
                        } else if (r < 0)
4✔
2644
                                log_exec_warning_errno(context, params, r, "Unable to detect whether unit state directory '%s' is missing, assuming it is: %m", p);
×
2645
                }
2646

2647
                if (exec_directory_is_private(context, type)) {
4,002✔
2648
                        /* So, here's one extra complication when dealing with DynamicUser=1 units. In that
2649
                         * case we want to avoid leaving a directory around fully accessible that is owned by
2650
                         * a dynamic user whose UID is later on reused. To lock this down we use the same
2651
                         * trick used by container managers to prohibit host users to get access to files of
2652
                         * the same UID in containers: we place everything inside a directory that has an
2653
                         * access mode of 0700 and is owned root:root, so that it acts as security boundary
2654
                         * for unprivileged host code. We then use fs namespacing to make this directory
2655
                         * permeable for the service itself.
2656
                         *
2657
                         * Specifically: for a service which wants a special directory "foo/" we first create
2658
                         * a directory "private/" with access mode 0700 owned by root:root. Then we place
2659
                         * "foo" inside of that directory (i.e. "private/foo/"), and make "foo" a symlink to
2660
                         * "private/foo". This way, privileged host users can access "foo/" as usual, but
2661
                         * unprivileged host users can't look into it. Inside of the namespace of the unit
2662
                         * "private/" is replaced by a more liberally accessible tmpfs, into which the host's
2663
                         * "private/foo/" is mounted under the same name, thus disabling the access boundary
2664
                         * for the service and making sure it only gets access to the dirs it needs but no
2665
                         * others. Tricky? Yes, absolutely, but it works!
2666
                         *
2667
                         * Note that we don't do this for EXEC_DIRECTORY_CONFIGURATION as that's assumed not
2668
                         * to be owned by the service itself.
2669
                         *
2670
                         * Also, note that we don't do this for EXEC_DIRECTORY_RUNTIME as that's often used
2671
                         * for sharing files or sockets with other services. */
2672

2673
                        pp = path_join(params->prefix[type], "private");
12✔
2674
                        if (!pp) {
12✔
2675
                                r = -ENOMEM;
×
2676
                                goto fail;
×
2677
                        }
2678

2679
                        /* First set up private root if it doesn't exist yet, with access mode 0700 and owned by root:root */
2680
                        r = mkdir_safe_label(pp, 0700, 0, 0, MKDIR_WARN_MODE);
12✔
2681
                        if (r < 0)
12✔
2682
                                goto fail;
×
2683

2684
                        if (!path_extend(&pp, i->path)) {
12✔
2685
                                r = -ENOMEM;
×
2686
                                goto fail;
×
2687
                        }
2688

2689
                        /* Create all directories between the configured directory and this private root, and mark them 0755 */
2690
                        r = mkdir_parents_label(pp, 0755);
12✔
2691
                        if (r < 0)
12✔
2692
                                goto fail;
×
2693

2694
                        if (is_dir(p, false) > 0 &&
12✔
2695
                            (access_nofollow(pp, F_OK) == -ENOENT)) {
×
2696

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

2701
                                log_exec_info(context,
×
2702
                                              params,
2703
                                              "Found pre-existing public %s= directory %s, migrating to %s.\n"
2704
                                              "Apparently, service previously had DynamicUser= turned off, and has now turned it on.",
2705
                                              exec_directory_type_to_string(type), p, pp);
2706

2707
                                r = RET_NERRNO(rename(p, pp));
×
2708
                                if (r < 0)
×
2709
                                        goto fail;
×
2710
                        } else {
2711
                                /* Otherwise, create the actual directory for the service */
2712

2713
                                r = mkdir_label(pp, context->directories[type].mode);
12✔
2714
                                if (r < 0 && r != -EEXIST)
12✔
2715
                                        goto fail;
×
2716
                        }
2717

2718
                        if (!FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE)) {
12✔
2719
                                /* And link it up from the original place.
2720
                                 * Notes
2721
                                 * 1) If a mount namespace is going to be used, then this symlink remains on
2722
                                 *    the host, and a new one for the child namespace will be created later.
2723
                                 * 2) It is not necessary to create this symlink when one of its parent
2724
                                 *    directories is specified and already created. E.g.
2725
                                 *        StateDirectory=foo foo/bar
2726
                                 *    In that case, the inode points to pp and p for "foo/bar" are the same:
2727
                                 *        pp = "/var/lib/private/foo/bar"
2728
                                 *        p = "/var/lib/foo/bar"
2729
                                 *    and, /var/lib/foo is a symlink to /var/lib/private/foo. So, not only
2730
                                 *    we do not need to create the symlink, but we cannot create the symlink.
2731
                                 *    See issue #24783. */
2732
                                r = symlink_idempotent(pp, p, true);
12✔
2733
                                if (r < 0)
12✔
2734
                                        goto fail;
×
2735
                        }
2736

2737
                } else {
2738
                        _cleanup_free_ char *target = NULL;
3,990✔
2739

2740
                        if (EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type) &&
7,940✔
2741
                            readlink_and_make_absolute(p, &target) >= 0) {
3,950✔
2742
                                _cleanup_free_ char *q = NULL, *q_resolved = NULL, *target_resolved = NULL;
11✔
2743

2744
                                /* This already exists and is a symlink? Interesting. Maybe it's one created
2745
                                 * by DynamicUser=1 (see above)?
2746
                                 *
2747
                                 * We do this for all directory types except for ConfigurationDirectory=,
2748
                                 * since they all support the private/ symlink logic at least in some
2749
                                 * configurations, see above. */
2750

2751
                                r = chase(target, NULL, 0, &target_resolved, NULL);
11✔
2752
                                if (r < 0)
11✔
2753
                                        goto fail;
×
2754

2755
                                q = path_join(params->prefix[type], "private", i->path);
11✔
2756
                                if (!q) {
11✔
2757
                                        r = -ENOMEM;
×
2758
                                        goto fail;
×
2759
                                }
2760

2761
                                /* /var/lib or friends may be symlinks. So, let's chase them also. */
2762
                                r = chase(q, NULL, CHASE_NONEXISTENT, &q_resolved, NULL);
11✔
2763
                                if (r < 0)
11✔
2764
                                        goto fail;
×
2765

2766
                                if (path_equal(q_resolved, target_resolved)) {
11✔
2767

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

2771
                                        log_exec_info(context,
24✔
2772
                                                      params,
2773
                                                      "Found pre-existing private %s= directory %s, migrating to %s.\n"
2774
                                                      "Apparently, service previously had DynamicUser= turned on, and has now turned it off.",
2775
                                                      exec_directory_type_to_string(type), q, p);
2776

2777
                                        r = RET_NERRNO(unlink(p));
8✔
2778
                                        if (r < 0)
×
2779
                                                goto fail;
×
2780

2781
                                        r = RET_NERRNO(rename(q, p));
11✔
2782
                                        if (r < 0)
×
2783
                                                goto fail;
×
2784
                                }
2785
                        }
2786

2787
                        r = mkdir_label(p, context->directories[type].mode);
3,990✔
2788
                        if (r < 0) {
3,990✔
2789
                                if (r != -EEXIST)
2,660✔
2790
                                        goto fail;
×
2791

2792
                                if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(type)) {
2,660✔
2793
                                        struct stat st;
27✔
2794

2795
                                        /* Don't change the owner/access mode of the configuration directory,
2796
                                         * as in the common case it is not written to by a service, and shall
2797
                                         * not be writable. */
2798

2799
                                        r = RET_NERRNO(stat(p, &st));
27✔
2800
                                        if (r < 0)
×
2801
                                                goto fail;
×
2802

2803
                                        /* Still complain if the access mode doesn't match */
2804
                                        if (((st.st_mode ^ context->directories[type].mode) & 07777) != 0)
27✔
2805
                                                log_exec_warning(context,
×
2806
                                                                 params,
2807
                                                                 "%s \'%s\' already exists but the mode is different. "
2808
                                                                 "(File system: %o %sMode: %o)",
2809
                                                                 exec_directory_type_to_string(type), i->path,
2810
                                                                 st.st_mode & 07777, exec_directory_type_to_string(type), context->directories[type].mode & 07777);
2811

2812
                                        continue;
27✔
2813
                                }
2814
                        }
2815
                }
2816

2817
                /* Lock down the access mode (we use chmod_and_chown() to make this idempotent. We don't
2818
                 * specify UID/GID here, so that path_chown_recursive() can optimize things depending on the
2819
                 * current UID/GID ownership.) */
2820
                const char *target_dir = pp ?: p;
3,975✔
2821
                r = chmod_and_chown(target_dir, context->directories[type].mode, UID_INVALID, GID_INVALID);
3,975✔
2822
                if (r < 0)
3,975✔
2823
                        goto fail;
×
2824

2825
                /* Skip the rest (which deals with ownership) in user mode, since ownership changes are not
2826
                 * available to user code anyway */
2827
                if (params->runtime_scope != RUNTIME_SCOPE_SYSTEM)
3,975✔
2828
                        continue;
9✔
2829

2830
                int idmapping_supported = is_idmapping_supported(target_dir);
3,966✔
2831
                if (idmapping_supported < 0) {
3,966✔
2832
                        r = log_debug_errno(idmapping_supported, "Unable to determine if ID mapping is supported on mount '%s': %m", target_dir);
×
2833
                        goto fail;
×
2834
                }
2835

2836
                log_debug("ID-mapping is%ssupported for exec directory %s", idmapping_supported ? " " : " not ", target_dir);
4,025✔
2837

2838
                /* Change the ownership of the whole tree, if necessary. When dynamic users are used we
2839
                 * drop the suid/sgid bits, since we really don't want SUID/SGID files for dynamic UID/GID
2840
                 * assignments to exist. */
2841
                uid_t chown_uid = uid;
3,966✔
2842
                gid_t chown_gid = gid;
3,966✔
2843
                bool do_chown = false;
3,966✔
2844

2845
                if (uid == 0 || gid == 0 || !idmapping_supported) {
3,966✔
2846
                        do_chown = true;
1,592✔
2847
                        i->idmapped = false;
1,592✔
2848
                } else {
2849
                        /* Use 'nobody' uid/gid for exec directories if ID-mapping is supported. For backward compatibility,
2850
                         * continue doing chmod/chown if the directory was chmod/chowned before (if uid/gid is not 'nobody') */
2851
                        struct stat st;
2,374✔
2852
                        r = RET_NERRNO(stat(target_dir, &st));
2,374✔
2853
                        if (r < 0)
×
2854
                                goto fail;
×
2855

2856
                        if (st.st_uid == UID_NOBODY && st.st_gid == GID_NOBODY) {
2,374✔
2857
                                do_chown = false;
6✔
2858
                                i->idmapped = true;
6✔
2859
                       } else if (exec_directory_is_private(context, type) && st.st_uid == 0 && st.st_gid == 0) {
2,368✔
2860
                                chown_uid = UID_NOBODY;
6✔
2861
                                chown_gid = GID_NOBODY;
6✔
2862
                                do_chown = true;
6✔
2863
                                i->idmapped = true;
6✔
2864
                        } else {
2865
                                do_chown = true;
2,362✔
2866
                                i->idmapped = false;
2,362✔
2867
                        }
2868
                }
2869

2870
                if (do_chown) {
3,966✔
2871
                        r = path_chown_recursive(target_dir, chown_uid, chown_gid, context->dynamic_user ? 01777 : 07777, AT_SYMLINK_FOLLOW);
7,911✔
2872
                        if (r < 0)
3,960✔
2873
                                goto fail;
1✔
2874
                }
2875
        }
2876

2877
        /* If we are not going to run in a namespace, set up the symlinks - otherwise
2878
         * they are set up later, to allow configuring empty var/run/etc. */
2879
        if (!needs_mount_namespace)
67,390✔
2880
                FOREACH_ARRAY(i, context->directories[type].items, context->directories[type].n_items) {
52,960✔
2881
                        r = create_many_symlinks(params->prefix[type], i->path, i->symlinks);
1,630✔
2882
                        if (r < 0)
1,630✔
2883
                                goto fail;
×
2884
                }
2885

2886
        return 0;
2887

2888
fail:
1✔
2889
        *exit_status = exit_status_table[type];
1✔
2890
        return r;
1✔
2891
}
2892

2893
#if ENABLE_SMACK
2894
static int setup_smack(
×
2895
                const ExecParameters *params,
2896
                const ExecContext *context,
2897
                int executable_fd) {
2898
        int r;
×
2899

2900
        assert(params);
×
2901
        assert(executable_fd >= 0);
×
2902

2903
        if (context->smack_process_label) {
×
2904
                r = mac_smack_apply_pid(0, context->smack_process_label);
×
2905
                if (r < 0)
×
2906
                        return r;
×
2907
        } else if (params->fallback_smack_process_label) {
×
2908
                _cleanup_free_ char *exec_label = NULL;
×
2909

2910
                r = mac_smack_read_fd(executable_fd, SMACK_ATTR_EXEC, &exec_label);
×
2911
                if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
×
2912
                        return r;
2913

2914
                r = mac_smack_apply_pid(0, exec_label ?: params->fallback_smack_process_label);
×
2915
                if (r < 0)
×
2916
                        return r;
2917
        }
2918

2919
        return 0;
2920
}
2921
#endif
2922

2923
static int compile_bind_mounts(
2,551✔
2924
                const ExecContext *context,
2925
                const ExecParameters *params,
2926
                uid_t exec_directory_uid, /* only used for id-mapped mounts Exec directories */
2927
                gid_t exec_directory_gid, /* only used for id-mapped mounts Exec directories */
2928
                BindMount **ret_bind_mounts,
2929
                size_t *ret_n_bind_mounts,
2930
                char ***ret_empty_directories) {
2931

2932
        _cleanup_strv_free_ char **empty_directories = NULL;
2,551✔
2933
        BindMount *bind_mounts = NULL;
2,551✔
2934
        size_t n, h = 0;
2,551✔
2935
        int r;
2,551✔
2936

2937
        assert(context);
2,551✔
2938
        assert(params);
2,551✔
2939
        assert(ret_bind_mounts);
2,551✔
2940
        assert(ret_n_bind_mounts);
2,551✔
2941
        assert(ret_empty_directories);
2,551✔
2942

2943
        CLEANUP_ARRAY(bind_mounts, h, bind_mount_free_many);
2,551✔
2944

2945
        n = context->n_bind_mounts;
2,551✔
2946
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
15,306✔
2947
                if (!params->prefix[t])
12,755✔
2948
                        continue;
×
2949

2950
                FOREACH_ARRAY(i, context->directories[t].items, context->directories[t].n_items)
14,495✔
2951
                        n += !FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE) || FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY);
1,740✔
2952
        }
2953

2954
        if (n <= 0) {
2,551✔
2955
                *ret_bind_mounts = NULL;
1,531✔
2956
                *ret_n_bind_mounts = 0;
1,531✔
2957
                *ret_empty_directories = NULL;
1,531✔
2958
                return 0;
1,531✔
2959
        }
2960

2961
        bind_mounts = new(BindMount, n);
1,020✔
2962
        if (!bind_mounts)
1,020✔
2963
                return -ENOMEM;
2964

2965
        FOREACH_ARRAY(item, context->bind_mounts, context->n_bind_mounts) {
1,040✔
2966
                r = bind_mount_add(&bind_mounts, &h, item);
20✔
2967
                if (r < 0)
20✔
2968
                        return r;
2969
        }
2970

2971
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
6,120✔
2972
                if (!params->prefix[t])
5,100✔
2973
                        continue;
×
2974

2975
                if (context->directories[t].n_items == 0)
5,100✔
2976
                        continue;
3,816✔
2977

2978
                if (exec_directory_is_private(context, t) &&
1,296✔
2979
                    !exec_context_with_rootfs(context)) {
12✔
2980
                        char *private_root;
12✔
2981

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

2986
                        private_root = path_join(params->prefix[t], "private");
12✔
2987
                        if (!private_root)
12✔
2988
                                return -ENOMEM;
2989

2990
                        r = strv_consume(&empty_directories, private_root);
12✔
2991
                        if (r < 0)
12✔
2992
                                return r;
2993
                }
2994

2995
                FOREACH_ARRAY(i, context->directories[t].items, context->directories[t].n_items) {
3,024✔
2996
                        _cleanup_free_ char *s = NULL, *d = NULL;
1,740✔
2997

2998
                        /* When one of the parent directories is in the list, we cannot create the symlink
2999
                         * for the child directory. See also the comments in setup_exec_directory().
3000
                         * But if it needs to be read only, then we have to create a bind mount anyway to
3001
                         * make it so. */
3002
                        if (FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE) && !FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY))
1,740✔
3003
                                continue;
×
3004

3005
                        if (exec_directory_is_private(context, t))
1,740✔
3006
                                s = path_join(params->prefix[t], "private", i->path);
12✔
3007
                        else
3008
                                s = path_join(params->prefix[t], i->path);
1,728✔
3009
                        if (!s)
1,740✔
3010
                                return -ENOMEM;
3011

3012
                        if (exec_directory_is_private(context, t) &&
1,752✔
3013
                            exec_context_with_rootfs(context))
12✔
3014
                                /* When RootDirectory= or RootImage= are set, then the symbolic link to the private
3015
                                 * directory is not created on the root directory. So, let's bind-mount the directory
3016
                                 * on the 'non-private' place. */
3017
                                d = path_join(params->prefix[t], i->path);
×
3018
                        else
3019
                                d = strdup(s);
1,740✔
3020
                        if (!d)
1,740✔
3021
                                return -ENOMEM;
3022

3023
                        bind_mounts[h++] = (BindMount) {
1,740✔
3024
                                .source = TAKE_PTR(s),
1,740✔
3025
                                .destination = TAKE_PTR(d),
1,740✔
3026
                                .nosuid = context->dynamic_user, /* don't allow suid/sgid when DynamicUser= is on */
1,740✔
3027
                                .recursive = true,
3028
                                .read_only = FLAGS_SET(i->flags, EXEC_DIRECTORY_READ_ONLY),
1,740✔
3029
                                .idmapped = i->idmapped,
1,740✔
3030
                                .uid = exec_directory_uid,
3031
                                .gid = exec_directory_gid,
3032
                        };
3033
                }
3034
        }
3035

3036
        assert(h == n);
1,020✔
3037

3038
        *ret_bind_mounts = TAKE_PTR(bind_mounts);
1,020✔
3039
        *ret_n_bind_mounts = n;
1,020✔
3040
        *ret_empty_directories = TAKE_PTR(empty_directories);
1,020✔
3041

3042
        return (int) n;
1,020✔
3043
}
3044

3045
/* ret_symlinks will contain a list of pairs src:dest that describes
3046
 * the symlinks to create later on. For example, the symlinks needed
3047
 * to safely give private directories to DynamicUser=1 users. */
3048
static int compile_symlinks(
2,551✔
3049
                const ExecContext *context,
3050
                const ExecParameters *params,
3051
                bool setup_os_release_symlink,
3052
                char ***ret_symlinks) {
3053

3054
        _cleanup_strv_free_ char **symlinks = NULL;
2,551✔
3055
        int r;
2,551✔
3056

3057
        assert(context);
2,551✔
3058
        assert(params);
2,551✔
3059
        assert(ret_symlinks);
2,551✔
3060

3061
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++)
15,306✔
3062
                FOREACH_ARRAY(i, context->directories[dt].items, context->directories[dt].n_items) {
14,495✔
3063
                        _cleanup_free_ char *private_path = NULL, *path = NULL;
1,728✔
3064

3065
                        STRV_FOREACH(symlink, i->symlinks) {
1,866✔
3066
                                _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;
126✔
3067

3068
                                src_abs = path_join(params->prefix[dt], i->path);
126✔
3069
                                dst_abs = path_join(params->prefix[dt], *symlink);
126✔
3070
                                if (!src_abs || !dst_abs)
126✔
3071
                                        return -ENOMEM;
3072

3073
                                r = strv_consume_pair(&symlinks, TAKE_PTR(src_abs), TAKE_PTR(dst_abs));
126✔
3074
                                if (r < 0)
126✔
3075
                                        return r;
3076
                        }
3077

3078
                        if (!exec_directory_is_private(context, dt) ||
1,752✔
3079
                            exec_context_with_rootfs(context) ||
12✔
3080
                            FLAGS_SET(i->flags, EXEC_DIRECTORY_ONLY_CREATE))
12✔
3081
                                continue;
1,728✔
3082

3083
                        private_path = path_join(params->prefix[dt], "private", i->path);
12✔
3084
                        if (!private_path)
12✔
3085
                                return -ENOMEM;
3086

3087
                        path = path_join(params->prefix[dt], i->path);
12✔
3088
                        if (!path)
12✔
3089
                                return -ENOMEM;
3090

3091
                        r = strv_consume_pair(&symlinks, TAKE_PTR(private_path), TAKE_PTR(path));
12✔
3092
                        if (r < 0)
12✔
3093
                                return r;
3094
                }
3095

3096
        /* We make the host's os-release available via a symlink, so that we can copy it atomically
3097
         * and readers will never get a half-written version. Note that, while the paths specified here are
3098
         * absolute, when they are processed in namespace.c they will be made relative automatically, i.e.:
3099
         * 'os-release -> .os-release-stage/os-release' is what will be created. */
3100
        if (setup_os_release_symlink) {
2,551✔
3101
                r = strv_extend_many(
7✔
3102
                                &symlinks,
3103
                                "/run/host/.os-release-stage/os-release",
3104
                                "/run/host/os-release");
3105
                if (r < 0)
7✔
3106
                        return r;
3107
        }
3108

3109
        *ret_symlinks = TAKE_PTR(symlinks);
2,551✔
3110

3111
        return 0;
2,551✔
3112
}
3113

3114
static bool insist_on_sandboxing(
×
3115
                const ExecContext *context,
3116
                const char *root_dir,
3117
                const char *root_image,
3118
                const BindMount *bind_mounts,
3119
                size_t n_bind_mounts) {
3120

3121
        assert(context);
×
3122
        assert(n_bind_mounts == 0 || bind_mounts);
×
3123

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

3128
        if (context->n_temporary_filesystems > 0)
×
3129
                return true;
3130

3131
        if (root_dir || root_image)
×
3132
                return true;
3133

3134
        if (context->n_mount_images > 0)
×
3135
                return true;
3136

3137
        if (context->dynamic_user)
×
3138
                return true;
3139

3140
        if (context->n_extension_images > 0 || !strv_isempty(context->extension_directories))
×
3141
                return true;
3142

3143
        /* If there are any bind mounts set that don't map back onto themselves, fs namespacing becomes
3144
         * essential. */
3145
        FOREACH_ARRAY(i, bind_mounts, n_bind_mounts)
×
3146
                if (!path_equal(i->source, i->destination))
×
3147
                        return true;
3148

3149
        if (context->log_namespace)
×
3150
                return true;
×
3151

3152
        return false;
3153
}
3154

3155
static int setup_ephemeral(
2,551✔
3156
                const ExecContext *context,
3157
                ExecRuntime *runtime,
3158
                char **root_image,            /* both input and output! modified if ephemeral logic enabled */
3159
                char **root_directory,        /* ditto */
3160
                char **reterr_path) {
3161

3162
        _cleanup_close_ int fd = -EBADF;
2,551✔
3163
        _cleanup_free_ char *new_root = NULL;
2,551✔
3164
        int r;
2,551✔
3165

3166
        assert(context);
2,551✔
3167
        assert(root_image);
2,551✔
3168
        assert(root_directory);
2,551✔
3169

3170
        if (!*root_image && !*root_directory)
2,551✔
3171
                return 0;
3172

3173
        if (!runtime || !runtime->ephemeral_copy)
8✔
3174
                return 0;
3175

3176
        assert(runtime->ephemeral_storage_socket[0] >= 0);
×
3177
        assert(runtime->ephemeral_storage_socket[1] >= 0);
×
3178

3179
        new_root = strdup(runtime->ephemeral_copy);
×
3180
        if (!new_root)
×
3181
                return log_oom_debug();
×
3182

3183
        r = posix_lock(runtime->ephemeral_storage_socket[0], LOCK_EX);
×
3184
        if (r < 0)
×
3185
                return log_debug_errno(r, "Failed to lock ephemeral storage socket: %m");
×
3186

3187
        CLEANUP_POSIX_UNLOCK(runtime->ephemeral_storage_socket[0]);
×
3188

3189
        fd = receive_one_fd(runtime->ephemeral_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
×
3190
        if (fd >= 0)
×
3191
                /* We got an fd! That means ephemeral has already been set up, so nothing to do here. */
3192
                return 0;
3193
        if (fd != -EAGAIN)
×
3194
                return log_debug_errno(fd, "Failed to receive file descriptor queued on ephemeral storage socket: %m");
×
3195

3196
        if (*root_image) {
×
3197
                log_debug("Making ephemeral copy of %s to %s", *root_image, new_root);
×
3198

3199
                fd = copy_file(*root_image, new_root, O_EXCL, 0600,
×
3200
                               COPY_LOCK_BSD|COPY_REFLINK|COPY_CRTIME|COPY_NOCOW_AFTER);
3201
                if (fd < 0) {
×
3202
                        *reterr_path = strdup(*root_image);
×
3203
                        return log_debug_errno(fd, "Failed to copy image %s to %s: %m",
×
3204
                                               *root_image, new_root);
3205
                }
3206
        } else {
3207
                assert(*root_directory);
×
3208

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

3211
                fd = btrfs_subvol_snapshot_at(
×
3212
                                AT_FDCWD, *root_directory,
3213
                                AT_FDCWD, new_root,
3214
                                BTRFS_SNAPSHOT_FALLBACK_COPY |
3215
                                BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
3216
                                BTRFS_SNAPSHOT_RECURSIVE |
3217
                                BTRFS_SNAPSHOT_LOCK_BSD);
3218
                if (fd < 0) {
×
3219
                        *reterr_path = strdup(*root_directory);
×
3220
                        return log_debug_errno(fd, "Failed to snapshot directory %s to %s: %m",
×
3221
                                               *root_directory, new_root);
3222
                }
3223
        }
3224

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

3229
        if (*root_image)
×
3230
                free_and_replace(*root_image, new_root);
×
3231
        else {
3232
                assert(*root_directory);
×
3233
                free_and_replace(*root_directory, new_root);
×
3234
        }
3235

3236
        return 1;
3237
}
3238

3239
static int verity_settings_prepare(
7✔
3240
                VeritySettings *verity,
3241
                const char *root_image,
3242
                const void *root_hash,
3243
                size_t root_hash_size,
3244
                const char *root_hash_path,
3245
                const void *root_hash_sig,
3246
                size_t root_hash_sig_size,
3247
                const char *root_hash_sig_path,
3248
                const char *verity_data_path) {
3249

3250
        int r;
7✔
3251

3252
        assert(verity);
7✔
3253

3254
        if (root_hash) {
7✔
3255
                void *d;
4✔
3256

3257
                d = memdup(root_hash, root_hash_size);
4✔
3258
                if (!d)
4✔
3259
                        return -ENOMEM;
7✔
3260

3261
                free_and_replace(verity->root_hash, d);
4✔
3262
                verity->root_hash_size = root_hash_size;
4✔
3263
                verity->designator = PARTITION_ROOT;
4✔
3264
        }
3265

3266
        if (root_hash_sig) {
7✔
3267
                void *d;
×
3268

3269
                d = memdup(root_hash_sig, root_hash_sig_size);
×
3270
                if (!d)
×
3271
                        return -ENOMEM;
7✔
3272

3273
                free_and_replace(verity->root_hash_sig, d);
×
3274
                verity->root_hash_sig_size = root_hash_sig_size;
×
3275
                verity->designator = PARTITION_ROOT;
×
3276
        }
3277

3278
        if (verity_data_path) {
7✔
3279
                r = free_and_strdup(&verity->data_path, verity_data_path);
×
3280
                if (r < 0)
×
3281
                        return r;
3282
        }
3283

3284
        r = verity_settings_load(
7✔
3285
                        verity,
3286
                        root_image,
3287
                        root_hash_path,
3288
                        root_hash_sig_path);
3289
        if (r < 0)
7✔
3290
                return log_debug_errno(r, "Failed to load root hash: %m");
×
3291

3292
        return 0;
3293
}
3294

3295
static int pick_versions(
2,553✔
3296
                const ExecContext *context,
3297
                const ExecParameters *params,
3298
                char **ret_root_image,
3299
                char **ret_root_directory,
3300
                char **reterr_path) {
3301

3302
        int r;
2,553✔
3303

3304
        assert(context);
2,553✔
3305
        assert(params);
2,553✔
3306
        assert(ret_root_image);
2,553✔
3307
        assert(ret_root_directory);
2,553✔
3308

3309
        if (context->root_image) {
2,553✔
3310
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
8✔
3311

3312
                r = path_pick(/* toplevel_path= */ NULL,
16✔
3313
                              /* toplevel_fd= */ AT_FDCWD,
3314
                              context->root_image,
8✔
3315
                              &pick_filter_image_raw,
3316
                              PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3317
                              &result);
3318
                if (r < 0) {
8✔
3319
                        *reterr_path = strdup(context->root_image);
1✔
3320
                        return r;
1✔
3321
                }
3322

3323
                if (!result.path) {
7✔
3324
                        *reterr_path = strdup(context->root_image);
×
3325
                        return log_exec_debug_errno(context, params, SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_image);
×
3326
                }
3327

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

3333
        if (context->root_directory) {
2,545✔
3334
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
2✔
3335

3336
                r = path_pick(/* toplevel_path= */ NULL,
4✔
3337
                              /* toplevel_fd= */ AT_FDCWD,
3338
                              context->root_directory,
2✔
3339
                              &pick_filter_image_dir,
3340
                              PICK_ARCHITECTURE|PICK_TRIES|PICK_RESOLVE,
3341
                              &result);
3342
                if (r < 0) {
2✔
3343
                        *reterr_path = strdup(context->root_directory);
×
3344
                        return r;
×
3345
                }
3346

3347
                if (!result.path) {
2✔
3348
                        *reterr_path = strdup(context->root_directory);
1✔
3349
                        return log_exec_debug_errno(context, params, SYNTHETIC_ERRNO(ENOENT), "No matching entry in .v/ directory %s found.", context->root_directory);
3✔
3350
                }
3351

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

3357
        *ret_root_image = *ret_root_directory = NULL;
2,543✔
3358
        return 0;
2,543✔
3359
}
3360

3361
static int apply_mount_namespace(
2,553✔
3362
                ExecCommandFlags command_flags,
3363
                const ExecContext *context,
3364
                const ExecParameters *params,
3365
                ExecRuntime *runtime,
3366
                const char *memory_pressure_path,
3367
                bool needs_sandboxing,
3368
                char **reterr_path,
3369
                uid_t exec_directory_uid,
3370
                gid_t exec_directory_gid) {
3371

3372
        _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
2,553✔
3373
        _cleanup_strv_free_ char **empty_directories = NULL, **symlinks = NULL,
2,553✔
3374
                        **read_write_paths_cleanup = NULL;
×
3375
        _cleanup_free_ char *creds_path = NULL, *incoming_dir = NULL, *propagate_dir = NULL,
×
3376
                *private_namespace_dir = NULL, *host_os_release_stage = NULL, *root_image = NULL, *root_dir = NULL;
2,553✔
3377
        const char *tmp_dir = NULL, *var_tmp_dir = NULL;
2,553✔
3378
        char **read_write_paths;
2,553✔
3379
        bool setup_os_release_symlink;
2,553✔
3380
        BindMount *bind_mounts = NULL;
2,553✔
3381
        size_t n_bind_mounts = 0;
2,553✔
3382
        int r;
2,553✔
3383

3384
        assert(context);
2,553✔
3385

3386
        CLEANUP_ARRAY(bind_mounts, n_bind_mounts, bind_mount_free_many);
2,553✔
3387

3388
        if (params->flags & EXEC_APPLY_CHROOT) {
2,553✔
3389
                r = pick_versions(
2,553✔
3390
                                context,
3391
                                params,
3392
                                &root_image,
3393
                                &root_dir,
3394
                                reterr_path);
3395
                if (r < 0)
2,553✔
3396
                        return r;
3397

3398
                r = setup_ephemeral(
2,551✔
3399
                                context,
3400
                                runtime,
3401
                                &root_image,
3402
                                &root_dir,
3403
                                reterr_path);
3404
                if (r < 0)
2,551✔
3405
                        return r;
3406
        }
3407

3408
        r = compile_bind_mounts(context, params, exec_directory_uid, exec_directory_gid, &bind_mounts, &n_bind_mounts, &empty_directories);
2,551✔
3409
        if (r < 0)
2,551✔
3410
                return r;
3411

3412
        /* We need to make the pressure path writable even if /sys/fs/cgroups is made read-only, as the
3413
         * service will need to write to it in order to start the notifications. */
3414
        if (exec_is_cgroup_mount_read_only(context, params) && memory_pressure_path && !streq(memory_pressure_path, "/dev/null")) {
2,551✔
3415
                read_write_paths_cleanup = strv_copy(context->read_write_paths);
1,591✔
3416
                if (!read_write_paths_cleanup)
1,591✔
3417
                        return -ENOMEM;
3418

3419
                r = strv_extend(&read_write_paths_cleanup, memory_pressure_path);
1,591✔
3420
                if (r < 0)
1,591✔
3421
                        return r;
3422

3423
                read_write_paths = read_write_paths_cleanup;
1,591✔
3424
        } else
3425
                read_write_paths = context->read_write_paths;
960✔
3426

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

3432
                if (context->private_tmp == PRIVATE_TMP_CONNECTED && runtime && runtime->shared) {
2,551✔
3433
                        if (streq_ptr(runtime->shared->tmp_dir, RUN_SYSTEMD_EMPTY))
624✔
3434
                                tmp_dir = runtime->shared->tmp_dir;
3435
                        else if (runtime->shared->tmp_dir)
624✔
3436
                                tmp_dir = strjoina(runtime->shared->tmp_dir, "/tmp");
3,120✔
3437

3438
                        if (streq_ptr(runtime->shared->var_tmp_dir, RUN_SYSTEMD_EMPTY))
624✔
3439
                                var_tmp_dir = runtime->shared->var_tmp_dir;
3440
                        else if (runtime->shared->var_tmp_dir)
624✔
3441
                                var_tmp_dir = strjoina(runtime->shared->var_tmp_dir, "/tmp");
3,120✔
3442
                }
3443
        }
3444

3445
        /* Symlinks (exec dirs, os-release) are set up after other mounts, before they are made read-only. */
3446
        setup_os_release_symlink = needs_sandboxing && exec_context_get_effective_mount_apivfs(context) && (root_dir || root_image);
2,551✔
3447
        r = compile_symlinks(context, params, setup_os_release_symlink, &symlinks);
2,551✔
3448
        if (r < 0)
2,551✔
3449
                return r;
3450

3451
        if (context->mount_propagation_flag == MS_SHARED)
2,551✔
3452
                log_exec_debug(context,
×
3453
                               params,
3454
                               "shared mount propagation hidden by other fs namespacing unit settings: ignoring");
3455

3456
        r = exec_context_get_credential_directory(context, params, params->unit_id, &creds_path);
2,551✔
3457
        if (r < 0)
2,551✔
3458
                return r;
3459

3460
        if (params->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
2,551✔
3461
                propagate_dir = path_join("/run/systemd/propagate/", params->unit_id);
2,528✔
3462
                if (!propagate_dir)
2,528✔
3463
                        return -ENOMEM;
3464

3465
                incoming_dir = strdup("/run/systemd/incoming");
2,528✔
3466
                if (!incoming_dir)
2,528✔
3467
                        return -ENOMEM;
3468

3469
                private_namespace_dir = strdup("/run/systemd");
2,528✔
3470
                if (!private_namespace_dir)
2,528✔
3471
                        return -ENOMEM;
3472

3473
                /* If running under a different root filesystem, propagate the host's os-release. We make a
3474
                 * copy rather than just bind mounting it, so that it can be updated on soft-reboot. */
3475
                if (setup_os_release_symlink) {
2,528✔
3476
                        host_os_release_stage = strdup("/run/systemd/propagate/.os-release-stage");
7✔
3477
                        if (!host_os_release_stage)
7✔
3478
                                return -ENOMEM;
3479
                }
3480
        } else {
3481
                assert(params->runtime_scope == RUNTIME_SCOPE_USER);
23✔
3482

3483
                if (asprintf(&private_namespace_dir, "/run/user/" UID_FMT "/systemd", geteuid()) < 0)
23✔
3484
                        return -ENOMEM;
3485

3486
                if (setup_os_release_symlink) {
23✔
3487
                        if (asprintf(&host_os_release_stage,
×
3488
                                     "/run/user/" UID_FMT "/systemd/propagate/.os-release-stage",
3489
                                     geteuid()) < 0)
3490
                                return -ENOMEM;
3491
                }
3492
        }
3493

3494
        if (root_image) {
2,551✔
3495
                r = verity_settings_prepare(
14✔
3496
                        &verity,
3497
                        root_image,
3498
                        context->root_hash, context->root_hash_size, context->root_hash_path,
7✔
3499
                        context->root_hash_sig, context->root_hash_sig_size, context->root_hash_sig_path,
7✔
3500
                        context->root_verity);
7✔
3501
                if (r < 0)
7✔
3502
                        return r;
3503
        }
3504

3505
        NamespaceParameters parameters = {
×
3506
                .runtime_scope = params->runtime_scope,
2,551✔
3507

3508
                .root_directory = root_dir,
3509
                .root_image = root_image,
3510
                .root_image_options = context->root_image_options,
2,551✔
3511
                .root_image_policy = context->root_image_policy ?: &image_policy_service,
2,551✔
3512

3513
                .read_write_paths = read_write_paths,
3514
                .read_only_paths = needs_sandboxing ? context->read_only_paths : NULL,
2,551✔
3515
                .inaccessible_paths = needs_sandboxing ? context->inaccessible_paths : NULL,
2,551✔
3516

3517
                .exec_paths = needs_sandboxing ? context->exec_paths : NULL,
2,551✔
3518
                .no_exec_paths = needs_sandboxing ? context->no_exec_paths : NULL,
2,551✔
3519

3520
                .empty_directories = empty_directories,
3521
                .symlinks = symlinks,
3522

3523
                .bind_mounts = bind_mounts,
3524
                .n_bind_mounts = n_bind_mounts,
3525

3526
                .temporary_filesystems = context->temporary_filesystems,
2,551✔
3527
                .n_temporary_filesystems = context->n_temporary_filesystems,
2,551✔
3528

3529
                .mount_images = context->mount_images,
2,551✔
3530
                .n_mount_images = context->n_mount_images,
2,551✔
3531
                .mount_image_policy = context->mount_image_policy ?: &image_policy_service,
2,551✔
3532

3533
                .tmp_dir = tmp_dir,
3534
                .var_tmp_dir = var_tmp_dir,
3535

3536
                .creds_path = creds_path,
3537
                .log_namespace = context->log_namespace,
2,551✔
3538
                .mount_propagation_flag = context->mount_propagation_flag,
2,551✔
3539

3540
                .verity = &verity,
3541

3542
                .extension_images = context->extension_images,
2,551✔
3543
                .n_extension_images = context->n_extension_images,
2,551✔
3544
                .extension_image_policy = context->extension_image_policy ?: &image_policy_sysext,
2,551✔
3545
                .extension_directories = context->extension_directories,
2,551✔
3546

3547
                .propagate_dir = propagate_dir,
3548
                .incoming_dir = incoming_dir,
3549
                .private_namespace_dir = private_namespace_dir,
3550
                .host_notify_socket = params->notify_socket,
2,551✔
3551
                .notify_socket_path = exec_get_private_notify_socket_path(context, params, needs_sandboxing),
2,551✔
3552
                .host_os_release_stage = host_os_release_stage,
3553

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

3559
                .protect_control_groups = needs_sandboxing ? exec_get_protect_control_groups(context, params) : PROTECT_CONTROL_GROUPS_NO,
2,551✔
3560
                .protect_kernel_tunables = needs_sandboxing && context->protect_kernel_tunables,
2,551✔
3561
                .protect_kernel_modules = needs_sandboxing && context->protect_kernel_modules,
2,551✔
3562
                .protect_kernel_logs = needs_sandboxing && context->protect_kernel_logs,
2,551✔
3563

3564
                .private_dev = needs_sandboxing && context->private_devices,
2,551✔
3565
                .private_network = needs_sandboxing && exec_needs_network_namespace(context),
2,551✔
3566
                .private_ipc = needs_sandboxing && exec_needs_ipc_namespace(context),
2,551✔
3567
                .private_pids = needs_sandboxing && exec_needs_pid_namespace(context) ? context->private_pids : PRIVATE_PIDS_NO,
2,551✔
3568
                .private_tmp = needs_sandboxing ? context->private_tmp : PRIVATE_TMP_NO,
2,551✔
3569

3570
                .mount_apivfs = needs_sandboxing && exec_context_get_effective_mount_apivfs(context),
2,551✔
3571
                .bind_log_sockets = needs_sandboxing && exec_context_get_effective_bind_log_sockets(context),
2,551✔
3572

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

3576
                .protect_home = needs_sandboxing ? context->protect_home : PROTECT_HOME_NO,
2,551✔
3577
                .protect_hostname = needs_sandboxing ? context->protect_hostname : PROTECT_HOSTNAME_NO,
2,551✔
3578
                .protect_system = needs_sandboxing ? context->protect_system : PROTECT_SYSTEM_NO,
2,551✔
3579
                .protect_proc = needs_sandboxing ? context->protect_proc : PROTECT_PROC_DEFAULT,
2,551✔
3580
                .proc_subset = needs_sandboxing ? context->proc_subset : PROC_SUBSET_ALL,
2,551✔
3581
        };
3582

3583
        r = setup_namespace(&parameters, reterr_path);
2,551✔
3584
        /* If we couldn't set up the namespace this is probably due to a missing capability. setup_namespace() reports
3585
         * that with a special, recognizable error ENOANO. In this case, silently proceed, but only if exclusively
3586
         * sandboxing options were used, i.e. nothing such as RootDirectory= or BindMount= that would result in a
3587
         * completely different execution environment. */
3588
        if (r == -ENOANO) {
2,551✔
3589
                if (insist_on_sandboxing(
×
3590
                                    context,
3591
                                    root_dir, root_image,
3592
                                    bind_mounts,
3593
                                    n_bind_mounts))
3594
                        return log_exec_debug_errno(context,
×
3595
                                                    params,
3596
                                                    SYNTHETIC_ERRNO(EOPNOTSUPP),
3597
                                                    "Failed to set up namespace, and refusing to continue since "
3598
                                                    "the selected namespacing options alter mount environment non-trivially.\n"
3599
                                                    "Bind mounts: %zu, temporary filesystems: %zu, root directory: %s, root image: %s, dynamic user: %s",
3600
                                                    n_bind_mounts,
3601
                                                    context->n_temporary_filesystems,
3602
                                                    yes_no(root_dir),
3603
                                                    yes_no(root_image),
3604
                                                    yes_no(context->dynamic_user));
3605

3606
                log_exec_debug(context, params, "Failed to set up namespace, assuming containerized execution and ignoring.");
×
3607
                return 0;
×
3608
        }
3609

3610
        return r;
3611
}
3612

3613
static int apply_working_directory(
11,065✔
3614
                const ExecContext *context,
3615
                const ExecParameters *params,
3616
                ExecRuntime *runtime,
3617
                const char *pwent_home,
3618
                char * const *env) {
3619

3620
        const char *wd;
11,065✔
3621
        int r;
11,065✔
3622

3623
        assert(context);
11,065✔
3624

3625
        if (context->working_directory_home) {
11,065✔
3626
                /* Preferably use the data from $HOME, in case it was updated by a PAM module */
3627
                wd = strv_env_get(env, "HOME");
59✔
3628
                if (!wd) {
59✔
3629
                        /* If that's not available, use the data from the struct passwd entry: */
3630
                        if (!pwent_home)
1✔
3631
                                return -ENXIO;
3632

3633
                        wd = pwent_home;
3634
                }
3635
        } else
3636
                wd = empty_to_root(context->working_directory);
11,006✔
3637

3638
        if (params->flags & EXEC_APPLY_CHROOT)
11,065✔
3639
                r = RET_NERRNO(chdir(wd));
11,065✔
3640
        else {
3641
                _cleanup_close_ int dfd = -EBADF;
×
3642

3643
                r = chase(wd,
×
3644
                          (runtime ? runtime->ephemeral_copy : NULL) ?: context->root_directory,
×
3645
                          CHASE_PREFIX_ROOT|CHASE_AT_RESOLVE_IN_ROOT,
3646
                          /* ret_path= */ NULL,
3647
                          &dfd);
3648
                if (r >= 0)
×
3649
                        r = RET_NERRNO(fchdir(dfd));
×
3650
        }
3651
        return context->working_directory_missing_ok ? 0 : r;
11,065✔
3652
}
3653

3654
static int apply_root_directory(
11,065✔
3655
                const ExecContext *context,
3656
                const ExecParameters *params,
3657
                ExecRuntime *runtime,
3658
                const bool needs_mount_ns,
3659
                int *exit_status) {
3660

3661
        assert(context);
11,065✔
3662
        assert(exit_status);
11,065✔
3663

3664
        if (params->flags & EXEC_APPLY_CHROOT)
11,065✔
3665
                if (!needs_mount_ns && context->root_directory)
11,065✔
3666
                        if (chroot((runtime ? runtime->ephemeral_copy : NULL) ?: context->root_directory) < 0) {
×
3667
                                *exit_status = EXIT_CHROOT;
×
3668
                                return -errno;
×
3669
                        }
3670

3671
        return 0;
3672
}
3673

3674
static int setup_keyring(
11,086✔
3675
                const ExecContext *context,
3676
                const ExecParameters *p,
3677
                uid_t uid, gid_t gid) {
3678

3679
        key_serial_t keyring;
11,086✔
3680
        int r = 0;
11,086✔
3681
        uid_t saved_uid;
11,086✔
3682
        gid_t saved_gid;
11,086✔
3683

3684
        assert(context);
11,086✔
3685
        assert(p);
11,086✔
3686

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

3694
        if (context->keyring_mode == EXEC_KEYRING_INHERIT)
11,086✔
3695
                return 0;
3696

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

3702
        saved_uid = getuid();
10,315✔
3703
        saved_gid = getgid();
10,315✔
3704

3705
        if (gid_is_valid(gid) && gid != saved_gid) {
10,315✔
3706
                if (setregid(gid, -1) < 0)
1,799✔
3707
                        return log_exec_error_errno(context,
×
3708
                                                    p,
3709
                                                    errno,
3710
                                                    "Failed to change GID for user keyring: %m");
3711
        }
3712

3713
        if (uid_is_valid(uid) && uid != saved_uid) {
10,315✔
3714
                if (setreuid(uid, -1) < 0) {
1,796✔
3715
                        r = log_exec_error_errno(context,
×
3716
                                                 p,
3717
                                                 errno,
3718
                                                 "Failed to change UID for user keyring: %m");
3719
                        goto out;
×
3720
                }
3721
        }
3722

3723
        keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
10,315✔
3724
        if (keyring == -1) {
10,315✔
3725
                if (errno == ENOSYS)
×
3726
                        log_exec_debug_errno(context,
×
3727
                                             p,
3728
                                             errno,
3729
                                             "Kernel keyring not supported, ignoring.");
3730
                else if (ERRNO_IS_PRIVILEGE(errno))
×
3731
                        log_exec_debug_errno(context,
×
3732
                                             p,
3733
                                             errno,
3734
                                             "Kernel keyring access prohibited, ignoring.");
3735
                else if (errno == EDQUOT)
×
3736
                        log_exec_debug_errno(context,
×
3737
                                             p,
3738
                                             errno,
3739
                                             "Out of kernel keyrings to allocate, ignoring.");
3740
                else
3741
                        r = log_exec_error_errno(context,
×
3742
                                                 p,
3743
                                                 errno,
3744
                                                 "Setting up kernel keyring failed: %m");
3745

3746
                goto out;
×
3747
        }
3748

3749
        /* When requested link the user keyring into the session keyring. */
3750
        if (context->keyring_mode == EXEC_KEYRING_SHARED) {
10,315✔
3751

3752
                if (keyctl(KEYCTL_LINK,
1,051✔
3753
                           KEY_SPEC_USER_KEYRING,
3754
                           KEY_SPEC_SESSION_KEYRING, 0, 0) < 0) {
3755
                        r = log_exec_error_errno(context,
×
3756
                                                 p,
3757
                                                 errno,
3758
                                                 "Failed to link user keyring into session keyring: %m");
3759
                        goto out;
×
3760
                }
3761
        }
3762

3763
        /* Restore uid/gid back */
3764
        if (uid_is_valid(uid) && uid != saved_uid) {
10,315✔
3765
                if (setreuid(saved_uid, -1) < 0) {
1,796✔
3766
                        r = log_exec_error_errno(context,
×
3767
                                                 p,
3768
                                                 errno,
3769
                                                 "Failed to change UID back for user keyring: %m");
3770
                        goto out;
×
3771
                }
3772
        }
3773

3774
        if (gid_is_valid(gid) && gid != saved_gid) {
10,315✔
3775
                if (setregid(saved_gid, -1) < 0)
1,799✔
3776
                        return log_exec_error_errno(context,
×
3777
                                                    p,
3778
                                                    errno,
3779
                                                    "Failed to change GID back for user keyring: %m");
3780
        }
3781

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

3786
                key = add_key("user",
20,630✔
3787
                              "invocation_id",
3788
                              &p->invocation_id,
10,315✔
3789
                              sizeof(p->invocation_id),
3790
                              KEY_SPEC_SESSION_KEYRING);
3791
                if (key == -1)
10,315✔
3792
                        log_exec_debug_errno(context,
×
3793
                                             p,
3794
                                             errno,
3795
                                             "Failed to add invocation ID to keyring, ignoring: %m");
3796
                else {
3797
                        if (keyctl(KEYCTL_SETPERM, key,
10,315✔
3798
                                   KEY_POS_VIEW|KEY_POS_READ|KEY_POS_SEARCH|
3799
                                   KEY_USR_VIEW|KEY_USR_READ|KEY_USR_SEARCH, 0, 0) < 0)
3800
                                r = log_exec_error_errno(context,
×
3801
                                                         p,
3802
                                                         errno,
3803
                                                         "Failed to restrict invocation ID permission: %m");
3804
                }
3805
        }
3806

3807
out:
10,315✔
3808
        /* Revert back uid & gid for the last time, and exit */
3809
        /* no extra logging, as only the first already reported error matters */
3810
        if (getuid() != saved_uid)
10,315✔
3811
                (void) setreuid(saved_uid, -1);
×
3812

3813
        if (getgid() != saved_gid)
10,315✔
3814
                (void) setregid(saved_gid, -1);
×
3815

3816
        return r;
3817
}
3818

3819
static void append_socket_pair(int *array, size_t *n, const int pair[static 2]) {
40,571✔
3820
        assert(array);
40,571✔
3821
        assert(n);
40,571✔
3822
        assert(pair);
40,571✔
3823

3824
        if (pair[0] >= 0)
40,571✔
3825
                array[(*n)++] = pair[0];
423✔
3826
        if (pair[1] >= 0)
40,571✔
3827
                array[(*n)++] = pair[1];
423✔
3828
}
40,571✔
3829

3830
static int close_remaining_fds(
13,483✔
3831
                const ExecParameters *params,
3832
                const ExecRuntime *runtime,
3833
                int socket_fd,
3834
                const int *fds, size_t n_fds) {
13,483✔
3835

3836
        size_t n_dont_close = 0;
13,483✔
3837
        int dont_close[n_fds + 17];
13,483✔
3838

3839
        assert(params);
13,483✔
3840

3841
        if (params->stdin_fd >= 0)
13,483✔
3842
                dont_close[n_dont_close++] = params->stdin_fd;
447✔
3843
        if (params->stdout_fd >= 0)
13,483✔
3844
                dont_close[n_dont_close++] = params->stdout_fd;
447✔
3845
        if (params->stderr_fd >= 0)
13,483✔
3846
                dont_close[n_dont_close++] = params->stderr_fd;
447✔
3847

3848
        if (socket_fd >= 0)
13,483✔
3849
                dont_close[n_dont_close++] = socket_fd;
17✔
3850
        if (n_fds > 0) {
13,483✔
3851
                memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
13,483✔
3852
                n_dont_close += n_fds;
13,483✔
3853
        }
3854

3855
        if (runtime)
13,483✔
3856
                append_socket_pair(dont_close, &n_dont_close, runtime->ephemeral_storage_socket);
13,483✔
3857

3858
        if (runtime && runtime->shared) {
13,483✔
3859
                append_socket_pair(dont_close, &n_dont_close, runtime->shared->netns_storage_socket);
13,483✔
3860
                append_socket_pair(dont_close, &n_dont_close, runtime->shared->ipcns_storage_socket);
13,483✔
3861
        }
3862

3863
        if (runtime && runtime->dynamic_creds) {
13,483✔
3864
                if (runtime->dynamic_creds->user)
13,483✔
3865
                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->user->storage_socket);
61✔
3866
                if (runtime->dynamic_creds->group)
13,483✔
3867
                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->group->storage_socket);
61✔
3868
        }
3869

3870
        if (params->user_lookup_fd >= 0)
13,483✔
3871
                dont_close[n_dont_close++] = params->user_lookup_fd;
13,483✔
3872

3873
        if (params->handoff_timestamp_fd >= 0)
13,483✔
3874
                dont_close[n_dont_close++] = params->handoff_timestamp_fd;
13,483✔
3875

3876
        if (params->pidref_transport_fd >= 0)
13,483✔
3877
                dont_close[n_dont_close++] = params->pidref_transport_fd;
12,352✔
3878

3879
        assert(n_dont_close <= ELEMENTSOF(dont_close));
13,483✔
3880

3881
        return close_all_fds(dont_close, n_dont_close);
13,483✔
3882
}
3883

3884
static int send_user_lookup(
13,481✔
3885
                const char *unit_id,
3886
                int user_lookup_fd,
3887
                uid_t uid,
3888
                gid_t gid) {
3889

3890
        assert(unit_id);
13,481✔
3891

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

3896
        if (user_lookup_fd < 0)
13,481✔
3897
                return 0;
3898

3899
        if (!uid_is_valid(uid) && !gid_is_valid(gid))
13,481✔
3900
                return 0;
3901

3902
        if (writev(user_lookup_fd,
2,683✔
3903
               (struct iovec[]) {
5,366✔
3904
                           IOVEC_MAKE(&uid, sizeof(uid)),
3905
                           IOVEC_MAKE(&gid, sizeof(gid)),
3906
                           IOVEC_MAKE_STRING(unit_id) }, 3) < 0)
5,366✔
3907
                return -errno;
×
3908

3909
        return 0;
2,683✔
3910
}
3911

3912
static int acquire_home(const ExecContext *c, const char **home, char **ret_buf) {
13,481✔
3913
        int r;
13,481✔
3914

3915
        assert(c);
13,481✔
3916
        assert(home);
13,481✔
3917
        assert(ret_buf);
13,481✔
3918

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

3921
        if (*home) /* Already acquired from get_fixed_user()? */
13,481✔
3922
                return 0;
3923

3924
        if (!c->working_directory_home)
10,864✔
3925
                return 0;
3926

3927
        if (c->dynamic_user || (c->user && is_this_me(c->user) <= 0))
×
3928
                return -EADDRNOTAVAIL;
×
3929

3930
        r = get_home_dir(ret_buf);
×
3931
        if (r < 0)
×
3932
                return r;
3933

3934
        *home = *ret_buf;
×
3935
        return 1;
×
3936
}
3937

3938
static int compile_suggested_paths(const ExecContext *c, const ExecParameters *p, char ***ret) {
61✔
3939
        _cleanup_strv_free_ char ** list = NULL;
61✔
3940
        int r;
61✔
3941

3942
        assert(c);
61✔
3943
        assert(p);
61✔
3944
        assert(ret);
61✔
3945

3946
        assert(c->dynamic_user);
61✔
3947

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

3952
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
366✔
3953

3954
                if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(t))
305✔
3955
                        continue;
61✔
3956

3957
                if (!p->prefix[t])
244✔
3958
                        continue;
×
3959

3960
                for (size_t i = 0; i < c->directories[t].n_items; i++) {
258✔
3961
                        char *e;
14✔
3962

3963
                        if (exec_directory_is_private(c, t))
14✔
3964
                                e = path_join(p->prefix[t], "private", c->directories[t].items[i].path);
12✔
3965
                        else
3966
                                e = path_join(p->prefix[t], c->directories[t].items[i].path);
2✔
3967
                        if (!e)
14✔
3968
                                return -ENOMEM;
3969

3970
                        r = strv_consume(&list, e);
14✔
3971
                        if (r < 0)
14✔
3972
                                return r;
3973
                }
3974
        }
3975

3976
        *ret = TAKE_PTR(list);
61✔
3977

3978
        return 0;
61✔
3979
}
3980

3981
static int exec_context_cpu_affinity_from_numa(const ExecContext *c, CPUSet *ret) {
2✔
3982
        _cleanup_(cpu_set_reset) CPUSet s = {};
2✔
3983
        int r;
2✔
3984

3985
        assert(c);
2✔
3986
        assert(ret);
2✔
3987

3988
        if (!c->numa_policy.nodes.set) {
2✔
3989
                log_debug("Can't derive CPU affinity mask from NUMA mask because NUMA mask is not set, ignoring");
×
3990
                return 0;
×
3991
        }
3992

3993
        r = numa_to_cpu_set(&c->numa_policy, &s);
2✔
3994
        if (r < 0)
2✔
3995
                return r;
3996

3997
        cpu_set_reset(ret);
2✔
3998

3999
        return cpu_set_add_all(ret, &s);
2✔
4000
}
4001

4002
static int add_shifted_fd(int *fds, size_t fds_size, size_t *n_fds, int *fd) {
51,514✔
4003
        int r;
51,514✔
4004

4005
        assert(fds);
51,514✔
4006
        assert(n_fds);
51,514✔
4007
        assert(*n_fds < fds_size);
51,514✔
4008
        assert(fd);
51,514✔
4009

4010
        if (*fd < 0)
51,514✔
4011
               return 0;
51,514✔
4012

4013
        if (*fd < 3 + (int) *n_fds) {
24,869✔
4014
                /* Let's move the fd up, so that it's outside of the fd range we will use to store
4015
                 * the fds we pass to the process (or which are closed only during execve). */
4016

4017
                r = fcntl(*fd, F_DUPFD_CLOEXEC, 3 + (int) *n_fds);
11,065✔
4018
                if (r < 0)
11,065✔
4019
                        return -errno;
×
4020

4021
                close_and_replace(*fd, r);
11,065✔
4022
        }
4023

4024
        fds[(*n_fds)++] = *fd;
24,869✔
4025
        return 1;
24,869✔
4026
}
4027

4028
static int connect_unix_harder(const ExecContext *c, const ExecParameters *p, const OpenFile *of, int ofd) {
1✔
4029
        static const int socket_types[] = { SOCK_DGRAM, SOCK_STREAM, SOCK_SEQPACKET };
1✔
4030

4031
        union sockaddr_union addr = {
1✔
4032
                .un.sun_family = AF_UNIX,
4033
        };
4034
        socklen_t sa_len;
1✔
4035
        int r;
1✔
4036

4037
        assert(c);
1✔
4038
        assert(p);
1✔
4039
        assert(of);
1✔
4040
        assert(ofd >= 0);
1✔
4041

4042
        r = sockaddr_un_set_path(&addr.un, FORMAT_PROC_FD_PATH(ofd));
1✔
4043
        if (r < 0)
1✔
4044
                return log_exec_debug_errno(c, p, r, "Failed to set sockaddr for '%s': %m", of->path);
×
4045
        sa_len = r;
1✔
4046

4047
        FOREACH_ELEMENT(i, socket_types) {
2✔
4048
                _cleanup_close_ int fd = -EBADF;
2✔
4049

4050
                fd = socket(AF_UNIX, *i|SOCK_CLOEXEC, 0);
2✔
4051
                if (fd < 0)
2✔
4052
                        return log_exec_debug_errno(c, p,
×
4053
                                                    errno, "Failed to create socket for '%s': %m",
4054
                                                    of->path);
4055

4056
                r = RET_NERRNO(connect(fd, &addr.sa, sa_len));
2✔
4057
                if (r >= 0)
1✔
4058
                        return TAKE_FD(fd);
1✔
4059
                if (r != -EPROTOTYPE)
1✔
4060
                        return log_exec_debug_errno(c, p,
×
4061
                                                    r, "Failed to connect to socket for '%s': %m",
4062
                                                    of->path);
4063
        }
4064

4065
        return log_exec_debug_errno(c, p,
×
4066
                                    SYNTHETIC_ERRNO(EPROTOTYPE), "No suitable socket type to connect to socket '%s'.",
4067
                                    of->path);
4068
}
4069

4070
static int get_open_file_fd(const ExecContext *c, const ExecParameters *p, const OpenFile *of) {
5✔
4071
        _cleanup_close_ int fd = -EBADF, ofd = -EBADF;
5✔
4072
        struct stat st;
5✔
4073

4074
        assert(c);
5✔
4075
        assert(p);
5✔
4076
        assert(of);
5✔
4077

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

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

4085
        if (S_ISSOCK(st.st_mode)) {
3✔
4086
                fd = connect_unix_harder(c, p, 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_exec_debug_errno(c, p,
×
4092
                                                    errno, "Failed to shutdown send for socket '%s': %m",
4093
                                                    of->path);
4094

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

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

4107
                log_exec_debug(c, p, "Opened file '%s' as fd %d.", of->path, fd);
6✔
4108
        }
4109

4110
        return TAKE_FD(fd);
4111
}
4112

4113
static int collect_open_file_fds(const ExecContext *c, ExecParameters *p, size_t *n_fds) {
13,484✔
4114
        assert(c);
13,484✔
4115
        assert(p);
13,484✔
4116
        assert(n_fds);
13,484✔
4117

4118
        LIST_FOREACH(open_files, of, p->open_files) {
13,484✔
4119
                _cleanup_close_ int fd = -EBADF;
13,489✔
4120

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

4132
                        return log_exec_error_errno(c, p, fd,
3✔
4133
                                                    "Failed to get OpenFile= file descriptor for '%s': %m",
4134
                                                    of->path);
4135
                }
4136

4137
                if (!GREEDY_REALLOC(p->fds, *n_fds + 1))
3✔
4138
                        return log_oom();
×
4139

4140
                if (strv_extend(&p->fd_names, of->fdname) < 0)
3✔
4141
                        return log_oom();
×
4142

4143
                p->fds[(*n_fds)++] = TAKE_FD(fd);
3✔
4144
        }
4145

4146
        return 0;
4147
}
4148

4149
static void log_command_line(
11,064✔
4150
                const ExecContext *context,
4151
                const ExecParameters *params,
4152
                const char *msg,
4153
                const char *executable,
4154
                char **argv) {
4155

4156
        assert(context);
11,064✔
4157
        assert(params);
11,064✔
4158
        assert(msg);
11,064✔
4159
        assert(executable);
11,064✔
4160

4161
        if (!DEBUG_LOGGING)
11,064✔
4162
                return;
11,064✔
4163

4164
        _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);
21,528✔
4165

4166
        log_exec_struct(context, params, LOG_DEBUG,
41,163✔
4167
                        "EXECUTABLE=%s", executable,
4168
                        LOG_EXEC_MESSAGE(params, "%s: %s", msg, strnull(cmdline)),
4169
                        LOG_EXEC_INVOCATION_ID(params));
4170
}
4171

4172
static bool exec_context_need_unprivileged_private_users(
11,086✔
4173
                const ExecContext *context,
4174
                const ExecParameters *params) {
4175

4176
        assert(context);
11,086✔
4177
        assert(params);
11,086✔
4178

4179
        /* These options require PrivateUsers= when used in user units, as we need to be in a user namespace
4180
         * to have permission to enable them when not running as root. If we have effective CAP_SYS_ADMIN
4181
         * (system manager) then we have privileges and don't need this. */
4182
        if (params->runtime_scope != RUNTIME_SCOPE_USER)
11,086✔
4183
                return false;
4184

4185
        return context->private_users != PRIVATE_USERS_NO ||
635✔
4186
               context->private_tmp != PRIVATE_TMP_NO ||
4187
               context->private_devices ||
632✔
4188
               context->private_network ||
627✔
4189
               context->network_namespace_path ||
627✔
4190
               context->private_ipc ||
627✔
4191
               context->ipc_namespace_path ||
627✔
4192
               context->private_mounts > 0 ||
627✔
4193
               context->mount_apivfs > 0 ||
627✔
4194
               context->bind_log_sockets > 0 ||
627✔
4195
               context->n_bind_mounts > 0 ||
627✔
4196
               context->n_temporary_filesystems > 0 ||
626✔
4197
               context->root_directory ||
626✔
4198
               !strv_isempty(context->extension_directories) ||
626✔
4199
               context->protect_system != PROTECT_SYSTEM_NO ||
626✔
4200
               context->protect_home != PROTECT_HOME_NO ||
623✔
4201
               exec_needs_pid_namespace(context) ||
623✔
4202
               context->protect_kernel_tunables ||
4203
               context->protect_kernel_modules ||
618✔
4204
               context->protect_kernel_logs ||
616✔
4205
               exec_needs_cgroup_mount(context, params) ||
616✔
4206
               context->protect_clock ||
616✔
4207
               context->protect_hostname != PROTECT_HOSTNAME_NO ||
615✔
4208
               !strv_isempty(context->read_write_paths) ||
614✔
4209
               !strv_isempty(context->read_only_paths) ||
611✔
4210
               !strv_isempty(context->inaccessible_paths) ||
611✔
4211
               !strv_isempty(context->exec_paths) ||
1,246✔
4212
               !strv_isempty(context->no_exec_paths);
635✔
4213
}
4214

4215
static bool exec_context_shall_confirm_spawn(const ExecContext *context) {
×
4216
        assert(context);
×
4217

4218
        if (confirm_spawn_disabled())
×
4219
                return false;
4220

4221
        /* For some reasons units remaining in the same process group
4222
         * as PID 1 fail to acquire the console even if it's not used
4223
         * by any process. So skip the confirmation question for them. */
4224
        return !context->same_pgrp;
×
4225
}
4226

4227
static int exec_context_named_iofds(
13,484✔
4228
                const ExecContext *c,
4229
                const ExecParameters *p,
4230
                int named_iofds[static 3]) {
4231

4232
        size_t targets;
13,484✔
4233
        const char* stdio_fdname[3];
13,484✔
4234
        size_t n_fds;
13,484✔
4235

4236
        assert(c);
13,484✔
4237
        assert(p);
13,484✔
4238
        assert(named_iofds);
13,484✔
4239

4240
        targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
13,484✔
4241
                  (c->std_output == EXEC_OUTPUT_NAMED_FD) +
13,484✔
4242
                  (c->std_error == EXEC_OUTPUT_NAMED_FD);
13,484✔
4243

4244
        for (size_t i = 0; i < 3; i++)
53,936✔
4245
                stdio_fdname[i] = exec_context_fdname(c, i);
40,452✔
4246

4247
        n_fds = p->n_storage_fds + p->n_socket_fds + p->n_extra_fds;
13,484✔
4248

4249
        for (size_t i = 0; i < n_fds  && targets > 0; i++)
13,484✔
4250
                if (named_iofds[STDIN_FILENO] < 0 &&
×
4251
                    c->std_input == EXEC_INPUT_NAMED_FD &&
×
4252
                    stdio_fdname[STDIN_FILENO] &&
×
4253
                    streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
×
4254

4255
                        named_iofds[STDIN_FILENO] = p->fds[i];
×
4256
                        targets--;
×
4257

4258
                } else if (named_iofds[STDOUT_FILENO] < 0 &&
×
4259
                           c->std_output == EXEC_OUTPUT_NAMED_FD &&
×
4260
                           stdio_fdname[STDOUT_FILENO] &&
×
4261
                           streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
×
4262

4263
                        named_iofds[STDOUT_FILENO] = p->fds[i];
×
4264
                        targets--;
×
4265

4266
                } else if (named_iofds[STDERR_FILENO] < 0 &&
×
4267
                           c->std_error == EXEC_OUTPUT_NAMED_FD &&
×
4268
                           stdio_fdname[STDERR_FILENO] &&
×
4269
                           streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
×
4270

4271
                        named_iofds[STDERR_FILENO] = p->fds[i];
×
4272
                        targets--;
×
4273
                }
4274

4275
        return targets == 0 ? 0 : -ENOENT;
13,484✔
4276
}
4277

4278
static void exec_shared_runtime_close(ExecSharedRuntime *shared) {
11,065✔
4279
        if (!shared)
11,065✔
4280
                return;
4281

4282
        safe_close_pair(shared->netns_storage_socket);
11,065✔
4283
        safe_close_pair(shared->ipcns_storage_socket);
11,065✔
4284
}
4285

4286
static void exec_runtime_close(ExecRuntime *rt) {
11,065✔
4287
        if (!rt)
11,065✔
4288
                return;
4289

4290
        safe_close_pair(rt->ephemeral_storage_socket);
11,065✔
4291

4292
        exec_shared_runtime_close(rt->shared);
11,065✔
4293
        dynamic_creds_close(rt->dynamic_creds);
11,065✔
4294
}
4295

4296
static void exec_params_close(ExecParameters *p) {
11,065✔
4297
        if (!p)
11,065✔
4298
                return;
4299

4300
        p->stdin_fd = safe_close(p->stdin_fd);
11,065✔
4301
        p->stdout_fd = safe_close(p->stdout_fd);
11,065✔
4302
        p->stderr_fd = safe_close(p->stderr_fd);
11,065✔
4303
}
4304

4305
static int exec_fd_mark_hot(
11,067✔
4306
                const ExecContext *c,
4307
                ExecParameters *p,
4308
                bool hot,
4309
                int *reterr_exit_status) {
4310

4311
        assert(c);
11,067✔
4312
        assert(p);
11,067✔
4313

4314
        if (p->exec_fd < 0)
11,067✔
4315
                return 0;
11,067✔
4316

4317
        uint8_t x = hot;
238✔
4318

4319
        if (write(p->exec_fd, &x, sizeof(x)) < 0) {
238✔
4320
                if (reterr_exit_status)
×
4321
                        *reterr_exit_status = EXIT_EXEC;
×
4322
                return log_exec_error_errno(c, p, errno, "Failed to mark exec_fd as %s: %m", hot ? "hot" : "cold");
×
4323
        }
4324

4325
        return 1;
4326
}
4327

4328
static int send_handoff_timestamp(
11,064✔
4329
                const ExecContext *c,
4330
                ExecParameters *p,
4331
                int *reterr_exit_status) {
4332

4333
        assert(c);
11,064✔
4334
        assert(p);
11,064✔
4335

4336
        if (p->handoff_timestamp_fd < 0)
11,064✔
4337
                return 0;
11,064✔
4338

4339
        dual_timestamp dt;
11,064✔
4340
        dual_timestamp_now(&dt);
11,064✔
4341

4342
        if (write(p->handoff_timestamp_fd, (const usec_t[2]) { dt.realtime, dt.monotonic }, sizeof(usec_t) * 2) < 0) {
11,064✔
4343
                if (reterr_exit_status)
×
4344
                        *reterr_exit_status = EXIT_EXEC;
×
4345
                return log_exec_error_errno(c, p, errno, "Failed to send handoff timestamp: %m");
×
4346
        }
4347

4348
        return 1;
11,064✔
4349
}
4350

4351
static void prepare_terminal(
13,481✔
4352
                const ExecContext *context,
4353
                ExecParameters *p) {
4354

4355
        _cleanup_close_ int lock_fd = -EBADF;
13,481✔
4356

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

4360
        assert(context);
13,481✔
4361
        assert(p);
13,481✔
4362

4363
        /* We only try to reset things if we there's the chance our stdout points to a TTY */
4364
        if (!(is_terminal_output(context->std_output) ||
13,481✔
4365
              (context->std_output == EXEC_OUTPUT_INHERIT && is_terminal_input(context->std_input)) ||
12,862✔
4366
              context->std_output == EXEC_OUTPUT_NAMED_FD ||
4367
              p->stdout_fd >= 0))
12,862✔
4368
                return;
12,415✔
4369

4370
        if (context->tty_reset) {
1,066✔
4371
                /* When we are resetting the TTY, then let's create a lock first, to synchronize access. This
4372
                 * in particular matters as concurrent resets and the TTY size ANSI DSR logic done by the
4373
                 * exec_context_apply_tty_size() below might interfere */
4374
                lock_fd = lock_dev_console();
162✔
4375
                if (lock_fd < 0)
162✔
4376
                        log_exec_debug_errno(context, p, lock_fd, "Failed to lock /dev/console, ignoring: %m");
×
4377

4378
                (void) terminal_reset_defensive(STDOUT_FILENO, /* switch_to_text= */ false);
162✔
4379
        }
4380

4381
        (void) exec_context_apply_tty_size(context, STDIN_FILENO, STDOUT_FILENO, /* tty_path= */ NULL);
1,066✔
4382
}
4383

4384
int exec_invoke(
13,484✔
4385
                const ExecCommand *command,
4386
                const ExecContext *context,
4387
                ExecParameters *params,
4388
                ExecRuntime *runtime,
4389
                const CGroupContext *cgroup_context,
4390
                int *exit_status) {
13,484✔
4391

4392
        _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **joined_exec_search_path = NULL, **accum_env = NULL, **replaced_argv = NULL;
28✔
4393
        int r, ngids = 0;
13,484✔
4394
        _cleanup_free_ gid_t *supplementary_gids = NULL;
×
4395
        const char *username = NULL, *groupname = NULL;
13,484✔
4396
        _cleanup_free_ char *home_buffer = NULL, *memory_pressure_path = NULL, *own_user = NULL;
×
4397
        const char *pwent_home = NULL, *shell = NULL;
13,484✔
4398
        char **final_argv = NULL;
13,484✔
4399
        dev_t journal_stream_dev = 0;
13,484✔
4400
        ino_t journal_stream_ino = 0;
13,484✔
4401
        bool userns_set_up = false;
13,484✔
4402
        bool needs_sandboxing,          /* Do we need to set up full sandboxing? (i.e. all namespacing, all MAC stuff, caps, yadda yadda */
13,484✔
4403
                needs_setuid,           /* Do we need to do the actual setresuid()/setresgid() calls? */
4404
                needs_mount_namespace;  /* Do we need to set up a mount namespace for this kernel? */
4405
        bool keep_seccomp_privileges = false;
13,484✔
4406
        bool has_cap_sys_admin = false;
13,484✔
4407
#if HAVE_SELINUX
4408
        _cleanup_free_ char *mac_selinux_context_net = NULL;
4409
        bool use_selinux = false;
4410
#endif
4411
#if ENABLE_SMACK
4412
        bool use_smack = false;
13,484✔
4413
#endif
4414
#if HAVE_APPARMOR
4415
        bool use_apparmor = false;
4416
#endif
4417
#if HAVE_SECCOMP
4418
        uint64_t saved_bset = 0;
13,484✔
4419
#endif
4420
        uid_t saved_uid = getuid();
13,484✔
4421
        gid_t saved_gid = getgid();
13,484✔
4422
        uid_t uid = UID_INVALID;
13,484✔
4423
        gid_t gid = GID_INVALID;
13,484✔
4424
        size_t n_fds, /* fds to pass to the child */
13,484✔
4425
               n_keep_fds; /* total number of fds not to close */
4426
        int secure_bits;
13,484✔
4427
        _cleanup_free_ gid_t *gids_after_pam = NULL;
28✔
4428
        int ngids_after_pam = 0;
13,484✔
4429

4430
        int socket_fd = -EBADF, named_iofds[3] = EBADF_TRIPLET;
13,484✔
4431
        size_t n_storage_fds, n_socket_fds, n_extra_fds;
13,484✔
4432

4433
        assert(command);
13,484✔
4434
        assert(context);
13,484✔
4435
        assert(params);
13,484✔
4436
        assert(exit_status);
13,484✔
4437

4438
        /* This should be mostly redundant, as the log level is also passed as an argument of the executor,
4439
         * and is already applied earlier. Just for safety. */
4440
        if (params->debug_invocation)
13,484✔
4441
                log_set_max_level(LOG_PRI(LOG_DEBUG));
2✔
4442
        else if (context->log_level_max >= 0)
13,482✔
4443
                log_set_max_level(context->log_level_max);
5✔
4444

4445
        /* Explicitly test for CVE-2021-4034 inspired invocations */
4446
        if (!command->path || strv_isempty(command->argv)) {
13,484✔
4447
                *exit_status = EXIT_EXEC;
×
4448
                return log_exec_error_errno(
×
4449
                                context,
4450
                                params,
4451
                                SYNTHETIC_ERRNO(EINVAL),
4452
                                "Invalid command line arguments.");
4453
        }
4454

4455
        LOG_CONTEXT_PUSH_EXEC(context, params);
39,208✔
4456

4457
        if (context->std_input == EXEC_INPUT_SOCKET ||
13,484✔
4458
            context->std_output == EXEC_OUTPUT_SOCKET ||
13,473✔
4459
            context->std_error == EXEC_OUTPUT_SOCKET) {
13,467✔
4460

4461
                if (params->n_socket_fds > 1)
17✔
4462
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EINVAL), "Got more than one socket.");
×
4463

4464
                if (params->n_socket_fds == 0)
17✔
4465
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EINVAL), "Got no socket.");
×
4466

4467
                socket_fd = params->fds[0];
17✔
4468
                n_storage_fds = n_socket_fds = n_extra_fds = 0;
17✔
4469
        } else {
4470
                n_socket_fds = params->n_socket_fds;
13,467✔
4471
                n_storage_fds = params->n_storage_fds;
13,467✔
4472
                n_extra_fds = params->n_extra_fds;
13,467✔
4473
        }
4474
        n_fds = n_socket_fds + n_storage_fds + n_extra_fds;
13,484✔
4475

4476
        r = exec_context_named_iofds(context, params, named_iofds);
13,484✔
4477
        if (r < 0)
13,484✔
4478
                return log_exec_error_errno(context, params, r, "Failed to load a named file descriptor: %m");
×
4479

4480
        rename_process_from_path(command->path);
13,484✔
4481

4482
        /* We reset exactly these signals, since they are the only ones we set to SIG_IGN in the main
4483
         * daemon. All others we leave untouched because we set them to SIG_DFL or a valid handler initially,
4484
         * both of which will be demoted to SIG_DFL. */
4485
        (void) default_signals(SIGNALS_CRASH_HANDLER,
13,484✔
4486
                               SIGNALS_IGNORE);
4487

4488
        if (context->ignore_sigpipe)
13,484✔
4489
                (void) ignore_signals(SIGPIPE);
13,322✔
4490

4491
        r = reset_signal_mask();
13,484✔
4492
        if (r < 0) {
13,484✔
4493
                *exit_status = EXIT_SIGNAL_MASK;
×
4494
                return log_exec_error_errno(context, params, r, "Failed to set process signal mask: %m");
×
4495
        }
4496

4497
        if (params->idle_pipe)
13,484✔
4498
                do_idle_pipe_dance(params->idle_pipe);
159✔
4499

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

4505
        log_forget_fds();
13,484✔
4506
        log_set_open_when_needed(true);
13,484✔
4507
        log_settle_target();
13,484✔
4508

4509
        /* In case anything used libc syslog(), close this here, too */
4510
        closelog();
13,484✔
4511

4512
        r = collect_open_file_fds(context, params, &n_fds);
13,484✔
4513
        if (r < 0) {
13,484✔
4514
                *exit_status = EXIT_FDS;
1✔
4515
                return log_exec_error_errno(context, params, r, "Failed to get OpenFile= file descriptors: %m");
3✔
4516
        }
4517

4518
        int keep_fds[n_fds + 4];
13,483✔
4519
        memcpy_safe(keep_fds, params->fds, n_fds * sizeof(int));
13,483✔
4520
        n_keep_fds = n_fds;
13,483✔
4521

4522
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->exec_fd);
13,483✔
4523
        if (r < 0) {
13,483✔
4524
                *exit_status = EXIT_FDS;
×
4525
                return log_exec_error_errno(context, params, r, "Failed to collect shifted fd: %m");
×
4526
        }
4527

4528
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->handoff_timestamp_fd);
13,483✔
4529
        if (r < 0) {
13,483✔
4530
                *exit_status = EXIT_FDS;
×
4531
                return log_exec_error_errno(context, params, r, "Failed to collect shifted fd: %m");
×
4532
        }
4533

4534
#if HAVE_LIBBPF
4535
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->bpf_restrict_fs_map_fd);
13,483✔
4536
        if (r < 0) {
13,483✔
4537
                *exit_status = EXIT_FDS;
×
4538
                return log_exec_error_errno(context, params, r, "Failed to collect shifted fd: %m");
×
4539
        }
4540
#endif
4541

4542
        r = close_remaining_fds(params, runtime, socket_fd, keep_fds, n_keep_fds);
13,483✔
4543
        if (r < 0) {
13,483✔
4544
                *exit_status = EXIT_FDS;
×
4545
                return log_exec_error_errno(context, params, r, "Failed to close unwanted file descriptors: %m");
×
4546
        }
4547

4548
        if (!context->same_pgrp &&
25,981✔
4549
            setsid() < 0) {
12,498✔
4550
                *exit_status = EXIT_SETSID;
×
4551
                return log_exec_error_errno(context, params, errno, "Failed to create new process session: %m");
×
4552
        }
4553

4554
        /* Now, reset the TTY associated to this service "destructively" (i.e. possibly even hang up or
4555
         * disallocate the VT), to get rid of any prior uses of the device. Note that we do not keep any fd
4556
         * open here, hence some of the settings made here might vanish again, depending on the TTY driver
4557
         * used. A 2nd ("constructive") initialization after we opened the input/output fds we actually want
4558
         * will fix this. */
4559
        exec_context_tty_reset(context, params);
13,483✔
4560

4561
        if (params->shall_confirm_spawn && exec_context_shall_confirm_spawn(context)) {
13,483✔
4562
                _cleanup_free_ char *cmdline = NULL;
×
4563

4564
                cmdline = quote_command_line(command->argv, SHELL_ESCAPE_EMPTY);
×
4565
                if (!cmdline) {
×
4566
                        *exit_status = EXIT_MEMORY;
×
4567
                        return log_oom();
×
4568
                }
4569

4570
                r = ask_for_confirmation(context, params, cmdline);
×
4571
                if (r != CONFIRM_EXECUTE) {
×
4572
                        if (r == CONFIRM_PRETEND_SUCCESS) {
×
4573
                                *exit_status = EXIT_SUCCESS;
×
4574
                                return 0;
×
4575
                        }
4576

4577
                        *exit_status = EXIT_CONFIRM;
×
4578
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(ECANCELED),
×
4579
                                                    "Execution cancelled by the user.");
4580
                }
4581
        }
4582

4583
        /* We are about to invoke NSS and PAM modules. Let's tell them what we are doing here, maybe they care. This is
4584
         * used by nss-resolve to disable itself when we are about to start systemd-resolved, to avoid deadlocks. Note
4585
         * that these env vars do not survive the execve(), which means they really only apply to the PAM and NSS
4586
         * invocations themselves. Also note that while we'll only invoke NSS modules involved in user management they
4587
         * might internally call into other NSS modules that are involved in hostname resolution, we never know. */
4588
        if (setenv("SYSTEMD_ACTIVATION_UNIT", params->unit_id, true) != 0 ||
26,966✔
4589
            setenv("SYSTEMD_ACTIVATION_SCOPE", runtime_scope_to_string(params->runtime_scope), true) != 0) {
13,483✔
4590
                *exit_status = EXIT_MEMORY;
×
4591
                return log_exec_error_errno(context, params, errno, "Failed to update environment: %m");
×
4592
        }
4593

4594
        if (context->dynamic_user && runtime && runtime->dynamic_creds) {
13,544✔
4595
                _cleanup_strv_free_ char **suggested_paths = NULL;
61✔
4596

4597
                /* On top of that, make sure we bypass our own NSS module nss-systemd comprehensively for any NSS
4598
                 * checks, if DynamicUser=1 is used, as we shouldn't create a feedback loop with ourselves here. */
4599
                if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
61✔
4600
                        *exit_status = EXIT_USER;
×
4601
                        return log_exec_error_errno(context, params, errno, "Failed to update environment: %m");
×
4602
                }
4603

4604
                r = compile_suggested_paths(context, params, &suggested_paths);
61✔
4605
                if (r < 0) {
61✔
4606
                        *exit_status = EXIT_MEMORY;
×
4607
                        return log_oom();
×
4608
                }
4609

4610
                r = dynamic_creds_realize(runtime->dynamic_creds, suggested_paths, &uid, &gid);
61✔
4611
                if (r < 0) {
61✔
4612
                        *exit_status = EXIT_USER;
×
4613
                        if (r == -EILSEQ)
×
4614
                                return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EOPNOTSUPP),
×
4615
                                                            "Failed to update dynamic user credentials: User or group with specified name already exists.");
4616
                        return log_exec_error_errno(context, params, r, "Failed to update dynamic user credentials: %m");
×
4617
                }
4618

4619
                if (!uid_is_valid(uid)) {
61✔
4620
                        *exit_status = EXIT_USER;
×
4621
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(ESRCH), "UID validation failed for \""UID_FMT"\".", uid);
×
4622
                }
4623

4624
                if (!gid_is_valid(gid)) {
61✔
4625
                        *exit_status = EXIT_USER;
×
4626
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(ESRCH), "GID validation failed for \""GID_FMT"\".", gid);
×
4627
                }
4628

4629
                if (runtime->dynamic_creds->user)
61✔
4630
                        username = runtime->dynamic_creds->user->name;
61✔
4631

4632
        } else {
4633
                const char *u;
13,422✔
4634

4635
                if (context->user)
13,422✔
4636
                        u = context->user;
4637
                else if (context->pam_name) {
10,862✔
4638
                        /* If PAM is enabled but no user name is explicitly selected, then use our own one. */
4639
                        own_user = getusername_malloc();
59✔
4640
                        if (!own_user) {
59✔
4641
                                *exit_status = EXIT_USER;
×
4642
                                return log_exec_error_errno(context, params, r, "Failed to determine my own user ID: %m");
×
4643
                        }
4644
                        u = own_user;
4645
                } else
4646
                        u = NULL;
4647

4648
                if (u) {
4649
                        r = get_fixed_user(u, &username, &uid, &gid, &pwent_home, &shell);
2,619✔
4650
                        if (r < 0) {
2,619✔
4651
                                *exit_status = EXIT_USER;
2✔
4652
                                return log_exec_error_errno(context, params, r, "Failed to determine user credentials: %m");
6✔
4653
                        }
4654
                }
4655

4656
                if (context->group) {
13,420✔
4657
                        r = get_fixed_group(context->group, &groupname, &gid);
9✔
4658
                        if (r < 0) {
9✔
4659
                                *exit_status = EXIT_GROUP;
×
4660
                                return log_exec_error_errno(context, params, r, "Failed to determine group credentials: %m");
×
4661
                        }
4662
                }
4663
        }
4664

4665
        /* Initialize user supplementary groups and get SupplementaryGroups= ones */
4666
        r = get_supplementary_groups(context, username, groupname, gid,
13,481✔
4667
                                     &supplementary_gids, &ngids);
4668
        if (r < 0) {
13,481✔
4669
                *exit_status = EXIT_GROUP;
×
4670
                return log_exec_error_errno(context, params, r, "Failed to determine supplementary groups: %m");
×
4671
        }
4672

4673
        r = send_user_lookup(params->unit_id, params->user_lookup_fd, uid, gid);
13,481✔
4674
        if (r < 0) {
13,481✔
4675
                *exit_status = EXIT_USER;
×
4676
                return log_exec_error_errno(context, params, r, "Failed to send user credentials to PID1: %m");
×
4677
        }
4678

4679
        params->user_lookup_fd = safe_close(params->user_lookup_fd);
13,481✔
4680

4681
        r = acquire_home(context, &pwent_home, &home_buffer);
13,481✔
4682
        if (r < 0) {
13,481✔
4683
                *exit_status = EXIT_CHDIR;
×
4684
                return log_exec_error_errno(context, params, r, "Failed to determine $HOME for the invoking user: %m");
×
4685
        }
4686

4687
        /* If a socket is connected to STDIN/STDOUT/STDERR, we must drop O_NONBLOCK */
4688
        if (socket_fd >= 0)
13,481✔
4689
                (void) fd_nonblock(socket_fd, false);
17✔
4690

4691
        /* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields.
4692
         * Hence we need to migrate to the target cgroup from init.scope before connecting to journald */
4693
        if (params->cgroup_path) {
13,481✔
4694
                _cleanup_free_ char *p = NULL;
13,481✔
4695

4696
                r = exec_params_get_cgroup_path(params, cgroup_context, &p);
13,481✔
4697
                if (r < 0) {
13,481✔
4698
                        *exit_status = EXIT_CGROUP;
×
4699
                        return log_exec_error_errno(context, params, r, "Failed to acquire cgroup path: %m");
×
4700
                }
4701

4702
                r = cg_attach_everywhere(params->cgroup_supported, p, 0);
13,481✔
4703
                if (r == -EUCLEAN) {
13,481✔
4704
                        *exit_status = EXIT_CGROUP;
×
4705
                        return log_exec_error_errno(context, params, r,
×
4706
                                                    "Failed to attach process to cgroup '%s', "
4707
                                                    "because the cgroup or one of its parents or "
4708
                                                    "siblings is in the threaded mode.", p);
4709
                }
4710
                if (r < 0) {
13,481✔
4711
                        *exit_status = EXIT_CGROUP;
×
4712
                        return log_exec_error_errno(context, params, r, "Failed to attach to cgroup %s: %m", p);
×
4713
                }
4714
        }
4715

4716
        if (context->network_namespace_path && runtime && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
13,481✔
4717
                r = open_shareable_ns_path(runtime->shared->netns_storage_socket, context->network_namespace_path, CLONE_NEWNET);
×
4718
                if (r < 0) {
×
4719
                        *exit_status = EXIT_NETWORK;
×
4720
                        return log_exec_error_errno(context, params, r, "Failed to open network namespace path %s: %m", context->network_namespace_path);
×
4721
                }
4722
        }
4723

4724
        if (context->ipc_namespace_path && runtime && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
13,481✔
4725
                r = open_shareable_ns_path(runtime->shared->ipcns_storage_socket, context->ipc_namespace_path, CLONE_NEWIPC);
×
4726
                if (r < 0) {
×
4727
                        *exit_status = EXIT_NAMESPACE;
×
4728
                        return log_exec_error_errno(context, params, r, "Failed to open IPC namespace path %s: %m", context->ipc_namespace_path);
×
4729
                }
4730
        }
4731

4732
        r = setup_input(context, params, socket_fd, named_iofds);
13,481✔
4733
        if (r < 0) {
13,481✔
UNCOV
4734
                *exit_status = EXIT_STDIN;
×
UNCOV
4735
                return log_exec_error_errno(context, params, r, "Failed to set up standard input: %m");
×
4736
        }
4737

4738
        _cleanup_free_ char *fname = NULL;
25✔
4739
        r = path_extract_filename(command->path, &fname);
13,481✔
4740
        if (r < 0) {
13,481✔
4741
                *exit_status = EXIT_STDOUT;
×
4742
                return log_exec_error_errno(context, params, r, "Failed to extract filename from path %s: %m", command->path);
×
4743
        }
4744

4745
        r = setup_output(context, params, STDOUT_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
13,481✔
4746
        if (r < 0) {
13,481✔
4747
                *exit_status = EXIT_STDOUT;
×
4748
                return log_exec_error_errno(context, params, r, "Failed to set up standard output: %m");
×
4749
        }
4750

4751
        r = setup_output(context, params, STDERR_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
13,481✔
4752
        if (r < 0) {
13,481✔
4753
                *exit_status = EXIT_STDERR;
×
4754
                return log_exec_error_errno(context, params, r, "Failed to set up standard error output: %m");
×
4755
        }
4756

4757
        /* Now that stdin/stdout are definiely opened, properly initialize it with our desired
4758
         * settings. Note: this is a "constructive" reset, it prepares things for us to use. This is
4759
         * different from the "destructive" TTY reset further up. Also note: we apply this on stdin/stdout in
4760
         * case this is a tty, regardless if we opened it ourselves or got it passed in pre-opened. */
4761
        prepare_terminal(context, params);
13,481✔
4762

4763
        if (context->oom_score_adjust_set) {
13,481✔
4764
                /* When we can't make this change due to EPERM, then let's silently skip over it. User
4765
                 * namespaces prohibit write access to this file, and we shouldn't trip up over that. */
4766
                r = set_oom_score_adjust(context->oom_score_adjust);
1,451✔
4767
                if (ERRNO_IS_NEG_PRIVILEGE(r))
1,451✔
4768
                        log_exec_debug_errno(context, params, r,
×
4769
                                             "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
4770
                else if (r < 0) {
1,451✔
4771
                        *exit_status = EXIT_OOM_ADJUST;
×
4772
                        return log_exec_error_errno(context, params, r, "Failed to adjust OOM setting: %m");
×
4773
                }
4774
        }
4775

4776
        if (context->coredump_filter_set) {
13,481✔
4777
                r = set_coredump_filter(context->coredump_filter);
2✔
4778
                if (ERRNO_IS_NEG_PRIVILEGE(r))
2✔
4779
                        log_exec_debug_errno(context, params, r, "Failed to adjust coredump_filter, ignoring: %m");
×
4780
                else if (r < 0) {
2✔
4781
                        *exit_status = EXIT_LIMITS;
×
4782
                        return log_exec_error_errno(context, params, r, "Failed to adjust coredump_filter: %m");
×
4783
                }
4784
        }
4785

4786
        if (context->cpu_sched_set) {
13,481✔
4787
                struct sched_attr attr = {
×
4788
                        .size = sizeof(attr),
4789
                        .sched_policy = context->cpu_sched_policy,
×
4790
                        .sched_priority = context->cpu_sched_priority,
×
4791
                        .sched_flags = context->cpu_sched_reset_on_fork ? SCHED_FLAG_RESET_ON_FORK : 0,
×
4792
                };
4793

4794
                r = sched_setattr(/* pid= */ 0, &attr, /* flags= */ 0);
×
4795
                if (r < 0) {
×
4796
                        *exit_status = EXIT_SETSCHEDULER;
×
4797
                        return log_exec_error_errno(context, params, errno, "Failed to set up CPU scheduling: %m");
×
4798
                }
4799
        }
4800

4801
        /*
4802
         * Set nice value _after_ the call to sched_setattr() because struct sched_attr includes sched_nice
4803
         * which we do not set, thus it will clobber any previously set nice value. Scheduling policy might
4804
         * be reasonably set together with nice value e.g. in case of SCHED_BATCH (see sched(7)).
4805
         * It would be ideal to set both with the same call, but we cannot easily do so because of all the
4806
         * extra logic in setpriority_closest().
4807
         */
4808
        if (context->nice_set) {
13,481✔
4809
                r = setpriority_closest(context->nice);
16✔
4810
                if (r < 0) {
16✔
4811
                        *exit_status = EXIT_NICE;
×
4812
                        return log_exec_error_errno(context, params, r, "Failed to set up process scheduling priority (nice level): %m");
×
4813
                }
4814
        }
4815

4816
        if (context->cpu_affinity_from_numa || context->cpu_set.set) {
13,481✔
4817
                _cleanup_(cpu_set_reset) CPUSet converted_cpu_set = {};
2✔
4818
                const CPUSet *cpu_set;
2✔
4819

4820
                if (context->cpu_affinity_from_numa) {
2✔
4821
                        r = exec_context_cpu_affinity_from_numa(context, &converted_cpu_set);
2✔
4822
                        if (r < 0) {
2✔
4823
                                *exit_status = EXIT_CPUAFFINITY;
×
4824
                                return log_exec_error_errno(context, params, r, "Failed to derive CPU affinity mask from NUMA mask: %m");
×
4825
                        }
4826

4827
                        cpu_set = &converted_cpu_set;
4828
                } else
4829
                        cpu_set = &context->cpu_set;
×
4830

4831
                if (sched_setaffinity(0, cpu_set->allocated, cpu_set->set) < 0) {
2✔
4832
                        *exit_status = EXIT_CPUAFFINITY;
×
4833
                        return log_exec_error_errno(context, params, errno, "Failed to set up CPU affinity: %m");
×
4834
                }
4835
        }
4836

4837
        if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) {
13,481✔
4838
                r = apply_numa_policy(&context->numa_policy);
19✔
4839
                if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
19✔
4840
                        log_exec_debug_errno(context, params, r, "NUMA support not available, ignoring.");
×
4841
                else if (r < 0) {
19✔
4842
                        *exit_status = EXIT_NUMA_POLICY;
2✔
4843
                        return log_exec_error_errno(context, params, r, "Failed to set NUMA memory policy: %m");
6✔
4844
                }
4845
        }
4846

4847
        if (context->ioprio_set)
13,479✔
4848
                if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
9✔
4849
                        *exit_status = EXIT_IOPRIO;
×
4850
                        return log_exec_error_errno(context, params, errno, "Failed to set up IO scheduling priority: %m");
×
4851
                }
4852

4853
        if (context->timer_slack_nsec != NSEC_INFINITY)
13,479✔
4854
                if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
×
4855
                        *exit_status = EXIT_TIMERSLACK;
×
4856
                        return log_exec_error_errno(context, params, errno, "Failed to set up timer slack: %m");
×
4857
                }
4858

4859
        if (context->personality != PERSONALITY_INVALID) {
13,479✔
4860
                r = safe_personality(context->personality);
×
4861
                if (r < 0) {
×
4862
                        *exit_status = EXIT_PERSONALITY;
×
4863
                        return log_exec_error_errno(context, params, r, "Failed to set up execution domain (personality): %m");
×
4864
                }
4865
        }
4866

4867
#if ENABLE_UTMP
4868
        if (context->utmp_id) {
13,479✔
4869
                _cleanup_free_ char *username_alloc = NULL;
164✔
4870

4871
                if (!username && context->utmp_mode == EXEC_UTMP_USER) {
164✔
4872
                        username_alloc = uid_to_name(uid_is_valid(uid) ? uid : saved_uid);
1✔
4873
                        if (!username_alloc) {
1✔
4874
                                *exit_status = EXIT_USER;
×
4875
                                return log_oom();
×
4876
                        }
4877
                }
4878

4879
                const char *line = context->tty_path ?
328✔
4880
                        (path_startswith(context->tty_path, "/dev/") ?: context->tty_path) :
164✔
4881
                        NULL;
4882
                utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
164✔
4883
                                      line,
4884
                                      context->utmp_mode == EXEC_UTMP_INIT  ? INIT_PROCESS :
164✔
4885
                                      context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
7✔
4886
                                      USER_PROCESS,
4887
                                      username ?: username_alloc);
164✔
4888
        }
4889
#endif
4890

4891
        if (uid_is_valid(uid)) {
13,479✔
4892
                r = chown_terminal(STDIN_FILENO, uid);
2,678✔
4893
                if (r < 0) {
2,678✔
4894
                        *exit_status = EXIT_STDIN;
×
4895
                        return log_exec_error_errno(context, params, r, "Failed to change ownership of terminal: %m");
×
4896
                }
4897
        }
4898

4899
        /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted
4900
         * from it. */
4901
        needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
13,479✔
4902

4903
        if (params->cgroup_path) {
13,479✔
4904
                /* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1
4905
                 * this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not
4906
                 * safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only
4907
                 * touch a single hierarchy too. */
4908

4909
                if (params->flags & EXEC_CGROUP_DELEGATE) {
13,479✔
4910
                        _cleanup_free_ char *p = NULL;
653✔
4911

4912
                        r = cg_set_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, uid, gid);
653✔
4913
                        if (r < 0) {
653✔
4914
                                *exit_status = EXIT_CGROUP;
×
4915
                                return log_exec_error_errno(context, params, r, "Failed to adjust control group access: %m");
×
4916
                        }
4917

4918
                        r = exec_params_get_cgroup_path(params, cgroup_context, &p);
653✔
4919
                        if (r < 0) {
653✔
4920
                                *exit_status = EXIT_CGROUP;
×
4921
                                return log_exec_error_errno(context, params, r, "Failed to acquire cgroup path: %m");
×
4922
                        }
4923
                        if (r > 0) {
653✔
4924
                                r = cg_set_access_recursive(SYSTEMD_CGROUP_CONTROLLER, p, uid, gid);
319✔
4925
                                if (r < 0) {
319✔
4926
                                        *exit_status = EXIT_CGROUP;
×
4927
                                        return log_exec_error_errno(context, params, r, "Failed to adjust control subgroup access: %m");
×
4928
                                }
4929
                        }
4930
                }
4931

4932
                if (cgroup_context && cg_unified() > 0 && is_pressure_supported() > 0) {
26,958✔
4933
                        if (cgroup_context_want_memory_pressure(cgroup_context)) {
13,479✔
4934
                                r = cg_get_path("memory", params->cgroup_path, "memory.pressure", &memory_pressure_path);
13,125✔
4935
                                if (r < 0) {
13,125✔
4936
                                        *exit_status = EXIT_MEMORY;
×
4937
                                        return log_oom();
×
4938
                                }
4939

4940
                                r = chmod_and_chown(memory_pressure_path, 0644, uid, gid);
13,125✔
4941
                                if (r < 0) {
13,125✔
4942
                                        log_exec_full_errno(context, params, r == -ENOENT || ERRNO_IS_PRIVILEGE(r) ? LOG_DEBUG : LOG_WARNING, r,
2✔
4943
                                                            "Failed to adjust ownership of '%s', ignoring: %m", memory_pressure_path);
4944
                                        memory_pressure_path = mfree(memory_pressure_path);
1✔
4945
                                }
4946
                                /* First we use the current cgroup path to chmod and chown the memory pressure path, then pass the path relative
4947
                                 * to the cgroup namespace to environment variables and mounts. If chown/chmod fails, we should not pass memory
4948
                                 * pressure path environment variable or read-write mount to the unit. This is why we check if
4949
                                 * memory_pressure_path != NULL in the conditional below. */
4950
                                if (memory_pressure_path && needs_sandboxing && exec_needs_cgroup_namespace(context, params)) {
13,125✔
4951
                                        memory_pressure_path = mfree(memory_pressure_path);
9✔
4952
                                        r = cg_get_path("memory", "", "memory.pressure", &memory_pressure_path);
9✔
4953
                                        if (r < 0) {
9✔
4954
                                                *exit_status = EXIT_MEMORY;
×
4955
                                                return log_oom();
×
4956
                                        }
4957
                                }
4958
                        } else if (cgroup_context->memory_pressure_watch == CGROUP_PRESSURE_WATCH_NO) {
354✔
4959
                                memory_pressure_path = strdup("/dev/null"); /* /dev/null is explicit indicator for turning of memory pressure watch */
×
4960
                                if (!memory_pressure_path) {
×
4961
                                        *exit_status = EXIT_MEMORY;
×
4962
                                        return log_oom();
×
4963
                                }
4964
                        }
4965
                }
4966
        }
4967

4968
        needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
13,479✔
4969

4970
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
80,869✔
4971
                r = setup_exec_directory(context, params, uid, gid, dt, needs_mount_namespace, exit_status);
67,391✔
4972
                if (r < 0)
67,391✔
4973
                        return log_exec_error_errno(context, params, r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
3✔
4974
        }
4975

4976
        r = exec_setup_credentials(context, params, params->unit_id, uid, gid);
13,478✔
4977
        if (r < 0) {
11,086✔
4978
                *exit_status = EXIT_CREDENTIALS;
×
4979
                return log_exec_error_errno(context, params, r, "Failed to set up credentials: %m");
×
4980
        }
4981

4982
        r = build_environment(
11,086✔
4983
                        context,
4984
                        params,
4985
                        cgroup_context,
4986
                        n_fds,
4987
                        pwent_home,
4988
                        username,
4989
                        shell,
4990
                        journal_stream_dev,
4991
                        journal_stream_ino,
4992
                        memory_pressure_path,
4993
                        needs_sandboxing,
4994
                        &our_env);
4995
        if (r < 0) {
11,086✔
4996
                *exit_status = EXIT_MEMORY;
×
4997
                return log_oom();
×
4998
        }
4999

5000
        r = build_pass_environment(context, &pass_env);
11,086✔
5001
        if (r < 0) {
11,086✔
5002
                *exit_status = EXIT_MEMORY;
×
5003
                return log_oom();
×
5004
        }
5005

5006
        /* The $PATH variable is set to the default path in params->environment. However, this is overridden
5007
         * if user-specified fields have $PATH set. The intention is to also override $PATH if the unit does
5008
         * not specify PATH but the unit has ExecSearchPath. */
5009
        if (!strv_isempty(context->exec_search_path)) {
11,086✔
5010
                _cleanup_free_ char *joined = NULL;
×
5011

5012
                joined = strv_join(context->exec_search_path, ":");
×
5013
                if (!joined) {
×
5014
                        *exit_status = EXIT_MEMORY;
×
5015
                        return log_oom();
×
5016
                }
5017

5018
                r = strv_env_assign(&joined_exec_search_path, "PATH", joined);
×
5019
                if (r < 0) {
×
5020
                        *exit_status = EXIT_MEMORY;
×
5021
                        return log_oom();
×
5022
                }
5023
        }
5024

5025
        accum_env = strv_env_merge(params->environment,
11,086✔
5026
                                   our_env,
5027
                                   joined_exec_search_path,
5028
                                   pass_env,
5029
                                   context->environment,
5030
                                   params->files_env);
5031
        if (!accum_env) {
11,086✔
5032
                *exit_status = EXIT_MEMORY;
×
5033
                return log_oom();
×
5034
        }
5035
        accum_env = strv_env_clean(accum_env);
11,086✔
5036

5037
        (void) umask(context->umask);
11,086✔
5038

5039
        r = setup_keyring(context, params, uid, gid);
11,086✔
5040
        if (r < 0) {
11,086✔
5041
                *exit_status = EXIT_KEYRING;
×
5042
                return log_exec_error_errno(context, params, r, "Failed to set up kernel keyring: %m");
×
5043
        }
5044

5045
        /* We need setresuid() if the caller asked us to apply sandboxing and the command isn't explicitly
5046
         * excepted from either whole sandboxing or just setresuid() itself. */
5047
        needs_setuid = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & (EXEC_COMMAND_FULLY_PRIVILEGED|EXEC_COMMAND_NO_SETUID));
11,086✔
5048

5049
        uint64_t capability_ambient_set = context->capability_ambient_set;
11,086✔
5050

5051
        /* Check CAP_SYS_ADMIN before we enter user namespace to see if we can mount /proc even though its masked. */
5052
        has_cap_sys_admin = have_effective_cap(CAP_SYS_ADMIN) > 0;
11,086✔
5053

5054
        if (needs_sandboxing) {
11,086✔
5055
                /* MAC enablement checks need to be done before a new mount ns is created, as they rely on
5056
                 * /sys being present. The actual MAC context application will happen later, as late as
5057
                 * possible, to avoid impacting our own code paths. */
5058

5059
#if HAVE_SELINUX
5060
                use_selinux = mac_selinux_use();
5061
#endif
5062
#if ENABLE_SMACK
5063
                use_smack = mac_smack_use();
11,086✔
5064
#endif
5065
#if HAVE_APPARMOR
5066
                if (mac_apparmor_use()) {
5067
                        r = dlopen_libapparmor();
5068
                        if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r))
5069
                                log_warning_errno(r, "Failed to load libapparmor, ignoring: %m");
5070
                        use_apparmor = r >= 0;
5071
                }
5072
#endif
5073
        }
5074

5075
        if (needs_sandboxing) {
11,086✔
5076
                int which_failed;
11,086✔
5077

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

5081
                r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed);
11,086✔
5082
                if (r < 0) {
11,086✔
5083
                        *exit_status = EXIT_LIMITS;
×
5084
                        return log_exec_error_errno(context, params, r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
×
5085
                }
5086
        }
5087

5088
        if (needs_setuid && context->pam_name && username) {
11,086✔
5089
                /* Let's call into PAM after we set up our own idea of resource limits so that pam_limits
5090
                 * wins here. (See above.) */
5091

5092
                /* All fds passed in the fds array will be closed in the pam child process. */
5093
                r = setup_pam(context, params, username, uid, gid, &accum_env, params->fds, n_fds, params->exec_fd);
307✔
5094
                if (r < 0) {
307✔
5095
                        *exit_status = EXIT_PAM;
×
5096
                        return log_exec_error_errno(context, params, r, "Failed to set up PAM session: %m");
×
5097
                }
5098

5099
                /* PAM modules might have set some ambient caps. Query them here and merge them into
5100
                 * the caps we want to set in the end, so that we don't end up unsetting them. */
5101
                uint64_t ambient_after_pam;
307✔
5102
                r = capability_get_ambient(&ambient_after_pam);
307✔
5103
                if (r < 0) {
307✔
5104
                        *exit_status = EXIT_CAPABILITIES;
×
5105
                        return log_exec_error_errno(context, params, r, "Failed to query ambient caps: %m");
×
5106
                }
5107

5108
                capability_ambient_set |= ambient_after_pam;
307✔
5109

5110
                ngids_after_pam = getgroups_alloc(&gids_after_pam);
307✔
5111
                if (ngids_after_pam < 0) {
307✔
5112
                        *exit_status = EXIT_GROUP;
×
5113
                        return log_exec_error_errno(context, params, ngids_after_pam, "Failed to obtain groups after setting up PAM: %m");
×
5114
                }
5115
        }
5116

5117
        if (needs_sandboxing && exec_context_need_unprivileged_private_users(context, params)) {
11,086✔
5118
                /* If we're unprivileged, set up the user namespace first to enable use of the other namespaces.
5119
                 * Users with CAP_SYS_ADMIN can set up user namespaces last because they will be able to
5120
                 * set up all of the other namespaces (i.e. network, mount, UTS) without a user namespace. */
5121
                PrivateUsers pu = context->private_users;
24✔
5122
                if (pu == PRIVATE_USERS_NO)
24✔
5123
                        pu = PRIVATE_USERS_SELF;
21✔
5124

5125
                /* The kernel requires /proc/pid/setgroups be set to "deny" prior to writing /proc/pid/gid_map in
5126
                 * unprivileged user namespaces. */
5127
                r = setup_private_users(pu, saved_uid, saved_gid, uid, gid, /* allow_setgroups= */ false);
24✔
5128
                /* If it was requested explicitly and we can't set it up, fail early. Otherwise, continue and let
5129
                 * the actual requested operations fail (or silently continue). */
5130
                if (r < 0 && context->private_users != PRIVATE_USERS_NO) {
24✔
5131
                        *exit_status = EXIT_USER;
×
5132
                        return log_exec_error_errno(context, params, r, "Failed to set up user namespacing for unprivileged user: %m");
×
5133
                }
5134
                if (r < 0)
×
5135
                        log_exec_info_errno(context, params, r, "Failed to set up user namespacing for unprivileged user, ignoring: %m");
×
5136
                else {
5137
                        assert(r > 0);
24✔
5138
                        userns_set_up = true;
5139
                }
5140
        }
5141

5142
        if (exec_needs_network_namespace(context) && runtime && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
11,086✔
5143

5144
                /* Try to enable network namespacing if network namespacing is available and we have
5145
                 * CAP_NET_ADMIN. We need CAP_NET_ADMIN to be able to configure the loopback device in the
5146
                 * new network namespace. And if we don't have that, then we could only create a network
5147
                 * namespace without the ability to set up "lo". Hence gracefully skip things then. */
5148
                if (ns_type_supported(NAMESPACE_NET) && have_effective_cap(CAP_NET_ADMIN) > 0) {
299✔
5149
                        r = setup_shareable_ns(runtime->shared->netns_storage_socket, CLONE_NEWNET);
299✔
5150
                        if (ERRNO_IS_NEG_PRIVILEGE(r))
299✔
5151
                                log_exec_notice_errno(context, params, r,
×
5152
                                                      "PrivateNetwork=yes is configured, but network namespace setup not permitted, proceeding without: %m");
5153
                        else if (r < 0) {
299✔
5154
                                *exit_status = EXIT_NETWORK;
×
5155
                                return log_exec_error_errno(context, params, r, "Failed to set up network namespacing: %m");
×
5156
                        }
5157
                } else if (context->network_namespace_path) {
×
5158
                        *exit_status = EXIT_NETWORK;
×
5159
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EOPNOTSUPP),
×
5160
                                                    "NetworkNamespacePath= is not supported, refusing.");
5161
                } else
5162
                        log_exec_notice(context, params, "PrivateNetwork=yes is configured, but the kernel does not support or we lack privileges for network namespace, proceeding without.");
×
5163
        }
5164

5165
        if (exec_needs_ipc_namespace(context) && runtime && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
11,086✔
5166

5167
                if (ns_type_supported(NAMESPACE_IPC)) {
2✔
5168
                        r = setup_shareable_ns(runtime->shared->ipcns_storage_socket, CLONE_NEWIPC);
2✔
5169
                        if (ERRNO_IS_NEG_PRIVILEGE(r))
2✔
5170
                                log_exec_warning_errno(context, params, r,
×
5171
                                                       "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m");
5172
                        else if (r < 0) {
2✔
5173
                                *exit_status = EXIT_NAMESPACE;
×
5174
                                return log_exec_error_errno(context, params, r, "Failed to set up IPC namespacing: %m");
×
5175
                        }
5176
                } else if (context->ipc_namespace_path) {
×
5177
                        *exit_status = EXIT_NAMESPACE;
×
5178
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EOPNOTSUPP),
×
5179
                                                    "IPCNamespacePath= is not supported, refusing.");
5180
                } else
5181
                        log_exec_warning(context, params, "PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring.");
×
5182
        }
5183

5184
        if (needs_sandboxing && exec_needs_cgroup_namespace(context, params)) {
11,086✔
5185
                r = unshare(CLONE_NEWCGROUP);
9✔
5186
                if (r < 0) {
9✔
5187
                        *exit_status = EXIT_NAMESPACE;
×
5188
                        return log_exec_error_errno(context, params, r, "Failed to set up cgroup namespacing: %m");
×
5189
                }
5190
        }
5191

5192
        /* Unshare a new PID namespace before setting up mounts to ensure /proc/ is mounted with only processes in PID namespace visible.
5193
         * Note PrivatePIDs=yes implies MountAPIVFS=yes so we'll always ensure procfs is remounted. */
5194
        if (needs_sandboxing && exec_needs_pid_namespace(context)) {
11,086✔
5195
                if (params->pidref_transport_fd < 0) {
10✔
5196
                        *exit_status = EXIT_NAMESPACE;
×
5197
                        return log_exec_error_errno(context, params, r, "PidRef socket is not set up: %m");
×
5198
                }
5199

5200
                /* If we had CAP_SYS_ADMIN prior to joining the user namespace, then we are privileged and don't need
5201
                 * to check if we can mount /proc/.
5202
                 *
5203
                 * We need to check prior to entering the user namespace because if we're running unprivileged or in a
5204
                 * system without CAP_SYS_ADMIN, then we can have CAP_SYS_ADMIN in the current user namespace but not
5205
                 * once we unshare a mount namespace. */
5206
                r = has_cap_sys_admin ? 1 : can_mount_proc(context, params);
10✔
5207
                if (r < 0) {
3✔
5208
                        *exit_status = EXIT_NAMESPACE;
×
5209
                        return log_exec_error_errno(context, params, r, "Failed to detect if /proc/ can be remounted: %m");
×
5210
                }
5211
                if (r == 0) {
8✔
5212
                        *exit_status = EXIT_NAMESPACE;
1✔
5213
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EPERM),
1✔
5214
                                                    "PrivatePIDs=yes is configured, but /proc/ cannot be re-mounted due to lack of privileges, refusing.");
5215
                }
5216

5217
                r = setup_private_pids(context, params);
7✔
5218
                if (r < 0) {
6✔
5219
                        *exit_status = EXIT_NAMESPACE;
×
5220
                        return log_exec_error_errno(context, params, r, "Failed to set up pid namespace: %m");
×
5221
                }
5222
        }
5223

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

5226
        if (needs_mount_namespace) {
11,082✔
5227
                _cleanup_free_ char *error_path = NULL;
2,553✔
5228

5229
                r = apply_mount_namespace(command->flags,
2,553✔
5230
                                          context,
5231
                                          params,
5232
                                          runtime,
5233
                                          memory_pressure_path,
5234
                                          needs_sandboxing,
5235
                                          &error_path,
5236
                                          uid,
5237
                                          gid);
5238
                if (r < 0) {
2,553✔
5239
                        *exit_status = EXIT_NAMESPACE;
15✔
5240
                        return log_exec_error_errno(context, params, r, "Failed to set up mount namespacing%s%s: %m",
59✔
5241
                                                    error_path ? ": " : "", strempty(error_path));
5242
                }
5243
        }
5244

5245
        if (needs_sandboxing) {
11,067✔
5246
                r = apply_protect_hostname(context, params, exit_status);
11,067✔
5247
                if (r < 0)
11,067✔
5248
                        return r;
5249
        }
5250

5251
        if (context->memory_ksm >= 0)
11,067✔
5252
                if (prctl(PR_SET_MEMORY_MERGE, context->memory_ksm, 0, 0, 0) < 0) {
×
5253
                        if (ERRNO_IS_NOT_SUPPORTED(errno))
×
5254
                                log_exec_debug_errno(context,
×
5255
                                                     params,
5256
                                                     errno,
5257
                                                     "KSM support not available, ignoring.");
5258
                        else {
5259
                                *exit_status = EXIT_KSM;
×
5260
                                return log_exec_error_errno(context, params, errno, "Failed to set KSM: %m");
×
5261
                        }
5262
                }
5263

5264
        /* Drop groups as early as possible.
5265
         * This needs to be done after PrivateDevices=yes setup as device nodes should be owned by the host's root.
5266
         * For non-root in a userns, devices will be owned by the user/group before the group change, and nobody. */
5267
        if (needs_setuid) {
11,067✔
5268
                _cleanup_free_ gid_t *gids_to_enforce = NULL;
11,067✔
5269
                int ngids_to_enforce = 0;
11,067✔
5270

5271
                ngids_to_enforce = merge_gid_lists(supplementary_gids,
11,067✔
5272
                                                   ngids,
5273
                                                   gids_after_pam,
5274
                                                   ngids_after_pam,
5275
                                                   &gids_to_enforce);
5276
                if (ngids_to_enforce < 0) {
11,067✔
5277
                        *exit_status = EXIT_GROUP;
×
5278
                        return log_exec_error_errno(context, params,
×
5279
                                                    ngids_to_enforce,
5280
                                                    "Failed to merge group lists. Group membership might be incorrect: %m");
5281
                }
5282

5283
                r = enforce_groups(gid, gids_to_enforce, ngids_to_enforce);
11,067✔
5284
                if (r < 0) {
11,067✔
5285
                        *exit_status = EXIT_GROUP;
1✔
5286
                        return log_exec_error_errno(context, params, r, "Changing group credentials failed: %m");
1✔
5287
                }
5288
        }
5289

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

5296
        if (needs_sandboxing && !userns_set_up) {
11,066✔
5297
                r = setup_private_users(context->private_users, saved_uid, saved_gid, uid, gid,
22,092✔
5298
                                        /* allow_setgroups= */ context->private_users == PRIVATE_USERS_FULL);
11,046✔
5299
                if (r < 0) {
11,046✔
5300
                        *exit_status = EXIT_USER;
×
5301
                        return log_exec_error_errno(context, params, r, "Failed to set up user namespacing: %m");
×
5302
                }
5303
        }
5304

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

5308
        _cleanup_free_ char *executable = NULL;
5✔
5309
        _cleanup_close_ int executable_fd = -EBADF;
5✔
5310
        r = find_executable_full(command->path, /* root= */ NULL, context->exec_search_path, false, &executable, &executable_fd);
11,066✔
5311
        if (r < 0) {
11,066✔
5312
                *exit_status = EXIT_EXEC;
1✔
5313
                log_exec_struct_errno(context, params, LOG_NOTICE, r,
3✔
5314
                                      "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
5315
                                      LOG_EXEC_MESSAGE(params,
5316
                                                       "Unable to locate executable '%s': %m",
5317
                                                       command->path),
5318
                                      "EXECUTABLE=%s", command->path);
5319
                /* If the error will be ignored by manager, tune down the log level here. Missing executable
5320
                 * is very much expected in this case. */
5321
                return r != -ENOMEM && FLAGS_SET(command->flags, EXEC_COMMAND_IGNORE_FAILURE) ? 1 : r;
1✔
5322
        }
5323

5324
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &executable_fd);
11,065✔
5325
        if (r < 0) {
11,065✔
5326
                *exit_status = EXIT_FDS;
×
5327
                return log_exec_error_errno(context, params, r, "Failed to collect shifted fd: %m");
×
5328
        }
5329

5330
#if HAVE_SELINUX
5331
        if (needs_sandboxing && use_selinux && params->selinux_context_net) {
5332
                int fd = -EBADF;
5333

5334
                if (socket_fd >= 0)
5335
                        fd = socket_fd;
5336
                else if (params->n_socket_fds == 1)
5337
                        /* If stdin is not connected to a socket but we are triggered by exactly one socket unit then we
5338
                         * use context from that fd to compute the label. */
5339
                        fd = params->fds[0];
5340

5341
                if (fd >= 0) {
5342
                        r = mac_selinux_get_child_mls_label(fd, executable, context->selinux_context, &mac_selinux_context_net);
5343
                        if (r < 0) {
5344
                                if (!context->selinux_context_ignore) {
5345
                                        *exit_status = EXIT_SELINUX_CONTEXT;
5346
                                        return log_exec_error_errno(context,
5347
                                                                    params,
5348
                                                                    r,
5349
                                                                    "Failed to determine SELinux context: %m");
5350
                                }
5351
                                log_exec_debug_errno(context,
5352
                                                     params,
5353
                                                     r,
5354
                                                     "Failed to determine SELinux context, ignoring: %m");
5355
                        }
5356
                }
5357
        }
5358
#endif
5359

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

5366
        exec_runtime_close(runtime);
11,065✔
5367
        exec_params_close(params);
11,065✔
5368

5369
        r = close_all_fds(keep_fds, n_keep_fds);
11,065✔
5370
        if (r >= 0)
11,065✔
5371
                r = pack_fds(params->fds, n_fds);
11,065✔
5372
        if (r >= 0)
11,065✔
5373
                r = flag_fds(params->fds, n_socket_fds, n_fds, context->non_blocking);
11,065✔
5374
        if (r < 0) {
11,065✔
5375
                *exit_status = EXIT_FDS;
×
5376
                return log_exec_error_errno(context, params, r, "Failed to adjust passed file descriptors: %m");
×
5377
        }
5378

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

5384
        secure_bits = context->secure_bits;
11,065✔
5385

5386
        if (needs_sandboxing) {
11,065✔
5387
                uint64_t bset;
11,065✔
5388

5389
                /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested.
5390
                 * (Note this is placed after the general resource limit initialization, see above, in order
5391
                 * to take precedence.) */
5392
                if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
11,065✔
5393
                        if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
2,052✔
5394
                                *exit_status = EXIT_LIMITS;
×
5395
                                return log_exec_error_errno(context, params, errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m");
×
5396
                        }
5397
                }
5398

5399
#if ENABLE_SMACK
5400
                /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the
5401
                 * process. This is the latest place before dropping capabilities. Other MAC context are set later. */
5402
                if (use_smack) {
11,065✔
5403
                        r = setup_smack(params, context, executable_fd);
×
5404
                        if (r < 0 && !context->smack_process_label_ignore) {
×
5405
                                *exit_status = EXIT_SMACK_PROCESS_LABEL;
×
5406
                                return log_exec_error_errno(context, params, r, "Failed to set SMACK process label: %m");
×
5407
                        }
5408
                }
5409
#endif
5410

5411
                bset = context->capability_bounding_set;
11,065✔
5412

5413
#if HAVE_SECCOMP
5414
                /* If the service has any form of a seccomp filter and it allows dropping privileges, we'll
5415
                 * keep the needed privileges to apply it even if we're not root. */
5416
                if (needs_setuid &&
22,130✔
5417
                    uid_is_valid(uid) &&
13,069✔
5418
                    context_has_seccomp(context) &&
2,852✔
5419
                    seccomp_allows_drop_privileges(context)) {
848✔
5420
                        keep_seccomp_privileges = true;
848✔
5421

5422
                        if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
848✔
5423
                                *exit_status = EXIT_USER;
×
5424
                                return log_exec_error_errno(context, params, errno, "Failed to enable keep capabilities flag: %m");
×
5425
                        }
5426

5427
                        /* Save the current bounding set so we can restore it after applying the seccomp
5428
                         * filter */
5429
                        saved_bset = bset;
848✔
5430
                        bset |= (UINT64_C(1) << CAP_SYS_ADMIN) |
848✔
5431
                                (UINT64_C(1) << CAP_SETPCAP);
5432
                }
5433
#endif
5434

5435
                if (!cap_test_all(bset)) {
11,065✔
5436
                        r = capability_bounding_set_drop(bset, /* right_now= */ false);
2,232✔
5437
                        if (r < 0) {
2,232✔
5438
                                *exit_status = EXIT_CAPABILITIES;
×
5439
                                return log_exec_error_errno(context, params, r, "Failed to drop capabilities: %m");
×
5440
                        }
5441
                }
5442

5443
                /* Ambient capabilities are cleared during setresuid() (in enforce_user()) even with
5444
                 * keep-caps set.
5445
                 *
5446
                 * To be able to raise the ambient capabilities after setresuid() they have to be added to
5447
                 * the inherited set and keep caps has to be set (done in enforce_user()).  After setresuid()
5448
                 * the ambient capabilities can be raised as they are present in the permitted and
5449
                 * inhertiable set. However it is possible that someone wants to set ambient capabilities
5450
                 * without changing the user, so we also set the ambient capabilities here.
5451
                 *
5452
                 * The requested ambient capabilities are raised in the inheritable set if the second
5453
                 * argument is true. */
5454
                if (capability_ambient_set != 0) {
11,065✔
5455
                        r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ true);
844✔
5456
                        if (r < 0) {
844✔
5457
                                *exit_status = EXIT_CAPABILITIES;
×
5458
                                return log_exec_error_errno(context, params, r, "Failed to apply ambient capabilities (before UID change): %m");
×
5459
                        }
5460
                }
5461
        }
5462

5463
        /* chroot to root directory first, before we lose the ability to chroot */
5464
        r = apply_root_directory(context, params, runtime, needs_mount_namespace, exit_status);
11,065✔
5465
        if (r < 0)
11,065✔
5466
                return log_exec_error_errno(context, params, r, "Chrooting to the requested root directory failed: %m");
×
5467

5468
        if (needs_setuid) {
11,065✔
5469
                if (uid_is_valid(uid)) {
11,065✔
5470
                        r = enforce_user(context, uid, capability_ambient_set);
2,004✔
5471
                        if (r < 0) {
2,004✔
5472
                                *exit_status = EXIT_USER;
×
5473
                                return log_exec_error_errno(context, params, r, "Failed to change UID to " UID_FMT ": %m", uid);
×
5474
                        }
5475

5476
                        if (keep_seccomp_privileges) {
2,004✔
5477
                                if (!BIT_SET(capability_ambient_set, CAP_SETUID)) {
848✔
5478
                                        r = drop_capability(CAP_SETUID);
848✔
5479
                                        if (r < 0) {
848✔
5480
                                                *exit_status = EXIT_USER;
×
5481
                                                return log_exec_error_errno(context, params, r, "Failed to drop CAP_SETUID: %m");
×
5482
                                        }
5483
                                }
5484

5485
                                r = keep_capability(CAP_SYS_ADMIN);
848✔
5486
                                if (r < 0) {
848✔
5487
                                        *exit_status = EXIT_USER;
×
5488
                                        return log_exec_error_errno(context, params, r, "Failed to keep CAP_SYS_ADMIN: %m");
×
5489
                                }
5490

5491
                                r = keep_capability(CAP_SETPCAP);
848✔
5492
                                if (r < 0) {
848✔
5493
                                        *exit_status = EXIT_USER;
×
5494
                                        return log_exec_error_errno(context, params, r, "Failed to keep CAP_SETPCAP: %m");
×
5495
                                }
5496
                        }
5497

5498
                        if (capability_ambient_set != 0) {
2,004✔
5499

5500
                                /* Raise the ambient capabilities after user change. */
5501
                                r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ false);
843✔
5502
                                if (r < 0) {
843✔
5503
                                        *exit_status = EXIT_CAPABILITIES;
×
5504
                                        return log_exec_error_errno(context, params, r, "Failed to apply ambient capabilities (after UID change): %m");
×
5505
                                }
5506
                        }
5507
                }
5508
        }
5509

5510
        /* Apply working directory here, because the working directory might be on NFS and only the user
5511
         * running this service might have the correct privilege to change to the working directory. Also, it
5512
         * is absolutely 💣 crucial 💣 we applied all mount namespacing rearrangements before this, so that
5513
         * the cwd cannot be used to pin directories outside of the sandbox. */
5514
        r = apply_working_directory(context, params, runtime, pwent_home, accum_env);
11,065✔
5515
        if (r < 0) {
11,065✔
5516
                *exit_status = EXIT_CHDIR;
1✔
5517
                return log_exec_error_errno(context, params, r, "Changing to the requested working directory failed: %m");
3✔
5518
        }
5519

5520
        if (needs_sandboxing) {
11,064✔
5521
                /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to
5522
                 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
5523
                 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
5524
                 * are restricted. */
5525

5526
#if HAVE_SELINUX
5527
                if (use_selinux) {
5528
                        char *exec_context = mac_selinux_context_net ?: context->selinux_context;
5529

5530
                        if (exec_context) {
5531
                                r = setexeccon(exec_context);
5532
                                if (r < 0) {
5533
                                        if (!context->selinux_context_ignore) {
5534
                                                *exit_status = EXIT_SELINUX_CONTEXT;
5535
                                                return log_exec_error_errno(context, params, r, "Failed to change SELinux context to %s: %m", exec_context);
5536
                                        }
5537
                                        log_exec_debug_errno(context,
5538
                                                             params,
5539
                                                             r,
5540
                                                             "Failed to change SELinux context to %s, ignoring: %m",
5541
                                                             exec_context);
5542
                                }
5543
                        }
5544
                }
5545
#endif
5546

5547
#if HAVE_APPARMOR
5548
                if (use_apparmor && context->apparmor_profile) {
5549
                        r = ASSERT_PTR(sym_aa_change_onexec)(context->apparmor_profile);
5550
                        if (r < 0 && !context->apparmor_profile_ignore) {
5551
                                *exit_status = EXIT_APPARMOR_PROFILE;
5552
                                return log_exec_error_errno(context,
5553
                                                            params,
5554
                                                            errno,
5555
                                                            "Failed to prepare AppArmor profile change to %s: %m",
5556
                                                            context->apparmor_profile);
5557
                        }
5558
                }
5559
#endif
5560

5561
                /* PR_GET_SECUREBITS is not privileged, while PR_SET_SECUREBITS is. So to suppress potential
5562
                 * EPERMs we'll try not to call PR_SET_SECUREBITS unless necessary. Setting securebits
5563
                 * requires CAP_SETPCAP. */
5564
                if (prctl(PR_GET_SECUREBITS) != secure_bits) {
11,064✔
5565
                        /* CAP_SETPCAP is required to set securebits. This capability is raised into the
5566
                         * effective set here.
5567
                         *
5568
                         * The effective set is overwritten during execve() with the following values:
5569
                         *
5570
                         * - ambient set (for non-root processes)
5571
                         *
5572
                         * - (inheritable | bounding) set for root processes)
5573
                         *
5574
                         * Hence there is no security impact to raise it in the effective set before execve
5575
                         */
5576
                        r = capability_gain_cap_setpcap(/* ret_before_caps = */ NULL);
901✔
5577
                        if (r < 0) {
901✔
5578
                                *exit_status = EXIT_CAPABILITIES;
×
5579
                                return log_exec_error_errno(context, params, r, "Failed to gain CAP_SETPCAP for setting secure bits");
×
5580
                        }
5581
                        if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
901✔
5582
                                *exit_status = EXIT_SECUREBITS;
×
5583
                                return log_exec_error_errno(context, params, errno, "Failed to set process secure bits: %m");
×
5584
                        }
5585
                }
5586

5587
                if (context_has_no_new_privileges(context))
11,064✔
5588
                        if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
1,926✔
5589
                                *exit_status = EXIT_NO_NEW_PRIVILEGES;
×
5590
                                return log_exec_error_errno(context, params, errno, "Failed to disable new privileges: %m");
×
5591
                        }
5592

5593
#if HAVE_SECCOMP
5594
                r = apply_address_families(context, params);
11,064✔
5595
                if (r < 0) {
11,064✔
5596
                        *exit_status = EXIT_ADDRESS_FAMILIES;
×
5597
                        return log_exec_error_errno(context, params, r, "Failed to restrict address families: %m");
×
5598
                }
5599

5600
                r = apply_memory_deny_write_execute(context, params);
11,064✔
5601
                if (r < 0) {
11,064✔
5602
                        *exit_status = EXIT_SECCOMP;
×
5603
                        return log_exec_error_errno(context, params, r, "Failed to disable writing to executable memory: %m");
×
5604
                }
5605

5606
                r = apply_restrict_realtime(context, params);
11,064✔
5607
                if (r < 0) {
11,064✔
5608
                        *exit_status = EXIT_SECCOMP;
×
5609
                        return log_exec_error_errno(context, params, r, "Failed to apply realtime restrictions: %m");
×
5610
                }
5611

5612
                r = apply_restrict_suid_sgid(context, params);
11,064✔
5613
                if (r < 0) {
11,064✔
5614
                        *exit_status = EXIT_SECCOMP;
×
5615
                        return log_exec_error_errno(context, params, r, "Failed to apply SUID/SGID restrictions: %m");
×
5616
                }
5617

5618
                r = apply_restrict_namespaces(context, params);
11,064✔
5619
                if (r < 0) {
11,064✔
5620
                        *exit_status = EXIT_SECCOMP;
×
5621
                        return log_exec_error_errno(context, params, r, "Failed to apply namespace restrictions: %m");
×
5622
                }
5623

5624
                r = apply_protect_sysctl(context, params);
11,064✔
5625
                if (r < 0) {
11,064✔
5626
                        *exit_status = EXIT_SECCOMP;
×
5627
                        return log_exec_error_errno(context, params, r, "Failed to apply sysctl restrictions: %m");
×
5628
                }
5629

5630
                r = apply_protect_kernel_modules(context, params);
11,064✔
5631
                if (r < 0) {
11,064✔
5632
                        *exit_status = EXIT_SECCOMP;
×
5633
                        return log_exec_error_errno(context, params, r, "Failed to apply module loading restrictions: %m");
×
5634
                }
5635

5636
                r = apply_protect_kernel_logs(context, params);
11,064✔
5637
                if (r < 0) {
11,064✔
5638
                        *exit_status = EXIT_SECCOMP;
×
5639
                        return log_exec_error_errno(context, params, r, "Failed to apply kernel log restrictions: %m");
×
5640
                }
5641

5642
                r = apply_protect_clock(context, params);
11,064✔
5643
                if (r < 0) {
11,064✔
5644
                        *exit_status = EXIT_SECCOMP;
×
5645
                        return log_exec_error_errno(context, params, r, "Failed to apply clock restrictions: %m");
×
5646
                }
5647

5648
                r = apply_private_devices(context, params);
11,064✔
5649
                if (r < 0) {
11,064✔
5650
                        *exit_status = EXIT_SECCOMP;
×
5651
                        return log_exec_error_errno(context, params, r, "Failed to set up private devices: %m");
×
5652
                }
5653

5654
                r = apply_syscall_archs(context, params);
11,064✔
5655
                if (r < 0) {
11,064✔
5656
                        *exit_status = EXIT_SECCOMP;
×
5657
                        return log_exec_error_errno(context, params, r, "Failed to apply syscall architecture restrictions: %m");
×
5658
                }
5659

5660
                r = apply_lock_personality(context, params);
11,064✔
5661
                if (r < 0) {
11,064✔
5662
                        *exit_status = EXIT_SECCOMP;
×
5663
                        return log_exec_error_errno(context, params, r, "Failed to lock personalities: %m");
×
5664
                }
5665

5666
                r = apply_syscall_log(context, params);
11,064✔
5667
                if (r < 0) {
11,064✔
5668
                        *exit_status = EXIT_SECCOMP;
×
5669
                        return log_exec_error_errno(context, params, r, "Failed to apply system call log filters: %m");
×
5670
                }
5671
#endif
5672

5673
#if HAVE_LIBBPF
5674
                r = apply_restrict_filesystems(context, params);
11,064✔
5675
                if (r < 0) {
11,064✔
5676
                        *exit_status = EXIT_BPF;
×
5677
                        return log_exec_error_errno(context, params, r, "Failed to restrict filesystems: %m");
×
5678
                }
5679
#endif
5680

5681
#if HAVE_SECCOMP
5682
                /* This really should remain as close to the execve() as possible, to make sure our own code is affected
5683
                 * by the filter as little as possible. */
5684
                r = apply_syscall_filter(context, params);
11,064✔
5685
                if (r < 0) {
11,064✔
5686
                        *exit_status = EXIT_SECCOMP;
×
5687
                        return log_exec_error_errno(context, params, r, "Failed to apply system call filters: %m");
×
5688
                }
5689

5690
                if (keep_seccomp_privileges) {
11,064✔
5691
                        /* Restore the capability bounding set with what's expected from the service + the
5692
                         * ambient capabilities hack */
5693
                        if (!cap_test_all(saved_bset)) {
847✔
5694
                                r = capability_bounding_set_drop(saved_bset, /* right_now= */ false);
812✔
5695
                                if (r < 0) {
812✔
5696
                                        *exit_status = EXIT_CAPABILITIES;
×
5697
                                        return log_exec_error_errno(context, params, r, "Failed to drop bset capabilities: %m");
×
5698
                                }
5699
                        }
5700

5701
                        /* Only drop CAP_SYS_ADMIN if it's not in the bounding set, otherwise we'll break
5702
                         * applications that use it. */
5703
                        if (!BIT_SET(saved_bset, CAP_SYS_ADMIN)) {
847✔
5704
                                r = drop_capability(CAP_SYS_ADMIN);
384✔
5705
                                if (r < 0) {
384✔
5706
                                        *exit_status = EXIT_USER;
×
5707
                                        return log_exec_error_errno(context, params, r, "Failed to drop CAP_SYS_ADMIN: %m");
×
5708
                                }
5709
                        }
5710

5711
                        /* Only drop CAP_SETPCAP if it's not in the bounding set, otherwise we'll break
5712
                         * applications that use it. */
5713
                        if (!BIT_SET(saved_bset, CAP_SETPCAP)) {
847✔
5714
                                r = drop_capability(CAP_SETPCAP);
582✔
5715
                                if (r < 0) {
582✔
5716
                                        *exit_status = EXIT_USER;
×
5717
                                        return log_exec_error_errno(context, params, r, "Failed to drop CAP_SETPCAP: %m");
×
5718
                                }
5719
                        }
5720

5721
                        if (prctl(PR_SET_KEEPCAPS, 0) < 0) {
847✔
5722
                                *exit_status = EXIT_USER;
×
5723
                                return log_exec_error_errno(context, params, errno, "Failed to drop keep capabilities flag: %m");
×
5724
                        }
5725
                }
5726
#endif
5727

5728
        }
5729

5730
        if (!strv_isempty(context->unset_environment)) {
11,064✔
5731
                char **ee = NULL;
44✔
5732

5733
                ee = strv_env_delete(accum_env, 1, context->unset_environment);
44✔
5734
                if (!ee) {
44✔
5735
                        *exit_status = EXIT_MEMORY;
×
5736
                        return log_oom();
5✔
5737
                }
5738

5739
                strv_free_and_replace(accum_env, ee);
44✔
5740
        }
5741

5742
        if (!FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) {
11,064✔
5743
                _cleanup_strv_free_ char **unset_variables = NULL, **bad_variables = NULL;
10,938✔
5744

5745
                r = replace_env_argv(command->argv, accum_env, &replaced_argv, &unset_variables, &bad_variables);
10,938✔
5746
                if (r < 0) {
10,938✔
5747
                        *exit_status = EXIT_MEMORY;
×
5748
                        return log_exec_error_errno(context,
×
5749
                                                    params,
5750
                                                    r,
5751
                                                    "Failed to replace environment variables: %m");
5752
                }
5753
                final_argv = replaced_argv;
10,938✔
5754

5755
                if (!strv_isempty(unset_variables)) {
10,938✔
5756
                        _cleanup_free_ char *ju = strv_join(unset_variables, ", ");
10✔
5757
                        log_exec_warning(context,
15✔
5758
                                         params,
5759
                                         "Referenced but unset environment variable evaluates to an empty string: %s",
5760
                                         strna(ju));
5761
                }
5762

5763
                if (!strv_isempty(bad_variables)) {
10,938✔
5764
                        _cleanup_free_ char *jb = strv_join(bad_variables, ", ");
×
5765
                        log_exec_warning(context,
×
5766
                                         params,
5767
                                         "Invalid environment variable name evaluates to an empty string: %s",
5768
                                         strna(jb));
5769
                }
5770
        } else
5771
                final_argv = command->argv;
126✔
5772

5773
        log_command_line(context, params, "Executing", executable, final_argv);
11,064✔
5774

5775
        /* We have finished with all our initializations. Let's now let the manager know that. From this
5776
         * point on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */
5777

5778
        r = exec_fd_mark_hot(context, params, /* hot= */ true, exit_status);
11,064✔
5779
        if (r < 0)
11,064✔
5780
                return r;
5781

5782
        /* As last thing before the execve(), let's send the handoff timestamp */
5783
        r = send_handoff_timestamp(context, params, exit_status);
11,064✔
5784
        if (r < 0) {
11,064✔
5785
                /* If this handoff timestamp failed, let's undo the marking as hot */
5786
                (void) exec_fd_mark_hot(context, params, /* hot= */ false, /* reterr_exit_status= */ NULL);
×
5787
                return r;
5788
        }
5789

5790
        /* NB: we leave executable_fd, exec_fd, handoff_timestamp_fd open here. This is safe, because they
5791
         * have O_CLOEXEC set, and the execve() below will thus automatically close them. In fact, for
5792
         * exec_fd this is pretty much the whole raison d'etre. */
5793

5794
        r = fexecve_or_execve(executable_fd, executable, final_argv, accum_env);
11,064✔
5795

5796
        /* The execve() failed, let's undo the marking as hot */
5797
        (void) exec_fd_mark_hot(context, params, /* hot= */ false, /* reterr_exit_status= */ NULL);
3✔
5798

5799
        *exit_status = EXIT_EXEC;
3✔
5800
        return log_exec_error_errno(context, params, r, "Failed to execute %s: %m", executable);
9✔
5801
}
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