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.
37.1 Special Permissions Deep Dive
Section titled “37.1 Special Permissions Deep Dive”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 51. SUID (Set User ID) — Value: 4
Section titled “1. SUID (Set User ID) — Value: 4”- 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
sin the user execute position (-rwsr-xr-x). If the user does not have execute permission, it appears as an uppercaseS. - Legitimate Use:
/usr/bin/passwdneeds 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).
# Add SUID to a binarychmod u+s /usr/local/bin/custom_tool# or octal:chmod 4755 /usr/local/bin/custom_tool
# Remove SUIDchmod u-s /usr/local/bin/custom_tool2. SGID (Set Group ID) — Value: 2
Section titled “2. SGID (Set Group ID) — Value: 2”- 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
sin the group execute position (-rwxr-sr-x). If group lacks execute permission, it appears as uppercaseS. - Best Practice: Critical for team-shared folders (e.g.,
/var/www/or/data/devops/).
# Set SGID on a shared directorychmod g+s /var/shared/# or octal:chmod 2775 /var/shared/3. Sticky Bit — Value: 1
Section titled “3. Sticky Bit — Value: 1”- Behavior: Protects files inside shared directories. Only the file owner, the directory owner, or
rootcan rename or delete files. - Representation: A
tin the others execute position (drwxrwxrwt). - Primary Use Case: Shared writeable directories like
/tmpand/var/tmp.
# Set sticky bitchmod +t /shared_scratch/# or octal:chmod 1777 /shared_scratch/37.2 Securing /tmp and /var/tmp
Section titled “37.2 Securing /tmp and /var/tmp”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.
Hardening /tmp via Mount Options
Section titled “Hardening /tmp via Mount Options”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 /tmptmpfs /tmp tmpfs defaults,noexec,nosuid,nodev 0 0noexec: 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:
sudo mount -o remount /tmp37.3 World-Writable Files & Directories
Section titled “37.3 World-Writable Files & Directories”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.
Hazards
Section titled “Hazards”- 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.
Auditing for World-Writable Files
Section titled “Auditing for World-Writable Files”# Find all world-writable files across the entire root filesystemsudo 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_file37.4 Sensitive System Files & Ownership
Section titled “37.4 Sensitive System Files & Ownership”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”# Verify sensitive shadow file permissionsls -l /etc/shadow /etc/gshadow /etc/sudoers
# Fix permissions on SSH keyschmod 700 ~/.sshchmod 600 ~/.ssh/id_rsa ~/.ssh/authorized_keyschmod 644 ~/.ssh/id_rsa.pub37.5 Permission Auditing Toolkit
Section titled “37.5 Permission Auditing Toolkit”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.
# Find files with no valid user or groupsudo find / -xdev \( -nouser -o -nogroup \) -exec ls -ld {} + 2>/dev/null2. Hunting for SUID / SGID Binaries
Section titled “2. Hunting for SUID / SGID Binaries”Audit the system against baseline SUID binaries to catch newly installed root backdoors:
# Scan for all SUID binariessudo find / -xdev -perm -4000 -type f -exec ls -la {} + 2>/dev/null
# Scan for all SGID binariessudo find / -xdev -perm -2000 -type f -exec ls -la {} + 2>/dev/null3. 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:
# On RHEL/Alma/CentOS: Verify all files owned by packagesrpm -Va | grep -E '^.{1}5|^.{5}P'
# On Debian/Ubuntu (requires debsums)sudo apt install debsumssudo debsums -s37.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.
The chattr Command
Section titled “The chattr Command”Syntax
Section titled “Syntax”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.
Common Attribute Flags
Section titled “Common Attribute Flags”| 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. |
Practical chattr Examples
Section titled “Practical chattr Examples”# 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 modificationssudo chattr -i /etc/resolv.conf
# Enforce append-only on an audit log filesudo chattr +a /var/log/secure_audit.log
# Recursively lock an entire static web directorysudo chattr -R +i /var/www/static/Inspecting Attributes with lsattr
Section titled “Inspecting Attributes with lsattr”The lsattr command prints active filesystem attribute flags.
Syntax & Options
Section titled “Syntax & Options”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.
Example Output Analysis
Section titled “Example Output Analysis”lsattr /etc/resolv.conf /var/log/secure_audit.logExample 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”Enterprise Security Applications
Section titled “Enterprise Security Applications”- Preventing DNS Hijacking: Malware and rogue DHCP clients often overwrite
/etc/resolv.conf. Runningchattr +i /etc/resolv.confensures name resolution servers remain constant. - Hardening Root Infrastructure: Apply
chattr +ito/etc/passwd,/etc/shadow, and/etc/sudoersin production after changes are committed. - Immutable Logging: Configure security event logs with
chattr +aso that even if an attacker gains an unprivileged shell, they cannot erase their footprints from log files.
Limitations
Section titled “Limitations”- Extended attributes are predominantly an ext2/ext3/ext4 feature. While XFS supports flags like
ianda, many flags (u,c,s) are specific to ext4. - Superuser privileges (
sudo) are required to manipulate flags like+iand+a.