Recent from talks
Nothing was collected or created yet.
Su (Unix)
View on Wikipedia| su | |
|---|---|
| Original authors | |
| Developer | AT&T Bell Laboratories |
| Initial release | November 3, 1971 |
| Operating system | Unix and Unix-like |
| Type | Command |
The Unix command su, which stands for "substitute user"[1][2] (or historically "superuser"[3][4]), is used by a computer user to execute commands with the privileges of another user account. When executed it invokes a shell without changing the current working directory or the user environment.
When the command is used without specifying the new user id as a command line argument, it defaults to using the superuser account (user id 0) of the system.
History
[edit]The command su, including the Unix permissions system and the setuid system call, was part of Version 1 Unix. Encrypted passwords appeared in Version 3.[5] The command is available as a separate package for Microsoft Windows as part of the UnxUtils collection of native Win32 ports of common GNU Unix-like utilities.[6]
The su command was removed from GNU coreutils as of release 8.18 (2012-08-12)[7] and is currently included in the util-linux package.
Usage
[edit]When run from the command line, su asks for the target user's password, and if authenticated, grants the operator access to that account and the files and directories that account is permitted to access.
john@localhost:~$ su jane
Password:
jane@localhost:/home/john$ exit
logout
john@localhost:~$
When used with a hyphen (su -) it can be used to start a login shell. In this mode users can assume the user environment of the target user.
john@localhost:~$ su - jane
Password:
jane@localhost:~$
The command sudo is related, and executes a command as another user but observes a set of constraints about which users can execute which commands as which other users (generally in a configuration file named /etc/sudoers, best editable by the command visudo). Unlike su, sudo authenticates users against their own password rather than that of the target user (to allow the delegation of specific commands to specific users on specific hosts without sharing passwords among them and while mitigating the risk of any unattended terminals).
Some Unix-like systems implement the user group wheel, and only allow members to become root with su.[8] This may or may not mitigate these security concerns, since an intruder might first simply break into one of those accounts. GNU su, however, does not support the group wheel for philosophical reasons. Richard Stallman argues that because the group would prevent users from utilizing root passwords leaked to them, the group would allow existing admins to ride roughshod over ordinary users.[9]
See also
[edit]Further reading
[edit]- "From Novice to Master, and Back Again". D-Mac's Stuff. 2013-01-14. Retrieved 2022-08-10.
References
[edit]- ^ "su(1) - Linux manual page". April 2, 2021.
su - run a command with substitute user and group ID
- ^ "Unix Programmer's Manual, Seventh Edition, Volume 1" (PDF). January 1, 1979. p. 174. Archived (PDF) from the original on Jan 20, 2022.
su - substitute user id temporarily
- ^ "Unix Programmer's Manual" (PDF). November 3, 1971. p. 17. Archived (PDF) from the original on March 17, 2022.
su -- become privileged user... su allows one to become the super-user.
- ^ "Unix Programmer's Manual - Table of Contents" (PDF). November 3, 1971. Archived (PDF) from the original on March 17, 2022.
su: become super-user
- ^ McIlroy, M. D. (1987). A Research Unix reader: offticles annotated excerpts from the Programmer's Manual, 1971–1986 (PDF) (Technical report). CSTR. Bell Labs. 139.
- ^ "Native Win32 ports of some GNU utilities". unxutils.sourceforge.net.
- ^ "NEWS". GitHub. 17 September 2022.
- ^ Levi, Bozidar (2002). UNIX Administration: A Comprehensive Sourcebook for Effective Systems and Network Management. CRC Press. pp. 207. ISBN 0-8493-1351-1.
- ^ "Why GNU su does not support the 'wheel' group". Archived from the original on June 21, 2021. Retrieved May 30, 2022.
External links
[edit]- su – manual pages from GNU coreutils.
- – Linux User Commands Manual
- – FreeBSD General Commands Manual
- – Solaris 11.4 System Administration Commands Reference Manual
- The su command – by The Linux Information Project (LINFO) (Archived 20 October 2021 at the Wayback Machine)
Su (Unix)
View on GrokipediaOverview
Definition and Purpose
Thesu command, short for "substitute user," is a utility in Unix-like operating systems that enables a user to execute commands or initiate an interactive shell with the effective user ID and group ID of another user account, thereby assuming that account's privileges.[1] This functionality supports secure user switching without requiring a full logout and login process, preserving the session's continuity while altering the security context.[5]
Its primary purpose is to facilitate temporary elevation of privileges, most commonly to the superuser (root) account, for performing system administration tasks that demand heightened access levels, such as software installation or file system modifications.[1] By allowing such switches, su maintains separation between regular user activities and administrative operations, promoting a controlled environment where users operate with minimal necessary permissions unless explicitly elevated.[5] When invoked without specifying a target user, su defaults to switching to the root user, prompting for the root password to authenticate the change.[1]
A key aspect of su's operation is that it does not alter the current working directory or fully emulate a complete login environment for the target user; instead, it retains the invoking user's directory and most environment variables, unless the login option is used to simulate a fresh login shell.[1] This design choice ensures seamless integration into ongoing sessions while avoiding unintended environmental disruptions.[5]
Originating as a core command in early Unix systems tailored for multi-user environments, su embodies the principle of least privilege by enabling brief, authenticated privilege escalations rather than encouraging persistent root logins, thereby reducing exposure to security risks in shared computing setups.[6]
Basic Functionality
Thesu command begins its execution by prompting for the target user's password to authenticate the switch, unless the invoking user already possesses sufficient privileges such as root access. Upon successful authentication, su verifies the credentials against the system's user database, primarily using the /etc/passwd file for account details like UID, GID, and default shell, and the /etc/shadow file for encrypted password storage and validation, often facilitated by Pluggable Authentication Modules (PAM) in contemporary Unix-like systems.[1][7][8][9]
Following authentication, su invokes a new shell process—defaulting to /bin/sh or the shell specified in the target user's entry in /etc/passwd—executing it with the target user's real and effective user ID (UID) and group ID (GID). This process switch occurs via system calls like setuid() and setgid(), enabling the new shell to operate with the target's permissions for file access and resource allocation. The original session's process group and session ID are preserved, ensuring the substituted environment remains part of the caller's terminal session without disrupting controlling terminal associations.[1][9]
Environment handling in su involves inheriting the majority of the calling user's environment variables, such as PATH and TERM, to maintain operational continuity, while setting key variables like HOME, SHELL, USER, and LOGNAME to reflect the target user. However, it does not source the target user's login profile scripts (e.g., .profile or .bashrc) by default, avoiding unintended modifications unless explicitly requested via a login shell invocation; this partial inheritance balances familiarity with security by preventing the loading of potentially untrusted configurations.[1][9]
If no command is specified as an argument, su launches an interactive shell under the target user's context, allowing the user to enter commands directly within the substituted environment. The interactive session continues until the shell exits, at which point su terminates and returns control to the original user's shell, restoring the prior privilege level without altering the parent process's state.[1][9]
Overall, su integrates deeply with Unix system components, depending on the user database entries in /etc/passwd for identity resolution and /etc/shadow for secure credential checks, ensuring reliable privilege escalation or delegation while adhering to the system's multi-user security model. Modern variants may employ PAM for extensible authentication, but the core reliance on these files remains foundational across POSIX-compliant implementations.[1][7][8][9]
History
Origins in Early Unix
Thesu command was introduced on November 3, 1971, as part of Version 1 Unix developed at AT&T Bell Laboratories.[10] Authored by Ken Thompson and Dennis Ritchie, it debuted in the first edition of the Unix Programmer's Manual, serving as a foundational utility for user identity switching in the nascent operating system.[11] This initial release ran on the PDP-11/20 minicomputer, marking Unix's transition from earlier experiments on the PDP-7.[12]
Designed for multi-user time-sharing environments, su addressed the need for secure transitions between user accounts without requiring system reboots, facilitating collaborative research and development at Bell Labs.[12] In these early setups, Unix supported multiple simultaneous users on limited hardware like the PDP-11, where efficient privilege management was essential for interactive computing tasks such as text processing and program development. The command's implementation featured basic password authentication, prompting for the target user's credentials and verifying them directly without encryption. It integrated seamlessly into the core command set of Version 1, appearing alongside essentials like ls for directory listings and cat for file concatenation.[11]
Early limitations of su included its reliance on plaintext password checks against entries in the /etc/passwd file, which stored credentials unencrypted—a design reflecting the system's primitive security model before the introduction of hashing in Unix Third Edition (1973).[13] There was no support for environment variable customization or login-like initialization, meaning switched sessions inherited the original user's environment without isolation. Despite these constraints, su quickly became a core utility in subsequent AT&T Unix releases, from Version 2 onward, and exerted influence on variants like Berkeley Software Distribution (BSD) by the mid-1970s, embedding itself in the evolving Unix ecosystem.[11]
Evolution and Standardization
Thesu command evolved significantly from its early Unix implementations, with a key enhancement in Version 3 Unix released in February 1973, where support for encrypted passwords was integrated through the /etc/passwd file structure, allowing secure authentication without storing plaintext credentials.[14] This change addressed growing security needs as Unix systems proliferated in research environments, enabling su to verify user-supplied passwords against hashed entries in the password database.[14]
While su follows common Unix conventions for syntax, default root switching, and environment handling, it is not part of the POSIX standard.[1]
In the GNU ecosystem, su was maintained within the coreutils package until version 8.18 released on August 14, 2012, after which it was relocated to the util-linux package to align with Linux-specific developments and reduce overlap in utility distributions.[15] BSD variants introduced the wheel group restriction in 4.3BSD (1986), limiting su to root access only for members of group 0 to prevent unauthorized privilege escalation.[16] Linux implementations, particularly through the shadow-utils package originating in the early 1990s, enhanced su with shadowed password support for better security isolation, followed by Pluggable Authentication Modules (PAM) integration starting with Linux-PAM 0.49 in 1997, enabling flexible authentication backends like LDAP or biometrics.[13]
Portability efforts extended su to non-Unix platforms, including Windows via Cygwin's POSIX emulation layer, which provides a functional su within its Unix-like environment despite Windows' lack of native UID switching.[17] Similarly, the UnxUtils project offers native Win32 ports of Unix utilities, including su, as an ongoing initiative to enable Unix command compatibility without full emulation layers as of 2025.[18]
Recent developments in util-linux emphasize stability, with minor enhancements such as improved PAM handling and man page clarifications in version 2.40 (released March 2024), reflecting no major overhauls since its early design due to the command's mature implementation.[19]
Usage
Command Syntax
The basic syntax of thesu command follows the form su [options] [user [argument...]], where the optional user argument specifies the target user account, defaulting to an unspecified privileged user (commonly root in Unix-like systems) if omitted, and any trailing argument... are passed to the invoked shell or command.[9][1] When invoked without arguments, su starts an interactive login shell for the target user, initializing the environment accordingly.[9]
Upon execution, su prompts for the target user's password unless the invoking process already holds appropriate privileges (such as running as root), and authentication fails if the provided credentials are incorrect, resulting in an error message and termination without switching users; failed attempts are typically logged in system files like /var/log/btmp on supported platforms.[1][9] For non-interactive use, the syntax su [options] [user] -c "command" allows execution of a single specified command as the target user, passing the quoted string to the shell for interpretation without spawning an interactive session.[1]
In terms of error handling, su returns an exit status of 1 upon authentication failure or other generic errors, while successfully executed commands propagate their original exit status (or 128 plus the signal number if terminated by a signal) to the parent process.[1] This behavior is specified in the Linux Standard Base (LSB) Core specification, though implementations like those in Linux may include minor variations documented in their respective manual pages.[9] A formal synopsis in Backus-Naur Form (BNF) notation, excluding options for clarity, can be expressed as:
su ::= "su" ["user" ["argument"...]]
non-interactive ::= "su" ["user"] "-c" "command"
su ::= "su" ["user" ["argument"...]]
non-interactive ::= "su" ["user"] "-c" "command"
user is an optional username string, argument... denotes zero or more shell arguments, and command is the string to execute via the target user's shell.[9]
Common Options and Examples
Thesu command supports several common options that modify its behavior, allowing users to control the shell environment, execute specific commands, or preserve existing variables. The - or -l (equivalent to --login) option invokes a login shell for the target user, which simulates a full login process by sourcing system-wide profile files such as /etc/profile and the user's ~/.profile, resetting most environment variables (except for TERM, HOME, SHELL, PATH, USER, and LOGNAME), and changing the working directory to the target user's home directory.[1] This option is particularly useful for ensuring a clean, user-specific environment. The -c (or --command) option enables the execution of a single command as the target user without starting an interactive shell, passing the command to the shell's -c argument for interpretation.[1] Additionally, the -s (or --shell) option allows specification of a particular shell, overriding the target user's default shell (falling back to /bin/sh if the default is restricted and the target is not root).[1] To maintain the invoking user's environment variables during the switch, the -m or -p (equivalent to --preserve-environment) option can be used, though it is overridden if combined with --login.[1]
Practical examples illustrate these options in everyday scenarios. For instance, entering su root prompts for the root password and starts an interactive root shell while retaining the caller's environment variables, providing a straightforward way to escalate privileges temporarily.[1] To switch to a login shell as another user, such as su - jane, the command authenticates with Jane's password, loads her login environment, and changes the directory to her home folder, ideal for testing user-specific configurations.[1] For non-interactive tasks, su -c "apt update" executes the package update command as root without spawning a full shell, minimizing the session's scope and reducing exposure to unintended actions.[1] Similarly, su -s /bin/bash jane starts a bash shell as Jane, even if her default shell differs, which is helpful in environments with restricted shells.[1]
On systems like FreeBSD, access to su for becoming root is restricted to members of the "wheel" group, a security measure that limits superuser elevation to authorized administrative users; non-members attempting su root will receive an authentication failure despite providing the correct password.[20] In contrast, many Linux distributions configure this restriction via Pluggable Authentication Modules (PAM), where wheel group enforcement is optional and often supplemented or replaced by tools like sudo for finer-grained control, though su itself does not enforce it by default.[1]
The choice of options significantly affects the environment inherited by the new session. Without the --login flag, su sets only HOME and SHELL based on the target user while preserving the invoker's other variables, such as PATH, which can lead to inconsistencies if the caller's environment includes non-standard paths.[1] Conversely, the --login option fully reinitializes the environment to mimic a fresh login, clearing potentially insecure variables and establishing a secure baseline, as implemented in util-linux versions up to recent releases.[1] This distinction ensures predictable behavior in scripted or multi-user setups.
Security Considerations
Potential Risks
Thesu command enables direct escalation to root privileges, bypassing more granular access controls and potentially allowing users to perform unintended system-wide modifications, such as accidentally executing destructive commands like rm -rf /, which can lead to complete data loss or system instability.[21] This lack of command-specific restrictions heightens the risk of both accidental damage and deliberate misuse by compromised user accounts.[1]
Authentication via su involves entering the target user's password at a prompt, which, while not echoed to the screen, remains vulnerable to observation through shoulder surfing—where an attacker visually captures the input—or keyloggers that record keystrokes during the process.[22] Additionally, attempts to automate su by piping passwords (e.g., echo "password" | su root) expose the plaintext credential in the process list visible via tools like ps, and in shell history files, facilitating unauthorized access if the system is monitored or logs are reviewed.[23]
When invoked without the --login or - option, su spawns a non-login shell that inherits the calling user's environment variables, including potentially unsafe ones like a modified PATH that could direct execution to malicious binaries instead of legitimate ones, leading to trojan horse activation or unintended command substitution.[1] Furthermore, without the --pty option, su may allocate a pseudo-terminal insecurely, exposing the session to ioctl-based attacks such as TIOCSTI or TIOCLINUX manipulations that could enable privilege escalation by injecting commands into the input stream.[1]
In early Unix implementations, user passwords were stored as DES-hashed values in the world-readable /etc/passwd file, allowing offline cracking attacks against the hashes using tools like those developed by Robert Morris in the 1970s, which compromised root access via su if weak passwords were used.[24] The introduction of shadow password files in the late 1980s (e.g., via SunOS 4.1) restricted password storage to root-readable /etc/shadow, mitigating direct file exposure but not eliminating brute-force threats against the root password during su authentication, especially without account lockout mechanisms.[25]
Abuse of su facilitates persistent backdoors by allowing attackers with initial user-level access to elevate privileges and install malware, as seen in privilege escalation chains where vulnerabilities like Dirty COW (CVE-2016-5195) enable memory corruption to overwrite critical files, indirectly amplifying risks by enabling easier root password guessing or modification for subsequent su exploitation. Such techniques are commonly documented in adversary playbooks for local credential access, underscoring su's role in broader system compromise scenarios.[26]
Mitigation and Best Practices
To mitigate the risks of unauthorized privilege escalation via the su command, administrators should restrict its invocation to members of the wheel group by editing /etc/group to include only trusted non-root users and configuring PAM in /etc/pam.d/su to require wheel group membership for su access.[27] This setup enforces the principle of least privilege, preventing arbitrary users from attempting root switches. Additionally, integrating PAM modules enables comprehensive logging of su attempts and supports two-factor authentication, such as through pam_duo or similar mechanisms, to verify user identity beyond passwords.[28][29] Safe usage habits further reduce exposure: opt for switching to specific non-root user accounts via su when administrative tasks do not require full root privileges, minimizing the scope of elevated access. Always invoke su with the -l option to load a complete login environment, which clears potentially malicious environment variables from the original session and initializes secure defaults. Limit elevated session durations by scripting timeouts or using tools like timeout, and explicitly log activities within the session using commands such as script to capture all input and output for auditing.[21] For broader system hardening, disable direct root logins over SSH by setting PermitRootLogin no in /etc/ssh/sshd_config and restarting the SSH service, forcing users to authenticate as non-root accounts before escalating via su or alternatives. Where feasible, transition to sudo for privileged operations, as it provides built-in auditing and granular command controls without a full user switch.[21] Effective monitoring involves configuring the auditd daemon to watch su invocations by adding rules like -a always,exit -F arch=b64 -S exec -k privileged to /etc/audit/rules.d/audit.rules, or relying on syslog for PAM-integrated logs; administrators should routinely review /var/log/auth.log for suspicious patterns, such as repeated failed su attempts from unusual sources.[30][31] Best practices for su have evolved significantly since 2010, with NIST SP 800-53 emphasizing minimal root exposure through controls like AC-6 (Least Privilege), which advocate restricting privileged commands to essential functions only. As of 2025, updated guidelines from frameworks like CIS benchmarks and vendor documentation recommend confining su processes using mandatory access controls, such as SELinux user mapping to confined roles (e.g., via semanage login -m user_u staff_u) or AppArmor profiles to limit su's file access and network capabilities, thereby containing potential exploits.[32][33][34]Alternatives
sudo
Sudo, short for "superuser do," is a program that enables a permitted user to execute commands as the superuser (root) or another user, as determined by a configurable security policy, while providing an audit trail of all actions taken.[35] Unlike traditional privilege escalation methods, sudo authenticates using the caller's own password rather than the target user's password, allowing administrators to delegate specific authorities without sharing sensitive credentials.[35] It has become the standard tool for managed privilege elevation in Unix-like systems, emphasizing security through fine-grained control and logging.[36] A primary distinction from su lies in sudo's support for granular permissions, where administrators can restrict users to specific commands—for instance, permitting execution of the apt package manager (/usr/bin/apt) while explicitly denying destructive operations like file removal (!/bin/rm)—rather than granting a full interactive shell.[37] By default, sudo does not invoke a complete shell environment, reducing the risk of unintended actions, and it implements session-based timeouts, typically caching credentials for 5 minutes to avoid repeated authentications during short tasks.[35] In contrast to su, which requires the root password for full access, sudo promotes the principle of least privilege by avoiding complete user switches.[35]
The basic syntax for sudo is sudo [options] command [arguments], enabling direct execution of a specified command with elevated privileges; for example, sudo apt update retrieves package lists as root.[35] To run a command as a non-root user, the -u option specifies the target, such as sudo -u www ls /var/www, which lists files as the web server user.[35] Additional options include -l to list a user's available privileges, -v to extend the credential timeout, and -i to simulate an initial login shell if needed, though this is used sparingly for security reasons.[35]
Configuration occurs primarily through the /etc/sudoers file, which defines rules for users, commands, and hosts, and must always be edited using the visudo command to prevent syntax errors and ensure atomic updates.[37] This file supports specifications for user aliases, groups (prefixed with %, e.g., %wheel ALL=(ALL) /usr/bin/apt), host lists (e.g., restricting access to certain machines or IP ranges), and command timeouts or no-password execution for trusted users.[37] Logging is enabled by default, capturing commands, arguments, and outcomes to /var/log/sudo or the system syslog, with optional I/O logging for session transcripts stored in directories like /var/log/sudo-io.[37] Sudo integrates with enterprise environments via LDAP for centralized policy management and supports a plugin architecture for custom policies and auditing, with enhancements in version 1.9.15 (released in 2023) improving plugin extensibility for advanced scenarios, including in 1.9.16p2 the ability to pass terminal device details to policy plugins without path resolution warnings.[37] As of 2025, the stable release 1.9.17p2 includes additional refinements to this handling.[38]
Sudo has been a standard component in major Linux distributions since the 1990s, originating from enhancements in 1991 that expanded its sudoers format for broader adoption.[36] Its design facilitates secure delegation in multi-user and enterprise settings, with auditing features like LDAP integration making it preferable for compliance-heavy environments over less controlled alternatives.[37]
Other Tools
doas is a lightweight privilege escalation tool originally developed for OpenBSD by Ted Unangst as a simpler and more secure alternative to sudo.[39] Introduced in OpenBSD 5.8 in October 2015, it emphasizes minimalism with a small codebase of approximately 3,000 lines of source code, compared to sudo's over 177,000 lines, reducing potential attack surfaces.[40][41] Configuration occurs via the doas.conf file, which uses straightforward rules to permit or deny commands for specific users, such as allowing a user to run package management tools without full root access.[42] The basic syntax isdoas <command>, for example, doas pkg install vim to install a package with elevated privileges.[43]
pkexec, part of the PolicyKit framework developed by freedesktop.org since around 2007, provides a mechanism for executing commands with elevated privileges in graphical environments.[44] It is particularly suited for desktop use cases, integrating with D-Bus to handle inter-process communication and prompt users for authentication via visual dialogs, such as password entry windows in GNOME or KDE.[45] The syntax follows pkexec <command>, enabling authorized users to run programs as root or another user, often triggered automatically by desktop applications needing temporary privileges.[44] PolicyKit's design allows fine-grained policy definitions through .policy files, focusing on authorization rather than full shell access.[46]
In comparisons, doas prioritizes speed and simplicity by avoiding complex features like sudo's session-based credential caching, which can persist authentication tokens and introduce risks if not managed; instead, doas requires re-authentication per invocation unless explicitly configured with a persist option, making it leaner for scripted or minimal setups.[41] pkexec, conversely, excels in graphical contexts with its D-Bus-driven prompting, offering user-friendly visual authentication that suits interactive desktop workflows but may add overhead in non-GUI scenarios.[47] Adoption trends show doas integrated natively in OpenBSD since version 5.8 and ported to Linux distributions, including as the opendoas package in Arch Linux's community repository since 2020, appealing to users seeking reduced complexity.[40][43] pkexec has been a standard component in GNOME since version 3 (around 2011) and in KDE Plasma environments throughout the 2010s, powering privilege escalations in tools like file managers and system settings.[48]
For niche applications, run0, introduced in systemd version 256 in April 2024, serves as an emerging tool for containerized or isolated privilege elevation, leveraging systemd's existing machinery without relying on traditional SUID binaries like su or sudo, thereby avoiding shell overhead and enhancing security in modern systemd-based systems.[49] It functions as an alias for systemd-run with elevated scope, prompting for confirmation via a simple terminal interface and changing the background color to indicate privileged mode, making it suitable for scripted or remote elevations in container environments.[50] These tools collectively address gaps in su's model by offering tailored alternatives for minimalism, graphical integration, and container-aware escalation in post-2020 Unix-like systems.[51]