chattr & lsattr

Extended File Attributes for Enhanced Security and Control

About chattr & lsattr

The chattr (change attribute) and lsattr (list attributes) commands are complementary tools for managing extended file attributes on Linux filesystems (ext2, ext3, ext4, and others). These attributes provide an additional layer of protection beyond standard Unix permissions.

Why Use File Attributes?

  • chattr: Sets or modifies file attributes (requires root for most attributes)
  • lsattr: Displays current file attributes (can be run by any user)
  • Immutable Flag (i): Makes files unchangeable, even by root - critical for security
  • Append-Only (a): Allows only appending to files - perfect for log files
  • Works at Filesystem Level: Protection survives chmod, chown, and even root access

Common Use Cases:

  • Protecting critical configuration files from accidental modification
  • Securing system binaries against tampering
  • Preventing deletion of important files during maintenance
  • Creating append-only log files that can't be truncated
  • Hardening servers against rootkit installation
  • Compliance requirements for immutable audit logs
File Attributes Reference
Attribute Symbol Description
immutable SECURITY i File cannot be modified, deleted, renamed, or linked. Even root cannot change it without removing attribute first.
append-only SECURITY a File can only be opened in append mode for writing. Cannot be deleted, truncated, or modified.
no-dump d File will not be backed up by the dump program.
synchronized S Changes are written synchronously to disk (like mount with sync option).
no-atime A Access time is not updated when file is accessed.
compressed c File is automatically compressed on disk (filesystem dependent).
undeletable u When deleted, contents are saved for later undeletion (not widely implemented).
secure-deletion s File is securely deleted (overwritten with zeros) when removed.
journaled j Data is written to journal before being written to file (ext3/4 only).
chattr Command Syntax
Operator Description
+ Add specified attributes
- Remove specified attributes
= Set attributes to exactly this value (clear others)
-R Recursive - apply to directories and their contents
-V Verbose - display attribute changes
-v version Set file version/generation number
Detailed Examples

Example 1Make File Immutable (Cannot Be Changed)

Protect a critical configuration file from any modification:

$ sudo touch /etc/important.conf $ sudo chattr +i /etc/important.conf $ lsattr /etc/important.conf
----i---------e----- /etc/important.conf
$ echo "test" | sudo tee -a /etc/important.conf
tee: /etc/important.conf: Operation not permitted
$ sudo rm /etc/important.conf
rm: cannot remove '/etc/important.conf': Operation not permitted

Explanation:

  • chattr +i: Adds immutable attribute
  • lsattr: Shows 'i' flag is set
  • File cannot be modified, even with sudo/root
  • File cannot be deleted, renamed, or linked
  • Directory entry cannot be modified
  • Must remove 'i' attribute before making any changes
Security Note: This is your strongest defense against accidental or malicious modification. Even if an attacker gains root access, they cannot modify files with the immutable flag without first removing it - which creates audit trail opportunities.

Example 2Remove Immutable Flag to Allow Changes

Temporarily remove protection to update the file:

$ sudo chattr -i /etc/important.conf $ lsattr /etc/important.conf
--------------e----- /etc/important.conf
$ sudo echo "Now I can modify this" >> /etc/important.conf $ sudo chattr +i /etc/important.conf $ lsattr /etc/important.conf
----i---------e----- /etc/important.conf

Explanation:

  • chattr -i: Removes immutable attribute
  • File becomes modifiable again
  • Make your changes
  • chattr +i: Restore protection
  • Best practice: Remove protection only when needed
  • Document when and why protection was removed
Tip: Create a wrapper script that removes immutable, edits file, and re-adds immutable: sudo chattr -i file; sudo vi file; sudo chattr +i file. This ensures protection is restored even if you forget.

Example 3Append-Only Flag for Log Files

Create log file that can only be appended to, never truncated:

$ sudo touch /var/log/critical-audit.log $ sudo chattr +a /var/log/critical-audit.log $ lsattr /var/log/critical-audit.log
-----a--------e----- /var/log/critical-audit.log
$ sudo echo "Log entry 1" >> /var/log/critical-audit.log # This works $ cat /var/log/critical-audit.log
Log entry 1
$ sudo echo "Overwrite" > /var/log/critical-audit.log # This fails
bash: /var/log/critical-audit.log: Operation not permitted
$ sudo rm /var/log/critical-audit.log # This also fails
rm: cannot remove '/var/log/critical-audit.log': Operation not permitted

Explanation:

  • chattr +a: Sets append-only attribute
  • Appending works: >> operator succeeds
  • Overwriting fails: > operator denied
  • Deletion fails: Cannot remove file
  • Perfect for audit logs and compliance
  • Prevents log tampering by attackers
Compliance Use Case: Many regulatory frameworks (PCI-DSS, HIPAA, SOX) require append-only audit logs to prevent tampering. The 'a' attribute provides this at the filesystem level, independent of application controls.

Example 4List All Attributes in Directory

View attributes for multiple files at once:

$ cd /etc $ sudo chattr +i hosts resolv.conf $ sudo chattr +a syslog.conf $ lsattr hosts resolv.conf syslog.conf
----i---------e----- hosts ----i---------e----- resolv.conf -----a--------e----- syslog.conf
$ lsattr -d /etc/important-configs/
----i---------e----- /etc/important-configs/

Explanation:

  • lsattr without args shows attributes for specified files
  • Shows all flags: 'i' for immutable, 'a' for append-only
  • -d: Show directory attributes, not contents
  • The 'e' flag is extent format (ext4 default, not settable)
  • Dashes indicate attributes that are not set
  • Useful for auditing protected files
Tip: Create a daily audit script: lsattr -R /etc /usr/bin /usr/sbin | grep "i\|a" > /var/log/protected-files.log to track which files have special attributes.

Example 5Recursive Protection of Directory

Protect entire directory tree from modification:

$ sudo mkdir -p /etc/critical-configs $ sudo cp /etc/hosts /etc/critical-configs/ $ sudo cp /etc/resolv.conf /etc/critical-configs/ $ sudo chattr -R +i /etc/critical-configs/ $ lsattr -R /etc/critical-configs/
----i---------e----- /etc/critical-configs/hosts ----i---------e----- /etc/critical-configs/resolv.conf /etc/critical-configs/: ----i---------e----- ./hosts ----i---------e----- ./resolv.conf
$ sudo rm -rf /etc/critical-configs/
rm: cannot remove '/etc/critical-configs/hosts': Operation not permitted

Explanation:

  • -R: Recursive flag applies to all files
  • Both files and directory itself get immutable flag
  • lsattr -R: Recursively list attributes
  • Even rm -rf cannot delete protected files
  • Must remove attributes from all files individually
  • Or use: sudo chattr -R -i /etc/critical-configs/
Warning: Setting immutable on a directory prevents creating, deleting, or renaming files within it. If you want to allow file additions but prevent modifications, set immutable only on individual files, not the directory.

Example 6Protect System Binaries from Tampering

Harden critical system executables against rootkit installation:

$ sudo chattr +i /bin/ls /bin/ps /bin/netstat /bin/login $ lsattr /bin/ls /bin/ps /bin/netstat /bin/login
----i---------e----- /bin/ls ----i---------e----- /bin/ps ----i---------e----- /bin/netstat ----i---------e----- /bin/login
$ sudo cp /tmp/malicious /bin/ls
cp: cannot create regular file '/bin/ls': Operation not permitted

Explanation:

  • Protects critical binaries from replacement
  • Common rootkit technique: replace ls, ps, netstat
  • Immutable flag prevents binary substitution
  • Even root cannot overwrite without removing attribute
  • Critical for intrusion detection and prevention
  • Should be part of system hardening checklist
Security Practice: After system installation and configuration, make critical binaries immutable. Remember to remove protection before system updates, then restore afterward. Consider using package manager hooks to automate this.

Example 7Combine Multiple Attributes

Set multiple attributes simultaneously:

$ sudo touch /var/log/secure-audit.log $ sudo chattr +ai /var/log/secure-audit.log $ lsattr /var/log/secure-audit.log
----ia--------e----- /var/log/secure-audit.log
$ sudo echo "Append works" >> /var/log/secure-audit.log # OK $ sudo echo "Overwrite fails" > /var/log/secure-audit.log # Fails $ sudo rm /var/log/secure-audit.log # Fails
bash: /var/log/secure-audit.log: Operation not permitted rm: cannot remove '/var/log/secure-audit.log': Operation not permitted

