Abusing Linux Inotify For Persistence
INotify Background
Inotify is a Linux utility that allows users to monitor changes that are made to the filesystem and reports on such changes. Inotify comes with an API that can be used programmatically as well as command-line tools that can be used.
If you wanted to monitor a specific directory or file for changes, you would run inotifywait <directory/file>
. Then when an event occurs to the specified directory/file, it’d report on it:
You can also pass an event to the -e
flag to monitor for specific filesystem events. A list of valid events to monitor for can be found here under Events.
You can even use Inotify in monitor mode which will continuously monitor a specified directory/file for events even after a single event occurs. This means you’d be able to catch all events that occur until you manually stop it:
inotifywait -e create -m /tmp
:
Abusing INotify for Persistence
So Inotify seems to be extremely useful for monitoring filesystem activities and reporting on what events occur which is good from a defensive perspective since we can see what files/directories an attacker may be touching. But what about from an offensive perspective? Well, as previously mentioned, Inotify has an API that can be used programmatically that can be used to elevate its usefulness to an adversary.
For example, we can use the Python library or native C API in order to monitor a specific directory/file of interest, wait for a target to create/modify a file, then read the contents of a file & perform some action, such as data exfiltration. Some examples of files of interest may be private keys, databases, configuration files, sensitive documents. This can be abused for data exfiltration & as a means of persistence.
To help facilitate this, I’ve created a quick Python tool which is available here. All it currently does is place a watch to the user-specified directory/file via the -d/--directory
& then will monitor for file creation events & output the contents of newly created files within the monitored directory/file. This could be modified to perform actual data exfiltration to a C2 server as well.
Mitigations
You could restrict the limits within inotify
by setting each limit to 0 within each file located at /proc/sys/fs/inotify/*
though, I’ve noticed that many processes utilize inotify
and this may negatively affect those normal system processes.
Detection
Now that I’ve talked about how Inotify could be used as a means of persistence, let’s discuss how to detect this. One way to detect the usage of the Python script I linked earlier is a simple lsof
while grepping for inotify
& python
:
lsof | grep 'inotify' | grep 'python'
:
python3 28528 username 3r a_inode 0,16 0 2080 inotify
Or you can run: lsof | grep 'a_inode' | grep inotify
:
You can also search through /proc
& find any processes that are using inotify