forked from containers/bubblewrap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bubblewrap.c
3369 lines (2809 loc) · 104 KB
/
bubblewrap.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
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
478
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
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
688
689
690
691
692
693
694
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
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
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* bubblewrap
* Copyright (C) 2016 Alexander Larsson
* SPDX-License-Identifier: LGPL-2.0-or-later
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "config.h"
#include <poll.h>
#include <sched.h>
#include <pwd.h>
#include <grp.h>
#include <ctype.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/eventfd.h>
#include <sys/fsuid.h>
#include <sys/signalfd.h>
#include <sys/capability.h>
#include <sys/prctl.h>
#include <linux/sched.h>
#include <linux/seccomp.h>
#include <linux/filter.h>
#include "utils.h"
#include "network.h"
#include "bind-mount.h"
#ifndef CLONE_NEWCGROUP
#define CLONE_NEWCGROUP 0x02000000 /* New cgroup namespace */
#endif
#ifndef TEMP_FAILURE_RETRY
#define TEMP_FAILURE_RETRY(expression) \
(__extension__ \
({ long int __result; \
do __result = (long int) (expression); \
while (__result == -1L && errno == EINTR); \
__result; }))
#endif
/* We limit the size of a tmpfs to half the architecture's address space,
* to avoid hitting arbitrary limits in the kernel.
* For example, on at least one x86_64 machine, the actual limit seems to be
* 2^64 - 2^12. */
#define MAX_TMPFS_BYTES ((size_t) (SIZE_MAX >> 1))
/* Globals to avoid having to use getuid(), since the uid/gid changes during runtime */
static uid_t real_uid;
static gid_t real_gid;
static uid_t overflow_uid;
static gid_t overflow_gid;
static bool is_privileged; /* See acquire_privs() */
static const char *argv0;
static const char *host_tty_dev;
static int proc_fd = -1;
static const char *opt_exec_label = NULL;
static const char *opt_file_label = NULL;
static bool opt_as_pid_1;
static const char *opt_chdir_path = NULL;
static bool opt_assert_userns_disabled = FALSE;
static bool opt_disable_userns = FALSE;
static bool opt_unshare_user = FALSE;
static bool opt_unshare_user_try = FALSE;
static bool opt_unshare_pid = FALSE;
static bool opt_unshare_ipc = FALSE;
static bool opt_unshare_net = FALSE;
static bool opt_unshare_uts = FALSE;
static bool opt_unshare_cgroup = FALSE;
static bool opt_unshare_cgroup_try = FALSE;
static bool opt_needs_devpts = FALSE;
static bool opt_new_session = FALSE;
static bool opt_die_with_parent = FALSE;
static uid_t opt_sandbox_uid = -1;
static gid_t opt_sandbox_gid = -1;
static int opt_sync_fd = -1;
static int opt_block_fd = -1;
static int opt_userns_block_fd = -1;
static int opt_info_fd = -1;
static int opt_json_status_fd = -1;
static int opt_seccomp_fd = -1;
static const char *opt_sandbox_hostname = NULL;
static char *opt_args_data = NULL; /* owned */
static int opt_userns_fd = -1;
static int opt_userns2_fd = -1;
static int opt_pidns_fd = -1;
static int next_perms = -1;
static size_t next_size_arg = 0;
#define CAP_TO_MASK_0(x) (1L << ((x) & 31))
#define CAP_TO_MASK_1(x) CAP_TO_MASK_0(x - 32)
typedef struct _NsInfo NsInfo;
struct _NsInfo {
const char *name;
bool *do_unshare;
ino_t id;
};
static NsInfo ns_infos[] = {
{"cgroup", &opt_unshare_cgroup, 0},
{"ipc", &opt_unshare_ipc, 0},
{"mnt", NULL, 0},
{"net", &opt_unshare_net, 0},
{"pid", &opt_unshare_pid, 0},
/* user namespace info omitted because it
* is not (yet) valid when we obtain the
* namespace info (get un-shared later) */
{"uts", &opt_unshare_uts, 0},
{NULL, NULL, 0}
};
typedef enum {
SETUP_BIND_MOUNT,
SETUP_RO_BIND_MOUNT,
SETUP_DEV_BIND_MOUNT,
SETUP_MOUNT_PROC,
SETUP_MOUNT_DEV,
SETUP_MOUNT_TMPFS,
SETUP_MOUNT_MQUEUE,
SETUP_MAKE_DIR,
SETUP_MAKE_FILE,
SETUP_MAKE_BIND_FILE,
SETUP_MAKE_RO_BIND_FILE,
SETUP_MAKE_SYMLINK,
SETUP_REMOUNT_RO_NO_RECURSIVE,
SETUP_SET_HOSTNAME,
SETUP_CHMOD,
} SetupOpType;
typedef enum {
NO_CREATE_DEST = (1 << 0),
ALLOW_NOTEXIST = (2 << 0),
} SetupOpFlag;
typedef struct _SetupOp SetupOp;
struct _SetupOp
{
SetupOpType type;
const char *source;
const char *dest;
int fd;
SetupOpFlag flags;
int perms;
size_t size; /* number of bytes, zero means unset/default */
SetupOp *next;
};
typedef struct _LockFile LockFile;
struct _LockFile
{
const char *path;
int fd;
LockFile *next;
};
enum {
PRIV_SEP_OP_DONE,
PRIV_SEP_OP_BIND_MOUNT,
PRIV_SEP_OP_PROC_MOUNT,
PRIV_SEP_OP_TMPFS_MOUNT,
PRIV_SEP_OP_DEVPTS_MOUNT,
PRIV_SEP_OP_MQUEUE_MOUNT,
PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE,
PRIV_SEP_OP_SET_HOSTNAME,
};
typedef struct
{
uint32_t op;
uint32_t flags;
uint32_t perms;
size_t size_arg;
uint32_t arg1_offset;
uint32_t arg2_offset;
} PrivSepOp;
/*
* DEFINE_LINKED_LIST:
* @Type: A struct with a `Type *next` member
* @name: Used to form the names of variables and functions
*
* Define a global linked list of @Type structures, with pointers
* `NAMEs` to the head of the list and `last_NAME` to the tail of the
* list.
*
* A new zero-filled item can be allocated and appended to the list
* by calling `_NAME_append_new()`, which returns the new item.
*/
#define DEFINE_LINKED_LIST(Type, name) \
static Type *name ## s = NULL; \
static Type *last_ ## name = NULL; \
\
static inline Type * \
_ ## name ## _append_new (void) \
{ \
Type *self = xcalloc (sizeof (Type)); \
\
if (last_ ## name != NULL) \
last_ ## name ->next = self; \
else \
name ## s = self; \
\
last_ ## name = self; \
return self; \
}
DEFINE_LINKED_LIST (SetupOp, op)
static SetupOp *
setup_op_new (SetupOpType type)
{
SetupOp *op = _op_append_new ();
op->type = type;
op->fd = -1;
op->flags = 0;
return op;
}
DEFINE_LINKED_LIST (LockFile, lock_file)
static LockFile *
lock_file_new (const char *path)
{
LockFile *lock = _lock_file_append_new ();
lock->path = path;
return lock;
}
typedef struct _SeccompProgram SeccompProgram;
struct _SeccompProgram
{
struct sock_fprog program;
SeccompProgram *next;
};
DEFINE_LINKED_LIST (SeccompProgram, seccomp_program)
static SeccompProgram *
seccomp_program_new (int *fd)
{
SeccompProgram *self = _seccomp_program_append_new ();
cleanup_free char *data = NULL;
size_t len;
data = load_file_data (*fd, &len);
if (data == NULL)
die_with_error ("Can't read seccomp data");
close (*fd);
*fd = -1;
if (len % 8 != 0)
die ("Invalid seccomp data, must be multiple of 8");
self->program.len = len / 8;
self->program.filter = (struct sock_filter *) steal_pointer (&data);
return self;
}
static void
seccomp_programs_apply (void)
{
SeccompProgram *program;
for (program = seccomp_programs; program != NULL; program = program->next)
{
if (prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &program->program) != 0)
{
if (errno == EINVAL)
die ("Unable to set up system call filtering as requested: "
"prctl(PR_SET_SECCOMP) reported EINVAL. "
"(Hint: this requires a kernel configured with "
"CONFIG_SECCOMP and CONFIG_SECCOMP_FILTER.)");
die_with_error ("prctl(PR_SET_SECCOMP)");
}
}
}
static void
usage (int ecode, FILE *out)
{
fprintf (out, "usage: %s [OPTIONS...] [--] COMMAND [ARGS...]\n\n", argv0 ? argv0 : "bwrap");
fprintf (out,
" --help Print this help\n"
" --version Print version\n"
" --args FD Parse NUL-separated args from FD\n"
" --unshare-all Unshare every namespace we support by default\n"
" --share-net Retain the network namespace (can only combine with --unshare-all)\n"
" --unshare-user Create new user namespace (may be automatically implied if not setuid)\n"
" --unshare-user-try Create new user namespace if possible else continue by skipping it\n"
" --unshare-ipc Create new ipc namespace\n"
" --unshare-pid Create new pid namespace\n"
" --unshare-net Create new network namespace\n"
" --unshare-uts Create new uts namespace\n"
" --unshare-cgroup Create new cgroup namespace\n"
" --unshare-cgroup-try Create new cgroup namespace if possible else continue by skipping it\n"
" --userns FD Use this user namespace (cannot combine with --unshare-user)\n"
" --userns2 FD After setup switch to this user namespace, only useful with --userns\n"
" --disable-userns Disable further use of user namespaces inside sandbox\n"
" --assert-userns-disabled Fail unless further use of user namespace inside sandbox is disabled\n"
" --pidns FD Use this pid namespace (as parent namespace if using --unshare-pid)\n"
" --uid UID Custom uid in the sandbox (requires --unshare-user or --userns)\n"
" --gid GID Custom gid in the sandbox (requires --unshare-user or --userns)\n"
" --hostname NAME Custom hostname in the sandbox (requires --unshare-uts)\n"
" --chdir DIR Change directory to DIR\n"
" --clearenv Unset all environment variables\n"
" --setenv VAR VALUE Set an environment variable\n"
" --unsetenv VAR Unset an environment variable\n"
" --lock-file DEST Take a lock on DEST while sandbox is running\n"
" --sync-fd FD Keep this fd open while sandbox is running\n"
" --bind SRC DEST Bind mount the host path SRC on DEST\n"
" --bind-try SRC DEST Equal to --bind but ignores non-existent SRC\n"
" --dev-bind SRC DEST Bind mount the host path SRC on DEST, allowing device access\n"
" --dev-bind-try SRC DEST Equal to --dev-bind but ignores non-existent SRC\n"
" --ro-bind SRC DEST Bind mount the host path SRC readonly on DEST\n"
" --ro-bind-try SRC DEST Equal to --ro-bind but ignores non-existent SRC\n"
" --remount-ro DEST Remount DEST as readonly; does not recursively remount\n"
" --exec-label LABEL Exec label for the sandbox\n"
" --file-label LABEL File label for temporary sandbox content\n"
" --proc DEST Mount new procfs on DEST\n"
" --dev DEST Mount new dev on DEST\n"
" --tmpfs DEST Mount new tmpfs on DEST\n"
" --mqueue DEST Mount new mqueue on DEST\n"
" --dir DEST Create dir at DEST\n"
" --file FD DEST Copy from FD to destination DEST\n"
" --bind-data FD DEST Copy from FD to file which is bind-mounted on DEST\n"
" --ro-bind-data FD DEST Copy from FD to file which is readonly bind-mounted on DEST\n"
" --symlink SRC DEST Create symlink at DEST with target SRC\n"
" --seccomp FD Load and use seccomp rules from FD (not repeatable)\n"
" --add-seccomp-fd FD Load and use seccomp rules from FD (repeatable)\n"
" --block-fd FD Block on FD until some data to read is available\n"
" --userns-block-fd FD Block on FD until the user namespace is ready\n"
" --info-fd FD Write information about the running container to FD\n"
" --json-status-fd FD Write container status to FD as multiple JSON documents\n"
" --new-session Create a new terminal session\n"
" --die-with-parent Kills with SIGKILL child process (COMMAND) when bwrap or bwrap's parent dies.\n"
" --as-pid-1 Do not install a reaper process with PID=1\n"
" --cap-add CAP Add cap CAP when running as privileged user\n"
" --cap-drop CAP Drop cap CAP when running as privileged user\n"
" --perms OCTAL Set permissions of next argument (--bind-data, --file, etc.)\n"
" --size BYTES Set size of next argument (only for --tmpfs)\n"
" --chmod OCTAL PATH Change permissions of PATH (must already exist)\n"
);
exit (ecode);
}
/* If --die-with-parent was specified, use PDEATHSIG to ensure SIGKILL
* is sent to the current process when our parent dies.
*/
static void
handle_die_with_parent (void)
{
if (opt_die_with_parent && prctl (PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0) != 0)
die_with_error ("prctl");
}
static void
block_sigchild (void)
{
sigset_t mask;
int status;
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
if (sigprocmask (SIG_BLOCK, &mask, NULL) == -1)
die_with_error ("sigprocmask");
/* Reap any outstanding zombies that we may have inherited */
while (waitpid (-1, &status, WNOHANG) > 0)
;
}
static void
unblock_sigchild (void)
{
sigset_t mask;
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
if (sigprocmask (SIG_UNBLOCK, &mask, NULL) == -1)
die_with_error ("sigprocmask");
}
/* Closes all fd:s except 0,1,2 and the passed in array of extra fds */
static int
close_extra_fds (void *data, int fd)
{
int *extra_fds = (int *) data;
int i;
for (i = 0; extra_fds[i] != -1; i++)
if (fd == extra_fds[i])
return 0;
if (fd <= 2)
return 0;
close (fd);
return 0;
}
static int
propagate_exit_status (int status)
{
if (WIFEXITED (status))
return WEXITSTATUS (status);
/* The process died of a signal, we can't really report that, but we
* can at least be bash-compatible. The bash manpage says:
* The return value of a simple command is its
* exit status, or 128+n if the command is
* terminated by signal n.
*/
if (WIFSIGNALED (status))
return 128 + WTERMSIG (status);
/* Weird? */
return 255;
}
static void
dump_info (int fd, const char *output, bool exit_on_error)
{
size_t len = strlen (output);
if (write_to_fd (fd, output, len))
{
if (exit_on_error)
die_with_error ("Write to info_fd");
}
}
static void
report_child_exit_status (int exitc, int setup_finished_fd)
{
ssize_t s;
char data[2];
cleanup_free char *output = NULL;
if (opt_json_status_fd == -1 || setup_finished_fd == -1)
return;
s = TEMP_FAILURE_RETRY (read (setup_finished_fd, data, sizeof data));
if (s == -1 && errno != EAGAIN)
die_with_error ("read eventfd");
if (s != 1) // Is 0 if pipe closed before exec, is 2 if closed after exec.
return;
output = xasprintf ("{ \"exit-code\": %i }\n", exitc);
dump_info (opt_json_status_fd, output, FALSE);
close (opt_json_status_fd);
opt_json_status_fd = -1;
close (setup_finished_fd);
}
/* This stays around for as long as the initial process in the app does
* and when that exits it exits, propagating the exit status. We do this
* by having pid 1 in the sandbox detect this exit and tell the monitor
* the exit status via a eventfd. We also track the exit of the sandbox
* pid 1 via a signalfd for SIGCHLD, and exit with an error in this case.
* This is to catch e.g. problems during setup. */
static int
monitor_child (int event_fd, pid_t child_pid, int setup_finished_fd)
{
int res;
uint64_t val;
ssize_t s;
int signal_fd;
sigset_t mask;
struct pollfd fds[2];
int num_fds;
struct signalfd_siginfo fdsi;
int dont_close[] = {-1, -1, -1, -1};
unsigned int j = 0;
int exitc;
pid_t died_pid;
int died_status;
/* Close all extra fds in the monitoring process.
Any passed in fds have been passed on to the child anyway. */
if (event_fd != -1)
dont_close[j++] = event_fd;
if (opt_json_status_fd != -1)
dont_close[j++] = opt_json_status_fd;
if (setup_finished_fd != -1)
dont_close[j++] = setup_finished_fd;
assert (j < sizeof(dont_close)/sizeof(*dont_close));
fdwalk (proc_fd, close_extra_fds, dont_close);
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
signal_fd = signalfd (-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK);
if (signal_fd == -1)
die_with_error ("Can't create signalfd");
num_fds = 1;
fds[0].fd = signal_fd;
fds[0].events = POLLIN;
if (event_fd != -1)
{
fds[1].fd = event_fd;
fds[1].events = POLLIN;
num_fds++;
}
while (1)
{
fds[0].revents = fds[1].revents = 0;
res = poll (fds, num_fds, -1);
if (res == -1 && errno != EINTR)
die_with_error ("poll");
/* Always read from the eventfd first, if pid 2 died then pid 1 often
* dies too, and we could race, reporting that first and we'd lose
* the real exit status. */
if (event_fd != -1)
{
s = read (event_fd, &val, 8);
if (s == -1 && errno != EINTR && errno != EAGAIN)
die_with_error ("read eventfd");
else if (s == 8)
{
exitc = (int) val - 1;
report_child_exit_status (exitc, setup_finished_fd);
return exitc;
}
}
/* We need to read the signal_fd, or it will keep polling as read,
* however we ignore the details as we get them from waitpid
* below anyway */
s = read (signal_fd, &fdsi, sizeof (struct signalfd_siginfo));
if (s == -1 && errno != EINTR && errno != EAGAIN)
die_with_error ("read signalfd");
/* We may actually get several sigchld compressed into one
SIGCHLD, so we have to handle all of them. */
while ((died_pid = waitpid (-1, &died_status, WNOHANG)) > 0)
{
/* We may be getting sigchild from other children too. For instance if
someone created a child process, and then exec:ed bubblewrap. Ignore them */
if (died_pid == child_pid)
{
exitc = propagate_exit_status (died_status);
report_child_exit_status (exitc, setup_finished_fd);
return exitc;
}
}
}
die ("Should not be reached");
return 0;
}
/* This is pid 1 in the app sandbox. It is needed because we're using
* pid namespaces, and someone has to reap zombies in it. We also detect
* when the initial process (pid 2) dies and report its exit status to
* the monitor so that it can return it to the original spawner.
*
* When there are no other processes in the sandbox the wait will return
* ECHILD, and we then exit pid 1 to clean up the sandbox. */
static int
do_init (int event_fd, pid_t initial_pid)
{
int initial_exit_status = 1;
LockFile *lock;
for (lock = lock_files; lock != NULL; lock = lock->next)
{
int fd = open (lock->path, O_RDONLY | O_CLOEXEC);
if (fd == -1)
die_with_error ("Unable to open lock file %s", lock->path);
struct flock l = {
.l_type = F_RDLCK,
.l_whence = SEEK_SET,
.l_start = 0,
.l_len = 0
};
if (fcntl (fd, F_SETLK, &l) < 0)
die_with_error ("Unable to lock file %s", lock->path);
/* Keep fd open to hang on to lock */
lock->fd = fd;
}
/* Optionally bind our lifecycle to that of the caller */
handle_die_with_parent ();
seccomp_programs_apply ();
while (TRUE)
{
pid_t child;
int status;
child = wait (&status);
if (child == initial_pid)
{
initial_exit_status = propagate_exit_status (status);
if(event_fd != -1)
{
uint64_t val;
int res UNUSED;
val = initial_exit_status + 1;
res = write (event_fd, &val, 8);
/* Ignore res, if e.g. the parent died and closed event_fd
we don't want to error out here */
}
}
if (child == -1 && errno != EINTR)
{
if (errno != ECHILD)
die_with_error ("init wait()");
break;
}
}
/* Close FDs. */
for (lock = lock_files; lock != NULL; lock = lock->next)
{
if (lock->fd >= 0)
{
close (lock->fd);
lock->fd = -1;
}
}
return initial_exit_status;
}
#define CAP_TO_MASK_0(x) (1L << ((x) & 31))
#define CAP_TO_MASK_1(x) CAP_TO_MASK_0(x - 32)
/* Set if --cap-add or --cap-drop were used */
static bool opt_cap_add_or_drop_used;
/* The capability set we'll target, used if above is true */
static uint32_t requested_caps[2] = {0, 0};
/* low 32bit caps needed */
/* CAP_SYS_PTRACE is needed to dereference the symlinks in /proc/<pid>/ns/, see namespaces(7) */
#define REQUIRED_CAPS_0 (CAP_TO_MASK_0 (CAP_SYS_ADMIN) | CAP_TO_MASK_0 (CAP_SYS_CHROOT) | CAP_TO_MASK_0 (CAP_NET_ADMIN) | CAP_TO_MASK_0 (CAP_SETUID) | CAP_TO_MASK_0 (CAP_SETGID) | CAP_TO_MASK_0 (CAP_SYS_PTRACE))
/* high 32bit caps needed */
#define REQUIRED_CAPS_1 0
static void
set_required_caps (void)
{
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
/* Drop all non-require capabilities */
data[0].effective = REQUIRED_CAPS_0;
data[0].permitted = REQUIRED_CAPS_0;
data[0].inheritable = 0;
data[1].effective = REQUIRED_CAPS_1;
data[1].permitted = REQUIRED_CAPS_1;
data[1].inheritable = 0;
if (capset (&hdr, data) < 0)
die_with_error ("capset failed");
}
static void
drop_all_caps (bool keep_requested_caps)
{
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
if (keep_requested_caps)
{
/* Avoid calling capset() unless we need to; currently
* systemd-nspawn at least is known to install a seccomp
* policy denying capset() for dubious reasons.
* <https://github.com/projectatomic/bubblewrap/pull/122>
*/
if (!opt_cap_add_or_drop_used && real_uid == 0)
{
assert (!is_privileged);
return;
}
data[0].effective = requested_caps[0];
data[0].permitted = requested_caps[0];
data[0].inheritable = requested_caps[0];
data[1].effective = requested_caps[1];
data[1].permitted = requested_caps[1];
data[1].inheritable = requested_caps[1];
}
if (capset (&hdr, data) < 0)
{
/* While the above logic ensures we don't call capset() for the primary
* process unless configured to do so, we still try to drop privileges for
* the init process unconditionally. Since due to the systemd seccomp
* filter that will fail, let's just ignore it.
*/
if (errno == EPERM && real_uid == 0 && !is_privileged)
return;
else
die_with_error ("capset failed");
}
}
static bool
has_caps (void)
{
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
if (capget (&hdr, data) < 0)
die_with_error ("capget failed");
return data[0].permitted != 0 || data[1].permitted != 0;
}
/* Most of the code here is used both to add caps to the ambient capabilities
* and drop caps from the bounding set. Handle both cases here and add
* drop_cap_bounding_set/set_ambient_capabilities wrappers to facilitate its usage.
*/
static void
prctl_caps (uint32_t *caps, bool do_cap_bounding, bool do_set_ambient)
{
unsigned long cap;
/* We ignore both EINVAL and EPERM, as we are actually relying
* on PR_SET_NO_NEW_PRIVS to ensure the right capabilities are
* available. EPERM in particular can happen with old, buggy
* kernels. See:
* https://github.com/projectatomic/bubblewrap/pull/175#issuecomment-278051373
* https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/security/commoncap.c?id=160da84dbb39443fdade7151bc63a88f8e953077
*/
for (cap = 0; cap <= CAP_LAST_CAP; cap++)
{
bool keep = FALSE;
if (cap < 32)
{
if (CAP_TO_MASK_0 (cap) & caps[0])
keep = TRUE;
}
else
{
if (CAP_TO_MASK_1 (cap) & caps[1])
keep = TRUE;
}
if (keep && do_set_ambient)
{
#ifdef PR_CAP_AMBIENT
int res = prctl (PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, cap, 0, 0);
if (res == -1 && !(errno == EINVAL || errno == EPERM))
die_with_error ("Adding ambient capability %ld", cap);
#else
/* We ignore the EINVAL that results from not having PR_CAP_AMBIENT
* in the current kernel at runtime, so also ignore not having it
* in the current kernel headers at compile-time */
#endif
}
if (!keep && do_cap_bounding)
{
int res = prctl (PR_CAPBSET_DROP, cap, 0, 0, 0);
if (res == -1 && !(errno == EINVAL || errno == EPERM))
die_with_error ("Dropping capability %ld from bounds", cap);
}
}
}
static void
drop_cap_bounding_set (bool drop_all)
{
if (!drop_all)
prctl_caps (requested_caps, TRUE, FALSE);
else
{
uint32_t no_caps[2] = {0, 0};
prctl_caps (no_caps, TRUE, FALSE);
}
}
static void
set_ambient_capabilities (void)
{
if (is_privileged)
return;
prctl_caps (requested_caps, FALSE, TRUE);
}
/* This acquires the privileges that the bwrap will need it to work.
* If bwrap is not setuid, then this does nothing, and it relies on
* unprivileged user namespaces to be used. This case is
* "is_privileged = FALSE".
*
* If bwrap is setuid, then we do things in phases.
* The first part is run as euid 0, but with fsuid as the real user.
* The second part, inside the child, is run as the real user but with
* capabilities.
* And finally we drop all capabilities.
* The reason for the above dance is to avoid having the setup phase
* being able to read files the user can't, while at the same time
* working around various kernel issues. See below for details.
*/
static void
acquire_privs (void)
{
uid_t euid, new_fsuid;
euid = geteuid ();
/* Are we setuid ? */
if (real_uid != euid)
{
if (euid != 0)
die ("Unexpected setuid user %d, should be 0", euid);
is_privileged = TRUE;
/* We want to keep running as euid=0 until at the clone()
* operation because doing so will make the user namespace be
* owned by root, which makes it not ptrace:able by the user as
* it otherwise would be. After that we will run fully as the
* user, which is necessary e.g. to be able to read from a fuse
* mount from the user.
*
* However, we don't want to accidentally mis-use euid=0 for
* escalated filesystem access before the clone(), so we set
* fsuid to the uid.
*/
if (setfsuid (real_uid) < 0)
die_with_error ("Unable to set fsuid");
/* setfsuid can't properly report errors, check that it worked (as per manpage) */
new_fsuid = setfsuid (-1);
if (new_fsuid != real_uid)
die ("Unable to set fsuid (was %d)", (int)new_fsuid);
/* We never need capabilities after execve(), so lets drop everything from the bounding set */
drop_cap_bounding_set (TRUE);
/* Keep only the required capabilities for setup */
set_required_caps ();
}
else if (real_uid != 0 && has_caps ())
{
/* We have some capabilities in the non-setuid case, which should not happen.
Probably caused by the binary being setcap instead of setuid which we
don't support anymore */
die ("Unexpected capabilities but not setuid, old file caps config?");
}
else if (real_uid == 0)
{
/* If our uid is 0, default to inheriting all caps; the caller
* can drop them via --cap-drop. This is used by at least rpm-ostree.
* Note this needs to happen before the argument parsing of --cap-drop.
*/
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
if (capget (&hdr, data) < 0)
die_with_error ("capget (for uid == 0) failed");
requested_caps[0] = data[0].effective;
requested_caps[1] = data[1].effective;
}
/* Else, we try unprivileged user namespaces */
}
/* This is called once we're inside the namespace */
static void
switch_to_user_with_privs (void)
{
/* If we're in a new user namespace, we got back the bounding set, clear it again */
if (opt_unshare_user || opt_userns_fd != -1)
drop_cap_bounding_set (FALSE);
/* If we switched to a new user namespace it may allow other uids/gids, so switch to the target one */
if (opt_userns_fd != -1)
{
if (opt_sandbox_uid != real_uid && setuid (opt_sandbox_uid) < 0)
die_with_error ("unable to switch to uid %d", opt_sandbox_uid);
if (opt_sandbox_gid != real_gid && setgid (opt_sandbox_gid) < 0)
die_with_error ("unable to switch to gid %d", opt_sandbox_gid);
}
if (!is_privileged)
return;
/* Tell kernel not clear capabilities when later dropping root uid */
if (prctl (PR_SET_KEEPCAPS, 1, 0, 0, 0) < 0)
die_with_error ("prctl(PR_SET_KEEPCAPS) failed");
if (setuid (opt_sandbox_uid) < 0)
die_with_error ("unable to drop root uid");
/* Regain effective required capabilities from permitted */
set_required_caps ();
}
/* Call setuid() and use capset() to adjust capabilities */
static void
drop_privs (bool keep_requested_caps,
bool already_changed_uid)
{
assert (!keep_requested_caps || !is_privileged);
/* Drop root uid */
if (is_privileged && !already_changed_uid &&
setuid (opt_sandbox_uid) < 0)
die_with_error ("unable to drop root uid");
drop_all_caps (keep_requested_caps);
/* We don't have any privs now, so mark us dumpable which makes /proc/self be owned by the user instead of root */
if (prctl (PR_SET_DUMPABLE, 1, 0, 0, 0) != 0)
die_with_error ("can't set dumpable");
}
static char *
get_newroot_path (const char *path)
{
while (*path == '/')
path++;
return strconcat ("/newroot/", path);
}
static void
write_uid_gid_map (uid_t sandbox_uid,
uid_t parent_uid,
uid_t sandbox_gid,
uid_t parent_gid,
pid_t pid,
bool deny_groups,
bool map_root)
{
cleanup_free char *uid_map = NULL;
cleanup_free char *gid_map = NULL;
cleanup_free char *dir = NULL;
cleanup_fd int dir_fd = -1;
uid_t old_fsuid = (uid_t)-1;
if (pid == -1)
dir = xstrdup ("self");
else
dir = xasprintf ("%d", pid);
dir_fd = openat (proc_fd, dir, O_PATH);
if (dir_fd < 0)
die_with_error ("open /proc/%s failed", dir);
if (map_root && parent_uid != 0 && sandbox_uid != 0)
uid_map = xasprintf ("0 %d 1\n"
"%d %d 1\n", overflow_uid, sandbox_uid, parent_uid);
else
uid_map = xasprintf ("%d %d 1\n", sandbox_uid, parent_uid);
if (map_root && parent_gid != 0 && sandbox_gid != 0)
gid_map = xasprintf ("0 %d 1\n"
"%d %d 1\n", overflow_gid, sandbox_gid, parent_gid);
else
gid_map = xasprintf ("%d %d 1\n", sandbox_gid, parent_gid);
/* We have to be root to be allowed to write to the uid map
* for setuid apps, so temporary set fsuid to 0 */
if (is_privileged)
old_fsuid = setfsuid (0);
if (write_file_at (dir_fd, "uid_map", uid_map) != 0)
die_with_error ("setting up uid map");
if (deny_groups &&
write_file_at (dir_fd, "setgroups", "deny\n") != 0)