問題描述
詳見:關于Android平臺WebView控件存在跨域訪問高危漏洞的安全公告。簡單來說就是js腳本可以訪問到系統的私有文件,導致用戶信息的泄漏。
問題復現
WebView加載下列Html數據可以查看到系統的host文件的內容:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="viewport"
content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-touch-fullscreen" content="yes">
<script>
function loadXMLDoc()
{
var arm = "file:///etc/hosts";
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
<!--//alert("status is"+xmlhttp.status);-->
<!--if (xmlhttp.readyState==4)-->
<!--{-->
console.log(xmlhttp.responseText);
<!--}-->
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
xmlhttp.open("GET",arm);
xmlhttp.send(null);
}
loadXMLDoc();
</script>
<title>用戶協議</title>
</head>
<body>
<div class="wrapper">
<h1>用戶協議</h1>
<p id="content">content</p>
</div>
</body>
</html>
問題修復
api版本>=16,可采用如下設置:
WebSettings settings = vWeb.getSettings();
if (Build.VERSION.SDK_INT > 15) {
settings.setAllowFileAccessFromFileURLs(false);
settings.setAllowUniversalAccessFromFileURLs(false);
}
api版本<16,可以設置文件白名單,如下:
private class MyWebViewClient extends WebViewClient {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
return isSafeSource(url) ? null : new WebResourceResponse(null, null, null);
}
private boolean isSafeSource(String url) {
//以下為白名單
return url.startsWith("file:///android_asset")
|| url.startsWith("file:///data/data/" + getContext().getPackageName())
|| url.startsWith("file://" + getContext().getFilesDir());
}
}