> ## Documentation Index
> Fetch the complete documentation index at: https://resources.devweekends.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Linux Permissions & Users

> Master Linux file permissions and user management

# Linux Permissions & Users

Understanding Linux permissions is crucial for security and system administration. Think of permissions like the keys and locks in an office building: every room (file) has a lock, every person (user) carries certain keys, and the building manager (root) has the master key. Getting this wrong means either locking yourself out or leaving the vault wide open.

***

## User Management

Every process in Linux runs as a specific user. This determines what files it can read, write, and execute. There is no such thing as an "anonymous" action in Linux -- everything traces back to a user.

```bash theme={null}
# View current user -- the identity your shell session is running as
whoami

# View all users on the system
# Each line follows the format: username:password:UID:GID:comment:home:shell
# The password field shows 'x' because actual hashes live in /etc/shadow
cat /etc/passwd

# Add a new user (creates home directory, sets default shell)
# adduser is the interactive, user-friendly wrapper around useradd
sudo adduser username

# useradd is the low-level tool -- you must specify options manually
# Use this in scripts where you need precise control
sudo useradd -m -s /bin/bash -G docker,sudo username

# Delete user and optionally their home directory
sudo deluser username
sudo deluser --remove-home username  # Also removes /home/username

# Switch to another user's session (the dash loads their environment)
su - username
# Without the dash, you keep your own environment variables -- a common gotcha
su username

# Switch to root (use sparingly -- prefer sudo for individual commands)
sudo su
```

### Users and Groups

Groups let you manage permissions for multiple users at once. Instead of granting file access to ten developers individually, you add them all to a `dev` group and grant access to the group.

```bash theme={null}
# See which groups your user belongs to
groups

# See groups for a specific user
groups username

# Create a new group
sudo groupadd developers

# Add a user to a group (-a means append, without it you REPLACE all groups)
sudo usermod -aG developers username

# Remove a user from a group
sudo gpasswd -d username developers

# View group membership details
cat /etc/group
```

<Warning>
  **Always use `-aG` (append to groups), not just `-G`.** Running `usermod -G developers username` without the `-a` flag removes the user from every other group, potentially locking them out of sudo access.
</Warning>

***

## File Permissions

Every file and directory in Linux has three sets of permissions for three audiences: the **owner**, the **group**, and **everyone else**.

```bash theme={null}
# View permissions with ls -l
ls -l
# Example output:
# -rw-r--r-- 1 alice developers 4096 Mar 15 10:00 report.txt
#  │││ │││ │││  │  │      │        │     │           │
#  │││ │││ │││  │  │      │        │     │           └─ Filename
#  │││ │││ │││  │  │      │        │     └─ Last modified date
#  │││ │││ │││  │  │      │        └─ File size in bytes
#  │││ │││ │││  │  │      └─ Group owner
#  │││ │││ │││  │  └─ User owner
#  │││ │││ │││  └─ Number of hard links
#  │││ │││ └└└─ Others: r-- (read only)
#  │││ └└└───── Group:  r-- (read only)
#  └└└───────── Owner:  rw- (read + write, no execute)
```

### The Permission Model

Each permission has a numeric value. You add them up to set permissions:

| Permission | Letter | Number | Meaning                                           |
| ---------- | ------ | ------ | ------------------------------------------------- |
| Read       | r      | 4      | View file contents / list directory               |
| Write      | w      | 2      | Modify file / create or delete files in directory |
| Execute    | x      | 1      | Run file as program / enter directory with cd     |

```bash theme={null}
# Numeric (octal) mode -- set all three audiences at once
chmod 755 script.sh   # rwxr-xr-x  Owner: full, Group: read+execute, Others: read+execute
chmod 644 config.txt  # rw-r--r--  Owner: read+write, everyone else: read only
chmod 600 secret.key  # rw-------  Owner only, nobody else can even read it
chmod 700 private/    # rwx------  Only owner can enter this directory

# Symbolic mode -- modify specific permissions without affecting others
chmod u+x script.sh   # Add execute for owner (u=user/owner)
chmod g-w file.txt    # Remove write for group (g=group)
chmod o-r secret.txt  # Remove read for others (o=others)
chmod a+r public.txt  # Add read for all (a=all)
```

<Tip>
  **Practical rule of thumb**: Scripts and binaries get `755` (everyone can run, only owner can edit). Config files get `644` (everyone can read, only owner can edit). Secrets and keys get `600` (owner only). Private directories get `700`.
</Tip>

### Changing Ownership

```bash theme={null}
# Change file owner
chown alice file.txt

# Change file owner and group at the same time
chown alice:developers file.txt

# Change recursively for an entire directory tree
chown -R alice:developers project/

# Change only the group (useful when you just need group access)
chgrp developers file.txt
```

### Special Permissions

Beyond the basic rwx, Linux has three special permission bits that come up in interviews and production troubleshooting. Think of these as special-purpose locks with unusual properties -- they solve problems that regular permissions cannot.

