How do I create audit rules to see events limited to a single directory?

Solution Verified - Updated -

Environment

  • Red Hat Enterprise Linux

Issue

  • When I look at a directory with an audit rule, it shows everything below that directory, too. How can I limit audit rules to a single directory?

Resolution

Create negative rules prior to positive rules to prevent unwanted processing of subdirectories.
Example:

-a exit,never -F dir=/bin/
-a exit,never -F dir=/dev/
-a exit,never -F dir=/etc/
-a exit,never -F dir=/usr/
-a exit,always -F dir=/ -F perm=w

It might be reasonable to write a short script to create rules for directories inside your target. Using root as a popular example:

#!/bin/sh
RULES="/etc/audit/rules.d/my-custom-audit.rules"

# Create negative rules so we only match creates inside /, not subdirs
ls -1d /*/ | while read dir
do
    echo "-a exit,never -F dir=$dir"
done > $RULES

# After the negative rules, add a rule to capture creates in /
echo "-a exit,always -F dir=/ -F perm=w -F key=my-custom-audit" >> $RULES

Note that the permission selector here will inherently capture all relevant syscalls that create inodes.

Root Cause

By default, directory rules are recursive. For example, this rule watches both the root directory and every directory below it that's part of the same filesystem, recusively, making its descriptive key somewhat inaccurate:

-a exit,always -F dir=/ -F perm=w -F key=watching-root

Note that rules apply in order. If a positive rule is matched, negative rules further down will not be applied. As an example, this set will audit activity in /etc:

-a exit,always -F dir=/ -F perm=w
-a exit,never -F dir=/etc/

Conversely, this set will not show changes in /etc, because the negative rule is matched first:

-a exit,never -F dir=/etc/
-a exit,always -F dir=/ -F perm=w

Diagnostic Steps

Choosing keys, generating rules, and reading data collected by auditd is described here:
- How to monitor filesystem changes with auditd

This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.