-
Notifications
You must be signed in to change notification settings - Fork 139
/
natter.py
executable file
·1849 lines (1664 loc) · 63.5 KB
/
natter.py
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 python3
'''
Natter - https://github.com/MikeWang000000/Natter
Copyright (C) 2023 MikeWang000000
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, either version 3 of the License, or
(at your option) any later version.
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/>.
'''
import os
import re
import sys
import json
import time
import errno
import atexit
import codecs
import random
import signal
import socket
import struct
import argparse
import threading
import subprocess
__version__ = "2.1.1"
class Logger(object):
DEBUG = 0
INFO = 1
WARN = 2
ERROR = 3
rep = {DEBUG: "D", INFO: "I", WARN: "W", ERROR: "E"}
level = INFO
if "256color" in os.environ.get("TERM", ""):
GREY = "\033[90;20m"
YELLOW_BOLD = "\033[33;1m"
RED_BOLD = "\033[31;1m"
RESET = "\033[0m"
else:
GREY = YELLOW_BOLD = RED_BOLD = RESET = ""
@staticmethod
def set_level(level):
Logger.level = level
@staticmethod
def debug(text=""):
if Logger.level <= Logger.DEBUG:
sys.stderr.write((Logger.GREY + "%s [%s] %s\n" + Logger.RESET) % (
time.strftime("%Y-%m-%d %H:%M:%S"), Logger.rep[Logger.DEBUG], text
))
@staticmethod
def info(text=""):
if Logger.level <= Logger.INFO:
sys.stderr.write(("%s [%s] %s\n") % (
time.strftime("%Y-%m-%d %H:%M:%S"), Logger.rep[Logger.INFO], text
))
@staticmethod
def warning(text=""):
if Logger.level <= Logger.WARN:
sys.stderr.write((Logger.YELLOW_BOLD + "%s [%s] %s\n" + Logger.RESET) % (
time.strftime("%Y-%m-%d %H:%M:%S"), Logger.rep[Logger.WARN], text
))
@staticmethod
def error(text=""):
if Logger.level <= Logger.ERROR:
sys.stderr.write((Logger.RED_BOLD + "%s [%s] %s\n" + Logger.RESET) % (
time.strftime("%Y-%m-%d %H:%M:%S"), Logger.rep[Logger.ERROR], text
))
class NatterExit(object):
atexit.register(lambda : NatterExit._atexit[0]())
_atexit = [lambda : None]
@staticmethod
def set_atexit(func):
NatterExit._atexit[0] = func
class PortTest(object):
def test_lan(self, addr, source_ip=None, interface=None, info=False):
print_status = Logger.info if info else Logger.debug
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
socket_set_opt(
sock,
bind_addr = (source_ip, 0) if source_ip else None,
interface = interface,
timeout = 1
)
if sock.connect_ex(addr) == 0:
print_status("LAN > %-21s [ OPEN ]" % addr_to_str(addr))
return 1
else:
print_status("LAN > %-21s [ CLOSED ]" % addr_to_str(addr))
return -1
except (OSError, socket.error) as ex:
print_status("LAN > %-21s [ UNKNOWN ]" % addr_to_str(addr))
Logger.debug("Cannot test port %s from LAN because: %s" % (addr_to_str(addr), ex))
return 0
finally:
sock.close()
def test_wan(self, addr, source_ip=None, interface=None, info=False):
# only port number in addr is used, WAN IP will be ignored
print_status = Logger.info if info else Logger.debug
ret01 = self._test_ifconfigco(addr[1], source_ip, interface)
if ret01 == 1:
print_status("WAN > %-21s [ OPEN ]" % addr_to_str(addr))
return 1
ret02 = self._test_transmission(addr[1], source_ip, interface)
if ret02 == 1:
print_status("WAN > %-21s [ OPEN ]" % addr_to_str(addr))
return 1
if ret01 == ret02 == -1:
print_status("WAN > %-21s [ CLOSED ]" % addr_to_str(addr))
return -1
print_status("WAN > %-21s [ UNKNOWN ]" % addr_to_str(addr))
return 0
def _test_ifconfigco(self, port, source_ip=None, interface=None):
# repo: https://github.com/mpolden/echoip
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
socket_set_opt(
sock,
bind_addr = (source_ip, 0) if source_ip else None,
interface = interface,
timeout = 8
)
sock.connect(("ifconfig.co", 80))
sock.sendall((
"GET /port/%d HTTP/1.0\r\n"
"Host: ifconfig.co\r\n"
"User-Agent: curl/8.0.0 (Natter)\r\n"
"Accept: */*\r\n"
"Connection: close\r\n"
"\r\n" % port
).encode())
response = b""
while True:
buff = sock.recv(4096)
if not buff:
break
response += buff
Logger.debug("port-test: ifconfig.co: %s" % response)
_, content = response.split(b"\r\n\r\n", 1)
dat = json.loads(content.decode())
return 1 if dat["reachable"] else -1
except (OSError, LookupError, ValueError, TypeError, socket.error) as ex:
Logger.debug("Cannot test port %d from ifconfig.co because: %s" % (port, ex))
return 0
finally:
sock.close()
def _test_transmission(self, port, source_ip=None, interface=None):
# repo: https://github.com/transmission/portcheck
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
socket_set_opt(
sock,
bind_addr = (source_ip, 0) if source_ip else None,
interface = interface,
timeout = 8
)
sock.connect(("portcheck.transmissionbt.com", 80))
sock.sendall((
"GET /%d HTTP/1.0\r\n"
"Host: portcheck.transmissionbt.com\r\n"
"User-Agent: curl/8.0.0 (Natter)\r\n"
"Accept: */*\r\n"
"Connection: close\r\n"
"\r\n" % port
).encode())
response = b""
while True:
buff = sock.recv(4096)
if not buff:
break
response += buff
Logger.debug("port-test: portcheck.transmissionbt.com: %s" % response)
_, content = response.split(b"\r\n\r\n", 1)
if content.strip() == b"1":
return 1
elif content.strip() == b"0":
return -1
raise ValueError("Unexpected response: %s" % response)
except (OSError, LookupError, ValueError, TypeError, socket.error) as ex:
Logger.debug(
"Cannot test port %d from portcheck.transmissionbt.com "
"because: %s" % (port, ex)
)
return 0
finally:
sock.close()
class StunClient(object):
class ServerUnavailable(Exception):
pass
def __init__(self, stun_server_list, source_host="0.0.0.0", source_port=0,
interface=None, udp=False):
if not stun_server_list:
raise ValueError("STUN server list is empty")
self.stun_server_list = stun_server_list
self.source_host = source_host
self.source_port = source_port
self.interface = interface
self.udp = udp
def get_mapping(self):
first = self.stun_server_list[0]
while True:
try:
return self._get_mapping()
except StunClient.ServerUnavailable as ex:
Logger.warning("stun: STUN server %s is unavailable: %s" % (
addr_to_uri(self.stun_server_list[0], udp = self.udp), ex
))
self.stun_server_list.append(self.stun_server_list.pop(0))
if self.stun_server_list[0] == first:
Logger.error("stun: No STUN server is available right now")
# force sleep for 10 seconds, then try the next loop
time.sleep(10)
def _get_mapping(self):
# ref: https://www.rfc-editor.org/rfc/rfc5389
socket_type = socket.SOCK_DGRAM if self.udp else socket.SOCK_STREAM
stun_host, stun_port = self.stun_server_list[0]
sock = socket.socket(socket.AF_INET, socket_type)
socket_set_opt(
sock,
reuse = True,
bind_addr = (self.source_host, self.source_port),
interface = self.interface,
timeout = 3
)
try:
sock.connect((stun_host, stun_port))
inner_addr = sock.getsockname()
self.source_host, self.source_port = inner_addr
sock.send(struct.pack(
"!LLLLL", 0x00010000, 0x2112a442, 0x4e415452,
random.getrandbits(32), random.getrandbits(32)
))
buff = sock.recv(1500)
ip = port = 0
payload = buff[20:]
while payload:
attr_type, attr_len = struct.unpack("!HH", payload[:4])
if attr_type in [1, 32]:
_, _, port, ip = struct.unpack("!BBHL", payload[4:4+attr_len])
if attr_type == 32:
port ^= 0x2112
ip ^= 0x2112a442
break
payload = payload[4 + attr_len:]
else:
raise ValueError("Invalid STUN response")
outer_addr = socket.inet_ntop(socket.AF_INET, struct.pack("!L", ip)), port
Logger.debug("stun: Got address %s from %s, source %s" % (
addr_to_uri(outer_addr, udp=self.udp),
addr_to_uri((stun_host, stun_port), udp=self.udp),
addr_to_uri(inner_addr, udp=self.udp)
))
return inner_addr, outer_addr
except (OSError, ValueError, struct.error, socket.error) as ex:
raise StunClient.ServerUnavailable(ex)
finally:
sock.close()
class KeepAlive(object):
def __init__(self, host, port, source_host, source_port, interface=None, udp=False):
self.sock = None
self.host = host
self.port = port
self.source_host = source_host
self.source_port = source_port
self.interface = interface
self.udp = udp
self.reconn = False
def __del__(self):
if self.sock:
self.sock.close()
def _connect(self):
sock_type = socket.SOCK_DGRAM if self.udp else socket.SOCK_STREAM
sock = socket.socket(socket.AF_INET, sock_type)
socket_set_opt(
sock,
reuse = True,
bind_addr = (self.source_host, self.source_port),
interface = self.interface,
timeout = 3
)
sock.connect((self.host, self.port))
if not self.udp:
Logger.debug("keep-alive: Connected to host %s" % (
addr_to_uri((self.host, self.port), udp=self.udp)
))
if self.reconn:
Logger.info("keep-alive: connection restored")
self.reconn = False
self.sock = sock
def keep_alive(self):
if self.sock is None:
self._connect()
if self.udp:
self._keep_alive_udp()
else:
self._keep_alive_tcp()
Logger.debug("keep-alive: OK")
def reset(self):
if self.sock is not None:
self.sock.close()
self.sock = None
self.reconn = True
def _keep_alive_tcp(self):
# send a HTTP request
self.sock.sendall((
"HEAD /natter-keep-alive HTTP/1.1\r\n"
"Host: %s\r\n"
"User-Agent: curl/8.0.0 (Natter)\r\n"
"Accept: */*\r\n"
"Connection: keep-alive\r\n"
"\r\n" % self.host
).encode())
buff = b""
try:
while True:
buff = self.sock.recv(4096)
if not buff:
raise OSError("Keep-alive server closed connection")
except socket.timeout as ex:
if not buff:
raise ex
return
def _keep_alive_udp(self):
# send a DNS request
self.sock.send(
struct.pack(
"!HHHHHH", random.getrandbits(16), 0x0100, 0x0001, 0x0000, 0x0000, 0x0000
) + b"\x09keepalive\x06natter\x00" + struct.pack("!HH", 0x0001, 0x0001)
)
buff = b""
try:
while True:
buff = self.sock.recv(1500)
if not buff:
raise OSError("Keep-alive server closed connection")
except socket.timeout as ex:
if not buff:
raise ex
# fix: Keep-alive cause STUN socket timeout on Windows
if sys.platform == "win32":
self.reset()
return
class ForwardNone(object):
# Do nothing. Don't forward.
def start_forward(self, ip, port, toip, toport, udp=False):
pass
def stop_forward(self):
pass
class ForwardTestServer(object):
def __init__(self):
self.active = False
self.sock = None
self.sock_type = None
self.buff_size = 8192
self.timeout = 3
# Start a socket server for testing purpose
# target address is ignored
def start_forward(self, ip, port, toip, toport, udp=False):
self.sock_type = socket.SOCK_DGRAM if udp else socket.SOCK_STREAM
self.sock = socket.socket(socket.AF_INET, self.sock_type)
socket_set_opt(
self.sock,
reuse = True,
bind_addr = ("", port)
)
Logger.debug("fwd-test: Starting test server at %s" % addr_to_uri((ip, port), udp=udp))
if udp:
th = start_daemon_thread(self._test_server_run_udp)
else:
th = start_daemon_thread(self._test_server_run_http)
time.sleep(1)
if not th.is_alive():
raise OSError("Test server thread exited too quickly")
self.active = True
def _test_server_run_http(self):
self.sock.listen(5)
while self.sock.fileno() != -1:
try:
conn, addr = self.sock.accept()
Logger.debug("fwd-test: got client %s" % (addr,))
except (OSError, socket.error):
return
try:
conn.settimeout(self.timeout)
conn.recv(self.buff_size)
content = "<html><body><h1>It works!</h1><hr/>Natter</body></html>"
content_len = len(content.encode())
data = (
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"Content-Length: %d\r\n"
"Connection: close\r\n"
"Server: Natter\r\n"
"\r\n"
"%s\r\n" % (content_len, content)
).encode()
conn.sendall(data)
conn.shutdown(socket.SHUT_RDWR)
except (OSError, socket.error):
pass
finally:
conn.close()
def _test_server_run_udp(self):
while self.sock.fileno() != -1:
try:
msg, addr = self.sock.recvfrom(self.buff_size)
Logger.debug("fwd-test: got client %s" % (addr,))
self.sock.sendto(b"It works! - Natter\r\n", addr)
except (OSError, socket.error):
return
def stop_forward(self):
Logger.debug("fwd-test: Stopping test server")
self.sock.close()
self.active = False
class ForwardIptables(object):
def __init__(self, snat=False, sudo=False):
self.rules = []
self.active = False
self.min_ver = (1, 4, 1)
self.curr_ver = (0, 0, 0)
self.snat = snat
self.sudo = sudo
if sudo:
self.iptables_cmd = ["sudo", "-n", "iptables"]
else:
self.iptables_cmd = ["iptables"]
if not self._iptables_check():
raise OSError("iptables >= %s not available" % str(self.min_ver))
# wait for iptables lock, since iptables 1.4.20
if self.curr_ver >= (1, 4, 20):
self.iptables_cmd += ["-w"]
self._iptables_init()
self._iptables_clean()
def __del__(self):
if self.active:
self.stop_forward()
def _iptables_check(self):
if os.name != "posix":
return False
if not self.sudo and os.getuid() != 0:
Logger.warning("fwd-iptables: You are not root")
try:
output = subprocess.check_output(
self.iptables_cmd + ["--version"]
).decode()
except (OSError, subprocess.CalledProcessError) as e:
return False
m = re.search(r"iptables v([0-9]+)\.([0-9]+)\.([0-9]+)", output)
if m:
self.curr_ver = tuple(int(v) for v in m.groups())
Logger.debug("fwd-iptables: Found iptables %s" % str(self.curr_ver))
if self.curr_ver < self.min_ver:
return False
# check nat table
try:
subprocess.check_output(
self.iptables_cmd + ["-t", "nat", "--list-rules"]
)
except (OSError, subprocess.CalledProcessError) as e:
return False
return True
def _iptables_init(self):
try:
subprocess.check_output(
self.iptables_cmd + ["-t", "nat", "--list-rules", "NATTER"],
stderr=subprocess.STDOUT
)
return
except subprocess.CalledProcessError:
pass
Logger.debug("fwd-iptables: Creating Natter chain")
subprocess.check_output(
self.iptables_cmd + ["-t", "nat", "-N", "NATTER"]
)
subprocess.check_output(
self.iptables_cmd + ["-t", "nat", "-I", "PREROUTING", "-j", "NATTER"]
)
subprocess.check_output(
self.iptables_cmd + ["-t", "nat", "-I", "OUTPUT", "-j", "NATTER"]
)
subprocess.check_output(
self.iptables_cmd + ["-t", "nat", "-N", "NATTER_SNAT"]
)
subprocess.check_output(
self.iptables_cmd + ["-t", "nat", "-I", "POSTROUTING", "-j", "NATTER_SNAT"]
)
subprocess.check_output(
self.iptables_cmd + ["-t", "nat", "-I", "INPUT", "-j", "NATTER_SNAT"]
)
def _iptables_clean(self):
Logger.debug("fwd-iptables: Cleaning up Natter rules")
while self.rules:
rule = self.rules.pop()
rule_rm = ["-D" if arg in ("-I", "-A") else arg for arg in rule]
try:
subprocess.check_output(
self.iptables_cmd + rule_rm,
stderr=subprocess.STDOUT
)
return
except subprocess.CalledProcessError as ex:
Logger.error("fwd-iptables: Failed to execute %s: %s" % (ex.cmd, ex.output))
continue
def start_forward(self, ip, port, toip, toport, udp=False):
if ip != toip:
self._check_sys_forward_config()
if (ip, port) == (toip, toport):
raise ValueError("Cannot forward to the same address %s" % addr_to_str((ip, port)))
proto = "udp" if udp else "tcp"
Logger.debug("fwd-iptables: Adding rule %s forward to %s" % (
addr_to_uri((ip, port), udp=udp), addr_to_uri((toip, toport), udp=udp)
))
rule = [
"-t", "nat",
"-I", "NATTER",
"-p", proto,
"--dst", ip,
"--dport", "%d" % port,
"-j", "DNAT",
"--to-destination", "%s:%d" % (toip, toport)
]
subprocess.check_output(self.iptables_cmd + rule)
self.rules.append(rule)
if self.snat:
rule = [
"-t", "nat",
"-I", "NATTER_SNAT",
"-p", proto,
"--dst", toip,
"--dport", "%d" % toport,
"-j", "SNAT",
"--to-source", ip
]
subprocess.check_output(self.iptables_cmd + rule)
self.rules.append(rule)
self.active = True
def stop_forward(self):
self._iptables_clean()
self.active = False
def _check_sys_forward_config(self):
fpath = "/proc/sys/net/ipv4/ip_forward"
if os.path.exists(fpath):
fin = open(fpath, "r")
buff = fin.read()
fin.close()
if buff.strip() != "1":
raise OSError("IP forwarding is not allowed. Please do `sysctl net.ipv4.ip_forward=1`")
else:
Logger.warning("fwd-iptables: '%s' not found" % str(fpath))
class ForwardSudoIptables(ForwardIptables):
def __init__(self):
super().__init__(sudo=True)
class ForwardIptablesSnat(ForwardIptables):
def __init__(self):
super().__init__(snat=True)
class ForwardSudoIptablesSnat(ForwardIptables):
def __init__(self):
super().__init__(snat=True, sudo=True)
class ForwardNftables(object):
def __init__(self, snat=False, sudo=False):
self.handle = -1
self.handle_snat = -1
self.active = False
self.min_ver = (0, 9, 0)
self.snat = snat
self.sudo = sudo
if sudo:
self.nftables_cmd = ["sudo", "-n", "nft"]
else:
self.nftables_cmd = ["nft"]
if not self._nftables_check():
raise OSError("nftables >= %s not available" % str(self.min_ver))
self._nftables_init()
self._nftables_clean()
def __del__(self):
if self.active:
self.stop_forward()
def _nftables_check(self):
if os.name != "posix":
return False
if not self.sudo and os.getuid() != 0:
Logger.warning("fwd-nftables: You are not root")
try:
output = subprocess.check_output(
self.nftables_cmd + ["--version"]
).decode()
except (OSError, subprocess.CalledProcessError) as e:
return False
m = re.search(r"nftables v([0-9]+)\.([0-9]+)\.([0-9]+)", output)
if m:
curr_ver = tuple(int(v) for v in m.groups())
Logger.debug("fwd-nftables: Found nftables %s" % str(curr_ver))
if curr_ver < self.min_ver:
return False
# check nat table
try:
subprocess.check_output(
self.nftables_cmd + ["list table ip nat"]
)
except (OSError, subprocess.CalledProcessError) as e:
return False
return True
def _nftables_init(self):
try:
subprocess.check_output(
self.nftables_cmd + ["list chain ip nat NATTER"],
stderr=subprocess.STDOUT
)
return
except subprocess.CalledProcessError:
pass
Logger.debug("fwd-nftables: Creating Natter chain")
subprocess.check_output(
self.nftables_cmd + ["add chain ip nat NATTER"]
)
subprocess.check_output(
self.nftables_cmd + ["insert rule ip nat PREROUTING counter jump NATTER"]
)
subprocess.check_output(
self.nftables_cmd + ["insert rule ip nat OUTPUT counter jump NATTER"]
)
subprocess.check_output(
self.nftables_cmd + ["add chain ip nat NATTER_SNAT"]
)
subprocess.check_output(
self.nftables_cmd + ["insert rule ip nat PREROUTING counter jump NATTER_SNAT"]
)
subprocess.check_output(
self.nftables_cmd + ["insert rule ip nat OUTPUT counter jump NATTER_SNAT"]
)
def _nftables_clean(self):
Logger.debug("fwd-nftables: Cleaning up Natter rules")
if self.handle > 0:
subprocess.check_output(
self.nftables_cmd + ["delete rule ip nat NATTER handle %d" % self.handle]
)
if self.handle_snat > 0:
subprocess.check_output(
self.nftables_cmd + ["delete rule ip nat NATTER_SNAT handle %d" % self.handle_snat]
)
def start_forward(self, ip, port, toip, toport, udp=False):
if ip != toip:
self._check_sys_forward_config()
if (ip, port) == (toip, toport):
raise ValueError("Cannot forward to the same address %s" % addr_to_str((ip, port)))
proto = "udp" if udp else "tcp"
Logger.debug("fwd-nftables: Adding rule %s forward to %s" % (
addr_to_uri((ip, port), udp=udp), addr_to_uri((toip, toport), udp=udp)
))
output = subprocess.check_output(self.nftables_cmd + [
"--echo", "--handle",
"insert rule ip nat NATTER ip daddr %s %s dport %d counter dnat to %s:%d" % (
ip, proto, port, toip, toport
)
]).decode()
m = re.search(r"# handle ([0-9]+)$", output, re.MULTILINE)
if not m:
raise ValueError("Unknown nftables handle")
self.handle = int(m.group(1))
if self.snat:
output = subprocess.check_output(self.nftables_cmd + [
"--echo", "--handle",
"insert rule ip nat NATTER_SNAT ip daddr %s %s dport %d counter snat to %s" % (
toip, proto, toport, ip
)
]).decode()
m = re.search(r"# handle ([0-9]+)$", output, re.MULTILINE)
if not m:
raise ValueError("Unknown nftables handle")
self.handle_snat = int(m.group(1))
self.active = True
def stop_forward(self):
self._nftables_clean()
self.active = False
def _check_sys_forward_config(self):
fpath = "/proc/sys/net/ipv4/ip_forward"
if os.path.exists(fpath):
fin = open(fpath, "r")
buff = fin.read()
fin.close()
if buff.strip() != "1":
raise OSError("IP forwarding is disabled by system. Please do `sysctl net.ipv4.ip_forward=1`")
else:
Logger.warning("fwd-nftables: '%s' not found" % str(fpath))
class ForwardSudoNftables(ForwardNftables):
def __init__(self):
super().__init__(sudo=True)
class ForwardNftablesSnat(ForwardNftables):
def __init__(self):
super().__init__(snat=True)
class ForwardSudoNftablesSnat(ForwardNftables):
def __init__(self):
super().__init__(snat=True, sudo=True)
class ForwardGost(object):
def __init__(self):
self.active = False
self.min_ver = (2, 3)
self.proc = None
self.udp_timeout = 60
if not self._gost_check():
raise OSError("gost >= %s not available" % str(self.min_ver))
def __del__(self):
if self.active:
self.stop_forward()
def _gost_check(self):
try:
output = subprocess.check_output(
["gost", "-V"], stderr=subprocess.STDOUT
).decode()
except (OSError, subprocess.CalledProcessError) as e:
return False
m = re.search(r"gost v?([0-9]+)\.([0-9]+)", output)
if m:
current_ver = tuple(int(v) for v in m.groups())
Logger.debug("fwd-gost: Found gost %s" % str(current_ver))
return current_ver >= self.min_ver
return False
def start_forward(self, ip, port, toip, toport, udp=False):
if (ip, port) == (toip, toport):
raise ValueError("Cannot forward to the same address %s" % addr_to_str((ip, port)))
proto = "udp" if udp else "tcp"
Logger.debug("fwd-gost: Starting gost %s forward to %s" % (
addr_to_uri((ip, port), udp=udp), addr_to_uri((toip, toport), udp=udp)
))
gost_arg = "-L=%s://:%d/%s:%d" % (proto, port, toip, toport)
if udp:
gost_arg += "?ttl=%ds" % self.udp_timeout
self.proc = subprocess.Popen(["gost", gost_arg])
time.sleep(1)
if self.proc.poll() is not None:
raise OSError("gost exited too quickly")
self.active = True
def stop_forward(self):
Logger.debug("fwd-gost: Stopping gost")
if self.proc and self.proc.returncode is not None:
return
self.proc.terminate()
self.active = False
class ForwardSocat(object):
def __init__(self):
self.active = False
self.min_ver = (1, 7, 2)
self.proc = None
self.udp_timeout = 60
self.max_children = 128
if not self._socat_check():
raise OSError("socat >= %s not available" % str(self.min_ver))
def __del__(self):
if self.active:
self.stop_forward()
def _socat_check(self):
try:
output = subprocess.check_output(
["socat", "-V"], stderr=subprocess.STDOUT
).decode()
except (OSError, subprocess.CalledProcessError) as e:
return False
m = re.search(r"socat version ([0-9]+)\.([0-9]+)\.([0-9]+)", output)
if m:
current_ver = tuple(int(v) for v in m.groups())
Logger.debug("fwd-socat: Found socat %s" % str(current_ver))
return current_ver >= self.min_ver
return False
def start_forward(self, ip, port, toip, toport, udp=False):
if (ip, port) == (toip, toport):
raise ValueError("Cannot forward to the same address %s" % addr_to_str((ip, port)))
proto = "UDP" if udp else "TCP"
Logger.debug("fwd-socat: Starting socat %s forward to %s" % (
addr_to_uri((ip, port), udp=udp), addr_to_uri((toip, toport), udp=udp)
))
if udp:
socat_cmd = ["socat", "-T%d" % self.udp_timeout]
else:
socat_cmd = ["socat"]
self.proc = subprocess.Popen(socat_cmd + [
"%s4-LISTEN:%d,reuseaddr,fork,max-children=%d" % (proto, port, self.max_children),
"%s4:%s:%d" % (proto, toip, toport)
])
time.sleep(1)
if self.proc.poll() is not None:
raise OSError("socat exited too quickly")
self.active = True
def stop_forward(self):
Logger.debug("fwd-socat: Stopping socat")
if self.proc and self.proc.returncode is not None:
return
self.proc.terminate()
self.active = False
class ForwardSocket(object):
def __init__(self):
self.active = False
self.sock = None
self.sock_type = None
self.outbound_addr = None
self.buff_size = 8192
self.udp_timeout = 60
self.max_threads = 128
def __del__(self):
if self.active:
self.stop_forward()
def start_forward(self, ip, port, toip, toport, udp=False):
if (ip, port) == (toip, toport):
raise ValueError("Cannot forward to the same address %s" % addr_to_str((ip, port)))
self.sock_type = socket.SOCK_DGRAM if udp else socket.SOCK_STREAM
self.sock = socket.socket(socket.AF_INET, self.sock_type)
socket_set_opt(
self.sock,
reuse = True,
bind_addr = ("", port)
)
self.outbound_addr = toip, toport
Logger.debug("fwd-socket: Starting socket %s forward to %s" % (
addr_to_uri((ip, port), udp=udp), addr_to_uri((toip, toport), udp=udp)
))
if udp:
th = start_daemon_thread(self._socket_udp_recvfrom)
else:
th = start_daemon_thread(self._socket_tcp_listen)
time.sleep(1)
if not th.is_alive():
raise OSError("Socket thread exited too quickly")
self.active = True
def _socket_tcp_listen(self):
self.sock.listen(5)
while True:
try:
sock_inbound, _ = self.sock.accept()
except (OSError, socket.error) as ex:
if not closed_socket_ex(ex):
Logger.error("fwd-socket: socket listening thread is exiting: %s" % ex)
return
sock_outbound = socket.socket(socket.AF_INET, self.sock_type)
try:
sock_outbound.settimeout(3)
sock_outbound.connect(self.outbound_addr)
sock_outbound.settimeout(None)
if threading.active_count() >= self.max_threads:
raise OSError("Too many threads")
start_daemon_thread(self._socket_tcp_forward, args=(sock_inbound, sock_outbound))
start_daemon_thread(self._socket_tcp_forward, args=(sock_outbound, sock_inbound))
except (OSError, socket.error) as ex:
Logger.error("fwd-socket: cannot forward port: %s" % ex)
sock_inbound.close()
sock_outbound.close()
continue
def _socket_tcp_forward(self, sock_to_recv, sock_to_send):
try:
while sock_to_recv.fileno() != -1:
buff = sock_to_recv.recv(self.buff_size)
if buff and sock_to_send.fileno() != -1:
sock_to_send.sendall(buff)
else:
sock_to_recv.close()
sock_to_send.close()
return
except (OSError, socket.error) as ex:
if not closed_socket_ex(ex):
Logger.error("fwd-socket: socket forwarding thread is exiting: %s" % ex)
sock_to_recv.close()
sock_to_send.close()
return
def _socket_udp_recvfrom(self):
outbound_socks = {}
while True:
try:
buff, addr = self.sock.recvfrom(self.buff_size)
s = outbound_socks.get(addr)
except (OSError, socket.error) as ex:
if not closed_socket_ex(ex):
Logger.error("fwd-socket: socket recvfrom thread is exiting: %s" % ex)
return
try:
if not s:
s = outbound_socks[addr] = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(self.udp_timeout)
s.connect(self.outbound_addr)
if threading.active_count() >= self.max_threads:
raise OSError("Too many threads")
start_daemon_thread(self._socket_udp_send, args=(self.sock, s, addr))
if buff:
s.send(buff)
else:
s.close()
del outbound_socks[addr]
except (OSError, socket.error):
if addr in outbound_socks:
outbound_socks[addr].close()
del outbound_socks[addr]
continue
def _socket_udp_send(self, server_sock, outbound_sock, client_addr):
try:
while outbound_sock.fileno() != -1:
buff = outbound_sock.recv(self.buff_size)
if buff:
server_sock.sendto(buff, client_addr)
else:
outbound_sock.close()
except (OSError, socket.error) as ex:
if not closed_socket_ex(ex):
Logger.error("fwd-socket: socket send thread is exiting: %s" % ex)
outbound_sock.close()
return