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

systemd / systemd / 13578340107

27 Feb 2025 09:12PM UTC coverage: 71.822% (+0.002%) from 71.82%
13578340107

push

github

web-flow
Issue OSC ANSI sequence whenever we change "context" of a TTY, i.e. acquire privs, enter container or VM or similar (#35224)

This is mostly a strawman to get a discussion going regarding how to
communicate to terminal emulators such as ptyxis about run0 (and nspawn,
and vmspawn, and moe) and what it does.

It's hierarchical and I think still relatively simple.

/cc @chergert

316 of 400 new or added lines in 18 files covered. (79.0%)

975 existing lines in 59 files now uncovered.

294628 of 410221 relevant lines covered (71.82%)

715614.58 hits per line

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

71.44
/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 "osc-context.h"
50
#include "proc-cmdline.h"
51
#include "process-util.h"
52
#include "psi-util.h"
53
#include "rlimit-util.h"
54
#include "seccomp-util.h"
55
#include "selinux-util.h"
56
#include "signal-util.h"
57
#include "smack-util.h"
58
#include "socket-util.h"
59
#include "string-table.h"
60
#include "strv.h"
61
#include "terminal-util.h"
62
#include "utmp-wtmp.h"
63
#include "vpick.h"
64

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

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

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

76
        int r;
11,087✔
77

78
        assert(fds || n_fds == 0);
11,087✔
79

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

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

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

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

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

100
        return 0;
101
}
102

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

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

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

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

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

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

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

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

137
        return !!c->tty_path;
10,671✔
138
}
139

140
static int open_null_as(int flags, int nfd) {
13,040✔
141
        int fd;
13,040✔
142

143
        assert(nfd >= 0);
13,040✔
144

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

149
        return move_fd(fd, nfd, false);
13,040✔
150
}
151

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

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

163
        assert(fd >= 0);
12,263✔
164

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

169
        if (gid_is_valid(gid)) {
12,263✔
170
                oldgid = getgid();
2,439✔
171

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

176
        if (uid_is_valid(uid)) {
12,263✔
177
                olduid = getuid();
2,436✔
178

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

185
        r = connect_unix_path(fd, AT_FDCWD, j);
12,263✔
186

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

190
        if (uid_is_valid(uid))
12,263✔
191
                (void) seteuid(olduid);
2,436✔
192

193
 restore_gid:
9,827✔
194
        if (gid_is_valid(gid))
12,263✔
195
                (void) setegid(oldgid);
2,439✔
196

197
        return r;
198
}
199

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

209
        _cleanup_close_ int fd = -EBADF;
12,263✔
210
        int r;
12,263✔
211

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

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

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

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

229
        (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
12,263✔
230

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

248
        return move_fd(TAKE_FD(fd), nfd, false);
12,263✔
249
}
250

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

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

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

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

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

268
        assert(path);
11✔
269

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

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

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

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

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

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

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

303
        return TAKE_FD(fd);
304
}
305

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

311
        ExecInput std_input;
39,132✔
312

313
        assert(context);
39,132✔
314

315
        std_input = context->std_input;
39,132✔
316

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

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

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

326
        return std_input;
327
}
328

329
static int fixup_output(ExecOutput output, int socket_fd) {
39,132✔
330

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

334
        return output;
335
}
336

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

343
        ExecInput i;
13,516✔
344
        int r;
13,516✔
345

346
        assert(context);
13,516✔
347
        assert(params);
13,516✔
348
        assert(named_iofds);
13,516✔
349

350
        if (params->stdin_fd >= 0) {
13,516✔
351
                if (dup2(params->stdin_fd, STDIN_FILENO) < 0)
472✔
352
                        return -errno;
×
353

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

358
                return STDIN_FILENO;
472✔
359
        }
360

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

363
        switch (i) {
13,044✔
364

365
        case EXEC_INPUT_NULL:
12,672✔
366
                return open_null_as(O_RDONLY, STDIN_FILENO);
12,672✔
367

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

374
                tty_path = ASSERT_PTR(exec_context_tty_path(context));
360✔
375

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

439
        assert(context);
13,044✔
440

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

444
        if (e == EXEC_OUTPUT_INHERIT)
13,044✔
445
                return true;
446
        if (e != o)
376✔
447
                return false;
448

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

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

455
        return true;
456
}
457

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

470
        ExecOutput o;
27,032✔
471
        ExecInput i;
27,032✔
472
        int r;
27,032✔
473

474
        assert(context);
27,032✔
475
        assert(params);
27,032✔
476
        assert(ident);
27,032✔
477
        assert(journal_stream_dev);
27,032✔
478
        assert(journal_stream_ino);
27,032✔
479

480
        if (fileno == STDOUT_FILENO && params->stdout_fd >= 0) {
27,032✔
481

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

485
                return STDOUT_FILENO;
486
        }
487

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

492
                return STDERR_FILENO;
493
        }
494

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

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

501
        if (fileno == STDERR_FILENO) {
26,088✔
502
                ExecOutput e;
13,044✔
503
                e = fixup_output(context->std_error, socket_fd);
13,044✔
504

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

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

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

520
                o = e;
521

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

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

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

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

539
        switch (o) {
13,043✔
540

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

544
        case EXEC_OUTPUT_TTY:
392✔
545
                if (is_terminal_input(i))
392✔
546
                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));
360✔
547

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

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

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

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

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

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

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

588
                (void) fd_nonblock(named_iofds[fileno], false);
×
589
                return RET_NERRNO(dup2(named_iofds[fileno], fileno));
27,032✔
590

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

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

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

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

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

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

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

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

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

626
        assert(fd >= 0);
2,704✔
627

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

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

637
        return 1;
638
}
639

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

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

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

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

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

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

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

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

NEW
672
        r = terminal_reset_defensive(fd, TERMINAL_RESET_SWITCH_TO_TEXT);
×
673
        if (r < 0)
×
674
                return r;
675

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

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

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

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

695
        errno = abs(err);
×
696

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

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

706
        assert(vc);
×
707

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

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

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

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

721
        release_terminal();
×
722

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

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

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

734
        return r;
×
735
}
736

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

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

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

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

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

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

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

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

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

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

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

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

851
        int r;
11,156✔
852

853
        assert(user_or_uid);
11,156✔
854
        assert(ret_username);
11,156✔
855

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

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

863
        return 0;
11,154✔
864
}
865

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

871
        int r;
9✔
872

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

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

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

883
        return 0;
9✔
884
}
885

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

895
        assert(c);
13,516✔
896

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

908
                keep_groups = true;
909
        }
910

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

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

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

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

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

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

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

949
                k++;
8✔
950
        }
951

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

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

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

969
        groups = NULL;
8✔
970

971
        return 0;
8✔
972
}
973

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

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

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

990
        return 0;
991
}
992

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

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

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

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

1009
        return 1;
1010
}
1011

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

1019
        if (!uid_is_valid(uid))
2,018✔
1020
                return 0;
1021

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

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

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

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

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

1045
#if HAVE_PAM
1046

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

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

1053
        free(responses);
×
1054
}
×
1055

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

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

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

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

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

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

1085
                switch (mi->msg_style) {
4✔
1086

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

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

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

1103
                                set_credential_env_var = true;
1✔
1104
                        }
1105

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

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

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

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

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

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

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

1151
        *ret = TAKE_PTR(responses);
4✔
1152
        n = 0;
4✔
1153

1154
        return PAM_SUCCESS;
4✔
1155
}
1156

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

1160
        assert(handle);
179✔
1161

1162
        r = pam_close_session(handle, flags);
179✔
1163
        if (r != PAM_SUCCESS)
179✔
1164
                log_debug("pam_close_session() failed: %s", pam_strerror(handle, r));
38✔
1165

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

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

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

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

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

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

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

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

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

1223
        if (log_get_max_level() < LOG_DEBUG)
321✔
1224
                flags |= PAM_SILENT;
2✔
1225

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

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

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

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

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

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

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

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

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

1267
        close_session = true;
321✔
1268

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

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

1277
        assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM) >= 0);
321✔
1278

1279
        parent_pid = getpid_cached();
321✔
1280

1281
        r = safe_fork("(sd-pam)", 0, NULL);
321✔
1282
        if (r < 0)
500✔
1283
                goto fail;
×
1284
        if (r == 0) {
500✔
1285
                int ret = EXIT_PAM;
179✔
1286

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

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

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

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

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

1307
                (void) ignore_signals(SIGPIPE);
179✔
1308

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

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

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

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

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

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

1340
                ret = 0;
1341

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

1349
        barrier_set_role(&barrier, BARRIER_PARENT);
321✔
1350

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

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

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

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

1367
        return strv_free_and_replace(*env, e);
321✔
1368

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

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

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

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

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

1394
        assert(path);
13,519✔
1395

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

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

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

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

1419
        (void) rename_process(process_name);
13,519✔
1420
}
1421

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

1425
        return c->address_families_allow_list ||
13,837✔
1426
                !set_isempty(c->address_families);
11,782✔
1427
}
1428

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

1432
        return c->syscall_allow_list ||
13,801✔
1433
                !hashmap_isempty(c->syscall_filter);
11,759✔
1434
}
1435

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

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

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

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

1465
        if (c->no_new_privileges)
11,086✔
1466
                return true;
1467

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

1471
        return context_has_seccomp(c);
1,545✔
1472
}
1473

1474
#if HAVE_SECCOMP
1475

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

1480
        assert(c);
848✔
1481

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

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

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

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

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

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

1507
        if (is_seccomp_available())
21,078✔
1508
                return false;
1509

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

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

1518
        assert(c);
11,086✔
1519
        assert(p);
11,086✔
1520

1521
        if (!context_has_syscall_filters(c))
11,086✔
1522
                return 0;
1523

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

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

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

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

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

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

1552
        assert(c);
11,086✔
1553
        assert(p);
11,086✔
1554

1555
        if (!context_has_syscall_logs(c))
11,086✔
1556
                return 0;
1557

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

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

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

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

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

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

1590
        return seccomp_restrict_archs(c->syscall_archs);
2,058✔
1591
}
1592

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

1597
        if (!context_has_address_families(c))
11,086✔
1598
                return 0;
1599

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

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

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

1609
        assert(c);
11,086✔
1610
        assert(p);
11,086✔
1611

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

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

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

1632
        return seccomp_memory_deny_write_execute();
×
1633
}
1634

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

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

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

1645
        return seccomp_restrict_realtime();
2,055✔
1646
}
1647

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

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

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

1658
        return seccomp_restrict_suid_sgid();
1,974✔
1659
}
1660

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

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

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

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

1674
        return seccomp_protect_sysctl();
717✔
1675
}
1676

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

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

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

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

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

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

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

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

1702
        return seccomp_protect_syslog();
1,587✔
1703
}
1704

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

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

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

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

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

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

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

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

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

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

1737
        if (!exec_context_restrict_namespaces_set(c))
11,086✔
1738
                return 0;
1739

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

1743
        return seccomp_restrict_namespaces(c->restrict_namespaces);
1,696✔
1744
}
1745

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

1750
        assert(c);
11,086✔
1751
        assert(p);
11,086✔
1752

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

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

1759
        personality = c->personality;
2,055✔
1760

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

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

1769
        return seccomp_lock_personality(personality);
2,055✔
1770
}
1771

1772
#endif
1773

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

1778
        assert(c);
11,086✔
1779
        assert(p);
11,086✔
1780

1781
        if (!exec_context_restrict_filesystems_set(c))
11,086✔
1782
                return 0;
1783

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

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

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

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

1802
        assert(c);
11,089✔
1803
        assert(p);
11,089✔
1804

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

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

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

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

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

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

1844
        return 0;
1845
}
1846

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

1850
        idle_pipe[1] = safe_close(idle_pipe[1]);
160✔
1851
        idle_pipe[2] = safe_close(idle_pipe[2]);
160✔
1852

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

1856
                r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
160✔
1857

1858
                if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
160✔
1859
                        ssize_t n;
114✔
1860

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

1868
                idle_pipe[0] = safe_close(idle_pipe[0]);
160✔
1869

1870
        }
1871

1872
        idle_pipe[3] = safe_close(idle_pipe[3]);
160✔
1873
}
160✔
1874

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

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

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

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

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

1908
        assert(c);
11,108✔
1909
        assert(p);
11,108✔
1910
        assert(ret);
11,108✔
1911

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

1917
        if (n_fds > 0) {
11,108✔
1918
                _cleanup_free_ char *joined = NULL;
1,575✔
1919

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

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

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

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

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

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

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

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

1971
        bool set_user_login_env = exec_context_get_set_login_environment(c);
11,108✔
1972

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

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

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

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

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

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

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

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

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

2015
                our_env[n_env++] = x;
11,108✔
2016
        }
2017

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

2022
                tty_path = exec_context_tty_path(c);
453✔
2023

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

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

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

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

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

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

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

2061
                our_env[n_env++] = x;
