toriptables2/toriptables2.py

163 lines
5.8 KiB
Python
Raw Normal View History

#! /usr/bin/env python3
2020-07-22 19:15:25 +00:00
# Written by Rupe version 2.1
2016-01-14 17:13:14 +00:00
#
2015-06-17 21:42:03 +00:00
"""
Tor Iptables script is an anonymizer
that sets up iptables and tor to route all services
and traffic including DNS through the tor network.
"""
from subprocess import call, check_call, getoutput, CalledProcessError
2016-01-04 08:05:44 +00:00
from os.path import isfile, basename
2015-06-17 21:42:03 +00:00
from os import devnull
2020-09-19 13:49:33 +00:00
from sys import exit, stdout, stderr
2015-12-19 04:27:05 +00:00
from atexit import register
2015-06-17 21:42:03 +00:00
from argparse import ArgumentParser
2016-02-19 23:43:14 +00:00
from json import load
from urllib.request import urlopen
from urllib.error import URLError
from time import sleep
2015-06-17 21:42:03 +00:00
2016-08-06 21:35:21 +00:00
2015-06-17 21:42:03 +00:00
class TorIptables(object):
2015-12-19 04:27:05 +00:00
def __init__(self):
2016-01-04 07:14:06 +00:00
self.local_dnsport = "53" # DNSPort
self.virtual_net = "10.0.0.0/10" # VirtualAddrNetwork
2020-07-22 19:15:25 +00:00
self.local_loopback = "127.0.0.1" # Local loopback
2016-01-04 06:11:53 +00:00
self.non_tor_net = ["192.168.0.0/16", "172.16.0.0/12"]
self.non_tor = ["127.0.0.0/9", "127.128.0.0/10", "127.0.0.0/8"]
self.tor_uid = getoutput("id -ur debian-tor") # Tor user uid
self.trans_port = "9040" # Tor port
2015-12-19 04:27:05 +00:00
self.tor_config_file = '/etc/tor/torrc'
2016-01-14 17:13:14 +00:00
self.torrc = r'''
2016-01-04 08:05:44 +00:00
## Inserted by %s for tor iptables rules set
2016-01-04 06:11:53 +00:00
## Transparently route all traffic thru tor on port %s
2016-01-04 06:37:27 +00:00
VirtualAddrNetwork %s
2015-06-17 21:42:03 +00:00
AutomapHostsOnResolve 1
2016-01-04 06:11:53 +00:00
TransPort %s
2016-01-04 06:37:27 +00:00
DNSPort %s
2020-07-22 19:15:25 +00:00
''' % (basename(__file__), self.trans_port, self.virtual_net,
self.trans_port, self.local_dnsport)
2015-06-17 21:42:03 +00:00
2015-12-19 04:27:05 +00:00
def flush_iptables_rules(self):
2015-12-19 05:18:22 +00:00
call(["iptables", "-F"])
2015-12-19 04:27:05 +00:00
call(["iptables", "-t", "nat", "-F"])
2015-06-17 21:42:03 +00:00
2015-12-19 04:27:05 +00:00
def load_iptables_rules(self):
self.flush_iptables_rules()
self.non_tor.extend(self.non_tor_net)
2015-06-17 21:42:03 +00:00
2015-12-19 04:27:05 +00:00
@register
def restart_tor():
fnull = open(devnull, 'w')
2016-01-04 03:33:56 +00:00
try:
2016-08-06 21:35:21 +00:00
tor_restart = check_call(
["systemctl", "restart", "tor"],
2016-08-06 21:35:21 +00:00
stdout=fnull, stderr=fnull)
if tor_restart == 0:
print((" {0}".format(
"[\033[92m+\033[0m] Anonymizer status \033[92m[ON]\033[0m")))
self.get_ip()
2016-01-04 03:33:56 +00:00
except CalledProcessError as err:
print(("\033[91m[!] Command failed: %s\033[0m" % ' '.join(err.cmd)))
2015-06-17 21:42:03 +00:00
# See https://trac.torproject.org/projects/tor/wiki/doc/TransparentProxy#WARNING
# See https://lists.torproject.org/pipermail/tor-talk/2014-March/032503.html
2016-08-06 21:35:21 +00:00
call(["iptables", "-I", "OUTPUT", "!", "-o", "lo", "!", "-d",
self.local_loopback, "!", "-s", self.local_loopback, "-p", "tcp",
"-m", "tcp", "--tcp-flags", "ACK,FIN", "ACK,FIN", "-j", "DROP"])
call(["iptables", "-I", "OUTPUT", "!", "-o", "lo", "!", "-d",
self.local_loopback, "!", "-s", self.local_loopback, "-p", "tcp",
"-m", "tcp", "--tcp-flags", "ACK,RST", "ACK,RST", "-j", "DROP"])
2015-12-19 04:27:05 +00:00
call(["iptables", "-t", "nat", "-A", "OUTPUT", "-m", "owner", "--uid-owner",
"%s" % self.tor_uid, "-j", "RETURN"])
2016-01-14 17:13:14 +00:00
call(["iptables", "-t", "nat", "-A", "OUTPUT", "-p", "udp", "--dport",
2016-01-14 17:15:46 +00:00
self.local_dnsport, "-j", "REDIRECT", "--to-ports", self.local_dnsport])
2015-06-17 21:42:03 +00:00
2015-12-21 23:18:40 +00:00
for net in self.non_tor:
2015-12-28 00:28:18 +00:00
call(["iptables", "-t", "nat", "-A", "OUTPUT", "-d", "%s" % net, "-j",
"RETURN"])
2015-06-17 21:42:03 +00:00
2015-12-19 04:27:05 +00:00
call(["iptables", "-t", "nat", "-A", "OUTPUT", "-p", "tcp", "--syn", "-j",
"REDIRECT", "--to-ports", "%s" % self.trans_port])
2015-06-17 21:42:03 +00:00
2015-12-19 04:27:05 +00:00
call(["iptables", "-A", "OUTPUT", "-m", "state", "--state",
"ESTABLISHED,RELATED", "-j", "ACCEPT"])
2015-06-17 21:42:03 +00:00
2015-12-21 23:31:00 +00:00
for net in self.non_tor:
2015-12-21 23:18:40 +00:00
call(["iptables", "-A", "OUTPUT", "-d", "%s" % net, "-j", "ACCEPT"])
2015-06-17 21:42:03 +00:00
2015-12-19 04:27:05 +00:00
call(["iptables", "-A", "OUTPUT", "-m", "owner", "--uid-owner", "%s" %
self.tor_uid, "-j", "ACCEPT"])
call(["iptables", "-A", "OUTPUT", "-j", "REJECT"])
2015-06-17 21:42:03 +00:00
def get_ip(self):
print((" {0}".format(
"[\033[92m*\033[0m] Getting public IP, please wait...")))
retries = 0
my_public_ip = None
while retries < 12 and not my_public_ip:
retries += 1
try:
2021-02-26 01:49:05 +00:00
my_public_ip = load(urlopen('https://check.torproject.org/api/ip'))['IP']
except URLError:
sleep(5)
print(" [\033[93m?\033[0m] Still waiting for IP address...")
except ValueError:
break
print()
if not my_public_ip:
my_public_ip = getoutput('wget -qO - ifconfig.me')
if not my_public_ip:
exit(" \033[91m[!]\033[0m Can't get public ip address!")
print((" {0}".format("[\033[92m+\033[0m] Your IP is \033[92m%s\033[0m" % my_public_ip)))
2020-07-22 19:15:25 +00:00
2015-06-17 21:42:03 +00:00
if __name__ == '__main__':
2015-12-19 04:27:05 +00:00
parser = ArgumentParser(
2016-01-04 02:36:53 +00:00
description=
'Tor Iptables script for loading and unloading iptables rules')
parser.add_argument('-l',
'--load',
2015-12-22 05:18:04 +00:00
action='store_true',
2015-12-19 04:27:05 +00:00
help='This option will load tor iptables rules')
2016-01-04 02:36:53 +00:00
parser.add_argument('-f',
'--flush',
2015-12-19 04:27:05 +00:00
action='store_true',
help='This option flushes the iptables rules to default')
parser.add_argument('-r',
'--refresh',
action='store_true',
2020-07-22 19:15:25 +00:00
help='This option will change the circuit and gives new IP')
parser.add_argument('-i',
'--ip',
action='store_true',
help='This option will output the current public IP address')
2015-12-19 04:27:05 +00:00
args = parser.parse_args()
try:
load_tables = TorIptables()
if isfile(load_tables.tor_config_file):
if not 'VirtualAddrNetwork' in open(load_tables.tor_config_file).read():
with open(load_tables.tor_config_file, 'a+') as torrconf:
torrconf.write(load_tables.torrc)
if args.load:
load_tables.load_iptables_rules()
elif args.flush:
load_tables.flush_iptables_rules()
print((" {0}".format(
"[\033[93m!\033[0m] Anonymizer status \033[91m[OFF]\033[0m")))
elif args.ip:
load_tables.get_ip()
elif args.refresh:
2020-07-22 19:15:25 +00:00
call(['kill', '-HUP', '%s' % getoutput('pidof tor')])
load_tables.get_ip()
2015-12-19 04:27:05 +00:00
else:
parser.print_help()
except Exception as err:
print(("[!] Run as super user: %s" % err))