Skip to content

MASTG-DEMO-0087: Uses of Root Detection Techniques with Semgrep

Download MASTG-DEMO-0087 APK Open MASTG-DEMO-0087 Folder Build MASTG-DEMO-0087 APK

Sample

This sample demonstrates common root detection techniques used in Android applications, including:

  • Checking for the su binary in common locations
  • Checking for the su binary using the which command
  • Detecting root management packages using PackageManager
  • Identifying test-keys builds indicating custom ROMs
  • Reading system properties that may indicate root or debugging

To ensure that the requests using PackageManager.getPackageInfo work as expected, the app includes the relevant <queries> element in the AndroidManifest.xml.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package org.owasp.mastestapp

import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import java.io.File

// SUMMARY: This sample demonstrates common root detection techniques used in Android applications.

class MastgTest(private val context: Context) {

    private val tag = "MASTG.RootDetect"

    fun mastgTest(): String {
        val checks = mutableListOf<String>()
        Log.i(tag, "Starting root detection checks")

        val su = checkForSuBinary()
        checks.add(if (su) "✓ Found su binary" else "✗ No su binary found")

        val whichSu = checkForWhichSu()
        checks.add(if (whichSu) "✓ Found su via which command" else "✗ su not found via which command")

        val pkgs = checkForRootPackages()
        checks.add(if (pkgs) "✓ Found root management apps" else "✗ No root management apps found")

        val testKeys = checkForTestKeys()
        checks.add(if (testKeys) "✓ Device has test-keys build" else "✗ Device has release-keys build")

        val props = checkForDangerousProps()
        checks.add(if (props) "✓ Found dangerous system properties" else "✗ No dangerous system properties")

        val isRooted = su || whichSu || pkgs || testKeys || props
        Log.i(tag, "Completed checks: rooted=$isRooted")

        return "Root Detection Results:\n\n" +
                checks.joinToString("\n") +
                "\n\nDevice appears to be rooted: $isRooted"
    }

    private fun checkForSuBinary(): Boolean {
        val paths = arrayOf(
            "/system/app/Superuser.apk",
            "/sbin/su",
            "/system/bin/su",
            "/system/xbin/su",
            "/data/local/xbin/su",
            "/data/local/bin/su",
            "/system/sd/xbin/su",
            "/system/bin/failsafe/su",
            "/data/local/su",
            "/su/bin/su"
        )

        Log.d(tag, "checkForSuBinary: testing ${paths.size} paths")

        var found = false
        for (path in paths) {
            try {
                val exists = File(path).exists()
                Log.d(tag, "su path check: path=$path, exists=$exists")
                if (exists) found = true
            } catch (se: SecurityException) {
                Log.w(tag, "su path check blocked: path=$path, msg=${se.message}")
            } catch (t: Throwable) {
                Log.w(
                    tag,
                    "su path check error: path=$path, err=${t::class.java.simpleName}, msg=${t.message}"
                )
            }
        }

        Log.i(tag, "checkForSuBinary result: found=$found")
        return found
    }

    private fun checkForWhichSu(): Boolean {
        return try {
            Log.d(tag, "checkForWhichSu: executing which su")
            val process = Runtime.getRuntime().exec(arrayOf("which", "su"))

            val stdout = process.inputStream.bufferedReader().use { it.readText().trim() }
            val stderr = process.errorStream.bufferedReader().use { it.readText().trim() }
            val exit = try { process.waitFor() } catch (_: Throwable) { -1 }

            val found = stdout.isNotEmpty() && exit == 0
            if (found) {
                Log.i(tag, "su found via which: path=$stdout")
            } else {
                Log.d(
                    tag,
                    "which su not found: exit=$exit, stderr=$stderr"
                )
            }
            found
        } catch (se: SecurityException) {
            Log.w(
                tag,
                "checkForWhichSu blocked: msg=${se.message}"
            )
            false
        } catch (t: Throwable) {
            Log.w(
                tag,
                "checkForWhichSu error: err=${t::class.java.simpleName}, msg=${t.message}"
            )
            false
        }
    }

    private fun checkForRootPackages(): Boolean {
        val packages = arrayOf(
            "com.noshufou.android.su",
            "com.noshufou.android.su.elite",
            "eu.chainfire.supersu",
            "com.koushikdutta.superuser",
            "com.thirdparty.superuser",
            "com.yellowes.su",
            "com.topjohnwu.magisk",
            "com.kingroot.kinguser",
            "com.kingo.root",
            "com.smedialink.oneclickroot",
            "com.zhiqupk.root.global",
            "com.alephzain.framaroot"
        )

        Log.d(tag, "checkForRootPackages: testing ${packages.size} package names")

        var foundAny = false
        for (packageName in packages) {
            try {
                context.packageManager.getPackageInfo(packageName, 0)
                Log.i(tag, "root package detected: package=$packageName")
                foundAny = true
            } catch (_: PackageManager.NameNotFoundException) {
                Log.d(tag, "root package not present: package=$packageName")
            } catch (se: SecurityException) {
                Log.w(
                    tag,
                    "package check blocked: package=$packageName, msg=${se.message}"
                )
            } catch (t: Throwable) {
                Log.w(
                    tag,
                    "package check error: package=$packageName, err=${t::class.java.simpleName}, msg=${t.message}"
                )
            }
        }

        Log.i(tag, "checkForRootPackages result: found=$foundAny")
        return foundAny
    }

    private fun checkForTestKeys(): Boolean {
        val buildTags = Build.TAGS
        val isTestKeys = buildTags != null && buildTags.contains("test-keys")
        Log.i(
            tag,
            "checkForTestKeys: buildTags=$buildTags, isTestKeys=$isTestKeys"
        )
        return isTestKeys
    }

    private fun checkForDangerousProps(): Boolean {
        val dangerousProps = mapOf(
            "ro.debuggable" to "1",
            "ro.secure" to "0"
        )

        Log.d(
            tag,
            "checkForDangerousProps: testing ${dangerousProps.size} properties"
        )

        var matchedAny = false
        for ((prop, expected) in dangerousProps) {
            val actual = getSystemProperty(prop)
            val matched = actual == expected
            Log.i(
                tag,
                "system property check: prop=$prop, actual=$actual, expected=$expected, matched=$matched"
            )
            if (matched) matchedAny = true
        }

        Log.i(tag, "checkForDangerousProps result: matched=$matchedAny")
        return matchedAny
    }

    private fun getSystemProperty(key: String): String? {
        return try {
            Log.d(tag, "getSystemProperty exec: key=$key")
            val process = Runtime.getRuntime().exec(arrayOf("getprop", key))

            val stdout = process.inputStream.bufferedReader().use { it.readText().trim() }
            val stderr = process.errorStream.bufferedReader().use { it.readText().trim() }
            val exit = try { process.waitFor() } catch (_: Throwable) { -1 }

            if (stderr.isNotEmpty()) {
                Log.w(
                    tag,
                    "getprop stderr: key=$key, exit=$exit, stderr=$stderr"
                )
            } else {
                Log.d(
                    tag,
                    "getprop ok: key=$key, exit=$exit"
                )
            }

            stdout.ifEmpty { null }
        } catch (se: SecurityException) {
            Log.w(
                tag,
                "getSystemProperty blocked: key=$key, msg=${se.message}"
            )
            null
        } catch (t: Throwable) {
            Log.w(
                tag,
                "getSystemProperty error: key=$key, err=${t::class.java.simpleName}, msg=${t.message}"
            )
            null
        }
    }
}
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package org.owasp.mastestapp;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import kotlin.Metadata;
import kotlin.TuplesKt;
import kotlin.collections.CollectionsKt;
import kotlin.collections.MapsKt;
import kotlin.io.CloseableKt;
import kotlin.io.TextStreamsKt;
import kotlin.jvm.internal.Intrinsics;
import kotlin.text.Charsets;
import kotlin.text.StringsKt;

