'''
globalRedirect.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.data.fuzzer.fuzzer import *
import core.data.kb.vuln as vuln
import core.data.kb.knowledgeBase as kb
import core.controllers.outputManager as om

import core.data.parsers.urlParser as urlParser
import core.data.parsers.dpCache as dpCache

from core.controllers.daemons.webserver import webserver
from core.controllers.w3afException import w3afException
from core.controllers.basePlugin.baseAuditPlugin import baseAuditPlugin

import re

class globalRedirect(baseAuditPlugin):
	'''
	This plugin tests for scripts that redirect the browser to any site.
	@author: Andres Riancho ( andres.riancho@gmail.com )
	'''

	def __init__(self):
		baseAuditPlugin.__init__(self)
		self._testSite = 'http://w3af.sourceforge.net/'
		self._scriptre = re.compile('< *script.*?>(.*)< */ *script *>',re.IGNORECASE | re.DOTALL )

	def _fuzzRequests(self, freq ):
		'''
		Tests an URL for global redirect vulnerabilities.
		
		@param freq: A fuzzableRequest
		'''
		om.out.debug( 'golbalRedirect plugin is testing: ' + freq.getURL() )
		
		globalRedirects = [self._testSite,]
		mutants = createMutants( freq , globalRedirects )
			
		for mutant in mutants:
			if self._hasNoBug( 'globalRedirect' , 'globalRedirect' , mutant.getURL() , mutant.getVar() ):
				targs = (mutant,)
				self._tm.startFunction( target=self._sendMutant, args=targs, ownerObj=self )
		
							
	def _analyzeResult( self, mutant, response ):
		'''
		Analyze results of the _sendMutant method.
		'''
		if self._findRedirect( response ):
			v = vuln.vuln( mutant )
			v.setId( response.id )
			v.setDesc( 'Global redirect was found at: ' + response.getURL() + ' . Using method: ' + v.getMethod() + '. The data sent was: ' + str(mutant.getDc()) )
			kb.kb.append( self, 'globalRedirect', v )
	
	def end(self):
		'''
		This method is called when the plugin wont be used anymore.
		'''
		self._tm.join( self )
		self.printUniq( kb.kb.getData( 'globalRedirect', 'globalRedirect' ), 'VAR' )
		
	def _findRedirect( self, response ):
		'''
		This method checks if the browser was redirected ( using a 302 code ) 
		or is being told to be redirected by javascript or <meta http-equiv="refresh"
		'''
		if response.getRedirURL() == self._testSite:
			# The script sent a 302, and w3af followed the redirection
			# so the URL is now the test site
			return True
		else:
			# Test for http-equiv redirects
			dp = dpCache.dpc.getDocumentParserFor( response.getBody(), response.getURL() )
			for redir in dp.getMetaRedir():
				if redir.count( self._testSite ):
					return True
					
			# Test for javascript redirects
			# These are some redirects I found on google :
			# location.href = '../htmljavascript.htm';
			# window.location = "http://www.google.com/"
			# window.location.href="http://www.example.com/";
			# location.replace('http://www.example.com/');
			res = self._scriptre.search( response.getBody() )
			if res:
				for scriptCode in res.groups():
					splittedCode = scriptCode.split('\n')
					code = []
					for i in splittedCode:
						code.extend( i.split(';') )
						
					for line in code:
						if re.search( '(window\.location|location\.).*' + self._testSite, line ):
							return True
		
		return False
		
	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>\
		</OptionList>\
		'

	def setOptions( self, OptionList ):
		'''
		This method sets all the options that are configured using the user interface 
		generated by the framework using the result of getOptionsXML().
		
		@parameter OptionList: A dictionary with the options for the plugin.
		@return: No value is returned.
		'''	
		pass
		
	def getPluginDeps( self ):
		'''
		@return: A list with the names of the plugins that should be runned before the
		current one.
		'''
		return []
	
	def getLongDesc( self ):
		'''
		@return: A DETAILED description of the plugin functions and features.
		'''
		return '''
		This plugin will find global redirection bugs. This kind of bugs are used for phishing and other identity theft
		attacks. A common example of a global redirection would be a script that takes a "url" parameter and when 
		requesting this page, a HTTP 302 message with the location header to the value of the url parameter is sent in
		the response.
		
		Global redirection bugs can be found in javascript, META tags and 302 / 301 HTTP return codes.
		'''
