Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # For use as a module
- # import firewallauth
- # firewallauth.login("username","password") #for login
- # firewallauth.logout() # for logout
- import getpass
- import httplib
- import urllib
- import urlparse
- import re
- from optparse import OptionParser
- import sys
- import logging
- import time
- import tempfile
- import atexit
- import os
- filename = "firewallauthurl.tmp"
- keepaliveURL = ""
- def InitLogger(options):
- logger = logging.getLogger("FirewallLogger")
- logger.setLevel(logging.DEBUG)
- handler = logging.StreamHandler()
- if options.verbose:
- handler.setLevel(logging.DEBUG)
- else:
- handler.setLevel(logging.INFO)
- if options.quiet:
- handler.setLevel(logging.ERROR)
- formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
- handler.setFormatter(formatter)
- logger.addHandler(handler)
- def FirewallKeepAlive(url):
- while 1:
- logger = logging.getLogger("FirewallLogger")
- logger.info("Sending request to keep alive")
- # Connect to the firewall
- try:
- conn = httplib.HTTPSConnection(url.netloc)
- conn.request("GET", url.path + "?" + url.query)
- response = conn.getresponse()
- logger.debug(str(response.status))
- logger.debug(response.read())
- if response.status == 303 :
- logger.debug("Network disturbance - lets do it again")
- break
- conn.close()
- except:
- break
- # Set a timer
- time.sleep(200);
- def logout():
- logger = logging.getLogger("FirewallLogger")
- logger.info("Logging out")
- try:
- file = open(os.path.join(tempfile.gettempdir(),filename),'r')
- keepaliveURL = file.readline()
- file.close()
- except:
- pass
- if keepaliveURL != "" :
- url = urlparse.urlparse(keepaliveURL)
- # logout to the firewall
- conn = httplib.HTTPSConnection(url.netloc)
- conn.request("GET", url.path.replace("keepalive","logout") + "?" + url.query)
- response = conn.getresponse()
- logger.debug(str(response.status))
- logger.debug(response.read())
- conn.close()
- """
- This checks whether we're logged in already
- """
- def IsLoggedIn():
- # Connect to Google, see if we can connect or not. We use the IP directly here
- # so that this runs on computers even if they don't have DNS configured.
- conn = httplib.HTTPConnection("74.125.67.100:80")
- # if network is down, this will
- conn.request("GET", "/")
- response = conn.getresponse()
- conn.close()
- # 303 leads to the auth page, which means we aren't logged in
- return not (response.status == 303)
- def FirewallAuth(username, password):
- logger = logging.getLogger("FirewallLogger")
- # If we're logged in, keep retrying until we've logged out
- while IsLoggedIn():
- logger.info("It seems like you're already logged in. Trying again in 60 seconds...")
- time.sleep(60)
- # At this point we aren't logged in
- conn = httplib.HTTPConnection("74.125.67.100:80")
- conn.request("GET", "/")
- response = conn.getresponse()
- authLocation = response.getheader("Location")
- conn.close()
- logger.info("The auth location is: " + authLocation)
- # Make a connection to the auth location
- parsedAuthLocation = urlparse.urlparse(authLocation)
- authConn = httplib.HTTPSConnection(parsedAuthLocation.netloc)
- authConn.request("GET", parsedAuthLocation.path + "?" + parsedAuthLocation.query)
- authResponse = authConn.getresponse()
- data = authResponse.read()
- authConn.close()
- # Look for the right magic value in the data
- match = re.search(r"VALUE=\"([0-9a-f]+)\"", data)
- magicString = match.group(1)
- logger.debug("The magic string is: " + magicString)
- # Now construct a POST request
- params = urllib.urlencode({'username': username, 'password': password,
- 'magic': magicString, '4Tredir': '/'})
- headers = {"Content-Type": "application/x-www-form-urlencoded",
- "Accept": "text/plain"}
- postConn = httplib.HTTPSConnection(parsedAuthLocation.netloc)
- postConn.request("POST", "/", params, headers)
- # Get the response
- postResponse = postConn.getresponse()
- postData = postResponse.read()
- postConn.close()
- # Look for the keepalive URL
- keepaliveMatch = re.search(r"location.href=\"(.+?)\"", postData)
- if keepaliveMatch is None:
- # Whoops, unsuccessful -- probably the username and password didn't match
- logger.error("Authentication unsuccessful, check your username and password")
- return 3
- keepaliveURL = keepaliveMatch.group(1)
- file = open(os.path.join(tempfile.gettempdir(),filename),'w')
- file.write(keepaliveURL)
- file.close()
- logger.info("The keep alive URL is: " + keepaliveURL)
- logger.debug(postData)
- FirewallKeepAlive(urlparse.urlparse(keepaliveURL))
- return FirewallAuth(username, password)
- """
- Get the username and password either from command line args or interactively
- """
- def GetUsernameAndPassword(args):
- username = None
- if len(args) == 0:
- # Get the username from the input
- print "Username: ",
- username = sys.stdin.readline()[:-1]
- else:
- # First member of args
- username = args[0]
- password = None
- if len(args) <= 1:
- # Read the password without echoing it
- password = getpass.getpass()
- else:
- password = args[1]
- return (username, password)
- """
- Main function
- """
- def main(argv = None):
- global keepaliveURL
- try:
- file = open(os.path.join(tempfile.gettempdir(),filename),'r')
- keepaliveURL = file.readline()
- file.close()
- except:
- pass
- if argv is None:
- argv = sys.argv[1:]
- # First generate help syntax
- usage = "Usage: %prog [options] [username [password]]"
- parser = OptionParser(usage = usage)
- parser.add_option("-v", "--verbose", action = "store_true", dest = "verbose",
- help = "Print lots of debugging information")
- parser.add_option("-q", "--quiet", action = "store_true", dest = "quiet",
- help = "No INFO to the screen")
- # Parse arguments
- (options, args) = parser.parse_args(argv)
- if len(args) > 2:
- parser.error("too many arguments")
- return 1
- InitLogger(options)
- if keepaliveURL != "":
- logger = logging.getLogger("FirewallLogger")
- logger.debug("Trying the URL in the tmp file")
- logger.debug("The keep alive URL is: " + keepaliveURL)
- FirewallKeepAlive(urlparse.urlparse(keepaliveURL))
- # Try authenticating!
- (username, password) = GetUsernameAndPassword(args)
- while True:
- try:
- return FirewallAuth(username, password)
- except:
- logger.info("looks like network is down! Will retry after 60 seconds")
- time.sleep(60)
- pass
- def login(username = "" ,password = ""):
- if username == "" or password == "" :
- print "Usage login(username,password)"
- return
- main(["--quiet",username,password])
- return
- if __name__ == "__main__":
- atexit.register(logout)
- sys.exit(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement