Commands.page Logo

How to Audit Every Sudo Command in Ubuntu

Yes, it is possible to audit every command executed with sudo privileges on Ubuntu to enhance system security and maintain compliance. This article explains how to configure detailed logging using the default syslog facility and the advanced auditd framework. You will learn the specific steps to verify current settings, safely modify the sudoers file, and query logs to track user activity effectively.

Configure Sudoers Logging

Ubuntu logs sudo commands by default to /var/log/auth.log, but you can customize this behavior. To modify settings, always use the visudo command to prevent syntax errors that could lock you out of sudo access. Open the terminal and run sudo visudo. Ensure the following line exists to log all sudo commands to a specific file or syslog:

Defaults logfile="/var/log/sudo.log"

Alternatively, to keep using syslog which is standard on Ubuntu, ensure Defaults syslog=priority is set. Saving this file enables immediate logging of every sudo invocation, including the user, timestamp, and command executed.

Implement System Auditing with Auditd

For more robust auditing that captures system calls and file access, install the audit daemon. Run sudo apt install auditd to install the package. Once installed, you can add rules to monitor the sudo binary specifically. Execute the following command to watch for execution of the sudo binary:

sudo auditctl -w /usr/bin/sudo -p x -k sudo_commands

To make this rule persistent across reboots, add the same line to /etc/audit/rules.d/audit.rules. The -w flag watches the path, -p x monitors execution, and -k assigns a key for easy searching.

Viewing and Analyzing Logs

If you configured the sudoers logfile, view entries directly with sudo cat /var/log/sudo.log. For default Ubuntu syslog configurations, check /var/log/auth.log using grep sudo /var/log/auth.log. If you implemented auditd, use the ausearch tool to query events by the key defined earlier:

sudo ausearch -k sudo_commands

Regularly review these logs to identify unauthorized privilege escalation attempts. Ensure log files are protected so that only root can modify or delete them, preserving the integrity of your audit trail.