Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 95 ยท Working with Files

ACLs, chattr and Extended Attributes

Go beyond rwx permissions: use setfacl and getfacl for per-user access, default ACLs, the mask, chattr +i and +a for immutable files, and xattrs.

The classic Unix permission model gives every file exactly one owner, one group and "everyone else". That is enough for a surprising number of cases, but sooner or later you meet a request it cannot express: "Alice may edit this report, Bob may only read it, and nobody else may see it", when Alice and Bob belong to different groups. You could create a new group for every combination, but that quickly becomes unmanageable.

Linux has three extra layers for these situations. POSIX ACLs (access control lists) let you attach any number of per-user and per-group rules to a file. File attributes set with chattr are filesystem-level flags such as "immutable" that even root cannot ignore until the flag is removed. Extended attributes (xattrs) are named metadata attached to files, and they are the storage that ACLs, SELinux labels and file capabilities are built on. This lesson builds on File Permissions and Ownership and Users, Groups and sudo.

Our sandbox has no setfacl, no root and no second user, so the ACL commands are shown read-only. To make the rules concrete you will write a small ACL evaluator in Bash that follows the same algorithm the kernel uses.

Why ordinary permissions are not enough

Suppose /srv/reports/q3.txt is owned by carol:finance with mode 640. Carol can read and write, group finance can read, everybody else gets nothing. Now Alice (group sales) needs read access, and Bob (group audit) needs read and write. With classic permissions your only options are to make the file world-readable, to put Alice and Bob in finance (which gives them access to every other finance file), or to build special-purpose groups. An ACL solves it directly: two more rules on one file.

Reading and setting ACLs

ACLs need the acl package (getfacl and setfacl) and a filesystem mounted with ACL support, which is the default on ext4, XFS and Btrfs today. The two commands you will use daily:

CONSOLE
$ getfacl q3.txt                     # show the ACL
$ setfacl -m u:alice:r q3.txt        # modify: give user alice read
$ setfacl -m u:bob:rw q3.txt         # give user bob read and write
$ setfacl -m g:audit:r q3.txt        # a named group
$ setfacl -x u:alice q3.txt          # remove one entry
$ setfacl -b q3.txt                  # remove ALL extended entries

After those commands, getfacl q3.txt prints something like this (read-only example):

TEXT
# file: q3.txt
# owner: carol
# group: finance
user::rw-
user:alice:r--
user:bob:rw-
group::r--
group:audit:r--
mask::rw-
other::---

Each line is an entry in the form tag:qualifier:permissions. The tags are:

Entry Meaning
user::rw- the file's owner (empty qualifier)
user:alice:r-- a named user
group::r-- the file's owning group
group:audit:r-- a named group
mask::rw- the upper limit for named users, named groups and the owning group
other::--- everyone else

The first, third and last lines are the old owner/group/other triple. Everything else is new. When a file has extra entries, ls -l shows a + after the mode (-rw-rw----+), and the group column of the mode no longer shows the owning group's permissions, but the mask. That is the single most surprising fact about ACLs, so it deserves its own section.

The mask

The mask caps the permissions of every entry except the owner and other. The effective permission of user:bob:rw- under mask::r-- is only r--, and getfacl tells you so with a comment:

TEXT
user:bob:rw-                  #effective:r--

setfacl recalculates the mask whenever you add an entry, so it normally stays out of the way. But chmod g-w file on a file with an ACL changes the mask, not the group entry, and silently removes write access from every named user and group. If someone's access "mysteriously disappeared" after a chmod, check getfacl for the mask. Set it explicitly with setfacl -m m::rw file.

Default ACLs for directories

An ACL on a directory only controls the directory itself. To make new files and subdirectories inherit rules, you add a default ACL with -d:

CONSOLE
$ setfacl -d -m g:audit:rX /srv/reports      # new files get these entries
$ setfacl -R -m g:audit:rX /srv/reports      # fix the files that already exist
$ getfacl /srv/reports

