/android-android-permissions-security:android-permissions-securityfrom android-android-permissions-security
Audits Android permissions and IPC security: detects weak custom permissions, overly broad URI grants, and unprotected exported components. Guides remediation with signature/knownSigner enforcement and runtime permission flows.
Ships in android-android-permissions-security. 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.
Guidelines for auditing permission vulnerabilities, enforcing least privilege, securing IPC boundaries, and handling runtime permissions across the Android ecosystem.
<permission>) to restrict access to its exported components.normal, dangerous, signature, knownSigner).Binder.getCallingUid().grantUriPermissions and intent flags.androidx.core:core-ktx and androidx.activity:activity-ktx (or androidx.fragment:fragment-ktx) dependencies to the app-level build.gradle file for ContextCompat and ActivityResultContracts.knownSigner partner permissions (android:knownCerts), ensure the project compileSdk and targetSdk are at least 31 (Android 12).BroadcastOptions.setShareIdentityEnabled), ensure compileSdk and targetSdk are at least 34 (Android 14).When auditing an Android project for permission and IPC security vulnerabilities, systematically inspect each area:
| Vulnerability Area | Search In / Pattern | Risk | Remediation Action |
|---|---|---|---|
| Weak Custom Permission Protection | AndroidManifest.xml with android:protectionLevel="normal", "dangerous", or "signatureOrSystem" | Unauthorized apps request or claim permission without restriction | Upgrade to signature or signature with knownSigner and android:knownCerts. |
| Overly Broad URI Permission Grants | <grant-uri-permission android:pathPrefix="/" /> or pathPrefix="" in <provider> | Leaks all provider data to third parties | Replace with explicit scoped subpath (e.g. android:pathPrefix="/shared/"). Retain android:grantUriPermissions="true". Remove any wildcard pathPrefix="/". |
| Missing ContentProvider Split Permissions | <provider> with only generic android:permission or missing android:readPermission and android:writePermission | Read-only callers execute write operations or write-only callers access read operations | Configure granular android:readPermission="...READ_DATA" and android:writePermission="...WRITE_DATA", AND declare the custom <permission> tags with android:protectionLevel="signature" (or signature with knownSigner) at the <manifest> root. |
| Spoofable Caller Identity Checks | intent.getStringExtra("calling_package"), intent.getStringExtra("sender"), callingPackage == "..." in Services | Malicious callers forge intent extras or strings | Remove string checks; authenticate caller UID cryptographically using Binder.getCallingUid() and pm.hasSigningCertificate(). |
| Bound Service Permission Bypass | checkCallingOrSelfPermission() or enforceCallingOrSelfPermission() in Binder AIDL stubs | Falls back to host app UID outside IPC or when identity is cleared, causing Confused Deputy bypass | Replace with enforceCallingPermission("...WRITE_DATA", ...) or checkCallingPermission("...WRITE_DATA"). |
| Missing Method-Level Checks in Bound Services | Bound Service AIDL methods mutating state without enforcing write permissions | Callers with read-only binding access invoke mutating write operations | Add enforceCallingPermission("...WRITE_DATA", "Caller lacks WRITE_DATA permission") inside mutating AIDL methods. |
| Flawed Runtime Permission Flow | Missing shouldShowRequestPermissionRationale(), missing permanent denial handling, or re-requesting in loops | Poor user experience, infinite loops, or inability to recover permissions | Implement 3-state flow: check grant -> check rationale dialog -> launch contract. On permanent denial, redirect to Settings.ACTION_APPLICATION_DETAILS_SETTINGS. |
| Simultaneous Location Requests | arrayOf(ACCESS_FINE_LOCATION, ACCESS_BACKGROUND_LOCATION) in one request | Rejected by Android 11+ (API 30+) | Request foreground location (ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION) first. Request ACCESS_BACKGROUND_LOCATION only after foreground is granted in a separate user step. |
| Broad Storage Permissions for Media | Requesting READ_EXTERNAL_STORAGE or READ_MEDIA_IMAGES for user image selection | Over-privilege, user privacy violation | Migrate to zero-permission Photo Picker (ActivityResultContracts.PickVisualMedia). |
| Cached Permission State | Storing permission status in var cachedLocationPermissionGranted = ... | Fails when permission is revoked or expires | Query ContextCompat.checkSelfPermission() dynamically at invocation time and wrap protected calls in try-catch blocks catching SecurityException. |
| Insecure Broadcasts | sendBroadcast(intent) without package target or receiver permission; receiver without sender authentication | Data interception or command spoofing | Set explicit package (intent.setPackage(...)), pass receiver permission, and enable BroadcastOptions.setShareIdentityEnabled(true) (API 34+) to verify sentFromPackage. |
When declaring custom permissions or partner certificates in the manifest, you
must follow the instructions in the <permission> element guide.
signature: Restricts access to apps signed with the same developer key.signature|knownSigner (API 31+): Restricts access to partner apps whose signing certificate digests match declared hashes in android:knownCerts.normal or dangerous : Do not use for private inter-app IPC.signatureOrSystem : Deprecated (API 23). Upgrade deprecated signatureOrSystem permissions to signature. Avoid in non-system apps.Use signature permissions when restricting component access exclusively to
apps signed with the same developer certificate by declaring the <permission>
in the manifest and applying android:permission to the target component.
<permission
android:name="com.example.snippets.permission.ACCESS_SECURE_API"
android:protectionLevel="signature" />
Use signature|knownSigner permissions when granting access to specific
external partner apps by declaring the <permission> in the manifest with
android:knownCerts referencing a resource array of trusted SHA-256
certificate digests.
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- SHA-256 fingerprints of trusted partner certificates (lowercase, no colons) -->
<string-array name="trusted_partner_certs" tools:ignore="Typos">
<item>103938ee4537e59e8ee792f654504fb8346fc6b346d0bbc4415fc339fcfc8ec1</item>
</string-array>
</resources>
<permission
android:name="com.example.snippets.permission.PARTNER_API"
android:protectionLevel="signature|knownSigner"
android:knownCerts="@array/trusted_partner_certs" />
android:exported="false".android:permission, android:readPermission, android:writePermission).android:grantUriPermissions="true" for secure sharing, but scope grants to specific sub-paths. Never use wildcard pathPrefix="/".<permission> tags with android:protectionLevel="signature" (or signature|knownSigner) at the <manifest> root level.<grant-uri-permission android:pathPrefix="/" /> or pathPrefix="" and replace it with an explicit scoped subpath (e.g. android:pathPrefix="/shared/").UriPermission Management : Instead of broad manifest grants, use runtime android.content.UriPermission tokens for least-privilege per-URI sharing:
context.grantUriPermission(targetPackage, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) or attach Intent.FLAG_GRANT_READ_URI_PERMISSION to outgoing intents.contentResolver.takePersistableUriPermission(uri, modeFlags) for durable access across reboots, and contentResolver.releasePersistableUriPermission(uri, modeFlags) when durable access is no longer needed.contentResolver.persistedUriPermissions (List<UriPermission>) to verify granted URIs (uriPermission.uri, uriPermission.isReadPermission(), uriPermission.isWritePermission()).context.revokeUriPermission(targetPackage, uri, modeFlags) (API 26+), falling back to context.revokeUriPermission(uri, modeFlags) on API 25 and lower so access fails closed as soon as operations conclude.Declare the split read and write permissions at the <manifest> root:
<permission
android:name="com.example.snippets.permission.READ_DATA"
android:protectionLevel="signature" />
<permission
android:name="com.example.snippets.permission.WRITE_DATA"
android:protectionLevel="signature" />
Then configure the provider with those permissions and a scoped URI grant:
<provider
android:name=".permissions.SecureDataProvider"
android:authorities="com.example.snippets.partnerprovider"
android:exported="true"
android:readPermission="com.example.snippets.permission.READ_DATA"
android:writePermission="com.example.snippets.permission.WRITE_DATA"
android:grantUriPermissions="true">
<grant-uri-permission android:pathPrefix="/shared/" />
</provider>
object UriPermissionManager {
/** Grants temporary read access to a specific URI for a partner package. */
fun grantScopedUriAccess(context: Context, targetPackage: String, uri: Uri) {
context.grantUriPermission(
targetPackage,
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION
)
}
/** Audits active persisted URI permissions held by the application. */
fun getActivePersistedPermissions(context: Context): List<UriPermission> {
return context.contentResolver.persistedUriPermissions
}
/** Revokes temporary URI access for a specific partner package when data transfer completes. */
fun revokeScopedUriAccess(context: Context, targetPackage: String, uri: Uri) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.revokeUriPermission(
targetPackage,
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
)
} else {
context.revokeUriPermission(
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
)
}
}
}
Never trust caller package names provided in Intents or string arguments
(getCallingPackage(), intent.getStringExtra("calling_package"),
intent.getStringExtra("sender"), intent.getStringExtra("package")). Intent
extras and string package names are forged by malicious applications.
// VULNERABLE PATTERN: DO NOT DO THIS
val callingPackage = intent?.getStringExtra("calling_package")
if (callingPackage != null && SignatureUtils.verifyPartnerPackage(this, callingPackage)) {
// A malicious app passes "com.example.partner" in the extra.
// The signature check verifies the installed partner on disk, but the CALLER was malicious!
}
intent.getStringExtra("calling_package"), intent.getStringExtra("sender"), and callingPackage == "..." checks.Binder.getCallingUid() inside an active Binder IPC transaction (such as an AIDL Stub method or ContentProvider method).PackageManager.hasSigningCertificate() (API 28+) or PackageManager.getPackagesForUid().Apply this to the service that currently performs the spoofable check.
CallerVerifier in the same file as the service you are fixing (for example inside SecureDataService.kt). Do not move the verification into a new file and leave the original service untouched.Binder.getCallingUid() only returns the remote caller's UID during an active Binder transaction (never inside Service.onStartCommand() or Service.onBind(), where it returns Process.myUid()). Reject callingUid == Process.myUid() so calls outside an active IPC transaction or after Binder.clearCallingIdentity() fail closed instead of bypassing verification.packageInfo.signatures is Array<Signature>?. Copy the ?: return false guard exactly as written below. Iterating packageInfo.signatures directly fails to compile with "Non-nullable value required to call an 'iterator()' method in a for-loop."object CallerVerifier {
private const val TRUSTED_PARTNER_SHA256 =
"A1B2C3D4E5F60708090A0B0C0D0E0F1011121314151617181920212223242526"
fun isCallerAuthorized(context: Context): Boolean {
val callingUid = Binder.getCallingUid()
if (callingUid == android.os.Process.myUid()) return false
val pm = context.packageManager
// Modern API 28+ check by UID:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val certBytes = hexStringToByteArray(TRUSTED_PARTNER_SHA256)
return pm.hasSigningCertificate(callingUid, certBytes, PackageManager.CERT_INPUT_SHA256)
}
// Fallback for legacy APIs:
val callingPackages = pm.getPackagesForUid(callingUid) ?: return false
for (pkg in callingPackages) {
if (verifyPackageSignature(pm, pkg)) {
return true
}
}
return false
}
@Suppress("DEPRECATION")
private fun verifyPackageSignature(pm: PackageManager, packageName: String): Boolean {
return try {
val packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES)
val signatures = packageInfo.signatures ?: return false
for (sig in signatures) {
val digest = java.security.MessageDigest.getInstance("SHA-256").digest(sig.toByteArray())
val hex = digest.joinToString("") { "%02X".format(it) }
if (hex.equals(TRUSTED_PARTNER_SHA256, ignoreCase = true)) return true
}
false
} catch (e: PackageManager.NameNotFoundException) {
false
}
}
private fun hexStringToByteArray(s: String): ByteArray {
val len = s.length
val data = ByteArray(len / 2)
for (i in 0 until len step 2) {
data[i / 2] = ((Character.digit(s[i], 16) shl 4) + Character.digit(s[i + 1], 16)).toByte()
}
return data
}
}
In bound services exposing AIDL Binder stubs, protect state-modifying methods
using enforceCallingPermission().
checkCallingOrSelfPermission() or enforceCallingOrSelfPermission().enforceCallingPermission("com.example.snippets.permission.WRITE_DATA", "Caller lacks WRITE_DATA permission") or checkCallingPermission("com.example.snippets.permission.WRITE_DATA").class SecureBoundService : Service() {
private val binder = object : IMyService.Stub() {
override fun getData(): String {
// Read-only operation guarded by manifest-level permission
return "Confidential Data"
}
override fun modifyData(newData: String) {
// MUST use enforceCallingPermission or checkCallingPermission.
// NEVER use checkCallingOrSelfPermission or enforceCallingOrSelfPermission.
[email protected](
"com.example.snippets.permission.WRITE_DATA",
"Caller lacks WRITE_DATA permission"
)
updateInternalState(newData)
Log.d("SecureBoundService", "Data modified to: $newData with proper WRITE_DATA permission check")
}
}
override fun onBind(intent: Intent?): IBinder = binder
private fun updateInternalState(data: String) {
// Internal state update logic
}
}
When implementing runtime permission requests or handling permission denial states, you must follow the instructions in the Request runtime permissions guide and Permissions overview. Implement a 3-state flow without caching states or creating infinite retry loops:
ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED.shouldShowRequestPermissionRationale(permission) returns true, show a rationale dialog and launch the permission request only from its Continue button.ActivityResultContracts.RequestPermission().!shouldShowRequestPermissionRationale(permission), guide the user to Settings.ACTION_APPLICATION_DETAILS_SETTINGS.class RuntimePermissionsActivity : ComponentActivity() {
private val cameraLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
if (isGranted) {
startCameraPreview()
} else {
if (!shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
// User selected 'Don't ask again' or permanently denied.
// Direct user to Application Details Settings.
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
data = Uri.fromParts("package", packageName, null)
}
startActivity(intent)
} else {
showSnackbar("Camera permission is required to preview camera feed.")
}
}
}
fun requestCameraPermissionSafely() {
val permission = Manifest.permission.CAMERA
when {
ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED -> {
startCameraPreview()
}
shouldShowRequestPermissionRationale(permission) -> {
showRationaleDialog(permission)
}
else -> {
cameraLauncher.launch(permission)
}
}
}
private fun showRationaleDialog(permission: String) {
AlertDialog.Builder(this)
.setTitle("Camera permission required")
.setMessage("Camera permission is needed to preview the camera feed.")
.setPositiveButton("Continue") { _, _ ->
cameraLauncher.launch(permission)
}
.setNegativeButton("Cancel", null)
.show()
}
private fun startCameraPreview() {
Log.d("RuntimePermissionsActivity", "Camera preview started")
}
private fun showSnackbar(msg: String) {
Log.i("RuntimePermissionsActivity", msg)
}
}
When implementing photo or media selection, you must follow the instructions in the Photo Picker API guide to avoid requesting broad storage permissions.
ActivityResultContracts.PickVisualMedia() over requesting wide storage permissions (READ_MEDIA_IMAGES, READ_EXTERNAL_STORAGE).ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION first. Never request ACCESS_BACKGROUND_LOCATION simultaneously. Only request background location in a separate step after foreground is granted.private val photoPickerLauncher =
registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
if (uri != null) {
handleImageUri(uri)
}
}
fun selectPhoto() {
photoPickerLauncher.launch(
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
)
}
private val foregroundLocationLauncher =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
val fineGranted = permissions[Manifest.permission.ACCESS_FINE_LOCATION] ?: false
val coarseGranted = permissions[Manifest.permission.ACCESS_COARSE_LOCATION] ?: false
if (fineGranted || coarseGranted) {
startForegroundLocationUpdates()
}
}
fun requestForegroundLocation() {
foregroundLocationLauncher.launch(
arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)
)
}
// Background location requested only AFTER foreground is granted and user explicitly opts in:
private val backgroundLocationLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
if (isGranted) {
startBackgroundTracking()
}
}
cachedLocationPermissionGranted). Check ContextCompat.checkSelfPermission() dynamically before each operation.SecurityException around permission-protected framework calls (e.g., location queries) to handle one-time permission revocation gracefully.fun performLocationAccess() {
val fine = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
val coarse = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
if (fine != PackageManager.PERMISSION_GRANTED && coarse != PackageManager.PERMISSION_GRANTED) {
requestForegroundLocation()
return
}
val provider = if (fine == PackageManager.PERMISSION_GRANTED) {
LocationManager.GPS_PROVIDER
} else {
LocationManager.NETWORK_PROVIDER
}
try {
val location = locationManager.getLastKnownLocation(provider)
processLocation(location)
} catch (e: SecurityException) {
Log.e("LocationAccess", "Permission revoked at runtime", e)
}
}
Use explicit intents, required receiver permissions, or Android 14+ broadcast options:
// Sender: Enforce permission and share identity
val intent = Intent("com.example.snippets.permission.ACTION_SECRET_UPDATE").apply {
setPackage("com.example.partner") // Explicit target
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
val options = BroadcastOptions.makeBasic().apply {
setShareIdentityEnabled(true)
}.toBundle()
sendBroadcast(intent, "com.example.snippets.permission.RECEIVE_SECRET_UPDATE", options)
} else {
sendBroadcast(intent, "com.example.snippets.permission.RECEIVE_SECRET_UPDATE")
}
// Receiver: Validate sender on Android 14+ (on API 33 and lower, restrict access
// by declaring android:permission with a signature or knownSigner permission on <receiver>)
class ProtectedReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == "com.example.snippets.permission.ACTION_SECRET_UPDATE") {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
val sender = sentFromPackage
if (sender != "com.example.trusted_sender") {
return // Reject unauthorized sender
}
}
processUpdate(intent)
}
}
private fun processUpdate(intent: Intent) {}
}
Legacy compatibility (Pre-API 34) : On API 33 and lower, never authenticate
a broadcast sender using PendingIntent.getCreatorPackage() or
PendingIntent.getCreatorUid(), because any app that acquires a trusted app's
PendingIntent can attach and send it (see Sender of Pending Intents).
Instead, restrict the <receiver> with a signature or signature|knownSigner
(API 31+) permission in the manifest; if minSdkVersion is lower than 31, use a
bound Service or ContentProvider and verify Binder.getCallingUid().
<permission android:name="..." android:protectionLevel="signature" /> (or signature|knownSigner) at the <manifest> root for custom permissions and ContentProvider split permissions.android:exported="false" for all private components to remove the need for custom permission management.Binder.getCallingUid() and certificate hashes (PackageManager.hasSigningCertificate or getPackagesForUid) rather than checking spoofable intent extras.shouldShowRequestPermissionRationale() before runtime prompts and during denial handling.Settings.ACTION_APPLICATION_DETAILS_SETTINGS when permission is permanently denied.enforceCallingPermission() or checkCallingPermission() on modifying AIDL methods.android:pathPrefix="/shared/") while retaining android:grantUriPermissions="true".SecurityException around protected API calls.intent.getStringExtra("calling_package"), intent.getStringExtra("sender"), intent.getStringExtra("package")). Always authenticate using Binder.getCallingUid() and certificates.PendingIntent.getCreatorPackage() or PendingIntent.getCreatorUid().checkCallingOrSelfPermission() or enforceCallingOrSelfPermission() to guard external caller methods. Always use enforceCallingPermission() or checkCallingPermission().signatureOrSystem.<grant-uri-permission android:pathPrefix="/" /> or pathPrefix="". Always replace with a scoped sub-path.references/android/guide/topics/manifest/permission-element.md (opens in a new tab)references/android/guide/topics/permissions/overview.md (opens in a new tab)references/android/privacy-and-security/risks/sender-of-pending-intents.md (opens in a new tab)references/android/training/permissions/requesting.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub premex-ab/claude-marketplace --plugin android-android-permissions-security2 plugins ship this exact skill · first indexed Nov 10, 2026
Other plugins' skills for the same job