Hubbry Logo
Su (Unix)Su (Unix)Main
Open search
Su (Unix)
Community hub
Su (Unix)
logo
7 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Su (Unix)
Su (Unix)
from Wikipedia
su
Original authors
DeveloperAT&T Bell Laboratories
Initial releaseNovember 3, 1971; 53 years ago (1971-11-03)
Operating systemUnix and Unix-like
TypeCommand

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]

References

[edit]
[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
In Unix-like operating systems, su (short for "substitute user") is a command-line utility that enables a user to switch to another user account, typically the superuser known as , by changing the effective user ID (UID) and group ID (GID) of the current process and invoking a new shell session. Originating in of Unix developed at Bell Laboratories in 1971, su was documented in the Fourth Edition of the Unix Programmer's Manual in 1973, where it was described as a tool to temporarily become a privileged user by entering the password and executing a shell with superuser privileges. When invoked without arguments, su defaults to switching to the account, prompting for the password unless the invoking user already has sufficient privileges; successful execution changes the shell prompt to a hash (#) symbol to indicate elevated responsibilities. The command supports various options to customize its behavior, such as the - or --login to simulate a full by resetting the environment variables, changing the to the target user's home, and sourcing scripts for a more isolated session, which is recommended for consistency with the target user's setup. Common options include -c to execute a specific command as the target user without starting an interactive shell; in implementations, additional options like --preserve-environment retain the current environment variables, and --pty allocates a pseudo-terminal for the session. and session management are handled via modules in many modern implementations, with system-specific configuration files controlling aspects such as prompts and resource limits (e.g., PAM and /etc/pam.d/su in ). Unlike su, which requires the target user's (often root's) and grants full account access, the related command allows granular without full session switching, though su remains a core utility in systems like , AIX, and Solaris for administrative tasks. Although not part of the standard, su implementations vary across Unix variants but maintain core functionality for switching users since its .

Overview

Definition and Purpose

The su command, short for "substitute user," is a in 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. This functionality supports secure user switching without requiring a full logout and process, preserving the session's continuity while altering the security context. Its primary purpose is to facilitate temporary elevation of privileges, most commonly to the (root) account, for performing system administration tasks that demand heightened access levels, such as software installation or modifications. 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. When invoked without specifying a target user, su defaults to switching to the root user, prompting for the root to authenticate the change. A key aspect of su's operation is that it does not alter the current or fully emulate a complete environment for the target user; instead, it retains the invoking user's directory and most environment variables, unless the option is used to simulate a fresh shell. This design choice ensures seamless integration into ongoing sessions while avoiding unintended environmental disruptions. Originating as a core command in early Unix systems tailored for multi-user environments, su embodies of least privilege by enabling brief, authenticated privilege escalations rather than encouraging persistent logins, thereby reducing exposure to security risks in shared computing setups.

Basic Functionality

The su 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 access. Upon successful , 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 storage and validation, often facilitated by Pluggable Authentication Modules (PAM) in contemporary systems. Following authentication, su invokes a new shell —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 switch occurs via system calls like and setgid(), enabling the new shell to operate with the target's permissions for file access and . The original session's and are preserved, ensuring the substituted environment remains part of the caller's terminal session without disrupting controlling terminal associations. 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. If no command is specified as an argument, su launches an interactive shell under the target user's , 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. 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 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.

History

Origins in Early Unix

The su command was introduced on November 3, 1971, as part of Unix developed at AT&T Bell Laboratories. Authored by and , 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. This initial release ran on the PDP-11/20 minicomputer, marking Unix's transition from earlier experiments on the PDP-7. Designed for multi-user environments, su addressed the need for secure transitions between user accounts without requiring system reboots, facilitating collaborative research and development at . 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 . It integrated seamlessly into the core command set of , appearing alongside essentials like ls for directory listings and cat for file concatenation. 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). 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.

Evolution and Standardization

The su 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. 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. While su follows common Unix conventions for syntax, default root switching, and environment handling, it is not part of the standard. 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 package to align with -specific developments and reduce overlap in utility distributions. 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 . implementations, particularly through the shadow-utils package originating in the early , enhanced su with shadowed password support for better isolation, followed by Pluggable Authentication Modules (PAM) integration starting with Linux-PAM 0.49 in 1997, enabling flexible authentication backends like LDAP or . 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. 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. 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.

Usage

Command Syntax

The basic syntax of the su 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 in systems) if omitted, and any trailing argument... are passed to the invoked shell or command. When invoked without arguments, su starts an interactive login shell for the target user, initializing the environment accordingly. Upon execution, su prompts for the target user's password unless the invoking process already holds appropriate privileges (such as running as ), and authentication fails if the provided credentials are incorrect, resulting in an and termination without switching users; failed attempts are typically logged in system files like /var/log/btmp on supported platforms. 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. 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 (or 128 plus the signal number if terminated by a signal) to the . This behavior is specified in the (LSB) Core specification, though implementations like those in may include minor variations documented in their respective manual pages. 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"

where 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.

Common Options and Examples

The su 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. 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. 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). 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. 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. 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. 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. 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. On systems like , access to su for becoming is restricted to members of the "wheel" group, a security measure that limits elevation to authorized administrative users; non-members attempting su root will receive an authentication failure despite providing the correct password. In contrast, many distributions configure this restriction via Pluggable Authentication Modules (PAM), where wheel group enforcement is optional and often supplemented or replaced by tools like for finer-grained control, though su itself does not enforce it by default. 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. Conversely, the --login option fully reinitializes the environment to mimic a fresh , clearing potentially insecure variables and establishing a secure baseline, as implemented in versions up to recent releases. This distinction ensures predictable behavior in scripted or multi-user setups.

Security Considerations

Potential Risks

The su 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 or system instability. This lack of command-specific restrictions heightens the risk of both accidental damage and deliberate misuse by compromised user accounts. 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. 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. 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 activation or unintended command substitution. 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 by injecting commands into the input stream. 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. 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. Abuse of su facilitates persistent backdoors by allowing attackers with initial user-level access to elevate privileges and install , as seen in privilege escalation chains where vulnerabilities like (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.

Mitigation and Best Practices

To mitigate the risks of unauthorized via the su command, administrators should restrict its invocation to members of the group by /etc/group to include only trusted non-root users and configuring PAM in /etc/pam.d/ to require group membership for su access. 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 , such as through pam_duo or similar mechanisms, to verify user identity beyond passwords. 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 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. 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 for privileged operations, as it provides built-in auditing and granular command controls without a full user switch. 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 for PAM-integrated logs; administrators should routinely review /var/log/auth.log for suspicious patterns, such as repeated failed su attempts from unusual sources. 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 profiles to limit su's file access and network capabilities, thereby containing potential exploits.

Alternatives

sudo

Sudo, short for "superuser do," is a program that enables a permitted user to execute commands as the (root) or another user, as determined by a configurable , while providing an of all actions taken. Unlike traditional 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. It has become the standard tool for managed privilege elevation in Unix-like systems, emphasizing security through fine-grained control and logging. 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. 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. In contrast to su, which requires the root password for full access, sudo promotes the principle of least privilege by avoiding complete user switches. 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. 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. 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. 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. 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. is enabled by default, capturing commands, arguments, and outcomes to /var/log/sudo or the system , with optional I/O logging for session transcripts stored in directories like /var/log/sudo-io. 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. As of 2025, the stable release 1.9.17p2 includes additional refinements to this handling. Sudo has been a standard component in major distributions since the 1990s, originating from enhancements in 1991 that expanded its sudoers format for broader adoption. 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.

Other Tools

is a lightweight tool originally developed for by Ted Unangst as a simpler and more secure alternative to . Introduced in OpenBSD 5.8 in October 2015, it emphasizes minimalism with a small codebase of approximately 3,000 lines of , compared to sudo's over 177,000 lines, reducing potential attack surfaces. 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 access. The basic is doas <command>, for example, doas pkg install vim to install a package with elevated privileges. pkexec, part of the PolicyKit framework developed by since around 2007, provides a mechanism for executing commands with elevated privileges in graphical environments. It is particularly suited for desktop use cases, integrating with to handle and prompt users for via visual dialogs, such as password entry windows in or . The syntax follows pkexec <command>, enabling authorized users to run programs as or another user, often triggered automatically by desktop applications needing temporary privileges. PolicyKit's design allows fine-grained policy definitions through .policy files, focusing on authorization rather than full shell access. In comparisons, doas prioritizes speed and simplicity by avoiding complex features like sudo's session-based credential caching, which can persist 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. pkexec, conversely, excels in graphical contexts with its D-Bus-driven prompting, offering user-friendly visual that suits interactive desktop workflows but may add overhead in non-GUI scenarios. Adoption trends show integrated natively in since version 5.8 and ported to distributions, including as the opendoas package in Arch Linux's community repository since 2020, appealing to users seeking reduced complexity. pkexec has been a standard component in since version 3 (around 2011) and in Plasma environments throughout the 2010s, powering privilege escalations in tools like file managers and . For niche applications, run0, introduced in systemd version 256 in April 2024, serves as an emerging tool for containerized or isolated privilege elevation, leveraging 's existing machinery without relying on traditional SUID binaries like su or , thereby avoiding shell overhead and enhancing in modern -based systems. 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 environments. These tools collectively address gaps in su's model by offering tailored alternatives for , graphical integration, and container-aware escalation in post-2020 systems.

References

Add your contribution
Related Hubs
User Avatar
No comments yet.