Match Containers PIDs With Host PIDs
While adding support for containers in the Python tool I developed, called MI-X, which checks exploitability for “Famous Vulnerabilities”, I encountered a challenge with matching the running processes on the host to those running on a container.
I did not find any solution on the internet, so I needed to solve it by myself.
I knew that in order to match the processes, I need to answer two questions:
- Which of the running containers belongs to the running process?
- Which process from the running processes on the container, matches the running process?
In the beginning, I had the answer for the second question.
I used the following command in order to match the process numbers:
cat /proc/<pid>/status | grep -i nspid
Now I know that process 12658, which is inside the container, matches the process 21 in some container, but I don’t know which one.
Initially, I thought about an interesting idea — to compare the maps file of each process in a container with the found PID (21 in this example), and if the maps file is equal, then this is the matched container. However, this solution is correct but ineffective.
After a while, I suddenly noticed the following thing that helped me answer the first question very easily: the “/proc/<container_pid>/root” is the root directory of the environment the processes are running in. Therefore, the “/proc/<container_pid>/root/proc” lists the running processes in the environment it is running in.
An example of a running Python process on the host:
Executing a Python container:
An example of a running Python process on a container:
As you can see, the “/proc” in the container is similar to the “/proc/<container_pid>/root/proc” (except for PID 44 in the container, which is the process executed by the command “ls /proc” on the container).
Now, I can use the solution for the second question I explained above and find the PID of the matched process.
Since I was unable to find a solution on the internet, I opted to create a Python script that matches container and host PIDs. This script, called MATCHO-PIDS (Match Containers Host PIDs), can be helpful if you encounter the same challenge.
The script is available on GitHub: MATCHO-PIDS
An example of an output: