Skip to content

37. File Security

File security in Linux goes beyond basic rwx permissions. Attackers frequently exploit misconfigured file ownership, rogue special permissions (SUID/SGID), world-writable files, and unmonitored temporary directories to escalate privileges.

This chapter focuses on identifying, hardening, and continuously auditing file system security.

Standard permissions allow Read (4), Write (2), and Execute (1). A 4th permission digit prepends standard permissions to represent Special Permissions:

[Special] [User] [Group] [Others]
4 7 5 5
  • Behavior: When an executable with SUID is run, it executes with the privileges of the file owner (typically root) rather than the user who executed it.
  • Representation: An s in the user execute position (-rwsr-xr-x). If the user does not have execute permission, it appears as an uppercase S.
  • Legitimate Use: /usr/bin/passwd needs SUID root to write changes into /etc/shadow.
  • Security Hazard: If an attacker can execute a vulnerable SUID binary (or place their own), they gain root privileges instantly (Privilege Escalation).
Terminal window
# Add SUID to a binary
chmod u+s /usr/local/bin/custom_tool
# or octal:
chmod 4755 /usr/local/bin/custom_tool
# Remove SUID
chmod u-s /usr/local/bin/custom_tool
  • On Files: Executes with the permissions of the file’s group.
  • On Directories: Any file or directory created within automatically inherits the group ownership of the directory, rather than the primary group of the user creating it.
  • Representation: An s in the group execute position (-rwxr-sr-x). If group lacks execute permission, it appears as uppercase S.
  • Best Practice: Critical for team-shared folders (e.g., /var/www/ or /data/devops/).
Terminal window
# Set SGID on a shared directory
chmod g+s /var/shared/
# or octal:
chmod 2775 /var/shared/
  • Behavior: Protects files inside shared directories. Only the file owner, the directory owner, or root can rename or delete files.
  • Representation: A t in the others execute position (drwxrwxrwt).
  • Primary Use Case: Shared writeable directories like /tmp and /var/tmp.
Terminal window
# Set sticky bit
chmod +t /shared_scratch/
# or octal:
chmod 1777 /shared_scratch/

Because /tmp must be writable by all users and services, it is the most common target for attackers to download and run malicious scripts or reverse shells.

In production, /tmp should reside on its own partition or tmpfs and be mounted with strict security restrictions in /etc/fstab:

# Example /etc/fstab entry for hardened /tmp
tmpfs /tmp tmpfs defaults,noexec,nosuid,nodev 0 0
  • noexec: Blocks execution of any binaries directly from /tmp.
  • nosuid: Disables SUID/SGID bit evaluation on /tmp.
  • nodev: Prevents creation of device nodes (block/character devices) in /tmp.

Apply changes immediately:

Terminal window
sudo mount -o remount /tmp

A world-writable file (permissions ending in w- or 2 / 6 / 7 for Others) allows ANY unprivileged user or compromised service to modify its contents.

  • If a world-writable file is executed by root via cron or systemd, an attacker can append malicious commands, gaining immediate root access.
  • If a system library or config file is world-writable, attackers can alter system behavior.
Terminal window
# Find all world-writable files across the entire root filesystem
sudo find / -xdev -type f -perm -0002 -exec ls -ld {} + 2>/dev/null
# Find world-writable directories that lack the Sticky Bit (high risk!)
sudo find / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -exec ls -ld {} + 2>/dev/null
# Remediate by removing others-write permission:
sudo chmod o-w /path/to/vulnerable_file

Certain core files contain critical authentication credentials and system configuration. If their permissions or ownership drift, the system is fundamentally compromised.

| File | Recommended Permissions | Recommended Ownership | Purpose | ||||| | /etc/passwd | 644 (rw-r--r--) | root:root | User account information | | /etc/shadow | 640 or 600 (rw-r--) | root:shadow or root:root | Encrypted password hashes | | /etc/group | 644 (rw-r--r--) | root:root | Group account definitions | | /etc/gshadow| 640 or 600 (rw-r--) | root:shadow or root:root | Encrypted group passwords | | /etc/sudoers| 440 (r--r--) | root:root | Sudo privilege configuration | | /etc/ssh/sshd_config | 600 (rw-) | root:root | OpenSSH daemon configuration | | ~/.ssh/id_rsa | 600 (rw-) | user:user | Private SSH key | | ~/.ssh/authorized_keys | 600 (rw-) | user:user | Public SSH keys authorized for login |

Checking and Restoring Sensitive Permissions

Section titled “Checking and Restoring Sensitive Permissions”
Terminal window
# Verify sensitive shadow file permissions
ls -l /etc/shadow /etc/gshadow /etc/sudoers
# Fix permissions on SSH keys
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_rsa ~/.ssh/authorized_keys
chmod 644 ~/.ssh/id_rsa.pub

SysAdmins should automate regular audits for permission drift.

1. Hunting for Orphaned Files (No Known User or Group)

Section titled “1. Hunting for Orphaned Files (No Known User or Group)”

When a user is deleted with userdel without the -r flag, their files remain owned by their numeric UID. If a new user is later assigned that UID, they automatically inherit ownership of those orphaned files.

