Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- """
- autocookie.py
- Copyright 2011 sh4r3m4n <shareman1204@gmail.com>
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
- MA 02110-1301, USA.
- """
- #Constant definition
- DEFAULT_FILE='httprequest.txt'
- TMP_FILE = '/tmp/tmphosts'
- HOSTS = '/etc/hosts'
- MESSAGE='<h1>Cookies established correctly</h1>'
- def get_args():
- """ This function load the arguments and options and returns a
- dictionary with them or None if there is an error on them. If there
- is an error, it displays a help screen
- """
- import sys
- import getopt
- def use():
- """ Function that prints the use of the program and exits"""
- print """Use: python """+ sys.argv[0] + \
- """ <options> [file]
- Options:
- -d <domain> or --domain=domain
- Set the domain where cookies are set. The default value is
- the value of the Host header of the HTTP request
- -w or --windows
- Make some changes that makes the program compatible with
- Windows. It must be indicated at first option
- -r or --restore
- If the program exits incorrectly, you could l
- -p <port> or --port=port
- The port to listen. It must be the port where the HTTP
- server of the domain is. The default value is 80
- --tmp-file=file
- The name of the temp file of hosts. You'll have to set this
- option in the restore mode if you have set it previously
- -h or --help
- Shows this screen
- file:
- The name of the file where the HTTP request is stored. Default
- is httprequest.txt
- """
- exit(-1)
- try:
- opts, args=getopt.getopt(sys.argv[1:],'hwrd:p:', \
- ['help',
- 'restore',
- 'domain=',
- 'port=',
- 'tmp-file=',
- 'windows'])
- except getopt.GetoptError:
- use()
- showhelp = False
- domain = None
- port = 80
- restore = False
- if len(args)==0: args.append(DEFAULT_FILE)
- for opt, val in opts:
- if opt in ('-h','--help'):
- showhelp = True
- elif opt in ('-d', '--domain'):
- domain = val
- elif opt in ('-p', '--port'):
- try:
- port = int(val)
- except ValueError:
- use()
- elif opt=='--tmp-file':
- TMP_FILE = val
- elif opt in ('-r', '--restore'):
- restore=True
- elif opt in ('-w', '--windows'):
- globals()['TMP_FILE'] = 'tmphosts'
- globals()['HOSTS'] = r'C:\Windows\system32\drivers\etc\hosts'
- if showhelp or len(args)>=2 : use()
- return {'domain':domain,
- 'port':port,
- 'file':args[0],
- 'restore':restore}
- def main():
- """ Main function """
- args = get_args()
- if args['restore']:
- try:
- open(HOSTS, 'w').write(open(TMP_FILE).read())
- print 'Hosts file restored correctly'
- except IOError as e:
- print 'An error has ocurred:', e
- exit(-1)
- exit()
- import re
- try:
- file_content = open(args['file']).read()
- except IOError:
- print 'Error opening the file. Quiting'
- exit(-1)
- lines = re.split('\r?\n', file_content)
- #Quit the first line if it is the start of an HTTP Request
- if(re.match(r'^[^ ]+ [^ ]+ HTTP/[0-9]\.[0-9]$',lines[0])): del(lines[0])
- #Set the HTTP headers in a variable
- headers = {}
- for line in lines:
- if line=='': break #A blank line means the end of the headers
- split = re.split(': ?', line, 1)
- try:
- headers[split[0]] = split[1]
- except IndexError:
- print 'The request is not valid'
- exit(-1)
- if headers.has_key('Cookie') == False:
- print 'There is no Cookie header in the request'
- exit(-1)
- cookie = headers['Cookie']
- if args['domain'] is None:
- args['domain'] = headers['Host']
- #Make a temp copy of the hosts file
- try:
- tmp = open(TMP_FILE, 'w')
- hosts_content = open(HOSTS).read()
- tmp.write(hosts_content)
- tmp.close()
- hosts = open(HOSTS, 'w')
- except IOError as e:
- print 'Error reading or writing the files. Quiting',e
- exit(-1)
- #Add an entry in the hosts file redirecting the domain to our computer
- hosts.write(hosts_content)
- hosts.write('127.0.0.1 '+ args['domain'] + '\n')
- hosts.close()
- #Create a temp web server to set the cookies
- try:
- print 'Now you can enter the domain with your web browser'
- from socket import socket, error as sockerr
- sock=socket()
- sock.bind(('', args['port']))
- sock.listen(1)
- a, b = sock.accept()
- data=a.recv(1024)
- try:
- protocol = data.split(' ', 3)[2][:8] #HTTP/x.x
- except IndexError:
- print 'Incorrect request of client. Quiting'
- exit(-1)
- headers=[ \
- 'Content-Length: ' + str(len(MESSAGE)),
- 'Content-Type: text/html',
- 'Set-Cookie: ' + cookie]
- a.send(
- protocol+' 200 OK\r\n' +
- '\r\n'.join(headers) +
- '\r\n\r\n' +
- MESSAGE)
- except sockerr as e:
- print 'Error in the web server:', e
- exit(-1)
- finally:
- try:
- a.close()
- sock.close()
- except:
- pass
- #Try to restore the hosts file
- try:
- hosts=open(HOSTS, 'w')
- hosts.write(hosts_content)
- hosts.close()
- except IOError:
- print 'Error restoring hosts file. You\'ll have to restore it with -r '
- else:
- print 'Hosts file restored correctly. Quitting'
- return 0
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement