Created
July 6, 2020 06:29
-
-
Save lecafard/72139f5a89f128aeb28cd8ea1d863dab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import socket | |
import ssl | |
import sys | |
import asyncio | |
BASE_HOSTNAME = '{}.ctf-challenges.example.com' | |
DEFAULT_CLIENT_PORT = 7000 | |
REMOTE_PORT = 7000 | |
BUF_SIZE = 1024 | |
# https://stackoverflow.com/questions/46413879/how-to-create-tcp-proxy-server-with-asyncio | |
async def create_pipe(reader, writer): | |
try: | |
while not reader.at_eof(): | |
writer.write(await reader.read(BUF_SIZE)) | |
finally: | |
writer.close() | |
async def proxy(hostname, lread, lwrite): | |
context = ssl.create_default_context() | |
rread, rwrite = await asyncio.open_connection(hostname, REMOTE_PORT, ssl=context) | |
pipe1 = create_pipe(lread, rwrite) | |
pipe2 = create_pipe(rread, lwrite) | |
await asyncio.gather(pipe1, pipe2) | |
if __name__ == '__main__': | |
if len(sys.argv) > 3 or len(sys.argv) < 2: | |
print("usage: {} <name> [port]".format(sys.argv[0])) | |
sys.exit(1) | |
hostname = BASE_HOSTNAME.format(sys.argv[1]) | |
port = int(sys.argv[2]) if len(sys.argv) == 3 and sys.argv[2].isnumeric() else DEFAULT_CLIENT_PORT | |
loop = asyncio.get_event_loop() | |
server = loop.run_until_complete( | |
asyncio.start_server(lambda r, w: proxy(hostname, r, w), '127.0.0.1', port) | |
) | |
print("proxy server listening on port", port) | |
try: | |
loop.run_forever() | |
except KeyboardInterrupt: | |
pass | |
server.close() | |
loop.run_until_complete(server.wait_closed()) | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment