Thursday, 5 June 2014

How to log user's actions in bash?

When you offer shell access to your users, logging their activity is a must. Bash is the most popular shell for Linux, so let's focus on it. There are at least three methods of logging bash commands used by your users. The first works on the kernel level and is the most effective, since it logs every user exec, doesn't matter if it comes from bash or not. The second is unbelievably simple, but would be enough in the most cases. The third is a patch for bash (or any another shell) but it is the worst method in my opinion, since it is quite complicated and not so effective.

Kernel-level logging


First apply the grsecurity patch and do:

make menuconfig

Than go to the Security options/Grsecurity and turn on Grsecurity. Next enter Customize Configuration/Kernel Auditing and turn on Exec logging and Chdir logging. Than compile your new kernel. Now, all execve() and chdir() calls can be found in the syslog.

Bash history logging


Bash has the built-in logging mechanism. It logs every command used by the user to the file $HOME/.bash_history. The problem is, that every user can delete or modify his own .bash_history. The solution is simple:

chattr +a $HOME/.bash_history

This line should be added to the script, which you use to add a new user. In some cases, $HOME should be replaced by the local variable which indicates given user home directory.

The disadvantage is, that there are many simple workarounds of this type of logging. The .bash_history was created as a command history for users, not as a logging tool for the system administrator.

Patching the bash


It was the first method, which I used many years ago, but I don't recommend it anymore. It is more difficult to implement it, but it isn't more secure (or less insecure) than the previous method.

The conclusion


As you see, it's not so hard to log your users' activity. Although the simpliest method is better than nothing, and may help you in analysis when something goes wrong, I strongly recommend kernel-lever logging, since it is hard to bypass it.