10,325✔
2062
        }
2063

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

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

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

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

2079
                if (c->directories[t].n_items == 0)
55,540✔
2080
                        continue;
52,848✔
2081

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

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

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

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

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

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

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

2113
                our_env[n_env++] = x;
2,398✔
2114
        }
2115

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

2119
        our_env[n_env++] = x;
11,108✔
2120

2121
        if (memory_pressure_path) {
11,108✔
2122
                x = strjoin("MEMORY_PRESSURE_WATCH=", memory_pressure_path);
10,752✔
2123
                if (!x)
10,752✔
2124
                        return -ENOMEM;
2125

2126
                our_env[n_env++] = x;
10,752✔
2127

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

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

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

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

2145
                        our_env[n_env++] = x;
10,752✔
2146
                }
2147
        }
2148

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

2154
                our_env[n_env++] = x;
2,458✔
2155
        }
2156

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

2160
        *ret = TAKE_PTR(our_env);
11,108✔
2161

2162
        return 0;
11,108✔
2163
}
2164

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

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

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

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

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

2187
        *ret = TAKE_PTR(pass_env);
11,108✔
2188

2189
        return 0;
11,108✔
2190
}
2191

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

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

2211
        if (private_users == PRIVATE_USERS_NO)
11,092✔
2212
                return 0;
2213

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

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

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

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

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

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

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

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

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

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

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

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

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

2345
                fd = safe_close(fd);
37✔
2346

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

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

2360
                _exit(EXIT_SUCCESS);
37✔
2361
        }
2362

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

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

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

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

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

2390
        return 1;
2391
}
2392

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

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

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

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

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

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

2428
                _exit(EXIT_SUCCESS);
2✔
2429
        }
2430

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

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

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

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

2455
        return 1;
2456
}
2457

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

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

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

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

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

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

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

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

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

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

2522
        assert(source);
1,630✔
2523

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

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

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

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

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

2544
        return 0;
2545
}
2546

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

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

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

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

2573
        if (params->flags & EXEC_CHOWN_DIRECTORIES) {
67,566✔
2574
                if (!uid_is_valid(uid))
64,376✔
2575
                        uid = 0;
50,856✔
2576
                if (!gid_is_valid(gid))
64,376✔
2577
                        gid = 0;
50,836✔
2578
        }
2579

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

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

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

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

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

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

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

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

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

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

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

2639
                                        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✔
2640
                                        continue;
1✔
2641
                                } else if (r != -ENOENT)
2✔
2642
                                        log_exec_warning_errno(context, params, r, "Unable to detect whether unit configuration directory '%s' exists, assuming not: %m", q);
×
2643

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2887
        return 0;
2888

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

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

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

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

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

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

2920
        return 0;
2921
}
2922
#endif
2923

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

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

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

2944
        CLEANUP_ARRAY(bind_mounts, h, bind_mount_free_many);
2,552✔
2945

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3055
        _cleanup_strv_free_ char **symlinks = NULL;
2,552✔
3056
        int r;
2,552✔
3057

3058
        assert(context);
2,552✔
3059
        assert(params);
2,552✔
3060
        assert(ret_symlinks);
2,552✔
3061

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

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

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

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

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

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

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

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

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

3110
        *ret_symlinks = TAKE_PTR(symlinks);
2,552✔
3111

3112
        return 0;
2,552✔
3113
}
3114

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

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

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

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

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

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

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

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

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

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

3153
        return false;
3154
}
3155

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

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

3167
        assert(context);
2,552✔
3168
        assert(root_image);
2,552✔
3169
        assert(root_directory);
2,552✔
3170

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

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

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

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

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

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

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

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

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

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

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

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

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

3237
        return 1;
3238
}
3239

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

3251
        int r;
7✔
3252

3253
        assert(verity);
7✔
3254

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

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

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

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

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

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

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

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

3293
        return 0;
3294
}
3295

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

3303
        int r;
2,554✔
3304

3305
        assert(context);
2,554✔
3306
        assert(params);
2,554✔
3307
        assert(ret_root_image);
2,554✔
3308
        assert(ret_root_directory);
2,554✔
3309

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

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

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

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

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

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

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

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

3358
        *ret_root_image = *ret_root_directory = NULL;
2,544✔
3359
        return 0;
2,544✔
3360
}
3361

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

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

3385
        assert(context);
2,554✔
3386

3387
        CLEANUP_ARRAY(bind_mounts, n_bind_mounts, bind_mount_free_many);
2,554✔
3388

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

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

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

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

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

3424
                read_write_paths = read_write_paths_cleanup;
1,594✔
3425
        } else
3426
                read_write_paths = context->read_write_paths;
958✔
3427

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

3433
                if (context->private_tmp == PRIVATE_TMP_CONNECTED && runtime && runtime->shared) {
2,552✔
3434
                        if (streq_ptr(runtime->shared->tmp_dir, RUN_SYSTEMD_EMPTY))
627✔
3435
                                tmp_dir = runtime->shared->tmp_dir;
3436
                        else if (runtime->shared->tmp_dir)
627✔
3437
                                tmp_dir = strjoina(runtime->shared->tmp_dir, "/tmp");
3,135✔
3438

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

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

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

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

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

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

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

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

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

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

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

3506
        NamespaceParameters parameters = {
×
3507
                .runtime_scope = params->runtime_scope,
2,552✔
3508

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

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

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

3521
                .empty_directories = empty_directories,
3522
                .symlinks = symlinks,
3523

3524
                .bind_mounts = bind_mounts,
3525
                .n_bind_mounts = n_bind_mounts,
3526

3527
                .temporary_filesystems = context->temporary_filesystems,
2,552✔
3528
                .n_temporary_filesystems = context->n_temporary_filesystems,
2,552✔
3529

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

3534
                .tmp_dir = tmp_dir,
3535
                .var_tmp_dir = var_tmp_dir,
3536

3537
                .creds_path = creds_path,
3538
                .log_namespace = context->log_namespace,
2,552✔
3539
                .mount_propagation_flag = context->mount_propagation_flag,
2,552✔
3540

3541
                .verity = &verity,
3542

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

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

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

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

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

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

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

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

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

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

3611
        return r;
3612
}
3613

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

3621
        const char *wd;
11,087✔
3622
        int r;
11,087✔
3623

3624
        assert(context);
11,087✔
3625

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

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

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

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

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

3662
        assert(context);
11,087✔
3663
        assert(exit_status);
11,087✔
3664

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

3672
        return 0;
3673
}
3674

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

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

3685
        assert(context);
11,108✔
3686
        assert(p);
11,108✔
3687

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

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

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

3703
        saved_uid = getuid();
10,334✔
3704
        saved_gid = getgid();
10,334✔
3705

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

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

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

3747
                goto out;
×
3748
        }
3749

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

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

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

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

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

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

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

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

3817
        return r;
3818
}
3819

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

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

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

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

3840
        assert(params);
13,518✔
3841

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

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

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

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

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

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

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

3877
        if (params->pidref_transport_fd >= 0)
13,518✔
3878
                dont_close[n_dont_close++] = params->pidref_transport_fd;
12,383✔
3879

3880
        assert(n_dont_close <= ELEMENTSOF(dont_close));
13,518✔
3881

3882
        return close_all_fds(dont_close, n_dont_close);
13,518✔
3883
}
3884

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

3891
        assert(unit_id);
13,516✔
3892

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

3897
        if (user_lookup_fd < 0)
13,516✔
3898
                return 0;
3899

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

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

3910
        return 0;
2,709✔
3911
}
3912

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

3916
        assert(c);
13,516✔
3917
        assert(home);
13,516✔
3918
        assert(ret_buf);
13,516✔
3919

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3979
        return 0;
61✔
3980
}
3981

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

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

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

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

3998
        cpu_set_reset(ret);
2✔
3999

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

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

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

4011
        if (*fd < 0)
51,641✔
4012
               return 0;
51,641✔
4013

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

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

4022
                close_and_replace(*fd, r);
11,087✔
4023
        }
4024

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4111
        return TAKE_FD(fd);
4112
}
4113

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

4119
        LIST_FOREACH(open_files, of, p->open_files) {
13,519✔
4120
                _cleanup_close_ int fd = -EBADF;
13,524✔
4121

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

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

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

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

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

4147
        return 0;
4148
}
4149

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

4157
        assert(context);
11,086✔
4158
        assert(params);
11,086✔
4159
        assert(msg);
11,086✔
4160
        assert(executable);
11,086✔
4161

4162
        if (!DEBUG_LOGGING)
11,086✔
4163
                return;
11,086✔
4164

4165
        _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);
21,570✔
4166

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

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

4177
        assert(context);
11,108✔
4178
        assert(params);
11,108✔
4179

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

4186
        return context->private_users != PRIVATE_USERS_NO ||
637✔
4187
               context->private_tmp != PRIVATE_TMP_NO ||
4188
               context->private_devices ||
634✔
4189
               context->private_network ||
629✔
4190
               context->network_namespace_path ||
629✔
4191
               context->private_ipc ||
629✔
4192
               context->ipc_namespace_path ||
629✔
4193
               context->private_mounts > 0 ||
629✔
4194
               context->mount_apivfs > 0 ||
629✔
4195
               context->bind_log_sockets > 0 ||
629✔
4196
               context->n_bind_mounts > 0 ||
629✔
4197
               context->n_temporary_filesystems > 0 ||
628✔
4198
               context->root_directory ||
628✔
4199
               !strv_isempty(context->extension_directories) ||
628✔
4200
               context->protect_system != PROTECT_SYSTEM_NO ||
628✔
4201
               context->protect_home != PROTECT_HOME_NO ||
625✔
4202
               exec_needs_pid_namespace(context) ||
625✔
4203
               context->protect_kernel_tunables ||
4204
               context->protect_kernel_modules ||
620✔
4205
               context->protect_kernel_logs ||
618✔
4206
               exec_needs_cgroup_mount(context, params) ||
618✔
4207
               context->protect_clock ||
618✔
4208
               context->protect_hostname != PROTECT_HOSTNAME_NO ||
617✔
4209
               !strv_isempty(context->read_write_paths) ||
616✔
4210
               !strv_isempty(context->read_only_paths) ||
613✔
4211
               !strv_isempty(context->inaccessible_paths) ||
613✔
4212
               !strv_isempty(context->exec_paths) ||
1,250✔
4213
               !strv_isempty(context->no_exec_paths);
637✔
4214
}
4215

4216
static bool exec_context_shall_confirm_spawn(const ExecContext *context) {
×
4217
        assert(context);
×
4218

4219
        if (confirm_spawn_disabled())
×
4220
                return false;
4221

4222
        /* For some reasons units remaining in the same process group
4223
         * as PID 1 fail to acquire the console even if it's not used
4224
         * by any process. So skip the confirmation question for them. */
4225
        return !context->same_pgrp;
×
4226
}
4227

4228
static int exec_context_named_iofds(
13,519✔
4229
                const ExecContext *c,
4230
                const ExecParameters *p,
4231
                int named_iofds[static 3]) {
4232

4233
        size_t targets;
13,519✔
4234
        const char* stdio_fdname[3];
13,519✔
4235
        size_t n_fds;
13,519✔
4236

4237
        assert(c);
13,519✔
4238
        assert(p);
13,519✔
4239
        assert(named_iofds);
13,519✔
4240

4241
        targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
13,519✔
4242
                  (c->std_output == EXEC_OUTPUT_NAMED_FD) +
13,519✔
4243
                  (c->std_error == EXEC_OUTPUT_NAMED_FD);
13,519✔
4244

4245
        for (size_t i = 0; i < 3; i++)
54,076✔
4246
                stdio_fdname[i] = exec_context_fdname(c, i);
40,557✔
4247

4248
        n_fds = p->n_storage_fds + p->n_socket_fds + p->n_extra_fds;
13,519✔
4249

4250
        for (size_t i = 0; i < n_fds  && targets > 0; i++)
13,519✔
4251
                if (named_iofds[STDIN_FILENO] < 0 &&
×
4252
                    c->std_input == EXEC_INPUT_NAMED_FD &&
×
4253
                    stdio_fdname[STDIN_FILENO] &&
×
4254
                    streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
×
4255

4256
                        named_iofds[STDIN_FILENO] = p->fds[i];
×
4257
                        targets--;
×
4258

4259
                } else if (named_iofds[STDOUT_FILENO] < 0 &&
×
4260
                           c->std_output == EXEC_OUTPUT_NAMED_FD &&
×
4261
                           stdio_fdname[STDOUT_FILENO] &&
×
4262
                           streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
×
4263

4264
                        named_iofds[STDOUT_FILENO] = p->fds[i];
×
4265
                        targets--;
×
4266

4267
                } else if (named_iofds[STDERR_FILENO] < 0 &&
×
4268
                           c->std_error == EXEC_OUTPUT_NAMED_FD &&
×
4269
                           stdio_fdname[STDERR_FILENO] &&
×
4270
                           streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
×
4271

4272
                        named_iofds[STDERR_FILENO] = p->fds[i];
×
4273
                        targets--;
×
4274
                }
4275

4276
        return targets == 0 ? 0 : -ENOENT;
13,519✔
4277
}
4278

