execute.c 57.5 KB
Newer Older
1
2
/*-*- Mode: C; c-basic-offset: 8 -*-*/

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/***
  This file is part of systemd.

  Copyright 2010 Lennart Poettering

  systemd is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  systemd is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/

22
#include <assert.h>
23
24
25
26
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
Lennart Poettering's avatar
Lennart Poettering committed
27
#include <string.h>
28
#include <signal.h>
29
30
#include <sys/socket.h>
#include <sys/un.h>
31
#include <sys/prctl.h>
32
#include <linux/sched.h>
33
34
#include <sys/types.h>
#include <sys/stat.h>
35
36
#include <grp.h>
#include <pwd.h>
37
#include <sys/mount.h>
Kay Sievers's avatar
Kay Sievers committed
38
#include <linux/fs.h>
39

40
41
42
43
#ifdef HAVE_PAM
#include <security/pam_appl.h>
#endif

44
45
46
47
#include "execute.h"
#include "strv.h"
#include "macro.h"
#include "util.h"
48
#include "log.h"
49
#include "ioprio.h"
50
#include "securebits.h"
51
#include "cgroup.h"
52
#include "namespace.h"
53
#include "tcpwrap.h"
54

55
56
57
/* This assumes there is a 'tty' group */
#define TTY_MODE 0620

58
59
60
61
62
63
static int shift_fds(int fds[], unsigned n_fds) {
        int start, restart_from;

        if (n_fds <= 0)
                return 0;

64
65
        /* Modifies the fds array! (sorts it) */

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
        assert(fds);

        start = 0;
        for (;;) {
                int i;

                restart_from = -1;

                for (i = start; i < (int) n_fds; i++) {
                        int nfd;

                        /* Already at right index? */
                        if (fds[i] == i+3)
                                continue;

                        if ((nfd = fcntl(fds[i], F_DUPFD, i+3)) < 0)
                                return -errno;

Lennart Poettering's avatar
Lennart Poettering committed
84
                        close_nointr_nofail(fds[i]);
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
                        fds[i] = nfd;

                        /* Hmm, the fd we wanted isn't free? Then
                         * let's remember that and try again from here*/
                        if (nfd != i+3 && restart_from < 0)
                                restart_from = i;
                }

                if (restart_from < 0)
                        break;

                start = restart_from;
        }

        return 0;
}

102
static int flags_fds(const int fds[], unsigned n_fds, bool nonblock) {
103
        unsigned i;
104
        int r;
105
106
107
108
109
110

        if (n_fds <= 0)
                return 0;

        assert(fds);

111
        /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
112
113
114

        for (i = 0; i < n_fds; i++) {

115
116
                if ((r = fd_nonblock(fds[i], nonblock)) < 0)
                        return r;
117

118
119
120
                /* We unconditionally drop FD_CLOEXEC from the fds,
                 * since after all we want to pass these fds to our
                 * children */
121

122
123
                if ((r = fd_cloexec(fds[i], false)) < 0)
                        return r;
124
125
126
127
128
        }

        return 0;
}

Lennart Poettering's avatar
Lennart Poettering committed
129
130
131
132
133
134
135
136
137
138
139
static const char *tty_path(const ExecContext *context) {
        assert(context);

        if (context->tty_path)
                return context->tty_path;

        return "/dev/console";
}

static int open_null_as(int flags, int nfd) {
        int fd, r;
140

Lennart Poettering's avatar
Lennart Poettering committed
141
        assert(nfd >= 0);
142

Lennart Poettering's avatar
Lennart Poettering committed
143
        if ((fd = open("/dev/null", flags|O_NOCTTY)) < 0)
144
145
                return -errno;

Lennart Poettering's avatar
Lennart Poettering committed
146
147
        if (fd != nfd) {
                r = dup2(fd, nfd) < 0 ? -errno : nfd;
Lennart Poettering's avatar
Lennart Poettering committed
148
                close_nointr_nofail(fd);
Lennart Poettering's avatar
Lennart Poettering committed
149
150
        } else
                r = nfd;
151

Lennart Poettering's avatar
Lennart Poettering committed
152
        return r;
153
154
}

