Find – How to Search for Files with Immutable Attribute Set

ext3find

For config auditing reasons, I want to be able to search my ext3 filesystem for files which have the immutable attribute set (via chattr +i). I can't find any options for find or similar that do this. At this point, I'm afraid I'll have to write my own script to parse lsattr output for each directory. Is there a standard utility that provides a better way?

Best Answer

It can be partially accomplished by piping the lsattr command through the grep command.

lsattr -R | grep +i

However, I believe when you mention the entire ext3 file system the search might involve /proc , /dev and some other directories which might report some errors that you just want to ignore. You can probably run the command as,

lsattr -R 2>/dev/null | grep -- "-i-"

You might want to make the grep a bit more strict by using grep's PCRE facility to more explicitly match the "-i-".

lsattr -R 2>/dev/null | grep -P "(?<=-)i(?=-)"

This will then work for situations such as this:

$ lsattr -R 2>/dev/null afile | grep -P "(?<=-)i(?=-)"
----i--------e-- afile

But is imperfect. If there are additional attributes enabled around the immutable flag, then we'll not match them, and this will be fooled by files whose names happen to match the above pattern as well, such as this:

$ lsattr -R 2>/dev/null afile* | grep -P "(?<=-)i(?=-)"
----i--------e-- afile
-------------e-- afile-i-am

We can tighten up the pattern a bit more like this:

$ lsattr -a -R 2>/dev/null afile* | grep -P "(?<=-)i(?=-).* "
----i--------e-- afile

But it's still a bit too fragile and would require additional tweaking depending on the files within your filesystem. Not to mention as @StephaneChazeles has mentioned in comments that this can be gamed fairly easily by the inclusion of newlines with a files name to bypass the above pattern to grep.

References

https://groups.google.com/forum/#!topic/alt.os.linux/LkatROg2SlM

Related Question