When to call SELinux.restorecon()?

Viewed 236

The Android open source code contains code such as this. Can anyone explain why and under which circumstances it is necessary to do SELinux.restorecon(File)?

    // If Encrypted file systems is enabled or disabled, this call will return the
    // correct directory.
    mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
    mBaseStateDir.mkdirs();
    if (!SELinux.restorecon(mBaseStateDir)) {
        Slog.e(TAG, "SELinux restorecon failed on " + mBaseStateDir);
    }

Can we do it too often?

1 Answers

SELinux restorecon is used to restore the default security contexts on some files/dir.

The thing (which is not obvious) is that we also use it to apply context changes, and/or to ensure that the file contexts are as you expect.

Usually, we define/override default security contexts using semanage-fcontext, and then run restorecon to relabel files according to these new defaults.

Here the code tries to relabel mBaseStateDir but fails to do so. It could be that :

  • there is no policy supporting the default context associated to that directory (given it's path)
  • mBaseStateDir is mislabeled (context type is not apllicable)
  • user/process running that code doesn't have the sufficient permission to relabel the directory (even it just created it).
Related