# -*- coding: binary -*-
module Msf


###
#
# This module exposes methods that may be useful to exploits that deal with
# servers that speak the IMAP protocol.
#
###
module Exploit::Remote::Imap

  include Exploit::Remote::Tcp

  #
  # Creates an instance of an IMAP exploit module.
  #
  def initialize(info = {})
    super

    # Register the options that all IMAP exploits may make use of.
    register_options(
      [
        Opt::RHOST,
        Opt::RPORT(143),
        OptString.new('IMAPUSER', [ false, 'The username to authenticate as']),
        OptString.new('IMAPPASS', [ false, 'The password for the specified username'])
      ], Msf::Exploit::Remote::Imap)
  end

  #
  # This method establishes a IMAP connection to host and port specified by
  # the RHOST and RPORT options, respectively.  After connecting, the banner
  # message is read in and stored in the 'banner' attribute.
  #
  def connect(global = true)
    fd = super

    # Wait for a banner to arrive...
    self.banner = fd.get_once(-1, 30)

    # Return the file descriptor to the caller
    fd
  end

  #
  # Connect and login to the remote IMAP server using the credentials
  # that have been supplied in the exploit options.
  #
  def connect_login(global = true)
    ftpsock = connect(global)


    if !(user and pass)
      print_status("No username and password were supplied, unable to login")
      return false
    end

    print_status("Authenticating as #{user} with password #{pass}...")
    res = raw_send_recv("a001 LOGIN #{user} #{pass}\r\n")

    if (res !~ /^a001 OK/)
      print_status("Authentication failed")
      return false
    end

    return true
  end

  #
  # This method transmits an IMAP command and waits for a response.  If one is
  # received, it is returned to the caller.
  #
  def raw_send_recv(cmd, nsock = self.sock)
    nsock.put(cmd)
    nsock.get_once
  end


  ##
  #
  # Wrappers for getters
  #
  ##

  #
  # Returns the user string from the 'IMAPUSER' option.
  #
  def user
    datastore['IMAPUSER']
  end

  #
  # Returns the user string from the 'IMAPPASS' option.
  #
  def pass
    datastore['IMAPPASS']
  end

protected

  #
  # This attribute holds the banner that was read in after a successful call
  # to connect or connect_login.
  #
  attr_accessor :banner

end

end

