Deep links and intent security
Why it matters
- An exported Activity that handles a deep link is a public API. Any app on the device, or any web page, can send it data. Trusting that data leads to bugs such as opening internal screens, leaking files or intent redirection.
- A mutable
PendingIntentwrapping an implicitIntentlets whoever receives it fill in the target. Google Play has published remediation guidance for both intent redirection and implicitPendingIntentvulnerabilities. - Verified Android App Links (
assetlinks.jsonplusandroid:autoVerify="true") make yourhttpslinks open your app and no one else's. Interviewers often ask how they differ from plain deep links and what changed in Android 12. - Obfuscation (R8) renames classes but does not stop anyone from sending a crafted
Intent. Validation in code is the control.
The simple explanation
- A deep link is a doorbell on your front door: anyone on the street can ring it.
- A verified App Link is a doorbell registered to your address: the city confirmed you own the house, so the delivery comes only to you.
- Data in the link or in intent extras is a note slipped under the door. Read only the lines you expect and check each one.
- A mutable
PendingIntentis a signed, pre-paid envelope with a blank address line.FLAG_IMMUTABLEand an explicit target fill in the address before you hand it over.
What is the difference between a deep link and an Android App Link? A deep link is any intent filter that opens your Activity from a URI, such as myapp://item/42 or https://example.com/item/42. Other apps can declare the same filter, so the user may get a chooser or the wrong app. An App Link is an https deep link whose domain you have verified: the filter has android:autoVerify="true" and your site serves https://example.com/.well-known/assetlinks.json listing your package name and signing certificate SHA-256 fingerprint. Android checks the file and then opens matching links directly in your app. Custom schemes cannot be verified.
Android 12 (API 31) changes. A generic web link (http/https, VIEW, BROWSABLE) opens your app only if your app is approved for that domain, through verification or because the user enabled it in settings; otherwise it opens in the browser. Verification is also tracked per domain, so one failing host no longer blocks the others.
Every incoming Intent is a message from an untrusted caller:
| Surface | Risk | Mitigation |
|---|---|---|
| Exported components | Any app can start your Activity, Service or Receiver | android:exported="false" unless it must be public; protect public ones with a signature permission when only your apps call them |
| Link data and extras | Caller controls every value | Parse only the values you need from the URI; validate type, length and format |
Nested Intent extras | Intent redirection: your app launches what the attacker chose | Never launch an Intent taken from extras; build a new explicit one |
PendingIntent | Receiver fills in an implicit target or adds URI grants | FLAG_IMMUTABLE plus an explicit component; FLAG_MUTABLE only when required |
Intent redirection happens when an exported component reads an Intent (or a URI it turns into one) from the incoming data and passes it to startActivity. Because the launch comes from your app, it can reach your non-exported components and your FileProvider grants. The fix is to never forward a caller-supplied intent.
PendingIntent rules. Apps targeting API 31+ must pass FLAG_IMMUTABLE or FLAG_MUTABLE, or creation throws IllegalArgumentException. Apps targeting API 34+ cannot create a mutable PendingIntent around an implicit Intent without an explicit opt-out flag.
Notes
- Set
android:exported="false"on every component that other apps do not need. Apps targeting Android 12+ must declareandroid:exportedexplicitly on components with intent filters, or the app cannot be installed. - An intent filter makes a component reachable from outside. Do not add one to an internal screen just to navigate to it; use an explicit
Intentinstead. - For App Links, put
android:autoVerify="true"on an intent filter withVIEW,DEFAULT,BROWSABLEandhttpsdata, and serveassetlinks.jsonover HTTPS without redirects, withContent-Type: application/json. - The fingerprint in
assetlinks.jsonmust match the key that signs the installed app. With Play App Signing that is the app signing key from Play Console, not your upload key. - Check App Link state on Android 12+ with
adb shell pm get-app-links com.example.appand re-run verification withadb shell pm verify-app-links --re-verify com.example.app. - Read only the parameters you expect, from
intent.data(path segments, query parameters). Validate each one: an ID should match a strict pattern and length, never be passed into SQL or file paths unchecked. - Never call
startActivitywith anIntentfromgetParcelableExtra. If a link must say "go here next", accept a short route name and map it to an explicit destination you control. getCallingPackage()returns null unless the Activity was started for a result, so it is not a reliable way to authorise callers. Use a signature-level permission for components only your own apps should call.- Use
FLAG_IMMUTABLEfor everyPendingIntentunless the receiver must fill in data, such as inline reply in notifications. A mutable one should wrap an explicitIntent(setPackageor a component). - In debug builds,
StrictMode.VmPolicy.Builder().detectUnsafeIntentLaunch()(API 31+) flags launches of intents that came from another app, which helps find redirection bugs.
Code example
The manifest declares a verified App Link for one path; the matching assetlinks.json sits on the website.
<activity
android:name=".DeepLinkActivity"
android:exported="true">
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" />
<data android:host="app.example.com" />
<data android:pathPrefix="/profile/" />
</intent-filter>
</activity>[
{
"relation": ["delegate_permission/common.handle_all_urls"],
"target": {
"namespace": "android_app",
"package_name": "com.example.secure",
"sha256_cert_fingerprints": ["AB:CD:...:EF"]
}
}
]This Activity validates the link, reads only the user ID from the path, and starts an explicit internal screen. A helper builds an immutable PendingIntent for a notification that opens the same screen.
package com.example.secure
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class DeepLinkActivity : AppCompatActivity() {
private val allowedHosts = setOf("app.example.com")
private val userIdPattern = Regex("[A-Za-z0-9_-]{1,64}")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
handle(intent)
finish() // trampoline: route, then get out of the back stack
}
private fun handle(intent: Intent) {
val uri: Uri = intent.data ?: return
if (uri.scheme != "https" || uri.host !in allowedHosts) return
// Expect exactly /profile/{userId}; ignore all extras.
val segments = uri.pathSegments
if (segments.size != 2 || segments[0] != "profile") return
val userId = segments[1]
if (!userIdPattern.matches(userId)) return
// New explicit Intent with only the validated value.
startActivity(ProfileActivity.intent(this, userId))
}
}
class ProfileActivity : AppCompatActivity() {
companion object {
private const val EXTRA_USER_ID = "user_id"
fun intent(context: Context, userId: String): Intent =
Intent(context, ProfileActivity::class.java).putExtra(EXTRA_USER_ID, userId)
fun pendingIntent(context: Context, userId: String): PendingIntent =
PendingIntent.getActivity(
context,
userId.hashCode(), // distinct request code per user
intent(context, userId),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
}
}- The scheme, host and path shape are checked first, then the one value the screen needs is validated with a strict pattern.
- Extras are ignored entirely. Browsers and other apps can add their own extras to a
VIEWintent, so the link data inintent.datais the contract. ProfileActivityis not exported (no intent filter,exported="false"), and it is reached only through a new explicitIntent. Nothing from the caller is forwarded.FLAG_IMMUTABLEstops a notification receiver from changing the intent;FLAG_UPDATE_CURRENTupdates the extras if the same request code is reused.- If the Activity used
launchMode="singleTop", it would also need to handleonNewIntent. As a trampoline that finishes immediately, it does not.
Run the idea in plain Kotlin
data class IncomingLink(
val scheme: String,
val host: String?,
val path: String,
val extras: Map<String, String> = emptyMap()
)
val allowedHosts = setOf("app.example.com")
val userIdPattern = Regex("[A-Za-z0-9_-]{1,64}")
fun route(link: IncomingLink): String {
if (link.scheme != "https") return "REJECTED: scheme " + link.scheme
if (link.host !in allowedHosts) return "REJECTED: host " + link.host
val segments = link.path.trim('/').split('/')
if (segments.size != 2 || segments[0] != "profile") return "REJECTED: unknown path " + link.path
val userId = segments[1]
if (!userIdPattern.matches(userId)) return "REJECTED: invalid user id"
// Extras are never read, so a smuggled "next_intent" has no effect
return "OPEN ProfileActivity(userId=" + userId + ")"
}
fun main() {
val links = listOf(
IncomingLink("https", "app.example.com", "/profile/user_42"),
IncomingLink("http", "app.example.com", "/profile/user_42"),
IncomingLink("https", "evil.example.net", "/profile/user_42"),
IncomingLink("https", "app.example.com", "/admin/settings"),
IncomingLink("https", "app.example.com", "/profile/" + "a".repeat(65)),
IncomingLink("https", "app.example.com", "/profile/abc", mapOf("next_intent" to "intent:#Intent;component=com.example.secure/.AdminActivity;end"))
)
for (link in links) println(route(link))
}Expected output:
OPEN ProfileActivity(userId=user_42)
REJECTED: scheme http
REJECTED: host evil.example.net
REJECTED: unknown path /admin/settings
REJECTED: invalid user id
OPEN ProfileActivity(userId=abc)
In production
- A "router" Activity was exported so marketing links could open it. If the incoming intent had an extra named
next, it calledstartActivityon that nestedIntent. - A security researcher showed that another app could put an
Intenttargeting a non-exported settings screen insidenext. Because the launch came from the app itself, the internal screen opened. - The same path could target the app's
FileProviderwith read grants, exposing private files.
- Removed the nested-intent extra. The router now accepts a route name from the link path and maps it to a fixed set of explicit destinations.
- Marked every internal Activity
exported="false"and removed intent filters that were only used for in-app navigation. - Enabled
detectUnsafeIntentLaunch()in debug builds and added a test that sends the router an intent with a nestedIntentextra and asserts nothing is launched.
- A notification action used a
PendingIntentcreated withFLAG_MUTABLEaround an implicitIntent(an action string, no package or component). - The app passed that
PendingIntentto a third-party SDK. Any code holding it could fill in the missing component, or add acontent://URI with a read-grant flag, and send it with the app's identity. - An internal security review found it; the action did not need mutability at all.
- Switched to
FLAG_IMMUTABLEand made the baseIntentexplicit with the app's own component. - For the one notification that needed inline reply (which requires a mutable
PendingIntent), keptFLAG_MUTABLEbut set an explicit component so nothing can redirect it. - Raised the target SDK to 34, where creating a mutable
PendingIntentaround an implicitIntentthrows, so the mistake cannot come back unnoticed.
Common mistakes
exported="true"on internal screens. Any app can start them. Export only entry points, and protect them with a signature permission when only your apps should call them.- Launching an
Intenttaken from extras. This is intent redirection: the attacker chooses the target and your app's identity opens it. Build a new explicitIntentfrom validated values. - Missing
FLAG_IMMUTABLE. Targeting API 31+ without a mutability flag throwsIllegalArgumentException. UseFLAG_IMMUTABLEunless the receiver must fill in data. - Mutable
PendingIntentaround an implicitIntent. Whoever receives it can choose the component. Make the base intent explicit. - Skipping scheme and host checks. A deep link handler that only reads the path accepts
http, other hosts and custom schemes. Check scheme, host and path shape before reading values. - Wrong fingerprint in
assetlinks.json. Using the upload key instead of the Play app signing key means verification fails and links open in the browser on Android 12+.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between a deep link and a verified App Link?”
“How do you prevent intent redirection?”
“What changed for PendingIntent in recent Android versions?”
“How do you validate an intent received by an exported Activity?”
Quiz
What does android:autoVerify="true" on an https intent filter require?
An app targeting API 31+ creates a PendingIntent without FLAG_IMMUTABLE or FLAG_MUTABLE. What happens?
Which approach prevents intent redirection in an exported Activity?
A verified App Link arrives with extra keys your handler does not use. What should the handler do?
0 of 4 answered
Mini task
Harden a deep-link Activity (20 min)
-
Declare the link. Add
DeepLinkActivitywithandroid:exported="true"and anautoVerifyintent filter forhttps://yourdomain.com/item/. Make every other Activityexported="false". -
Publish
assetlinks.json. Get the SHA-256 fingerprint of your signing key (Play Console's app signing page for Play builds, or./gradlew signingReportfor local builds) and serve the file athttps://yourdomain.com/.well-known/assetlinks.json. -
Write a pure parser. Create
fun parseItemLink(uri: Uri): String?that returns the item ID only forhttps, your host, and a path of exactly/item/{id}where the ID matches[A-Za-z0-9_-]{1,64}. Unit test it with good and bad inputs. -
Route explicitly. In
DeepLinkActivity, call the parser, startDetailActivitywith a new explicitIntentcarrying only the ID, thenfinish(). -
Test. Run
adb shell am start -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "https://yourdomain.com/item/42"and confirm the detail screen opens. Then runadb shell am start -n com.example.app/.DetailActivityand confirm it fails because the Activity is not exported. -
Check verification. On an Android 12+ device, run
adb shell pm get-app-links com.example.appand confirm your domain showsverified.
Done condition: valid links open the detail screen, malformed links do nothing, internal screens cannot be started from adb, and the domain shows as verified.