Explanation:

  • +ai: Sets both append-only and immutable
  • With 'i': File cannot be deleted or renamed
  • With 'a': File can only be appended to
  • Combined: Maximum protection for log files
  • Both attributes shown in lsattr output
  • Must remove both to modify: chattr -ai
Tip: For critical audit logs, use +ai together. This ensures logs cannot be deleted (i) or have entries removed by truncation (a), providing complete tamper protection.

Example 8No-Dump Attribute for Temporary Files

Exclude files from backup operations:

$ touch /tmp/cache-data.tmp $ chattr +d /tmp/cache-data.tmp $ lsattr /tmp/cache-data.tmp
---d----------e----- /tmp/cache-data.tmp
$ dump -0f /dev/null /tmp/ # File will be skipped

Explanation:

  • +d: Sets no-dump attribute
  • File excluded from dump backups
  • Useful for cache files and temporary data
  • Reduces backup size and time
  • File still accessible and writable normally
  • Does not affect tar, rsync, or other backup tools
Note: The no-dump flag only affects the dump utility, which is less commonly used today. Modern backup tools (rsync, tar) typically ignore this attribute. Use exclude lists in those tools instead.

Example 9Check Attributes Before and After Operations

Monitor attribute changes during system maintenance:

$ cd /etc $ sudo lsattr hosts passwd shadow > /tmp/attrs-before.txt $ cat /tmp/attrs-before.txt
----i---------e----- hosts --------------e----- passwd --------------e----- shadow
# Perform system maintenance $ sudo apt-get upgrade # Check for changes $ sudo lsattr hosts passwd shadow > /tmp/attrs-after.txt $ diff /tmp/attrs-before.txt /tmp/attrs-after.txt
1c1 < ----i---------e----- hosts --- > --------------e----- hosts

Explanation:

  • Capture attributes before maintenance window
  • Perform system updates or changes
  • Compare attributes afterward
  • Diff shows immutable flag was removed from hosts
  • Indicates file was modified during upgrade
  • May need to restore protection afterward
Tip: Create a pre/post maintenance script: sudo lsattr -R /etc > /var/log/attrs-$(date +%Y%m%d-%H%M).txt. Track attribute changes as part of change management process.

Example 10Automated Protection Script

Create a script to protect critical system files:

$ sudo cat > /usr/local/sbin/protect-critical-files.sh << 'EOF' #!/bin/bash # Protect critical system files with immutable attribute CRITICAL_FILES=( "/etc/passwd" "/etc/shadow" "/etc/group" "/etc/sudoers" "/etc/ssh/sshd_config" "/boot/grub/grub.cfg" ) echo "Protecting critical files..." for file in "${CRITICAL_FILES[@]}"; do if [ -f "$file" ]; then chattr +i "$file" echo " Protected: $file" fi done echo "Verification:" lsattr "${CRITICAL_FILES[@]}" EOF $ sudo chmod +x /usr/local/sbin/protect-critical-files.sh $ sudo /usr/local/sbin/protect-critical-files.sh
Protecting critical files... Protected: /etc/passwd Protected: /etc/shadow Protected: /etc/group Protected: /etc/sudoers Protected: /etc/ssh/sshd_config Protected: /boot/grub/grub.cfg Verification: ----i---------e----- /etc/passwd ----i---------e----- /etc/shadow ----i---------e----- /etc/group ----i---------e----- /etc/sudoers ----i---------e----- /etc/ssh/sshd_config ----i---------e----- /boot/grub/grub.cfg

Explanation:

  • Script automates protection of critical files
  • Array holds list of files to protect
  • Loop applies immutable attribute to each
  • Verification shows current protection status
  • Can be run after system installation
  • Create complementary unprotect script for maintenance
Tip: Create paired scripts: protect-critical-files.sh and unprotect-critical-files.sh. Run unprotect before maintenance, protect afterward. Log all executions for audit trail.
Related Commands and Tools
Common Pitfalls and Solutions
Pitfall 1: Forgetting Files Are Immutable During Updates

System updates fail when trying to modify protected config files.

Solution: Before system updates: sudo chattr -R -i /etc. After updates: sudo chattr -R +i /etc/critical-files/. Better: use apt hooks or package manager triggers to automate this.

Pitfall 2: Cannot Delete Directory with Protected Files

rm -rf directory/ fails even with root when files inside are immutable.