4279
static void exec_shared_runtime_close(ExecSharedRuntime *shared) {
11,087✔
4280
        if (!shared)
11,087✔
4281
                return;
4282

4283
        safe_close_pair(shared->netns_storage_socket);
11,087✔
4284
        safe_close_pair(shared->ipcns_storage_socket);
11,087✔
4285
}
4286

4287
static void exec_runtime_close(ExecRuntime *rt) {
11,087✔
4288
        if (!rt)
11,087✔
4289
                return;
4290

4291
        safe_close_pair(rt->ephemeral_storage_socket);
11,087✔
4292

4293
        exec_shared_runtime_close(rt->shared);
11,087✔
4294
        dynamic_creds_close(rt->dynamic_creds);
11,087✔
4295
}
4296

4297
static void exec_params_close(ExecParameters *p) {
11,087✔
4298
        if (!p)
11,087✔
4299
                return;
4300

4301
        p->stdin_fd = safe_close(p->stdin_fd);
11,087✔
4302
        p->stdout_fd = safe_close(p->stdout_fd);
11,087✔
4303
        p->stderr_fd = safe_close(p->stderr_fd);
11,087✔
4304
}
4305

4306
static int exec_fd_mark_hot(
11,089✔
4307
                const ExecContext *c,
4308
                ExecParameters *p,
4309
                bool hot,
4310
                int *reterr_exit_status) {
4311

4312
        assert(c);
11,089✔
4313
        assert(p);
11,089✔
4314

4315
        if (p->exec_fd < 0)
11,089✔
4316
                return 0;
11,089✔
4317

4318
        uint8_t x = hot;
250✔
4319

4320
        if (write(p->exec_fd, &x, sizeof(x)) < 0) {
250✔
4321
                if (reterr_exit_status)
×
4322
                        *reterr_exit_status = EXIT_EXEC;
×
4323
                return log_exec_error_errno(c, p, errno, "Failed to mark exec_fd as %s: %m", hot ? "hot" : "cold");
×
4324
        }
4325

4326
        return 1;
4327
}
4328

4329
static int send_handoff_timestamp(
11,086✔
4330
                const ExecContext *c,
4331
                ExecParameters *p,
4332
                int *reterr_exit_status) {
4333

4334
        assert(c);
11,086✔
4335
        assert(p);
11,086✔
4336

4337
        if (p->handoff_timestamp_fd < 0)
11,086✔
4338
                return 0;
11,086✔
4339

4340
        dual_timestamp dt;
11,086✔
4341
        dual_timestamp_now(&dt);
11,086✔
4342

4343
        if (write(p->handoff_timestamp_fd, (const usec_t[2]) { dt.realtime, dt.monotonic }, sizeof(usec_t) * 2) < 0) {
11,086✔
4344
                if (reterr_exit_status)
×
4345
                        *reterr_exit_status = EXIT_EXEC;
×
4346
                return log_exec_error_errno(c, p, errno, "Failed to send handoff timestamp: %m");
×
4347
        }
4348

4349
        return 1;
11,086✔
4350
}
4351

4352
static void prepare_terminal(
13,516✔
4353
                const ExecContext *context,
4354
                ExecParameters *p) {
4355

4356
        _cleanup_close_ int lock_fd = -EBADF;
13,516✔
4357

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

4361
        assert(context);
13,516✔
4362
        assert(p);
13,516✔
4363

4364
        /* We only try to reset things if we there's the chance our stdout points to a TTY */
4365
        if (!(is_terminal_output(context->std_output) ||
13,516✔
4366
              (context->std_output == EXEC_OUTPUT_INHERIT && is_terminal_input(context->std_input)) ||
12,896✔
4367
              context->std_output == EXEC_OUTPUT_NAMED_FD ||
4368
              p->stdout_fd >= 0))
12,896✔
4369
                return;
12,424✔
4370

4371
        /* Let's explicitly determine whether to reset via ANSI sequences or not, taking our ExecContext
4372
         * information into account */
4373
        bool use_ansi = exec_context_shall_ansi_seq_reset(context);
1,092✔
4374

4375
        if (context->tty_reset) {
1,092✔
4376
                /* When we are resetting the TTY, then let's create a lock first, to synchronize access. This
4377
                 * in particular matters as concurrent resets and the TTY size ANSI DSR logic done by the
4378
                 * exec_context_apply_tty_size() below might interfere */
4379
                lock_fd = lock_dev_console();
163✔
4380
                if (lock_fd < 0)
163✔
4381
                        log_exec_debug_errno(context, p, lock_fd, "Failed to lock /dev/console, ignoring: %m");
×
4382

4383
                /* We explicitly control whether to send ansi sequences or not here, since we want to consult
4384
                 * the env vars explicitly configured in the ExecContext, rather than our own environment
4385
                 * block. */
4386
                (void) terminal_reset_defensive(STDOUT_FILENO, use_ansi ? TERMINAL_RESET_FORCE_ANSI_SEQ : TERMINAL_RESET_AVOID_ANSI_SEQ);
166✔
4387
        }
4388

4389
        (void) exec_context_apply_tty_size(context, STDIN_FILENO, STDOUT_FILENO, /* tty_path= */ NULL);
1,092✔
4390

4391
        if (use_ansi)
1,092✔
4392
                (void) osc_context_open_service(p->unit_id, p->invocation_id, /* ret_seq= */ NULL);
160✔
4393
}
4394

4395
int exec_invoke(
13,520✔
4396
                const ExecCommand *command,
4397
                const ExecContext *context,
4398
                ExecParameters *params,
4399
                ExecRuntime *runtime,
4400
                const CGroupContext *cgroup_context,
4401
                int *exit_status) {
13,520✔
4402

4403
        _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **joined_exec_search_path = NULL, **accum_env = NULL, **replaced_argv = NULL;
28✔
4404
        int r, ngids = 0;
13,520✔
4405
        _cleanup_free_ gid_t *supplementary_gids = NULL;
×
4406
        const char *username = NULL, *groupname = NULL;
13,520✔
4407
        _cleanup_free_ char *home_buffer = NULL, *memory_pressure_path = NULL, *own_user = NULL;
×
4408
        const char *pwent_home = NULL, *shell = NULL;
13,520✔
4409
        char **final_argv = NULL;
13,520✔
4410
        dev_t journal_stream_dev = 0;
13,520✔
4411
        ino_t journal_stream_ino = 0;
13,520✔
4412
        bool userns_set_up = false;
13,520✔
4413
        bool needs_sandboxing,          /* Do we need to set up full sandboxing? (i.e. all namespacing, all MAC stuff, caps, yadda yadda */
13,520✔
4414
                needs_setuid,           /* Do we need to do the actual setresuid()/setresgid() calls? */
4415
                needs_mount_namespace;  /* Do we need to set up a mount namespace for this kernel? */
4416
        bool keep_seccomp_privileges = false;
13,520✔
4417
        bool has_cap_sys_admin = false;
13,520✔
4418
#if HAVE_SELINUX
4419
        _cleanup_free_ char *mac_selinux_context_net = NULL;
4420
        bool use_selinux = false;
4421
#endif
4422
#if ENABLE_SMACK
4423
        bool use_smack = false;
13,520✔
4424
#endif
4425
#if HAVE_APPARMOR
4426
        bool use_apparmor = false;
4427
#endif
4428
#if HAVE_SECCOMP
4429
        uint64_t saved_bset = 0;
13,520✔
4430
#endif
4431
        uid_t saved_uid = getuid();
13,520✔
4432
        gid_t saved_gid = getgid();
13,520✔
4433
        uid_t uid = UID_INVALID;
13,520✔
4434
        gid_t gid = GID_INVALID;
13,520✔
4435
        size_t n_fds, /* fds to pass to the child */
13,520✔
4436
               n_keep_fds; /* total number of fds not to close */
4437
        int secure_bits;
13,520✔
4438
        _cleanup_free_ gid_t *gids_after_pam = NULL;
28✔
4439
        int ngids_after_pam = 0;
13,520✔
4440

4441
        int socket_fd = -EBADF, named_iofds[3] = EBADF_TRIPLET;
13,520✔
4442
        size_t n_storage_fds, n_socket_fds, n_extra_fds;
13,520✔
4443

4444
        assert(command);
13,520✔
4445
        assert(context);
13,520✔
4446
        assert(params);
13,520✔
4447
        assert(exit_status);
13,520✔
4448

4449
        /* This should be mostly redundant, as the log level is also passed as an argument of the executor,
4450
         * and is already applied earlier. Just for safety. */
4451
        if (params->debug_invocation)
13,520✔
4452
                log_set_max_level(LOG_PRI(LOG_DEBUG));
2✔
4453
        else if (context->log_level_max >= 0)
13,518✔
4454
                log_set_max_level(context->log_level_max);
5✔
4455

4456
        /* Explicitly test for CVE-2021-4034 inspired invocations */
4457
        if (!command->path || strv_isempty(command->argv)) {
13,520✔
4458
                *exit_status = EXIT_EXEC;
×
4459
                return log_exec_error_errno(
×
4460
                                context,
4461
                                params,
4462
                                SYNTHETIC_ERRNO(EINVAL),
4463
                                "Invalid command line arguments.");
4464
        }
4465

4466
        LOG_CONTEXT_PUSH_EXEC(context, params);
39,310✔
4467

4468
        if (context->std_input == EXEC_INPUT_SOCKET ||
13,520✔
4469
            context->std_output == EXEC_OUTPUT_SOCKET ||
13,509✔
4470
            context->std_error == EXEC_OUTPUT_SOCKET) {
13,503✔
4471

4472
                if (params->n_socket_fds > 1)
17✔
4473
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EINVAL), "Got more than one socket.");
×
4474

4475
                if (params->n_socket_fds == 0)
17✔
4476
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EINVAL), "Got no socket.");
×
4477

4478
                socket_fd = params->fds[0];
17✔
4479
                n_storage_fds = n_socket_fds = n_extra_fds = 0;
17✔
4480
        } else {
4481
                n_socket_fds = params->n_socket_fds;
13,503✔
4482
                n_storage_fds = params->n_storage_fds;
13,503✔
4483
                n_extra_fds = params->n_extra_fds;
13,503✔
4484
        }
4485
        n_fds = n_socket_fds + n_storage_fds + n_extra_fds;
13,520✔
4486

4487
        r = exec_context_named_iofds(context, params, named_iofds);
13,520✔
4488
        if (r < 0)
13,520✔
4489
                return log_exec_error_errno(context, params, r, "Failed to load a named file descriptor: %m");
×
4490

4491
        rename_process_from_path(command->path);
13,520✔
4492

4493
        /* We reset exactly these signals, since they are the only ones we set to SIG_IGN in the main
4494
         * daemon. All others we leave untouched because we set them to SIG_DFL or a valid handler initially,
4495
         * both of which will be demoted to SIG_DFL. */
4496
        (void) default_signals(SIGNALS_CRASH_HANDLER,
13,520✔
4497
                               SIGNALS_IGNORE);
4498

4499
        if (context->ignore_sigpipe)
13,520✔
4500
                (void) ignore_signals(SIGPIPE);
13,357✔
4501

4502
        r = reset_signal_mask();
13,520✔
4503
        if (r < 0) {
13,520✔
4504
                *exit_status = EXIT_SIGNAL_MASK;
×
4505
                return log_exec_error_errno(context, params, r, "Failed to set process signal mask: %m");
×
4506
        }
4507

4508
        if (params->idle_pipe)
13,520✔
4509
                do_idle_pipe_dance(params->idle_pipe);
160✔
4510

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

4516
        log_forget_fds();
13,520✔
4517
        log_set_open_when_needed(true);
13,520✔
4518
        log_settle_target();
13,520✔
4519

4520
        /* In case anything used libc syslog(), close this here, too */
4521
        closelog();
13,520✔
4522

4523
        r = collect_open_file_fds(context, params, &n_fds);
13,520✔
4524
        if (r < 0) {
13,520✔
4525
                *exit_status = EXIT_FDS;
1✔
4526
                return log_exec_error_errno(context, params, r, "Failed to get OpenFile= file descriptors: %m");
3✔
4527
        }
4528

4529
        int keep_fds[n_fds + 4];
13,519✔
4530
        memcpy_safe(keep_fds, params->fds, n_fds * sizeof(int));
13,519✔
4531
        n_keep_fds = n_fds;
13,519✔
4532

4533
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->exec_fd);
13,519✔
4534
        if (r < 0) {
13,519✔
4535
                *exit_status = EXIT_FDS;
×
4536
                return log_exec_error_errno(context, params, r, "Failed to collect shifted fd: %m");
×
4537
        }
