Skip to content

Instantly share code, notes, and snippets.

@NicolaiSoeborg
Last active March 18, 2021 10:35
Show Gist options
  • Save NicolaiSoeborg/ba44b9df21ebb28cbd2f744f12bec7ef to your computer and use it in GitHub Desktop.
Save NicolaiSoeborg/ba44b9df21ebb28cbd2f744f12bec7ef to your computer and use it in GitHub Desktop.
MITM proxy program to forward (tee) traffic between two TCP ports
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