add tcp forward to tunnel and fix a bug for pack_addr from common.py

1. update tunnel to tcprelay.py

2. add tunnel_tcp_server to tunnel.py

3. add tunnel_tcp_server to local.py

4. add `address = to_bytes(address)` to `pack_addr` from common.py (fix a error when address is a domain)
This commit is contained in:
Falseen 2017-02-17 23:39:28 +08:00
parent 70c8373a0f
commit d29baa3102
5 changed files with 86 additions and 37 deletions

View file

@ -146,6 +146,7 @@ ADDRTYPE_MASK = 0xF
def pack_addr(address):
address_str = to_str(address)
address = to_bytes(address)
for family in (socket.AF_INET, socket.AF_INET6):
try:
r = socket.inet_pton(family, address_str)
@ -162,9 +163,9 @@ def pack_addr(address):
# add ss header
def add_header(address, port, data):
header = b''
header = pack_addr(address) + struct.pack('>H', port) + data
return header
_data = b''
_data = pack_addr(address) + struct.pack('>H', port) + data
return _data
def parse_header(data):

View file

@ -55,9 +55,15 @@ def main():
if config["both_tunnel_local"]:
_config = config.copy()
_config["local_port"] = _config["tunnel_port"]
logging.info("starting tunnel at %s:%d forward to %s:%d" %
(_config['local_address'], _config['local_port'],
_config['tunnel_remote'], _config['tunnel_remote_port']))
logging.info("starting tcp tunnel at %s:%d forward to %s:%d" %
(_config['local_address'], _config['local_port'],
_config['tunnel_remote'], _config['tunnel_remote_port']))
tunnel_tcp_server = tcprelay.TCPRelay(_config, dns_resolver, True)
tunnel_tcp_server.is_tunnel = True
tunnel_tcp_server.add_to_loop(loop)
logging.info("starting udp tunnel at %s:%d forward to %s:%d" %
(_config['local_address'], _config['local_port'],
_config['tunnel_remote'], _config['tunnel_remote_port']))
tunnel_udp_server = udprelay.UDPRelay(_config, dns_resolver, True)
tunnel_udp_server.is_tunnel = True
tunnel_udp_server.add_to_loop(loop)
@ -69,6 +75,7 @@ def main():
udp_server.close(next_tick=True)
if has_tunnel:
tunnel_udp_server.close(next_tick=True)
tunnel_tcp_server.close(next_tick=True)
signal.signal(getattr(signal, 'SIGQUIT', signal.SIGTERM), handler)
def int_handler(signum, _):

View file

@ -132,6 +132,13 @@ def check_config(config, is_local):
sys.exit(2)
else:
config['server'] = to_str(config['server'])
if config.get('tunnel_remote', None) is None:
logging.error('tunnel_remote addr not specified')
print_local_help()
sys.exit(2)
else:
config['tunnel_remote'] = to_str(config['tunnel_remote'])
else:
config['server'] = to_str(config.get('server', '0.0.0.0'))
try:

View file