Terminal window
# Find files with no valid user or group
sudo find / -xdev \( -nouser -o -nogroup \) -exec ls -ld {} + 2>/dev/null

Audit the system against baseline SUID binaries to catch newly installed root backdoors:

Terminal window
# Scan for all SUID binaries
sudo find / -xdev -perm -4000 -type f -exec ls -la {} + 2>/dev/null
# Scan for all SGID binaries
sudo find / -xdev -perm -2000 -type f -exec ls -la {} + 2>/dev/null

3. Package Verification (Detecting Altered Permissions)

Section titled “3. Package Verification (Detecting Altered Permissions)”

RPM and DEB package managers can verify installed files against their official package checksums and permissions:

Terminal window
# On RHEL/Alma/CentOS: Verify all files owned by packages
rpm -Va | grep -E '^.{1}5|^.{5}P'
# On Debian/Ubuntu (requires debsums)
sudo apt install debsums
sudo debsums -s

37.6 File Attributes with chattr and lsattr

Section titled “37.6 File Attributes with chattr and lsattr”

The standard POSIX permission model (rwx) can be overridden by root. However, Linux ext-family filesystems (ext2, ext3, ext4) support extended file attributes managed via chattr (change attribute) and lsattr (list attributes). These attributes operate at the VFS filesystem layer, enforcing restrictions that even the root superuser cannot bypass without first explicitly removing the attribute.

Terminal window
chattr [options] [operator][flag] files...
  • Operators:
    • + : Add the specified attribute.
    • - : Remove the specified attribute.
    • = : Set only the specified attributes (clearing others).
  • Options:
    • -R : Recursively apply changes to directories and their contents.
    • -V : Verbose execution details.
    • -f : Suppress most error messages.
    • -v <version> : Set file version/generation number.
    • -p <project> : Set file project number.

Flag Attribute Name Operational Description Security & Administrative Benefit
i Immutable File cannot be modified, deleted, renamed, or linked to. Even root cannot alter it until chattr -i is run. Defends critical configuration files against tampering or accidental deletion.
a Append Only File can only be opened for writing in append mode (O_APPEND). Existing content cannot be overwritten or truncated. Guarantees audit and security logs cannot have historical entries modified.
A No atime Access time (atime) is not updated when the file is read. Reduces disk write I/O on heavily read volumes.
c Compressed File is transparently compressed on disk by the kernel. Conserves storage space.
d No Dump File is excluded from backups generated by the traditional dump utility. Excludes temporary or volatile caches from backup archives.
e Extent Format Indicates the file uses extents for disk block mapping (default on ext4). Filesystem block organization indicator.
j Data Journaling All data written to the file is written to the ext4 journal before disk commit. Protects databases or critical transactions from partial writes.
s Secure Deletion When deleted, data blocks are zeroed immediately on disk. Prevents forensically recovering confidential deleted data.
u Undeletable When deleted, blocks are saved to permit recovery. Failsafe for high-value files.
S Synchronous All updates to file are written synchronously to storage. Avoids write-buffer loss during system crashes.

Terminal window
# Make a critical file immutable (e.g. DNS resolver or shadow file)
sudo chattr +i /etc/resolv.conf
# Verify: Even root cannot delete or modify the file!
sudo rm -f /etc/resolv.conf
# Output: rm: cannot remove '/etc/resolv.conf': Operation not permitted
# Remove the immutable attribute to make modifications
sudo chattr -i /etc/resolv.conf
# Enforce append-only on an audit log file
sudo chattr +a /var/log/secure_audit.log
# Recursively lock an entire static web directory
sudo chattr -R +i /var/www/static/

The lsattr command prints active filesystem attribute flags.

Terminal window
lsattr [options] [files...]
  • -R : Recursively list directory contents.
  • -a : Include hidden files (dotfiles).
  • -d : List directory attributes themselves, rather than listing their contents.
  • -l : Display long flag names instead of single-character flags.
Terminal window
lsattr /etc/resolv.conf /var/log/secure_audit.log

Example Output:

----i---------e-- /etc/resolv.conf
-----a--------e-- /var/log/secure_audit.log
  • In the output string, each letter represents an active attribute (i = immutable, a = append-only, e = extent mapping). Dashes (-) represent inactive attribute slots.

Practical Security Use Cases & Limitations

Section titled “Practical Security Use Cases & Limitations”
  1. Preventing DNS Hijacking: Malware and rogue DHCP clients often overwrite /etc/resolv.conf. Running chattr +i /etc/resolv.conf ensures name resolution servers remain constant.
  2. Hardening Root Infrastructure: Apply chattr +i to /etc/passwd, /etc/shadow, and /etc/sudoers in production after changes are committed.
  3. Immutable Logging: Configure security event logs with chattr +a so that even if an attacker gains an unprivileged shell, they cannot erase their footprints from log files.
  • Extended attributes are predominantly an ext2/ext3/ext4 feature. While XFS supports flags like i and a, many flags (u, c, s) are specific to ext4.
  • Superuser privileges (sudo) are required to manipulate flags like +i and +a.