Last active
March 18, 2021 10:35
-
-
Save NicolaiSoeborg/ba44b9df21ebb28cbd2f744f12bec7ef to your computer and use it in GitHub Desktop.
MITM proxy program to forward (tee) traffic between two TCP ports
This file contains hidden or 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
import trio # python3 -m pip install --upgrade trio | |
from functools import partial | |
async def forward_from_a_to_b(a, b): | |
async for chunk in a: | |
print(f"=> {chunk}", flush=True) | |
await b.send_all(chunk) | |
async def proxy(args, listen_stream): | |
target_stream = await trio.open_tcp_stream(args.forward_host, args.forward_port) | |
async with trio.open_nursery() as nursery: | |
nursery.start_soon(forward_from_a_to_b, listen_stream, target_stream) | |
nursery.start_soon(forward_from_a_to_b, target_stream, listen_stream) | |
async def main(args): | |
handler = partial(proxy, args) | |
await trio.serve_tcp(handler, args.listen_port) | |
if __name__ == '__main__': | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument('listen_port', type=int, help="Listen port") | |
parser.add_argument('forward_port', type=int, help="Port traffic is forwarded to") | |
parser.add_argument('--forward_host', type=str, default="127.0.0.1", help="Host to forward traffic to") | |
args = parser.parse_args() | |
trio.run(main, args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment