/android-kotlin:android-intent-securityfrom android-kotlin
Audits, detects, and remediates Android Intent and component security
Ships in android-kotlin. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
This skill provides guidelines and patterns to secure Android components (Activities, Services, Broadcast Receivers, Content Providers) and handle Intents safely, preventing privilege escalation and unauthorized access.
android:exported="true") accessible to other apps on the device.signature, granted only to apps signed with the same developer key.FLAG_ACTIVITY_SINGLE_TOP and is already running at the top of the history stack.onCreate, onNewIntent, and the singleTop launch mode.<activity>, <service>, <receiver>, and <provider> tags in AndroidManifest.xml and define their android:exported and android:permission attributes.PackageManager.androidx.core:core:1.9.0 or higher is mandatory to leverage IntentSanitizer.PackageManager APIs are required for runtime component verification.Evaluate the security features of different intent delivery methods:
| Intent Delivery Method | Scope | Recommended Use Case |
|---|---|---|
| Explicit Intent (Internal) | App Private | Launching internal activities/services |
| Implicit Intent | System Wide | Launching system camera, dialer, or sharing |
| Local Broadcasts (LocalBroadcastManager) (DEPRECATED) | App Private | Internal asynchronous event routing. Deprecated: Use in-app observers like Kotlin Flows/SharedFlow, LiveData, or reactive patterns instead. |
| System Broadcasts | System Wide | Receiving system events (NFC, Bluetooth) |
Evaluate the security implications of PendingIntent mutability flags:
| Flag Name | Mutability | Recommended Use Case |
|---|---|---|
PendingIntent.FLAG_IMMUTABLE | Immutable | Default for almost all PendingIntents, such as alarms and notifications |
PendingIntent.FLAG_MUTABLE | Mutable | Inline notifications replies, slice actions (requires explicit target intent) |
IF (the component receives a nested Intent as an extra) {
IF (AndroidX Core 1.9.0+ and higher is available) {
MUST construct an IntentSanitizer with an explicit allowlist of
components, actions, data, and extras.
MUST call sanitizeByThrowing() or sanitizeByFiltering() before
launching.
} ELSE {
MUST reject or strip URI permission grant flags
(FLAG_GRANT_READ_URI_PERMISSION, FLAG_GRANT_WRITE_URI_PERMISSION,
FLAG_GRANT_PERSISTABLE_URI_PERMISSION,
FLAG_GRANT_PREFIX_URI_PERMISSION).
MUST resolve the target component using resolveActivity() and verify
that both its packageName and className are on an explicit
allowlist.
}
NEVER launch the nested Intent directly without validation.
}
IF (the component handles broadcasts) {
MUST rely on the system's Protected Broadcast mechanism for system events
(which verifies that the sender is the system framework).
MUST protect custom receivers with signature-level permissions or use
RECEIVER_NOT_EXPORTED for dynamic receivers to restrict the sender.
IF (using ContextCompat.registerReceiver with RECEIVER_NOT_EXPORTED AND
minSdk < 33) {
MUST verify that the
${applicationId}.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION
<permission> (with android:protectionLevel="signature") and
<uses-permission> elements are declared in AndroidManifest.xml.
}
}
IF (a PendingIntent is created for delivery to another application) {
MUST use PendingIntent.FLAG_IMMUTABLE by default.
IF (the PendingIntent must be mutable) {
MUST set the explicit target component or package name on the base
Intent.
NEVER create an implicit, mutable PendingIntent.
}
}
IF (the ContentProvider is only for internal app use) {
MUST set android:exported="false".
} ELSE {
MUST protect it with android:readPermission and android:writePermission.
MUST set android:grantUriPermissions="false" unless temporary URL access
is strictly required.
}
IF (an exported service communicates with trusted sister or partner apps) {
MUST expose a cross-process interface (such as an AIDL Stub or
Messenger) instead of a local Binder subclass.
MUST read the caller UID on every IPC request using
Binder.getCallingUid() in AIDL or Message.sendingUid in Messenger.
MUST reject callingUid == Process.myUid() so calls outside an active IPC
transaction fail closed.
MUST verify that the calling package signing certificate matches the
trusted certificate hash.
}
Validate the target of a nested intent before launching it when modern sanitization libraries are unavailable.
Intent containing a nested Intent extra named EXTRA_NESTED_INTENT.SecurityException if validation fails.fun safeIntentRedirectionManual() {
val nestedIntent = IntentCompat.getParcelableExtra(intent, "EXTRA_NESTED_INTENT", Intent::class.java)
if (nestedIntent != null) {
// 1. Check for URI permission grants to prevent URI permission bypass
val hasUriPermissionGrants = (
nestedIntent.flags and (
Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION or
Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION or
Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
)
) != 0
if (hasUriPermissionGrants) {
throw SecurityException("Nested intent contains forbidden URI permission grant flags!")
}
// 2. Clear any selector intent that could override resolution
nestedIntent.selector = null
// 3. Resolve the target activity and verify both packageName and className
// match the expected allowlisted destination
val target = nestedIntent.resolveActivity(packageManager)
if (target != null &&
target.packageName == packageName &&
target.className == TargetActivity::class.java.name
) {
// 4. Explicitly pin the resolved component to prevent intent interception
nestedIntent.component = target
startActivity(nestedIntent)
} else {
throw SecurityException("Invalid or disallowed redirect target: $target")
}
}
}
Filter or reject dynamic intents using AndroidX IntentSanitizer (AndroidX Core
1.9.0+).
Intent.Intent: A sanitized copy containing only components, categories, and actions on the allowlist. Throws SecurityException on violations if using sanitizeByThrowing().fun safeIntentRedirectionSanitizer() {
// Allowlist: anything NOT listed is rejected (only component is required; other fields are optional).
// No allowFlags(): every flag, including FLAG_GRANT_*_URI_PERMISSION, is rejected.
val sanitizer = IntentSanitizer.Builder()
.allowComponent(ComponentName(this, TargetActivity::class.java))
.allowAction(Intent.ACTION_VIEW)
.allowData { it.scheme == ContentResolver.SCHEME_CONTENT && it.authority == "$packageName.provider" }
.allowType("text/plain")
.allowExtra("user_display_name", String::class.java) { it.length <= 100 } // type and content
.build()
val safeIntent = try {
val untrusted = IntentCompat.getParcelableExtra(intent, "EXTRA_NESTED_INTENT", Intent::class.java)
?: return
sanitizer.sanitizeByThrowing(untrusted)
} catch (_: SecurityException) {
Log.w("SECURITY_ALERT", "Blocked non-allowlisted nested intent")
return
} catch (_: BadParcelableException) { // e.g. an extra naming an unknown Parcelable/Serializable
Log.w("SECURITY_ALERT", "Malformed nested intent")
return
}
// The sanitizer doesn't enforce presence; check what the target actually requires.
if (safeIntent.getStringExtra("user_display_name") == null) {
Log.w("SECURITY_ALERT", "Nested intent missing user_display_name")
return
}
startActivity(safeIntent)
}
Declare a custom signature-level permission in the manifest to secure family app communication.
<permission
android:name="com.example.snippets.permission.INTERNAL_COMMUNICATION"
android:protectionLevel="signature" />
<activity
android:name=".intents.InternalSharingActivity"
android:exported="true"
android:permission="com.example.snippets.permission.INTERNAL_COMMUNICATION">
<intent-filter>
<action android:name="com.example.snippets.ACTION_SHARE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Ensure that activities reusing dynamic intents (for example, in background
launch paths) apply the same strict security filters inside onNewIntent.
newIntent (Intent): The newly delivered intent.override fun onNewIntent(newIntent: Intent) {
super.onNewIntent(newIntent)
// Set the intent to ensure intent returns the new one
intent = newIntent
// Validate the intent payload
if (validateIntent(newIntent)) {
processIntentPayload(newIntent)
} else {
Log.w("SECURITY_ALERT", "Received invalid or insecure intent during warm boot")
}
}
private fun validateIntent(intent: Intent): Boolean {
return intent.hasExtra("VALID_PAYLOAD_MARKER")
}
Enforce immutability unless mutability is explicitly required.
PendingIntent that cannot be altered by the receiver.PendingIntent locked to a specific receiver component to prevent hijacking.fun createPendingIntents(context: Context) {
// 1. Secure Immutable PendingIntent (Default)
val intent = Intent(context, TargetActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
context,
0,
intent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
// 2. Secure Mutable PendingIntent (e.g., Notification Direct Reply)
val mutableIntent = Intent().apply {
// MUST set explicit target component to prevent redirection hijacking
component = ComponentName(context, ReplyReceiver::class.java)
}
val mutablePendingIntent = PendingIntent.getBroadcast(
context,
0,
mutableIntent,
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
}
Expose a ContentProvider securely and parameterize queries to prevent SQL injection.
uri (Uri): The query URI.projection (String[]): Columns to retrieve.selection (String): Query criteria.selectionArgs (String[]): Values mapping to selection placeholders (?).Cursor: Filtered query results, strictly bound to projection maps.<provider
android:name=".intents.SecureDataProvider"
android:authorities="com.example.snippets.provider"
android:exported="true"
android:readPermission="com.example.snippets.permission.READ_DATA"
android:writePermission="com.example.snippets.permission.WRITE_DATA"
android:grantUriPermissions="false" />
override fun query(
uri: Uri,
projection: Array<String>?,
selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?
): Cursor? {
val queryBuilder = SQLiteQueryBuilder()
queryBuilder.tables = tableName
// Strict projection map to prevent querying unauthorized columns
queryBuilder.projectionMap = mapOf(
"_id" to "_id",
"display_name" to "display_name"
)
// Enable strict validation (always available since minSdk is 36)
queryBuilder.setStrict(true)
queryBuilder.setStrictColumns(true)
queryBuilder.setStrictGrammar(true)
// MUST parameterize selection criteria; NEVER append selection strings directly
val db = dbHelper.readableDatabase
return queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder)
}
Verify the calling application's signing certificate on incoming cross-process IPC calls in an exported bound service.
Stub method call or onTransact()).SecurityException otherwise.class SecureBoundService : Service() {
companion object {
// Expected SHA-256 hash of the trusted app's signing certificate (Base64 encoded)
private const val TRUSTED_PARTNER_SHA256 = "A1B2C3D4E5F6G7H8I9J0K1L2M3N4O5P6Q7R8S9T0U1V="
}
// Use an AIDL Stub for cross-process IPC
private val binder = object : IMyService.Stub() {
override fun doSecureWork() {
// Verify caller identity inside the active Binder IPC transaction
enforceTrustedCaller()
// Safe to proceed with sensitive operations
}
}
override fun onBind(intent: Intent): IBinder {
// Return the AIDL Stub. Do NOT perform Binder.getCallingUid() checks in onBind()
// because onBind() is invoked asynchronously by system_server and the IBinder is cached.
return binder
}
private fun enforceTrustedCaller() {
val callingUid = Binder.getCallingUid()
if (callingUid == Process.myUid() || !verifyUidSignature(callingUid)) {
throw SecurityException("Access Denied: Unauthorized or local/cleared-identity caller.")
}
}
private fun verifyUidSignature(callingUid: Int): Boolean {
return try {
val trustedSha256Raw = Base64.decode(TRUSTED_PARTNER_SHA256, Base64.DEFAULT)
// PackageManager.hasSigningCertificate(uid, ...) (API 28+) checks the UID directly
// and handles certificate rotation.
packageManager.hasSigningCertificate(
callingUid,
trustedSha256Raw,
PackageManager.CERT_INPUT_SHA256
)
} catch (e: IllegalArgumentException) {
Log.e("SECURITY_ERROR", "Invalid certificate hash format", e)
false
}
}
}
Handle component binding, database queries, and intent redirection failures securely to avoid exposing internal structures.
fun safeErrorHandling(callingPackage: String?) {
try {
val payload = intent.getStringExtra("DATA_EXTRA") ?: throw IllegalArgumentException("Payload parameter missing.")
// Create a specific target intent using the validated payload
val targetIntent = Intent(this, TargetActivity::class.java).apply {
putExtra("SECURE_PAYLOAD", payload)
}
startActivity(targetIntent)
} catch (e: SecurityException) {
// MUST log security violations for audit, but NEVER expose exception details to the user.
Log.e("SECURITY_ERROR", "Unauthorized component transition blocked. Calling Package: ${callingPackage ?: "Unknown"}", e)
// MUST provide generic user feedback.
showFeedbackToUser("Process request failed: Access Denied.")
} catch (e: IllegalArgumentException) {
Log.w("INTEGRITY_WARNING", "Missing intent parameter", e)
}
}
When querying a ContentProvider on the client side, catch SQLiteException
and log a generic error message rather than exposing raw query syntax details
to the user interface.
When this skill is executed to apply security hardening updates to a codebase, the agent MUST generate a structured "Security Hardening and Alignment Update" report for the developer. The report must be written to the session artifact folder (or printed in the final response) and include:
IntentSanitizer API with a strict component allowlist").Use the following Markdown template when reporting changes to developers:
### Security hardening and alignment update: [Security Alignment Area]
* **Improvement Description:** [Brief description of the hardening update and why it's recommended]
* **Priority Level:** [High / Medium / Low]
* **Alignment Action:** [Summary of updates, for example, converted to FLAG_IMMUTABLE]
#### Files modified
* `[Relative path to File 1]`
* `[Relative path to File 2]`
#### Implementation diff
```diff
// Insert Unified Diff here
```
#### Testing and verification
1. [Step 1 to verify the component behaves correctly, for example, run
component unit test]
2. [Step 2 to verify regression safety]
Intent received from an untrusted source without verifying that its resolved component (packageName and className) matches an explicit allowlist and rejecting or stripping URI permission grant flags.sendStickyBroadcast).onNewIntent without applying the same security controls as onCreate.PendingIntent without setting an explicit target component in the base Intent.ContentProvider query.Binder.getCallingUid inside a BroadcastReceiver.onReceive to identify the sender of a broadcast, as it returns the receiver's own UID, not the sender's.android:exported="false" for all components that don't need external communication.android:protectionLevel="signature" when communicating between family apps.RECEIVER_NOT_EXPORTED for dynamic receivers to restrict the sender.${applicationId}.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION signature <permission> and <uses-permission> in AndroidManifest.xml when minSdk < 33.setIntent(newIntent) inside onNewIntent() before processing payloads to keep active references updated.PendingIntent.FLAG_IMMUTABLE by default when constructing PendingIntent instances.ContentProviders with readPermission and writePermission.ContentProvider query and update methods.Stub or Messenger.androidx.core.content.IntentSanitizer to sanitize incoming dynamic intents before redirection, if AndroidX Core 1.9.0+ is imported in the project.What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub fcakiroglu16/marketplace --plugin android-kotlin12 skills in this plugin
/edge-to-edgeUse this skill to migrate your Jetpack Compose app to add adaptive edge-to-edgeOther plugins' skills for the same job