├── .github └── FUNDING.yml ├── tests ├── udp │ ├── client.py │ └── server.py └── tcp │ ├── client.py │ └── server.py ├── LICENSE ├── README.md ├── .gitignore └── code └── pyproxy.py /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: rsc-dev 2 | -------------------------------------------------------------------------------- /tests/udp/client.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | __author__ = 'Radoslaw Matusiak' 4 | __copyright__ = 'Copyright (c) 2016 Radoslaw Matusiak' 5 | __license__ = 'MIT' 6 | __version__ = '0.1' 7 | 8 | import socket 9 | 10 | SERVER_HOST = "127.0.0.1" 11 | SERVER_PORT = 8000 12 | BUFFER_SIZE = 2 ** 10 13 | 14 | MESSAGE = "client" 15 | 16 | 17 | def run_client(): 18 | client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 19 | client_socket.sendto(MESSAGE, (SERVER_HOST, SERVER_PORT)) 20 | 21 | data, address = client_socket.recvfrom(BUFFER_SIZE) 22 | print '[*] Server (%s) response: "%s"' % (str(address), data) 23 | # end-of-function run_client 24 | 25 | 26 | if __name__ == '__main__': 27 | print '[*] Running UDP client...' 28 | run_client() -------------------------------------------------------------------------------- /tests/udp/server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | __author__ = 'Radoslaw Matusiak' 4 | __copyright__ = 'Copyright (c) 2016 Radoslaw Matusiak' 5 | __license__ = 'MIT' 6 | __version__ = '0.1' 7 | 8 | import socket 9 | 10 | SERVER_HOST = '127.0.0.1' 11 | SERVER_PORT = 8888 12 | BUFFER_SIZE = 2 ** 10 13 | 14 | def run_server(): 15 | server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 16 | server_socket.bind((SERVER_HOST, SERVER_PORT)) 17 | 18 | while True: 19 | data, address = server_socket.recvfrom(BUFFER_SIZE) 20 | print '[*] Received data ("%s") from client (%s)' % (data, str(address)) 21 | 22 | data = 'server: %s' % data 23 | 24 | server_socket.sendto(data, address) 25 | # end-of-function run_server 26 | 27 | 28 | if __name__ == '__main__': 29 | print '[*] Running UDP server on %s:%d...' % (SERVER_HOST, SERVER_PORT) 30 | run_server() 31 | -------------------------------------------------------------------------------- /tests/tcp/client.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | __author__ = 'Radoslaw Matusiak' 4 | __copyright__ = 'Copyright (c) 2016 Radoslaw Matusiak' 5 | __license__ = 'MIT' 6 | __version__ = '0.1' 7 | 8 | import socket 9 | import time 10 | 11 | SERVER_HOST = "127.0.0.1" 12 | SERVER_PORT = 8000 13 | BUFFER_SIZE = 2 ** 10 14 | 15 | MESSAGE = "client" 16 | 17 | 18 | def run_client(): 19 | client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 20 | server_address = (SERVER_HOST, SERVER_PORT) 21 | 22 | client_socket.connect(server_address) 23 | 24 | while True: 25 | client_socket.sendall('hello_server') 26 | data = client_socket.recv(BUFFER_SIZE) 27 | 28 | print '[*] Server (%s) response: "%s"' % (str(server_address), data) 29 | 30 | time.sleep(3) 31 | # end-of-function run_client 32 | 33 | 34 | if __name__ == '__main__': 35 | print '[*] Running TCP client...' 36 | run_client() -------------------------------------------------------------------------------- /tests/tcp/server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | __author__ = 'Radoslaw Matusiak' 4 | __copyright__ = 'Copyright (c) 2016 Radoslaw Matusiak' 5 | __license__ = 'MIT' 6 | __version__ = '0.1' 7 | 8 | import socket 9 | 10 | SERVER_HOST = '127.0.0.1' 11 | SERVER_PORT = 8888 12 | BUFFER_SIZE = 2 ** 10 13 | 14 | def run_server(): 15 | server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 16 | server_socket.bind((SERVER_HOST, SERVER_PORT)) 17 | server_socket.listen(1) 18 | 19 | conn, addr = server_socket.accept() 20 | 21 | while True: 22 | data = conn.recv(BUFFER_SIZE) 23 | 24 | if not data: 25 | break 26 | 27 | print '[*] Received data ("%s") from client (%s)' % (data, str(addr)) 28 | conn.sendall(data) 29 | # end-of-function run_server 30 | 31 | 32 | if __name__ == '__main__': 33 | print '[*] Running TCP server on %s:%d...' % (SERVER_HOST, SERVER_PORT) 34 | run_server() 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Radoslaw Matusiak 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PyProxy - Very Simple TCP/UDP Proxy 2 | 3 | ## About 4 | PyProxy is a very simple TCP/UDP pure Python proxy. 5 | It can be easily extended for custom data handling logic. 6 | 7 | ## Usage 8 | ```cmd 9 | >pyproxy.py -h 10 | usage: pyproxy.py [-h] (--tcp | --udp) -s SRC -d DST [-q | -v] 11 | 12 | TCP/UPD proxy. 13 | 14 | optional arguments: 15 | -h, --help show this help message and exit 16 | --tcp TCP proxy 17 | --udp UDP proxy 18 | -s SRC, --src SRC Source IP and port, i.e.: 127.0.0.1:8000 19 | -d DST, --dst DST Destination IP and port, i.e.: 127.0.0.1:8888 20 | -q, --quiet Be quiet 21 | -v, --verbose Be loud 22 | ``` 23 | 24 | ### Custom data handlers 25 | Proxy uses two data handlers for incoming and outgoing data. 26 | By default both are set to identity function. 27 | ```python 28 | LOCAL_DATA_HANDLER = lambda x:x 29 | REMOTE_DATA_HANDLER = lambda x:x 30 | ``` 31 | 32 | One can easily implement own rules. It might be very useful while testing network applications. 33 | ```python 34 | def custom_data_handler(data): 35 | # code goes here 36 | pass 37 | 38 | LOCAL_DATA_HANDLER = custom_data_handler 39 | REMOTE_DATA_HANDLER = lambda x:'constant_value' 40 | ``` 41 | 42 | ## License 43 | Code is released under [MIT license](https://github.com/rsc-dev/pyproxy/blob/master/LICENSE) © [Radoslaw '[rsc]' Matusiak](https://rm2084.blogspot.com/). -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | -------------------------------------------------------------------------------- /code/pyproxy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | __author__ = 'Radoslaw Matusiak' 4 | __copyright__ = 'Copyright (c) 2016 Radoslaw Matusiak' 5 | __license__ = 'MIT' 6 | __version__ = '0.1' 7 | 8 | 9 | """ 10 | TCP/UDP proxy. 11 | """ 12 | 13 | import argparse 14 | import signal 15 | import logging 16 | import select 17 | import socket 18 | 19 | 20 | FORMAT = '%(asctime)-15s %(levelname)-10s %(message)s' 21 | logging.basicConfig(format=FORMAT) 22 | LOGGER = logging.getLogger() 23 | 24 | LOCAL_DATA_HANDLER = lambda x:x 25 | REMOTE_DATA_HANDLER = lambda x:x 26 | 27 | BUFFER_SIZE = 2 ** 10 # 1024. Keep buffer size as power of 2. 28 | 29 | 30 | def udp_proxy(src, dst): 31 | """Run UDP proxy. 32 | 33 | Arguments: 34 | src -- Source IP address and port string. I.e.: '127.0.0.1:8000' 35 | dst -- Destination IP address and port. I.e.: '127.0.0.1:8888' 36 | """ 37 | LOGGER.debug('Starting UDP proxy...') 38 | LOGGER.debug('Src: {}'.format(src)) 39 | LOGGER.debug('Dst: {}'.format(dst)) 40 | 41 | proxy_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 42 | proxy_socket.bind(ip_to_tuple(src)) 43 | 44 | client_address = None 45 | server_address = ip_to_tuple(dst) 46 | 47 | LOGGER.debug('Looping proxy (press Ctrl-Break to stop)...') 48 | while True: 49 | data, address = proxy_socket.recvfrom(BUFFER_SIZE) 50 | 51 | if client_address == None: 52 | client_address = address 53 | 54 | if address == client_address: 55 | data = LOCAL_DATA_HANDLER(data) 56 | proxy_socket.sendto(data, server_address) 57 | elif address == server_address: 58 | data = REMOTE_DATA_HANDLER(data) 59 | proxy_socket.sendto(data, client_address) 60 | client_address = None 61 | else: 62 | LOGGER.warning('Unknown address: {}'.format(str(address))) 63 | # end-of-function udp_proxy 64 | 65 | 66 | def tcp_proxy(src, dst): 67 | """Run TCP proxy. 68 | 69 | Arguments: 70 | src -- Source IP address and port string. I.e.: '127.0.0.1:8000' 71 | dst -- Destination IP address and port. I.e.: '127.0.0.1:8888' 72 | """ 73 | LOGGER.debug('Starting TCP proxy...') 74 | LOGGER.debug('Src: {}'.format(src)) 75 | LOGGER.debug('Dst: {}'.format(dst)) 76 | 77 | sockets = [] 78 | 79 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 80 | s.bind(ip_to_tuple(src)) 81 | s.listen(1) 82 | 83 | s_src, _ = s.accept() 84 | 85 | s_dst = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 86 | s_dst.connect(ip_to_tuple(dst)) 87 | 88 | sockets.append(s_src) 89 | sockets.append(s_dst) 90 | 91 | while True: 92 | s_read, _, _ = select.select(sockets, [], []) 93 | 94 | for s in s_read: 95 | data = s.recv(BUFFER_SIZE) 96 | 97 | if s == s_src: 98 | d = LOCAL_DATA_HANDLER(data) 99 | s_dst.sendall(d) 100 | elif s == s_dst: 101 | d = REMOTE_DATA_HANDLER(data) 102 | s_src.sendall(d) 103 | # end-of-function tcp_proxy 104 | 105 | 106 | def ip_to_tuple(ip): 107 | """Parse IP string and return (ip, port) tuple. 108 | 109 | Arguments: 110 | ip -- IP address:port string. I.e.: '127.0.0.1:8000'. 111 | """ 112 | ip, port = ip.split(':') 113 | return (ip, int(port)) 114 | # end-of-function ip_to_tuple 115 | 116 | 117 | def main(): 118 | """Main method.""" 119 | parser = argparse.ArgumentParser(description='TCP/UPD proxy.') 120 | 121 | # TCP UPD groups 122 | proto_group = parser.add_mutually_exclusive_group(required=True) 123 | proto_group.add_argument('--tcp', action='store_true', help='TCP proxy') 124 | proto_group.add_argument('--udp', action='store_true', help='UDP proxy') 125 | 126 | parser.add_argument('-s', '--src', required=True, help='Source IP and port, i.e.: 127.0.0.1:8000') 127 | parser.add_argument('-d', '--dst', required=True, help='Destination IP and port, i.e.: 127.0.0.1:8888') 128 | 129 | output_group = parser.add_mutually_exclusive_group() 130 | output_group.add_argument('-q', '--quiet', action='store_true', help='Be quiet') 131 | output_group.add_argument('-v', '--verbose', action='store_true', help='Be loud') 132 | 133 | args = parser.parse_args() 134 | 135 | if args.quiet: 136 | LOGGER.setLevel(logging.CRITICAL) 137 | if args.verbose: 138 | LOGGER.setLevel(logging.NOTSET) 139 | 140 | if args.udp: 141 | udp_proxy(args.src, args.dst) 142 | elif args.tcp: 143 | tcp_proxy(args.src, args.dst) 144 | # end-of-function main 145 | 146 | 147 | if __name__ == '__main__': 148 | main() --------------------------------------------------------------------------------