The Unsung Hero: Deep Dive into su on Ubuntu
Introduction
A critical production incident involving a compromised application server recently highlighted a fundamental gap in our team’s understanding of su’s nuances. The attacker leveraged a misconfigured service account and escalated privileges using su to root, bypassing several layers of security. This incident underscored that su, often treated as a basic command, is a powerful tool requiring deep understanding for secure and reliable Ubuntu-based systems. We operate a hybrid cloud environment with a significant footprint of Ubuntu 22.04 LTS VMs, containerized applications orchestrated by Kubernetes, and a growing number of immutable server images built with Packer. Mastering su is no longer optional; it’s essential for maintaining a robust security posture and enabling effective incident response.
What is "su" in Ubuntu/Linux context?
su (Substitute User) is a command-line utility used to assume the identity of another user. In Ubuntu, and Debian-based systems generally, it’s a core component of user management and privilege escalation. Unlike sudo, which executes a single command as another user, su starts a new shell as that user.
Key system tools involved include:
- PAM (Pluggable Authentication Modules): Handles authentication for
su, allowing for flexible authentication methods (passwords, tokens, etc.). Configuration files reside in/etc/pam.d/su. -
/etc/passwdand/etc/shadow: Contain user account information and encrypted passwords, respectively. -
login: The underlying system callsuutilizes to change user context. -
systemd-logind: Manages user sessions and provides information about logged-in users.
Ubuntu’s implementation of su adheres to POSIX standards, but PAM configuration can significantly alter its behavior. Distro-specific differences primarily lie in the default PAM configuration and the availability of security enhancements like AppArmor.
Use Cases and Scenarios
- Emergency Root Access: When SSH access to root is disabled (a best practice),
suprovides a controlled method for administrators to gain root privileges after authenticating as a standard user. - Service Account Management: Switching to a dedicated service account to perform tasks specific to that service, isolating operations and minimizing potential damage from compromised credentials. For example, switching to the
postgresuser to perform database maintenance. - Container Entry: Entering a running container as a specific user (often non-root) for debugging or administrative tasks.
docker exec -it -u <user> <container_id> bashleverages similar principles. - Immutable Infrastructure Builds: During image creation with Packer,
sucan be used to execute commands as specific users to configure services or install software within the image. - Secure Application Deployment: Deploying applications as a dedicated, low-privilege user and using
suto temporarily escalate privileges for specific deployment tasks (e.g., restarting a service).
Command-Line Deep Dive
- Basic Usage:
su - <username>(The-option simulates a full login, sourcing the target user’s environment.) - Checking Current User:
whoamiandidprovide information about the current user and their group memberships. - Listing Users:
getent passwdlists all users on the system. - PAM Configuration Inspection:
cat /etc/pam.d/sureveals the authentication methods configured forsu. - Auditing
suUsage:auditdcan be configured to log allsuattempts. Example rule:auditctl -w /etc/passwd -p wa -k su_activity. Logs are found in/var/log/audit/audit.log. - Example: Switching to Postgres User:
sudo su - postgres
psql -c "SELECT version();"
exit # Return to original user
- Example: Examining PAM configuration:
cat /etc/pam.d/su
# Output will show authentication modules like pam_unix.so, pam_succeed_if.so, etc.
System Architecture
graph LR
A[User] --> B(SSH/Terminal)
B --> C{su Command}
C --> D[PAM (Authentication)]
D --> E{/etc/passwd /etc/shadow}
D --> F[systemd-logind]
E --> G[Kernel (User Context Switch)]
F --> H[Journald (Logging)]
G --> I[New Shell (Target User)]
I --> J[Applications/Services]
su interacts heavily with PAM for authentication. Successful authentication triggers a user context switch within the kernel, managed by systemd-logind. All actions are logged via journald and potentially auditd. The networking stack is unaffected directly, but the effective user ID (EUID) changes, impacting file access and network permissions.
Performance Considerations
su itself has minimal performance overhead. The primary performance impact comes from:
- PAM Modules: Complex PAM configurations can introduce latency during authentication.
- Environment Sourcing: Sourcing the target user’s environment (
su -) can be slow if the user has a large.bashrcor similar startup file. - Disk I/O: Accessing
/etc/passwdand/etc/shadowinvolves disk I/O.
Benchmarking:
-
time su - <username>: Measures the time taken to switch users. -
htop: Monitor CPU and memory usage duringsuexecution. -
sysctl -a | grep vfs_cache_pressure: Adjustingvfs_cache_pressurecan influence disk caching behavior.
Tuning: Optimize PAM configuration by removing unnecessary modules. Consider caching user information to reduce disk I/O.
Security and Hardening
- Disable Direct Root Login:
PermitRootLogin noin/etc/ssh/sshd_config. - Restrict
suAccess: Use/etc/pam.d/suto limit which users cansuto root or other privileged accounts.pam_listfile.socan be used to define allowed users. - AppArmor/SELinux: Confine the
suprocess with AppArmor or SELinux profiles to restrict its capabilities. - Fail2ban: Monitor
suattempts and ban malicious IPs that repeatedly fail authentication. - Auditd: Log all
suattempts for forensic analysis. - UFW: Restrict SSH access to authorized networks.
Example: Restricting su to root to specific users in /etc/pam.d/su:
auth required pam_listfile.so item=user sense=allow file=/etc/su.allowed
Create /etc/su.allowed and add allowed usernames, one per line.
Automation & Scripting
Ansible Example:
- name: Restrict su access to root
copy:
dest: /etc/pam.d/su
content: |
auth required pam_listfile.so item=user sense=allow file=/etc/su.allowed
notify: Restart SSH
- name: Add allowed users to /etc/su.allowed
lineinfile:
path: /etc/su.allowed
line: "{{ item }}"
create: yes
loop:
- admin1
- admin2
- name: Restart SSH
service:
name: sshd
state: restarted
This Ansible playbook restricts su access to root to only the users listed in /etc/su.allowed. Idempotency is ensured by lineinfile.
Logs, Debugging, and Monitoring
-
journalctl -u systemd-logind: Monitor user login/logout events. -
/var/log/auth.log: Contains authentication logs, includingsuattempts. -
/var/log/audit/audit.log: Ifauditdis configured, this log contains detailed audit records ofsuusage. -
strace su - <username>: Trace system calls made bysuto diagnose authentication or environment issues. -
lsof -p <su_pid>: List open files associated with thesuprocess. - System Health Indicator: Monitor the number of failed
suattempts over time as a potential indicator of brute-force attacks.
Common Mistakes & Anti-Patterns
- Enabling Root Login via SSH:
PermitRootLogin yes– Incorrect. Disable root login and usesuorsudoinstead. - Using
suwithout the-option:su <username>– Incorrect. This doesn’t source the target user’s environment, leading to unexpected behavior. - Hardcoding Passwords in Scripts: Using
su - <username> -c "command"with a hardcoded password – Incorrect. Use key-based authentication or a secrets management solution. - Overly Permissive PAM Configuration: Allowing any user to
suto root – Incorrect. Restrict access to authorized users only. - Ignoring Audit Logs: Not monitoring
auditdlogs for suspicioussuactivity – Incorrect. Regularly review audit logs for security incidents.
Best Practices Summary
- Disable Root Login via SSH.
- Always use
su - <username>to source the target user’s environment. - Restrict
suaccess using PAM and/etc/su.allowed. - Implement AppArmor or SELinux profiles for
su. - Enable and monitor
auditdlogs forsuactivity. - Avoid hardcoding passwords in scripts; use secure authentication methods.
- Regularly review and update PAM configuration.
- Automate
suconfiguration with Ansible or similar tools. - Monitor failed
suattempts as a security indicator. - Document
suusage policies and procedures.
Conclusion
su is a deceptively simple command with profound implications for system security and administration. Ignoring its nuances can lead to critical vulnerabilities, as demonstrated by recent incidents. By understanding its architecture, security considerations, and best practices, we can leverage su effectively to maintain robust, reliable, and secure Ubuntu-based systems. Actionable next steps include auditing existing su configurations, building automated configuration scripts, implementing comprehensive monitoring, and documenting clear usage standards for our team.
Top comments (0)