/* compiled from: MastgTest.kt */
@Metadata(d1 = {"\u0000\"\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0000\n\u0002\u0018\u0002\n\u0002\b\u0003\n\u0002\u0010\u000e\n\u0002\b\u0002\n\u0002\u0010\u000b\n\u0002\b\u0007\b\u0007\u0018\u00002\u00020\u0001B\u000f\u0012\u0006\u0010\u0002\u001a\u00020\u0003¢\u0006\u0004\b\u0004\u0010\u0005J\u0006\u0010\b\u001a\u00020\u0007J\b\u0010\t\u001a\u00020\nH\u0002J\b\u0010\u000b\u001a\u00020\nH\u0002J\b\u0010\f\u001a\u00020\nH\u0002J\b\u0010\r\u001a\u00020\nH\u0002J\b\u0010\u000e\u001a\u00020\nH\u0002J\u0012\u0010\u000f\u001a\u0004\u0018\u00010\u00072\u0006\u0010\u0010\u001a\u00020\u0007H\u0002R\u000e\u0010\u0002\u001a\u00020\u0003X\u0082\u0004¢\u0006\u0002\n\u0000R\u000e\u0010\u0006\u001a\u00020\u0007X\u0082D¢\u0006\u0002\n\u0000¨\u0006\u0011"}, d2 = {"Lorg/owasp/mastestapp/MastgTest;", "", "context", "Landroid/content/Context;", "<init>", "(Landroid/content/Context;)V", "tag", "", "mastgTest", "checkForSuBinary", "", "checkForWhichSu", "checkForRootPackages", "checkForTestKeys", "checkForDangerousProps", "getSystemProperty", "key", "app_debug"}, k = 1, mv = {2, 0, 0}, xi = 48)
/* loaded from: classes3.dex */
public final class MastgTest {
    public static final int $stable = 8;
    private final Context context;
    private final String tag;

    public MastgTest(Context context) {
        Intrinsics.checkNotNullParameter(context, "context");
        this.context = context;
        this.tag = "MASTG.RootDetect";
    }

    public final String mastgTest() {
        List checks = new ArrayList();
        Log.i(this.tag, "Starting root detection checks");
        boolean su = checkForSuBinary();
        checks.add(su ? "✓ Found su binary" : "✗ No su binary found");
        boolean whichSu = checkForWhichSu();
        checks.add(whichSu ? "✓ Found su via which command" : "✗ su not found via which command");
        boolean pkgs = checkForRootPackages();
        checks.add(pkgs ? "✓ Found root management apps" : "✗ No root management apps found");
        boolean testKeys = checkForTestKeys();
        checks.add(testKeys ? "✓ Device has test-keys build" : "✗ Device has release-keys build");
        boolean props = checkForDangerousProps();
        checks.add(props ? "✓ Found dangerous system properties" : "✗ No dangerous system properties");
        boolean isRooted = su || whichSu || pkgs || testKeys || props;
        Log.i(this.tag, "Completed checks: rooted=" + isRooted);
        return "Root Detection Results:\n\n" + CollectionsKt.joinToString$default(checks, "\n", null, null, 0, null, null, 62, null) + "\n\nDevice appears to be rooted: " + isRooted;
    }

    private final boolean checkForSuBinary() {
        String[] paths = {"/system/app/Superuser.apk", "/sbin/su", "/system/bin/su", "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su", "/system/bin/failsafe/su", "/data/local/su", "/su/bin/su"};
        Log.d(this.tag, "checkForSuBinary: testing " + paths.length + " paths");
        boolean found = false;
        for (String path : paths) {
            try {
                boolean exists = new File(path).exists();
                Log.d(this.tag, "su path check: path=" + path + ", exists=" + exists);
                if (exists) {
                    found = true;
                }
            } catch (SecurityException se) {
                Log.w(this.tag, "su path check blocked: path=" + path + ", msg=" + se.getMessage());
            } catch (Throwable t) {
                Log.w(this.tag, "su path check error: path=" + path + ", err=" + t.getClass().getSimpleName() + ", msg=" + t.getMessage());
            }
        }
        Log.i(this.tag, "checkForSuBinary result: found=" + found);
        return found;
    }

    private final boolean checkForWhichSu() {
        int exit;
        try {
            Log.d(this.tag, "checkForWhichSu: executing which su");
            boolean found = true;
            Process process = Runtime.getRuntime().exec(new String[]{"which", "su"});
            InputStream inputStream = process.getInputStream();
            Intrinsics.checkNotNullExpressionValue(inputStream, "getInputStream(...)");
            Reader inputStreamReader = new InputStreamReader(inputStream, Charsets.UTF_8);
            BufferedReader bufferedReader = inputStreamReader instanceof BufferedReader ? (BufferedReader) inputStreamReader : new BufferedReader(inputStreamReader, 8192);
            try {
                BufferedReader it = bufferedReader;
                String stdout = StringsKt.trim((CharSequence) TextStreamsKt.readText(it)).toString();
                CloseableKt.closeFinally(bufferedReader, null);
                InputStream errorStream = process.getErrorStream();
                Intrinsics.checkNotNullExpressionValue(errorStream, "getErrorStream(...)");
                Reader inputStreamReader2 = new InputStreamReader(errorStream, Charsets.UTF_8);
                bufferedReader = inputStreamReader2 instanceof BufferedReader ? (BufferedReader) inputStreamReader2 : new BufferedReader(inputStreamReader2, 8192);
                try {
                    BufferedReader it2 = bufferedReader;
                    String stderr = StringsKt.trim((CharSequence) TextStreamsKt.readText(it2)).toString();
                    CloseableKt.closeFinally(bufferedReader, null);
                    try {
                        exit = process.waitFor();
                    } catch (Throwable th) {
                        exit = -1;
                    }
                    if (!(stdout.length() > 0) || exit != 0) {
                        found = false;
                    }
                    if (found) {
                        Log.i(this.tag, "su found via which: path=" + stdout);
                    } else {
                        Log.d(this.tag, "which su not found: exit=" + exit + ", stderr=" + stderr);
                    }
                    return found;
                } finally {
                }
            } finally {
            }
        } catch (SecurityException se) {
            Log.w(this.tag, "checkForWhichSu blocked: msg=" + se.getMessage());
            return false;
        } catch (Throwable t) {
            Log.w(this.tag, "checkForWhichSu error: err=" + t.getClass().getSimpleName() + ", msg=" + t.getMessage());
            return false;
        }
    }

    private final boolean checkForRootPackages() {
        String[] packages = {"com.noshufou.android.su", "com.noshufou.android.su.elite", "eu.chainfire.supersu", "com.koushikdutta.superuser", "com.thirdparty.superuser", "com.yellowes.su", "com.topjohnwu.magisk", "com.kingroot.kinguser", "com.kingo.root", "com.smedialink.oneclickroot", "com.zhiqupk.root.global", "com.alephzain.framaroot"};
        Log.d(this.tag, "checkForRootPackages: testing " + packages.length + " package names");
        boolean foundAny = false;
        for (String packageName : packages) {
            try {
                this.context.getPackageManager().getPackageInfo(packageName, 0);
                Log.i(this.tag, "root package detected: package=" + packageName);
                foundAny = true;
            } catch (PackageManager.NameNotFoundException e) {
                Log.d(this.tag, "root package not present: package=" + packageName);
            } catch (SecurityException se) {
                Log.w(this.tag, "package check blocked: package=" + packageName + ", msg=" + se.getMessage());
            } catch (Throwable t) {
                Log.w(this.tag, "package check error: package=" + packageName + ", err=" + t.getClass().getSimpleName() + ", msg=" + t.getMessage());
            }
        }
        Log.i(this.tag, "checkForRootPackages result: found=" + foundAny);
        return foundAny;
    }

    private final boolean checkForTestKeys() {
        String buildTags = Build.TAGS;
        boolean isTestKeys = false;
        if (buildTags != null && StringsKt.contains$default((CharSequence) buildTags, (CharSequence) "test-keys", false, 2, (Object) null)) {
            isTestKeys = true;
        }
        Log.i(this.tag, "checkForTestKeys: buildTags=" + buildTags + ", isTestKeys=" + isTestKeys);
        return isTestKeys;
    }

