module Msf

###
#
# This module provides methods for sending raw 802.11 frames using the ruby-lorcon extension.
# Please see the ruby-lorcon documentation for more information.
#
###

module Exploit::Lorcon

	#
	# Initializes an instance of an exploit module that accesses a 802.11 network
	#
	
	def initialize(info = {})
		super

		register_options(
			[
				OptString.new('INTERFACE', [true, 'The name of the wireless interface', 'ath0']),
				OptString.new('DRIVER', [true, 'The name of the wireless driver for lorcon', 'madwifi']),
				OptInt.new('CHANNEL', [true, 'The default channel number', 11])
			], Msf::Exploit::Lorcon
		)

		
		begin
			require 'Lorcon'
			@lorcon_loaded = true
		rescue ::Exception => e
			@lorcon_loaded = false
			@lorcon_error  = e
		end
	
	end

	#
	# Opens a handle to the specified wireless device
	#
	def open_wifi
	
		if (not @lorcon_loaded)
			print_status("The Lorcon module is not available: #{@lorcon_error.to_s}")
			raise RuntimeError, "Lorcon not available"
		end
		
		# XXX: Force the interface to be up
		system("ifconfig", datastore['INTERFACE'], "up")
		
		self.wifi = ::Lorcon::Device.new(datastore['INTERFACE'], datastore['DRIVER'], datastore['CHANNEL'])
		
		if (not self.wifi)
			raise RuntimeError, "Could not open the wireless device interface"
		end
	end

	def close_wifi
		return if not self.wifi
	end

	#
	# Converts ethernet addresses to binary
	#
	def eton(addr)
		addr.split(':').map { |c| c.hex.chr }.join
	end
	
	def channel
		self.wifi.channel
	end
	
	def next_channel
		cur = self.wifi.channel
		nxt = (cur > 10) ? 1 : cur + 1
		self.wifi.channel = nxt
	end
	
	attr_accessor :wifi

end

end
