Skip to content

Instantly share code, notes, and snippets.

@scottyab
Created May 14, 2014 15:36
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save scottyab/6f51bbd82a0ffb08ac7a to your computer and use it in GitHub Desktop.
Save scottyab/6f51bbd82a0ffb08ac7a to your computer and use it in GitHub Desktop.
Make Webview safer - some of the code based on recommendations in article https://labs.mwrinfosecurity.com/blog/2012/04/23/adventures-with-android-webviews/
/**
* Implements whitelisting on host name
*/
public class SaferWebViewClient extends WebViewClient {
private String[] hostsWhitelist;
public SaferWebViewClient(String hostsWhitelsit){
super();
this.hostsWhitelist = hostsWhitelist;
}
@Override
public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
if (isValidHost(url)) {
return super.shouldInterceptRequest(view, url);
} else {
return getWebResourceResponseFromString();
}
}
private WebResourceResponse getWebResourceResponseFromString() {
return getUtf8EncodedWebResourceResponse(new StringBufferInputStream("alert('!NO!')"));
}
private WebResourceResponse getUtf8EncodedWebResourceResponse(InputStream data) {
return new WebResourceResponse("text/css", "UTF-8", data);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return isValidHost(url);
}
private boolean isValidHost(String url){
if (!TextUtils.isEmpty(url)) {
final String host = Uri.parse(url).getHost();
for (String whitelistedHost: hostsWhitelist){
if (whitelistedHost.equalsIgnoreCase(host)){
return true;
}
}
}
return false;
}
}
public class Util {
public static void disableRiskySettings(WebView webView){
//javascript could be a vector to exploit your applications
webView.getSettings().setJavaScriptEnabled(false);
//default is off, but just in case. plugins could be a vector to exploit your applications process
webView.getSettings().setPluginState(WebSettings.PluginState.OFF);
//Should an attacker somehow find themselves in a position to inject script into a WebView, then they could exploit the opportunity to access local resources. This can be somewhat prevented by disabling local file system access. It is enabled by default. The Android WebSettings class can be used to disable local file system access via the public method setAllowFileAccess.
//This restricts the WebView to loading local resources from file:///android_asset (assets) and file:///android_res (resources).
webView.getSettings().setAllowFileAccess(false);
//disable Geolocation API
webView.getSettings().setGeolocationEnabled(false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment