Android intent security

From huytran1120/vie-agentic-skills · View interactive version

Android intent security is an AI agent skill from the GitHub repository huytran1120/vie-agentic-skills. Best practices for Android Intent security. Use this skill when auditing component configurations in AndroidManifest.xml activities, services, receivers) or source code handling incoming Intents (getIntent, getParcelableExtra) to prevent Intent Redirection and unauthorized access.

How to use this skill

Skill file

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.

Glossary

Prerequisites

Limitations

Setup and dependencies

*

Intent security logic and decisions

1. Intent routing comparison

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) |

2. PendingIntent mutability flag options

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) |

3. Intent handling and redirection logic

IF (the component receives a nested Intent as an extra) {

IF (AndroidX Core 1.9.0+ and higher is available) {

MUST construct an IntentSanitizer to explicitly allowlist 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 match an explicitly allowlisted component.

}

NEVER launch the nested Intent directly without validation.

} ELSE IF (the component handles broadcasts) {

MUST rely on the system's Protected Broadcast mechanism for system events (which guarantees 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 <permission android:name="${applicationId}.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION" android:protectionLevel="signature" /> and <uses-permission android:name="${applicationId}.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION" /> are declared in AndroidManifest.xml.

}

}

4. PendingIntent security logic

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.

}

}

5. ContentProvider security logic

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.

}

6. Service caller verification logic

IF (an exported service communicates with trusted sister/partner apps) {

MUST expose a cross-process interface (such as an AIDL Stub or Messenger) rather than a local Binder subclass, which only works within the same process.

MUST verify the caller on every IPC request---using Binder.getCallingUid() inside an AIDL Stub method (or onTransact()) or Message.sendingUid in a Messenger Handler---and verify that the calling package signature fingerprint matches your trusted certificate hash.

}

*

Code and configuration patterns

1. Safe intent redirection (manual verification)

Validate the target of a nested intent before launching it when modern

sanitization libraries are unavailable.

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")
        }
    }
}

<br />

2. Safe intent redirection using IntentSanitizer

Filter or reject dynamic intents using AndroidX IntentSanitizer (AndroidX Core

1.9.0+).

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)
}

<br />

3. Custom signature permission protection

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" />

<br />

<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>

<br />

4. Safe onNewIntent lifecycle verification (warm boot protection)

Ensure that activities reusing dynamic intents (for example, in background

launch paths) apply the same strict security filters inside onNewIntent.

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")
}

<br />

5. Secure PendingIntent creation

Enforce immutability unless mutability is explicitly required.

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
    )
}

<br />

6. Secure ContentProvider configuration and queries

Expose a ContentProvider securely and parameterize queries to prevent SQL

injection.

<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" />

<br />

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)
}

<br />

7. Service caller signature verification

Verify the calling application's signing certificate on incoming cross-process

IPC calls in an exported bound service.

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="
    }

    override fun onBind(intent: Intent): IBinder {
        // Return the binder. Do NOT perform signature verification in onBind() because
        // the binder connection is cached by Android, which can bypass checks on subsequent binds.
        return LocalBinder()
    }

    private fun enforceTrustedCaller() {
        val callingUid = Binder.getCallingUid()
        // Allow calls from the same application
        if (callingUid == Process.myUid()) {
            return
        }
        val pm = packageManager
        val packages = pm.getPackagesForUid(callingUid)

        if (packages.isNullOrEmpty() || !verifySignature(pm, packages[0])) {
            throw SecurityException("Access Denied: Caller signature is untrusted.")
        }
    }

    private fun verifySignature(pm: PackageManager, packageName: String): Boolean {
        try {
            val trustedSha256Raw = Base64.decode(TRUSTED_PARTNER_SHA256, Base64.DEFAULT)
            // API 28+ handles rotated certificates and avoids manual hashing.
            // Since minSdk is 36, this is always available.
            return pm.hasSigningCertificate(packageName, trustedSha256Raw, PackageManager.CERT_INPUT_SHA256)
        } catch (e: Exception) {
            Log.e("SECURITY_ERROR", "Verification failed for package: $packageName", e)
        }
        return false
    }

    inner class LocalBinder : Binder() {
        fun doSecureWork() {
            // Verify caller identity on every transaction method call
            enforceTrustedCaller()
            // Safe to proceed with sensitive operations
        }
    }
}

<br />

*

Error handling

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)
    }
}

<br />

// Secure handling of ContentProvider queries on the client side:

try {

val cursor = contentResolver.query(providerUri, projection, selection, selectionArgs, null)

} catch (e: SQLiteException) {

Log.e("PROVIDER_ERROR", "ContentProvider database query failed", e)

// Secure handling: prevent raw query syntax details from leaking to UI

}

*

Reporting guidelines

When this skill is executed to apply security hardening updates to a codebase,

the agent MUST generate a structured "Best Practices and Security Alignment

Update" report for the developer. The report must be written to the session

artifact folder (or printed in the final response) and include:

  1. Security alignment area: The category of improvement applied (for example, Safe Intent Redirection, Secure PendingIntent Configuration, ContentProvider Data Guarding).
  2. Impact and priority: The potential safety risk addressed by the update (for example, Component Hijacking Prevention, Private Data Isolation).
  3. Scope of changes: A list of all modified classes, XML files, and dependencies.
  4. Implementation summary: Concrete details of the solution (for example, "Updated nested intent parsing to use the IntentSanitizer API with a strict component allowlist").
  5. Code diff: Standard unified diffs showing the exact modifications.

Best practices and security alignment update template

Use the following markdown template when reporting changes to developers:

### Best practices and security alignment update: [Security Alignment Area]

#### Files modified

#### 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\] \\\`

*

Antipatterns

Best Practices

VAS installation notes

Distributed from android/skills at

6daa53ef27fa2aa87827d183a85c06cedceca833 under Apache-2.0, by Google LLC and

the Android Open Source Project. Original copyright headers are retained and

the complete upstream LICENSE.txt is included with every standalone skill.

Only the frontmatter description/license formatting and these VAS notes differ;

the original workflow and all supporting files are preserved.

Use the VAS website's Copy Agent Prompt or ./vas install <skill-id> --target <agent>

with VAS's existing agent-folder mapping. Installing this skill only copies or

links its files and writes the CLI-compatible receipt. It does not install or

update Android CLI, SDK, Gradle, JDK, Python packages, plugins, MCP servers,

models or native binaries, connect to devices/services, run bundled helpers,

collect traces or send app source, credentials or application data.

Before using a workflow, check the project's compatible SDK/JDK/Gradle/library

versions and any required device, emulator, preview access or account. External

documentation, libraries, model weights and services are not bundled snapshots

and may have separate terms. Obtain explicit permission before downloads,

installer execution, package installation, telemetry, network requests, device

changes, sensitive-data processing or paid operations. Review downloaded code

and its provenance before execution; never pipe a network installer into a shell.

Surface missing prerequisites and command failures rather than inventing results.

The r8-analyzer protobuf converter needs a compatible google.protobuf runtime

(the bundled generated module declares version 6.33.4); this dependency is not

installed automatically. Its keep_radius_pb2.py helper is bundled locally.

play-policy-insights includes its scanner, scraper and template_engine helpers;

scraping Play Store pages requires network access and consent, and its report

is assistance, not a guarantee of Google Play approval or legal compliance.

android-profiler includes the upstream Perfetto Python launcher, not native

Perfetto binaries: running it can download/cache and execute a platform binary.

Review its pinned URL/hash and cache destination before approving execution.

Keep upstream executable permissions; the launcher is non-executable upstream

and can be invoked with python3 only after approval. No helpers were run and

no runtime packages or external binaries were installed during this import.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.