getfacl shows default entries with a default: prefix. Two details matter. First, when a directory has a default ACL, the process's umask is not applied to new files there; the default ACL's entries (limited by the permission bits the program asks for) decide. Second, the capital X in rX means "execute only if it is a directory or already executable for someone", which is what you want for recursive grants.

Preserving ACLs is not automatic. cp -p and cp -a, mv on the same filesystem, rsync -A and tar --acls keep them; a plain cp or tar may not. You can save and restore a whole tree's ACLs with getfacl -R dir > acls.txt and setfacl --restore=acls.txt.

How the kernel evaluates an ACL

The check is a short, ordered list of tests. The first rule that applies decides, and later rules are never consulted:

flowchart TD
    A["Process asks for r, w or x"] --> B{"Is the process owner<br/>of the file?"}
    B -- yes --> O["Use user:: entry<br/>(no mask)"]
    B -- no --> C{"Does a user:NAME entry<br/>match the process uid?"}
    C -- yes --> D["Entry AND mask"]
    C -- no --> E{"Does any of the process groups<br/>match group:: or a group:NAME entry?"}
    E -- yes --> F["Grant if ANY matching entry AND mask<br/>allows it, otherwise deny"]
    E -- no --> G["Use other:: entry"]

The ACL check: owner first, then named users, then groups, then everyone else.

Notice that being the owner, or matching a named user, stops the search. If Bob is a named user with r-- but is also in a group that has rw-, he gets only r--, because the named-user rule matched first.

An ACL evaluator you can run

The script below implements exactly that flowchart. An ACL is a plain list of entries, a request names a user, their groups and what they want, and the function prints the verdict plus the reason. Run it, then change the mask or the entries and predict the result before you press Run.

Bash A POSIX ACL evaluator in Bash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Read the output against the ACL. Carol is the owner, so the mask is ignored and she may write. Alice has r--, so her write is denied. Bob's entry says rw-, but the mask is r--, so his effective permission is only read, and his write request is denied. That is the "chmod removed their write access" surprise reproduced. Dave is in the named group audit (rw-), which the mask also trims to r--, so his read passes. Erin matches nothing and falls through to other::---.

Now change "mask::r--" to "mask::rw-" and run it again: Bob's write is allowed and so is Dave's write. A single entry controlled all of that.

chattr: attributes below the permission system

Permission bits and ACLs answer "who may do what". File attributes answer a different question: "what may be done to this file, no matter who asks". They are flags stored in the filesystem (mainly ext4, with partial support on XFS and Btrfs), set with chattr and shown with lsattr:

CONSOLE
$ lsattr notes.txt
--------------e------- notes.txt
$ sudo chattr +i notes.txt           # make it immutable
$ rm notes.txt
rm: cannot remove 'notes.txt': Operation not permitted
$ echo more >> notes.txt
bash: notes.txt: Operation not permitted
$ sudo chattr -i notes.txt           # undo it

An immutable file (i) cannot be modified, deleted, renamed or hard-linked, not even by root, until the flag is removed. Setting or clearing it needs the CAP_LINUX_IMMUTABLE capability, which in practice means root. The flags worth knowing:

Flag Name Effect
i immutable no change, delete, rename or link at all
a append-only data can only be appended; no overwrite, truncate or delete (good for logs)
A no atime do not update the access time on reads (less disk writing)
d no dump skipped by the dump backup tool
c compressed filesystem compresses the file transparently (not supported everywhere)
C no copy-on-write for Btrfs: avoid fragmentation of VM images and databases
e extents file uses extents (shown on almost every modern ext4 file)

Typical uses: chattr +i /etc/resolv.conf to stop a network manager from rewriting it, chattr +a /var/log/audit.log so that an intruder who gains root-less write access cannot erase history, and chattr +i on a few critical files as a tripwire. Remember that an immutable file also blocks you: package upgrades will fail with "Operation not permitted", and the error does not mention the flag. If a file refuses to change although the permissions look fine, run lsattr. Add -d to look at a directory itself and -R to recurse.

