mitmproxy/libmproxy/proxy/modes/socks_proxy.py

61 lines
2.2 KiB
Python
Raw Normal View History

from __future__ import (absolute_import, print_function, division)
2015-07-24 16:29:13 +00:00
2015-08-29 23:21:58 +00:00
from netlib import socks
2015-09-17 00:13:28 +00:00
from netlib.exceptions import TcpException
2015-08-30 13:27:29 +00:00
2015-09-17 00:13:28 +00:00
from ...exceptions import Socks5ProtocolException
2015-08-30 13:27:29 +00:00
from ...protocol import Layer, ServerConnectionMixin
2015-07-24 16:29:13 +00:00
2015-08-11 18:27:34 +00:00
2015-08-18 13:59:44 +00:00
class Socks5Proxy(Layer, ServerConnectionMixin):
2015-07-24 16:29:13 +00:00
def __call__(self):
try:
2015-08-29 23:21:58 +00:00
# Parse Client Greeting
client_greet = socks.ClientGreeting.from_file(self.client_conn.rfile, fail_early=True)
client_greet.assert_socks5()
if socks.METHOD.NO_AUTHENTICATION_REQUIRED not in client_greet.methods:
raise socks.SocksError(
socks.METHOD.NO_ACCEPTABLE_METHODS,
"mitmproxy only supports SOCKS without authentication"
)
2015-07-24 16:29:13 +00:00
2015-08-29 23:21:58 +00:00
# Send Server Greeting
server_greet = socks.ServerGreeting(
socks.VERSION.SOCKS5,
socks.METHOD.NO_AUTHENTICATION_REQUIRED
)
server_greet.to_file(self.client_conn.wfile)
self.client_conn.wfile.flush()
2015-07-24 16:29:13 +00:00
2015-08-29 23:21:58 +00:00
# Parse Connect Request
connect_request = socks.Message.from_file(self.client_conn.rfile)
connect_request.assert_socks5()
if connect_request.msg != socks.CMD.CONNECT:
raise socks.SocksError(
socks.REP.COMMAND_NOT_SUPPORTED,
"mitmproxy only supports SOCKS5 CONNECT."
)
2015-08-18 13:59:44 +00:00
2015-08-29 23:21:58 +00:00
# We always connect lazily, but we need to pretend to the client that we connected.
connect_reply = socks.Message(
socks.VERSION.SOCKS5,
socks.REP.SUCCEEDED,
connect_request.atyp,
# dummy value, we don't have an upstream connection yet.
connect_request.addr
)
connect_reply.to_file(self.client_conn.wfile)
self.client_conn.wfile.flush()
2015-09-17 00:13:28 +00:00
except (socks.SocksError, TcpException) as e:
raise Socks5ProtocolException("SOCKS5 mode failure: %s" % repr(e))
2015-08-18 13:59:44 +00:00
2015-08-29 23:21:58 +00:00
self.server_conn.address = connect_request.addr
layer = self.ctx.next_layer(self)
2015-08-18 13:59:44 +00:00
try:
layer()
finally:
if self.server_conn:
2015-09-03 15:01:25 +00:00
self.disconnect()