Linux – How to detect what is changing file ownership on Linux

diagnosticfile-permissionslinux

I have inherited a bunch of Linux (Ubuntu Precise) servers and am currently having problems with the ownership of a folder changing to "root" fairly often. We run puppet, which changes the ownership to the user it should be, but something else changes it back a bit later.

I'm currently logging the permissions on the file every 30 seconds to try and narrow down a time to see if there's anything in logs, etc. It's a large busy server, so without more information it's not easy to find anything in logs.

Is there a way in Linux to catch when a file/folder ownership changes and detect the process responsible?

Best Answer

I think you can use audit for specific file/directory or you can write custom rule based on your requirement

        auditctl -w <path to the file you need to monitor> -p war -k test

        Where -w is for specifying file path
        -p is for permission access (read,write,execute and attribute change)
        -k key name,you can give name you can use to filter audit rule

Then you can search it using

        ausearch -ts today -k test

For eg I used this,create this file /tmp/test and then write some random data

       auditctl -w /tmp/test -p warx -k test

and then execute this command

       ausearch -ts today -k test

      --ts for start date
      -k is for key string

So the output of this

  type=SYSCALL msg=audit(1407949301.821:63216): arch=c000003e syscall=191 success=no
  exit=-61 a0=eacca0 a1=3600005db7 a2=7fff15265180 a3=84 items=1 ppid=2384 pid=16921
  auid=0 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=10096
  comm="vim" exe="/usr/bin/vim" key="test"

So if you check the last line of output it will show command executed is vim and with uid=0 which is root

If you want to make these changes persistent across reboot,inside /etc/audit/audit.rules add the entry like this

  -w /tmp/test -p warx -k test

and make sure auditd service is up and running

  service auditd status 

For more info you can refer http://www.cyberciti.biz/tips/linux-audit-files-to-see-who-made-changes-to-a-file.html