This repository was archived by the owner on Jan 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 249
/
Copy pathdnsmasq-sandbox.patch
1873 lines (1859 loc) · 56.2 KB
/
dnsmasq-sandbox.patch
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
diff --git a/Makefile b/Makefile
index 73ea23e..b6c7021 100644
--- a/Makefile
+++ b/Makefile
@@ -76,10 +76,11 @@ objs = cache.o rfc1035.o util.o option.o forward.o network.o \
helper.o tftp.o log.o conntrack.o dhcp6.o rfc3315.o \
dhcp-common.o outpacket.o radv.o slaac.o auth.o ipset.o \
domain.o dnssec.o blockdata.o tables.o loop.o inotify.o \
- poll.o rrfilter.o edns0.o arp.o
+ poll.o rrfilter.o edns0.o arp.o seccomp.o bpf-helper.o \
+ mount-namespace.o seccomp-testing.o
hdrs = dnsmasq.h config.h dhcp-protocol.h dhcp6-protocol.h \
- dns-protocol.h radv-protocol.h ip6addr.h
+ dns-protocol.h radv-protocol.h ip6addr.h bpf-helper.h
all : $(BUILDDIR)
@cd $(BUILDDIR) && $(MAKE) \
diff --git a/dnsmasq_sandbox_test.py b/dnsmasq_sandbox_test.py
new file mode 100755
index 0000000..24f7ffd
--- /dev/null
+++ b/dnsmasq_sandbox_test.py
@@ -0,0 +1,398 @@
+#!/usr/bin/python2
+""" dnsmasq is Copyright (c) 2000-2017 Simon Kelley
+
+ This program 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; version 2 dated June, 1991, or
+ (at your option) version 3 dated 29 June, 2007.
+
+ This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
+
+Tests for dnsmasq_sandbox.
+
+Launch the dnsmasq instance and try to run "dig" with different types.
+
+In case of test failure you can do the following steps to fix the policy error:
+1) Using the syscall number, given by the test, lookup syscall name
+2) Edit the seccomp policy to temporary fully allow this syscall
+3) Run application with strace, e.g. strace -f src/dnsmasq [...]
+4) Using the log from strace, look at the syscall arguments to determine the
+appropriate seccomp policy for it
+5) Either fully allow the syscall or put additional restriction on its
+arguments
+
+The rule of thumb for dealing with arguments is to restrict them as much as
+you can.
+"""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import ctypes
+import errno
+import grp
+import os
+import pwd
+import random
+import re
+import shutil
+import signal
+import subprocess
+import time
+
+
+TESTING_DIR = 'dnsmasq_sandbox_testing/'
+LOG_FILE = 'dnsmasq.log'
+CONF_FILE = 'dnsmasq.conf'
+PID_FILE = 'dnsmasq.pid'
+PORT_NUMBER = 8951
+
+CLONE_NEWNET = 0x40000000
+DHCP_IPV4 = '10.0.0.1/24'
+DHCP_RANGEV4 = '10.0.0.2,10.0.0.100,10m'
+DHCP_IPV6 = '1:1:1:1:1:1:1:1/64'
+DHCP_RANGEV6 = '1:1:1:1:1:1:1:2,1:1:1:1:1:1:1:100,10m'
+
+TFTP_ROOT = 'dnsmasq_test_tftp_root'
+TFTP_TEST_FILE = 'test.txt'
+
+# Because of Ubuntu AppArmor policy we have to keep pid file at this location
+DHCLIENT_PID_FILE = '/var/run/dhclient_dnsmasq_testing.pid'
+
+BASE_CONFIG = ('domain-needed\n'
+ 'bogus-priv\n'
+ 'sandbox=force\n'
+ 'sandbox-test\n'
+ 'log-facility=%s\n'
+ 'pid-file=%s\n'
+ 'port=%d\n')
+
+DNSMASQ_PATH = 'src/dnsmasq'
+
+DIG_OPTIONS = ['tcp', 'aaonly', 'adflag', 'cdflag', 'recurse', 'dnssec',
+ 'nsid']
+DIG_TYPES = ['A', 'AAAA', 'ANY', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'TXT',
+ 'A6', 'AFSDB', 'APL', 'ATMA', 'CAA', 'CERT', 'DNAME', 'DNSKEY',
+ 'DS', 'EID', 'GID', 'GPOS', 'HINFO', 'ISDN', 'KEY', 'KX', 'LOC',
+ 'MB', 'MD', 'MF', 'MG', 'MINFO', 'MR', 'MX', 'NAPTR', 'NIMLOC',
+ 'NSEC', 'NSEC3', 'NSEC3PARAM', 'NULL', 'NS', 'NSAP', 'NSAP-PTR',
+ 'NXT', 'OPT', 'PTR', 'PX', 'RP', 'RPSIG', 'RT', 'SIG', 'SINK',
+ 'SPF', 'SRV', 'SSHFP', 'TKEY', 'TLSA', 'TSIG', 'UID', 'UINFO',
+ 'UNSPEC', 'WKS', 'X25']
+
+WEBSITES = ['example.com', 'example.org']
+
+SYSCALL_RE = re.compile(r'Seccomp violation detected. Syscall number = (\d+)')
+
+
+def get_syscall_numbers(s):
+ return set(int(i) for i in SYSCALL_RE.findall(s))
+
+
+class DnsmasqTest(object):
+
+ def __init__(self):
+ cwd = os.getcwd()
+ self.testing_dir = os.path.join(cwd, TESTING_DIR)
+ self.config = ''
+ self.name = 'Test template'
+
+ def _log(self, msg, in_test=True):
+ print(('TEST:' if in_test else '') + msg)
+
+ def _report_error(self, numbers):
+ if not numbers:
+ self._log('dnsmasq error detected. '
+ 'Unable to determine bad syscall numbers')
+ return
+ self._log('Seccomp policy violation detected. Bad syscall numbers: %s'
+ % list(numbers))
+
+ def _get_pid(self):
+ try:
+ with open(self.pid_path, 'r') as f:
+ return int(f.read())
+ except (IOError, ValueError):
+ return None
+
+ def _start_dnsmasq(self):
+ self._log('starting dnsmasq instance')
+ with open(os.devnull, 'w') as devnull:
+ dnsmasq = subprocess.Popen([DNSMASQ_PATH, '-C', self.conf_path],
+ stdout=devnull,
+ stderr=subprocess.PIPE)
+ _, output = dnsmasq.communicate()
+ syscalls = get_syscall_numbers(output)
+ if dnsmasq.returncode != 0 and not syscalls:
+ self._log('dnsmasq died at setup')
+ self._log('return code = %d' % dnsmasq.returncode)
+ self._log('dnsmasq stderr = %s' % output.strip())
+ return 1
+ if syscalls:
+ self._report_error(syscalls)
+ return 1
+ self._log('dnsmasq setup complete')
+ return 0
+
+ def _kill_process(self):
+ pid = self._get_pid()
+ if pid:
+ try:
+ os.kill(pid, signal.SIGTERM)
+ time.sleep(1)
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+
+ def _set_up(self):
+ try:
+ shutil.rmtree(TESTING_DIR)
+ except OSError as e:
+ if e.errno != errno.ENOENT:
+ raise
+ self.log_path = os.path.join(self.testing_dir, LOG_FILE)
+ self.conf_path = os.path.join(self.testing_dir, CONF_FILE)
+ self.pid_path = os.path.join(self.testing_dir, PID_FILE)
+ os.mkdir(TESTING_DIR)
+ # Ensuring, that log file exists and it is empty.
+ with open(self.log_path, 'w'):
+ pass
+ with open(self.conf_path, 'w') as f:
+ f.write(BASE_CONFIG % (self.log_path, self.pid_path, PORT_NUMBER))
+ f.write(self.config)
+
+ def _tear_down(self):
+ self._kill_process()
+ shutil.rmtree(TESTING_DIR)
+
+ def _run_test(self, name, f):
+ self._log('Running test %s' % name, False)
+ self._set_up()
+ result = f()
+ self._tear_down()
+ if not result:
+ self._log('Test %s: OK' % name, False)
+ else:
+ self._log('Test %s: FAILED' % name, False)
+
+ def run(self):
+ self._log('Running test group: %s' % self.name, False)
+ for name in dir(self):
+ if name.startswith('_test_') and callable(getattr(self, name)):
+ self._run_test(name[len('_test_'):], getattr(self, name))
+
+
+class DnsmasqDNSTest(DnsmasqTest):
+
+ def __init__(self):
+ super(DnsmasqDNSTest, self).__init__()
+ self.name = 'DNS seccomp'
+
+ def _set_up(self):
+ super(DnsmasqDNSTest, self)._set_up()
+
+ def _tear_down(self):
+ super(DnsmasqDNSTest, self)._tear_down()
+
+ def _test_dnsmasq_sandbox(self):
+ with open(os.devnull, 'w') as devnull:
+ if self._start_dnsmasq():
+ return 1
+ self._log('starting to run dig')
+ no_reply = 0
+ for dig_type in DIG_TYPES:
+ if no_reply:
+ break
+ self._log('running type = %s' % dig_type)
+ for option in DIG_OPTIONS:
+ url = random.choice(WEBSITES)
+ dig = subprocess.Popen(['dig', '-p', str(PORT_NUMBER), '@localhost',
+ '+' + option, '+time=1', '+tries=1', '+noall',
+ url, dig_type],
+ stdout=devnull,
+ stderr=devnull)
+ dig.wait()
+ if dig.returncode == 9:
+ no_reply = 1
+ break
+
+ self._kill_process()
+ with open(self.log_path, 'r') as f:
+ text = f.read()
+ syscalls = get_syscall_numbers(text)
+ if syscalls or no_reply:
+ self._report_error(syscalls)
+ return 1
+ return 0
+
+
+class DnsmasqDHCPTest(DnsmasqTest):
+
+ def __init__(self):
+ super(DnsmasqDHCPTest, self).__init__()
+ self.name = 'DHCP seccomp'
+ self.config = ('interface=veth0\n'
+ 'dhcp-range=%s\n'
+ 'dhcp-range=%s\n'
+ 'dhcp-alternate-port=1067,1068')
+ self.config = self.config % (DHCP_RANGEV4, DHCP_RANGEV6)
+
+ def _set_up(self):
+ super(DnsmasqDHCPTest, self)._set_up()
+ self.dhclient_pid = DHCLIENT_PID_FILE
+ # Setting up network namespace
+ libc = ctypes.CDLL(None, use_errno=True)
+ libc.unshare(CLONE_NEWNET)
+ with open(os.devnull, 'w') as devnull:
+ # Setting up virtual network interfaces
+ subprocess.call(['ip', 'link', 'add', 'veth0', 'type', 'veth', 'peer',
+ 'name', 'veth1'],
+ stdout=devnull,
+ stderr=devnull)
+ subprocess.call(['ip', 'link', 'set', 'veth0', 'up'],
+ stdout=devnull,
+ stderr=devnull)
+ subprocess.call(['ip', 'link', 'set', 'veth1', 'up'],
+ stdout=devnull,
+ stderr=devnull)
+ subprocess.call(['ip', 'addr', 'add', DHCP_IPV4, 'dev', 'veth0'],
+ stdout=devnull,
+ stderr=devnull)
+ subprocess.call(['ip', 'addr', 'add', DHCP_IPV6, 'dev', 'veth0'],
+ stdout=devnull,
+ stderr=devnull)
+
+ def _test_dhcp_v4(self):
+ if self._start_dnsmasq():
+ return 1
+ self._log('starting to run dhclient')
+ with open(os.devnull, 'w') as devnull:
+ self._log('acquiring lease')
+ subprocess.call(['timeout', '1m', 'dhclient', '-1',
+ '-pf', self.dhclient_pid, '-p', '1068', 'veth1'],
+ stdout=devnull,
+ stderr=devnull)
+ self._log('releasing lease')
+ subprocess.call(['timeout', '1m', 'dhclient', '-r',
+ '-pf', self.dhclient_pid, '-p', '1068', 'veth1'],
+ stdout=devnull,
+ stderr=devnull)
+ self._kill_process()
+ with open(self.log_path, 'r') as f:
+ text = f.read()
+ syscalls = get_syscall_numbers(text)
+ if syscalls:
+ self._report_error(syscalls)
+ return 1
+ return 0
+
+ def _test_dhcp_v6(self):
+ if self._start_dnsmasq():
+ return 1
+ self._log('starting to run dhclient')
+ with open(os.devnull, 'w') as devnull:
+ self._log('acquiring lease')
+ subprocess.call(['timeout', '1m', 'dhclient', '-6', '-1',
+ '-pf', self.dhclient_pid, 'veth1'],
+ stdout=devnull,
+ stderr=devnull)
+ self._log('releasing lease')
+ subprocess.call(['timeout', '1m', 'dhclient', '-6', '-r',
+ '-pf', self.dhclient_pid, 'veth1'],
+ stdout=devnull,
+ stderr=devnull)
+ self._kill_process()
+ with open(self.log_path, 'r') as f:
+ text = f.read()
+ syscalls = get_syscall_numbers(text)
+ if syscalls:
+ self._report_error(syscalls)
+ return 1
+ return 0
+
+ def _tear_down(self):
+ super(DnsmasqDHCPTest, self)._tear_down()
+ try:
+ with open(self.dhclient_pid, 'r') as f:
+ pid = int(f.read())
+ except (IOError, OSError, ValueError):
+ pid = None
+ if pid:
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+
+
+class DnsmasqTFTPTest(DnsmasqTest):
+
+ def __init__(self):
+ super(DnsmasqTFTPTest, self).__init__()
+ self.name = 'TFTP seccomp'
+ self.config = ('enable-tftp\n'
+ 'tftp-secure\n'
+ 'tftp-root=%s\n')
+ self.tftp_root = os.path.join(self.testing_dir, TFTP_ROOT)
+ self.config = self.config % self.tftp_root
+
+ def _set_up(self):
+ super(DnsmasqTFTPTest, self)._set_up()
+ nobody_uid = pwd.getpwnam('nobody').pw_uid
+ nogroup_gid = grp.getgrnam('nogroup').gr_gid
+ os.mkdir(self.tftp_root)
+ os.chown(self.tftp_root, nobody_uid, nogroup_gid)
+ self.tftp_root_file = os.path.join(self.tftp_root, TFTP_TEST_FILE)
+ self.tftp_file = os.path.join(self.testing_dir, TFTP_TEST_FILE)
+ with open(self.tftp_root_file, 'w') as f:
+ f.write('test\n')
+ os.chown(self.tftp_root_file, nobody_uid, nogroup_gid)
+
+ def _test_basic_tftp(self):
+ if self._start_dnsmasq():
+ return 1
+ self._log('starting to run tftp client')
+ with open(os.devnull, 'w') as devnull:
+ try:
+ subprocess.call(['busybox', 'tftp', '-g', '-l', self.tftp_file,
+ '-r', TFTP_TEST_FILE, 'localhost'],
+ stdout=devnull,
+ stderr=devnull)
+ except OSError as e:
+ if e.errno != errno.ENOENT:
+ raise
+ self._log('Failed to run tftp client. Perhaps it is not installed?')
+ return 1
+ self._kill_process()
+ with open(self.log_path, 'r') as f:
+ text = f.read()
+ syscalls = get_syscall_numbers(text)
+ if syscalls:
+ self._report_error(syscalls)
+ return 1
+ return 0
+
+ def _tear_down(self):
+ super(DnsmasqTFTPTest, self)._tear_down()
+
+
+def main():
+ test = DnsmasqDNSTest()
+ test.run()
+ test = DnsmasqTFTPTest()
+ test.run()
+ # Since DHCP test enters network namespace and mess up interfaces, we are
+ # doing it last
+ test = DnsmasqDHCPTest()
+ test.run()
+ print('Testing finished')
+
+if __name__ == '__main__':
+ main()
+
diff --git a/src/bpf-helper.c b/src/bpf-helper.c
new file mode 100644
index 0000000..1354988
--- /dev/null
+++ b/src/bpf-helper.c
@@ -0,0 +1,96 @@
+/*
+ * Seccomp BPF helper functions
+ *
+ * Copyright (c) 2012 The Chromium OS Authors <[email protected]>
+ * Author: Will Drewry <[email protected]>
+ *
+ * The code may be used by anyone for any purpose,
+ * and can serve as a starting point for developing
+ * applications using prctl(PR_ATTACH_SECCOMP_FILTER).
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "bpf-helper.h"
+
+int bpf_resolve_jumps(struct bpf_labels *labels,
+ struct sock_filter *filter, size_t count)
+{
+ size_t i;
+
+ if (count < 1 || count > BPF_MAXINSNS)
+ return -1;
+ /*
+ * Walk it once, backwards, to build the label table and do fixups.
+ * Since backward jumps are disallowed by BPF, this is easy.
+ */
+ for (i = 0; i < count; ++i) {
+ size_t offset = count - i - 1;
+ struct sock_filter *instr = &filter[offset];
+ if (instr->code != (BPF_JMP+BPF_JA))
+ continue;
+ switch ((instr->jt<<8)|instr->jf) {
+ case (JUMP_JT<<8)|JUMP_JF:
+ if (labels->labels[instr->k].location == 0xffffffff) {
+ fprintf(stderr, "Unresolved label: '%s'\n",
+ labels->labels[instr->k].label);
+ return 1;
+ }
+ instr->k = labels->labels[instr->k].location -
+ (offset + 1);
+ instr->jt = 0;
+ instr->jf = 0;
+ continue;
+ case (LABEL_JT<<8)|LABEL_JF:
+ if (labels->labels[instr->k].location != 0xffffffff) {
+ fprintf(stderr, "Duplicate label use: '%s'\n",
+ labels->labels[instr->k].label);
+ return 1;
+ }
+ labels->labels[instr->k].location = offset;
+ instr->k = 0; /* fall through */
+ instr->jt = 0;
+ instr->jf = 0;
+ continue;
+ }
+ }
+ return 0;
+}
+
+/* Simple lookup table for labels. */
+__u32 seccomp_bpf_label(struct bpf_labels *labels, const char *label)
+{
+ struct __bpf_label *begin = labels->labels, *end;
+ int id;
+
+ if (labels->count == BPF_LABELS_MAX) {
+ fprintf(stderr, "Too many labels\n");
+ exit(1);
+ }
+ if (labels->count == 0) {
+ begin->label = label;
+ begin->location = 0xffffffff;
+ labels->count++;
+ return 0;
+ }
+ end = begin + labels->count;
+ for (id = 0; begin < end; ++begin, ++id) {
+ if (!strcmp(label, begin->label))
+ return id;
+ }
+ begin->label = label;
+ begin->location = 0xffffffff;
+ labels->count++;
+ return id;
+}
+
+void seccomp_bpf_print(struct sock_filter *filter, size_t count)
+{
+ struct sock_filter *end = filter + count;
+ for ( ; filter < end; ++filter)
+ printf("{ code=%u,jt=%u,jf=%u,k=%u },\n",
+ filter->code, filter->jt, filter->jf, filter->k);
+}
+
diff --git a/src/bpf-helper.h b/src/bpf-helper.h
new file mode 100644
index 0000000..e71a128
--- /dev/null
+++ b/src/bpf-helper.h
@@ -0,0 +1,268 @@
+/*
+ * Example wrapper around BPF macros.
+ *
+ * Copyright (c) 2012 The Chromium OS Authors <[email protected]>
+ * Author: Will Drewry <[email protected]>
+ *
+ * The code may be used by anyone for any purpose,
+ * and can serve as a starting point for developing
+ * applications using prctl(PR_SET_SECCOMP, 2, ...).
+ *
+ * No guarantees are provided with respect to the correctness
+ * or functionality of this code.
+ */
+#ifndef __BPF_HELPER_H__
+#define __BPF_HELPER_H__
+
+#include <asm/bitsperlong.h> /* for __BITS_PER_LONG */
+#include <endian.h>
+#include <linux/filter.h>
+#include <linux/seccomp.h> /* for seccomp_data */
+#include <linux/types.h>
+#include <linux/unistd.h>
+#include <stddef.h>
+
+#define BPF_LABELS_MAX 256
+struct bpf_labels {
+ int count;
+ struct __bpf_label {
+ const char *label;
+ __u32 location;
+ } labels[BPF_LABELS_MAX];
+};
+
+int bpf_resolve_jumps(struct bpf_labels *labels,
+ struct sock_filter *filter, size_t count);
+__u32 seccomp_bpf_label(struct bpf_labels *labels, const char *label);
+void seccomp_bpf_print(struct sock_filter *filter, size_t count);
+
+#define JUMP_JT 0xff
+#define JUMP_JF 0xff
+#define LABEL_JT 0xfe
+#define LABEL_JF 0xfe
+
+#define ALLOW \
+ BPF_STMT(BPF_RET+BPF_K, SECCOMP_RET_ALLOW)
+#define DENY \
+ BPF_STMT(BPF_RET+BPF_K, SECCOMP_RET_KILL)
+#define TRAP \
+ BPF_STMT(BPF_RET+BPF_K, SECCOMP_RET_TRAP)
+#define JUMP(labels, label) \
+ BPF_JUMP(BPF_JMP+BPF_JA, FIND_LABEL((labels), (label)), \
+ JUMP_JT, JUMP_JF)
+#define LABEL(labels, label) \
+ BPF_JUMP(BPF_JMP+BPF_JA, FIND_LABEL((labels), (label)), \
+ LABEL_JT, LABEL_JF)
+#define SYSCALL(nr, jt) \
+ BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, (nr), 0, 1), \
+ jt
+
+/* Lame, but just an example */
+#define FIND_LABEL(labels, label) seccomp_bpf_label((labels), #label)
+
+#define EXPAND(...) __VA_ARGS__
+
+/* Ensure that we load the logically correct offset. */
+#if __BYTE_ORDER == __LITTLE_ENDIAN
+#define LO_ARG(idx) offsetof(struct seccomp_data, args[(idx)])
+#elif __BYTE_ORDER == __BIG_ENDIAN
+#define LO_ARG(idx) offsetof(struct seccomp_data, args[(idx)]) + sizeof(__u32)
+#else
+#error "Unknown endianness"
+#endif
+
+/* Map all width-sensitive operations */
+#if __BITS_PER_LONG == 32
+
+#define JEQ(x, jt) JEQ32(x, EXPAND(jt))
+#define JNE(x, jt) JNE32(x, EXPAND(jt))
+#define JGT(x, jt) JGT32(x, EXPAND(jt))
+#define JLT(x, jt) JLT32(x, EXPAND(jt))
+#define JGE(x, jt) JGE32(x, EXPAND(jt))
+#define JLE(x, jt) JLE32(x, EXPAND(jt))
+#define JA(x, jt) JA32(x, EXPAND(jt))
+#define ARG(i) ARG_32(i)
+
+#elif __BITS_PER_LONG == 64
+
+/* Ensure that we load the logically correct offset. */
+#if __BYTE_ORDER == __LITTLE_ENDIAN
+#define ENDIAN(_lo, _hi) _lo, _hi
+#define HI_ARG(idx) offsetof(struct seccomp_data, args[(idx)]) + sizeof(__u32)
+#elif __BYTE_ORDER == __BIG_ENDIAN
+#define ENDIAN(_lo, _hi) _hi, _lo
+#define HI_ARG(idx) offsetof(struct seccomp_data, args[(idx)])
+#endif
+
+union arg64 {
+ struct {
+ __u32 ENDIAN(lo32, hi32);
+ };
+ __u64 u64;
+};
+
+#define JEQ(x, jt) \
+ JEQ64(((union arg64){.u64 = (x)}).lo32, \
+ ((union arg64){.u64 = (x)}).hi32, \
+ EXPAND(jt))
+#define JGT(x, jt) \
+ JGT64(((union arg64){.u64 = (x)}).lo32, \
+ ((union arg64){.u64 = (x)}).hi32, \
+ EXPAND(jt))
+#define JGE(x, jt) \
+ JGE64(((union arg64){.u64 = (x)}).lo32, \
+ ((union arg64){.u64 = (x)}).hi32, \
+ EXPAND(jt))
+#define JNE(x, jt) \
+ JNE64(((union arg64){.u64 = (x)}).lo32, \
+ ((union arg64){.u64 = (x)}).hi32, \
+ EXPAND(jt))
+#define JLT(x, jt) \
+ JLT64(((union arg64){.u64 = (x)}).lo32, \
+ ((union arg64){.u64 = (x)}).hi32, \
+ EXPAND(jt))
+#define JLE(x, jt) \
+ JLE64(((union arg64){.u64 = (x)}).lo32, \
+ ((union arg64){.u64 = (x)}).hi32, \
+ EXPAND(jt))
+
+#define JA(x, jt) \
+ JA64(((union arg64){.u64 = (x)}).lo32, \
+ ((union arg64){.u64 = (x)}).hi32, \
+ EXPAND(jt))
+#define ARG(i) ARG_64(i)
+
+#else
+#error __BITS_PER_LONG value unusable.
+#endif
+
+/* Loads the arg into A */
+#define ARG_32(idx) \
+ BPF_STMT(BPF_LD+BPF_W+BPF_ABS, LO_ARG(idx))
+
+/* Loads lo into M[0] and hi into M[1] and A */
+#define ARG_64(idx) \
+ BPF_STMT(BPF_LD+BPF_W+BPF_ABS, LO_ARG(idx)), \
+ BPF_STMT(BPF_ST, 0), /* lo -> M[0] */ \
+ BPF_STMT(BPF_LD+BPF_W+BPF_ABS, HI_ARG(idx)), \
+ BPF_STMT(BPF_ST, 1) /* hi -> M[1] */
+
+#define JEQ32(value, jt) \
+ BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, (value), 0, 1), \
+ jt
+
+#define JNE32(value, jt) \
+ BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, (value), 1, 0), \
+ jt
+
+#define JA32(value, jt) \
+ BPF_JUMP(BPF_JMP+BPF_JSET+BPF_K, (value), 0, 1), \
+ jt
+
+#define JGE32(value, jt) \
+ BPF_JUMP(BPF_JMP+BPF_JGE+BPF_K, (value), 0, 1), \
+ jt
+
+#define JGT32(value, jt) \
+ BPF_JUMP(BPF_JMP+BPF_JGT+BPF_K, (value), 0, 1), \
+ jt
+
+#define JLE32(value, jt) \
+ BPF_JUMP(BPF_JMP+BPF_JGT+BPF_K, (value), 1, 0), \
+ jt
+
+#define JLT32(value, jt) \
+ BPF_JUMP(BPF_JMP+BPF_JGE+BPF_K, (value), 1, 0), \
+ jt
+
+/*
+ * All the JXX64 checks assume lo is saved in M[0] and hi is saved in both
+ * A and M[1]. This invariant is kept by restoring A if necessary.
+ */
+#define JEQ64(lo, hi, jt) \
+ /* if (hi != arg.hi) goto NOMATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, (hi), 0, 5), \
+ BPF_STMT(BPF_LD+BPF_MEM, 0), /* swap in lo */ \
+ /* if (lo != arg.lo) goto NOMATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, (lo), 0, 2), \
+ BPF_STMT(BPF_LD+BPF_MEM, 1), \
+ jt, \
+ BPF_STMT(BPF_LD+BPF_MEM, 1)
+
+#define JNE64(lo, hi, jt) \
+ /* if (hi != arg.hi) goto MATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, (hi), 0, 3), \
+ BPF_STMT(BPF_LD+BPF_MEM, 0), \
+ /* if (lo != arg.lo) goto MATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, (lo), 2, 0), \
+ BPF_STMT(BPF_LD+BPF_MEM, 1), \
+ jt, \
+ BPF_STMT(BPF_LD+BPF_MEM, 1)
+
+#define JA64(lo, hi, jt) \
+ /* if (hi & arg.hi) goto MATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JSET+BPF_K, (hi), 3, 0), \
+ BPF_STMT(BPF_LD+BPF_MEM, 0), \
+ /* if (lo & arg.lo) goto MATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JSET+BPF_K, (lo), 0, 2), \
+ BPF_STMT(BPF_LD+BPF_MEM, 1), \
+ jt, \
+ BPF_STMT(BPF_LD+BPF_MEM, 1)
+
+#define JGE64(lo, hi, jt) \
+ /* if (hi > arg.hi) goto MATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JGT+BPF_K, (hi), 4, 0), \
+ /* if (hi != arg.hi) goto NOMATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, (hi), 0, 5), \
+ BPF_STMT(BPF_LD+BPF_MEM, 0), \
+ /* if (lo >= arg.lo) goto MATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JGE+BPF_K, (lo), 0, 2), \
+ BPF_STMT(BPF_LD+BPF_MEM, 1), \
+ jt, \
+ BPF_STMT(BPF_LD+BPF_MEM, 1)
+
+#define JGT64(lo, hi, jt) \
+ /* if (hi > arg.hi) goto MATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JGT+BPF_K, (hi), 4, 0), \
+ /* if (hi != arg.hi) goto NOMATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, (hi), 0, 5), \
+ BPF_STMT(BPF_LD+BPF_MEM, 0), \
+ /* if (lo > arg.lo) goto MATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JGT+BPF_K, (lo), 0, 2), \
+ BPF_STMT(BPF_LD+BPF_MEM, 1), \
+ jt, \
+ BPF_STMT(BPF_LD+BPF_MEM, 1)
+
+#define JLE64(lo, hi, jt) \
+ /* if (hi < arg.hi) goto MATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JGE+BPF_K, (hi), 0, 4), \
+ /* if (hi != arg.hi) goto NOMATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, (hi), 0, 5), \
+ BPF_STMT(BPF_LD+BPF_MEM, 0), \
+ /* if (lo <= arg.lo) goto MATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JGT+BPF_K, (lo), 2, 0), \
+ BPF_STMT(BPF_LD+BPF_MEM, 1), \
+ jt, \
+ BPF_STMT(BPF_LD+BPF_MEM, 1)
+
+#define JLT64(lo, hi, jt) \
+ /* if (hi < arg.hi) goto MATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JGE+BPF_K, (hi), 0, 4), \
+ /* if (hi != arg.hi) goto NOMATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, (hi), 0, 5), \
+ BPF_STMT(BPF_LD+BPF_MEM, 0), \
+ /* if (lo < arg.lo) goto MATCH; */ \
+ BPF_JUMP(BPF_JMP+BPF_JGE+BPF_K, (lo), 2, 0), \
+ BPF_STMT(BPF_LD+BPF_MEM, 1), \
+ jt, \
+ BPF_STMT(BPF_LD+BPF_MEM, 1)
+
+#define LOAD_SYSCALL_NR \
+ BPF_STMT(BPF_LD+BPF_W+BPF_ABS, \
+ offsetof(struct seccomp_data, nr))
+#define LOAD_ARCH \
+ BPF_STMT(BPF_LD+BPF_W+BPF_ABS, \
+ offsetof(struct seccomp_data, arch))
+
+#endif /* __BPF_HELPER_H__ */
+
diff --git a/src/config.h b/src/config.h
index 4c03e2c..3f5ef52 100644
--- a/src/config.h
+++ b/src/config.h
@@ -180,6 +180,7 @@ RESOLVFILE
/* #define HAVE_LIBIDN2 */
/* #define HAVE_CONNTRACK */
/* #define HAVE_DNSSEC */
+/* #define HAVE_SECCOMP */
/* Default locations for important system files. */
@@ -232,6 +233,10 @@ HAVE_GETOPT_LONG
HAVE_SOCKADDR_SA_LEN
defined if struct sockaddr has sa_len field (*BSD)
+
+HAVE_SECCOMP
+ defined if seccomp-bpf and mount namespaces Linux-only features are
+ available, to enable the sandbox code.
*/
/* Must precede __linux__ since uClinux defines __linux__ too. */
@@ -265,6 +270,10 @@ HAVE_SOCKADDR_SA_LEN
#elif defined(__linux__)
#define HAVE_LINUX_NETWORK
#define HAVE_GETOPT_LONG
+#if defined(__x86_64__) || defined(__i386__) || defined(__aarch64__) || \
+ defined(__arm__) || defined(__powerpc__)
+#define HAVE_SECCOMP
+#endif
#undef HAVE_SOCKADDR_SA_LEN
#elif defined(__FreeBSD__) || \
@@ -365,6 +374,10 @@ HAVE_SOCKADDR_SA_LEN
#undef HAVE_LOOP
#endif
+#ifdef NO_SECCOMP
+#undef HAVE_SECCOMP
+#endif
+
#if defined (HAVE_LINUX_NETWORK) && !defined(NO_INOTIFY)
#define HAVE_INOTIFY
#endif
@@ -443,6 +456,10 @@ static char *compile_opts =
"no-"
#endif
"DNSSEC "
+#ifndef HAVE_SECCOMP
+"no-"
+#endif
+"SECCOMP "
#ifdef NO_ID
"no-ID "
#endif
diff --git a/src/dnsmasq.c b/src/dnsmasq.c
index 771bec1..79562b3 100644
--- a/src/dnsmasq.c
+++ b/src/dnsmasq.c
@@ -67,7 +67,6 @@ int main (int argc, char **argv)
bindtextdomain("dnsmasq", LOCALEDIR);
textdomain("dnsmasq");
#endif
-
sigact.sa_handler = sig_handler;
sigact.sa_flags = 0;
sigemptyset(&sigact.sa_mask);
@@ -87,7 +86,27 @@ int main (int argc, char **argv)
rand_init(); /* Must precede read_opts() */
read_opts(argc, argv, compile_opts);
-
+
+ /* Enabling sandbox */
+#ifndef HAVE_SECCOMP
+ if (!option_bool(OPT_NO_SANDBOX) && option_bool(OPT_SANDBOX_FORCE))
+ {
+ die(_("Seccomp not available: see HAVE_SECCOMP in src/config.h"), NULL, EC_BADCONF);
+ }
+#else
+ if (!option_bool(OPT_NO_SANDBOX))
+ {
+ if (setup_mount_namespace(daemon) && option_bool(OPT_SANDBOX_FORCE))
+ {
+ die(_("mount namespace initialization failed"), NULL, EC_MISC);
+ }
+ if (setup_seccomp(daemon) && option_bool(OPT_SANDBOX_FORCE))
+ {
+ die(_("seccomp initialization failed"), NULL, EC_MISC);
+ }
+ }
+#endif
+
if (daemon->edns_pktsz < PACKETSZ)
daemon->edns_pktsz = PACKETSZ;
diff --git a/src/dnsmasq.h b/src/dnsmasq.h
index 24dda08..ae85dc9 100644
--- a/src/dnsmasq.h
+++ b/src/dnsmasq.h
@@ -239,7 +239,10 @@ struct event_desc {
#define OPT_MAC_B64 54
#define OPT_MAC_HEX 55
#define OPT_TFTP_APREF_MAC 56
-#define OPT_LAST 57
+#define OPT_NO_SANDBOX 57
+#define OPT_SANDBOX_FORCE 58
+#define OPT_SANDBOX_TEST 59
+#define OPT_LAST 60
/* extra flags for my_syslog, we use a couple of facilities since they are known
not to occupy the same bits as priorities, no matter how syslog.h is set up. */
@@ -1558,3 +1561,19 @@ int check_source(struct dns_header *header, size_t plen, unsigned char *pseudohe
/* arp.c */
int find_mac(union mysockaddr *addr, unsigned char *mac, int lazy, time_t now);
int do_arp_script_run(void);
+
+/* seccomp.c */
+#ifdef HAVE_SECCOMP
+int setup_seccomp(struct daemon *daemon);
+#endif
+
+/* seccomp-testing.c */
+#ifdef HAVE_SECCOMP
+int setup_seccomp_testing();
+#endif
+
+/* mount-namespace.c */
+#ifdef HAVE_SECCOMP
+int setup_mount_namespace(struct daemon *daemon);
+#endif
+
diff --git a/src/mount-namespace.c b/src/mount-namespace.c
new file mode 100644
index 0000000..c3a6f8e
--- /dev/null
+++ b/src/mount-namespace.c
@@ -0,0 +1,387 @@
+/* dnsmasq is Copyright (c) 2000-2017 Simon Kelley
+
+ This program 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; version 2 dated June, 1991, or
+ (at your option) version 3 dated 29 June, 2007.
+
+ This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* Using linux mount namespace implementation to limit dnsmasq access to files.
+
+ Basically, we create a copy of the file tree in /tmp, including only files
+ and directories, necessary for the dnsmasq, mount them to their
+ versions in the original file tree and then do pivot_root into this folder
+ to prevent possible escapes. While seccomp restrict syscalls, a mount
+ namespace complements this by restricting which files can be read and
+ modified on the filesystem, so we end up with a robust sandbox.
+ Also we create a copy of our cwd in our fake tree and chdir into it later,
+ so all relative links still work.
+
+ We use mount namespaces, so all mount operations we do to establish our
+ sandbox, doesn't affect anything outside dnsmasq process.
+
+ If you want to add a file or directory there are two possibilities:
+ 1) The file or directory only need to exist, doesn't hold any data on the
+ beginning and you don't need to save the data between dnsmasq launches.
+ Then you use: create_sandbox_dir / create_sandbox_file.
+ Examples:
+ create_sandbox_file("/tmp/dnsmasq_tmp_cache")
+ create_sandbox_dir(cwd) // to chdir into it later, we don't really
+ need its content.
+ 2) You need the contents of the file/dir to be reachable by application.
+ Then you use: mount_dir / mount_file.
+ Examples:
+ mount_dir("/var/dnsmasq/hosts_file_directory")
+ mount_file("/etc/resolv.conf") */
+
+#include "dnsmasq.h"
+
+#ifdef HAVE_SECCOMP
+
+#include <sched.h>
+#include <libgen.h>
+#include <sys/mount.h>
+#include <sys/syscall.h>
+
+#define MOUNT_ROOT "/tmp/dnsmasq.sandbox"
+#define MOUNT_FILE 0
+#define MOUNT_DIR 1
+
+static char *cwd;
+
+static char* join_paths(char *first, char *second)
+{
+ /* +2 for null byte and slash, that may be added */
+ char *result = safe_malloc(strlen(first) + strlen(second) + 2);