DEV Community

Schiff Heimlich
Schiff Heimlich

Posted on

chattr +i: The Immutable Flag That Actually Stops root

You know how chmod 000 feels like it should protect a file? It doesn't. Root ignores it. sudo rm still works.

chattr +i is different. It sets the immutable flag at the filesystem level. Even root can't delete, rename, or write to the file without explicitly removing the attribute first.

# Make a file immutable
sudo chattr +i /etc/ssh/sshd_config

# Verify
lsattr /etc/ssh/sshd_config
# ----i---------e----- /etc/ssh/sshd_config

# Try to modify (fails)
echo "Port 2222" | sudo tee -a /etc/ssh/sshd_config
# tee: /etc/ssh/sshd_config: Operation not permitted

# Remove the flag when you actually need to change it
sudo chattr -i /etc/ssh/sshd_config
Enter fullscreen mode Exit fullscreen mode

There's also +a for append-only — useful for log files you want protected from rotation bugs or accidental truncation:

sudo chattr +a /var/log/myapp.log
# Now you can only append, not overwrite or delete
Enter fullscreen mode Exit fullscreen mode

A few things that bite people:

Filesystem support varies. Works on ext4, XFS, Btrfs. Doesn't work on tmpfs, NFS mounts, or some FUSE filesystems. Check with lsattr first.

Recursive is -R, not -r. Easy to mix up.

cp doesn't preserve attributes. If you copy an immutable file, the copy is mutable. Use cp --attributes-only if you need that behavior.

Docker volumes. If you bind-mount a file with +i into a container, the container can't modify it — which is either a feature or a headache depending on what you're doing.

Practical uses I've actually reached for:

  • Locking /etc/ssh/sshd_config and /etc/sudoers after hardening
  • Protecting critical cron files from "quick edits" that survive a reboot
  • Append-only on audit logs where compliance matters
  • Preventing logrotate from accidentally truncating a file the app holds open

It's not a security boundary — a determined attacker with root can just chattr -i — but it's a solid guard against accidents and automation gone wrong. The kind of thing that saves you at 2 AM when a script runs rm -rf on /etc because a variable expanded to empty.

Top comments (0)