4538

4539
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->handoff_timestamp_fd);
13,519✔
4540
        if (r < 0) {
13,519✔
4541
                *exit_status = EXIT_FDS;
×
4542
                return log_exec_error_errno(context, params, r, "Failed to collect shifted fd: %m");
×
4543
        }
4544

4545
#if HAVE_LIBBPF
4546
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &params->bpf_restrict_fs_map_fd);
13,519✔
4547
        if (r < 0) {
13,519✔
4548
                *exit_status = EXIT_FDS;
×
4549
                return log_exec_error_errno(context, params, r, "Failed to collect shifted fd: %m");
×
4550
        }
4551
#endif
4552

4553
        r = close_remaining_fds(params, runtime, socket_fd, keep_fds, n_keep_fds);
13,519✔
4554
        if (r < 0) {
13,519✔
4555
                *exit_status = EXIT_FDS;
×
4556
                return log_exec_error_errno(context, params, r, "Failed to close unwanted file descriptors: %m");
×
4557
        }
4558

4559
        if (!context->same_pgrp &&
26,050✔
4560
            setsid() < 0) {
12,531✔
4561
                *exit_status = EXIT_SETSID;
×
4562
                return log_exec_error_errno(context, params, errno, "Failed to create new process session: %m");
×
4563
        }
4564

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

4574
        if (params->shall_confirm_spawn && exec_context_shall_confirm_spawn(context)) {
13,519✔
4575
                _cleanup_free_ char *cmdline = NULL;
×
4576

4577
                cmdline = quote_command_line(command->argv, SHELL_ESCAPE_EMPTY);
×
4578
                if (!cmdline) {
×
4579
                        *exit_status = EXIT_MEMORY;
×
4580
                        return log_oom();
×
4581
                }
4582

4583
                r = ask_for_confirmation(context, params, cmdline);
×
4584
                if (r != CONFIRM_EXECUTE) {
×
4585
                        if (r == CONFIRM_PRETEND_SUCCESS) {
×
4586
                                *exit_status = EXIT_SUCCESS;
×
4587
                                return 0;
×
4588
                        }
4589

4590
                        *exit_status = EXIT_CONFIRM;
×
4591
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(ECANCELED),
×
4592
                                                    "Execution cancelled by the user.");
4593
                }
4594
        }
4595

4596
        /* We are about to invoke NSS and PAM modules. Let's tell them what we are doing here, maybe they care. This is
4597
         * used by nss-resolve to disable itself when we are about to start systemd-resolved, to avoid deadlocks. Note
4598
         * that these env vars do not survive the execve(), which means they really only apply to the PAM and NSS
4599
         * invocations themselves. Also note that while we'll only invoke NSS modules involved in user management they
4600
         * might internally call into other NSS modules that are involved in hostname resolution, we never know. */
4601
        if (setenv("SYSTEMD_ACTIVATION_UNIT", params->unit_id, true) != 0 ||
27,038✔
4602
            setenv("SYSTEMD_ACTIVATION_SCOPE", runtime_scope_to_string(params->runtime_scope), true) != 0) {
13,519✔
4603
                *exit_status = EXIT_MEMORY;
×
4604
                return log_exec_error_errno(context, params, errno, "Failed to update environment: %m");
×
4605
        }
4606

4607
        if (context->dynamic_user && runtime && runtime->dynamic_creds) {
13,580✔
4608
                _cleanup_strv_free_ char **suggested_paths = NULL;
61✔
4609

4610
                /* On top of that, make sure we bypass our own NSS module nss-systemd comprehensively for any NSS
4611
                 * checks, if DynamicUser=1 is used, as we shouldn't create a feedback loop with ourselves here. */
4612
                if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
61✔
4613
                        *exit_status = EXIT_USER;
×
4614
                        return log_exec_error_errno(context, params, errno, "Failed to update environment: %m");
×
4615
                }
4616

4617
                r = compile_suggested_paths(context, params, &suggested_paths);
61✔
4618
                if (r < 0) {
61✔
4619
                        *exit_status = EXIT_MEMORY;
×
4620
                        return log_oom();
×
4621
                }
4622

4623
                r = dynamic_creds_realize(runtime->dynamic_creds, suggested_paths, &uid, &gid);
61✔
4624
                if (r < 0) {
61✔
4625
                        *exit_status = EXIT_USER;
×
4626
                        if (r == -EILSEQ)
×
4627
                                return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EOPNOTSUPP),
×
4628
                                                            "Failed to update dynamic user credentials: User or group with specified name already exists.");
4629
                        return log_exec_error_errno(context, params, r, "Failed to update dynamic user credentials: %m");
×
4630
                }
4631

4632
                if (!uid_is_valid(uid)) {
61✔
4633
                        *exit_status = EXIT_USER;
×
4634
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(ESRCH), "UID validation failed for \""UID_FMT"\".", uid);
×
4635
                }
4636

4637
                if (!gid_is_valid(gid)) {
61✔
4638
                        *exit_status = EXIT_USER;
×
4639
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(ESRCH), "GID validation failed for \""GID_FMT"\".", gid);
×
4640
                }
4641

4642
                if (runtime->dynamic_creds->user)
61✔
4643
                        username = runtime->dynamic_creds->user->name;
61✔
4644

4645
        } else {
4646
                const char *u;
13,458✔
4647

4648
                if (context->user)
13,458✔
4649
                        u = context->user;
4650
                else if (context->pam_name) {
10,872✔
4651
                        /* If PAM is enabled but no user name is explicitly selected, then use our own one. */
4652
                        own_user = getusername_malloc();
59✔
4653
                        if (!own_user) {
59✔
4654
                                *exit_status = EXIT_USER;
×
4655
                                return log_exec_error_errno(context, params, r, "Failed to determine my own user ID: %m");
×
4656
                        }
4657
                        u = own_user;
4658
                } else
4659
                        u = NULL;
4660

4661
                if (u) {
4662
                        r = get_fixed_user(u, &username, &uid, &gid, &pwent_home, &shell);
2,645✔
4663
                        if (r < 0) {
2,645✔
4664
                                *exit_status = EXIT_USER;
2✔
4665
                                return log_exec_error_errno(context, params, r, "Failed to determine user credentials: %m");
6✔
4666
                        }
4667
                }
4668

4669
                if (context->group) {
13,456✔
4670
                        r = get_fixed_group(context->group, &groupname, &gid);
9✔
4671
                        if (r < 0) {
9✔
4672
                                *exit_status = EXIT_GROUP;
×
4673
                                return log_exec_error_errno(context, params, r, "Failed to determine group credentials: %m");
×
4674
                        }
4675
                }
4676
        }
4677

4678
        /* Initialize user supplementary groups and get SupplementaryGroups= ones */
4679
        r = get_supplementary_groups(context, username, groupname, gid,
13,517✔
4680
                                     &supplementary_gids, &ngids);
4681
        if (r < 0) {
13,517✔
4682
                *exit_status = EXIT_GROUP;
×
4683
                return log_exec_error_errno(context, params, r, "Failed to determine supplementary groups: %m");
×
4684
        }
4685

4686
        r = send_user_lookup(params->unit_id, params->user_lookup_fd, uid, gid);
13,517✔
4687
        if (r < 0) {
13,517✔
4688
                *exit_status = EXIT_USER;
×
4689
                return log_exec_error_errno(context, params, r, "Failed to send user credentials to PID1: %m");
×
4690
        }
4691

4692
        params->user_lookup_fd = safe_close(params->user_lookup_fd);
13,517✔
4693

4694
        r = acquire_home(context, &pwent_home, &home_buffer);
13,517✔
4695
        if (r < 0) {
13,517✔
4696
                *exit_status = EXIT_CHDIR;
×
4697
                return log_exec_error_errno(context, params, r, "Failed to determine $HOME for the invoking user: %m");
×
4698
        }
4699

4700
        /* If a socket is connected to STDIN/STDOUT/STDERR, we must drop O_NONBLOCK */
4701
        if (socket_fd >= 0)
13,517✔
4702
                (void) fd_nonblock(socket_fd, false);
17✔
4703

4704
        /* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields.
4705
         * Hence we need to migrate to the target cgroup from init.scope before connecting to journald */
4706
        if (params->cgroup_path) {
13,517✔
4707
                _cleanup_free_ char *p = NULL;
13,517✔
4708

4709
                r = exec_params_get_cgroup_path(params, cgroup_context, &p);
13,517✔
4710
                if (r < 0) {
13,517✔
4711
                        *exit_status = EXIT_CGROUP;
×
4712
                        return log_exec_error_errno(context, params, r, "Failed to acquire cgroup path: %m");
×
4713
                }
4714

4715
                r = cg_attach_everywhere(params->cgroup_supported, p, 0);
13,517✔
4716
                if (r == -EUCLEAN) {
13,517✔
4717
                        *exit_status = EXIT_CGROUP;
×
4718
                        return log_exec_error_errno(context, params, r,
×
4719
                                                    "Failed to attach process to cgroup '%s', "
4720
                                                    "because the cgroup or one of its parents or "
4721
                                                    "siblings is in the threaded mode.", p);
4722
                }
4723
                if (r < 0) {
13,517✔
4724
                        *exit_status = EXIT_CGROUP;
×
4725
                        return log_exec_error_errno(context, params, r, "Failed to attach to cgroup %s: %m", p);
×
4726
                }
4727
        }
4728

4729
        if (context->network_namespace_path && runtime && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
13,517✔
4730
                r = open_shareable_ns_path(runtime->shared->netns_storage_socket, context->network_namespace_path, CLONE_NEWNET);
×
4731
                if (r < 0) {
×
4732
                        *exit_status = EXIT_NETWORK;
×
4733
                        return log_exec_error_errno(context, params, r, "Failed to open network namespace path %s: %m", context->network_namespace_path);
×
4734
                }
4735
        }
4736

4737
        if (context->ipc_namespace_path && runtime && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
13,517✔
4738
                r = open_shareable_ns_path(runtime->shared->ipcns_storage_socket, context->ipc_namespace_path, CLONE_NEWIPC);
×
4739
                if (r < 0) {
×
4740
                        *exit_status = EXIT_NAMESPACE;
×
4741
                        return log_exec_error_errno(context, params, r, "Failed to open IPC namespace path %s: %m", context->ipc_namespace_path);
×
4742
                }
4743
        }
4744

4745
        r = setup_input(context, params, socket_fd, named_iofds);
13,517✔
4746
        if (r < 0) {
13,517✔
4747
                *exit_status = EXIT_STDIN;
×
4748
                return log_exec_error_errno(context, params, r, "Failed to set up standard input: %m");
×
4749
        }
4750

4751
        _cleanup_free_ char *fname = NULL;
25✔
4752
        r = path_extract_filename(command->path, &fname);
13,517✔
4753
        if (r < 0) {
13,517✔
4754
                *exit_status = EXIT_STDOUT;
×
4755
                return log_exec_error_errno(context, params, r, "Failed to extract filename from path %s: %m", command->path);
×
4756
        }
4757