```bash theme={null}
# SUID (Set User ID) -- file runs as the file OWNER, not the user who launched it
# Analogy: A valet key that starts the car as if the owner is driving, even when someone
# else turns the key. This is how /usr/bin/passwd can modify /etc/shadow (owned by root)
# even when run by a normal user -- the binary has SUID set and is owned by root.
chmod u+s /usr/local/bin/special-tool
ls -l /usr/bin/passwd
# -rwsr-xr-x  (notice the 's' in owner execute position -- 's' means SUID + execute)
# If you see 'S' (capital), it means SUID is set but execute is NOT -- usually a mistake

# SGID (Set Group ID) -- on directories, new files inherit the DIRECTORY'S group
# Without SGID, new files inherit the creator's primary group, which breaks shared folders.
# Analogy: A shared team folder where everything automatically gets stamped with the team
# name, regardless of who put it there.
chmod g+s /shared/project/
# Now files created inside inherit the 'project' group automatically
# Without this, Alice's files belong to group 'alice' and Bob cannot read them

# Sticky bit -- on directories, only file OWNERS can delete their own files
# Without sticky bit, anyone with write permission to a directory can delete any file in it.
# Analogy: A shared bulletin board where everyone can post, but only you can remove your own notes.
chmod +t /shared/uploads/
ls -ld /tmp
# drwxrwxrwt  (notice the 't' in others execute position)
# /tmp is the canonical example: world-writable, but you cannot delete other users' temp files
```

<Warning>
  **Security warning about SUID**: SUID binaries are a common attack vector. If an attacker can overwrite a SUID-root binary (or find a vulnerability in one), they get root access. Audit your SUID files periodically with `find / -type f -perm -u+s 2>/dev/null` and remove SUID from any binary that does not need it. Never set SUID on shell scripts -- it is a well-known security hole because the script can be manipulated between the kernel checking SUID and the interpreter executing it.
</Warning>

***

## Sudo and Root Access

The `root` user (UID 0) can do anything on the system -- bypass all permission checks, kill any process, read any file. This power is dangerous. `sudo` lets you run individual commands as root without staying logged in as root.

```bash theme={null}
# Run a single command with root privileges
sudo apt update

# Edit the sudoers file safely (validates syntax before saving)
# NEVER edit /etc/sudoers directly with a text editor -- a syntax error locks you out
sudo visudo

# Open a root shell (use this sparingly and exit when done)
sudo -i

# Run a command as a different user (not just root)
sudo -u postgres psql

# Check what sudo permissions you have
sudo -l
```

### Sudoers Configuration

```bash theme={null}
# In /etc/sudoers (always edit with visudo):

# Allow user to run all commands as root
username ALL=(ALL:ALL) ALL

# Allow user to restart nginx without a password (common for deploy scripts)
deployer ALL=(ALL) NOPASSWD: /bin/systemctl restart nginx

# Allow an entire group to use sudo
%developers ALL=(ALL:ALL) ALL
```

<Warning>
  **Production tip**: Grant the minimum sudo access needed. `NOPASSWD: ALL` on a service account is a security incident waiting to happen. Scope it to specific commands like `/bin/systemctl restart myapp`.
</Warning>

***

## Common Permission Scenarios

### Scenario 1: Shared Project Directory

```bash theme={null}
# Create a shared directory where the 'developers' group can collaborate
sudo mkdir /opt/project
sudo chown root:developers /opt/project
sudo chmod 2775 /opt/project
# 2 = SGID (new files inherit group), 775 = owner+group full, others read+execute

# Now any developer can create files, and all files belong to the 'developers' group
```

### Scenario 2: Securing SSH Keys

```bash theme={null}
# SSH is strict about permissions -- it refuses to use keys with lax permissions
chmod 700 ~/.ssh           # Only you can enter the directory
chmod 600 ~/.ssh/id_rsa    # Private key: owner read+write only
chmod 644 ~/.ssh/id_rsa.pub  # Public key: anyone can read
chmod 600 ~/.ssh/authorized_keys  # Controls who can SSH into your account
```

### Scenario 3: Web Server Files

```bash theme={null}
# Web files owned by deploy user, readable by web server group
sudo chown -R deploy:www-data /var/www/mysite
sudo find /var/www/mysite -type d -exec chmod 755 {} \;  # Directories: enter + list
sudo find /var/www/mysite -type f -exec chmod 644 {} \;  # Files: read only
```

***

## Key Takeaways

* Every file has an owner, a group, and permissions for owner/group/others
* Use `chmod` for permissions, `chown` for ownership
* Numeric mode (755, 644) sets all permissions at once; symbolic mode (u+x) modifies specific bits
* `sudo` grants temporary root access for individual commands -- prefer it over logging in as root
* Special bits (SUID, SGID, sticky) solve real problems but require careful use
* Always use `usermod -aG` (with the `-a` flag) to add users to groups

***

Next: [Linux Process Management →](/courses/devops-tools/linux-processes)
