forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
seccomp.go
2037 lines (1734 loc) · 53.9 KB
/
seccomp.go
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
//go:build linux && cgo
// +build linux,cgo
package seccomp
import (
"fmt"
"io"
"io/ioutil"
"net"
"os"
"path"
"regexp"
"runtime"
"strconv"
"strings"
"unsafe"
"github.com/pkg/errors"
"golang.org/x/sys/unix"
liblxc "gopkg.in/lxc/go-lxc.v2"
// Used by cgo
_ "github.com/lxc/lxd/lxd/include"
deviceConfig "github.com/lxc/lxd/lxd/device/config"
"github.com/lxc/lxd/lxd/project"
"github.com/lxc/lxd/lxd/state"
"github.com/lxc/lxd/lxd/ucred"
"github.com/lxc/lxd/lxd/util"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/idmap"
log "github.com/lxc/lxd/shared/log15"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/netutils"
"github.com/lxc/lxd/shared/osarch"
)
/*
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
#include <elf.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/seccomp.h>
#include <linux/types.h>
#include <linux/kdev_t.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#include <unistd.h>
#include "../include/lxd_bpf.h"
#include "../include/lxd_seccomp.h"
#include "../include/memory_utils.h"
#include "../include/process_utils.h"
struct seccomp_notif_sizes expected_sizes;
struct seccomp_notify_proxy_msg {
uint64_t __reserved;
pid_t monitor_pid;
pid_t init_pid;
struct seccomp_notif_sizes sizes;
uint64_t cookie_len;
// followed by: seccomp_notif, seccomp_notif_resp, cookie
};
#define SECCOMP_PROXY_MSG_SIZE (sizeof(struct seccomp_notify_proxy_msg))
#define SECCOMP_NOTIFY_SIZE (sizeof(struct seccomp_notif))
#define SECCOMP_RESPONSE_SIZE (sizeof(struct seccomp_notif_resp))
#define SECCOMP_MSG_SIZE_MIN (SECCOMP_PROXY_MSG_SIZE + SECCOMP_NOTIFY_SIZE + SECCOMP_RESPONSE_SIZE)
#define SECCOMP_COOKIE_SIZE (64 * sizeof(char))
#define SECCOMP_MSG_SIZE_MAX (SECCOMP_MSG_SIZE_MIN + SECCOMP_COOKIE_SIZE)
static int seccomp_notify_get_sizes(struct seccomp_notif_sizes *sizes)
{
if (syscall(SYS_seccomp, SECCOMP_GET_NOTIF_SIZES, 0, sizes) != 0)
return -1;
if (sizes->seccomp_notif != sizeof(struct seccomp_notif) ||
sizes->seccomp_notif_resp != sizeof(struct seccomp_notif_resp) ||
sizes->seccomp_data != sizeof(struct seccomp_data))
return -1;
return 0;
}
static int device_allowed(dev_t dev, mode_t mode)
{
switch (mode & S_IFMT) {
case S_IFCHR:
if (dev == makedev(0, 0)) // whiteout
return 0;
else if (dev == makedev(5, 1)) // /dev/console
return 0;
else if (dev == makedev(1, 7)) // /dev/full
return 0;
else if (dev == makedev(1, 3)) // /dev/null
return 0;
else if (dev == makedev(1, 8)) // /dev/random
return 0;
else if (dev == makedev(5, 0)) // /dev/tty
return 0;
else if (dev == makedev(1, 9)) // /dev/urandom
return 0;
else if (dev == makedev(1, 5)) // /dev/zero
return 0;
}
return -EPERM;
}
#include <linux/audit.h>
struct lxd_seccomp_data_arch {
int arch;
int nr_mknod;
int nr_mknodat;
int nr_setxattr;
int nr_mount;
int nr_bpf;
};
#define LXD_SECCOMP_NOTIFY_MKNOD 0
#define LXD_SECCOMP_NOTIFY_MKNODAT 1
#define LXD_SECCOMP_NOTIFY_SETXATTR 2
#define LXD_SECCOMP_NOTIFY_MOUNT 3
#define LXD_SECCOMP_NOTIFY_BPF 4
// ordered by likelihood of usage...
static const struct lxd_seccomp_data_arch seccomp_notify_syscall_table[] = {
{ -1, LXD_SECCOMP_NOTIFY_MKNOD, LXD_SECCOMP_NOTIFY_MKNODAT, LXD_SECCOMP_NOTIFY_SETXATTR, LXD_SECCOMP_NOTIFY_MOUNT, LXD_SECCOMP_NOTIFY_BPF },
#ifdef AUDIT_ARCH_X86_64
{ AUDIT_ARCH_X86_64, 133, 259, 188, 165, 321 },
#endif
#ifdef AUDIT_ARCH_I386
{ AUDIT_ARCH_I386, 14, 297, 226, 21, 357 },
#endif
#ifdef AUDIT_ARCH_AARCH64
{ AUDIT_ARCH_AARCH64, -1, 33, 5, 21, 386 },
#endif
#ifdef AUDIT_ARCH_ARM
{ AUDIT_ARCH_ARM, 14, 324, 226, 21, 386 },
#endif
#ifdef AUDIT_ARCH_ARMEB
{ AUDIT_ARCH_ARMEB, 14, 324, 226, 21, 386 },
#endif
#ifdef AUDIT_ARCH_S390
{ AUDIT_ARCH_S390, 14, 290, 224, 21, 386 },
#endif
#ifdef AUDIT_ARCH_S390X
{ AUDIT_ARCH_S390X, 14, 290, 224, 21, 351 },
#endif
#ifdef AUDIT_ARCH_PPC
{ AUDIT_ARCH_PPC, 14, 288, 209, 21, 361 },
#endif
#ifdef AUDIT_ARCH_PPC64
{ AUDIT_ARCH_PPC64, 14, 288, 209, 21, 361 },
#endif
#ifdef AUDIT_ARCH_PPC64LE
{ AUDIT_ARCH_PPC64LE, 14, 288, 209, 21, 361 },
#endif
#ifdef AUDIT_ARCH_SPARC
{ AUDIT_ARCH_SPARC, 14, 286, 169, 167, 349 },
#endif
#ifdef AUDIT_ARCH_SPARC64
{ AUDIT_ARCH_SPARC64, 14, 286, 169, 167, 349 },
#endif
#ifdef AUDIT_ARCH_MIPS
{ AUDIT_ARCH_MIPS, 14, 290, 224, 21, -1 },
#endif
#ifdef AUDIT_ARCH_MIPSEL
{ AUDIT_ARCH_MIPSEL, 14, 290, 224, 21, -1 },
#endif
#ifdef AUDIT_ARCH_MIPS64
{ AUDIT_ARCH_MIPS64, 131, 249, 180, 160, -1 },
#endif
#ifdef AUDIT_ARCH_MIPS64N32
{ AUDIT_ARCH_MIPS64N32, 131, 253, 180, 160, -1 },
#endif
#ifdef AUDIT_ARCH_MIPSEL64
{ AUDIT_ARCH_MIPSEL64, 131, 249, 180, 160, -1 },
#endif
#ifdef AUDIT_ARCH_MIPSEL64N32
{ AUDIT_ARCH_MIPSEL64N32, 131, 253, 180, 160, -1 },
#endif
};
static int seccomp_notify_get_syscall(struct seccomp_notif *req,
struct seccomp_notif_resp *resp)
{
resp->id = req->id;
resp->flags = req->flags;
resp->val = 0;
resp->error = 0;
for (size_t i = 0; i < (sizeof(seccomp_notify_syscall_table) /
sizeof(seccomp_notify_syscall_table[0]));
i++) {
const struct lxd_seccomp_data_arch *entry = &seccomp_notify_syscall_table[i];
if (entry->arch != req->data.arch)
continue;
if (entry->nr_mknod == req->data.nr)
return LXD_SECCOMP_NOTIFY_MKNOD;
if (entry->nr_mknodat == req->data.nr)
return LXD_SECCOMP_NOTIFY_MKNODAT;
if (entry->nr_setxattr == req->data.nr)
return LXD_SECCOMP_NOTIFY_SETXATTR;
if (entry->nr_mount == req->data.nr)
return LXD_SECCOMP_NOTIFY_MOUNT;
if (entry->nr_bpf == req->data.nr)
return LXD_SECCOMP_NOTIFY_BPF;
break;
}
errno = EINVAL;
return -EINVAL;
}
static void seccomp_notify_update_response(struct seccomp_notif_resp *resp,
int new_neg_errno, uint32_t flags)
{
resp->error = new_neg_errno;
resp->flags |= flags;
}
static void prepare_seccomp_iovec(struct iovec *iov,
struct seccomp_notify_proxy_msg *msg,
struct seccomp_notif *notif,
struct seccomp_notif_resp *resp, char *cookie)
{
iov[0].iov_base = msg;
iov[0].iov_len = SECCOMP_PROXY_MSG_SIZE;
iov[1].iov_base = notif;
iov[1].iov_len = SECCOMP_NOTIFY_SIZE;
iov[2].iov_base = resp;
iov[2].iov_len = SECCOMP_RESPONSE_SIZE;
iov[3].iov_base = cookie;
iov[3].iov_len = SECCOMP_COOKIE_SIZE;
}
// We use the BPF_DEVCG_DEV_CHAR macro as a cheap way to detect whether the kernel has
// the correct headers available to be compiled for bpf support. Since cgo doesn't have
// a good way of letting us probe for structs or enums the alternative would be to vendor
// bpf.h similar to what we do for seccomp itself. But that's annoying since bpf.h is quite
// large. So users that want bpf interception support should make sure to have the relevant
// header available at build time.
static inline int pidfd_getfd(int pidfd, int fd, int flags)
{
return syscall(__NR_pidfd_getfd, pidfd, fd, flags);
}
#define ptr_to_u64(p) ((__aligned_u64)((uintptr_t)(p)))
static inline int bpf(int cmd, union bpf_attr *attr, size_t size)
{
return syscall(__NR_bpf, cmd, attr, size);
}
static int handle_bpf_syscall(int notify_fd, int mem_fd, struct seccomp_notify_proxy_msg *msg,
struct seccomp_notif *req, struct seccomp_notif_resp *resp,
int *bpf_cmd, int *bpf_prog_type, int *bpf_attach_type)
{
__do_close int pidfd = -EBADF, bpf_target_fd = -EBADF, bpf_attach_fd = -EBADF,
bpf_prog_fd = -EBADF;
__do_free struct bpf_insn *insn = NULL;
char log_buf[4096] = {};
char license[128] = {};
size_t insn_size = 0;
union bpf_attr attr = {}, new_attr = {};
unsigned int attr_len = sizeof(attr);
struct seccomp_notif_addfd addfd = {};
int ret;
int cmd;
*bpf_cmd = -EINVAL;
*bpf_prog_type = -EINVAL;
*bpf_attach_type = -EINVAL;
if (attr_len < req->data.args[2])
return -EFBIG;
attr_len = req->data.args[2];
*bpf_cmd = req->data.args[0];
switch (req->data.args[0]) {
case BPF_PROG_LOAD:
cmd = BPF_PROG_LOAD;
break;
case BPF_PROG_ATTACH:
cmd = BPF_PROG_ATTACH;
break;
case BPF_PROG_DETACH:
cmd = BPF_PROG_DETACH;
break;
default:
return -EINVAL;
}
ret = pread(mem_fd, &attr, attr_len, req->data.args[1]);
if (ret < 0)
return -errno;
*bpf_prog_type = attr.prog_type;
pidfd = pidfd_open(req->pid, 0);
if (pidfd < 0)
return -errno;
if (ioctl(notify_fd, SECCOMP_IOCTL_NOTIF_ID_VALID, &req->id))
return -errno;
switch (cmd) {
case BPF_PROG_LOAD:
if (attr.prog_type != BPF_PROG_TYPE_CGROUP_DEVICE)
return -EINVAL;
// bpf is currently limited to 1 million instructions. Don't
// allow the container to allocate more than that.
if (attr.insn_cnt > 1000000)
return -EINVAL;
insn_size = sizeof(struct bpf_insn) * attr.insn_cnt;
insn = malloc(insn_size);
if (!insn)
return -ENOMEM;
ret = pread(mem_fd, insn, insn_size, attr.insns);
if (ret < 0)
return -errno;
if (ret != insn_size)
return -EIO;
memcpy(&new_attr, &attr, sizeof(attr));
if (attr.log_size > sizeof(log_buf))
new_attr.log_size = sizeof(log_buf);
if (new_attr.log_size > 0)
new_attr.log_buf = ptr_to_u64(log_buf);
if (attr.license && pread(mem_fd, license, sizeof(license), attr.license) < 0)
return -errno;
new_attr.insns = ptr_to_u64(insn);
new_attr.license = ptr_to_u64(license);
bpf_prog_fd = bpf(cmd, &new_attr, sizeof(new_attr));
if (bpf_prog_fd < 0) {
int saved_errno = errno;
if ((new_attr.log_size) > 0 && (pwrite(mem_fd, log_buf, new_attr.log_size,
attr.log_buf) != new_attr.log_size))
errno = saved_errno;
return -errno;
}
addfd.srcfd = bpf_prog_fd;
addfd.id = req->id;
addfd.flags = 0;
ret = ioctl(notify_fd, SECCOMP_IOCTL_NOTIF_ADDFD, &addfd);
if (ret < 0)
return -errno;
resp->val = ret;
ret = 0;
break;
case BPF_PROG_ATTACH:
if (attr.attach_type != BPF_CGROUP_DEVICE)
return -EINVAL;
*bpf_attach_type = attr.attach_type;
bpf_target_fd = pidfd_getfd(pidfd, attr.target_fd, 0);
if (bpf_target_fd < 0)
return -errno;
bpf_attach_fd = pidfd_getfd(pidfd, attr.attach_bpf_fd, 0);
if (bpf_attach_fd < 0)
return -errno;
attr.target_fd = bpf_target_fd;
attr.attach_bpf_fd = bpf_attach_fd;
ret = bpf(cmd, &attr, attr_len);
break;
case BPF_PROG_DETACH:
if (attr.attach_type != BPF_CGROUP_DEVICE)
return -EINVAL;
*bpf_attach_type = attr.attach_type;
bpf_target_fd = pidfd_getfd(pidfd, attr.target_fd, 0);
if (bpf_target_fd < 0)
return -errno;
bpf_attach_fd = pidfd_getfd(pidfd, attr.attach_bpf_fd, 0);
if (bpf_attach_fd < 0)
return -errno;
attr.target_fd = bpf_target_fd;
attr.attach_bpf_fd = bpf_attach_fd;
ret = bpf(cmd, &attr, attr_len);
break;
}
return ret;
}
#ifndef MS_LAZYTIME
#define MS_LAZYTIME (1<<25)
#endif
*/
import "C"
const lxdSeccompNotifyMknod = C.LXD_SECCOMP_NOTIFY_MKNOD
const lxdSeccompNotifyMknodat = C.LXD_SECCOMP_NOTIFY_MKNODAT
const lxdSeccompNotifySetxattr = C.LXD_SECCOMP_NOTIFY_SETXATTR
const lxdSeccompNotifyMount = C.LXD_SECCOMP_NOTIFY_MOUNT
const lxdSeccompNotifyBpf = C.LXD_SECCOMP_NOTIFY_BPF
const seccompHeader = `2
`
const defaultSeccompPolicy = `reject_force_umount # comment this to allow umount -f; not recommended
[all]
kexec_load errno 38
open_by_handle_at errno 38
init_module errno 38
finit_module errno 38
delete_module errno 38
`
// 8 == SECCOMP_FILTER_FLAG_NEW_LISTENER
// 2146435072 == SECCOMP_RET_TRACE
const seccompNotifyDisallow = `seccomp errno 22 [1,2146435072,SCMP_CMP_MASKED_EQ,2146435072]
seccomp errno 22 [1,8,SCMP_CMP_MASKED_EQ,8]
`
const seccompNotifyMknod = `mknod notify [1,8192,SCMP_CMP_MASKED_EQ,61440]
mknod notify [1,24576,SCMP_CMP_MASKED_EQ,61440]
mknodat notify [2,8192,SCMP_CMP_MASKED_EQ,61440]
mknodat notify [2,24576,SCMP_CMP_MASKED_EQ,61440]
`
const seccompNotifySetxattr = `setxattr notify [3,1,SCMP_CMP_EQ]
`
const seccompBlockNewMountAPI = `fsopen errno 38
fsconfig errno 38
fsinfo errno 38
fsmount errno 38
fspick errno 38
open_tree errno 38
move_mount errno 38
openat2 errno 38
`
// We don't want to filter any of the following flag combinations since they do
// not cause the creation of a new superblock:
//
// MS_REMOUNT
// MS_BIND
// MS_MOVE
// MS_UNBINDABLE
// MS_PRIVATE
// MS_SLAVE
// MS_SHARED
// MS_KERNMOUNT
// MS_I_VERSION
//
// So define the following mask of allowed flags:
//
// long unsigned int mask = MS_MGC_VAL | MS_RDONLY | MS_NOSUID | MS_NODEV |
// MS_NOEXEC | MS_SYNCHRONOUS | MS_MANDLOCK |
// MS_DIRSYNC | MS_NOATIME | MS_NODIRATIME | MS_REC |
// MS_VERBOSE | MS_SILENT | MS_POSIXACL | MS_RELATIME |
// MS_STRICTATIME | MS_LAZYTIME;
//
// Now we inverse the flag:
//
// inverse_mask ~= mask;
//
// Seccomp will now only intercept these flags if they do not contain any of
// the allowed flags, i.e. we only intercept combinations were a new superblock
// is created.
const seccompNotifyMount = `mount notify [3,0,SCMP_CMP_MASKED_EQ,18446744070422410016]
`
// 5 == BPF_PROG_LOAD
// 8 == BPF_PROG_ATTACH
// 9 == BPF_PROG_DETACH
const seccompNotifyBpf = `bpf notify [0,5,SCMP_CMP_EQ]
bpf notify [0,8,SCMP_CMP_EQ]
bpf notify [0,9,SCMP_CMP_EQ]
`
const compatBlockingPolicy = `[%s]
compat_sys_rt_sigaction errno 38
stub_x32_rt_sigreturn errno 38
compat_sys_ioctl errno 38
compat_sys_readv errno 38
compat_sys_writev errno 38
compat_sys_recvfrom errno 38
compat_sys_sendmsg errno 38
compat_sys_recvmsg errno 38
stub_x32_execve errno 38
compat_sys_ptrace errno 38
compat_sys_rt_sigpending errno 38
compat_sys_rt_sigtimedwait errno 38
compat_sys_rt_sigqueueinfo errno 38
compat_sys_sigaltstack errno 38
compat_sys_timer_create errno 38
compat_sys_mq_notify errno 38
compat_sys_kexec_load errno 38
compat_sys_waitid errno 38
compat_sys_set_robust_list errno 38
compat_sys_get_robust_list errno 38
compat_sys_vmsplice errno 38
compat_sys_move_pages errno 38
compat_sys_preadv64 errno 38
compat_sys_pwritev64 errno 38
compat_sys_rt_tgsigqueueinfo errno 38
compat_sys_recvmmsg errno 38
compat_sys_sendmmsg errno 38
compat_sys_process_vm_readv errno 38
compat_sys_process_vm_writev errno 38
compat_sys_setsockopt errno 38
compat_sys_getsockopt errno 38
compat_sys_io_setup errno 38
compat_sys_io_submit errno 38
stub_x32_execveat errno 38
`
// Instance is a seccomp specific instance interface.
// This is used rather than instance.Instance to avoid import loops.
type Instance interface {
Name() string
Project() string
ExpandedConfig() map[string]string
IsPrivileged() bool
Architecture() int
RootfsPath() string
CurrentIdmap() (*idmap.IdmapSet, error)
DiskIdmap() (*idmap.IdmapSet, error)
InsertSeccompUnixDevice(prefix string, m deviceConfig.Device, pid int) error
}
var seccompPath = shared.VarPath("security", "seccomp")
// ProfilePath returns the seccomp path for the instance.
func ProfilePath(c Instance) string {
return path.Join(seccompPath, project.Instance(c.Project(), c.Name()))
}
// InstanceNeedsPolicy returns whether the instance needs a policy or not.
func InstanceNeedsPolicy(c Instance) bool {
config := c.ExpandedConfig()
// Check for text keys
keys := []string{
"raw.seccomp",
"security.syscalls.allow",
"security.syscalls.deny",
"security.syscalls.whitelist",
"security.syscalls.blacklist",
}
for _, k := range keys {
_, hasKey := config[k]
if hasKey {
return true
}
}
// Check for boolean keys that default to false
keys = []string{
"security.syscalls.deny_compat",
"security.syscalls.blacklist_compat",
"security.syscalls.intercept.mknod",
"security.syscalls.intercept.setxattr",
"security.syscalls.intercept.mount",
"security.syscalls.intercept.bpf",
}
for _, k := range keys {
if shared.IsTrue(config[k]) {
return true
}
}
// Check for boolean keys that default to true
value, ok := config["security.syscalls.deny_default"]
if !ok {
value, ok = config["security.syscalls.blacklist_default"]
}
if !ok || shared.IsTrue(value) {
return true
}
return false
}
// InstanceNeedsIntercept returns whether instance needs intercept.
func InstanceNeedsIntercept(s *state.State, c Instance) (bool, error) {
// No need if privileged
if c.IsPrivileged() {
return false, nil
}
// If nested, assume the host handles it
if s.OS.RunningInUserNS {
return false, nil
}
config := c.ExpandedConfig()
var keys = map[string]func(state *state.State) error{
"security.syscalls.intercept.mknod": lxcSupportSeccompNotify,
"security.syscalls.intercept.setxattr": lxcSupportSeccompNotify,
"security.syscalls.intercept.mount": lxcSupportSeccompNotifyContinue,
"security.syscalls.intercept.bpf": lxcSupportSeccompNotifyAddfd,
}
needed := false
for key, check := range keys {
if !shared.IsTrue(config[key]) {
continue
}
err := check(s)
if err != nil {
return needed, err
}
needed = true
}
return needed, nil
}
// MakePidFd prepares a pidfd to inherit for the init process of the container.
func MakePidFd(pid int, s *state.State) (int, *os.File) {
if s.OS.PidFds {
pidFdFile, err := shared.PidFdOpen(pid, 0)
if err != nil {
return -1, nil
}
return 3, pidFdFile
}
return -1, nil
}
func seccompGetPolicyContent(s *state.State, c Instance) (string, error) {
config := c.ExpandedConfig()
// Full policy override
raw := config["raw.seccomp"]
if raw != "" {
return raw, nil
}
// Policy header
policy := seccompHeader
allowlist := config["security.syscalls.allow"]
if allowlist == "" {
allowlist = config["security.syscalls.whitelist"]
}
if allowlist != "" {
if s.OS.LXCFeatures["seccomp_allow_deny_syntax"] {
policy += "allowlist\n[all]\n"
} else {
policy += "whitelist\n[all]\n"
}
policy += allowlist
} else {
if s.OS.LXCFeatures["seccomp_allow_deny_syntax"] {
policy += "denylist\n[all]\n"
} else {
policy += "blacklist\n[all]\n"
}
defaultFlag, ok := config["security.syscalls.deny_default"]
if !ok {
defaultFlag, ok = config["security.syscalls.blacklist_default"]
}
if !ok || shared.IsTrue(defaultFlag) {
policy += defaultSeccompPolicy
}
}
// Syscall interception
ok, err := InstanceNeedsIntercept(s, c)
if err != nil {
return "", err
}
if ok {
// Prevent the container from overriding our syscall
// supervision.
policy += seccompNotifyDisallow
if shared.IsTrue(config["security.syscalls.intercept.mknod"]) {
policy += seccompNotifyMknod
}
if shared.IsTrue(config["security.syscalls.intercept.setxattr"]) {
policy += seccompNotifySetxattr
}
if shared.IsTrue(config["security.syscalls.intercept.mount"]) {
policy += seccompNotifyMount
// We block the new mount api for now to simplify mount
// syscall interception. Since it keeps state over
// multiple syscalls we'd need more invasive changes to
// make this work.
policy += seccompBlockNewMountAPI
}
if shared.IsTrue(config["security.syscalls.intercept.bpf"]) {
policy += seccompNotifyBpf
}
}
if allowlist != "" {
return policy, nil
}
// Additional deny entries
compat, ok := config["security.syscalls.deny_compat"]
if !ok {
compat = config["security.syscalls.blacklist_compat"]
}
if shared.IsTrue(compat) {
arch, err := osarch.ArchitectureName(c.Architecture())
if err != nil {
return "", err
}
policy += fmt.Sprintf(compatBlockingPolicy, arch)
}
denylist, ok := config["security.syscalls.deny"]
if !ok {
denylist = config["security.syscalls.blacklist"]
}
if denylist != "" {
policy += denylist
}
return policy, nil
}
// CreateProfile creates a seccomp profile.
func CreateProfile(s *state.State, c Instance) error {
/* Unlike apparmor, there is no way to "cache" profiles, and profiles
* are automatically unloaded when a task dies. Thus, we don't need to
* unload them when a container stops, and we don't have to worry about
* the mtime on the file for any compiler purpose, so let's just write
* out the profile.
*/
if !InstanceNeedsPolicy(c) {
return nil
}
profile, err := seccompGetPolicyContent(s, c)
if err != nil {
return err
}
if err := os.MkdirAll(seccompPath, 0700); err != nil {
return err
}
return ioutil.WriteFile(ProfilePath(c), []byte(profile), 0600)
}
// DeleteProfile removes a seccomp profile.
func DeleteProfile(c Instance) {
/* similar to AppArmor, if we've never started this container, the
* delete can fail and that's ok.
*/
os.Remove(ProfilePath(c))
}
// Server defines a seccomp server.
type Server struct {
s *state.State
path string
l net.Listener
}
// Iovec defines an iovec to move data between kernel and userspace.
type Iovec struct {
ucred *unix.Ucred
memFd int
procFd int
notifyFd int
msg *C.struct_seccomp_notify_proxy_msg
req *C.struct_seccomp_notif
resp *C.struct_seccomp_notif_resp
cookie *C.char
iov *C.struct_iovec
}
// NewSeccompIovec creates a new seccomp iovec.
func NewSeccompIovec(ucred *unix.Ucred) *Iovec {
msgPtr := C.malloc(C.sizeof_struct_seccomp_notify_proxy_msg)
msg := (*C.struct_seccomp_notify_proxy_msg)(msgPtr)
C.memset(msgPtr, 0, C.sizeof_struct_seccomp_notify_proxy_msg)
regPtr := C.malloc(C.sizeof_struct_seccomp_notif)
req := (*C.struct_seccomp_notif)(regPtr)
C.memset(regPtr, 0, C.sizeof_struct_seccomp_notif)
respPtr := C.malloc(C.sizeof_struct_seccomp_notif_resp)
resp := (*C.struct_seccomp_notif_resp)(respPtr)
C.memset(respPtr, 0, C.sizeof_struct_seccomp_notif_resp)
cookiePtr := C.malloc(64 * C.sizeof_char)
cookie := (*C.char)(cookiePtr)
C.memset(cookiePtr, 0, 64*C.sizeof_char)
iovUnsafePtr := C.malloc(4 * C.sizeof_struct_iovec)
iov := (*C.struct_iovec)(iovUnsafePtr)
C.memset(iovUnsafePtr, 0, 4*C.sizeof_struct_iovec)
C.prepare_seccomp_iovec(iov, msg, req, resp, cookie)
return &Iovec{
memFd: -1,
procFd: -1,
notifyFd: -1,
msg: msg,
req: req,
resp: resp,
cookie: cookie,
iov: iov,
ucred: ucred,
}
}
// PutSeccompIovec puts a seccomp iovec.
func (siov *Iovec) PutSeccompIovec() {
if siov.memFd >= 0 {
unix.Close(siov.memFd)
}
if siov.procFd >= 0 {
unix.Close(siov.procFd)
}
if siov.notifyFd >= 0 {
unix.Close(siov.notifyFd)
}
C.free(unsafe.Pointer(siov.msg))
C.free(unsafe.Pointer(siov.req))
C.free(unsafe.Pointer(siov.resp))
C.free(unsafe.Pointer(siov.cookie))
C.free(unsafe.Pointer(siov.iov))
}
// ReceiveSeccompIovec receives a seccomp iovec.
func (siov *Iovec) ReceiveSeccompIovec(fd int) (uint64, error) {
bytes, fds, err := netutils.AbstractUnixReceiveFdData(fd, 3, netutils.UnixFdsAcceptLess, unsafe.Pointer(siov.iov), 4)
if err != nil || err == io.EOF {
return 0, err
}
siov.procFd = int(fds[0])
siov.memFd = int(fds[1])
siov.notifyFd = int(fds[2])
logger.Debugf("Syscall handler received fds %d(/proc/<pid>), %d(/proc/<pid>/mem), and %d([seccomp notify])", siov.procFd, siov.memFd, siov.notifyFd)
return bytes, nil
}
// IsValidSeccompIovec checks whether a seccomp iovec is valid.
func (siov *Iovec) IsValidSeccompIovec(size uint64) bool {
if size < uint64(C.SECCOMP_MSG_SIZE_MIN) {
logger.Warnf("Disconnected from seccomp socket after incomplete receive")
return false
}
if siov.msg.__reserved != 0 {
logger.Warnf("Disconnected from seccomp socket after client sent non-zero reserved field: pid=%v",
siov.ucred.Pid)
return false
}
if siov.msg.sizes.seccomp_notif != C.expected_sizes.seccomp_notif {
logger.Warnf("Disconnected from seccomp socket since client uses different seccomp_notif sizes: %d != %d, pid=%v",
siov.msg.sizes.seccomp_notif, C.expected_sizes.seccomp_notif, siov.ucred.Pid)
return false
}
if siov.msg.sizes.seccomp_notif_resp != C.expected_sizes.seccomp_notif_resp {
logger.Warnf("Disconnected from seccomp socket since client uses different seccomp_notif_resp sizes: %d != %d, pid=%v",
siov.msg.sizes.seccomp_notif_resp, C.expected_sizes.seccomp_notif_resp, siov.ucred.Pid)
return false
}
if siov.msg.sizes.seccomp_data != C.expected_sizes.seccomp_data {
logger.Warnf("Disconnected from seccomp socket since client uses different seccomp_data sizes: %d != %d, pid=%v",
siov.msg.sizes.seccomp_data, C.expected_sizes.seccomp_data, siov.ucred.Pid)
return false
}
return true
}
// SendSeccompIovec sends seccomp iovec.
func (siov *Iovec) SendSeccompIovec(fd int, errno int, flags uint32) error {
C.seccomp_notify_update_response(siov.resp, C.int(errno), C.uint32_t(flags))
msghdr := C.struct_msghdr{}
msghdr.msg_iov = siov.iov
msghdr.msg_iovlen = 4 - 1 // without cookie
retry:
bytes, err := C.sendmsg(C.int(fd), &msghdr, C.MSG_NOSIGNAL)
if bytes < 0 {
if err == unix.EINTR {
logger.Debugf("Caught EINTR, retrying...")
goto retry
}
logger.Debugf("Disconnected from seccomp socket after failed write for process %v: %s", siov.ucred.Pid, err)
return fmt.Errorf("Failed to send response to seccomp client %v", siov.ucred.Pid)
}
if uint64(bytes) != uint64(C.SECCOMP_MSG_SIZE_MIN) {
logger.Debugf("Disconnected from seccomp socket after short write: pid=%v", siov.ucred.Pid)
return fmt.Errorf("Failed to send full response to seccomp client %v", siov.ucred.Pid)
}
logger.Debugf("Send seccomp notification for id(%d)", siov.resp.id)
return nil
}
// NewSeccompServer creates a new seccomp server.
func NewSeccompServer(s *state.State, path string, findPID func(pid int32, state *state.State) (Instance, error)) (*Server, error) {
ret := C.seccomp_notify_get_sizes(&C.expected_sizes)
if ret < 0 {
return nil, fmt.Errorf("Failed to query kernel for seccomp notifier sizes")
}
// Cleanup existing sockets
if shared.PathExists(path) {
err := os.Remove(path)
if err != nil {
return nil, err
}
}
// Bind new socket
l, err := net.Listen("unixpacket", path)
if err != nil {
return nil, err
}
// Restrict access
err = os.Chmod(path, 0700)
if err != nil {
return nil, err
}
// Start the server
server := Server{
s: s,
path: path,
l: l,
}
go func() {
for {
c, err := l.Accept()
if err != nil {
return
}
go func() {
ucred, err := ucred.GetCred(c.(*net.UnixConn))
if err != nil {
logger.Errorf("Unable to get ucred from seccomp socket client: %v", err)
return