4758
        r = setup_output(context, params, STDOUT_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
13,517✔
4759
        if (r < 0) {
13,517✔
4760
                *exit_status = EXIT_STDOUT;
×
4761
                return log_exec_error_errno(context, params, r, "Failed to set up standard output: %m");
×
4762
        }
4763

4764
        r = setup_output(context, params, STDERR_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
13,517✔
4765
        if (r < 0) {
13,517✔
4766
                *exit_status = EXIT_STDERR;
×
4767
                return log_exec_error_errno(context, params, r, "Failed to set up standard error output: %m");
×
4768
        }
4769

4770
        /* Now that stdin/stdout are definiely opened, properly initialize it with our desired
4771
         * settings. Note: this is a "constructive" reset, it prepares things for us to use. This is
4772
         * different from the "destructive" TTY reset further up. Also note: we apply this on stdin/stdout in
4773
         * case this is a tty, regardless if we opened it ourselves or got it passed in pre-opened. */
4774
        prepare_terminal(context, params);
13,517✔
4775

4776
        if (context->oom_score_adjust_set) {
13,517✔
4777
                /* When we can't make this change due to EPERM, then let's silently skip over it. User
4778
                 * namespaces prohibit write access to this file, and we shouldn't trip up over that. */
4779
                r = set_oom_score_adjust(context->oom_score_adjust);
1,451✔
4780
                if (ERRNO_IS_NEG_PRIVILEGE(r))
1,451✔
4781
                        log_exec_debug_errno(context, params, r,
×
4782
                                             "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
4783
                else if (r < 0) {
1,451✔
4784
                        *exit_status = EXIT_OOM_ADJUST;
×
4785
                        return log_exec_error_errno(context, params, r, "Failed to adjust OOM setting: %m");
×
4786
                }
4787
        }
4788

4789
        if (context->coredump_filter_set) {
13,517✔
4790
                r = set_coredump_filter(context->coredump_filter);
2✔
4791
                if (ERRNO_IS_NEG_PRIVILEGE(r))
2✔
4792
                        log_exec_debug_errno(context, params, r, "Failed to adjust coredump_filter, ignoring: %m");
×
4793
                else if (r < 0) {
2✔
4794
                        *exit_status = EXIT_LIMITS;
×
4795
                        return log_exec_error_errno(context, params, r, "Failed to adjust coredump_filter: %m");
×
4796
                }
4797
        }
4798

4799
        if (context->cpu_sched_set) {
13,517✔
4800
                struct sched_attr attr = {
×
4801
                        .size = sizeof(attr),
4802
                        .sched_policy = context->cpu_sched_policy,
×
4803
                        .sched_priority = context->cpu_sched_priority,
×
4804
                        .sched_flags = context->cpu_sched_reset_on_fork ? SCHED_FLAG_RESET_ON_FORK : 0,
×
4805
                };
4806

4807
                r = sched_setattr(/* pid= */ 0, &attr, /* flags= */ 0);
×
4808
                if (r < 0) {
×
4809
                        *exit_status = EXIT_SETSCHEDULER;
×
4810
                        return log_exec_error_errno(context, params, errno, "Failed to set up CPU scheduling: %m");
×
4811
                }
4812
        }
4813

4814
        /*
4815
         * Set nice value _after_ the call to sched_setattr() because struct sched_attr includes sched_nice
4816
         * which we do not set, thus it will clobber any previously set nice value. Scheduling policy might
4817
         * be reasonably set together with nice value e.g. in case of SCHED_BATCH (see sched(7)).
4818
         * It would be ideal to set both with the same call, but we cannot easily do so because of all the
4819
         * extra logic in setpriority_closest().
4820
         */
4821
        if (context->nice_set) {
13,517✔
4822
                r = setpriority_closest(context->nice);
16✔
4823
                if (r < 0) {
16✔
4824
                        *exit_status = EXIT_NICE;
×
4825
                        return log_exec_error_errno(context, params, r, "Failed to set up process scheduling priority (nice level): %m");
×
4826
                }
4827
        }
4828

4829
        if (context->cpu_affinity_from_numa || context->cpu_set.set) {
13,517✔
4830
                _cleanup_(cpu_set_reset) CPUSet converted_cpu_set = {};
2✔
4831
                const CPUSet *cpu_set;
2✔
4832

4833
                if (context->cpu_affinity_from_numa) {
2✔
4834
                        r = exec_context_cpu_affinity_from_numa(context, &converted_cpu_set);
2✔
4835
                        if (r < 0) {
2✔
4836
                                *exit_status = EXIT_CPUAFFINITY;
×
4837
                                return log_exec_error_errno(context, params, r, "Failed to derive CPU affinity mask from NUMA mask: %m");
×
4838
                        }
4839

4840
                        cpu_set = &converted_cpu_set;
4841
                } else
4842
                        cpu_set = &context->cpu_set;
×
4843

4844
                if (sched_setaffinity(0, cpu_set->allocated, cpu_set->set) < 0) {
2✔
4845
                        *exit_status = EXIT_CPUAFFINITY;
×
4846
                        return log_exec_error_errno(context, params, errno, "Failed to set up CPU affinity: %m");
×
4847
                }
4848
        }
4849

4850
        if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) {
13,517✔
4851
                r = apply_numa_policy(&context->numa_policy);
19✔
4852
                if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
19✔
4853
                        log_exec_debug_errno(context, params, r, "NUMA support not available, ignoring.");
×
4854
                else if (r < 0) {
19✔
4855
                        *exit_status = EXIT_NUMA_POLICY;
2✔
4856
                        return log_exec_error_errno(context, params, r, "Failed to set NUMA memory policy: %m");
6✔
4857
                }
4858
        }
4859

4860
        if (context->ioprio_set)
13,515✔
4861
                if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
7✔
4862
                        *exit_status = EXIT_IOPRIO;
×
4863
                        return log_exec_error_errno(context, params, errno, "Failed to set up IO scheduling priority: %m");
×
4864
                }
4865

4866
        if (context->timer_slack_nsec != NSEC_INFINITY)
13,515✔
4867
                if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
×
4868
                        *exit_status = EXIT_TIMERSLACK;
×
4869
                        return log_exec_error_errno(context, params, errno, "Failed to set up timer slack: %m");
×
4870
                }
4871

4872
        if (context->personality != PERSONALITY_INVALID) {
13,515✔
4873
                r = safe_personality(context->personality);
×
4874
                if (r < 0) {
×
4875
                        *exit_status = EXIT_PERSONALITY;
×
4876
                        return log_exec_error_errno(context, params, r, "Failed to set up execution domain (personality): %m");
×
4877
                }
4878
        }
4879

4880
#if ENABLE_UTMP
4881
        if (context->utmp_id) {
13,515✔
4882
                _cleanup_free_ char *username_alloc = NULL;
165✔
4883

4884
                if (!username && context->utmp_mode == EXEC_UTMP_USER) {
165✔
4885
                        username_alloc = uid_to_name(uid_is_valid(uid) ? uid : saved_uid);
1✔
4886
                        if (!username_alloc) {
1✔
4887
                                *exit_status = EXIT_USER;
×
4888
                                return log_oom();
×
4889
                        }
4890
                }
4891

4892
                const char *line = context->tty_path ?
330✔
4893
                        (path_startswith(context->tty_path, "/dev/") ?: context->tty_path) :
165✔
4894
                        NULL;
4895
                utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
165✔
4896
                                      line,
4897
                                      context->utmp_mode == EXEC_UTMP_INIT  ? INIT_PROCESS :
165✔
4898
                                      context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
7✔
4899
                                      USER_PROCESS,
4900
                                      username ?: username_alloc);
165✔
4901
        }
4902
#endif
4903

4904
        if (uid_is_valid(uid)) {
13,515✔
4905
                r = chown_terminal(STDIN_FILENO, uid);
2,704✔
4906
                if (r < 0) {
2,704✔
4907
                        *exit_status = EXIT_STDIN;
×
4908
                        return log_exec_error_errno(context, params, r, "Failed to change ownership of terminal: %m");
×
4909
                }
4910
        }
4911

4912
        /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted
4913
         * from it. */
4914
        needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
13,515✔
4915

4916
        if (params->cgroup_path) {
13,515✔
4917
                /* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1
4918
                 * this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not
4919
                 * safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only
4920
                 * touch a single hierarchy too. */
4921

4922
                if (params->flags & EXEC_CGROUP_DELEGATE) {
13,515✔
4923
                        _cleanup_free_ char *p = NULL;
655✔
4924

4925
                        r = cg_set_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, uid, gid);
655✔
4926
                        if (r < 0) {
655✔
4927
                                *exit_status = EXIT_CGROUP;
×
4928
                                return log_exec_error_errno(context, params, r, "Failed to adjust control group access: %m");
×
4929
                        }
4930

4931
                        r = exec_params_get_cgroup_path(params, cgroup_context, &p);
655✔
4932
                        if (r < 0) {
655✔
4933
                                *exit_status = EXIT_CGROUP;
×
4934
                                return log_exec_error_errno(context, params, r, "Failed to acquire cgroup path: %m");
×
4935
                        }
4936
                        if (r > 0) {
655✔
4937
                                r = cg_set_access_recursive(SYSTEMD_CGROUP_CONTROLLER, p, uid, gid);
320✔
4938
                                if (r < 0) {
320✔
4939
                                        *exit_status = EXIT_CGROUP;
×
4940
                                        return log_exec_error_errno(context, params, r, "Failed to adjust control subgroup access: %m");
×
4941
                                }
4942
                        }
4943
                }
4944

4945
                if (cgroup_context && cg_unified() > 0 && is_pressure_supported() > 0) {
27,030✔
4946
                        if (cgroup_context_want_memory_pressure(cgroup_context)) {
13,515✔
4947
                                r = cg_get_path("memory", params->cgroup_path, "memory.pressure", &memory_pressure_path);
13,160✔
4948
                                if (r < 0) {
13,160✔
4949
                                        *exit_status = EXIT_MEMORY;
×
4950
                                        return log_oom();
×
4951
                                }
4952

4953
                                r = chmod_and_chown(memory_pressure_path, 0644, uid, gid);
13,160✔
4954
                                if (r < 0) {
13,160✔
4955
                                        log_exec_full_errno(context, params, r == -ENOENT || ERRNO_IS_PRIVILEGE(r) ? LOG_DEBUG : LOG_WARNING, r,
2✔
4956
                                                            "Failed to adjust ownership of '%s', ignoring: %m", memory_pressure_path);
4957
                                        memory_pressure_path = mfree(memory_pressure_path);
1✔
4958
                                }
4959
                                /* First we use the current cgroup path to chmod and chown the memory pressure path, then pass the path relative
4960
                                 * to the cgroup namespace to environment variables and mounts. If chown/chmod fails, we should not pass memory
4961
                                 * pressure path environment variable or read-write mount to the unit. This is why we check if
4962
                                 * memory_pressure_path != NULL in the conditional below. */
4963
                                if (memory_pressure_path && needs_sandboxing && exec_needs_cgroup_namespace(context, params)) {
13,160✔
4964
                                        memory_pressure_path = mfree(memory_pressure_path);
9✔
4965
                                        r = cg_get_path("memory", "", "memory.pressure", &memory_pressure_path);
9✔
4966
                                        if (r < 0) {
9✔
4967
                                                *exit_status = EXIT_MEMORY;
×
4968
                                                return log_oom();
×
4969
                                        }
4970
                                }
4971
                        } else if (cgroup_context->memory_pressure_watch == CGROUP_PRESSURE_WATCH_NO) {
355✔
4972
                                memory_pressure_path = strdup("/dev/null"); /* /dev/null is explicit indicator for turning of memory pressure watch */
×
4973
                                if (!memory_pressure_path) {
×
4974
                                        *exit_status = EXIT_MEMORY;
×
4975
                                        return log_oom();
×
4976
                                }
4977
                        }
4978
                }
4979
        }
4980

4981
        needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
13,515✔
4982

4983
        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
81,085✔
4984
                r = setup_exec_directory(context, params, uid, gid, dt, needs_mount_namespace, exit_status);
67,571✔
4985
                if (r < 0)
67,571✔
4986
                        return log_exec_error_errno(context, params, r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
3✔
4987
        }
4988

4989
        r = exec_setup_credentials(context, params, params->unit_id, uid, gid);
13,514✔
4990
        if (r < 0) {
11,109✔
4991
                *exit_status = EXIT_CREDENTIALS;
×
4992
                return log_exec_error_errno(context, params, r, "Failed to set up credentials: %m");
×
4993
        }
4994

4995
        r = build_environment(
11,109✔
4996
                        context,
4997
                        params,
4998
                        cgroup_context,
4999
                        n_fds,
5000
                        pwent_home,
5001
                        username,
5002
                        shell,
5003
                        journal_stream_dev,
5004
                        journal_stream_ino,
5005
                        memory_pressure_path,
5006
                        needs_sandboxing,
5007
                        &our_env);
5008
        if (r < 0) {
11,109✔
5009
                *exit_status = EXIT_MEMORY;
×
5010
                return log_oom();
×
5011
        }
5012

5013
        r = build_pass_environment(context, &pass_env);
11,109✔
5014
        if (r < 0) {
11,109✔
5015
                *exit_status = EXIT_MEMORY;
×
5016
                return log_oom();
×
5017
        }
5018

5019
        /* The $PATH variable is set to the default path in params->environment. However, this is overridden
5020
         * if user-specified fields have $PATH set. The intention is to also override $PATH if the unit does
5021
         * not specify PATH but the unit has ExecSearchPath. */
5022
        if (!strv_isempty(context->exec_search_path)) {
11,109✔
5023
                _cleanup_free_ char *joined = NULL;
×
5024

5025
                joined = strv_join(context->exec_search_path, ":");
×
5026
                if (!joined) {
×
5027
                        *exit_status = EXIT_MEMORY;
×
5028
                        return log_oom();
×
5029
                }
5030

5031
                r = strv_env_assign(&joined_exec_search_path, "PATH", joined);
×
5032
                if (r < 0) {
×
5033
                        *exit_status = EXIT_MEMORY;
×
5034
                        return log_oom();
×
5035
                }
5036
        }
5037

5038
        accum_env = strv_env_merge(params->environment,
11,109✔
5039
                                   our_env,
5040
                                   joined_exec_search_path,
5041
                                   pass_env,
5042
                                   context->environment,
5043
                                   params->files_env);
5044
        if (!accum_env) {
11,109✔
5045
                *exit_status = EXIT_MEMORY;
×
5046
                return log_oom();
×
5047
        }
5048
        accum_env = strv_env_clean(accum_env);
11,109✔
5049

5050
        (void) umask(context->umask);
11,109✔
5051

5052
        r = setup_keyring(context, params, uid, gid);
11,109✔
5053
        if (r < 0) {
11,109✔
5054
                *exit_status = EXIT_KEYRING;
×
5055
                return log_exec_error_errno(context, params, r, "Failed to set up kernel keyring: %m");
×
5056
        }
5057

5058
        /* We need setresuid() if the caller asked us to apply sandboxing and the command isn't explicitly
5059
         * excepted from either whole sandboxing or just setresuid() itself. */
5060
        needs_setuid = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & (EXEC_COMMAND_FULLY_PRIVILEGED|EXEC_COMMAND_NO_SETUID));
11,109✔
5061

5062
        uint64_t capability_ambient_set = context->capability_ambient_set;
11,109✔
5063

5064
        /* Check CAP_SYS_ADMIN before we enter user namespace to see if we can mount /proc even though its masked. */
5065
        has_cap_sys_admin = have_effective_cap(CAP_SYS_ADMIN) > 0;
11,109✔
5066

5067
        if (needs_sandboxing) {
11,109✔
5068
                /* MAC enablement checks need to be done before a new mount ns is created, as they rely on
5069
                 * /sys being present. The actual MAC context application will happen later, as late as
5070
                 * possible, to avoid impacting our own code paths. */
5071

5072
#if HAVE_SELINUX
5073
                use_selinux = mac_selinux_use();
5074
#endif
5075
#if ENABLE_SMACK
5076
                use_smack = mac_smack_use();
11,109✔
5077
#endif
5078
#if HAVE_APPARMOR
5079
                if (mac_apparmor_use()) {
5080
                        r = dlopen_libapparmor();
5081
                        if (r < 0 && !ERRNO_IS_NEG_NOT_SUPPORTED(r))
5082
                                log_warning_errno(r, "Failed to load libapparmor, ignoring: %m");
5083
                        use_apparmor = r >= 0;
5084
                }
5085
#endif
5086
        }
5087

5088
        if (needs_sandboxing) {
11,109✔
5089
                int which_failed;
11,109✔
5090

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

5094
                r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed);
11,109✔
5095
                if (r < 0) {
11,109✔
5096
                        *exit_status = EXIT_LIMITS;
×
5097
                        return log_exec_error_errno(context, params, r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
×
5098
                }
5099
        }
5100

5101
        if (needs_setuid && context->pam_name && username) {
11,109✔
5102
                /* Let's call into PAM after we set up our own idea of resource limits so that pam_limits
5103
                 * wins here. (See above.) */
5104

5105
                /* All fds passed in the fds array will be closed in the pam child process. */
5106
                r = setup_pam(context, params, username, uid, gid, &accum_env, params->fds, n_fds, params->exec_fd);
321✔
5107
                if (r < 0) {
321✔
5108
                        *exit_status = EXIT_PAM;
×
5109
                        return log_exec_error_errno(context, params, r, "Failed to set up PAM session: %m");
×
5110
                }
5111

5112
                /* PAM modules might have set some ambient caps. Query them here and merge them into
5113
                 * the caps we want to set in the end, so that we don't end up unsetting them. */
5114
                uint64_t ambient_after_pam;
321✔
5115
                r = capability_get_ambient(&ambient_after_pam);
321✔
5116
                if (r < 0) {
321✔
5117
                        *exit_status = EXIT_CAPABILITIES;
×
5118
                        return log_exec_error_errno(context, params, r, "Failed to query ambient caps: %m");
×
5119
                }
5120

5121
                capability_ambient_set |= ambient_after_pam;
321✔
5122

5123
                ngids_after_pam = getgroups_alloc(&gids_after_pam);
321✔
5124
                if (ngids_after_pam < 0) {
321✔
5125
                        *exit_status = EXIT_GROUP;
×
5126
                        return log_exec_error_errno(context, params, ngids_after_pam, "Failed to obtain groups after setting up PAM: %m");
×
5127
                }
5128
        }
5129

5130
        if (needs_sandboxing && exec_context_need_unprivileged_private_users(context, params)) {
11,109✔
5131
                /* If we're unprivileged, set up the user namespace first to enable use of the other namespaces.
5132
                 * Users with CAP_SYS_ADMIN can set up user namespaces last because they will be able to
5133
                 * set up all of the other namespaces (i.e. network, mount, UTS) without a user namespace. */
5134
                PrivateUsers pu = context->private_users;
25✔
5135
                if (pu == PRIVATE_USERS_NO)
25✔
5136
                        pu = PRIVATE_USERS_SELF;
22✔
5137

5138
                /* The kernel requires /proc/pid/setgroups be set to "deny" prior to writing /proc/pid/gid_map in
5139
                 * unprivileged user namespaces. */
5140
                r = setup_private_users(pu, saved_uid, saved_gid, uid, gid, /* allow_setgroups= */ false);
25✔
5141
                /* If it was requested explicitly and we can't set it up, fail early. Otherwise, continue and let
5142
                 * the actual requested operations fail (or silently continue). */
5143
                if (r < 0 && context->private_users != PRIVATE_USERS_NO) {
25✔
5144
                        *exit_status = EXIT_USER;
×
5145
                        return log_exec_error_errno(context, params, r, "Failed to set up user namespacing for unprivileged user: %m");
×
5146
                }
5147
                if (r < 0)
×
5148
                        log_exec_info_errno(context, params, r, "Failed to set up user namespacing for unprivileged user, ignoring: %m");
×
5149
                else {
5150
                        assert(r > 0);
25✔
5151
                        userns_set_up = true;
5152
                }
5153
        }
5154

5155
        if (exec_needs_network_namespace(context) && runtime && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
11,109✔
5156

5157
                /* Try to enable network namespacing if network namespacing is available and we have
5158
                 * CAP_NET_ADMIN. We need CAP_NET_ADMIN to be able to configure the loopback device in the
5159
                 * new network namespace. And if we don't have that, then we could only create a network
5160
                 * namespace without the ability to set up "lo". Hence gracefully skip things then. */
5161
                if (ns_type_supported(NAMESPACE_NET) && have_effective_cap(CAP_NET_ADMIN) > 0) {
301✔
5162
                        r = setup_shareable_ns(runtime->shared->netns_storage_socket, CLONE_NEWNET);
301✔
5163
                        if (ERRNO_IS_NEG_PRIVILEGE(r))
301✔
5164
                                log_exec_notice_errno(context, params, r,
×
5165
                                                      "PrivateNetwork=yes is configured, but network namespace setup not permitted, proceeding without: %m");
5166
                        else if (r < 0) {
301✔
5167
                                *exit_status = EXIT_NETWORK;
×
5168
                                return log_exec_error_errno(context, params, r, "Failed to set up network namespacing: %m");
×
5169
                        }
5170
                } else if (context->network_namespace_path) {
×
5171
                        *exit_status = EXIT_NETWORK;
×
5172
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EOPNOTSUPP),
×
5173
                                                    "NetworkNamespacePath= is not supported, refusing.");
5174
                } else
5175
                        log_exec_notice(context, params, "PrivateNetwork=yes is configured, but the kernel does not support or we lack privileges for network namespace, proceeding without.");
×
5176
        }
5177

5178
        if (exec_needs_ipc_namespace(context) && runtime && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
11,109✔
5179

5180
                if (ns_type_supported(NAMESPACE_IPC)) {
2✔
5181
                        r = setup_shareable_ns(runtime->shared->ipcns_storage_socket, CLONE_NEWIPC);
2✔
5182
                        if (ERRNO_IS_NEG_PRIVILEGE(r))
2✔
5183
                                log_exec_warning_errno(context, params, r,
×
5184
                                                       "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m");
5185
                        else if (r < 0) {
2✔
5186
                                *exit_status = EXIT_NAMESPACE;
×
5187
                                return log_exec_error_errno(context, params, r, "Failed to set up IPC namespacing: %m");
×
5188
                        }
5189
                } else if (context->ipc_namespace_path) {
×
5190
                        *exit_status = EXIT_NAMESPACE;
×
5191
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EOPNOTSUPP),
×
5192
                                                    "IPCNamespacePath= is not supported, refusing.");
5193
                } else
5194
                        log_exec_warning(context, params, "PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring.");
×
5195
        }
5196

5197
        if (needs_sandboxing && exec_needs_cgroup_namespace(context, params)) {
11,109✔
5198
                if (unshare(CLONE_NEWCGROUP) < 0) {
9✔
UNCOV
5199
                        *exit_status = EXIT_NAMESPACE;
×
5200
                        return log_exec_error_errno(context, params, errno, "Failed to set up cgroup namespacing: %m");
×
5201
                }
5202
        }
5203

5204
        /* Unshare a new PID namespace before setting up mounts to ensure /proc/ is mounted with only processes in PID namespace visible.
5205
         * Note PrivatePIDs=yes implies MountAPIVFS=yes so we'll always ensure procfs is remounted. */
5206
        if (needs_sandboxing && exec_needs_pid_namespace(context)) {
11,109✔
5207
                if (params->pidref_transport_fd < 0) {
11✔
UNCOV
5208
                        *exit_status = EXIT_NAMESPACE;
×
5209
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(ENOTCONN), "PidRef socket is not set up: %m");
×
5210
                }
5211

5212
                /* If we had CAP_SYS_ADMIN prior to joining the user namespace, then we are privileged and don't need
5213
                 * to check if we can mount /proc/.
5214
                 *
5215
                 * We need to check prior to entering the user namespace because if we're running unprivileged or in a
5216
                 * system without CAP_SYS_ADMIN, then we can have CAP_SYS_ADMIN in the current user namespace but not
5217
                 * once we unshare a mount namespace. */
5218
                r = has_cap_sys_admin ? 1 : can_mount_proc(context, params);
11✔
5219
                if (r < 0) {
3✔
UNCOV
5220
                        *exit_status = EXIT_NAMESPACE;
×
5221
                        return log_exec_error_errno(context, params, r, "Failed to detect if /proc/ can be remounted: %m");
×
5222
                }
5223
                if (r == 0) {
8✔
5224
                        *exit_status = EXIT_NAMESPACE;
1✔
5225
                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EPERM),
1✔
5226
                                                    "PrivatePIDs=yes is configured, but /proc/ cannot be re-mounted due to lack of privileges, refusing.");
5227
                }
5228

5229
                r = setup_private_pids(context, params);
7✔
5230
                if (r < 0) {
6✔
UNCOV
5231
                        *exit_status = EXIT_NAMESPACE;
×
5232
                        return log_exec_error_errno(context, params, r, "Failed to set up pid namespace: %m");
×
5233
                }
5234
        }
5235

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

5238
        if (needs_mount_namespace) {
11,104✔
5239
                _cleanup_free_ char *error_path = NULL;
2,554✔
5240

5241
                r = apply_mount_namespace(command->flags,
2,554✔
5242
                                          context,
5243
                                          params,
5244
                                          runtime,
5245
                                          memory_pressure_path,
5246
                                          needs_sandboxing,
5247
                                          &error_path,
5248
                                          uid,
5249
                                          gid);
5250
                if (r < 0) {
2,554✔
5251
                        *exit_status = EXIT_NAMESPACE;
15✔
5252
                        return log_exec_error_errno(context, params, r, "Failed to set up mount namespacing%s%s: %m",
59✔
5253
                                                    error_path ? ": " : "", strempty(error_path));
5254
                }
5255
        }
5256

5257
        if (needs_sandboxing) {
11,089✔
5258
                r = apply_protect_hostname(context, params, exit_status);
11,089✔
5259
                if (r < 0)
11,089✔
5260
                        return r;
5261
        }
5262

5263
        if (context->memory_ksm >= 0)
11,089✔
UNCOV
5264
                if (prctl(PR_SET_MEMORY_MERGE, context->memory_ksm, 0, 0, 0) < 0) {
×
5265
                        if (ERRNO_IS_NOT_SUPPORTED(errno))
×
5266
                                log_exec_debug_errno(context,
×
5267
                                                     params,
5268
                                                     errno,
5269
                                                     "KSM support not available, ignoring.");
5270
                        else {
UNCOV
5271
                                *exit_status = EXIT_KSM;
×
5272
                                return log_exec_error_errno(context, params, errno, "Failed to set KSM: %m");
×
5273
                        }
5274
                }
5275

5276
        /* Drop groups as early as possible.
5277
         * This needs to be done after PrivateDevices=yes setup as device nodes should be owned by the host's root.
5278
         * For non-root in a userns, devices will be owned by the user/group before the group change, and nobody. */
