module Msf

require 'msf/core/exploit/tcp'
require 'rex/mime'

###
#
# This module exposes methods that may be useful to exploits that deal that
# send email messages via SMTP
#
###

module Exploit::Remote::SMTPDeliver
	
	include Exploit::Remote::Tcp
	
	#
	# Creates an instance of an exploit that delivers messages via SMTP
	#
	def initialize(info = {})
		super

		# Register our options, overriding the RHOST/RPORT from TCP
		register_options(
			[
				Opt::RPORT(25),
				OptString.new('MAILFROM', [ true, 'The FROM address of the e-mail', 'random@example.com']),
				OptString.new('MAILTO', [ true, 'The TO address of the e-mail']),
				OptString.new('VERBOSE', [ false, 'Display verbose information']),
			], Msf::Exploit::Remote::SMTPDeliver)
	end


	# This method connects to the server and sends a message
	def send_message(data)

        if datastore['VERBOSE']  
            print_status("Connecting to SMTP server #{rhost}:#{rport}...")
        end
		msock = connect(false)
		res = msock.get_once
		
        if datastore['VERBOSE']  
            print_status("SMTP: #{res.strip}")
        end

		res = raw_send_recv("EHLO #{Rex::Text.rand_text_alpha(rand(32)+1)}\r\n", msock)
        if datastore['VERBOSE']  
            print_status("SMTP: #{res.strip}")		
        end
		
		res = raw_send_recv("MAIL FROM: #{datastore['MAILFROM']}\r\n", msock)
        if datastore['VERBOSE']
            print_status("SMTP: #{res.strip}")				
        end

		res = raw_send_recv("RCPT TO: #{datastore['MAILTO']}\r\n", msock)
        if datastore['VERBOSE']
            print_status("SMTP: #{res.strip}")		
        end

        if datastore['VERBOSE']
            print_status("Sending the message (#{data.length} bytes)...")
        end
		res = raw_send_recv("DATA\r\n", msock)
        if datastore['VERBOSE']
            print_status("SMTP: #{res.strip}")
        end
	
		res = raw_send_recv("#{data}\r\n.\r\n", msock)
        if datastore['VERBOSE']
            print_status("SMTP: #{res.strip}")
        end
		
        if datastore['VERBOSE']
            print_status("Closing the connection...")
        end
		res = raw_send_recv("QUIT\r\n", msock)
        if datastore['VERBOSE']
            print_status("SMTP: #{res.strip}")
        end
		
		msock.close		
	end

	def raw_send_recv(cmd, nsock = self.sock)
		nsock.put(cmd)
		nsock.get_once
	end


end

end
