SUID and SGID are powerful tools used when a normal user needs "temporary" higher privileges to perform a specific task. Here is how they are used in practical scenarios:
1. Using SUID (Set User ID)
Purpose: Allows a user to run a file with the permissions of the file owner.
- Common Example: The
passwdcommand.
When you change your password, the system needs to write to/etc/shadow, a file owned byrootthat normal users cannot edit.
If you check its permissions:ls -l /usr/bin/passwd, you will see:
-rwsr-xr-x
Thesmeans that when you runpasswd, the system treats you as therootuser for that specific task, allowing the password update to succeed. - How to set it:
chmod u+s filename
2. Using SGID (Set Group ID)
Purpose: This has two main uses depending on whether it's applied to a file or a directory.
- On a File: The process runs with the privileges of the file's group.
- On a Directory (Most common use): Any new file created inside that directory will automatically inherit the Group ID of the directory, rather than the group of the user who created it.
- Use Case: Collaborative folders. If a team shares a directory, you set SGID on it so that every file anyone creates is automatically accessible to the whole team's group.
- How to set it:
chmod g+s folder_name
3. Practical Example: Creating a Shared Repo
If you wanted to create a folder where a group named developers can all work on the same files:
- Change the folder's group:
chgrp developers project_folder - Set SGID:
chmod g+s project_folder - Now, when user "Alice" creates a file inside, it will belong to the
developersgroup automatically, allowing user "Bob" to edit it.
⚠️ A Note on Safety
SUID/SGID should be used very carefully:
- Security Risk: If a script with SUID owned by
roothas a bug, a regular user could exploit it to gain full control of the system. - Scripts: On most modern Linux systems (like Ubuntu), SUID is ignored for shell scripts (like your
script.sh) for security reasons; it usually only works on compiled binary programs (likepasswdorsudo).
Does that help clarify how these special permissions work? Feel free to experiment with them in your ~/project directory!