5279
        if (needs_setuid) {
11,089✔
5280
                _cleanup_free_ gid_t *gids_to_enforce = NULL;
11,089✔
5281
                int ngids_to_enforce = 0;
11,089✔
5282

5283
                ngids_to_enforce = merge_gid_lists(supplementary_gids,
11,089✔
5284
                                                   ngids,
5285
                                                   gids_after_pam,
5286
                                                   ngids_after_pam,
5287
                                                   &gids_to_enforce);
5288
                if (ngids_to_enforce < 0) {
11,089✔
UNCOV
5289
                        *exit_status = EXIT_GROUP;
×
5290
                        return log_exec_error_errno(context, params,
×
5291
                                                    ngids_to_enforce,
5292
                                                    "Failed to merge group lists. Group membership might be incorrect: %m");
5293
                }
5294

5295
                r = enforce_groups(gid, gids_to_enforce, ngids_to_enforce);
11,089✔
5296
                if (r < 0) {
11,089✔
5297
                        *exit_status = EXIT_GROUP;
1✔
5298
                        return log_exec_error_errno(context, params, r, "Changing group credentials failed: %m");
1✔
5299
                }
5300
        }
5301

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

5308
        if (needs_sandboxing && !userns_set_up) {
11,088✔
5309
                r = setup_private_users(context->private_users, saved_uid, saved_gid, uid, gid,
22,136✔
5310
                                        /* allow_setgroups= */ context->private_users == PRIVATE_USERS_FULL);
11,068✔
5311
                if (r < 0) {
11,068✔
UNCOV
5312
                        *exit_status = EXIT_USER;
×
5313
                        return log_exec_error_errno(context, params, r, "Failed to set up user namespacing: %m");
×
5314
                }
5315
        }
5316

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

5320
        _cleanup_free_ char *executable = NULL;
5✔
5321
        _cleanup_close_ int executable_fd = -EBADF;
5✔
5322
        r = find_executable_full(command->path, /* root= */ NULL, context->exec_search_path, false, &executable, &executable_fd);
11,088✔
5323
        if (r < 0) {
11,088✔
5324
                *exit_status = EXIT_EXEC;
1✔
5325
                log_exec_struct_errno(context, params, LOG_NOTICE, r,
3✔
5326
                                      "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
5327
                                      LOG_EXEC_MESSAGE(params,
5328
                                                       "Unable to locate executable '%s': %m",
5329
                                                       command->path),
5330
                                      "EXECUTABLE=%s", command->path);
5331
                /* If the error will be ignored by manager, tune down the log level here. Missing executable
5332
                 * is very much expected in this case. */
5333
                return r != -ENOMEM && FLAGS_SET(command->flags, EXEC_COMMAND_IGNORE_FAILURE) ? 1 : r;
1✔
5334
        }
5335

5336
        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, &executable_fd);
11,087✔
5337
        if (r < 0) {
11,087✔
UNCOV
5338
                *exit_status = EXIT_FDS;
×
5339
                return log_exec_error_errno(context, params, r, "Failed to collect shifted fd: %m");
×
5340
        }
5341

5342
#if HAVE_SELINUX
5343
        if (needs_sandboxing && use_selinux && params->selinux_context_net) {
5344
                int fd = -EBADF;
5345

5346
                if (socket_fd >= 0)
5347
                        fd = socket_fd;
5348
                else if (params->n_socket_fds == 1)
5349
                        /* If stdin is not connected to a socket but we are triggered by exactly one socket unit then we
5350
                         * use context from that fd to compute the label. */
5351
                        fd = params->fds[0];
5352

5353
                if (fd >= 0) {
5354
                        r = mac_selinux_get_child_mls_label(fd, executable, context->selinux_context, &mac_selinux_context_net);
5355
                        if (r < 0) {
5356
                                if (!context->selinux_context_ignore) {
5357
                                        *exit_status = EXIT_SELINUX_CONTEXT;
5358
                                        return log_exec_error_errno(context,
5359
                                                                    params,
5360
                                                                    r,
5361
                                                                    "Failed to determine SELinux context: %m");
5362
                                }
5363
                                log_exec_debug_errno(context,
5364
                                                     params,
5365
                                                     r,
5366
                                                     "Failed to determine SELinux context, ignoring: %m");
5367
                        }
5368
                }
5369
        }
5370
#endif
5371

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

5378
        exec_runtime_close(runtime);
11,087✔
5379
        exec_params_close(params);
11,087✔
5380

5381
        r = close_all_fds(keep_fds, n_keep_fds);
11,087✔
5382
        if (r >= 0)
11,087✔
5383
                r = pack_fds(params->fds, n_fds);
11,087✔
5384
        if (r >= 0)
11,087✔
5385
                r = flag_fds(params->fds, n_socket_fds, n_fds, context->non_blocking);
11,087✔
5386
        if (r < 0) {
11,087✔
UNCOV
5387
                *exit_status = EXIT_FDS;
×
5388
                return log_exec_error_errno(context, params, r, "Failed to adjust passed file descriptors: %m");
×
5389
        }
5390

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

5396
        secure_bits = context->secure_bits;
11,087✔
5397

5398
        if (needs_sandboxing) {
11,087✔
5399
                uint64_t bset;
11,087✔
5400

5401
                /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested.
5402
                 * (Note this is placed after the general resource limit initialization, see above, in order
5403
                 * to take precedence.) */
5404
                if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
11,087✔
5405
                        if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
2,055✔
UNCOV
5406
                                *exit_status = EXIT_LIMITS;
×
5407
                                return log_exec_error_errno(context, params, errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m");
×
5408
                        }
5409
                }
5410

5411
#if ENABLE_SMACK
5412
                /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the
5413
                 * process. This is the latest place before dropping capabilities. Other MAC context are set later. */
5414
                if (use_smack) {
11,087✔
UNCOV
5415
                        r = setup_smack(params, context, executable_fd);
×
5416
                        if (r < 0 && !context->smack_process_label_ignore) {
×
5417
                                *exit_status = EXIT_SMACK_PROCESS_LABEL;
×
5418
                                return log_exec_error_errno(context, params, r, "Failed to set SMACK process label: %m");
×
5419
                        }
5420
                }
5421
#endif
5422

5423
                bset = context->capability_bounding_set;
11,087✔
5424

5425
#if HAVE_SECCOMP
5426
                /* If the service has any form of a seccomp filter and it allows dropping privileges, we'll
5427
                 * keep the needed privileges to apply it even if we're not root. */
5428
                if (needs_setuid &&
22,174✔
5429
                    uid_is_valid(uid) &&
13,105✔
5430
                    context_has_seccomp(context) &&
2,866✔
5431
                    seccomp_allows_drop_privileges(context)) {
848✔
5432
                        keep_seccomp_privileges = true;
848✔
5433

5434
                        if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
848✔
UNCOV
5435
                                *exit_status = EXIT_USER;
×
5436
                                return log_exec_error_errno(context, params, errno, "Failed to enable keep capabilities flag: %m");
×
5437
                        }
5438

5439
                        /* Save the current bounding set so we can restore it after applying the seccomp
5440
                         * filter */
5441
                        saved_bset = bset;
848✔
5442
                        bset |= (UINT64_C(1) << CAP_SYS_ADMIN) |
848✔
5443
                                (UINT64_C(1) << CAP_SETPCAP);
5444
                }
5445
#endif
5446

5447
                if (!cap_test_all(bset)) {
11,087✔
5448
                        r = capability_bounding_set_drop(bset, /* right_now= */ false);
2,235✔
5449
                        if (r < 0) {
2,235✔
UNCOV
5450
                                *exit_status = EXIT_CAPABILITIES;
×
5451
                                return log_exec_error_errno(context, params, r, "Failed to drop capabilities: %m");
×
5452
                        }
5453
                }
5454

5455
                /* Ambient capabilities are cleared during setresuid() (in enforce_user()) even with
5456
                 * keep-caps set.
5457
                 *
5458
                 * To be able to raise the ambient capabilities after setresuid() they have to be added to
5459
                 * the inherited set and keep caps has to be set (done in enforce_user()).  After setresuid()
5460
                 * the ambient capabilities can be raised as they are present in the permitted and
5461
                 * inhertiable set. However it is possible that someone wants to set ambient capabilities
5462
                 * without changing the user, so we also set the ambient capabilities here.
5463
                 *
5464
                 * The requested ambient capabilities are raised in the inheritable set if the second
5465
                 * argument is true. */
5466
                if (capability_ambient_set != 0) {
11,087✔
5467
                        r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ true);
844✔
5468
                        if (r < 0) {
844✔
UNCOV
5469
                                *exit_status = EXIT_CAPABILITIES;
×
5470
                                return log_exec_error_errno(context, params, r, "Failed to apply ambient capabilities (before UID change): %m");
×
5471
                        }
5472
                }
5473
        }
5474

5475
        /* chroot to root directory first, before we lose the ability to chroot */
5476
        r = apply_root_directory(context, params, runtime, needs_mount_namespace, exit_status);
11,087✔
5477
        if (r < 0)
11,087✔
UNCOV
5478
                return log_exec_error_errno(context, params, r, "Chrooting to the requested root directory failed: %m");
×
5479

5480
        if (needs_setuid) {
11,087✔
5481
                if (uid_is_valid(uid)) {
11,087✔
5482
                        r = enforce_user(context, uid, capability_ambient_set);
2,018✔
5483
                        if (r < 0) {
2,018✔
UNCOV
5484
                                *exit_status = EXIT_USER;
×
5485
                                return log_exec_error_errno(context, params, r, "Failed to change UID to " UID_FMT ": %m", uid);
×
5486
                        }
5487

5488
                        if (keep_seccomp_privileges) {
2,018✔
5489
                                if (!BIT_SET(capability_ambient_set, CAP_SETUID)) {
848✔
5490
                                        r = drop_capability(CAP_SETUID);
848✔
5491
                                        if (r < 0) {
848✔
UNCOV
5492
                                                *exit_status = EXIT_USER;
×
5493
                                                return log_exec_error_errno(context, params, r, "Failed to drop CAP_SETUID: %m");
×
5494
                                        }
5495
                                }
5496

5497
                                r = keep_capability(CAP_SYS_ADMIN);
848✔
5498
                                if (r < 0) {
848✔
UNCOV
5499
                                        *exit_status = EXIT_USER;
×
5500
                                        return log_exec_error_errno(context, params, r, "Failed to keep CAP_SYS_ADMIN: %m");
×
5501
                                }
5502

5503
                                r = keep_capability(CAP_SETPCAP);
848✔
5504
                                if (r < 0) {
848✔
UNCOV
5505
                                        *exit_status = EXIT_USER;
×
5506
                                        return log_exec_error_errno(context, params, r, "Failed to keep CAP_SETPCAP: %m");
×
5507
                                }
5508
                        }
5509

5510
                        if (capability_ambient_set != 0) {
2,018✔
5511

5512
                                /* Raise the ambient capabilities after user change. */
5513
                                r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ false);
843✔
5514
                                if (r < 0) {
843✔
UNCOV
5515
                                        *exit_status = EXIT_CAPABILITIES;
×
5516
                                        return log_exec_error_errno(context, params, r, "Failed to apply ambient capabilities (after UID change): %m");
×
5517
                                }
5518
                        }
5519
                }
5520
        }
5521

5522
        /* Apply working directory here, because the working directory might be on NFS and only the user
5523
         * running this service might have the correct privilege to change to the working directory. Also, it
5524
         * is absolutely 💣 crucial 💣 we applied all mount namespacing rearrangements before this, so that
5525
         * the cwd cannot be used to pin directories outside of the sandbox. */
5526
        r = apply_working_directory(context, params, runtime, pwent_home, accum_env);
11,087✔
5527
        if (r < 0) {
11,087✔
5528
                *exit_status = EXIT_CHDIR;
1✔
5529
                return log_exec_error_errno(context, params, r, "Changing to the requested working directory failed: %m");
3✔
5530
        }
5531