Lennart Poettering's avatar
Lennart Poettering committed
155
156
157
158
159
160
static int connect_logger_as(const ExecContext *context, ExecOutput output, const char *ident, int nfd) {
        int fd, r;
        union {
                struct sockaddr sa;
                struct sockaddr_un un;
        } sa;
161
162

        assert(context);
Lennart Poettering's avatar
Lennart Poettering committed
163
164
165
        assert(output < _EXEC_OUTPUT_MAX);
        assert(ident);
        assert(nfd >= 0);
166

Lennart Poettering's avatar
Lennart Poettering committed
167
168
        if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
                return -errno;
169

Lennart Poettering's avatar
Lennart Poettering committed
170
171
172
        zero(sa);
        sa.sa.sa_family = AF_UNIX;
        strncpy(sa.un.sun_path+1, LOGGER_SOCKET, sizeof(sa.un.sun_path)-1);
173

174
        if (connect(fd, &sa.sa, sizeof(sa_family_t) + 1 + sizeof(LOGGER_SOCKET) - 1) < 0) {
Lennart Poettering's avatar
Lennart Poettering committed
175
176
177
                close_nointr_nofail(fd);
                return -errno;
        }
178

Lennart Poettering's avatar
Lennart Poettering committed
179
180
181
182
        if (shutdown(fd, SHUT_RD) < 0) {
                close_nointr_nofail(fd);
                return -errno;
        }
183

Lennart Poettering's avatar
Lennart Poettering committed
184
185
186
187
188
189
190
191
192
193
194
        /* We speak a very simple protocol between log server
         * and client: one line for the log destination (kmsg
         * or syslog), followed by the priority field,
         * followed by the process name. Since we replaced
         * stdin/stderr we simple use stdio to write to
         * it. Note that we use stderr, to minimize buffer
         * flushing issues. */

        dprintf(fd,
                "%s\n"
                "%i\n"
195
196
                "%s\n"
                "%i\n",
197
                output == EXEC_OUTPUT_KMSG ? "kmsg" : "syslog",
Lennart Poettering's avatar
Lennart Poettering committed
198
                context->syslog_priority,
199
                context->syslog_identifier ? context->syslog_identifier : ident,
200
                context->syslog_level_prefix);
Lennart Poettering's avatar
Lennart Poettering committed
201
202
203

        if (fd != nfd) {
                r = dup2(fd, nfd) < 0 ? -errno : nfd;
Lennart Poettering's avatar
Lennart Poettering committed
204
                close_nointr_nofail(fd);
Lennart Poettering's avatar
Lennart Poettering committed
205
206
        } else
                r = nfd;
207

Lennart Poettering's avatar
Lennart Poettering committed
208
209
210
211
        return r;
}
static int open_terminal_as(const char *path, mode_t mode, int nfd) {
        int fd, r;
212

Lennart Poettering's avatar
Lennart Poettering committed
213
214
        assert(path);
        assert(nfd >= 0);
215

Lennart Poettering's avatar
Lennart Poettering committed
216
217
        if ((fd = open_terminal(path, mode | O_NOCTTY)) < 0)
                return fd;
218

Lennart Poettering's avatar
Lennart Poettering committed
219
220
221
222
223
        if (fd != nfd) {
                r = dup2(fd, nfd) < 0 ? -errno : nfd;
                close_nointr_nofail(fd);
        } else
                r = nfd;
224

Lennart Poettering's avatar
Lennart Poettering committed
225
226
        return r;
}
227

Lennart Poettering's avatar
Lennart Poettering committed
228
229
230
231
232
233
static bool is_terminal_input(ExecInput i) {
        return
                i == EXEC_INPUT_TTY ||
                i == EXEC_INPUT_TTY_FORCE ||
                i == EXEC_INPUT_TTY_FAIL;
}
234

