Tuesday, March 4, 2014

How do I detect if SELinux is enabled in android ?


public class SELinuxUtil {
    /***
* Detects whether device has SELinux
* @return
*/
public static boolean isSELinuxPresent() {
   boolean isSELinuxPresent = false;
 
   // First known firmware with SELinux built-in was a 4.2 (17)
   if(android.os.Build.VERSION.SDK_INT >= 17) {
     
            isSELinuxPresent = hasSELinuxSysProperty() || hasEnforce() ||
                hasGetEnforce() || OSUtil.isAndroid43OrLater();
   }  
return isSELinuxPresent;
}
private static boolean hasSELinuxSysProperty() {
boolean hasSELinux = false;
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class);
String selinux = (String) get.invoke(c, "ro.build.selinux");
hasSELinux = FxStringUtils.isEmptyOrNull(selinux);
} catch (Exception ignored) { }
return hasSELinux;
}
private static boolean hasEnforce() {
   boolean isFileExisted = false;
   try {
       isFileExisted = new File("/sys/fs/selinux/enforce").exists();
   } catch (Exception ignored) { }
   return isFileExisted;
}

private static boolean hasGetEnforce() {
   boolean isFileExisted = false;  
   try {
       isFileExisted = (new File("/system/bin/getenforce").exists());
   } catch (Exception ignored) {}  

   return isFileExisted;
} }