5532
        if (needs_sandboxing) {
11,086✔
5533
                /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to
5534
                 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
5535
                 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
5536
                 * are restricted. */
5537

5538
#if HAVE_SELINUX
5539
                if (use_selinux) {
5540
                        char *exec_context = mac_selinux_context_net ?: context->selinux_context;
5541

5542
                        if (exec_context) {
5543
                                r = setexeccon(exec_context);
5544
                                if (r < 0) {
5545
                                        if (!context->selinux_context_ignore) {
5546
                                                *exit_status = EXIT_SELINUX_CONTEXT;
5547
                                                return log_exec_error_errno(context, params, r, "Failed to change SELinux context to %s: %m", exec_context);
5548
                                        }
5549
                                        log_exec_debug_errno(context,
5550
                                                             params,
5551
                                                             r,
5552
                                                             "Failed to change SELinux context to %s, ignoring: %m",
5553
                                                             exec_context);
5554
                                }
5555
                        }
5556
                }
5557
#endif
5558

5559
#if HAVE_APPARMOR
5560
                if (use_apparmor && context->apparmor_profile) {
5561
                        r = ASSERT_PTR(sym_aa_change_onexec)(context->apparmor_profile);
5562
                        if (r < 0 && !context->apparmor_profile_ignore) {
5563
                                *exit_status = EXIT_APPARMOR_PROFILE;
5564
                                return log_exec_error_errno(context,
5565
                                                            params,
5566
                                                            errno,
5567
                                                            "Failed to prepare AppArmor profile change to %s: %m",
5568
                                                            context->apparmor_profile);
5569
                        }
5570
                }
5571
#endif
5572

5573
                /* PR_GET_SECUREBITS is not privileged, while PR_SET_SECUREBITS is. So to suppress potential
5574
                 * EPERMs we'll try not to call PR_SET_SECUREBITS unless necessary. Setting securebits
5575
                 * requires CAP_SETPCAP. */
5576
                if (prctl(PR_GET_SECUREBITS) != secure_bits) {
11,086✔
5577
                        /* CAP_SETPCAP is required to set securebits. This capability is raised into the
5578
                         * effective set here.
5579
                         *
5580
                         * The effective set is overwritten during execve() with the following values:
5581
                         *
5582
                         * - ambient set (for non-root processes)
5583
                         *
5584
                         * - (inheritable | bounding) set for root processes)
5585
                         *
5586
                         * Hence there is no security impact to raise it in the effective set before execve
5587
                         */
5588
                        r = capability_gain_cap_setpcap(/* ret_before_caps = */ NULL);
901✔
5589
                        if (r < 0) {
901✔
UNCOV
5590
                                *exit_status = EXIT_CAPABILITIES;
×
5591
                                return log_exec_error_errno(context, params, r, "Failed to gain CAP_SETPCAP for setting secure bits");
×
5592
                        }
5593
                        if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
901✔
UNCOV
5594
                                *exit_status = EXIT_SECUREBITS;
×
5595
                                return log_exec_error_errno(context, params, errno, "Failed to set process secure bits: %m");
×
5596
                        }
5597
                }
5598

5599
                if (context_has_no_new_privileges(context))
11,086✔
5600
                        if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
1,929✔
UNCOV
5601
                                *exit_status = EXIT_NO_NEW_PRIVILEGES;
×
5602
                                return log_exec_error_errno(context, params, errno, "Failed to disable new privileges: %m");
×
5603
                        }
5604

5605
#if HAVE_SECCOMP
5606
                r = apply_address_families(context, params);
11,086✔
5607
                if (r < 0) {
11,086✔
UNCOV
5608
                        *exit_status = EXIT_ADDRESS_FAMILIES;
×
5609
                        return log_exec_error_errno(context, params, r, "Failed to restrict address families: %m");
×
5610
                }
5611

5612
                r = apply_memory_deny_write_execute(context, params);
11,086✔
5613
                if (r < 0) {
11,086✔
UNCOV
5614
                        *exit_status = EXIT_SECCOMP;
×
5615
                        return log_exec_error_errno(context, params, r, "Failed to disable writing to executable memory: %m");
×
5616
                }
5617

5618
                r = apply_restrict_realtime(context, params);
11,086✔
5619
                if (r < 0) {
11,086✔
UNCOV
5620
                        *exit_status = EXIT_SECCOMP;
×
5621
                        return log_exec_error_errno(context, params, r, "Failed to apply realtime restrictions: %m");
×
5622
                }
5623

5624
                r = apply_restrict_suid_sgid(context, params);
11,086✔
5625
                if (r < 0) {
11,086✔
UNCOV
5626
                        *exit_status = EXIT_SECCOMP;
×
5627
                        return log_exec_error_errno(context, params, r, "Failed to apply SUID/SGID restrictions: %m");
×
5628
                }
5629

5630
                r = apply_restrict_namespaces(context, params);
11,086✔
5631
                if (r < 0) {
11,086✔
UNCOV
5632
                        *exit_status = EXIT_SECCOMP;
×
5633
                        return log_exec_error_errno(context, params, r, "Failed to apply namespace restrictions: %m");
×
5634
                }
5635

5636
                r = apply_protect_sysctl(context, params);
11,086✔
5637
                if (r < 0) {
11,086✔
UNCOV
5638
                        *exit_status = EXIT_SECCOMP;
×
5639
                        return log_exec_error_errno(context, params, r, "Failed to apply sysctl restrictions: %m");
×
5640
                }
5641

5642
                r = apply_protect_kernel_modules(context, params);
11,086✔
5643
                if (r < 0) {
11,086✔
UNCOV
5644
                        *exit_status = EXIT_SECCOMP;
×
5645
                        return log_exec_error_errno(context, params, r, "Failed to apply module loading restrictions: %m");
×
5646
                }
5647

5648
                r = apply_protect_kernel_logs(context, params);
11,086✔
5649
                if (r < 0) {
11,086✔
UNCOV
5650
                        *exit_status = EXIT_SECCOMP;
×
5651
                        return log_exec_error_errno(context, params, r, "Failed to apply kernel log restrictions: %m");
×
5652
                }
5653

5654
                r = apply_protect_clock(context, params);
11,086✔
5655
                if (r < 0) {
11,086✔
UNCOV
5656
                        *exit_status = EXIT_SECCOMP;
×
5657
                        return log_exec_error_errno(context, params, r, "Failed to apply clock restrictions: %m");
×
5658
                }
5659

5660
                r = apply_private_devices(context, params);
11,086✔
5661
                if (r < 0) {
11,086✔
UNCOV
5662
                        *exit_status = EXIT_SECCOMP;
×
5663
                        return log_exec_error_errno(context, params, r, "Failed to set up private devices: %m");
×
5664
                }
5665

5666
                r = apply_syscall_archs(context, params);
11,086✔
5667
                if (r < 0) {
11,086✔
UNCOV
5668
                        *exit_status = EXIT_SECCOMP;
×
5669
                        return log_exec_error_errno(context, params, r, "Failed to apply syscall architecture restrictions: %m");
×
5670
                }
5671

5672
                r = apply_lock_personality(context, params);
11,086✔
5673
                if (r < 0) {
11,086✔
UNCOV
5674
                        *exit_status = EXIT_SECCOMP;
×
5675
                        return log_exec_error_errno(context, params, r, "Failed to lock personalities: %m");
×
5676
                }
5677

5678
                r = apply_syscall_log(context, params);
11,086✔
5679
                if (r < 0) {
11,086✔
UNCOV
5680
                        *exit_status = EXIT_SECCOMP;
×
5681
                        return log_exec_error_errno(context, params, r, "Failed to apply system call log filters: %m");
×
5682
                }
5683
#endif
5684

5685
#if HAVE_LIBBPF
5686
                r = apply_restrict_filesystems(context, params);
11,086✔
5687
                if (r < 0) {
11,086✔
UNCOV
5688
                        *exit_status = EXIT_BPF;
×
5689
                        return log_exec_error_errno(context, params, r, "Failed to restrict filesystems: %m");
×
5690
                }
5691
#endif
5692

5693
#if HAVE_SECCOMP
5694
                /* This really should remain as close to the execve() as possible, to make sure our own code is affected
5695
                 * by the filter as little as possible. */
5696
                r = apply_syscall_filter(context, params);
11,086✔
5697
                if (r < 0) {
11,086✔
UNCOV
5698
                        *exit_status = EXIT_SECCOMP;
×
5699
                        return log_exec_error_errno(context, params, r, "Failed to apply system call filters: %m");
×
5700
                }
5701

5702
                if (keep_seccomp_privileges) {
11,086✔
5703
                        /* Restore the capability bounding set with what's expected from the service + the
5704
                         * ambient capabilities hack */
5705
                        if (!cap_test_all(saved_bset)) {
847✔
5706
                                r = capability_bounding_set_drop(saved_bset, /* right_now= */ false);
812✔
5707
                                if (r < 0) {
812✔
UNCOV
5708
                                        *exit_status = EXIT_CAPABILITIES;
×
5709
                                        return log_exec_error_errno(context, params, r, "Failed to drop bset capabilities: %m");
×
5710
                                }
5711
                        }
5712

5713
                        /* Only drop CAP_SYS_ADMIN if it's not in the bounding set, otherwise we'll break
5714
                         * applications that use it. */
5715
                        if (!BIT_SET(saved_bset, CAP_SYS_ADMIN)) {
847✔
5716
                                r = drop_capability(CAP_SYS_ADMIN);
384✔
5717
                                if (r < 0) {
384✔
UNCOV
5718
                                        *exit_status = EXIT_USER;
×
5719
                                        return log_exec_error_errno(context, params, r, "Failed to drop CAP_SYS_ADMIN: %m");
×
5720
                                }
5721
                        }
5722

5723
                        /* Only drop CAP_SETPCAP if it's not in the bounding set, otherwise we'll break
5724
                         * applications that use it. */
5725
                        if (!BIT_SET(saved_bset, CAP_SETPCAP)) {
847✔
5726
                                r = drop_capability(CAP_SETPCAP);
582✔
5727
                                if (r < 0) {
582✔
UNCOV
5728
                                        *exit_status = EXIT_USER;
×
5729
                                        return log_exec_error_errno(context, params, r, "Failed to drop CAP_SETPCAP: %m");
×
5730
                                }
5731
                        }
5732

5733
                        if (prctl(PR_SET_KEEPCAPS, 0) < 0) {
847✔
UNCOV
5734
                                *exit_status = EXIT_USER;
×
5735
                                return log_exec_error_errno(context, params, errno, "Failed to drop keep capabilities flag: %m");
×
5736
                        }
5737
                }
5738
#endif
5739

5740
        }
5741

5742
        if (!strv_isempty(context->unset_environment)) {
11,086✔
5743
                char **ee = NULL;
44✔
5744

5745
                ee = strv_env_delete(accum_env, 1, context->unset_environment);
44✔
5746
                if (!ee) {
44✔
UNCOV
5747
                        *exit_status = EXIT_MEMORY;
×
5748
                        return log_oom();
5✔
5749
                }
5750

5751
                strv_free_and_replace(accum_env, ee);
44✔
5752
        }
5753

5754
        if (!FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) {
11,086✔
5755
                _cleanup_strv_free_ char **unset_variables = NULL, **bad_variables = NULL;
10,948✔
5756

5757
                r = replace_env_argv(command->argv, accum_env, &replaced_argv, &unset_variables, &bad_variables);
10,948✔
5758
                if (r < 0) {
10,948✔
UNCOV
5759
                        *exit_status = EXIT_MEMORY;
×
5760
                        return log_exec_error_errno(context,
×
5761
                                                    params,
5762
                                                    r,
5763
                                                    "Failed to replace environment variables: %m");
5764
                }
5765
                final_argv = replaced_argv;
10,948✔
5766

5767
                if (!strv_isempty(unset_variables)) {
10,948✔
5768
                        _cleanup_free_ char *ju = strv_join(unset_variables, ", ");
10✔
5769
                        log_exec_warning(context,
15✔
5770
                                         params,
5771
                                         "Referenced but unset environment variable evaluates to an empty string: %s",
5772
                                         strna(ju));
5773
                }
5774

5775
                if (!strv_isempty(bad_variables)) {
10,948✔
UNCOV
5776
                        _cleanup_free_ char *jb = strv_join(bad_variables, ", ");
×
5777
                        log_exec_warning(context,
×
5778
                                         params,
5779
                                         "Invalid environment variable name evaluates to an empty string: %s",
5780
                                         strna(jb));
5781
                }
5782
        } else
5783
                final_argv = command->argv;
138✔
5784

5785
        log_command_line(context, params, "Executing", executable, final_argv);
11,086✔
5786

5787
        /* We have finished with all our initializations. Let's now let the manager know that. From this
5788
         * point on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */
5789

5790
        r = exec_fd_mark_hot(context, params, /* hot= */ true, exit_status);
11,086✔
5791
        if (r < 0)
11,086✔
5792
                return r;
5793

5794
        /* As last thing before the execve(), let's send the handoff timestamp */
5795
        r = send_handoff_timestamp(context, params, exit_status);
11,086✔
5796
        if (r < 0) {
11,086✔
5797
                /* If this handoff timestamp failed, let's undo the marking as hot */
UNCOV
5798
                (void) exec_fd_mark_hot(context, params, /* hot= */ false, /* reterr_exit_status= */ NULL);
×
5799
                return r;
5800
        }
5801

5802
        /* NB: we leave executable_fd, exec_fd, handoff_timestamp_fd open here. This is safe, because they
5803
         * have O_CLOEXEC set, and the execve() below will thus automatically close them. In fact, for
5804
         * exec_fd this is pretty much the whole raison d'etre. */
5805

5806
        r = fexecve_or_execve(executable_fd, executable, final_argv, accum_env);
11,086✔
5807

5808
        /* The execve() failed, let's undo the marking as hot */
5809
        (void) exec_fd_mark_hot(context, params, /* hot= */ false, /* reterr_exit_status= */ NULL);
3✔
5810

5811
        *exit_status = EXIT_EXEC;
3✔
5812
        return log_exec_error_errno(context, params, r, "Failed to execute %s: %m", executable);
9✔
5813
}
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