Advertisement
Guest User

cookset.py

a guest
Jan 2nd, 2012
559
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.68 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4.       autocookie.py
  5.      
  6.       Copyright 2011 sh4r3m4n <shareman1204@gmail.com>
  7.      
  8.       This program is free software; you can redistribute it and/or modify
  9.       it under the terms of the GNU General Public License as published by
  10.       the Free Software Foundation; either version 2 of the License, or
  11.       (at your option) any later version.
  12.      
  13.       This program is distributed in the hope that it will be useful,
  14.       but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16.       GNU General Public License for more details.
  17.      
  18.       You should have received a copy of the GNU General Public License
  19.       along with this program; if not, write to the Free Software
  20.       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  21.       MA 02110-1301, USA.
  22. """
  23.  
  24. #Constant definition
  25. DEFAULT_FILE='httprequest.txt'
  26. TMP_FILE = '/tmp/tmphosts'
  27. HOSTS = '/etc/hosts'
  28. MESSAGE='<h1>Cookies established correctly</h1>'
  29.  
  30. def get_args():
  31.     """ This function load the arguments and options and returns a
  32.     dictionary with them or None if there is an error on them. If there
  33.     is an error, it displays a help screen
  34.     """
  35.     import sys
  36.     import getopt
  37.  
  38.     def use():
  39.         """ Function that prints the use of the program and exits"""
  40.         print """Use: python """+ sys.argv[0] + \
  41. """ <options> [file]
  42.     Options:
  43.         -d <domain> or --domain=domain
  44.             Set the domain where cookies are set. The default value is
  45.             the value of the Host header of the HTTP request
  46.         -w or --windows
  47.             Make some changes that makes the program compatible with
  48.             Windows. It must be indicated at first option
  49.         -r or --restore
  50.             If the program exits incorrectly, you could l
  51.         -p <port> or --port=port
  52.             The port to listen. It must be the port where the HTTP
  53.             server of the domain is. The default value is 80
  54.         --tmp-file=file
  55.             The name of the temp file of hosts. You'll have to set this
  56.             option in the restore mode if you have set it previously
  57.         -h or --help
  58.             Shows this screen
  59.     file:
  60.         The name of the file where the HTTP request is stored. Default
  61.         is httprequest.txt
  62. """
  63.         exit(-1)
  64.     try:
  65.         opts, args=getopt.getopt(sys.argv[1:],'hwrd:p:', \
  66.                 ['help',
  67.                  'restore',
  68.                  'domain=',
  69.                  'port=',
  70.                  'tmp-file=',
  71.                  'windows'])
  72.     except getopt.GetoptError:
  73.         use()
  74.    
  75.     showhelp = False
  76.     domain = None
  77.     port = 80
  78.     restore = False
  79.     if len(args)==0: args.append(DEFAULT_FILE)
  80.  
  81.     for opt, val in opts:
  82.         if opt in ('-h','--help'):
  83.             showhelp = True
  84.         elif opt in ('-d', '--domain'):
  85.             domain = val
  86.         elif opt in ('-p', '--port'):
  87.             try:
  88.                 port = int(val)
  89.             except ValueError:
  90.                 use()
  91.         elif opt=='--tmp-file':
  92.             TMP_FILE = val
  93.         elif opt in ('-r', '--restore'):
  94.             restore=True
  95.         elif opt in ('-w', '--windows'):
  96.             globals()['TMP_FILE'] = 'tmphosts'
  97.             globals()['HOSTS'] = r'C:\Windows\system32\drivers\etc\hosts'
  98.  
  99.     if showhelp or len(args)>=2 : use()
  100.  
  101.     return {'domain':domain,
  102.             'port':port,
  103.             'file':args[0],
  104.             'restore':restore}
  105.  
  106.  
  107. def main():
  108.     """ Main function """
  109.     args = get_args()
  110.  
  111.     if args['restore']:
  112.         try:
  113.             open(HOSTS, 'w').write(open(TMP_FILE).read())
  114.             print 'Hosts file restored correctly'
  115.         except IOError as e:
  116.             print 'An error has ocurred:', e
  117.             exit(-1)
  118.         exit()
  119.  
  120.  
  121.     import re
  122.  
  123.     try:
  124.         file_content = open(args['file']).read()
  125.     except IOError:
  126.         print 'Error opening the file. Quiting'
  127.         exit(-1)
  128.  
  129.     lines = re.split('\r?\n', file_content)
  130.  
  131.     #Quit the first line if it is the start of an HTTP Request
  132.     if(re.match(r'^[^ ]+ [^ ]+ HTTP/[0-9]\.[0-9]$',lines[0])): del(lines[0])
  133.  
  134.     #Set the HTTP headers in a variable
  135.     headers = {}
  136.     for line in lines:
  137.         if line=='': break #A blank line means the end of the headers
  138.         split = re.split(': ?', line, 1)
  139.         try:
  140.             headers[split[0]] = split[1]
  141.         except IndexError:
  142.             print 'The request is not valid'
  143.             exit(-1)
  144.  
  145.     if headers.has_key('Cookie') == False:
  146.         print 'There is no Cookie header in the request'
  147.         exit(-1)
  148.  
  149.     cookie = headers['Cookie']
  150.     if args['domain'] is None:
  151.         args['domain'] = headers['Host']
  152.  
  153.     #Make a temp copy of the hosts file
  154.     try:
  155.         tmp = open(TMP_FILE, 'w')
  156.         hosts_content = open(HOSTS).read()
  157.         tmp.write(hosts_content)
  158.         tmp.close()
  159.         hosts = open(HOSTS, 'w')
  160.     except IOError as e:
  161.         print 'Error reading or writing the files. Quiting',e
  162.         exit(-1)
  163.  
  164.     #Add an entry in the hosts file redirecting the domain to our computer
  165.     hosts.write(hosts_content)
  166.     hosts.write('127.0.0.1 '+ args['domain'] + '\n')
  167.     hosts.close()
  168.  
  169.     #Create a temp web server to set the cookies
  170.     try:
  171.         print 'Now you can enter the domain with your web browser'
  172.         from socket import socket, error as sockerr
  173.         sock=socket()
  174.         sock.bind(('', args['port']))
  175.         sock.listen(1)
  176.         a, b = sock.accept()
  177.         data=a.recv(1024)
  178.         try:
  179.             protocol = data.split(' ', 3)[2][:8] #HTTP/x.x
  180.         except IndexError:
  181.             print 'Incorrect request of client. Quiting'
  182.             exit(-1)
  183.         headers=[ \
  184.             'Content-Length: ' + str(len(MESSAGE)),
  185.             'Content-Type: text/html',
  186.             'Set-Cookie: ' + cookie]
  187.         a.send(
  188.             protocol+' 200 OK\r\n' +
  189.             '\r\n'.join(headers) +
  190.             '\r\n\r\n' +
  191.             MESSAGE)
  192.     except sockerr as e:
  193.         print 'Error in the web server:', e
  194.         exit(-1)
  195.     finally:
  196.         try:
  197.             a.close()
  198.             sock.close()
  199.         except:
  200.             pass
  201.    
  202.     #Try to restore the hosts file
  203.     try:
  204.         hosts=open(HOSTS, 'w')
  205.         hosts.write(hosts_content)
  206.         hosts.close()
  207.     except IOError:
  208.         print 'Error restoring hosts file. You\'ll have to restore it with -r '
  209.     else:
  210.         print 'Hosts file restored correctly. Quitting'
  211.  
  212.     return 0
  213.  
  214. if __name__ == '__main__':
  215.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement