# Linux Users and File Permissions

> Chapter 50 of the Courseiva A-PLUS-CORE-2 curriculum — https://courseiva.com/learn/a-plus-core-2/linux-users-permissions

**Official objective:** 1.6 — Operating Systems

## Introduction

Managing Linux users and file permissions is a core topic for the CompTIA A+ 220-1102 exam under Objective 1.6. Understanding how to manage user accounts, groups, and file permissions is essential for securing Linux systems and troubleshooting access issues. Expect 5-10% of exam questions to touch on user management, permission modes, and special permissions like SUID, SGID, and the sticky bit. Mastering these concepts will help you configure systems correctly and diagnose common problems.

## File Permissions as a Club with Three Bouncers

What if a private club had three bouncers named Owner, Group, and Others? Each bouncer checks a specific list of permissions for members: Read (R) means you can look at the guest list, Write (W) means you can add or remove names, and Execute (X) means you can enter the club. The Owner bouncer always checks first and has the highest authority. If you are the owner, you can override the other bouncers. The Group bouncer checks only if you belong to a certain group (like VIP members). The Others bouncer handles everyone else. Each bouncer has a clipboard with three checkboxes: R, W, X. If the checkbox is checked, you have that permission. For a directory (the club itself), the permissions work differently: Read lets you list the members inside, Write lets you create or delete members (like adding or removing people from the club), and Execute lets you enter the club (cd into it). The sticky bit is like a special rule: if the club has a sticky bit on a table, only the person who placed an item on that table can remove it, even if others have write permission. SUID and SGID are like temporary badges: when you run a program with SUID set, you temporarily become the owner of that program, like borrowing the owner's badge to perform a task. This analogy directly mirrors Linux permissions: each file/directory has an owner, group, and others, with read (4), write (2), and execute (1) permissions represented by octal numbers. The sticky bit (1) on directories prevents non-owners from deleting files, and SUID (4) / SGID (2) bits elevate privileges during execution.

## Core explanation

### Linux Users and Groups

Linux is a multi-user operating system. Each user has a unique user ID (UID) and belongs to one or more groups. Users are stored in `/etc/passwd`, groups in `/etc/group`, and passwords (hashed) in `/etc/shadow`. The root user (UID 0) has unlimited privileges.

- **User types:** root (administrator), system users (for services), regular users.
- **Group types:** primary group (default group for files the user creates) and supplementary groups (additional permissions).

### File Permissions Basics

Every file and directory has an owner and a group. Permissions are defined for three classes: user (owner), group, and others. Each class has three permissions: read (r), write (w), and execute (x). For a file, read allows viewing contents, write allows modifying, execute allows running as a program. For a directory, read allows listing contents, write allows creating/deleting files, execute allows entering (cd) and accessing files by name.

Permissions are often represented in symbolic form (e.g., `-rwxr-xr--`) or octal (e.g., 755). The first character indicates type: `-` for file, `d` for directory, `l` for symlink, etc.

### Octal Representation

Each permission set maps to a 3-bit octal digit:
- r = 4
- w = 2
- x = 1
- Sum gives the octal value: e.g., rwx = 4+2+1 = 7, r-x = 4+0+1 = 5, r-- = 4+0+0 = 4.

Common modes:
- 755: owner rwx, group r-x, others r-x (typical for executables and directories)
- 644: owner rw-, group r--, others r-- (typical for files)
- 700: owner rwx, group ---, others --- (private files)

### Changing Permissions: `chmod`

Use `chmod` to change permissions. Symbolic mode: `chmod u+x file` adds execute for user. `chmod g-w file` removes write for group. `chmod o=r file` sets others to read-only. `chmod a+x file` adds execute for all.

Octal mode: `chmod 755 file` sets permissions directly. `chmod -R` applies recursively.

### Changing Ownership: `chown` and `chgrp`

`chown` changes owner and/or group: `chown user:group file` changes both. `chown user file` changes owner only. `chgrp group file` changes group only. Only root can change owner; group can be changed by owner if they are a member of the target group.

### Special Permissions: SUID, SGID, Sticky Bit

- **SUID (Set User ID):** When set on an executable file, the process runs with the privileges of the file owner, not the user who executed it. Represented as `s` in the owner's execute position (e.g., `-rwsr-xr-x`). Octal: 4xxx. Example: `/usr/bin/passwd` has SUID set, allowing non-root users to change their password (which updates `/etc/shadow`).
- **SGID (Set Group ID):** On a file, the process runs with the file's group privileges. On a directory, new files inherit the directory's group. Represented as `s` in the group's execute position. Octal: 2xxx. Example: `/usr/bin/write` has SGID.
- **Sticky Bit:** Primarily used on directories (e.g., `/tmp`). Only the file owner, directory owner, or root can delete or rename files within the directory, even if others have write permission. Represented as `t` in others' execute position (e.g., `drwxrwxrwt`). Octal: 1xxx.

### Viewing Permissions: `ls -l`

Output example:
```
-rwxr-xr-- 1 alice devops 1024 Mar 10 10:00 script.sh
drwxr-xr-x 2 alice devops 4096 Mar 10 10:00 mydir
```
- First column: type and permissions (10 chars).
- Second: number of hard links.
- Third: owner.
- Fourth: group.
- Fifth: size in bytes.
- Sixth: modification time.
- Seventh: name.

### User Management Commands

- `useradd` / `adduser`: Create user. `useradd -m -G group1,group2 username` creates home directory and adds to supplementary groups. Default files: `/etc/default/useradd`, `/etc/login.defs`.
- `usermod`: Modify user. `usermod -aG group username` appends to group (avoid `-G` alone as it overwrites).
- `userdel`: Delete user. `userdel -r username` removes home directory and mail spool.
- `passwd`: Change password. `passwd username` (as root).
- `groupadd` / `groupdel`: Create/delete groups.
- `groups username`: List groups for a user.
- `id username`: Show UID, GID, and groups.

### Default Permissions: `umask`

`umask` subtracts permissions from the base (666 for files, 777 for directories). Default umask is often 022, resulting in 644 for files (666-022=644) and 755 for directories (777-022=755). To make files private: `umask 077` gives 600. `umask -S` shows symbolic representation.

### ACLs (Access Control Lists)

For finer-grained control, ACLs allow setting permissions for specific users or groups beyond owner/group/others. `getfacl` to view, `setfacl -m u:username:rwx file` to set. `setfacl -x u:username file` removes. Requires `acl` package and filesystem mounted with `acl` option.

### Interaction with Related Technologies

- **SELinux/AppArmor:** These are mandatory access control (MAC) systems that work alongside traditional permissions. Even if traditional permissions allow access, SELinux can deny it based on security contexts.
- **sudo:** Allows users to run commands as root or other users. Configured in `/etc/sudoers`. Uses permissions to execute, but access is controlled by policy, not file permissions.
- **Filesystem mounting options:** Options like `nosuid`, `nodev`, `noexec` can override permission behavior. For example, `mount -o nosuid /dev/sda1 /mnt` disables SUID/SGID on that filesystem.

### Common Commands Summary

- `ls -l` : view permissions
- `chmod [ugoa][+-=][rwx] file` : change permissions
- `chmod 755 file` : octal change
- `chown user:group file` : change owner/group
- `chgrp group file` : change group
- `umask` : view/set default permissions
- `id`, `groups` : user info
- `useradd`, `usermod`, `userdel` : user management
- `groupadd`, `groupmod`, `groupdel` : group management
- `getfacl`, `setfacl` : ACL management

### Troubleshooting Permission Issues

- **Permission denied:** Check file permissions, ownership, and group membership. Use `ls -l` and `id`.
- **Cannot execute:** Ensure execute bit is set for the user (`chmod +x`).
- **Cannot write to directory:** Check directory write permission and sticky bit.
- **SUID not working:** Verify SUID bit is set (`ls -l` shows `s`). Check if filesystem is mounted with `nosuid`.
- **SGID not inheriting:** Ensure SGID is set on directory (`chmod g+s`). New files will inherit group.

### Security Considerations

- Avoid setting SUID on custom scripts; use `sudo` instead.
- Use the sticky bit on shared directories like `/tmp` to prevent users from deleting others' files.
- Regularly audit SUID/SGID files with `find / -perm /6000 -type f`.
- Set restrictive umask for sensitive environments (e.g., 077).

## Real-world context

In a web hosting company, Linux user and file permissions are critical for isolating customer websites. Each customer has a separate user account and a home directory. The web server (e.g., Apache) runs as a specific user (e.g., www-data). To allow the web server to serve files, the customer's directories must have read and execute permissions for the web server user or group. Typically, the web server is added to a group, and directories are set with 755 permissions or ACLs. A common misconfiguration is setting permissions to 777, which exposes files to all users. Instead, use ACLs to grant the web server user specific access: `setfacl -m u:www-data:rx /home/customer/public_html`. This maintains security while enabling functionality.

In a university lab environment, multiple students need to collaborate on projects without interfering with each other. The instructor creates a shared directory with SGID and sticky bit. For example, `/lab/cs101` has group 'cs101-students' and permissions 2775 (SGID + rwx for owner and group, rx for others). The sticky bit is set to prevent students from deleting each other's files. Students are added to the 'cs101-students' group. When a student creates a file, it inherits the group and can be read by others. The instructor uses `chmod g+s` and `chmod +t` on the directory. This setup works well for up to 100 students; beyond that, ACLs or more sophisticated permission schemes may be needed.

In a DevOps pipeline, CI/CD agents run as a service user (e.g., jenkins). The agent needs to access source code repositories, build artifacts, and deploy to servers. File permissions must allow the jenkins user to read source code and write to build directories. Using groups simplifies management: add jenkins to a 'devops' group, set SGID on build directories, and use umask 002 to ensure group writability. A common pitfall is forgetting to set SGID, so new directories created by the agent have the wrong group, causing build failures. Regular auditing with `find /var/lib/jenkins -not -group devops` helps catch such issues. Performance is rarely a concern, but checking ACLs on large filesystems can be slow; use `getfacl -R` sparingly.

## Exam focus

The CompTIA A+ 220-1102 exam tests Linux users and file permissions under Objective 1.6 (Given a scenario, configure and use Linux). You must know:
- How to view permissions with `ls -l` and interpret the 10-character string.
- How to change permissions with `chmod` (both symbolic and octal).
- How to change ownership with `chown` and `chgrp`.
- The meaning and usage of SUID (4), SGID (2), and sticky bit (1).
- User management commands: `useradd`, `usermod`, `userdel`, `passwd`, `groupadd`, `groupdel`.
- The purpose of `/etc/passwd`, `/etc/shadow`, `/etc/group`.
- Default permissions and `umask`.

Common wrong answers:
1. **Confusing chmod and chown:** Candidates often think `chmod` changes ownership. Wrong: `chmod` changes permissions; `chown` changes owner/group.
2. **Misinterpreting octal permissions:** Adding instead of subtracting. For example, thinking 666 means full access (it's read/write for all, no execute). Actually, 777 is full access.
3. **SUID vs SGID:** Thinking SUID sets group instead of user. Remember: SUID = user (owner), SGID = group.
4. **Sticky bit on files:** The sticky bit is rarely used on files today; it's primarily for directories. On files, it historically meant keep in memory, but modern Linux ignores it.

Specific numbers and terms:
- Octal: r=4, w=2, x=1.
- Common modes: 755 (directories), 644 (files), 700 (private), 777 (open).
- SUID octal: 4xxx (e.g., 4755).
- SGID octal: 2xxx (e.g., 2755).
- Sticky bit octal: 1xxx (e.g., 1777 for /tmp).
- umask default: 022 (files 644, dirs 755).

Edge cases:
- **SUID on shell scripts:** Many systems ignore SUID on scripts for security reasons; it only works on binary executables.
- **umask and file creation:** `umask` is subtracted from base permissions, not added. A umask of 022 results in 644 for files (666-022=644) and 755 for directories (777-022=755).
- **Symbolic chmod with =:** `chmod o=r file` sets others to read-only, removing any existing execute/write bits.

To eliminate wrong answers, focus on the underlying mechanism: permissions are checked in order (owner, group, others). If the owner matches, only owner permissions apply; group and others are ignored. If owner doesn't match but group does, group permissions apply; others are ignored. This is critical for troubleshooting 'permission denied' even when group permissions seem correct.

## Step by step

1. **Create a New User with Specific Groups** — Use `useradd -m -G users,developers john` to create user 'john' with home directory and add to supplementary groups 'users' and 'developers'. The `-m` flag creates the home directory `/home/john`. Without `-G`, the user is only added to their own primary group (usually same as username). The command updates `/etc/passwd`, `/etc/shadow`, `/etc/group`, and creates `/home/john` with default files from `/etc/skel`. Verify with `id john` and `groups john`.
2. **Set a Password for the User** — Run `passwd john` as root. It prompts for a new password and updates `/etc/shadow`. The password is hashed (typically using SHA-512). The shadow file stores the hash, last change date, minimum/maximum age, warning period, and inactivity period. Default password aging parameters are in `/etc/login.defs`. After setting, the user can log in.
3. **Create a Directory and Set Permissions for Collaboration** — Create `/project` with `sudo mkdir /project`. Set group ownership to 'developers': `sudo chown :developers /project`. Set permissions so owner and group have full access: `sudo chmod 770 /project`. This allows the owner (root) and group members (developers) to read, write, and execute (enter) the directory. Others have no access. Verify with `ls -ld /project`.
4. **Apply SGID on the Directory to Inherit Group** — Set SGID with `sudo chmod g+s /project`. Now any new file or subdirectory created inside `/project` will inherit the group 'developers' instead of the creator's primary group. This ensures all team members can access files. Verify with `ls -ld /project`; the group execute position shows `s` instead of `x`. Create a test file to confirm inheritance.
5. **Set Sticky Bit on Shared Directory** — On a shared writable directory like `/shared`, set the sticky bit: `sudo chmod +t /shared`. Now only the file owner, directory owner, or root can delete or rename files within `/shared`, even if others have write permission. This prevents users from deleting each other's files. Verify with `ls -ld /shared`; the others execute position shows `t`. Common on `/tmp`.
6. **Test Permissions by Switching Users** — Use `su - john` to switch to user 'john'. Try to create, read, and delete files in `/project` and `/shared`. Use `touch`, `ls`, `rm` commands. Observe permission denials. For example, if 'john' is in 'developers', he can write to `/project`; if not, he gets 'Permission denied'. This verifies group membership and permission settings.

## Comparisons

### Symbolic chmod (e.g., u+x) vs Octal chmod (e.g., 755)

**Symbolic chmod (e.g., u+x):**
- More intuitive for adding/removing specific permissions.
- Does not require calculating sums.
- Can be applied recursively with -R.
- Easier to learn for beginners.
- Less error-prone when changing one class.

**Octal chmod (e.g., 755):**
- Sets all permissions explicitly at once.
- Requires knowing octal values (r=4, w=2, x=1).
- Common modes are memorized (755, 644).
- More concise for scripts and automation.
- Risk of accidentally removing all permissions if wrong value used.

## Common misconceptions

- **Misconception:** chmod 777 gives full access to everyone, including execute on files. **Reality:** 777 gives rwx to owner, group, and others. For files, execute allows running as a program. For directories, execute allows entering. 777 is insecure and rarely needed; prefer 755 or 700.
- **Misconception:** The sticky bit prevents anyone except root from deleting files. **Reality:** The sticky bit on a directory allows the file owner, directory owner, or root to delete/rename files. Other users with write permission cannot delete files they don't own.
- **Misconception:** SUID allows a user to run a program as root regardless of permissions. **Reality:** SUID runs the program with the file owner's privileges, not necessarily root. If the file owner is root, then it runs as root. If owner is a regular user, it runs as that user.
- **Misconception:** umask adds permissions to the default. **Reality:** umask subtracts permissions from the base (666 for files, 777 for directories). A umask of 022 results in 644 for files (666-022=644) and 755 for directories (777-022=755).
- **Misconception:** You can change a file's owner without being root. **Reality:** Only root can change the owner of a file. Regular users can change the group of files they own, but only to groups they belong to. Use `chown` as root or via sudo.

## Key takeaways

- File permissions are defined for owner, group, and others, each with read (4), write (2), execute (1).
- Use `ls -l` to view permissions; the first character indicates type (- file, d directory).
- `chmod` changes permissions; `chown` changes owner; `chgrp` changes group.
- SUID (4) allows execution with owner's privileges; SGID (2) on directories inherits group; sticky bit (1) restricts deletion.
- Default umask is usually 022, resulting in 644 for files and 755 for directories.
- User management commands: `useradd`, `usermod`, `userdel`, `passwd`, `groupadd`, `groupdel`.
- Only root can change file owner; group can be changed by owner if member of target group.
- ACLs provide finer-grained control beyond owner/group/others.
- The sticky bit on /tmp prevents users from deleting each other's files.
- SUID on shell scripts is often ignored for security reasons.
- Permissions are checked in order: owner, group, others; first match applies.
- `id` and `groups` commands show user and group memberships for troubleshooting.

## FAQ

**How do I change file permissions recursively in Linux?**

Use `chmod -R` followed by the permission mode and directory. For example, `chmod -R 755 /path/to/dir` changes all files and subdirectories to 755. Be careful: this applies the same mode to both files and directories, which may not be desired (e.g., files should be 644). To differentiate, use `find` with `-type f` and `-type d`. Example: `find /path -type f -exec chmod 644 {} \;` and `find /path -type d -exec chmod 755 {} \;`.

**What is the difference between chmod and chown?**

`chmod` changes the permissions (read, write, execute) of a file or directory. `chown` changes the owner and/or group. For example, `chmod 755 file` sets permissions; `chown alice:devops file` changes owner to alice and group to devops. They are often used together to set both ownership and permissions.

**How do I set SUID on a file?**

Use `chmod u+s filename` or octal `chmod 4xxx filename` (e.g., `chmod 4755 filename`). The SUID bit appears as 's' in the owner's execute position. Only set SUID on trusted binaries; avoid on scripts. Verify with `ls -l`; you should see `-rwsr-xr-x`.

**What does the sticky bit do?**

The sticky bit on a directory restricts deletion: only the file owner, directory owner, or root can delete or rename files within that directory. It is commonly set on `/tmp` (permissions 1777). Set it with `chmod +t dirname` or octal `chmod 1xxx dirname`. View with `ls -ld`; the others execute position shows 't'.

**How do I add a user to a group in Linux?**

Use `usermod -aG groupname username`. The `-a` (append) flag is crucial to avoid removing the user from other groups. For example, `usermod -aG sudo john` adds john to the sudo group. Verify with `groups john` or `id john`. Alternatively, use `gpasswd -a username groupname`.

**What is umask and how do I set it?**

`umask` sets default permissions for newly created files and directories. It subtracts from the base (666 for files, 777 for directories). A umask of 022 results in 644 for files and 755 for directories. Set it temporarily with `umask 077` (makes files 600, dirs 700). To make permanent, add to `~/.bashrc` or `/etc/profile`.

**How do I view ACLs on a file?**

Use `getfacl filename`. It displays the current ACL entries, including owner, group, and any additional users/groups with specific permissions. Example output: `# file: test.txt # owner: alice # group: devops user::rw- user:bob:r-- group::r-- mask::r-- other::r--`.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/a-plus-core-2/linux-users-permissions
