How do I detect if SELinux is enabled in an android application?

Brian Pellin picture Brian Pellin · Sep 10, 2013 · Viewed 12k times · Source

I'm trying to use the SecureRandom workaround that Google posted in my android application: http://android-developers.blogspot.com/2013/08/some-securerandom-thoughts.html

This work around involve writing to (and reading from) /dev/urandom. However, it looks like Samsung has enabled SELinux in such a way that prevents applications from accessing /dev/urandom.

I don't have one of these devices, so it is a little hard for me to test solutions, other than to push out attempts at workarounds on the Android market, but it seems like this is not an error that I can trap with a try catch block. It also appears that File.canRead and canWrite return true. You can see my attempts at workaround in the supportedOnThisDevice method in the following class: PRNGFixes.java

I'm looking for a reliable way to detect if I am an such a device, and if so, not apply the Google SecureRandom workaround.

Answer

Martin L. picture Martin L. · Nov 24, 2014

This is my way to check if SELinux is in enforce-mode - can be done via any Shell-script, not depending on RootTools:

private static boolean isSELinuxEnforcing() {
    try {
        CommandCapture command = new CommandCapture(1, "getenforce");
        RootTools.getShell(false).add(command).waitForFinish();
        boolean isSELinuxEnforcing = command.toString().trim().equalsIgnoreCase("enforcing");
        return isSELinuxEnforcing;
    } catch (Exception e) {
        // handle exception
    }
    return false;
}