Pyinotify, simple approach
Since you asked for
Python among potential variations on solutions, there is Python's
pyinotify module. I'm personally using Python 3. The solution can be as simple as
python3 -m pyinotify <FILE> or you can write a full-blown script if necessary.
Here's an example in action:
One possibility of a custom script can be done via modifying the tutorial provided on official GitHub repository for pyinotify. Since you're only concerned with modifications to the file, I implemented the script only for that, but it can be altered to include other events.
def process_IN_MODIFY(self, event):
print("File",sys.argv," was modified:",event.pathname)
wm = pyinotify.WatchManager()
mask = pyinotify.IN_MODIFY
handler = EventHandler()
notifier = pyinotify.Notifier(wm, handler)
wdd = wm.add_watch(sys.argv, mask, rec=True)
And here is a small test:
Taking it further
In either case, all you need to do is to launch the command with root privileges via
/etc/rc.local or via
cron, and that's it. Output can be sent to either some sort of log file, or send a notification to admin user. Personally, I'd launch two commands - one with root privileges that writes to a log file, and another one that watches log file for changes and sends a GUI notification to the user. Possibilities are endless here, so use your imagination.
Looking for changes can be done via keeping backup of the file (maybe taken at the start of the script), and once the file is modified - run
diff or via Python script itself via difflib. You can also incorporate checking
sha256 hashsums into the equation, but those aren't very useful except for knowing that file was altered. Another issue is that running a notifier script doesn't prevent changes that may have occurred while system was off-line, i.e. if somebody booted live USB or took out your hard-drive and connected to their machine, and only then modified the file. This can be mitigated by encrypting the hard drive. That also means that you probably should check for changes as soon as the script starts up.
As far as figuring out who altered the file, you could consider correlating date of modification and date of users logging in as root/sudo. Of course, I have to warn: this is a somewhat hopeless task. A rogue user with root abilities can alter logs and erase that user's presence, leaving little to no indication of who it may have been. Users who acquired root powers can even alter your script. In conclusion, the best security to avoid having your sensitive file modified is to prevent anyone being able to open that file in the first place.