235
236
237
238
static int fixup_input(ExecInput std_input, int socket_fd, bool apply_tty_stdin) {

        if (is_terminal_input(std_input) && !apply_tty_stdin)
                return EXEC_INPUT_NULL;
239

240
        if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
241
242
                return EXEC_INPUT_NULL;

243
        return std_input;
244
245
}

246
static int fixup_output(ExecOutput std_output, int socket_fd) {
247

248
        if (std_output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
249
250
                return EXEC_OUTPUT_INHERIT;

251
        return std_output;
252
253
}

254
static int setup_input(const ExecContext *context, int socket_fd, bool apply_tty_stdin) {
255
256
257
258
        ExecInput i;

        assert(context);

259
        i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
260
261

        switch (i) {
262

Lennart Poettering's avatar
Lennart Poettering committed
263
264
265
266
267
268
269
        case EXEC_INPUT_NULL:
                return open_null_as(O_RDONLY, STDIN_FILENO);

        case EXEC_INPUT_TTY:
        case EXEC_INPUT_TTY_FORCE:
        case EXEC_INPUT_TTY_FAIL: {
                int fd, r;
270

Lennart Poettering's avatar
Lennart Poettering committed
271
272
                if ((fd = acquire_terminal(
                                     tty_path(context),
273
                                     i == EXEC_INPUT_TTY_FAIL,
274
275
                                     i == EXEC_INPUT_TTY_FORCE,
                                     false)) < 0)
Lennart Poettering's avatar
Lennart Poettering committed
276
277
278
279
                        return fd;

                if (fd != STDIN_FILENO) {
                        r = dup2(fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
280
                        close_nointr_nofail(fd);
Lennart Poettering's avatar
Lennart Poettering committed
281
282
283
284
285
286
                } else
                        r = STDIN_FILENO;

                return r;
        }

287
288
289
        case EXEC_INPUT_SOCKET:
                return dup2(socket_fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;

Lennart Poettering's avatar
Lennart Poettering committed
290
291
292
293
294
        default:
                assert_not_reached("Unknown input type");
        }
}

295
static int setup_output(const ExecContext *context, int socket_fd, const char *ident, bool apply_tty_stdin) {
296
297
298
        ExecOutput o;
        ExecInput i;

Lennart Poettering's avatar
Lennart Poettering committed
299
300
301
        assert(context);
        assert(ident);

302
        i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
303
        o = fixup_output(context->std_output, socket_fd);
304

Lennart Poettering's avatar
Lennart Poettering committed
305
306
        /* This expects the input is already set up */

307
        switch (o) {
308

Lennart Poettering's avatar
Lennart Poettering committed
309
310
        case EXEC_OUTPUT_INHERIT:

311
                /* If the input is connected to anything that's not a /dev/null, inherit that... */
312
                if (i != EXEC_INPUT_NULL)
Lennart Poettering's avatar
Lennart Poettering committed
313
                        return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
314

315
316
317
                /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
                if (getppid() != 1)
                        return STDOUT_FILENO;
318

319
320
                /* We need to open /dev/null here anew, to get the
                 * right access mode. So we fall through */
Lennart Poettering's avatar
Lennart Poettering committed
321
322
323
324

        case EXEC_OUTPUT_NULL:
                return open_null_as(O_WRONLY, STDOUT_FILENO);

325
326
        case EXEC_OUTPUT_TTY:
                if (is_terminal_input(i))
Lennart Poettering's avatar
Lennart Poettering committed
327
328
329
330
                        return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;

                /* We don't reset the terminal if this is just about output */
                return open_terminal_as(tty_path(context), O_WRONLY, STDOUT_FILENO);
331

Lennart Poettering's avatar
Lennart Poettering committed
332
        case EXEC_OUTPUT_SYSLOG:
333
        case EXEC_OUTPUT_KMSG:
334
335
336
337
338
                return connect_logger_as(context, o, ident, STDOUT_FILENO);

        case EXEC_OUTPUT_SOCKET:
                assert(socket_fd >= 0);
                return dup2(socket_fd, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
Lennart Poettering's avatar
Lennart Poettering committed
339

340
341
        default:
                assert_not_reached("Unknown output type");
342
        }
343
344
}

345
static int setup_error(const ExecContext *context, int socket_fd, const char *ident, bool apply_tty_stdin) {
346
347
348
        ExecOutput o, e;
        ExecInput i;

349
        assert(context);
350
        assert(ident);
351

352
        i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
353
354
        o = fixup_output(context->std_output, socket_fd);
        e = fixup_output(context->std_error, socket_fd);
355

Lennart Poettering's avatar
Lennart Poettering committed
356
        /* This expects the input and output are already set up */
357

Lennart Poettering's avatar
Lennart Poettering committed
358
359
        /* Don't change the stderr file descriptor if we inherit all
         * the way and are not on a tty */
360
361
        if (e == EXEC_OUTPUT_INHERIT &&
            o == EXEC_OUTPUT_INHERIT &&
362
            i == EXEC_INPUT_NULL &&
363
            getppid () != 1)
Lennart Poettering's avatar
Lennart Poettering committed
364
                return STDERR_FILENO;
365

Lennart Poettering's avatar
Lennart Poettering committed
366
        /* Duplicate form stdout if possible */
367
        if (e == o || e == EXEC_OUTPUT_INHERIT)
Lennart Poettering's avatar
Lennart Poettering committed
368
                return dup2(STDOUT_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
369

370
        switch (e) {
Lennart Poettering's avatar
Lennart Poettering committed
371
372
373
374
375

        case EXEC_OUTPUT_NULL:
                return open_null_as(O_WRONLY, STDERR_FILENO);

        case EXEC_OUTPUT_TTY:
376
                if (is_terminal_input(i))
Lennart Poettering's avatar
Lennart Poettering committed
377
378
379
380
381
382
                        return dup2(STDIN_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;

                /* We don't reset the terminal if this is just about output */
                return open_terminal_as(tty_path(context), O_WRONLY, STDERR_FILENO);

        case EXEC_OUTPUT_SYSLOG:
383
        case EXEC_OUTPUT_KMSG:
384
385
386
387
388
                return connect_logger_as(context, e, ident, STDERR_FILENO);

        case EXEC_OUTPUT_SOCKET:
                assert(socket_fd >= 0);
                return dup2(socket_fd, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
389
390

        default:
Lennart Poettering's avatar
Lennart Poettering committed
391
                assert_not_reached("Unknown error type");
392
        }
393
394
}

395
396
397
398
399
400
static int chown_terminal(int fd, uid_t uid) {
        struct stat st;

        assert(fd >= 0);

        /* This might fail. What matters are the results. */
Lennart Poettering's avatar
Lennart Poettering committed
401
402
        (void) fchown(fd, uid, -1);
        (void) fchmod(fd, TTY_MODE);
403
404
405
406

        if (fstat(fd, &st) < 0)
                return -errno;

407
        if (st.st_uid != uid || (st.st_mode & 0777) != TTY_MODE)
408
409
410
411
412
                return -EPERM;

        return 0;
}

Lennart Poettering's avatar
Lennart Poettering committed
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
static int setup_confirm_stdio(const ExecContext *context,
                               int *_saved_stdin,
                               int *_saved_stdout) {
        int fd = -1, saved_stdin, saved_stdout = -1, r;

        assert(context);
        assert(_saved_stdin);
        assert(_saved_stdout);

        /* This returns positive EXIT_xxx return values instead of
         * negative errno style values! */

        if ((saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3)) < 0)
                return EXIT_STDIN;

        if ((saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3)) < 0) {
                r = EXIT_STDOUT;
                goto fail;
        }

        if ((fd = acquire_terminal(
                             tty_path(context),
                             context->std_input == EXEC_INPUT_TTY_FAIL,
436
437
                             context->std_input == EXEC_INPUT_TTY_FORCE,
                             false)) < 0) {
Lennart Poettering's avatar
Lennart Poettering committed
438
439
440
441
                r = EXIT_STDIN;
                goto fail;
        }

442
443
444
445
446
        if (chown_terminal(fd, getuid()) < 0) {
                r = EXIT_STDIN;
                goto fail;
        }

Lennart Poettering's avatar
Lennart Poettering committed
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
        if (dup2(fd, STDIN_FILENO) < 0) {
                r = EXIT_STDIN;
                goto fail;
        }

        if (dup2(fd, STDOUT_FILENO) < 0) {
                r = EXIT_STDOUT;
                goto fail;
        }

        if (fd >= 2)
                close_nointr_nofail(fd);

        *_saved_stdin = saved_stdin;
        *_saved_stdout = saved_stdout;

        return 0;

fail:
        if (saved_stdout >= 0)
                close_nointr_nofail(saved_stdout);

        if (saved_stdin >= 0)
                close_nointr_nofail(saved_stdin);

        if (fd >= 0)
                close_nointr_nofail(fd);

        return r;
}

Lennart Poettering's avatar
Lennart Poettering committed
478
static int restore_confirm_stdio(const ExecContext *context,
Lennart Poettering's avatar
Lennart Poettering committed
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
                                 int *saved_stdin,
                                 int *saved_stdout,
                                 bool *keep_stdin,
                                 bool *keep_stdout) {

        assert(context);
        assert(saved_stdin);
        assert(*saved_stdin >= 0);
        assert(saved_stdout);
        assert(*saved_stdout >= 0);

        /* This returns positive EXIT_xxx return values instead of
         * negative errno style values! */

        if (is_terminal_input(context->std_input)) {

                /* The service wants terminal input. */

                *keep_stdin = true;
                *keep_stdout =
                        context->std_output == EXEC_OUTPUT_INHERIT ||
                        context->std_output == EXEC_OUTPUT_TTY;

        } else {
                /* If the service doesn't want a controlling terminal,
                 * then we need to get rid entirely of what we have
                 * already. */

                if (release_terminal() < 0)
                        return EXIT_STDIN;

                if (dup2(*saved_stdin, STDIN_FILENO) < 0)
                        return EXIT_STDIN;

                if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
                        return EXIT_STDOUT;

                *keep_stdout = *keep_stdin = false;
        }

        return 0;
}

522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
static int get_group_creds(const char *groupname, gid_t *gid) {
        struct group *g;
        unsigned long lu;

        assert(groupname);
        assert(gid);

        /* We enforce some special rules for gid=0: in order to avoid
         * NSS lookups for root we hardcode its data. */

        if (streq(groupname, "root") || streq(groupname, "0")) {
                *gid = 0;
                return 0;
        }

        if (safe_atolu(groupname, &lu) >= 0) {
                errno = 0;
                g = getgrgid((gid_t) lu);
        } else {
                errno = 0;
                g = getgrnam(groupname);
        }

        if (!g)
                return errno != 0 ? -errno : -ESRCH;

        *gid = g->gr_gid;
        return 0;
}

static int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
        struct passwd *p;
        unsigned long lu;

        assert(username);
        assert(*username);
        assert(uid);
        assert(gid);
        assert(home);

        /* We enforce some special rules for uid=0: in order to avoid
         * NSS lookups for root we hardcode its data. */

        if (streq(*username, "root") || streq(*username, "0")) {
                *username = "root";
                *uid = 0;
                *gid = 0;
                *home = "/root";
                return 0;
        }

        if (safe_atolu(*username, &lu) >= 0) {
                errno = 0;
                p = getpwuid((uid_t) lu);

                /* If there are multiple users with the same id, make
                 * sure to leave $USER to the configured value instead
                 * of the first occurence in the database. However if
                 * the uid was configured by a numeric uid, then let's
                 * pick the real username from /etc/passwd. */
                if (*username && p)
                        *username = p->pw_name;
        } else {
                errno = 0;
                p = getpwnam(*username);
        }

        if (!p)
                return errno != 0 ? -errno : -ESRCH;

        *uid = p->pw_uid;
        *gid = p->pw_gid;
        *home = p->pw_dir;
        return 0;
}

static int enforce_groups(const ExecContext *context, const char *username, gid_t gid) {
        bool keep_groups = false;
        int r;

        assert(context);

        /* Lookup and ser GID and supplementary group list. Here too
         * we avoid NSS lookups for gid=0. */

        if (context->group || username) {

                if (context->group)
                        if ((r = get_group_creds(context->group, &gid)) < 0)
                                return r;

                /* First step, initialize groups from /etc/groups */
                if (username && gid != 0) {
                        if (initgroups(username, gid) < 0)
                                return -errno;

                        keep_groups = true;
                }

                /* Second step, set our gids */
                if (setresgid(gid, gid, gid) < 0)
                        return -errno;
        }

        if (context->supplementary_groups) {
                int ngroups_max, k;
                gid_t *gids;
                char **i;

                /* Final step, initialize any manually set supplementary groups */
                ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);

                if (!(gids = new(gid_t, ngroups_max)))
                        return -ENOMEM;

                if (keep_groups) {
                        if ((k = getgroups(ngroups_max, gids)) < 0) {
                                free(gids);
                                return -errno;
                        }
                } else
                        k = 0;

                STRV_FOREACH(i, context->supplementary_groups) {

                        if (k >= ngroups_max) {
                                free(gids);
                                return -E2BIG;
                        }

                        if ((r = get_group_creds(*i, gids+k)) < 0) {
                                free(gids);
                                return r;
                        }

                        k++;
                }

                if (setgroups(k, gids) < 0) {
                        free(gids);
                        return -errno;
                }

                free(gids);
        }

        return 0;
}

static int enforce_user(const ExecContext *context, uid_t uid) {
        int r;
        assert(context);

        /* Sets (but doesn't lookup) the uid and make sure we keep the
         * capabilities while doing so. */

        if (context->capabilities) {
                cap_t d;
                static const cap_value_t bits[] = {
                        CAP_SETUID,   /* Necessary so that we can run setresuid() below */
                        CAP_SETPCAP   /* Necessary so that we can set PR_SET_SECUREBITS later on */
                };

                /* First step: If we need to keep capabilities but
                 * drop privileges we need to make sure we keep our
                 * caps, whiel we drop priviliges. */
688
689
690
691
692
693
694
                if (uid != 0) {
                        int sb = context->secure_bits|SECURE_KEEP_CAPS;

                        if (prctl(PR_GET_SECUREBITS) != sb)
                                if (prctl(PR_SET_SECUREBITS, sb) < 0)
                                        return -errno;
                }
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729

                /* Second step: set the capabilites. This will reduce
                 * the capabilities to the minimum we need. */

                if (!(d = cap_dup(context->capabilities)))
                        return -errno;

                if (cap_set_flag(d, CAP_EFFECTIVE, ELEMENTSOF(bits), bits, CAP_SET) < 0 ||
                    cap_set_flag(d, CAP_PERMITTED, ELEMENTSOF(bits), bits, CAP_SET) < 0) {
                        r = -errno;
                        cap_free(d);
                        return r;
                }

                if (cap_set_proc(d) < 0) {
                        r = -errno;
                        cap_free(d);
                        return r;
                }

                cap_free(d);
        }

        /* Third step: actually set the uids */
        if (setresuid(uid, uid, uid) < 0)
                return -errno;

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

        return 0;
}

730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
#ifdef HAVE_PAM

static int null_conv(
                int num_msg,
                const struct pam_message **msg,
                struct pam_response **resp,
                void *appdata_ptr) {

        /* We don't support conversations */

        return PAM_CONV_ERR;
}

static int setup_pam(
                const char *name,
                const char *user,
                const char *tty,
                char ***pam_env,
                int fds[], unsigned n_fds) {

        static const struct pam_conv conv = {
                .conv = null_conv,
                .appdata_ptr = NULL
        };

        pam_handle_t *handle = NULL;
        sigset_t ss, old_ss;
        int pam_code = PAM_SUCCESS;
        char **e = NULL;
        bool close_session = false;
        pid_t pam_pid = 0, parent_pid;

        assert(name);
        assert(user);
        assert(pam_env);

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

        if ((pam_code = pam_start(name, user, &conv, &handle)) != PAM_SUCCESS) {
                handle = NULL;
                goto fail;
        }

        if (tty)
                if ((pam_code = pam_set_item(handle, PAM_TTY, tty)) != PAM_SUCCESS)
                        goto fail;

        if ((pam_code = pam_acct_mgmt(handle, PAM_SILENT)) != PAM_SUCCESS)
                goto fail;

        if ((pam_code = pam_open_session(handle, PAM_SILENT)) != PAM_SUCCESS)
                goto fail;

        close_session = true;

        if ((pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | PAM_SILENT)) != PAM_SUCCESS)
                goto fail;

        if ((!(e = pam_getenvlist(handle)))) {
                pam_code = PAM_BUF_ERR;
                goto fail;
        }

        /* Block SIGTERM, so that we know that it won't get lost in
         * the child */
        if (sigemptyset(&ss) < 0 ||
            sigaddset(&ss, SIGTERM) < 0 ||
            sigprocmask(SIG_BLOCK, &ss, &old_ss) < 0)
                goto fail;

        parent_pid = getpid();

        if ((pam_pid = fork()) < 0)
                goto fail;

        if (pam_pid == 0) {
                int sig;
                int r = EXIT_PAM;

                /* The child's job is to reset the PAM session on
                 * termination */

                /* This string must fit in 10 chars (i.e. the length
                 * of "/sbin/init") */
                rename_process("sd:pam");

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

                /* Wait until our parent died. This will most likely
                 * not work since the kernel does not allow
                 * unpriviliged paretns kill their priviliged children
                 * this way. We rely on the control groups kill logic
                 * to do the rest for us. */
                if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
                        goto child_finish;

                /* Check if our parent process might already have
                 * died? */
                if (getppid() == parent_pid) {
                        if (sigwait(&ss, &sig) < 0)
                                goto child_finish;

                        assert(sig == SIGTERM);
                }

                /* Only if our parent died we'll end the session */
                if (getppid() != parent_pid)
                        if ((pam_code = pam_close_session(handle, PAM_DATA_SILENT)) != PAM_SUCCESS)
                                goto child_finish;

                r = 0;

        child_finish:
                pam_end(handle, pam_code | PAM_DATA_SILENT);
                _exit(r);
        }

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

        /* Unblock SIGSUR1 again in the parent */
        if (sigprocmask(SIG_SETMASK, &old_ss, NULL) < 0)
                goto fail;

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

        return 0;

fail:
        if (handle) {
                if (close_session)
                        pam_code = pam_close_session(handle, PAM_DATA_SILENT);

                pam_end(handle, pam_code | PAM_DATA_SILENT);
        }

        strv_free(e);

        closelog();

        if (pam_pid > 1)
                kill(pam_pid, SIGTERM);

        return EXIT_PAM;
}
#endif

888
int exec_spawn(ExecCommand *command,
889
               char **argv,
890
               const ExecContext *context,
891
               int fds[], unsigned n_fds,
892
               char **environment,
893
894
               bool apply_permissions,
               bool apply_chroot,
895
               bool apply_tty_stdin,
Lennart Poettering's avatar
Lennart Poettering committed
896
               bool confirm_spawn,
897
               CGroupBonding *cgroup_bondings,
898
899
               pid_t *ret) {

900
        pid_t pid;
901
        int r;
902
        char *line;
903
        int socket_fd;
904

905
906
907
        assert(command);
        assert(context);
        assert(ret);
908
909
        assert(fds || n_fds <= 0);

910
911
912
913
914
915
916
917
918
919
920
921
922
923
        if (context->std_input == EXEC_INPUT_SOCKET ||
            context->std_output == EXEC_OUTPUT_SOCKET ||
            context->std_error == EXEC_OUTPUT_SOCKET) {

                if (n_fds != 1)
                        return -EINVAL;

                socket_fd = fds[0];

                fds = NULL;
                n_fds = 0;
        } else
                socket_fd = -1;

924
925
926
927
        if (!argv)
                argv = command->argv;

        if (!(line = exec_command_line(argv)))
928
929
930
931
                return -ENOMEM;

        log_debug("About to execute: %s", line);
        free(line);
932

933
934
935
936
        if (cgroup_bondings)
                if ((r = cgroup_bonding_realize_list(cgroup_bondings)))
                        return r;

937
938
939
940
        if ((pid = fork()) < 0)
                return -errno;

        if (pid == 0) {
941
                int i;
942
                sigset_t ss;
943
944
945
                const char *username = NULL, *home = NULL;
                uid_t uid = (uid_t) -1;
                gid_t gid = (gid_t) -1;
946
                char **our_env = NULL, **pam_env = NULL, **final_env = NULL, **final_argv = NULL;
947
                unsigned n_env = 0;
Lennart Poettering's avatar
Lennart Poettering committed
948
949
                int saved_stdout = -1, saved_stdin = -1;
                bool keep_stdout = false, keep_stdin = false;
950

951
                /* child */
952

953
954
955
956
                /* This string must fit in 10 chars (i.e. the length
                 * of "/sbin/init") */
                rename_process("sd:exec");

Lennart Poettering's avatar
Lennart Poettering committed
957
958
959
960
961
962
                /* We reset exactly these signals, since they are the
                 * only ones we set to SIG_IGN in the main daemon. All
                 * others we leave untouched because we set them to
                 * SIG_DFL or a valid handler initially, both of which
                 * will be demoted to SIG_DFL. */
                default_signals(SIGNALS_CRASH_HANDLER,
963
                                SIGNALS_IGNORE, -1);
964

965
966
967
968
969
970
                if (sigemptyset(&ss) < 0 ||
                    sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
                        r = EXIT_SIGNAL_MASK;
                        goto fail;
                }

971
972
973
974
975
976
977
978
                /* Close sockets very early to make sure we don' block
                 * init reexecution because it cannot bind its sockets
                 * or so */
                if (close_all_fds(fds, n_fds) < 0) {
                        r = EXIT_FDS;
                        goto fail;
                }

979
                if (!context->same_pgrp)
980
981
982
983
                        if (setsid() < 0) {
                                r = EXIT_SETSID;
                                goto fail;
                        }
Lennart Poettering's avatar
Lennart Poettering committed
984

985
986
987
988
989
990
991
992
993
994
995
996
                if (context->tcpwrap_name) {
                        if (socket_fd >= 0)
                                if (!socket_tcpwrap(socket_fd, context->tcpwrap_name)) {
                                        r = EXIT_TCPWRAP;
                                        goto fail;
                                }

                        for (i = 0; i < (int) n_fds; i++) {
                                if (!socket_tcpwrap(fds[i], context->tcpwrap_name)) {
                                        r = EXIT_TCPWRAP;
                                        goto fail;
                                }
997
                        }
998
                }
999

1000
                /* We skip the confirmation step if we shall not apply the TTY */
For faster browsing, not all history is shown. View entire blame