@ -115,6 +115,11 @@ class TCPRelayHandler(object):
self._remote_sock = None
self._config = config
self._dns_resolver = dns_resolver
self.both_tunnel_local = config.get('both_tunnel_local', False)
self.tunnel_remote = config.get('tunnel_remote', "8.8.8.8")
self.tunnel_remote_port = config.get('tunnel_remote_port', 53)
self.tunnel_port = config.get('tunnel_port', 53)
self.is_tunnel = server.is_tunnel
# TCP Relay works as either sslocal or ssserver
# if is_local, this is sslocal
@ -250,7 +255,12 @@ class TCPRelayHandler(object):
else:
self._data_to_write_to_remote.append(data)
return
if self.is_tunnel:
# add ss header to data
tunnel_remote = self.tunnel_remote
tunnel_remote_port = self.tunnel_remote_port
data = common.add_header(tunnel_remote,
tunnel_remote_port, data)
if self._ota_enable_session:
data = self._ota_chunk_data_gen(data)
data = self._encryptor.encrypt(data)
@ -293,29 +303,36 @@ class TCPRelayHandler(object):
@shell.exception_handle(self_=True, destroy=True, conn_err=True)
def _handle_stage_addr(self, data):
if self._is_local:
cmd = common.ord(data[1])
if cmd == CMD_UDP_ASSOCIATE:
logging.debug('UDP associate')
if self._local_sock.family == socket.AF_INET6:
header = b'\x05\x00\x00\x04'
else:
header = b'\x05\x00\x00\x01'
addr, port = self._local_sock.getsockname()[:2]
addr_to_send = socket.inet_pton(self._local_sock.family,
addr)
port_to_send = struct.pack('>H', port)
self._write_to_sock(header + addr_to_send + port_to_send,
self._local_sock)
self._stage = STAGE_UDP_ASSOC
# just wait for the client to disconnect
return
elif cmd == CMD_CONNECT:
# just trim VER CMD RSV
data = data[3:]
if self.is_tunnel:
# add ss header to data
tunnel_remote = self.tunnel_remote
tunnel_remote_port = self.tunnel_remote_port
data = common.add_header(tunnel_remote,
tunnel_remote_port, data)
else:
logging.error('unknown command %d', cmd)
self.destroy()
return
cmd = common.ord(data[1])
if cmd == CMD_UDP_ASSOCIATE:
logging.debug('UDP associate')
if self._local_sock.family == socket.AF_INET6:
header = b'\x05\x00\x00\x04'
else:
header = b'\x05\x00\x00\x01'
addr, port = self._local_sock.getsockname()[:2]
addr_to_send = socket.inet_pton(self._local_sock.family,
addr)
port_to_send = struct.pack('>H', port)
self._write_to_sock(header + addr_to_send + port_to_send,
self._local_sock)
self._stage = STAGE_UDP_ASSOC
# just wait for the client to disconnect
return
elif cmd == CMD_CONNECT:
# just trim VER CMD RSV
data = data[3:]
else:
logging.error('unknown command %d', cmd)
self.destroy()
return
header_result = parse_header(data)
if header_result is None:
raise Exception('can not parse header')
@ -347,10 +364,12 @@ class TCPRelayHandler(object):
self._update_stream(STREAM_UP, WAIT_STATUS_WRITING)
self._stage = STAGE_DNS
if self._is_local:
# forward address to remote
self._write_to_sock((b'\x05\x00\x00\x01'
b'\x00\x00\x00\x00\x10\x10'),
self._local_sock)
# jump over socks5 response
if not self.is_tunnel:
# forward address to remote
self._write_to_sock((b'\x05\x00\x00\x01'
b'\x00\x00\x00\x00\x10\x10'),
self._local_sock)
# spec https://shadowsocks.org/en/spec/one-time-auth.html
# ATYP & 0x10 == 0x10, then OTA is enabled.
if self._ota_enable_session:
@ -484,6 +503,12 @@ class TCPRelayHandler(object):
def _handle_stage_stream(self, data):
if self._is_local:
if self.is_tunnel:
# add ss header to data
tunnel_remote = self.tunnel_remote
tunnel_remote_port = self.tunnel_remote_port
data = common.add_header(tunnel_remote,
tunnel_remote_port, data)
if self._ota_enable_session:
data = self._ota_chunk_data_gen(data)
data = self._encryptor.encrypt(data)
@ -554,6 +579,9 @@ class TCPRelayHandler(object):
data = self._encryptor.decrypt(data)
if not data:
return
# jump over socks5 init
if self.is_tunnel:
self._stage = STAGE_ADDR
if self._stage == STAGE_STREAM:
self._handle_stage_stream(data)
return
@ -696,6 +724,7 @@ class TCPRelay(object):
self._closed = False
self._eventloop = None
self._fd_to_handlers = {}
self.is_tunnel = False
self._timeout = config['timeout']
self._timeouts = [] # a list for all the handlers

View file

@ -24,7 +24,7 @@ import logging
import signal
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../'))
from shadowsocks import shell, daemon, eventloop, udprelay, asyncdns
from shadowsocks import shell, daemon, eventloop, tcprelay, udprelay, asyncdns
@shell.exception_handle(self_=False, exit_code=1)
@ -42,10 +42,15 @@ def main():
dns_resolver = asyncdns.DNSResolver()
loop = eventloop.EventLoop()
dns_resolver.add_to_loop(loop)
# tcp_server.add_to_loop(loop)
_config = config.copy()
_config["local_port"] = _config["tunnel_port"]
logging.info("starting tunnel at %s:%d forward to %s:%d" %
logging.info("starting tcp tunnel at %s:%d forward to %s:%d" %
(_config['local_address'], _config['local_port'],
_config['tunnel_remote'], _config['tunnel_remote_port']))
tunnel_tcp_server = tcprelay.TCPRelay(_config, dns_resolver, True)
tunnel_tcp_server.is_tunnel = True
tunnel_tcp_server.add_to_loop(loop)
logging.info("starting udp tunnel at %s:%d forward to %s:%d" %
(_config['local_address'], _config['local_port'],
_config['tunnel_remote'], _config['tunnel_remote_port']))
tunnel_udp_server = udprelay.UDPRelay(_config, dns_resolver, True)
@ -54,7 +59,7 @@ def main():
def handler(signum, _):
logging.warn('received SIGQUIT, doing graceful shutting down..')
# tcp_server.close(next_tick=True)
tunnel_tcp_server.close(next_tick=True)
tunnel_udp_server.close(next_tick=True)
signal.signal(getattr(signal, 'SIGQUIT', signal.SIGTERM), handler)