Advertisement
BaSs_HaXoR

[TOR ROUTING SCRIPT] Tor Iptables

Nov 12th, 2016
784
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.36 KB | None | 0 0
  1. ##########################################
  2. # SOURCE: https://github.com/ruped24/toriptables2
  3. ##########################################
  4. # Tor Iptables script is an anonymizer that sets up iptables and tor to route all services and traffic including DNS through the tor network.
  5. ##########################################
  6. # Dependencies:
  7. # tor
  8. ##########################################
  9. # Usage:
  10. # toriptables2.py -h
  11. ##########################################
  12. # To test:
  13.  
  14. # What is my IP address
  15. # Check Tor Project
  16. # Witch proxy checker
  17. # IP leak test
  18. # DNS leak test
  19. # What every Browser knows about you
  20.  
  21. ##########################################
  22. # To change IP w/o reload:
  23. # Refresh Check Tor project webpage
  24. # sudo kill -HUP $(pidof tor)
  25.  
  26. ##########################################
  27. #               THE SCRIPT               #
  28. ##########################################
  29. #! /usr/bin/env python
  30. # Written by Rupe version 2
  31. #
  32. """
  33. Tor Iptables script is an anonymizer
  34. that sets up iptables and tor to route all services
  35. and traffic including DNS through the tor network.
  36. """
  37.  
  38. from __future__ import print_function
  39. from commands import getoutput
  40. from subprocess import call, check_call, CalledProcessError
  41. from os.path import isfile, basename
  42. from os import devnull
  43. from sys import stdout, stderr
  44. from atexit import register
  45. from argparse import ArgumentParser
  46. from json import load
  47. from urllib2 import urlopen, URLError
  48. from time import sleep
  49.  
  50.  
  51. class TorIptables(object):
  52.  
  53.   def __init__(self):
  54.     self.local_dnsport = "53"  # DNSPort
  55.     self.virtual_net = "10.0.0.0/10"  # VirtualAddrNetwork
  56.     self.local_loopback = "127.0.0.1" # Local loopback
  57.     self.non_tor_net = ["192.168.0.0/16", "172.16.0.0/12"]
  58.     self.non_tor = ["127.0.0.0/9", "127.128.0.0/10", "127.0.0.0/8"]
  59.     self.tor_uid = getoutput("id -ur debian-tor")  # Tor user uid
  60.     self.trans_port = "9040"  # Tor port
  61.     self.tor_config_file = '/etc/tor/torrc'
  62.     self.torrc = r'''
  63. ## Inserted by %s for tor iptables rules set
  64. ## Transparently route all traffic thru tor on port %s
  65. VirtualAddrNetwork %s
  66. AutomapHostsOnResolve 1
  67. TransPort %s
  68. DNSPort %s
  69. ''' % (basename(__file__), self.trans_port, self.virtual_net,
  70.        self.trans_port, self.local_dnsport)
  71.  
  72.   def flush_iptables_rules(self):
  73.     call(["iptables", "-F"])
  74.     call(["iptables", "-t", "nat", "-F"])
  75.  
  76.   def load_iptables_rules(self):
  77.     self.flush_iptables_rules()
  78.     self.non_tor.extend(self.non_tor_net)
  79.  
  80.     @register
  81.     def restart_tor():
  82.       fnull = open(devnull, 'w')
  83.       try:
  84.         tor_restart = check_call(
  85.             ["service", "tor", "restart"],
  86.               stdout=fnull, stderr=fnull)
  87.  
  88.         if tor_restart is 0:
  89.           print(" {0}".format(
  90.               "[\033[92m+\033[0m] Anonymizer status \033[92m[ON]\033[0m"))
  91.           print(" {0}".format(
  92.               "[\033[92m*\033[0m] Getting public IP, please wait..."))
  93.           retries = 0
  94.           my_public_ip = None
  95.           while retries < 12 and not my_public_ip:
  96.             retries += 1
  97.             try:
  98.               my_public_ip = load(urlopen('http://jsonip.com/'))['ip']
  99.             except URLError:
  100.               sleep(5)
  101.               print(" [\033[93m?\033[0m] Still waiting for IP address...")
  102.           print
  103.           if not my_public_ip:
  104.             my_public_ip = getoutput('wget -qO - v4.ifconfig.co')
  105.           if not my_public_ip:
  106.             exit(" \033[91m[!]\033[0m Can't get public ip address!")
  107.           print(" {0}".format("[\033[92m+\033[0m] Your IP is \033[92m%s\033[0m" % my_public_ip))
  108.       except CalledProcessError as err:
  109.         print("\033[91m[!] Command failed: %s\033[0m" % ' '.join(err.cmd))
  110.  
  111.     # See https://trac.torproject.org/projects/tor/wiki/doc/TransparentProxy#WARNING
  112.     # See https://lists.torproject.org/pipermail/tor-talk/2014-March/032503.html
  113.     call(["iptables", "-I", "OUTPUT", "!", "-o", "lo", "!", "-d",
  114.           self.local_loopback, "!", "-s", self.local_loopback, "-p", "tcp",
  115.           "-m", "tcp", "--tcp-flags", "ACK,FIN", "ACK,FIN", "-j", "DROP"])
  116.     call(["iptables", "-I", "OUTPUT", "!", "-o", "lo", "!", "-d",
  117.           self.local_loopback, "!", "-s", self.local_loopback, "-p", "tcp",
  118.           "-m", "tcp", "--tcp-flags", "ACK,RST", "ACK,RST", "-j", "DROP"])
  119.  
  120.     call(["iptables", "-t", "nat", "-A", "OUTPUT", "-m", "owner", "--uid-owner",
  121.           "%s" % self.tor_uid, "-j", "RETURN"])
  122.     call(["iptables", "-t", "nat", "-A", "OUTPUT", "-p", "udp", "--dport",
  123.           self.local_dnsport, "-j", "REDIRECT", "--to-ports", self.local_dnsport])
  124.  
  125.     for net in self.non_tor:
  126.       call(["iptables", "-t", "nat", "-A", "OUTPUT", "-d", "%s" % net, "-j",
  127.             "RETURN"])
  128.  
  129.     call(["iptables", "-t", "nat", "-A", "OUTPUT", "-p", "tcp", "--syn", "-j",
  130.           "REDIRECT", "--to-ports", "%s" % self.trans_port])
  131.  
  132.     call(["iptables", "-A", "OUTPUT", "-m", "state", "--state",
  133.           "ESTABLISHED,RELATED", "-j", "ACCEPT"])
  134.  
  135.     for net in self.non_tor:
  136.       call(["iptables", "-A", "OUTPUT", "-d", "%s" % net, "-j", "ACCEPT"])
  137.  
  138.     call(["iptables", "-A", "OUTPUT", "-m", "owner", "--uid-owner", "%s" %
  139.           self.tor_uid, "-j", "ACCEPT"])
  140.     call(["iptables", "-A", "OUTPUT", "-j", "REJECT"])
  141.  
  142.  
  143. if __name__ == '__main__':
  144.   parser = ArgumentParser(
  145.       description=
  146.       'Tor Iptables script for loading and unloading iptables rules')
  147.   parser.add_argument('-l',
  148.                       '--load',
  149.                       action='store_true',
  150.                       help='This option will load tor iptables rules')
  151.   parser.add_argument('-f',
  152.                       '--flush',
  153.                       action='store_true',
  154.                       help='This option flushes the iptables rules to default')
  155.   args = parser.parse_args()
  156.  
  157.   try:
  158.     load_tables = TorIptables()
  159.     if isfile(load_tables.tor_config_file):
  160.       if not 'VirtualAddrNetwork' in open(load_tables.tor_config_file).read():
  161.         with open(load_tables.tor_config_file, 'a+') as torrconf:
  162.           torrconf.write(load_tables.torrc)
  163.  
  164.     if args.load:
  165.       load_tables.load_iptables_rules()
  166.     elif args.flush:
  167.       load_tables.flush_iptables_rules()
  168.       print(" {0}".format(
  169.           "[\033[93m!\033[0m] Anonymizer status \033[91m[OFF]\033[0m"))
  170.     else:
  171.       parser.print_help()
  172.   except Exception as err:
  173.     print("[!] Run as super user: %s" % err[1])
  174. 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement