-
Notifications
You must be signed in to change notification settings - Fork 593
Expand file tree
/
Copy pathrooter.py
More file actions
1152 lines (1004 loc) · 37.6 KB
/
Copy pathrooter.py
File metadata and controls
1152 lines (1004 loc) · 37.6 KB
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
#!/usr/bin/env python
# Copyright (C) 2014-2016 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
import argparse
import errno
import grp
import ipaddress
import json
import logging.handlers
import os
import signal
import socket
import stat
import subprocess
import sys
if sys.version_info[:2] < (3, 10):
sys.exit("You are running an incompatible version of Python, please use >= 3.10")
CUCKOO_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), "..")
sys.path.append(CUCKOO_ROOT)
from lib.cuckoo.common.path_utils import path_delete, path_exists
username = False
log = logging.getLogger("cuckoo-rooter")
formatter = logging.Formatter("%(asctime)s [%(name)s] %(levelname)s: %(message)s")
ch = logging.StreamHandler()
ch.setFormatter(formatter)
log.addHandler(ch)
log.setLevel(logging.INFO)
class ServicePaths:
iptables = None
iptables_save = None
iptables_restore = None
ip = None
def run(*args):
"""Wrapper to subprocess.run."""
log.debug("Running command: %s", " ".join(args))
try:
p = subprocess.run(args, capture_output=True, text=True, check=False)
return p.stdout, p.stderr
except Exception as e:
log.error("Error executing command %s: %s", args, e)
return "", str(e)
def get_tun_peer_address(interface_name):
"""Gets the peer address of a tun interface.
Args:
interface_name: The name of the tun interface (e.g., "tun0").
Format similar to:
inet 172.30.1.5 peer 172.30.1.6/32 scope global
Returns:
The peer IP address as a string, or None if an error occurs. Returns None if the interface does not exist, or does not have a peer.
"""
try:
result = subprocess.run(["ip", "addr", "show", interface_name], capture_output=True, text=True, check=True)
output = result.stdout
for line in output.splitlines():
if "peer" in line:
parts = line.split()
if len(parts) > 1: # Check if there's a second element to avoid IndexError
peer_with_cidr = parts[3]
try:
# Handle CIDR notation using ipaddress library
peer_ip = ipaddress.ip_interface(peer_with_cidr).ip.exploded
return peer_ip
except ValueError: # Handle invalid CIDR notations
try:
peer_ip = peer_with_cidr.split("/")[0] # Try just splitting by /
return peer_ip
except IndexError:
return None # Invalid format - give up.
else:
return None # No peer address found on the line.
return None # "peer" not found in the output
except subprocess.CalledProcessError as e:
if e.returncode == 1: # Interface not found
return None
else:
print(f"Error executing ip command: {e}")
return None
except FileNotFoundError:
print("ip command not found. Is iproute2 installed?")
return None
def enable_ip_forwarding(sysctl="/usr/sbin/sysctl"):
log.debug("Enabling IPv4 forwarding")
run(sysctl, "-w" "net.ipv4.ip_forward=1")
def check_tuntap(vm_name, main_iface):
"""Create tuntap device for qemu vms"""
try:
run(ServicePaths.ip, "tuntap", "add", "dev", f"tap_{vm_name}", "mode", "tap", "user", username)
run(ServicePaths.ip, "link", "set", "tap_{vm_name}", "master", main_iface)
run(ServicePaths.ip, "link", "set", "dev", "tap_{vm_name}", "up")
run(ServicePaths.ip, "link", "set", "dev", main_iface, "up")
return True
except subprocess.CalledProcessError:
return False
def run_iptables(*args, **kwargs):
if kwargs and kwargs.get('netns'):
netns = kwargs.get('netns')
iptables_args = ["/usr/sbin/ip", "netns", "exec", netns, ServicePaths.iptables]
else:
iptables_args = [ServicePaths.iptables]
iptables_args.extend(list(args))
iptables_args.extend(["-m", "comment", "--comment", "CAPE-rooter"])
return run(*iptables_args)
def cleanup_rooter():
"""Filter out all CAPE rooter entries from iptables-save and
restore the resulting ruleset."""
stdout = False
try:
stdout, _ = run(ServicePaths.iptables_save)
except OSError as e:
log.error("Failed to clean CAPE rooter rules. Is iptables-save available? %s", e)
return
if not stdout:
return
cleaned = [line for line in stdout.split("\n") if line and "CAPE-rooter" not in line]
p = subprocess.Popen([ServicePaths.iptables_restore], stdin=subprocess.PIPE, universal_newlines=True)
p.communicate(input="\n".join(cleaned))
run_iptables("-F", "CAPE_ACCEPTED_SEGMENTS")
run_iptables("-F", "CAPE_REJECTED_SEGMENTS")
run_iptables("-N", "CAPE_ACCEPTED_SEGMENTS")
run_iptables("-N", "CAPE_REJECTED_SEGMENTS")
run_iptables("-I", "FORWARD", "-j", "CAPE_REJECTED_SEGMENTS")
run_iptables("-I", "FORWARD", "-j", "CAPE_ACCEPTED_SEGMENTS")
def nic_available(interface):
"""Check if specified network interface is available."""
try:
subprocess.check_call(
[settings.ip, "link", "show", interface], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True
)
return True
except subprocess.CalledProcessError:
return False
def rt_available(rt_table):
"""Check if specified routing table is defined."""
try:
subprocess.check_call(
[settings.ip, "route", "list", "table", rt_table],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)
return True
except subprocess.CalledProcessError:
return False
def init_vrf(rt_table, dirty_line_dev):
run(ServicePaths.ip, "link", "add", "dirty-line", "type", "vrf", "table", rt_table)
run(ServicePaths.ip, "link", "set", "dev", "dirty-line", "up")
run(ServicePaths.ip, "rule", "add", "l3mdev", "proto", "kernel", "prio", "1000")
run(ServicePaths.ip, "rule", "add", "l3mdev", "proto", "kernel", "unreachable", "prio", "1001")
run(ServicePaths.ip, "rule", "add", "lookup", "local", "proto", "kernel", "prio", "32765")
run(ServicePaths.ip, "rule", "delete", "lookup", "local", "prio", "0")
run(ServicePaths.ip, "link", "set", "dev", dirty_line_dev, "master", "dirty-line")
def cleanup_vrf(dirty_line_dev):
run(ServicePaths.ip, "rule", "add", "lookup", "local", "proto", "kernel", "prio", "0")
run(ServicePaths.ip, "rule", "delete", "lookup", "local", "prio", "32765")
run(ServicePaths.ip, "rule", "delete", "l3mdev", "prio", "1000")
run(ServicePaths.ip, "rule", "delete", "l3mdev", "unreachable", "prio", "1001")
run(ServicePaths.ip, "link", "set", "dev", dirty_line_dev, "nomaster")
run(ServicePaths.ip, "link", "set", "dev", "dirty-line", "down")
run(ServicePaths.ip, "link", "del", "dirty-line")
def add_dev_to_vrf(dev):
run(ServicePaths.ip, "link", "set", "dev", dev, "master", "dirty-line")
def delete_dev_from_vrf(dev):
run(ServicePaths.ip, "link", "set", "dev", dev, "nomaster")
def vpn_status(name):
"""Gets current VPN status."""
ret = {}
for line in run(settings.systemctl, "status", f"openvpn@{name}.service")[0].split("\n"):
if "running" in line:
ret[name] = "running"
break
return ret
def forward_drop():
"""Disable any and all forwarding unless explicitly said so."""
run_iptables("-P", "FORWARD", "DROP")
def state_enable():
"""Enable stateful connection tracking."""
run_iptables("-A", "INPUT", "-m", "state", "--state", "ESTABLISHED,RELATED", "-j", "ACCEPT")
run_iptables("-I", "CAPE_ACCEPTED_SEGMENTS", "-m", "state", "--state", "ESTABLISHED,RELATED", "-j", "ACCEPT")
def state_disable():
"""Disable stateful connection tracking."""
while True:
_, err = run_iptables("-D", "INPUT", "-m", "state", "--state", "ESTABLISHED,RELATED", "-j", "ACCEPT")
if err:
break
_, err = run_iptables("-D", "CAPE_ACCEPTED_SEGMENTS", "-m", "state", "--state", "ESTABLISHED,RELATED", "-j", "ACCEPT")
if err:
break
def enable_nat(interface):
"""Enable NAT on this interface."""
run_iptables("-t", "nat", "-A", "POSTROUTING", "-o", interface, "-j", "MASQUERADE")
def disable_nat(interface):
"""Disable NAT on this interface."""
run_iptables("-t", "nat", "-D", "POSTROUTING", "-o", interface, "-j", "MASQUERADE")
def enable_mitmdump(interface, client, port, netns):
"""Enable mitmdump on this interface."""
log.info("enable_mitmdump client: %s port: %s netns: %s", client, port, netns)
if netns:
# assume all traffic in network namespace can be captured
run_iptables(
"-t",
"nat",
"-I",
"PREROUTING",
"-p",
"tcp",
"--dport",
"443",
"-j",
"REDIRECT",
"--to-port",
port,
netns=netns,
)
run_iptables(
"-t",
"nat",
"-I",
"PREROUTING",
"-p",
"tcp",
"--dport",
"80",
"-j",
"REDIRECT",
"--to-port",
port,
netns=netns,
)
else:
run_iptables(
"-t",
"nat",
"-I",
"PREROUTING",
"-i",
interface,
"-s",
client,
"-p",
"tcp",
"--dport",
"443",
"-j",
"REDIRECT",
"--to-port",
port,
)
run_iptables(
"-t",
"nat",
"-I",
"PREROUTING",
"-i",
interface,
"-s",
client,
"-p",
"tcp",
"--dport",
"80",
"-j",
"REDIRECT",
"--to-port",
port
)
def disable_mitmdump(interface, client, port, netns):
"""Disable mitmdump on this interface."""
if netns:
run_iptables(
"-t",
"nat",
"-D",
"PREROUTING",
"-p",
"tcp",
"--dport",
"443",
"-j",
"REDIRECT",
"--to-port",
port,
netns=netns,
)
run_iptables(
"-t",
"nat",
"-D",
"PREROUTING",
"-p",
"tcp",
"--dport",
"80",
"-j",
"REDIRECT",
"--to-port",
port,
netns=netns,
)
else:
run_iptables(
"-t",
"nat",
"-D",
"PREROUTING",
"-i",
interface,
"-s",
client,
"-p",
"tcp",
"--dport",
"443",
"-j",
"REDIRECT",
"--to-port",
port,
)
run_iptables(
"-t",
"nat",
"-D",
"PREROUTING",
"-i",
interface,
"-s",
client,
"-p",
"tcp",
"--dport",
"80",
"-j",
"REDIRECT",
"--to-port",
port,
)
def polarproxy_enable(interface, client, tls_port, proxy_port):
log.info("Enabling polarproxy route.")
run_iptables(
"-t",
"nat",
"-I",
"PREROUTING",
"1",
"-i",
interface,
"--source",
client,
"-p",
"tcp",
"--dport",
tls_port,
"-j",
"REDIRECT",
"--to",
proxy_port
)
run_iptables(
"-A",
"INPUT",
"-i",
interface,
"-p",
"tcp",
"--dport",
proxy_port,
"-m",
"state",
"--state",
"NEW",
"-j",
"ACCEPT"
)
def polarproxy_disable(interface, client, tls_port, proxy_port):
log.info("Disabling polarproxy route.")
run_iptables(
"-t",
"nat",
"-D",
"PREROUTING",
"-i",
interface,
"--source",
client,
"-p",
"tcp",
"--dport",
tls_port,
"-j",
"REDIRECT",
"--to",
proxy_port
)
run_iptables(
"-D",
"INPUT",
"-i",
interface,
"-p",
"tcp",
"--dport",
proxy_port,
"-m",
"state",
"--state",
"NEW",
"-j",
"ACCEPT"
)
def libvirt_fwo_enable(interface, source):
"""Enable LIBVIRT_FWO for a specific interface and source."""
run_iptables("-I", "LIBVIRT_FWO", "1", "-i", interface, "-s", source, "-j", "ACCEPT")
def libvirt_fwo_disable(interface, source):
"""Disable LIBVIRT_FWO for a specific interface and source."""
run_iptables("-D", "LIBVIRT_FWO", "-i", interface, "-s", source, "-j", "ACCEPT")
def init_rttable(rt_table, interface):
"""Initialise routing table for this interface using routes
from main table."""
if rt_table in ("local", "main", "default"):
return
stdout, _ = run(settings.ip, "route", "list", "dev", interface)
for line in stdout.split("\n"):
args = ["route", "add"] + [x for x in line.split(" ") if x]
args += ["dev", interface, "table", rt_table]
run(settings.ip, *args)
def flush_rttable(rt_table):
"""Flushes specified routing table entries."""
if rt_table in ("local", "main", "default"):
return
run(settings.ip, "route", "flush", "table", rt_table)
def forward_enable(src, dst, ipaddr, accept_segments=None, proto=None, ports=None):
"""Enable forwarding a specific IP address from one interface into another."""
# Delete libvirt's default FORWARD REJECT rules. e.g.:
# -A FORWARD -o virbr0 -j REJECT --reject-with icmp-port-unreachable
# -A FORWARD -i virbr0 -j REJECT --reject-with icmp-port-unreachable
run_iptables("-D", "FORWARD", "-i", src, "-j", "REJECT")
run_iptables("-D", "FORWARD", "-o", src, "-j", "REJECT")
if ports and (not proto or proto not in ["tcp", "udp"]):
log.debug("Invalid protocol of transport layer")
return False
if ports:
if "-" in ports:
# We need a single hyphen to indicate that it is a range
if ports.count("-") != 1:
log.debug("Invalid ports range entry: %s", ports)
return False
else:
start_port, end_port = ports.split("-")
if not start_port.isdigit() or not end_port.isdigit() or start_port > end_port:
log.debug("Invalid port range entry: %s", ports)
return False
else:
# Good to go! iptables takes port ranges as start:end
ports = ports.replace("-", ":")
# Handle a single port
else:
if not ports.isdigit():
log.debug("Invalid port entry: %s", ports)
return False
args = ["-I", "CAPE_ACCEPTED_SEGMENTS", "-i", src, "-o", dst, "--source", ipaddr]
if accept_segments:
args += ["--destination", accept_segments]
if ports:
args += ["-p", proto, "-m", "multiport", "--dport", ports]
args += ["-j", "ACCEPT"]
run_iptables(*args)
def forward_disable(src, dst, ipaddr, accept_segments=None, proto=None, ports=None):
"""Disable forwarding of a specific IP address from one interface into
another."""
if ports and (not proto or proto not in ["tcp", "udp"]):
log.debug("Invalid protocol of transport layer")
return False
if ports:
if "-" in ports:
# We need a single hyphen to indicate that it is a range
if ports.count("-") != 1:
log.debug("Invalid ports range entry: %s", ports)
return False
else:
start_port, end_port = ports.split("-")
if not start_port.isdigit() or not end_port.isdigit() or start_port > end_port:
log.debug("Invalid port range entry: %s", ports)
return False
else:
# Good to go! iptables takes port ranges as start:end
ports = ports.replace("-", ":")
# Handle a single port
else:
if not ports.isdigit():
log.debug("Invalid port entry: %s", ports)
return False
args = ["-D", "CAPE_ACCEPTED_SEGMENTS", "-i", src, "-o", dst, "--source", ipaddr]
if accept_segments:
args += ["--destination", accept_segments]
if ports:
args += ["-p", proto, "-m", "multiport", "--dport", ports]
args += ["-j", "ACCEPT"]
run_iptables(*args)
def forward_reject_enable(src, dst, ipaddr, reject_segments):
"""Enable forwarding a specific IP address from one interface into another
but reject some targets network segments."""
run_iptables(
"-I", "CAPE_REJECTED_SEGMENTS", "-i", src, "-o", dst, "--source", ipaddr, "--destination", reject_segments, "-j", "REJECT"
)
def forward_reject_disable(src, dst, ipaddr, reject_segments):
"""Disable forwarding a specific IP address from one interface into another
but reject some targets network segments."""
run_iptables(
"-D", "CAPE_REJECTED_SEGMENTS", "-i", src, "-o", dst, "--source", ipaddr, "--destination", reject_segments, "-j", "REJECT"
)
def hostports_reject_enable(src, ipaddr, reject_hostports):
"""Enable drop a specific IP address from one interface to host ports."""
run_iptables(
"-A", "INPUT", "-i", src, "--source", ipaddr, "-p", "tcp", "-m", "multiport", "--dport", reject_hostports, "-j", "REJECT"
)
run_iptables(
"-A", "INPUT", "-i", src, "--source", ipaddr, "-p", "udp", "-m", "multiport", "--dport", reject_hostports, "-j", "REJECT"
)
def hostports_reject_disable(src, ipaddr, reject_hostports):
"""Disable drop a specific IP address from one interface to host ports."""
run_iptables(
"-D", "INPUT", "-i", src, "--source", ipaddr, "-p", "tcp", "-m", "multiport", "--dport", reject_hostports, "-j", "REJECT"
)
run_iptables(
"-D", "INPUT", "-i", src, "--source", ipaddr, "-p", "udp", "-m", "multiport", "--dport", reject_hostports, "-j", "REJECT"
)
def srcroute_enable(rt_table, ipaddr):
"""Enable routing policy for specified source IP address."""
run(settings.ip, "rule", "add", "from", ipaddr, "table", rt_table)
run(settings.ip, "route", "flush", "cache")
def srcroute_disable(rt_table, ipaddr):
"""Disable routing policy for specified source IP address."""
run(settings.ip, "rule", "del", "from", ipaddr, "table", rt_table)
run(settings.ip, "route", "flush", "cache")
def dns_forward(action, vm_ip, dns_ip, dns_port="53"):
"""Route DNS requests from the VM to a custom DNS on a separate network."""
run_iptables(
"-t",
"nat",
action,
"PREROUTING",
"-p",
"tcp",
"--dport",
"53",
"--source",
vm_ip,
"-j",
"DNAT",
"--to-destination",
"%s:%s" % (dns_ip, dns_port),
)
run_iptables(
"-t",
"nat",
action,
"PREROUTING",
"-p",
"udp",
"--dport",
"53",
"--source",
vm_ip,
"-j",
"DNAT",
"--to-destination",
"%s:%s" % (dns_ip, dns_port),
)
def inetsim_redirect_port(action, srcip, dstip, ports):
"""Note that the parameters (probably) mean the opposite of what they
imply; this method adds or removes an iptables rule for redirect traffic
from (srcip, srcport) to (dstip, dstport).
E.g., if 192.168.56.101:80 -> 192.168.56.1:8080, then it redirects
outgoing traffic from 192.168.56.101 to port 80 to 192.168.56.1:8080.
"""
for entry in ports.split():
if entry.count(":") != 1:
log.debug("Invalid inetsim ports entry: %s", entry)
continue
srcport, dstport = entry.split(":")
if not dstport.isdigit():
log.debug("Invalid inetsim dstport entry: %s", dstport)
continue
# Handle srcport ranges
if "-" in srcport:
# We need a single hyphen to indicate that it is a range
if srcport.count("-") != 1:
log.debug("Invalid inetsim srcport range entry: %s", srcport)
continue
else:
start_srcport, end_srcport = srcport.split("-")
if not start_srcport.isdigit() or not end_srcport.isdigit():
log.debug("Invalid inetsim srcport range entry: %s", srcport)
continue
else:
# Good to go! iptables takes port ranges as start:end
srcport = srcport.replace("-", ":")
# Handle a single srcport
else:
if not srcport.isdigit():
log.debug("Invalid inetsim srcport entry: %s", srcport)
continue
run_iptables(
"-t",
"nat",
action,
"PREROUTING",
"--source",
srcip,
"-p",
"tcp",
"--syn",
"--dport",
srcport,
"-j",
"DNAT",
"--to-destination",
"%s:%s" % (dstip, dstport),
)
def inetsim_service_port_trap(action, srcip, dstip, protocol):
# Note that the multiport limit for ports specified is 15,
# so we will split this up into two rules
run_iptables(
"-t",
"nat",
action,
"PREROUTING",
"--source",
srcip,
"-p",
protocol,
"-m",
"multiport",
"--dports",
# The following ports are used for default services on Ubuntu
"7,9,13,17,19,21,22,25,37,69,79,80,110,113",
"-j",
"DNAT",
"--to-destination",
dstip,
)
run_iptables(
"-t",
"nat",
action,
"PREROUTING",
"--source",
srcip,
"-p",
protocol,
"-m",
"multiport",
"--dports",
# The following ports are used for default services on Ubuntu
"123,443,465,514,990,995,6667",
"-j",
"DNAT",
"--to-destination",
dstip,
)
def inetsim_trap(action, ipaddr, inetsim_ip, resultserver_port):
# There are four options for protocol in iptables: tcp, udp, icmp and all
# Since we want tcp, udp and icmp to be configured differently, we cannot use all
# tcp
run_iptables(
"-t",
"nat",
action,
"PREROUTING",
"--source",
ipaddr,
"-p",
"tcp",
"-m",
"tcp",
"--syn",
"!",
"--dport",
resultserver_port,
"-j",
"DNAT",
"--to-destination",
"%s:%s" % (inetsim_ip, "1"),
)
# udp
run_iptables(
"-t",
"nat",
action,
"PREROUTING",
"--source",
ipaddr,
"-p",
"udp",
"!",
"--dport",
resultserver_port,
"-j",
"DNAT",
"--to-destination",
"%s:%s" % (inetsim_ip, "1"),
)
# icmp
run_iptables(
"-t",
"nat",
action,
"PREROUTING",
"--source",
ipaddr,
"-p",
"icmp",
"--icmp-type",
"any",
"-j",
"DNAT",
"--to-destination",
"%s:%s" % (inetsim_ip, "1"),
)
def inetsim_enable(ipaddr, inetsim_ip, dns_port, resultserver_port, ports):
"""Enable hijacking of all traffic and send it to InetSIM."""
log.info("Enabling inetsim route.")
inetsim_redirect_port("-A", ipaddr, inetsim_ip, ports)
inetsim_service_port_trap("-A", ipaddr, inetsim_ip, "tcp")
inetsim_service_port_trap("-A", ipaddr, inetsim_ip, "udp")
dns_forward("-A", ipaddr, inetsim_ip, dns_port)
inetsim_trap("-A", ipaddr, inetsim_ip, resultserver_port)
# INetSim does not have an SSH service, so SSH traffic can get through to the host. We want to block this.
run_iptables("-A", "INPUT", "--source", ipaddr, "-p", "tcp", "-m", "tcp", "--dport", "22", "-j", "DROP")
run_iptables("-A", "OUTPUT", "-m", "conntrack", "--ctstate", "INVALID", "-j", "DROP")
run_iptables("-A", "OUTPUT", "-m", "state", "--state", "INVALID", "-j", "DROP")
run_iptables("-A", "OUTPUT", "--source", ipaddr, "-j", "DROP")
def inetsim_disable(ipaddr, inetsim_ip, dns_port, resultserver_port, ports):
"""Disable hijacking of all traffic and send it to InetSIM."""
log.info("Disabling inetsim route.")
inetsim_redirect_port("-D", ipaddr, inetsim_ip, ports)
inetsim_service_port_trap("-D", ipaddr, inetsim_ip, "tcp")
inetsim_service_port_trap("-D", ipaddr, inetsim_ip, "udp")
dns_forward("-D", ipaddr, inetsim_ip, dns_port)
inetsim_trap("-D", ipaddr, inetsim_ip, resultserver_port)
run_iptables("-D", "INPUT", "--source", ipaddr, "-p", "tcp", "-m", "tcp", "--dport", "22", "-j", "DROP")
run_iptables("-D", "OUTPUT", "-m", "conntrack", "--ctstate", "INVALID", "-j", "DROP")
run_iptables("-D", "OUTPUT", "-m", "state", "--state", "INVALID", "-j", "DROP")
run_iptables("-D", "OUTPUT", "--source", ipaddr, "-j", "DROP")
def interface_route_tun_enable(ipaddr: str, out_interface: str, task_id: str):
"""Enable routing and NAT via tun output_interface."""
log.info("Enabling interface routing via: %s for task: %s", out_interface, task_id)
# mark packets from analysis VM
run_iptables("-t", "mangle", "-I", "PREROUTING", "--source", ipaddr, "-j", "MARK", "--set-mark", task_id)
run_iptables("-t", "nat", "-I", "POSTROUTING", "--source", ipaddr, "-o", out_interface, "-j", "MASQUERADE")
# ACCEPT forward
run_iptables("-t", "filter", "-I", "FORWARD", "--source", ipaddr, "-o", out_interface, "-j", "ACCEPT")
# in routing table add route table task_id
run(ServicePaths.ip, "rule", "add", "fwmark", task_id, "lookup", task_id)
peer_ip = get_tun_peer_address(out_interface)
if peer_ip:
log.info("interface_route_enable %s has peer: %s ", out_interface, peer_ip)
run(ServicePaths.ip, "route", "add", "default", "via", peer_ip, "table", task_id)
else:
log.error("interface_route_enable missing peer IP ")
def interface_route_tun_disable(ipaddr: str, out_interface: str, task_id: str):
"""Disable routing and NAT via tun output_interface."""
log.info("Disable interface routing via: %s for task: %s", out_interface, task_id)
# mark packets from analysis VM
run_iptables("-t", "mangle", "-D", "PREROUTING", "--source", ipaddr, "-j", "MARK", "--set-mark", task_id)
run_iptables("-t", "nat", "-D", "POSTROUTING", "--source", ipaddr, "-o", out_interface, "-j", "MASQUERADE")
# ACCEPT forward
run_iptables("-t", "filter", "-D", "FORWARD", "--source", ipaddr, "-o", out_interface, "-j", "ACCEPT")
# in routing table add route table task_id
run(ServicePaths.ip, "rule", "del", "fwmark", task_id, "lookup", task_id)
peer_ip = get_tun_peer_address(out_interface)
if peer_ip:
log.info("interface_route_disable %s has peer %s", out_interface, peer_ip)
run(ServicePaths.ip, "route", "del", "default", "via", peer_ip, "table", task_id)
else:
log.error("interface_route_disable missing peer IP ")
def socks5_enable(ipaddr, resultserver_port, dns_port, proxy_port):
"""Enable hijacking of all traffic and send it to socks5."""
log.info("Enabling socks route.")
run_iptables(
"-t",
"nat",
"-I",
"PREROUTING",
"--source",
ipaddr,
"-p",
"tcp",
"--syn",
"!",
"--dport",
resultserver_port,
"-j",
"REDIRECT",
"--to-ports",
proxy_port,
)
run_iptables("-I", "OUTPUT", "1", "-m", "conntrack", "--ctstate", "INVALID", "-j", "DROP")
run_iptables("-I", "OUTPUT", "2", "-m", "state", "--state", "INVALID", "-j", "DROP")
run_iptables(
"-t", "nat", "-A", "PREROUTING", "-p", "tcp", "--dport", "53", "--source", ipaddr, "-j", "REDIRECT", "--to-ports", dns_port
)
run_iptables(
"-t", "nat", "-A", "PREROUTING", "-p", "udp", "--dport", "53", "--source", ipaddr, "-j", "REDIRECT", "--to-ports", dns_port
)
run_iptables("-A", "OUTPUT", "--source", ipaddr, "-j", "DROP")
def socks5_disable(ipaddr, resultserver_port, dns_port, proxy_port):
"""Enable hijacking of all traffic and send it to socks5."""
log.info("Disabling socks route.")
run_iptables(
"-t",
"nat",
"-D",
"PREROUTING",
"--source",
ipaddr,
"-p",
"tcp",
"--syn",
"!",
"--dport",
resultserver_port,
"-j",
"REDIRECT",
"--to-ports",
proxy_port,
)
run_iptables("-D", "OUTPUT", "-m", "conntrack", "--ctstate", "INVALID", "-j", "DROP")
run_iptables("-D", "OUTPUT", "-m", "state", "--state", "INVALID", "-j", "DROP")
run_iptables(
"-t", "nat", "-D", "PREROUTING", "-p", "tcp", "--dport", "53", "--source", ipaddr, "-j", "REDIRECT", "--to-ports", dns_port
)
run_iptables(
"-t", "nat", "-D", "PREROUTING", "-p", "udp", "--dport", "53", "--source", ipaddr, "-j", "REDIRECT", "--to-ports", dns_port
)
run_iptables("-D", "OUTPUT", "--source", ipaddr, "-j", "DROP")
def drop_enable(ipaddr, resultserver_port):
run_iptables(
"-t", "nat", "-I", "PREROUTING", "--source", ipaddr, "-p", "tcp", "--syn", "--dport", resultserver_port, "-j", "ACCEPT"
)
run_iptables("-A", "INPUT", "--destination", ipaddr, "-p", "tcp", "--dport", "8000", "-j", "ACCEPT")
run_iptables("-A", "INPUT", "--destination", ipaddr, "-p", "tcp", "--sport", resultserver_port, "-j", "ACCEPT")
run_iptables("-A", "OUTPUT", "--destination", ipaddr, "-p", "tcp", "--dport", "8000", "-j", "ACCEPT")
run_iptables("-A", "OUTPUT", "--destination", ipaddr, "-p", "tcp", "--sport", resultserver_port, "-j", "ACCEPT")
# run_iptables("-A", "OUTPUT", "--destination", ipaddr, "-j", "LOG")
run_iptables("-A", "OUTPUT", "--destination", ipaddr, "-j", "DROP")
def drop_disable(ipaddr, resultserver_port):
run_iptables(
"-t", "nat", "-D", "PREROUTING", "--source", ipaddr, "-p", "tcp", "--syn", "--dport", resultserver_port, "-j", "ACCEPT"
)
run_iptables("-D", "INPUT", "--destination", ipaddr, "-p", "tcp", "--dport", "8000", "-j", "ACCEPT")
run_iptables("-D", "INPUT", "--destination", ipaddr, "-p", "tcp", "--sport", resultserver_port, "-j", "ACCEPT")
run_iptables("-D", "OUTPUT", "--destination", ipaddr, "-p", "tcp", "--dport", "8000", "-j", "ACCEPT")
run_iptables("-D", "OUTPUT", "--destination", ipaddr, "-p", "tcp", "--sport", resultserver_port, "-j", "ACCEPT")
# run_iptables("-D", "OUTPUT", "--destination", ipaddr, "-j", "LOG")
run_iptables("-D", "OUTPUT", "--destination", ipaddr, "-j", "DROP")
handlers = {
"nic_available": nic_available,
"rt_available": rt_available,
"vpn_status": vpn_status,
"forward_drop": forward_drop,
"state_enable": state_enable,
"state_disable": state_disable,
"enable_nat": enable_nat,
"disable_nat": disable_nat,
"init_rttable": init_rttable,
"flush_rttable": flush_rttable,
"forward_enable": forward_enable,
"forward_disable": forward_disable,
"forward_reject_enable": forward_reject_enable,
"forward_reject_disable": forward_reject_disable,
"hostports_reject_enable": hostports_reject_enable,
"hostports_reject_disable": hostports_reject_disable,
"srcroute_enable": srcroute_enable,
"srcroute_disable": srcroute_disable,
"inetsim_enable": inetsim_enable,
"inetsim_disable": inetsim_disable,