Android Fragment Injection
ID |
kotlin.android_fragment_injection |
Severity |
critical |
Resource |
Injection |
Language |
Kotlin |
Tags |
CWE:470, NIST.SP.800-53, PCI-DSS:6.5.1, android |
Description
Android Fragment Injection vulnerabilities occur when fragments are instantiated using unvalidated user input, allowing potential injection of unintended fragments into an activity.
Rationale
When an application allows fragments to be instantiated from names provided by external sources, it risks exposing sensitive activities to fragment injection. This vulnerability can be exploited by a malicious app to inject arbitrary fragments, bypassing intended access controls. Fragments are building blocks of an Android UI that depend on activities for hosting; thus, exporting an activity without proper fragment validation can lead to security breaches.
Consider the following Kotlin example:
class MyActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val fragmentName = intent.getStringExtra("fragmentName")
if (isValidFragment(fragmentName)) {
try {
// Safe instantiation
supportFragmentManager.beginTransaction()
.replace(android.R.id.content, Class.forName(fragmentName!!).newInstance() as Fragment)
.commit()
} catch (e: Exception) {
// Handle instantiation errors
println("Error loading fragment")
}
} else {
// Handle invalid fragment case
println("Invalid fragment")
}
}
private fun isValidFragment(fragmentName: String?): Boolean {
// Allow only specified fragments
}
}
Remediation
To prevent fragment injection, always validate the fragment names before instantiation. This is especially crucial for activities extending PreferenceActivity. Implement checks to ensure only trusted fragments are loaded.
Practical Remediation Steps for Kotlin:
-
Validate Fragment Names: Always sanitize and validate fragment names against a list of trusted fragments.
-
Override isValidFragment: For activities extending
PreferenceActivity, overrideisValidFragmentto check fragment names rigorously. -
Use Static Instantiation: Prefer static, predefined fragment names to safeguard against injection.
References
-
CWE-470 : Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')