'''
baseBruteforcePlugin.py

Copyright 2006 Andres Riancho

This file is part of w3af, w3af.sourceforge.net .

w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.

w3af is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with w3af; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

'''


from core.controllers.basePlugin.baseAuditPlugin import baseAuditPlugin
from core.controllers.bruteforce.bruteforcer import bruteforcer
from core.controllers.w3afException import w3afException
import core.controllers.outputManager as om
from core.data.request.frFactory import createFuzzableRequests
import core.data.kb.knowledgeBase as kb

import os.path


class baseBruteforcePlugin(baseAuditPlugin):
	'''
	This plugin is a superclass for plugins that want to bruteforce any type of login.
	@author: Andres Riancho ( andres.riancho@gmail.com )
	'''

	def __init__(self):
		baseAuditPlugin.__init__(self)
		self._alreadyTested = []
		
		# Config params
		self._usersFile = 'core'+os.path.sep+'controllers'+os.path.sep+'bruteforce'+os.path.sep+'users.txt'
		self._passwdFile = 'core'+os.path.sep+'controllers'+os.path.sep+'bruteforce'+os.path.sep+'passwords.txt'
		self._useMailUsers = True
		self._useSvnUsers = True
		self._stopOnFirst = True
		self._passEqUser = True
		self._useMails = True
		self._useProfiling = True
		self._profilingNumber = 50
		
		# Internal vars
		self._found = False
		self._alreadyReported = []
		
		self._bruteforcer = bruteforcer()

	def _initBruteforcer( self, url ):
		self._bruteforcer.setURL( url )
		self._bruteforcer.setUseMailUsers( self._useMailUsers )
		self._bruteforcer.setUseMails( self._useMails )
		self._bruteforcer.setUseProfiling( self._useProfiling )
		self._bruteforcer.setProfilingNumber( self._profilingNumber )
		self._bruteforcer.setUseSvnUsers( self._profilingNumber )
		self._bruteforcer.init()
	
	def _fuzzRequests(self, freq ):
		'''
		This method is the entry point of the plugin.
		
		THIS METHOD MUST BE IMPLEMENTED BY EVERY BRUTEFORCEPLUGIN!
		
		@param freq: A fuzzableRequest
		'''
		raise w3afException('Bruteforce plugins MUST override method _fuzzRequests.')
	
	def bruteforce( self, fuzzableRequest ):
		self.audit( fuzzableRequest )
		
		res = []
		for v in kb.kb.getData( self.getName(), 'auth' ):
			if v.getURL() not in self._alreadyReported:
				self._alreadyReported.append( v.getURL() )
				res.extend( createFuzzableRequests(v['response']) )
		return res
	
	def _bruteforce( self, url, combinations ):
		'''
		@parameter url: A string representation of an URL
		@parameter combinations: A list of tuples with (user,pass)
		'''
		targs = (url,combinations)
		self._tm.startFunction( target=self._bruteWorker, args=targs , ownerObj=self )
	
	def end( self ):
		self._tm.join( self )
			
	def _bruteWorker( self, url, combinations ):
		'''
		This is the method that sends the request to the remote server.
		
		@parameter url: A string representation of an URL
		@parameter combinations: A list of tuples with (user,pass)
		'''
		raise w3afException('Bruteforce plugins MUST override method _bruteWorker.')			

	def getOptionsXML(self):
		'''
		This method returns a XML containing the Options that the plugin has.
		Using this XML the framework will build a window, a menu, or some other input method to retrieve
		the info from the user. The XML has to validate against the xml schema file located at :
		w3af/core/ui/userInterface.dtd
		
		@return: XML with the plugin options.
		'''	
		return	'<?xml version="1.0" encoding="ISO-8859-1"?>\
		<OptionList>\
			<Option name="usersFile">\
				<default>'+str(self._usersFile)+'</default>\
				<desc>Users file to use in bruteforcing</desc>\
				<type>string</type>\
			</Option>\
			<Option name="passwdFile">\
				<default>'+str(self._passwdFile)+'</default>\
				<desc>Passwords file to use in bruteforcing</desc>\
				<type>string</type>\
			</Option>\
			<Option name="useMailUsers">\
				<default>'+str(self._useMailUsers)+'</default>\
				<desc>This indicates if we will use usernames from emails collected by w3af plugins in bruteforce.</desc>\
				<type>boolean</type>\
			</Option>\
			<Option name="useSvnUsers">\
				<default>'+str(self._useSvnUsers)+'</default>\
				<desc>This indicates if we will use usernames from SVN headers collected by w3af plugins in bruteforce.</desc>\
				<type>boolean</type>\
			</Option>\
			<Option name="stopOnFirst">\
				<default>'+str(self._stopOnFirst)+'</default>\
				<desc>This indicates if the bruteforce should stop after finding the first correct user and password.</desc>\
				<type>boolean</type>\
			</Option>\
			<Option name="passEqUser">\
				<default>'+str(self._passEqUser)+'</default>\
				<desc>This indicates if the bruteforce should try password equal user in logins.</desc>\
				<type>boolean</type>\
			</Option>\
			<Option name="useMails">\
				<default>'+str(self._useMails)+'</default>\
				<desc>This indicates if the bruteforcer should use usernames collected by w3af plugins.</desc>\
				<type>boolean</type>\
			</Option>\
			<Option name="useProfiling">\
				<default>'+str(self._useProfiling)+'</default>\
				<desc>This indicates if the bruteforce should use password profiling to collect new passwords.</desc>\
				<type>boolean</type>\
			</Option>\
			<Option name="profilingNumber">\
				<default>'+str(self._profilingNumber)+'</default>\
				<desc>This indicates how many passwords from profiling will be used.</desc>\
				<type>integer</type>\
			</Option>\
		</OptionList>\
		'

	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 getOptionsXML().
		
		@parameter optionsMap: A dictionary with the options for the plugin.
		@return: No value is returned.
		'''	
		self._usersFile = optionsMap['usersFile']
		self._stopOnFirst = optionsMap['stopOnFirst']
		self._passwdFile = optionsMap['passwdFile']
		self._passEqUser = optionsMap['passEqUser']
		self._useMailUsers = optionsMap['useMailUsers']
		self._useSvnUsers = optionsMap['useSvnUsers']
		self._useMails = optionsMap['useMails']
		self._useProfiling = optionsMap['useProfiling']
		self._profilingNumber = optionsMap['profilingNumber']
		

	def getPluginDeps( self ):
		'''
		@return: A list with the names of the plugins that should be runned before the
		current one.
		'''
		return ['grep.passwordProfiling','grep.getMails']

	def getLongDesc( self ):
		'''
		@return: A DETAILED description of the plugin functions and features.
		'''
		return '''
		This plugin bruteforces form authentication logins.
		
		Nine configurable parameters exist:
			- usersFile
			- stopOnFirst
			- passwdFile
			- passEqUser
			- useMailUsers
			- useSvnUsers
			- useMails
			- useProfiling
			- profilingNumber
		
		This plugin will take users from the file pointed by "usersFile", mail users found on the site ( if "useMailUsers" is
		set to True ), mails found on the site ( if "useMails" is set to True ), and svn users found on the site ( if "useSvnUsers"
		is set to True ).
		
		This plugin will take passwords from the file pointed by "passwdFile" and the result of the password profiling plugin 
		( if "useProfiling" is set to True). The profilingNumber sets the number of results from the password profiling plugin
		to use in the password field.
		
		The "stopOnFirst" parameter indicates if the bruteforce will stop when finding the first valid credentials or not.
		'''
