This sample demonstrates the static detection of StrictMode in the app using Semgrep. The app enables a StrictMode policy to detect leaked SQLite objects and intentionally leaves a cursor unclosed to trigger the policy.
packageorg.owasp.mastestappimportandroid.content.Contextimportandroid.database.sqlite.SQLiteDatabaseimportandroid.os.StrictModeclassMastgTest(privatevalcontext:Context){funmastgTest():String{enableStrictMode()triggerSqliteCursorLeak()System.gc()// Force garbage collection to trigger leak detectionreturn"SUCCESS!!\n\nSQL Cursor leaked."}privatefunenableStrictMode(){StrictMode.setVmPolicy(StrictMode.VmPolicy.Builder().detectLeakedClosableObjects()// Detect leaked/unclosed SQLite objects.penaltyLog()// Log violations.build())}privatefuntriggerSqliteCursorLeak(){valdb:SQLiteDatabase=context.openOrCreateDatabase("test.db",Context.MODE_PRIVATE,null)db.execSQL("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")db.execSQL("INSERT INTO users (name) VALUES ('Alice'), ('Bob')")// Create cursor, and intentionally do not close itvalcursor=db.rawQuery("SELECT * FROM users",null)}}
rules:-id:mastg-android-strictmodeseverity:WARNINGlanguages:-javametadata:summary:ThisrulescansusesofStrictMode.message:"[MASVS-RESILIENCE] Detected usage of StrictMode"patterns:-pattern:StrictMode.setVmPolicy(...)