Android Webview JavaScript Interface Annotation

ID

kotlin.android_webview_javascript_interface_annotation

Severity

critical

Resource

Access Control

Language

Kotlin

Tags

CWE:79, NIST.SP.800-53, PCI-DSS:6.5.7, android

Description

Potential WebView code injection with addJavaScriptInterface.

Rationale

Android apps frequently use the WebView class to present online content. Developers can inject Java objects into a WebView using the addJavascriptInterface() method, enabling JavaScript code in the web page to invoke public methods on these Kotlin objects — a mechanism known as the "JavaScript bridge."

Exposing Kotlin objects in this manner can introduce security vulnerabilities, such as code injection. This could, for instance, allow malicious code to access sensitive device functions:

Example of potential code injection:

import android.app.Activity
import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebSettings

class MainActivity : Activity() {
    private lateinit var appView: WebView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        appView = WebView(this)
        configureWebView(appView)
        setContentView(appView)
        bindBrowser(appView)
    }

    private fun configureWebView(appView: WebView) {
        val webSettings: WebSettings = appView.settings
        webSettings.javaScriptEnabled = true
    }

    private fun bindBrowser(appView: WebView) {
        appView.addJavascriptInterface(JS(), "JS") // FLAW
    }
}

For applications targeting API level 17 or higher (JellyBean MR1 and above), only public methods with the @JavascriptInterface annotation can be accessed by JavaScript. In contrast, if the app targets API levels below 17, calling any public method without restriction is possible, increasing the risk of exploitation.

The detector looks for any addJavascriptInterface() call when the app’s minimum SDK level is below 17.

Remediation

To mitigate these security risks, consider these actions:

  1. Avoid addJavascriptInterface(): If feasible, remove the call to addJavascriptInterface() to eliminate the JavaScript bridge.

  2. Target SDK Level 17 or Above: Ensure the application targets a minimum SDK level of 17 or higher to restrict access to methods without the @JavascriptInterface annotation.

  3. Annotate Public Methods: For applications targeting API level 17 or above, annotate necessary public methods with @JavascriptInterface to explicitly allow access.

  4. Trust Only Trusted Content: If you’re supporting API levels below 17, ensure that only trusted content is loaded into the WebView to prevent scripting exploitation.

References

  • CWE-79 : Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting').

  • EnablingJavaScript : Use JavaScript in WebView.