├── .gitignore ├── LICENSE ├── README.md └── socks5.py /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *~ 3 | .settings/ 4 | .project 5 | .classpath 6 | target/ 7 | /cache/ 8 | *.bak 9 | *.log 10 | .idea/ 11 | *.iml 12 | .pysocks.pid 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PySocks 2 | **PySocks** is a simple SOCKS5 server without any third-party dependencies. 3 | 4 | ## Progress 5 | 6 | * CONNECT commnad - OK 7 | * UDP ASSOCIATE - NO 8 | * BIND - NO 9 | * No Authentication Required - YES 10 | * USERNAME/PASSWORD Authentication - YES 11 | * GSS-API - NO 12 | 13 | ## Environment 14 | Python 3.6 15 | 16 | > If you need to use it in a python2 environment, you can roll back to 61edb32. I will consider compatibility with python2 in the future. 17 | 18 | ## Install 19 | 20 | 21 | ``` 22 | $ git clone https://github.com/fengyouchao/pysocks.git ~/pysocks 23 | ``` 24 | 25 | ## Usage 26 | 27 | ``` 28 | $ python ~/pysocks/socks5.py start # Start a socks5 server 29 | $ python ~/pysocks/socks5.py status # Print socks5 server status 30 | $ python ~/pysocks/socks5.py stop # Stop socks5 server 31 | $ python ~/pysocks/socks5.py start --auth root:1235 admin:1234 # Only allow clients that provide the specified username and password 32 | $ python ~/pysocks/socks5.py start --allow-ip 10.0.0.5 10.0.0.6 # Only allow clients from 10.0.05 or 10.0.06 33 | $ python ~/pysocks/socks5.py -h # print help information 34 | $ python ~/pysocks/socks5.py start -h # print help information for start subcommand 35 | $ python ~/pysocks/socks5.py status -h # print help information for status subcommand 36 | $ python ~/pysocks/socks5.py stop -h # print help information for stop subcommand 37 | ``` 38 | 39 | ## Thanks 40 | 41 | I wrote **PySocks** after a week of learning python, so there is a lot of immature code in it. After completing this project, I haven't updated it for a long time. I am very grateful to the friends who submitted PR to this project during this period. 42 | 43 | Thanks to [C W](https://github.com/fake-name) for migrating **PySocks** to python3. 44 | 45 | -------------------------------------------------------------------------------- /socks5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | import logging 5 | import os 6 | import platform 7 | import signal 8 | import struct 9 | import sys 10 | import threading 11 | from socket import AF_INET, SOCK_STREAM, socket 12 | from socketserver import BaseServer, StreamRequestHandler, ThreadingTCPServer 13 | 14 | __author__ = 'Youchao Feng' 15 | support_os = ('Darwin', 'Linux') 16 | current_os = platform.system() 17 | 18 | 19 | def byte_to_int(b): 20 | """ 21 | Convert Unsigned byte to int 22 | :param b: byte value 23 | :return: int value 24 | """ 25 | return b & 0xFF 26 | 27 | 28 | def port_from_byte(b1, b2): 29 | """ 30 | :param b1: First byte of port 31 | :param b2: Second byte of port 32 | :return: Port in Int 33 | """ 34 | return byte_to_int(b1) << 8 | byte_to_int(b2) 35 | 36 | 37 | def host_from_ip(a, b, c, d): 38 | a = byte_to_int(a) 39 | b = byte_to_int(b) 40 | c = byte_to_int(c) 41 | d = byte_to_int(d) 42 | return "%d.%d.%d.%d" % (a, b, c, d) 43 | 44 | 45 | def get_command_name(value): 46 | """ 47 | Gets command name by value 48 | :param value: value of Command 49 | :return: Command Name 50 | """ 51 | if value == 1: 52 | return 'CONNECT' 53 | elif value == 2: 54 | return 'BIND' 55 | elif value == 3: 56 | return 'UDP_ASSOCIATE' 57 | else: 58 | return None 59 | 60 | 61 | def build_command_response(reply): 62 | start = b'\x05%s\x00\x01\x00\x00\x00\x00\x00\x00' 63 | return start % reply.get_byte_string() 64 | 65 | 66 | def close_session(session): 67 | session.get_client_socket().close() 68 | logging.info("Session[%s] closed", session.get_id()) 69 | 70 | 71 | def run_daemon_process(stdout='/dev/null', 72 | stderr=None, 73 | stdin='/dev/null', 74 | pid_file=None, 75 | start_msg='started with pid %s'): 76 | """ 77 | This forks the current process into a daemon. 78 | The stdin, stdout, and stderr arguments are file names that 79 | will be opened and be used to replace the standard file descriptors 80 | in sys.stdin, sys.stdout, and sys.stderr. 81 | These arguments are optional and default to /dev/null. 82 | Note that stderr is opened unbuffered, so 83 | if it shares a file with stdout then interleaved output 84 | may not appear in the order that you expect. 85 | """ 86 | # flush io 87 | sys.stdout.flush() 88 | sys.stderr.flush() 89 | # Do first fork. 90 | try: 91 | if os.fork() > 0: 92 | sys.exit(0) # Exit first parent. 93 | except OSError as e: 94 | sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror)) 95 | sys.exit(1) 96 | # Decouple from parent environment. 97 | os.chdir("/") 98 | os.umask(0) 99 | os.setsid() 100 | # Do second fork. 101 | try: 102 | if os.fork() > 0: 103 | sys.exit(0) # Exit second parent. 104 | except OSError as e: 105 | sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror)) 106 | sys.exit(1) 107 | # Open file descriptors and print start message 108 | if not stderr: 109 | stderr = stdout 110 | si = open(stdin, 'r') 111 | so = open(stdout, 'a+') 112 | se = open(stderr, 'ba+', 0) # unbuffered 113 | pid = str(os.getpid()) 114 | sys.stderr.write(start_msg % pid) 115 | sys.stderr.flush() 116 | if pid_file: 117 | open(pid_file, 'w+').write("%s\n" % pid) 118 | # Redirect standard file descriptors. 119 | os.dup2(si.fileno(), sys.stdin.fileno()) 120 | os.dup2(so.fileno(), sys.stdout.fileno()) 121 | os.dup2(se.fileno(), sys.stderr.fileno()) 122 | 123 | 124 | class Session: 125 | index = 0 126 | 127 | def __init__(self, client_socket): 128 | Session.index += 1 129 | self.__id = Session.index 130 | self.__client_socket = client_socket 131 | self._attr = {} 132 | 133 | def get_id(self): 134 | return self.__id 135 | 136 | def set_attr(self, key, value): 137 | self._attr[key] = value 138 | 139 | def get_client_socket(self): 140 | return self.__client_socket 141 | 142 | 143 | class AddressType: 144 | IPV4 = 1 145 | DOMAIN_NAME = 3 146 | IPV6 = 4 147 | 148 | 149 | class SocksCommand: 150 | CONNECT = 1 151 | BIND = 2 152 | UDP_ASSOCIATE = 3 153 | 154 | 155 | class SocksMethod: 156 | NO_AUTHENTICATION_REQUIRED = 0 157 | GSS_API = 1 158 | USERNAME_PASSWORD = 2 159 | 160 | 161 | class ServerReply: 162 | def __init__(self, value): 163 | self.__value = value 164 | 165 | def get_byte_string(self): 166 | if self.__value == 0: 167 | return b'\x00' 168 | elif self.__value == 1: 169 | return b'\x01' 170 | elif self.__value == 2: 171 | return b'\x02' 172 | elif self.__value == 3: 173 | return b'\x03' 174 | elif self.__value == 4: 175 | return b'\x04' 176 | elif self.__value == 5: 177 | return b'\x05' 178 | elif self.__value == 6: 179 | return b'\x06' 180 | elif self.__value == 7: 181 | return b'\x07' 182 | elif self.__value == 8: 183 | return b'\x08' 184 | 185 | def get_value(self): 186 | return self.__value 187 | 188 | 189 | class ReplyType: 190 | SUCCEEDED = ServerReply(0) 191 | GENERAL_SOCKS_SERVER_FAILURE = ServerReply(1) 192 | CONNECTION_NOT_ALLOWED_BY_RULESET = ServerReply(2) 193 | NETWORK_UNREACHABLE = ServerReply(3) 194 | HOST_UNREACHABLE = ServerReply(4) 195 | CONNECTION_REFUSED = ServerReply(5) 196 | TTL_EXPIRED = ServerReply(6) 197 | COMMAND_NOT_SUPPORTED = ServerReply(7) 198 | ADDRESS_TYPE_NOT_SUPPORTED = ServerReply(8) 199 | 200 | 201 | class SocketPipe: 202 | BUFFER_SIZE = 1024 * 1024 203 | 204 | def __init__(self, socket1, socket2): 205 | self._socket1 = socket1 206 | self._socket2 = socket2 207 | self.__running = False 208 | 209 | self.t1 = threading.Thread(target=self.__transfer, args=(self._socket1, self._socket2)) 210 | self.t2 = threading.Thread(target=self.__transfer, args=(self._socket2, self._socket1)) 211 | 212 | def __transfer(self, socket1, socket2): 213 | while self.__running: 214 | try: 215 | data = socket1.recv(self.BUFFER_SIZE) 216 | if len(data) > 0: 217 | socket2.sendall(data) 218 | else: 219 | break 220 | except IOError: 221 | self.stop() 222 | self.stop() 223 | 224 | def start(self): 225 | self.__running = True 226 | 227 | self.t1.start() 228 | self.t2.start() 229 | 230 | def stop(self): 231 | self._socket1.close() 232 | self._socket2.close() 233 | self.__running = False 234 | 235 | def is_running(self): 236 | return self.__running 237 | 238 | 239 | class CommandExecutor: 240 | def __init__(self, remote_server_host, remote_server_port, session): 241 | self.__proxy_socket = socket(AF_INET, SOCK_STREAM) 242 | self.__remote_server_host = remote_server_host 243 | self.__remote_server_port = remote_server_port 244 | self.__client = session.get_client_socket() 245 | self.__session = session 246 | 247 | def do_connect(self): 248 | """ 249 | Do SOCKS CONNECT method 250 | :return: None 251 | """ 252 | address = self.__get_address() 253 | logging.info("Connect request to %s", address) 254 | result = self.__proxy_socket.connect_ex(address) 255 | if result == 0: 256 | self.__client.send(build_command_response(ReplyType.SUCCEEDED)) 257 | socket_pipe = SocketPipe(self.__client, self.__proxy_socket) 258 | socket_pipe.start() 259 | while socket_pipe.is_running(): 260 | pass 261 | elif result == 60: 262 | self.__client.send(build_command_response(ReplyType.TTL_EXPIRED)) 263 | elif result == 61: 264 | self.__client.send(build_command_response(ReplyType.NETWORK_UNREACHABLE)) 265 | else: 266 | logging.error('Connection Error:[%s] is unknown', result) 267 | self.__client.send(build_command_response(ReplyType.NETWORK_UNREACHABLE)) 268 | 269 | def do_bind(self): 270 | pass 271 | 272 | def do_udp_associate(self): 273 | pass 274 | 275 | def __get_address(self): 276 | return self.__remote_server_host, self.__remote_server_port 277 | 278 | 279 | class User: 280 | def __init__(self, username, password): 281 | self.__username = username 282 | self.__password = password 283 | 284 | def get_username(self): 285 | return self.__username 286 | 287 | def get_password(self): 288 | return self.__password 289 | 290 | def __repr__(self): 291 | return '' % (self.get_username(), self.__password) 292 | 293 | 294 | class UserManager: 295 | def __init__(self): 296 | self.__users = {} 297 | 298 | def add_user(self, user): 299 | self.__users[user.get_username()] = user 300 | 301 | def remove_user(self, username): 302 | if username in self.__users: 303 | del self.__users[username] 304 | 305 | def check(self, username, password): 306 | if username in self.__users and self.__users[username].get_password() == password: 307 | return True 308 | else: 309 | return False 310 | 311 | def get_user(self, username): 312 | return self.__users[username] 313 | 314 | def get_users(self): 315 | return self.__users 316 | 317 | 318 | class Socks5RequestHandler(StreamRequestHandler): 319 | def __init__(self, request, client_address, server): 320 | StreamRequestHandler.__init__(self, request, client_address, server) 321 | 322 | def handle(self): 323 | session = Session(self.connection) 324 | logging.info('Create session[%s] for %s:%d', 1, self.client_address[0], self.client_address[1]) 325 | # print(self.server.allowed) 326 | if self.server.allowed and self.client_address[0] not in self.server.allowed: 327 | logging.info('Remote IP not in allowed list. Closing connection') 328 | close_session(session) 329 | return 330 | client = self.connection 331 | client.recv(1) 332 | method_num, = struct.unpack('b', client.recv(1)) 333 | meth_bytes = client.recv(method_num) 334 | methods = struct.unpack('b' * method_num, meth_bytes) 335 | auth = self.server.is_auth() 336 | if methods.__contains__(SocksMethod.NO_AUTHENTICATION_REQUIRED) and not auth: 337 | client.send(b"\x05\x00") 338 | elif methods.__contains__(SocksMethod.USERNAME_PASSWORD) and auth: 339 | client.send(b"\x05\x02") 340 | if not self.__do_username_password_auth(): 341 | logging.info('Session[%d] authentication failed', session.get_id()) 342 | close_session(session) 343 | return 344 | else: 345 | logging.info('Client requested unknown method (%s, %s->%s). Cannot continue.', methods, method_num, 346 | meth_bytes) 347 | client.send(b"\x05\xFF") 348 | return 349 | 350 | version, command, reserved, address_type = struct.unpack('B' * 4, client.recv(4)) 351 | host = None 352 | port = None 353 | if address_type == AddressType.IPV4: 354 | ip_a, ip_b, ip_c, ip_d, port = struct.unpack('!' + ('b' * 4) + 'H', client.recv(6)) 355 | host = host_from_ip(ip_a, ip_b, ip_c, ip_d) 356 | elif address_type == AddressType.DOMAIN_NAME: 357 | host_length, = struct.unpack('b', client.recv(1)) 358 | host = client.recv(host_length) 359 | port, = struct.unpack('!H', client.recv(2)) 360 | elif address_type == AddressType.IPV6: 361 | ip6_01, ip6_02, ip6_03, ip6_04, \ 362 | ip6_05, ip6_06, ip6_07, ip6_08, \ 363 | ip6_09, ip6_10, ip6_11, ip6_12, \ 364 | ip6_13, ip6_14, ip6_15, ip6_16, \ 365 | port = struct.unpack('!' + ('b' * 16) + 'H', client.recv(18)) 366 | 367 | logging.warn("Address type not implemented: %s (IPV6 Connect)", address_type) 368 | logging.info("Params: %s, port: %s", ( 369 | ip6_01, ip6_02, ip6_03, ip6_04, ip6_05, ip6_06, ip6_07, ip6_08, ip6_09, ip6_10, ip6_11, ip6_12, ip6_13, 370 | ip6_14, ip6_15, ip6_16), port) 371 | client.send(build_command_response(ReplyType.ADDRESS_TYPE_NOT_SUPPORTED)) 372 | return 373 | 374 | else: # address type not support 375 | logging.warn("Address type not supported: %s", address_type) 376 | client.send(build_command_response(ReplyType.ADDRESS_TYPE_NOT_SUPPORTED)) 377 | return 378 | 379 | command_executor = CommandExecutor(host, port, session) 380 | if command == SocksCommand.CONNECT: 381 | logging.info("Session[%s] Request connect %s:%s", session.get_id(), host, port) 382 | command_executor.do_connect() 383 | close_session(session) 384 | 385 | def __do_username_password_auth(self): 386 | client = self.connection 387 | client.recv(1) 388 | length = byte_to_int(struct.unpack('b', client.recv(1))[0]) 389 | username = client.recv(length) 390 | length = byte_to_int(struct.unpack('b', client.recv(1))[0]) 391 | password = client.recv(length) 392 | user_manager = self.server.get_user_manager() 393 | if user_manager.check(username, password): 394 | client.send(b"\x01\x00") 395 | return True 396 | else: 397 | client.send(b"\x01\x01") 398 | return False 399 | 400 | 401 | class Socks5Server(ThreadingTCPServer): 402 | """ 403 | SOCKS5 proxy server 404 | """ 405 | 406 | def __init__(self, port, auth=False, user_manager=UserManager(), allowed=None): 407 | ThreadingTCPServer.__init__(self, ('', port), Socks5RequestHandler) 408 | self.__port = port 409 | self.__users = {} 410 | self.__auth = auth 411 | self.__user_manager = user_manager 412 | self.__sessions = {} 413 | self.allowed = allowed 414 | 415 | self.th = threading.Thread(target=self.serve_forever) 416 | 417 | def serve_forever(self, poll_interval=0.5): 418 | logging.info("Create SOCKS5 server at port %d", self.__port) 419 | ThreadingTCPServer.serve_forever(self, poll_interval) 420 | 421 | def finish_request(self, request, client_address): 422 | BaseServer.finish_request(self, request, client_address) 423 | 424 | def is_auth(self): 425 | return self.__auth 426 | 427 | def set_auth(self, auth): 428 | self.__auth = auth 429 | 430 | def get_all_managed_session(self): 431 | return self.__sessions 432 | 433 | def get_bind_port(self): 434 | return self.__port 435 | 436 | def get_user_manager(self): 437 | return self.__user_manager 438 | 439 | def set_user_manager(self, user_manager): 440 | self.__user_manager = user_manager 441 | 442 | def run_in_thread(self): 443 | self.th.start() 444 | 445 | def stop_server_thread(self): 446 | self.server_close() 447 | self.shutdown() 448 | self.th.join() 449 | 450 | 451 | def check_os_support(): 452 | if not support_os.__contains__(current_os): 453 | print('Not support in %s' % current_os) 454 | sys.exit() 455 | 456 | 457 | def stop(pid_file): 458 | check_os_support() 459 | print('Stopping server...', end=' ') 460 | try: 461 | f = open(pid_file, 'r') 462 | pid = int(f.readline()) 463 | os.kill(pid, signal.SIGTERM) 464 | os.remove(pid_file) 465 | print(" [OK]") 466 | except OSError: 467 | print("pysocks is not running") 468 | except IOError: 469 | print("pysocks is not running") 470 | 471 | 472 | def status(pid_file): 473 | check_os_support() 474 | try: 475 | f = open(pid_file, 'r') 476 | pid = int(f.readline()) 477 | print('pysocks(pid %d) is running...' % pid) 478 | except IOError: 479 | print("pysocks is stopped") 480 | 481 | 482 | def start_command(args): 483 | enable_log = True 484 | log_file = args.logfile 485 | auth = args.auth is not None 486 | pid_file = args.pidfile 487 | user_manager = UserManager() 488 | should_daemonisze = not args.foreground 489 | if auth: 490 | for user in args.auth: 491 | user_pwd = user.split(':') 492 | user_manager.add_user(User(user_pwd[0], user_pwd[1])) 493 | if enable_log: 494 | logging.basicConfig(level=logging.INFO, 495 | format='%(asctime)s %(levelname)s - %(message)s', 496 | filename=log_file, 497 | filemode='a') 498 | console = logging.StreamHandler(sys.stdout) 499 | console.setLevel(logging.INFO) 500 | formatter = logging.Formatter('%(asctime)s %(levelname)-5s %(lineno)-3d - %(message)s') 501 | console.setFormatter(formatter) 502 | logging.getLogger().addHandler(console) 503 | 504 | Socks5Server.allow_reuse_address = True 505 | socks5_server = Socks5Server(args.port, auth, user_manager, allowed=args.allow_ip) 506 | try: 507 | if support_os.__contains__(current_os) and should_daemonisze: 508 | run_daemon_process(pid_file=pid_file, start_msg='Start SOCKS5 server at pid %s\n') 509 | socks5_server.serve_forever() 510 | except KeyboardInterrupt: 511 | socks5_server.server_close() 512 | socks5_server.shutdown() 513 | logging.info("SOCKS5 server shutdown") 514 | 515 | 516 | def stop_command(args): 517 | pid_file = pid_file = args.pidfile 518 | stop(pid_file) 519 | sys.exit() 520 | 521 | 522 | def status_command(args): 523 | pid_file = args.pidfile 524 | status(pid_file) 525 | sys.exit() 526 | 527 | 528 | def main(): 529 | default_pid_file = os.path.join(os.path.expanduser('~'), '.pysocks.pid') 530 | default_log_file = os.path.join(os.path.expanduser('~'), 'pysocks.log') 531 | parser = argparse.ArgumentParser(description='start a simple socks5 server', 532 | formatter_class=argparse.ArgumentDefaultsHelpFormatter) 533 | subparsers = parser.add_subparsers(help='sub-command help') 534 | parser_start = subparsers.add_parser('start', help='start a SOCKS5 server', description='start a SOCKS5 server', 535 | formatter_class=argparse.ArgumentDefaultsHelpFormatter) 536 | parser_start.add_argument('-p', '--port', type=int, help='specify server port, default 1080', default=1080) 537 | parser_start.add_argument('-f', '--foreground', help='stay in foreground (prevents daemonization)', 538 | action='store_true', default=False) 539 | parser_start.add_argument('-i', '--allow-ip', nargs='+', help='allowed client IP list') 540 | parser_start.add_argument('-a', '--auth', nargs='+', help='allowed users') 541 | parser_start.add_argument('-L', '--logfile', help='log file', default=default_log_file) 542 | parser_start.add_argument('-P', '--pidfile', help='pid file', default=default_pid_file) 543 | parser_start.set_defaults(func=start_command) 544 | parser_stop = subparsers.add_parser('stop', help='stop a SOCKS5 server', description='stop a SOCKS5 server', 545 | formatter_class=argparse.ArgumentDefaultsHelpFormatter) 546 | parser_stop.add_argument('-P', '--pidfile', help='pid file', default=default_pid_file) 547 | parser_stop.set_defaults(func=stop_command) 548 | parser_status = subparsers.add_parser('status', help='print SOCKS5 server status', 549 | description='print SOCKS5 server status', 550 | formatter_class=argparse.ArgumentDefaultsHelpFormatter) 551 | parser_status.add_argument('-P', '--pidfile', help='pid file', default=default_pid_file) 552 | parser_status.set_defaults(func=status_command) 553 | args = parser.parse_args() 554 | args.func(args) 555 | 556 | 557 | if __name__ == '__main__': 558 | main() 559 | --------------------------------------------------------------------------------