Our sandbox is not root, so we can set harmless flags but not the powerful ones. This example shows both outcomes honestly:

Bash lsattr, chattr +A works, chattr +i is refused

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The flags row --------------e---- becomes -------A------e---- after +A; each position is one flag. The +i request fails with Operation not permitted because the program has no capability to set it, and the exit status is non-zero. On a real server, sudo chattr +i would succeed and the final append would fail.

Extended attributes

An extended attribute is a name/value pair stored with a file's metadata, in addition to its contents. Names live in namespaces, and the namespace decides who may read and write them:

Namespace Used for Access
user. your own labels, such as user.comment or user.checksum normal file permissions, regular files and directories only
trusted. data for privileged software root only
security. security modules and capabilities (security.selinux, security.capability) set by the kernel and security tools
system. kernel objects such as ACLs (system.posix_acl_access) kernel-defined

The tools come from the attr package. This is a read-only session:

CONSOLE
$ setfattr -n user.comment -v "reviewed by Dana" report.pdf
$ getfattr -n user.comment report.pdf
# file: report.pdf
user.comment="reviewed by Dana"
$ getfattr -d -m - report.pdf        # dump every attribute in every namespace
$ setfattr -x user.comment report.pdf
$ getcap /usr/bin/ping               # file capabilities live in security.capability

Desktop software uses user. attributes for tags and download origins, backup tools may or may not carry them, and the ACL machinery described above stores its data in the system.posix_acl_* attributes. Not every filesystem supports xattrs (many network and FAT filesystems do not) and the total size per file is small, so treat them as labels, not as a database. When copying, ask explicitly: cp --preserve=xattr, rsync -X, tar --xattrs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A file has the ACL entries user:bob:rw- and mask::r--. What can Bob do?

    The mask is the upper limit for named users, named groups and the owning group. Bob's effective permission is rw- AND r-- = r--. getfacl shows this as #effective:r--.
  2. 2. After chmod g-w report.txt on a file that has several named-user ACL entries, those users lose write access. Why?

    When a file has an ACL, the middle triple of its mode is the mask. chmod g-w therefore removes write from every entry the mask applies to. Fix it with setfacl -m m::rw.
  3. 3. Which command makes files created later inside /srv/shared give group team read and write access?

    The -d option sets a default ACL, which new files and subdirectories inherit. Without -d the entry only affects the directory itself, and -R only changes what exists now.
  4. 4. Root runs rm /etc/important.conf and gets Operation not permitted, although the file is owned by root with mode 644. What should you check?

    An immutable file (chattr +i) cannot be changed or removed even by root. lsattr shows the i flag; chattr -i clears it.
  5. 5. Which statement about extended attributes is correct?

    xattrs are small metadata items organized in namespaces. ACLs use system.posix_acl_access, SELinux uses security.selinux, and your own tags can use user.NAME.

Summary

  • Classic permissions know one owner, one group and everyone else; ACLs add any number of named-user and named-group rules to a file.
  • setfacl -m u:NAME:rw FILE adds, -x removes one entry, -b removes all; getfacl shows them, and ls -l marks such files with +.
  • The mask limits every entry except the owner and other. chmod g-w on a file with an ACL lowers the mask, a common cause of lost access.
  • The kernel checks owner, then named users, then groups, then other, and the first match decides.
  • A default ACL (setfacl -d) on a directory is inherited by new files; copy tools need -p, -a, -A or --acls to keep ACLs.
  • chattr +i (immutable) and +a (append-only) block changes even for root until cleared; use lsattr when a permitted operation fails.
  • Extended attributes are namespaced name/value metadata (user., security., system., trusted.) managed with getfattr and setfattr.

Next: Viewing Text