您的当前位置:首页正文

Android WebView控件跨域访问高危漏洞问题解析

来源:华拓网

问题描述

问题复现

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(true);
    settings.setAllowUniversalAccessFromFileURLs(true);
}

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());
        }
    }