DEV Community

Ubuntu Fundamentals: su

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/passwd and /etc/shadow: Contain user account information and encrypted passwords, respectively.
  • login: The underlying system call su utilizes 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

  1. Emergency Root Access: When SSH access to root is disabled (a best practice), su provides a controlled method for administrators to gain root privileges after authenticating as a standard user.
  2. 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 postgres user to perform database maintenance.
  3. 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> bash leverages similar principles.
  4. Immutable Infrastructure Builds: During image creation with Packer, su can be used to execute commands as specific users to configure services or install software within the image.
  5. Secure Application Deployment: Deploying applications as a dedicated, low-privilege user and using su to 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: whoami and id provide information about the current user and their group memberships.
  • Listing Users: getent passwd lists all users on the system.
  • PAM Configuration Inspection: cat /etc/pam.d/su reveals the authentication methods configured for su.
  • Auditing su Usage: auditd can be configured to log all su attempts. 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

Enter fullscreen mode Exit fullscreen mode
  • Example: Examining PAM configuration:
cat /etc/pam.d/su
# Output will show authentication modules like pam_unix.so, pam_succeed_if.so, etc.

Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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 .bashrc or similar startup file.
  • Disk I/O: Accessing /etc/passwd and /etc/shadow involves disk I/O.

Benchmarking:

  • time su - <username>: Measures the time taken to switch users.
  • htop: Monitor CPU and memory usage during su execution.
  • sysctl -a | grep vfs_cache_pressure: Adjusting vfs_cache_pressure can 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 no in /etc/ssh/sshd_config.
  • Restrict su Access: Use /etc/pam.d/su to limit which users can su to root or other privileged accounts. pam_listfile.so can be used to define allowed users.
  • AppArmor/SELinux: Confine the su process with AppArmor or SELinux profiles to restrict its capabilities.
  • Fail2ban: Monitor su attempts and ban malicious IPs that repeatedly fail authentication.
  • Auditd: Log all su attempts 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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, including su attempts.
  • /var/log/audit/audit.log: If auditd is configured, this log contains detailed audit records of su usage.
  • strace su - <username>: Trace system calls made by su to diagnose authentication or environment issues.
  • lsof -p <su_pid>: List open files associated with the su process.
  • System Health Indicator: Monitor the number of failed su attempts over time as a potential indicator of brute-force attacks.

Common Mistakes & Anti-Patterns

  1. Enabling Root Login via SSH: PermitRootLogin yesIncorrect. Disable root login and use su or sudo instead.
  2. Using su without the - option: su <username>Incorrect. This doesn’t source the target user’s environment, leading to unexpected behavior.
  3. Hardcoding Passwords in Scripts: Using su - <username> -c "command" with a hardcoded password – Incorrect. Use key-based authentication or a secrets management solution.
  4. Overly Permissive PAM Configuration: Allowing any user to su to root – Incorrect. Restrict access to authorized users only.
  5. Ignoring Audit Logs: Not monitoring auditd logs for suspicious su activity – Incorrect. Regularly review audit logs for security incidents.

Best Practices Summary

  1. Disable Root Login via SSH.
  2. Always use su - <username> to source the target user’s environment.
  3. Restrict su access using PAM and /etc/su.allowed.
  4. Implement AppArmor or SELinux profiles for su.
  5. Enable and monitor auditd logs for su activity.
  6. Avoid hardcoding passwords in scripts; use secure authentication methods.
  7. Regularly review and update PAM configuration.
  8. Automate su configuration with Ansible or similar tools.
  9. Monitor failed su attempts as a security indicator.
  10. Document su usage 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)