AOSP Framework & Internals
3 min read

file_contexts and labeling

Learn about file_contexts and labeling.

In SELinux, a file's security context (its label) dictates which domains can access it. Managing these labels correctly is essential for maintaining a secure Android filesystem. The file_contexts files define the canonical labeling for the system.

file_contexts Syntax

The file_contexts file maps regular expressions (representing file paths) to SELinux contexts. The syntax is:

<regular_expression>    <security_context>

Example:

/system/bin/surfaceflinger      u:object_r:surfaceflinger_exec:s0
/data/vendor/wifi(/.*)?         u:object_r:wifi_vendor_data_file:s0

The regular expressions allow for wildcard matching, making it easy to label entire directory trees.

Labeling New Files and Directories

When the Android build system generates filesystem images (like system.img or vendor.img), it uses the file_contexts definitions to stamp the correct SELinux labels onto every file in the image using the setfiles utility.

When a process creates a new file at runtime, the kernel automatically assigns a label based on:

  1. The domain of the creating process.
  2. The type of the parent directory.
  3. Explicit filetrans rules in the .te policy.

For example, if the init process creates a file in /dev, the filetrans rules dictate what label the new file should receive, rather than just inheriting the generic /dev type.

restorecon and chcon

If a file's label becomes corrupted or is incorrectly assigned (often happening when pushing files manually via adb), you need utilities to fix it.

  • restorecon: This is the preferred tool. It reads the file_contexts definitions and applies the correct canonical label to the specified path.

    adb shell restorecon /data/vendor/wifi/wpa_supplicant.conf
    # Use -R for recursive labeling of a directory
    adb shell restorecon -R /data/vendor/wifi/
    
  • chcon: This tool allows you to manually change a file's context to any arbitrary value, bypassing file_contexts. It is primarily used for temporary debugging and testing.

    adb shell chcon u:object_r:audio_data_file:s0 /data/local/tmp/test.wav
    

Persistent Labeling on Userdata

Files on the /data partition (userdata) are created dynamically. If a service needs to create files in /data/vendor/ with a specific label, you must ensure two things:

  1. Define the mapping in file_contexts.
  2. Ensure the service creating the file has the permissions to create files of that specific type, and that a filetrans rule exists if it does not manually set the label using setfscreatecon() before creation.

If you add new paths to file_contexts for the /data partition via an OTA update, the system will automatically run a restorecon pass over those specific directories during the boot process to ensure the labels are correct.