[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[or-cvs] r14864: This is the python backend for the Gnome applet. (torwall/trunk/src)



Author: ioerror
Date: 2008-05-31 07:48:09 -0400 (Sat, 31 May 2008)
New Revision: 14864

Added:
   torwall/trunk/src/torwall.py
Log:
This is the python backend for the Gnome applet.


Added: torwall/trunk/src/torwall.py
===================================================================
--- torwall/trunk/src/torwall.py	                        (rev 0)
+++ torwall/trunk/src/torwall.py	2008-05-31 11:48:09 UTC (rev 14864)
@@ -0,0 +1,262 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+"""
+ torwall.py
+
+ torwall.py is the backend script for the torwall Gnome Applet.
+ It is run as root by the applet and must be run with sudo to function properly.
+
+"""
+
+__program__ = 'torwall'
+__version__ = '20080529.00'
+__url__ = 'https://tor-svn.freehaven.net/svn/torwall/'
+__author__ = 'Jacob Appelbaum <jacob@xxxxxxxxxxxxx>'
+__copyright__ = 'Copyleft (c) 2008, Jacob Appelbaum'
+__license__ = 'See COPYING for licensing information'
+
+import os
+import sys
+import getopt
+from pwd import getpwnam
+
+def findIPTables():
+    """
+    Returns the full path to iptables, iptables-save and iptables-restore
+    """
+
+    iptables="/sbin/iptables"
+    iptablesSave="/sbin/iptables-save"
+    iptablesRestore="/sbin/iptables-restore"
+
+    return iptables, iptablesSave, iptablesRestore
+
+def saveState(iptablesSave="/sbin/iptables-save", savedState="/etc/torwall/iptables-state"):
+    """
+    This is where we save the state of the firewall
+    """
+
+    try:
+        print("Attempting to save the current rules: %s" % savedState)
+        os.system(iptablesSave + " > " + savedState)
+
+    except OSError:
+        print("We failed our attempt to save the current rules: %s" % savedState)
+        return None
+
+    return True
+
+def restoreState(iptablesRestore="/sbin/iptables-restore", savedState="/etc/torwall/iptables-state"):
+    """
+    This is where we restore the state of the firewall
+    """
+
+    try:
+        print("Attempting to restore the saved rules: %s" % savedState)
+        os.system(iptablesRestore + " > " + savedState)
+
+    except OSError:
+        print("We failed our attempt to restore the saved rules: %s" % savedState)
+        return None
+
+    return True
+
+def fetchTorUID(toruser="debian-tor"):
+    """
+    Fetch the Tor UID and return a valid, verified UID
+    """
+
+    try:
+        toruid = getpwnam(toruser)[2]
+    except KeyError:
+        print("We were unable to find the uid for any Tor user!")
+        return None
+    
+    return toruid
+
+def loadTorRules(toruser=fetchTorUID(), iptablesRestore="/sbin/iptables-restore", \
+    TorRules="/etc/torwall/torrules", transparent=False, subnet=None):
+    """
+    This loads a set of Tor specific firewall rules
+    """
+    
+    # TODO:
+    # If we're transparent, we'll load different rules
+    # If our users have local devices on a subnet, we want to allow users access to that subnet
+    # If we get a specific toruser, we'll want to set the rules to use it
+    # We'll also need to ensure that Tor has a functional dns server configured
+    if transparent:
+        switchResolveConf()
+
+    print("Attempting to load Tor specific rules: %s" % TorRules)
+    os.system(iptablesRestore + " < " + TorRules)
+
+def clearRules(iptables="/sbin/iptables"):
+    """
+    This clears all firewall rules, deletes all user supplied chains and sets
+    an ACCEPT policy for INPUT, OUTPUT and FORWARD
+    """
+
+    print("Attempting to clean iptables rules")
+    try:
+        os.system(iptables + " -F")
+        os.system(iptables + " -X")
+        os.system(iptables + " -t nat -F")
+        os.system(iptables + " -P INPUT ACCEPT")
+        os.system(iptables + " -P OUTPUT ACCEPT")
+        os.system(iptables + " -P FORWARD ACCEPT")
+
+    except:
+        print("Unable to flush iptables rules")
+        return False
+
+def swapFiles(src, dst):
+    """
+    Make two files switch places.
+    """
+
+    try:
+        srcStat = os.stat(src)
+    except OSError:
+        print("You're missing a file: %s" % src)
+        srcStat = None
+    try:
+        dstStat = os.stat(dst)
+    except OSError:
+        print("You're missing a file: %s" % dst)
+        dstStat = None
+
+    if srcStat and dstStat is not None:
+        try:
+            os.move(src, dst + ".swaping")
+            os.move(dst, src + ".swaping")
+            os.move(src + ".swaping", src)
+            os.move(dst + ".swaping", dst)
+            return True
+        except IOError:
+            print("Unable to swap files")
+            return None
+    else:
+       print("Something is wrong with your files.") 
+       return None
+
+def switchResolveConf(resolvConf="/etc/resolv.conf", \
+    newResolvConf="/etc/torwall/resolv.conf"):
+
+    """
+    To operate transparently, we'll need to configure a custom /etc/resolv.conf
+    """
+
+    filesSwapped = swapFiles(resolvConf, newResolvConf)
+
+    # backup the original and move our resolv.conf into place
+    if filesSwapped is None:
+            print("Unable to copy around requested the resolv.conf files")
+            return False
+    else:
+        return True
+
+def help():
+    """
+    Print a helpful message
+    """
+
+    print "Syntax: TorWall.py --start || --stop [--help] [--toruid uid] [--local-subnet subnet] " + \
+    "[--log] [--system-wide-proxy] [--transparent]" 
+
+def systemProxy(proxyConf, action):
+    """
+    This configures the GNOME system to use Tor (SOCKS 4a and Privoxy for HTTP)
+    as it's global proxy setting for all applications.
+    """
+
+    # TODO
+    # Make this happen someday
+
+def main():
+
+    # By default, no Gnome proxy fixups, no real action taken
+    proxy = 0
+    proxyConf = None
+    loading = False
+    unloading = False
+    iptables = "/sbin/iptables"
+
+    try:
+        opts, args = getopt.getopt(sys.argv[1:], "tn:sthlpz", \
+        ["start","stop","help","toruser","local-subnet","log","system-wide-proxy","transparent"])
+
+    except getopt.GetoptError, err:
+        print str(err)
+        help()
+        sys.exit(1)
+
+    toruid = fetchTorUID()
+    start = None
+    stop = None
+    toruser = localSubnet = log = systemWideProxy = transparent = None
+
+    for opt, arg in opts:
+        if opt in ("-s", "--start"):
+            start = True
+        elif opt in ("-e", "--stop"):
+            stop = True
+        elif opt in ("-h", "--help"):
+            help()
+            sys.exit()
+        elif opt in ("-t", "--toruser"):
+            toruser = arg
+            toruid = fetchTorUID(toruser)
+        elif opt in ("-n", "local-subnet"):
+            # TODO:
+            # We'll want to vet this eventually
+            # however, we currently do nothing with it
+            localSubnet = arg
+        elif opt in ("-l", "log"):
+            log = True
+        elif opt in ("-p", "system-wide-proxy"):
+            systemWideProxy = True
+        elif opt in ("-z", "transparent"): 
+            transparent = True
+        else:
+            assert False, "Unknown option"
+
+    if toruser == None:
+        toruid = fetchTorUID()
+    
+    if start:
+        saveState()
+        clearRules()
+
+        if proxy:
+            systemProxy(proxyConf, "load")
+
+        try:
+            loadTorRules(toruid)
+            print("Loading tor rules")
+        except:
+            print("Unable to load the Tor specific firewall rules. You are unsafe.")
+            return 1
+
+        print("Tor rules loaded.")
+        return 0
+
+    if stop:
+        if proxy:
+            systemProxy(proxyConf, "unload")
+        clearRules()
+        try:
+            restoreState()
+        except:
+            print("Unable to load the previous firewall state.")
+            return 1
+
+        print("Previous firewall state restored. TorWall is now deactivated.")
+        return 0
+
+    help()
+    return 0
+
+if __name__ == '__main__':
+
+    main()


Property changes on: torwall/trunk/src/torwall.py
___________________________________________________________________
Name: svn:executable
   + *