It’s a very well known issue that if you award sudo to an user and he/she executes a shell, you lost what the user does. I received a requirement in a project to find out how to have a registry of the user actions after sudo. Linux offers a way to do this, using the “Audit” system. With this piece of the kernel and its user space tools, you can log the system calls invoked (and other things too). The most important one to observe is the “execve” system call. Having a record of its invocations, you’ll know what the users are doing after “sudo some_shell”.
There are some things to note about audit:
- What is going to be audited is configured by a set of rules.
- Rules define things like what system call, what user id, etc.
- The rules are persistent if they are set in /etc/audit/audit.rules. This means, for example, that if you set audit for some user and he restarts a daemon or executes something with nohup, the system will continue sending records to the system log, even if the user log out.
- auditctl is a command line tool that can be used to load rules without using the configuration file.
- auid is the user ID of the user. This value is set in the pam stack at login and persists after sudo or su execution.
The third point is problematic. If you don’t fix that, a lot of useless things will appear in the log files. What I used to avoid this is the pam_script module. It permits to execute scripts when the user opens and close a session. Instead of persistent rules, I execute auditctl to add/remove rules at every login and logout.
The configuration of this is simple. First install auditd and pam_script packages (I used Debian), and then put this line in the session section of service where you want to enable audit:
session required pam_script.so onerr=success dir=/etc/pam-script
The place where you put that line depends on when do you want to enable audit. For example, I only want to know what the user does after sudo, so that line is in the sudo pam service config file. If you want to watch the user just after login, you must put that line in every pam service that is an entry point (ssh, login, etc).
Next, you have to configure the pam_loginuid.so module.
session required pam_loginuid.so
The line above must be in every entry point. It sets the auid variable that I mentioned before. It doesn’t work if you use it in sudo or su pam files.
To finish, you have to create the scripts to be executed by pam_script. The location of the scripts depends on the “dir=” options of the pam module. The scripts must be called pam_script_ses_open and pam_script_ses_close. In my setup they execute the following lines:
AUID=$(getent passwd $USER | cut -d: -f3)
/sbin/auditctl [-a|-d] entry,always \
-S execve \
-a to add the rule, -d to remove.
You can see the logs in /var/log/audit/audit.log