    private final boolean checkForDangerousProps() {
        Map dangerousProps = MapsKt.mapOf(TuplesKt.to("ro.debuggable", "1"), TuplesKt.to("ro.secure", "0"));
        Log.d(this.tag, "checkForDangerousProps: testing " + dangerousProps.size() + " properties");
        boolean matchedAny = false;
        for (Map.Entry entry : dangerousProps.entrySet()) {
            String prop = (String) entry.getKey();
            String expected = (String) entry.getValue();
            String actual = getSystemProperty(prop);
            boolean matched = Intrinsics.areEqual(actual, expected);
            Log.i(this.tag, "system property check: prop=" + prop + ", actual=" + actual + ", expected=" + expected + ", matched=" + matched);
            if (matched) {
                matchedAny = true;
            }
        }
        Log.i(this.tag, "checkForDangerousProps result: matched=" + matchedAny);
        return matchedAny;
    }

    private final String getSystemProperty(String key) {
        int exit;
        try {
            Log.d(this.tag, "getSystemProperty exec: key=" + key);
            Process process = Runtime.getRuntime().exec(new String[]{"getprop", key});
            InputStream inputStream = process.getInputStream();
            Intrinsics.checkNotNullExpressionValue(inputStream, "getInputStream(...)");
            Reader inputStreamReader = new InputStreamReader(inputStream, Charsets.UTF_8);
            BufferedReader bufferedReader = inputStreamReader instanceof BufferedReader ? (BufferedReader) inputStreamReader : new BufferedReader(inputStreamReader, 8192);
            try {
                BufferedReader it = bufferedReader;
                String stdout = StringsKt.trim((CharSequence) TextStreamsKt.readText(it)).toString();
                CloseableKt.closeFinally(bufferedReader, null);
                InputStream errorStream = process.getErrorStream();
                Intrinsics.checkNotNullExpressionValue(errorStream, "getErrorStream(...)");
                Reader inputStreamReader2 = new InputStreamReader(errorStream, Charsets.UTF_8);
                bufferedReader = inputStreamReader2 instanceof BufferedReader ? (BufferedReader) inputStreamReader2 : new BufferedReader(inputStreamReader2, 8192);
                try {
                    BufferedReader it2 = bufferedReader;
                    String stderr = StringsKt.trim((CharSequence) TextStreamsKt.readText(it2)).toString();
                    CloseableKt.closeFinally(bufferedReader, null);
                    try {
                        exit = process.waitFor();
                    } catch (Throwable th) {
                        exit = -1;
                    }
                    if (stderr.length() > 0) {
                        Log.w(this.tag, "getprop stderr: key=" + key + ", exit=" + exit + ", stderr=" + stderr);
                    } else {
                        Log.d(this.tag, "getprop ok: key=" + key + ", exit=" + exit);
                    }
                    String str = stdout;
                    if (str.length() == 0) {
                        str = null;
                    }
                    return str;
                } finally {
                    try {
                        throw th;
                    } finally {
                    }
                }
            } finally {
            }
        } catch (SecurityException se) {
            Log.w(this.tag, "getSystemProperty blocked: key=" + key + ", msg=" + se.getMessage());
            return null;
        } catch (Throwable t) {
            Log.w(this.tag, "getSystemProperty error: key=" + key + ", err=" + t.getClass().getSimpleName() + ", msg=" + t.getMessage());
            return null;
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET" />

    <queries>
        <package android:name="com.noshufou.android.su" />
        <package android:name="com.noshufou.android.su.elite" />
        <package android:name="eu.chainfire.supersu" />
        <package android:name="com.koushikdutta.superuser" />
        <package android:name="com.thirdparty.superuser" />
        <package android:name="com.yellowes.su" />
        <package android:name="com.topjohnwu.magisk" />
        <package android:name="com.kingroot.kinguser" />
        <package android:name="com.kingo.root" />
        <package android:name="com.smedialink.oneclickroot" />
        <package android:name="com.zhiqupk.root.global" />
        <package android:name="com.alephzain.framaroot" />
    </queries>

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MASTestApp"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:windowSoftInputMode="adjustResize"
            android:theme="@style/Theme.MASTestApp">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Steps

Let's run semgrep with the following rule:

../../../../rules/mastg-android-root-detection.yaml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
rules:
  - id: mastg-android-root-detection-file-checks
    severity: INFO
    languages: [java]
    metadata:
      summary: Detection of file existence checks commonly used for root detection
    message: "[MASVS-RESILIENCE-1] The app checks for file existence, which may be part of root detection implementation."
    pattern: new File($PATH).exists()
    metavariable-regex:
      metavariable: $PATH
      regex: '.*(su|magisk|Superuser\.apk).*'

  - id: mastg-android-root-detection-package-check
    severity: INFO
    languages: [java]
    metadata:
      summary: Detection of package manager checks that may be used for root detection
    message: "[MASVS-RESILIENCE-1] The app checks for installed packages, which may be looking for root management apps."
    pattern: $PM.getPackageInfo($PKG, ...)

  - id: mastg-android-root-detection-test-keys
    severity: INFO
    languages: [java]
    metadata:
      summary: Detection of test-keys build check for root/custom ROM detection
    message: "[MASVS-RESILIENCE-1] The app checks Build.TAGS for test-keys, indicating custom ROM or root detection."
    pattern-either:
      - pattern: Build.TAGS.contains("test-keys")
      - patterns:
          - pattern: $TAGS.contains("test-keys")
          - pattern-inside: |
              $TAGS = Build.TAGS;
              ...
      - patterns:
          - pattern: StringsKt.contains$default(..., "test-keys", ...)
          - pattern-inside: |
              $TAGS = Build.TAGS;
              ...

  - id: mastg-android-root-detection-system-properties
    severity: INFO
    languages: [java]
    metadata:
      summary: Detection of system property checks via getprop
    message: "[MASVS-RESILIENCE-1] The app reads system properties via getprop, which may be checking for root indicators."
    pattern-either:
      - pattern: Runtime.getRuntime().exec("getprop " + $PROP)
      - pattern: Runtime.getRuntime().exec(new String[] { "getprop", $PROP })

  - id: mastg-android-root-detection-runtime-exec
    severity: INFO
    languages: [java]
    metadata:
      summary: Detection of Runtime.exec calls that may be used for root detection
    message: "[MASVS-RESILIENCE-1] The app uses Runtime.exec(), which may be attempting to execute su or other commands for root detection."
    patterns:
      - pattern: Runtime.getRuntime().exec($CMD)
      - pattern-not: Runtime.getRuntime().exec("getprop " + $PROP)
      - pattern-not: Runtime.getRuntime().exec(new String[] { "getprop", $PROP })
run.sh
1
2
3
#!/bin/bash

NO_COLOR=true semgrep -c ../../../../rules/mastg-android-root-detection.yaml ./MastgTest_reversed.java > output.txt

Observation

The output shows all locations where root detection checks are implemented in the code.

output.txt
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
┌─────────────────┐
 5 Code Findings 
└─────────────────┘

    MastgTest_reversed.java
      rules.mastg-android-root-detection-file-checks
          [MASVS-RESILIENCE-1] The app checks for file existence, which may be part of root detection
          implementation.                                                                            

           63 boolean exists = new File(path).exists();

      rules.mastg-android-root-detection-runtime-exec
          [MASVS-RESILIENCE-1] The app uses Runtime.exec(), which may be attempting to execute su or other
          commands for root detection.                                                                    

           83 Process process = Runtime.getRuntime().exec(new String[]{"which", "su"});

      rules.mastg-android-root-detection-package-check
          [MASVS-RESILIENCE-1] The app checks for installed packages, which may be looking for root management
          apps.                                                                                               

          133 this.context.getPackageManager().getPackageInfo(packageName, 0);

      rules.mastg-android-root-detection-test-keys
          [MASVS-RESILIENCE-1] The app checks Build.TAGS for test-keys, indicating custom ROM or root
          detection.                                                                                 

          151 if (buildTags != null && StringsKt.contains$default((CharSequence) buildTags,
               (CharSequence) "test-keys", false, 2, (Object) null)) {                      

      rules.mastg-android-root-detection-system-properties
          [MASVS-RESILIENCE-1] The app reads system properties via getprop, which may be checking for root
          indicators.                                                                                     

          180 Process process = Runtime.getRuntime().exec(new String[]{"getprop", key});

Evaluation

The test passes because the output shows multiple root detection implementations:

  • Line 63: File existence checks for su binaries and root-related files
  • Line 83: which su command execution
  • Line 133: PackageManager checks for root management apps
  • Line 151: Build.TAGS check for test-keys indicating custom ROM
  • Line 180: Runtime.exec() and getprop calls to read system properties