Skip to content

Instantly share code, notes, and snippets.

@fbion
Forked from informationsea/transproxy-helper.py
Created February 26, 2020 09:25
Show Gist options
  • Save fbion/b69b8f9ac66816186dc91d8fd52b64b5 to your computer and use it in GitHub Desktop.
Save fbion/b69b8f9ac66816186dc91d8fd52b64b5 to your computer and use it in GitHub Desktop.
use go-transproxy with FreeBSD, macOS
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import ipaddress
import itertools
import subprocess
import tempfile
import os
import signal
def _main():
parser = argparse.ArgumentParser(description="Transproxy Helper")
parser.add_argument('proxy', help="Proxy URL (HTTP, HTTPS)")
parser.add_argument('no_proxy_address', default="10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,169.254.0.0/16,100.64.0.0/10", help="", nargs="?")
parser.add_argument('--default-pf', default='/etc/pf.conf')
parser.add_argument('--transproxy-options', default=["-disable-iptables"], nargs="*")
options = parser.parse_args()
ipnetwork = [ipaddress.ip_network("0.0.0.0/0")]
for one in options.no_proxy_address.split(','):
#print(one.strip(), ipnetwork)
one_network = ipaddress.ip_network(one.strip())
new_networks = [x.address_exclude(one_network) if x.overlaps(one_network) else [x] for x in ipnetwork]
ipnetwork = list(itertools.chain(*new_networks))
with tempfile.NamedTemporaryFile(mode="w+", prefix="pf-", suffix=".conf", encoding='utf-8') as tmp:
print('''Packets = "proto tcp from em0 to {''' + ", ".join([str(x) for x in ipnetwork]) + '''}"
rdr pass log on lo0 $Packets port 80 -> 127.0.0.1 port 3129
rdr pass log on lo0 $Packets port 443 -> 127.0.0.1 port 3130
pass out on em0 route-to lo0 inet $Packets port {80, 443} keep state''', file=tmp)
tmp.flush()
print(tmp.name)
print("Enabling firewall settings")
subprocess.run(["sudo", "pfctl", "-f", tmp.name])
env = dict(os.environ)
env['no_proxy'] = options.no_proxy_address
env['http_proxy'] = options.proxy
env['https_proxy'] = options.proxy
try:
p = subprocess.run(["./transproxy"] + options.transproxy_options, env=env)
except KeyboardInterrupt:
pass
print("Clearing firewall settings")
subprocess.run(["sudo", "pfctl", "-f", options.default_pf])
if __name__ == '__main__':
_main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment