Sensei Logo Sensei Hub

Recipe - WebView Best Practices: Disable File Access (setter)

Description:
Enabling file access in the webview could lead to misuse
Level:
error
Language:
  • java
Tags:
  • security
  • framework specific
  • Android
  • mobile
  • Android security set
Documentation

The Android best practices and secure coding guidelines make recommendations for WebView and its configuration.

Regardless where the URL originates from, it is 'best practice' to verify that the URL does not target local resources. This can easily be achieved by checking the start of the string for file:. It is considered best practice to also check the URL to be loaded against a white list. The settings below should also be considered to improve the overall security of the application:

Before
WebView wv = new WebView(context);
wv.loadUrl(url);
After
WebView wv = new WebView(context);
WebSettings = ws = wv.getSettings();
ws.setJavaScriptEnabled(false);
ws.setAllowFileAccess(false);
ws.setGeolocationEnabled(false);
ws.setAllowContentAccess(false);
int never = WebSettings.MIXED_CONTENT_NEVER_ALLOW
ws.setMixedContentMode(never);

if( !url.startsWith("file:"))
    wv.loadUrl(url);

Additionally avoid using the following settings (Deprecated since API level 30) to prevent malicious scripts from accessing arbitrary local files or launching XSS attacks.

ws.setAllowFileAccessFromFileURLs(true);
ws.setAllowUniversalAccessFromFileURLs(true);
Recipe
id: scw:android:webview-disable-file-access-setter
version: 10
metadata:
  name: 'WebView Best Practices: Disable File Access (setter)'
  shortDescription: Enabling file access in the webview could lead to misuse
  level: error
  language: java
  enabled: true
  comment: ""
  descriptionFile: descriptions/AndroidWebViewbestpractices.html
  tags: security;framework specific;Android;mobile;Android security set
search:
  methodcall:
    args:
      1:
        value:
          stringified: "true"
    anyOf:
    - name: setAllowFileAccess
    - name: setAllowFileAccessFromFileURLs
    - name: setAllowUniversalAccessFromFileURLs
    type: android.webkit.WebSettings
availableFixes:
- name: Disable file access
  actions:
  - modifyArguments:
      rewrite:
        1: "false"