Solution: Must remove attributes first: sudo chattr -R -i directory/, then delete. Or use script: find directory/ -type f -exec chattr -i {} \; && rm -rf directory/

Pitfall 3: Backup Failures

Backup software fails when trying to update files with append-only attribute.

Solution: Either configure backup software to handle attribute errors gracefully, or temporarily remove append-only flag during backup window: chattr -a logfile; backup; chattr +a logfile

Pitfall 4: Filesystem Not Supporting Attributes

NFS, FAT32, and some network filesystems don't support extended attributes.

Solution: Check filesystem support: mount | grep $(df /path | tail -1 | awk '{print $1}'). Attributes only work on ext2/3/4, XFS, Btrfs, ReiserFS. Not on NFS, CIFS, FAT.

Pitfall 5: SELinux/AppArmor Conflicts

Security modules may conflict with file attributes or add confusion.

Solution: File attributes and MAC (SELinux/AppArmor) work on different layers and generally don't conflict. Use both for defense in depth. Check logs when troubleshooting: ausearch -m AVC for SELinux.

Pro Tips and Best Practices
Tip 1: Document Protected Files

Maintain a list of files with special attributes:

sudo find / -xdev -type f -exec lsattr {} \; 2>/dev/null | \ grep -E "^.*i.*$|^.*a.*$" > /root/protected-files.txt

Update documentation when adding/removing protection. Helps troubleshooting and knowledge transfer.

Tip 2: Use for Compliance

Meet regulatory requirements for immutable logs:

sudo chattr +a /var/log/audit/audit.log sudo chattr +a /var/log/secure

Document this in compliance reports. Demonstrate technical controls for log integrity.

Tip 3: Monitor Attribute Changes with auditd

Create audit rules to alert when attributes are modified:

sudo auditctl -w /usr/bin/chattr -p x -k attribute_changes sudo tail -f /var/log/audit/audit.log | grep attribute_changes

Alerts you when someone removes protection from files - potential security incident.

Tip 4: Protect Package Manager Database

Prevent accidental corruption of package databases:

sudo chattr +i /var/lib/dpkg/status # Debian/Ubuntu sudo chattr +i /var/lib/rpm/Packages # RedHat/CentOS

Remove protection before package operations, restore after. Prevents database corruption.

Tip 5: Test Recovery Procedures

Before depending on immutable protection, test recovery:

# Can you remove protection in single-user mode? # Can you remove it from rescue USB? # Do you have documented procedures?

Ensure you can recover if attributes prevent legitimate system maintenance.

Tip 6: Combination with Read-Only Root

For maximum security, combine with read-only root filesystem:

mount -o remount,ro / # Even with root access, filesystem is read-only # Plus immutable attributes on critical files # Double protection against tampering

Enterprise security: read-only root + immutable binaries + SELinux = defense in depth.

Historical Note: Extended file attributes were introduced in Linux kernel 2.2 (1999) for ext2 filesystems. The 'i' (immutable) and 'a' (append-only) flags were inspired by BSD's chflags command. Initially controversial, they're now standard security practice. Modern Linux distributions include them by default, and they've proven essential for system hardening and compliance requirements.
Quick Reference Cheat Sheet
Task Command
Make file immutable sudo chattr +i file
Remove immutable flag sudo chattr -i file
Make file append-only sudo chattr +a file
List file attributes lsattr file
Recursive protection sudo chattr -R +i directory/
List directory attributes lsattr -d directory/
Multiple attributes sudo chattr +ai file
Remove all protection sudo chattr -R -ai directory/
No-dump flag chattr +d file
List recursively lsattr -R directory/
Security Hardening Checklist

Files to Consider Protecting

File/Directory Attribute Reason
/etc/passwd, /etc/shadow, /etc/group +i Prevent unauthorized user account modifications
/etc/sudoers, /etc/sudoers.d/* +i Protect privilege escalation configuration
/etc/ssh/sshd_config +i Prevent SSH configuration tampering
/boot/grub/grub.cfg +i Protect bootloader configuration
/bin/*, /sbin/*, /usr/bin/*, /usr/sbin/* +i Prevent rootkit binary replacement
/var/log/audit/audit.log +a Ensure audit log integrity
/var/log/secure, /var/log/auth.log +a Protect authentication logs
/etc/fstab +i Prevent mount table manipulation
/etc/hosts, /etc/resolv.conf +i Prevent DNS hijacking