Advertisement
Guest User

Untitled

a guest
May 3rd, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.89 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. # For use as a module
  4. # import firewallauth
  5. # firewallauth.login("username","password") #for login
  6. # firewallauth.logout() # for logout
  7.  
  8. import getpass
  9. import httplib
  10. import urllib
  11. import urlparse
  12. import re
  13. from optparse import OptionParser
  14. import sys
  15. import logging
  16. import time
  17. import tempfile
  18. import atexit
  19. import os
  20. filename = "firewallauthurl.tmp"
  21. keepaliveURL = ""
  22.  
  23.  
  24. def InitLogger(options):
  25.   logger = logging.getLogger("FirewallLogger")
  26.   logger.setLevel(logging.DEBUG)
  27.   handler = logging.StreamHandler()
  28.   if options.verbose:
  29.     handler.setLevel(logging.DEBUG)
  30.   else:
  31.     handler.setLevel(logging.INFO)
  32.   if options.quiet:
  33.     handler.setLevel(logging.ERROR)
  34.  
  35.   formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
  36.   handler.setFormatter(formatter)
  37.   logger.addHandler(handler)
  38.  
  39. def FirewallKeepAlive(url):
  40.   while 1:
  41.     logger = logging.getLogger("FirewallLogger")
  42.     logger.info("Sending request to keep alive")
  43.     # Connect to the firewall
  44.     try:
  45.         conn = httplib.HTTPSConnection(url.netloc)
  46.         conn.request("GET", url.path + "?" + url.query)
  47.         response = conn.getresponse()
  48.         logger.debug(str(response.status))
  49.         logger.debug(response.read())
  50.         if response.status == 303 :
  51.             logger.debug("Network disturbance - lets do it again")
  52.             break
  53.         conn.close()
  54.     except:
  55.         break
  56.  
  57.     # Set a timer
  58.     time.sleep(200);
  59.  
  60. def logout():
  61.  logger = logging.getLogger("FirewallLogger")
  62.  logger.info("Logging out")
  63.  try:
  64.       file = open(os.path.join(tempfile.gettempdir(),filename),'r')
  65.       keepaliveURL = file.readline()
  66.       file.close()
  67.  except:
  68.       pass
  69.  
  70.  if keepaliveURL  != "" :
  71.     url = urlparse.urlparse(keepaliveURL)
  72.     # logout to the firewall
  73.     conn = httplib.HTTPSConnection(url.netloc)
  74.     conn.request("GET", url.path.replace("keepalive","logout") + "?" + url.query)
  75.     response = conn.getresponse()
  76.  
  77.     logger.debug(str(response.status))
  78.     logger.debug(response.read())
  79.     conn.close()
  80.  
  81. """
  82. This checks whether we're logged in already
  83. """
  84. def IsLoggedIn():
  85.   # Connect to Google, see if we can connect or not. We use the IP directly here
  86.   # so that this runs on computers even if they don't have DNS configured.
  87.   conn = httplib.HTTPConnection("74.125.67.100:80")
  88.   # if network is down, this will
  89.   conn.request("GET", "/")
  90.   response = conn.getresponse()
  91.   conn.close()
  92.   # 303 leads to the auth page, which means we aren't logged in
  93.   return not (response.status == 303)
  94.  
  95. def FirewallAuth(username, password):
  96.   logger = logging.getLogger("FirewallLogger")
  97.  
  98.   # If we're logged in, keep retrying until we've logged out
  99.   while IsLoggedIn():
  100.     logger.info("It seems like you're already logged in. Trying again in 60 seconds...")
  101.     time.sleep(60)
  102.  
  103.   # At this point we aren't logged in
  104.   conn = httplib.HTTPConnection("74.125.67.100:80")
  105.   conn.request("GET", "/")
  106.   response = conn.getresponse()
  107.   authLocation = response.getheader("Location")
  108.   conn.close()
  109.   logger.info("The auth location is: " + authLocation)
  110.  
  111.   # Make a connection to the auth location
  112.   parsedAuthLocation = urlparse.urlparse(authLocation)
  113.   authConn = httplib.HTTPSConnection(parsedAuthLocation.netloc)
  114.   authConn.request("GET", parsedAuthLocation.path + "?" + parsedAuthLocation.query)
  115.   authResponse = authConn.getresponse()
  116.   data = authResponse.read()
  117.   authConn.close()
  118.  
  119.   # Look for the right magic value in the data
  120.   match = re.search(r"VALUE=\"([0-9a-f]+)\"", data)
  121.   magicString = match.group(1)
  122.   logger.debug("The magic string is: " + magicString)
  123.  
  124.   # Now construct a POST request
  125.   params = urllib.urlencode({'username': username, 'password': password,
  126.                              'magic': magicString, '4Tredir': '/'})
  127.   headers = {"Content-Type": "application/x-www-form-urlencoded",
  128.              "Accept": "text/plain"}
  129.  
  130.   postConn = httplib.HTTPSConnection(parsedAuthLocation.netloc)
  131.   postConn.request("POST", "/", params, headers)
  132.  
  133.   # Get the response
  134.   postResponse = postConn.getresponse()
  135.  
  136.   postData = postResponse.read()
  137.   postConn.close()
  138.  
  139.   # Look for the keepalive URL
  140.   keepaliveMatch = re.search(r"location.href=\"(.+?)\"", postData)
  141.   if keepaliveMatch is None:
  142.     # Whoops, unsuccessful -- probably the username and password didn't match
  143.     logger.error("Authentication unsuccessful, check your username and password")
  144.     return 3
  145.  
  146.   keepaliveURL = keepaliveMatch.group(1)
  147.   file = open(os.path.join(tempfile.gettempdir(),filename),'w')
  148.   file.write(keepaliveURL)
  149.   file.close()
  150.   logger.info("The keep alive URL is: " + keepaliveURL)
  151.   logger.debug(postData)
  152.   FirewallKeepAlive(urlparse.urlparse(keepaliveURL))
  153.   return FirewallAuth(username, password)
  154.  
  155.  
  156. """
  157. Get the username and password either from command line args or interactively
  158. """
  159. def GetUsernameAndPassword(args):
  160.   username = None
  161.   if len(args) == 0:
  162.     # Get the username from the input
  163.     print "Username: ",
  164.     username = sys.stdin.readline()[:-1]
  165.   else:
  166.     # First member of args
  167.     username = args[0]
  168.  
  169.   password = None
  170.   if len(args) <= 1:
  171.     # Read the password without echoing it
  172.     password = getpass.getpass()
  173.   else:
  174.     password = args[1]
  175.  
  176.   return (username, password)
  177.  
  178. """
  179. Main function
  180. """
  181. def main(argv = None):
  182.   global keepaliveURL
  183.   try:
  184.       file = open(os.path.join(tempfile.gettempdir(),filename),'r')
  185.       keepaliveURL = file.readline()
  186.       file.close()
  187.   except:
  188.       pass
  189.   if argv is None:
  190.     argv = sys.argv[1:]
  191.  
  192.   # First generate help syntax
  193.   usage = "Usage: %prog [options] [username [password]]"
  194.   parser = OptionParser(usage = usage)
  195.   parser.add_option("-v", "--verbose", action = "store_true", dest = "verbose",
  196.                     help = "Print lots of debugging information")
  197.  
  198.   parser.add_option("-q", "--quiet", action = "store_true", dest = "quiet",
  199.                     help = "No INFO to the screen")
  200.   # Parse arguments
  201.   (options, args) = parser.parse_args(argv)
  202.  
  203.   if len(args) > 2:
  204.     parser.error("too many arguments")
  205.     return 1
  206.  
  207.   InitLogger(options)
  208.   if keepaliveURL != "":
  209.     logger = logging.getLogger("FirewallLogger")
  210.  
  211.     logger.debug("Trying the URL in the tmp file")
  212.     logger.debug("The keep alive URL is: " + keepaliveURL)
  213.     FirewallKeepAlive(urlparse.urlparse(keepaliveURL))
  214.   # Try authenticating!
  215.   (username, password) = GetUsernameAndPassword(args)
  216.   while True:
  217.     try:
  218.       return FirewallAuth(username, password)
  219.     except:
  220.       logger.info("looks like network is down! Will retry after 60 seconds")
  221.       time.sleep(60)
  222.       pass
  223.  
  224. def login(username = "" ,password = ""):
  225.     if username == "" or password == "" :
  226.         print "Usage login(username,password)"
  227.         return
  228.     main(["--quiet",username,password])
  229.     return
  230.  
  231. if __name__ == "__main__":
  232.   atexit.register(logout)
  233.   sys.exit(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement