[
  {
    "path": ".gitignore",
    "content": "*.iml\n.gradle\n/local.properties\n/.idea\n.DS_Store\n/build\n/captures\n.externalNativeBuild\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2017 Rafael Toledo\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License."
  },
  {
    "path": "README.md",
    "content": "# Android Security Sandbox\n\nA sandbox app with some tools and code to help you to better secure your Android apps.\n\n[Related presentation - pt-BR](https://speakerdeck.com/rafaeltoledo/seguranca-no-android-1)\n\n## This sample includes\n1. Obfuscation using Proguard and `android-proguard-optimize` rules\n2. Encrypted database storage using [SQLCipher](https://www.zetetic.net/sqlcipher/sqlcipher-for-android)\n3. Encrypted key-value storage using [Hawk](https://github.com/orhanobut/hawk), powered by [Conceal](https://facebook.github.io/conceal/)\n4. Device checking using [SafetyNet](https://developers.google.com/android/reference/com/google/android/gms/safetynet/SafetyNet)\n5. Root detection using [RootBeer](https://github.com/scottyab/rootbeer)\n6. HTTP pinning using [OkHttp](https://github.com/square/okhttp/wiki/HTTPS)\n7. Other environment checks, like *Debug*, *Emulator*, *Installation Source*, and *Tampering*\n"
  },
  {
    "path": "app/.gitignore",
    "content": "/build\n"
  },
  {
    "path": "app/build.gradle",
    "content": "apply plugin: 'com.android.application'\n\nandroid {\n    compileSdkVersion 25\n    buildToolsVersion '25.0.3'\n\n    defaultConfig {\n        applicationId 'net.rafaeltoledo.security'\n        minSdkVersion 16\n        targetSdkVersion 25\n        versionCode 1\n        versionName '1.0.0'\n\n        testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'\n\n        manifestPlaceholders = [\n                SAFETYNET_API_KEY: System.getenv('SAFETYNET_API_KEY')\n        ]\n    }\n\n    dataBinding.enabled true\n\n    compileOptions {\n        sourceCompatibility JavaVersion.VERSION_1_8\n        targetCompatibility JavaVersion.VERSION_1_8\n    }\n\n    signingConfigs {\n        release {\n            storeFile file(System.getenv('PROJECT_STORE_FILE'))\n            storePassword System.getenv('PROJECT_STORE_PASSWORD')\n            keyAlias System.getenv('PROJECT_KEY_ALIAS')\n            keyPassword System.getenv('PROJECT_KEY_PASSWORD')\n        }\n    }\n\n    buildTypes {\n        release {\n            minifyEnabled true\n            shrinkResources true\n            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'\n\n            signingConfig signingConfigs.release\n        }\n    }\n}\n\ndependencies {\n    compile 'com.android.support:appcompat-v7:25.3.1'\n\n    compile 'com.scottyab:rootbeer-lib:0.0.6'\n    compile 'com.orhanobut:hawk:2.0.1'\n    compile 'com.google.code.gson:gson:2.8.0' // Forcing latest GSON\n    compile 'net.zetetic:android-database-sqlcipher:3.5.7@aar'\n    compile 'com.squareup.okhttp3:okhttp:3.7.0'\n\n    compile 'com.google.android.gms:play-services-safetynet:10.2.4'\n}\n"
  },
  {
    "path": "app/proguard-rules.pro",
    "content": "-dontwarn java.nio.file.*\n-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement\n-dontwarn okio.**\n-dontwarn okhttp3.**\n\n-keepattributes Signature\n-keepattributes EnclosingMethod\n-keepattributes *Annotation*\n\n-keep class sun.misc.Unsafe { *; }\n-keep class okhttp3.** { *; }\n-keep interface okhttp3.** { *; }\n-keep class com.google.gson.stream.** { *; }\n-keep class net.sqlcipher.** { *; }\n-keep class net.sqlcipher.database.** { *; }\n\n-assumenosideeffects class android.util.Log {\n    public static boolean isLoggable(java.lang.String, int);\n    public static int v(...);\n    public static int i(...);\n    public static int w(...);\n    public static int d(...);\n    public static int e(...);\n}\n"
  },
  {
    "path": "app/src/main/AndroidManifest.xml",
    "content": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    package=\"net.rafaeltoledo.security\">\n\n    <uses-permission android:name=\"android.permission.INTERNET\" />\n\n    <application\n        android:name=\".SecurityApp\"\n        android:allowBackup=\"false\"\n        android:icon=\"@mipmap/ic_launcher\"\n        android:label=\"@string/app_name\"\n        android:roundIcon=\"@mipmap/ic_launcher_round\"\n        android:supportsRtl=\"true\"\n        android:theme=\"@style/AppTheme\"\n        tools:ignore=\"GoogleAppIndexingWarning\">\n\n        <activity android:name=\".ui.MainActivity\">\n            <intent-filter>\n                <action android:name=\"android.intent.action.MAIN\" />\n\n                <category android:name=\"android.intent.category.LAUNCHER\" />\n            </intent-filter>\n        </activity>\n\n        <meta-data\n            android:name=\"com.google.android.safetynet.ATTEST_API_KEY\"\n            android:value=\"${SAFETYNET_API_KEY}\" />\n\n    </application>\n</manifest>\n"
  },
  {
    "path": "app/src/main/java/net/rafaeltoledo/security/SecurityApp.java",
    "content": "package net.rafaeltoledo.security;\n\nimport android.app.Application;\nimport android.util.Log;\n\nimport com.orhanobut.hawk.Hawk;\n\nimport net.sqlcipher.database.SQLiteDatabase;\n\npublic class SecurityApp extends Application {\n\n    private static final String TAG = SecurityApp.class.getSimpleName();\n    private static final String PREF_TIMES = \"net.rafaeltoledo.security.PREF_TIMES\";\n\n    @Override\n    public void onCreate() {\n        super.onCreate();\n        Hawk.init(this).build();\n        SQLiteDatabase.loadLibs(this);\n\n        int times = Hawk.get(PREF_TIMES, 0) + 1;\n        Log.d(TAG, \"Psss! Let me tell a secret: you opened this app \" + times + \" times.\");\n        Hawk.put(PREF_TIMES, times);\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/net/rafaeltoledo/security/http/HttpClientProvider.java",
    "content": "package net.rafaeltoledo.security.http;\n\nimport android.util.Log;\n\nimport java.security.GeneralSecurityException;\nimport java.security.KeyStore;\nimport java.util.Collections;\n\nimport javax.net.ssl.TrustManager;\nimport javax.net.ssl.TrustManagerFactory;\nimport javax.net.ssl.X509TrustManager;\n\nimport okhttp3.CertificatePinner;\nimport okhttp3.ConnectionSpec;\nimport okhttp3.OkHttpClient;\nimport okhttp3.TlsVersion;\n\npublic class HttpClientProvider {\n\n    private static final String TAG = HttpClientProvider.class.getSimpleName();\n\n    private static final OkHttpClient CLIENT = init();\n\n    private static OkHttpClient init() {\n        ConnectionSpec.Builder spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)\n                .tlsVersions(TlsVersion.TLS_1_2);\n        OkHttpClient.Builder client = new OkHttpClient.Builder()\n                .connectionSpecs(Collections.singletonList(spec.build()));\n        // This setup is necessary because API 16-18 support TLS 1.2,\n        // but use 1.0 as default.\n        setupTls(client);\n        setupPinning(client);\n\n        return client.build();\n    }\n\n    private static void setupPinning(OkHttpClient.Builder client) {\n        client.certificatePinner(new CertificatePinner.Builder()\n                .add(\"github.com\", \"sha256/pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=\")\n                .add(\"github.com\", \"sha256/RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=\")\n                .add(\"github.com\", \"sha256/WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\")\n                .build());\n    }\n\n    private static void setupTls(OkHttpClient.Builder builder) {\n        try {\n            TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());\n            factory.init((KeyStore) null);\n            for (TrustManager trustManager : factory.getTrustManagers()) {\n                if (trustManager instanceof X509TrustManager) {\n                    builder.sslSocketFactory(new Tls12SslSocketFactory(), (X509TrustManager) trustManager);\n                    break;\n                }\n            }\n        } catch (GeneralSecurityException e) {\n            Log.e(TAG, \"Failed to initialize SSL Socket Factory\", e);\n        }\n    }\n\n    public static OkHttpClient getClient() {\n        return CLIENT;\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/net/rafaeltoledo/security/http/Tls12SslSocketFactory.java",
    "content": "package net.rafaeltoledo.security.http;\n\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.Socket;\n\nimport javax.net.ssl.SSLSocket;\nimport javax.net.ssl.SSLSocketFactory;\n\npublic class Tls12SslSocketFactory extends SSLSocketFactory {\n    private final String tag = \"TLSv1.2\";\n\n    private SSLSocketFactory delegate;\n\n    public Tls12SslSocketFactory() {\n        delegate = (SSLSocketFactory) SSLSocketFactory.getDefault();\n    }\n\n    @Override\n    public String[] getDefaultCipherSuites() {\n        return delegate.getDefaultCipherSuites();\n    }\n\n    @Override\n    public String[] getSupportedCipherSuites() {\n        return delegate.getSupportedCipherSuites();\n    }\n\n    @Override\n    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {\n        SSLSocket s = (SSLSocket) delegate.createSocket(socket, host, port, autoClose);\n        s.setEnabledProtocols(new String[]{tag});\n        return s;\n    }\n\n    @Override\n    public Socket createSocket(String host, int port) throws IOException {\n        SSLSocket s = (SSLSocket) delegate.createSocket(host, port);\n        s.setEnabledProtocols(new String[]{tag});\n        return s;\n    }\n\n    @Override\n    public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {\n        SSLSocket s = (SSLSocket) delegate.createSocket(host, port, localHost, localPort);\n        s.setEnabledProtocols(new String[]{tag});\n        return s;\n    }\n\n    @Override\n    public Socket createSocket(InetAddress host, int port) throws IOException {\n        SSLSocket s = (SSLSocket) delegate.createSocket(host, port);\n        s.setEnabledProtocols(new String[]{tag});\n        return s;\n    }\n\n    @Override\n    public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {\n        SSLSocket s = (SSLSocket) delegate.createSocket(address, port, localAddress, localPort);\n        s.setEnabledProtocols(new String[]{tag});\n        return s;\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/net/rafaeltoledo/security/ui/MainActivity.java",
    "content": "package net.rafaeltoledo.security.ui;\n\nimport android.databinding.DataBindingUtil;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.Log;\n\nimport com.google.android.gms.common.ConnectionResult;\nimport com.google.android.gms.common.api.GoogleApiClient;\nimport com.google.android.gms.safetynet.SafetyNet;\nimport com.scottyab.rootbeer.RootBeer;\n\nimport net.rafaeltoledo.security.R;\nimport net.rafaeltoledo.security.databinding.ActivityMainBinding;\nimport net.rafaeltoledo.security.http.HttpClientProvider;\nimport net.rafaeltoledo.security.http.Tls12SslSocketFactory;\nimport net.rafaeltoledo.security.util.EnvironmentChecker;\nimport net.rafaeltoledo.security.util.InstallationChecker;\nimport net.rafaeltoledo.security.util.SignatureUtils;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.security.GeneralSecurityException;\nimport java.security.KeyStore;\nimport java.security.SecureRandom;\nimport java.util.Collections;\nimport java.util.Random;\n\nimport javax.net.ssl.TrustManager;\nimport javax.net.ssl.TrustManagerFactory;\nimport javax.net.ssl.X509TrustManager;\n\nimport okhttp3.Call;\nimport okhttp3.Callback;\nimport okhttp3.ConnectionSpec;\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.Response;\nimport okhttp3.TlsVersion;\n\npublic class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, MainController {\n\n    private static final String TAG = MainActivity.class.getSimpleName();\n\n    private GoogleApiClient client;\n    private final Random random = new SecureRandom();\n\n    @Override\n    protected void onCreate(@Nullable Bundle savedInstanceState) {\n        super.onCreate(savedInstanceState);\n        ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);\n\n        client = new GoogleApiClient.Builder(this)\n                .addApi(SafetyNet.API)\n                .enableAutoManage(this, this)\n                .build();\n\n        binding.root.setText(new RootBeer(this).isRooted() ? \"Device is rooted\" : \"Device isn't rooted\");\n        binding.installation.setText(InstallationChecker.verifyInstaller(this) ? \"Installed from Play Store\" : \"Installed from unknown source\");\n\n        binding.enviroment.setText((EnvironmentChecker.alternativeIsEmulator() ? \"Running on an emulator\" : \"Running on a device\")\n                + (EnvironmentChecker.isDebuggable(this) ? \" with debugger\" : \"\"));\n\n        binding.tampering.setText((InstallationChecker.checkPackage(this) ?\n                \"The package is consistent\" : \"The package was modified\")\n                + (SignatureUtils.checkSignature(this) ? \" and the signature is ok\" : \" and the signature was changed!\"));\n\n        binding.setController(this);\n    }\n\n    @Override\n    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {\n        Log.e(TAG, \"Failed to connect to Google Client\");\n    }\n\n    @Override\n    public void requestSafetyNetCheck() {\n        byte[] nonce = getRequestNonce();\n        SafetyNet.SafetyNetApi.attest(client, nonce)\n                .setResultCallback(result -> {\n                    if (result.getStatus().isSuccess()) {\n                        showSafetyNetResult(result.getJwsResult());\n                    } else {\n                        Log.e(TAG, \"Error on SafetyNet request - Code (\"\n                                + result.getStatus().getStatusCode() + \"): \" +\n                                \"\" + result.getStatus().getStatusMessage());\n                    }\n                });\n    }\n\n    @Override\n    public void performOkHttpRequest() {\n        OkHttpClient client = HttpClientProvider.getClient();\n\n        Request request = new Request.Builder()\n                .url(\"https://github.com/robots.txt\")\n                .build();\n\n        client.newCall(request).enqueue(new Callback() {\n            @Override\n            public void onFailure(Call call, IOException e) {\n                Log.e(TAG, \"Failed to perform request\", e);\n            }\n\n            @Override\n            public void onResponse(Call call, Response response) throws IOException {\n                Log.d(TAG, response.body().string());\n            }\n        });\n    }\n\n    private void showSafetyNetResult(String result) {\n        /*\n           Forward this result to your server together with the nonce for verification.\n           You can also parse the JwsResult locally to confirm that the API\n           returned a response by checking for an 'error' field first and before\n           retrying the request with an exponential backoff.\n           NOTE: Do NOT rely on a local, client-side only check for security, you\n           must verify the response on a remote server!\n        */\n        Log.d(TAG, \"Success! SafetyNet result:\\n\" + result + \"\\n\");\n    }\n\n    // Ideally, the Nonce should be generated in your server\n    private byte[] getRequestNonce() {\n        String nonceData = \"SafetyNet Sample: \" + System.currentTimeMillis();\n        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();\n        byte[] bytes = new byte[24];\n        random.nextBytes(bytes);\n        try {\n            byteStream.write(bytes);\n            byteStream.write(nonceData.getBytes());\n        } catch (IOException e) {\n            Log.e(TAG, \"Failed to generate nonce\", e);\n            return null;\n        }\n        return byteStream.toByteArray();\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/net/rafaeltoledo/security/ui/MainController.java",
    "content": "package net.rafaeltoledo.security.ui;\n\npublic interface MainController {\n\n    void requestSafetyNetCheck();\n\n    void performOkHttpRequest();\n}\n"
  },
  {
    "path": "app/src/main/java/net/rafaeltoledo/security/util/EnvironmentChecker.java",
    "content": "package net.rafaeltoledo.security.util;\n\nimport android.content.Context;\nimport android.content.pm.ApplicationInfo;\nimport android.os.Build;\nimport android.util.Log;\n\npublic class EnvironmentChecker {\n\n    private static final String TAG = EnvironmentChecker.class.getSimpleName();\n\n    private static String getSystemProperty(String name) throws Exception {\n        Class systemPropertyClass = Class.forName(\"android.os.SystemProperties\");\n        return (String) systemPropertyClass.getMethod(\"get\", new Class[]{String.class})\n                .invoke(systemPropertyClass, name);\n    }\n\n    public static boolean alternativeIsEmulator() {\n        return Build.FINGERPRINT.startsWith(\"generic\")\n                || Build.FINGERPRINT.startsWith(\"unknown\")\n                || Build.MODEL.contains(\"google_sdk\")\n                || Build.MODEL.contains(\"Emulator\")\n                || Build.MODEL.contains(\"Android SDK built for x86\")\n                || Build.MANUFACTURER.contains(\"Genymotion\")\n                || (Build.BRAND.startsWith(\"generic\") && Build.DEVICE.startsWith(\"generic\"))\n                || \"google_sdk\".equals(Build.PRODUCT)\n                || \"goldfish\".equals(Build.HARDWARE);\n    }\n\n    public static boolean isEmulator() {\n        try {\n            boolean goldfish = getSystemProperty(\"ro.hardware\").contains(\"goldfish\");\n            boolean emu = getSystemProperty(\"ro.kernel.qemu\").length() > 0;\n            boolean sdk = getSystemProperty(\"ro.product.model\").equals(\"sdk\");\n\n            if (emu || goldfish || sdk) {\n                return true;\n            }\n\n        } catch (Exception e) {\n            Log.d(TAG, \"Failed to check enviroment\", e);\n        }\n\n        return false;\n    }\n\n    public static boolean isDebuggable(Context context) {\n        return (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/net/rafaeltoledo/security/util/InstallationChecker.java",
    "content": "package net.rafaeltoledo.security.util;\n\nimport android.content.Context;\n\npublic class InstallationChecker {\n\n    private static final String GOOGLE_PLAY = \"com.android.vending\";\n    private static final String ORIGINAL_PACKAGE = \"net.rafaeltoledo.security\";\n\n    public static boolean verifyInstaller(Context context) {\n        final String installer = context.getPackageManager()\n                .getInstallerPackageName(context.getPackageName());\n        return installer != null && installer.compareTo(GOOGLE_PLAY) == 0;\n    }\n\n    public static boolean checkPackage(Context context) {\n        return context.getPackageName().compareTo(ORIGINAL_PACKAGE) == 0;\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/net/rafaeltoledo/security/util/SignatureUtils.java",
    "content": "package net.rafaeltoledo.security.util;\n\nimport android.content.Context;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.Signature;\nimport android.util.Base64;\nimport android.util.Log;\n\nimport java.security.MessageDigest;\n\npublic class SignatureUtils {\n\n    private static final String TAG = SignatureUtils.class.getSimpleName();\n    private static final String SIGNATURE = \"0P333z1O57jHJ87piTMi3W6VuQU=\\n\";\n\n    public static boolean checkSignature(Context context) {\n        try {\n            PackageInfo packageInfo = context.getPackageManager()\n                    .getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);\n            for (Signature signature : packageInfo.signatures) {\n                MessageDigest sha = MessageDigest.getInstance(\"SHA\");\n                sha.update(signature.toByteArray());\n                final String currentSignature = Base64.encodeToString(sha.digest(), Base64.DEFAULT);\n                if (SIGNATURE.equals(currentSignature)) {\n                    return true;\n                }\n            }\n        } catch (Exception e) {\n            Log.e(TAG, \"Failed to check signature\", e);\n        }\n\n        return false;\n    }\n}\n"
  },
  {
    "path": "app/src/main/res/layout/activity_main.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layout xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n    <data>\n\n        <variable\n            name=\"controller\"\n            type=\"net.rafaeltoledo.security.ui.MainController\" />\n    </data>\n\n    <android.support.v7.widget.LinearLayoutCompat\n        android:layout_width=\"match_parent\"\n        android:layout_height=\"match_parent\"\n        android:gravity=\"center\"\n        android:orientation=\"vertical\">\n\n        <TextView\n            android:id=\"@+id/root\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\" />\n\n        <TextView\n            android:id=\"@+id/installation\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\" />\n\n        <TextView\n            android:id=\"@+id/enviroment\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\" />\n\n        <TextView\n            android:id=\"@+id/tampering\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:gravity=\"center\" />\n\n        <Button\n            android:id=\"@+id/button_safetynet\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:onClick=\"@{() -> controller.requestSafetyNetCheck()}\"\n            android:text=\"@string/button_safetynet\" />\n\n        <Button\n            android:id=\"@+id/button_okhttp\"\n            android:layout_width=\"wrap_content\"\n            android:layout_height=\"wrap_content\"\n            android:onClick=\"@{() -> controller.performOkHttpRequest()}\"\n            android:text=\"@string/button_okhttp\" />\n\n    </android.support.v7.widget.LinearLayoutCompat>\n</layout>"
  },
  {
    "path": "app/src/main/res/values/colors.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n    <color name=\"colorPrimary\">#3F51B5</color>\n    <color name=\"colorPrimaryDark\">#303F9F</color>\n    <color name=\"colorAccent\">#FF4081</color>\n</resources>\n"
  },
  {
    "path": "app/src/main/res/values/strings.xml",
    "content": "<resources>\n    <string name=\"app_name\">Security</string>\n\n    <string name=\"button_safetynet\">SafetyNet</string>\n    <string name=\"button_okhttp\">Pinned Request</string>\n</resources>\n"
  },
  {
    "path": "app/src/main/res/values/styles.xml",
    "content": "<resources>\n\n    <!-- Base application theme. -->\n    <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\">\n        <!-- Customize your theme here. -->\n        <item name=\"colorPrimary\">@color/colorPrimary</item>\n        <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item>\n        <item name=\"colorAccent\">@color/colorAccent</item>\n    </style>\n\n</resources>\n"
  },
  {
    "path": "build.gradle",
    "content": "buildscript {\n    repositories {\n        jcenter()\n    }\n    dependencies {\n        classpath 'com.android.tools.build:gradle:2.4.0-alpha7'\n    }\n}\n\nallprojects {\n    repositories {\n        jcenter()\n    }\n}\n\ntask clean(type: Delete) {\n    delete rootProject.buildDir\n}\n"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "content": "#Tue May 02 09:28:42 BRT 2017\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-3.5-all.zip\n"
  },
  {
    "path": "gradle.properties",
    "content": "# Project-wide Gradle settings.\n\n# IDE (e.g. Android Studio) users:\n# Gradle settings configured through the IDE *will override*\n# any settings specified in this file.\n\n# For more details on how to configure your build environment visit\n# http://www.gradle.org/docs/current/userguide/build_environment.html\n\n# Specifies the JVM arguments used for the daemon process.\n# The setting is particularly useful for tweaking memory settings.\norg.gradle.jvmargs=-Xmx1536m\n\n# When configured, Gradle will run in incubating parallel mode.\n# This option should only be used with decoupled projects. More details, visit\n# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects\n# org.gradle.parallel=true\n"
  },
  {
    "path": "gradlew",
    "content": "#!/usr/bin/env bash\n\n##############################################################################\n##\n##  Gradle start up script for UN*X\n##\n##############################################################################\n\n# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nDEFAULT_JVM_OPTS=\"\"\n\nAPP_NAME=\"Gradle\"\nAPP_BASE_NAME=`basename \"$0\"`\n\n# Use the maximum available, or set MAX_FD != -1 to use that value.\nMAX_FD=\"maximum\"\n\nwarn ( ) {\n    echo \"$*\"\n}\n\ndie ( ) {\n    echo\n    echo \"$*\"\n    echo\n    exit 1\n}\n\n# OS specific support (must be 'true' or 'false').\ncygwin=false\nmsys=false\ndarwin=false\ncase \"`uname`\" in\n  CYGWIN* )\n    cygwin=true\n    ;;\n  Darwin* )\n    darwin=true\n    ;;\n  MINGW* )\n    msys=true\n    ;;\nesac\n\n# Attempt to set APP_HOME\n# Resolve links: $0 may be a link\nPRG=\"$0\"\n# Need this for relative symlinks.\nwhile [ -h \"$PRG\" ] ; do\n    ls=`ls -ld \"$PRG\"`\n    link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n    if expr \"$link\" : '/.*' > /dev/null; then\n        PRG=\"$link\"\n    else\n        PRG=`dirname \"$PRG\"`\"/$link\"\n    fi\ndone\nSAVED=\"`pwd`\"\ncd \"`dirname \\\"$PRG\\\"`/\" >/dev/null\nAPP_HOME=\"`pwd -P`\"\ncd \"$SAVED\" >/dev/null\n\nCLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar\n\n# Determine the Java command to use to start the JVM.\nif [ -n \"$JAVA_HOME\" ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n        # IBM's JDK on AIX uses strange locations for the executables\n        JAVACMD=\"$JAVA_HOME/jre/sh/java\"\n    else\n        JAVACMD=\"$JAVA_HOME/bin/java\"\n    fi\n    if [ ! -x \"$JAVACMD\" ] ; then\n        die \"ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nelse\n    JAVACMD=\"java\"\n    which java >/dev/null 2>&1 || die \"ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\nfi\n\n# Increase the maximum file descriptors if we can.\nif [ \"$cygwin\" = \"false\" -a \"$darwin\" = \"false\" ] ; then\n    MAX_FD_LIMIT=`ulimit -H -n`\n    if [ $? -eq 0 ] ; then\n        if [ \"$MAX_FD\" = \"maximum\" -o \"$MAX_FD\" = \"max\" ] ; then\n            MAX_FD=\"$MAX_FD_LIMIT\"\n        fi\n        ulimit -n $MAX_FD\n        if [ $? -ne 0 ] ; then\n            warn \"Could not set maximum file descriptor limit: $MAX_FD\"\n        fi\n    else\n        warn \"Could not query maximum file descriptor limit: $MAX_FD_LIMIT\"\n    fi\nfi\n\n# For Darwin, add options to specify how the application appears in the dock\nif $darwin; then\n    GRADLE_OPTS=\"$GRADLE_OPTS \\\"-Xdock:name=$APP_NAME\\\" \\\"-Xdock:icon=$APP_HOME/media/gradle.icns\\\"\"\nfi\n\n# For Cygwin, switch paths to Windows format before running java\nif $cygwin ; then\n    APP_HOME=`cygpath --path --mixed \"$APP_HOME\"`\n    CLASSPATH=`cygpath --path --mixed \"$CLASSPATH\"`\n    JAVACMD=`cygpath --unix \"$JAVACMD\"`\n\n    # We build the pattern for arguments to be converted via cygpath\n    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`\n    SEP=\"\"\n    for dir in $ROOTDIRSRAW ; do\n        ROOTDIRS=\"$ROOTDIRS$SEP$dir\"\n        SEP=\"|\"\n    done\n    OURCYGPATTERN=\"(^($ROOTDIRS))\"\n    # Add a user-defined pattern to the cygpath arguments\n    if [ \"$GRADLE_CYGPATTERN\" != \"\" ] ; then\n        OURCYGPATTERN=\"$OURCYGPATTERN|($GRADLE_CYGPATTERN)\"\n    fi\n    # Now convert the arguments - kludge to limit ourselves to /bin/sh\n    i=0\n    for arg in \"$@\" ; do\n        CHECK=`echo \"$arg\"|egrep -c \"$OURCYGPATTERN\" -`\n        CHECK2=`echo \"$arg\"|egrep -c \"^-\"`                                 ### Determine if an option\n\n        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition\n            eval `echo args$i`=`cygpath --path --ignore --mixed \"$arg\"`\n        else\n            eval `echo args$i`=\"\\\"$arg\\\"\"\n        fi\n        i=$((i+1))\n    done\n    case $i in\n        (0) set -- ;;\n        (1) set -- \"$args0\" ;;\n        (2) set -- \"$args0\" \"$args1\" ;;\n        (3) set -- \"$args0\" \"$args1\" \"$args2\" ;;\n        (4) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" ;;\n        (5) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" ;;\n        (6) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" ;;\n        (7) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" ;;\n        (8) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" ;;\n        (9) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" \"$args8\" ;;\n    esac\nfi\n\n# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules\nfunction splitJvmOpts() {\n    JVM_OPTS=(\"$@\")\n}\neval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS\nJVM_OPTS[${#JVM_OPTS[*]}]=\"-Dorg.gradle.appname=$APP_BASE_NAME\"\n\nexec \"$JAVACMD\" \"${JVM_OPTS[@]}\" -classpath \"$CLASSPATH\" org.gradle.wrapper.GradleWrapperMain \"$@\"\n"
  },
  {
    "path": "gradlew.bat",
    "content": "@if \"%DEBUG%\" == \"\" @echo off\r\n@rem ##########################################################################\r\n@rem\r\n@rem  Gradle startup script for Windows\r\n@rem\r\n@rem ##########################################################################\r\n\r\n@rem Set local scope for the variables with windows NT shell\r\nif \"%OS%\"==\"Windows_NT\" setlocal\r\n\r\n@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\r\nset DEFAULT_JVM_OPTS=\r\n\r\nset DIRNAME=%~dp0\r\nif \"%DIRNAME%\" == \"\" set DIRNAME=.\r\nset APP_BASE_NAME=%~n0\r\nset APP_HOME=%DIRNAME%\r\n\r\n@rem Find java.exe\r\nif defined JAVA_HOME goto findJavaFromJavaHome\r\n\r\nset JAVA_EXE=java.exe\r\n%JAVA_EXE% -version >NUL 2>&1\r\nif \"%ERRORLEVEL%\" == \"0\" goto init\r\n\r\necho.\r\necho ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\r\necho.\r\necho Please set the JAVA_HOME variable in your environment to match the\r\necho location of your Java installation.\r\n\r\ngoto fail\r\n\r\n:findJavaFromJavaHome\r\nset JAVA_HOME=%JAVA_HOME:\"=%\r\nset JAVA_EXE=%JAVA_HOME%/bin/java.exe\r\n\r\nif exist \"%JAVA_EXE%\" goto init\r\n\r\necho.\r\necho ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%\r\necho.\r\necho Please set the JAVA_HOME variable in your environment to match the\r\necho location of your Java installation.\r\n\r\ngoto fail\r\n\r\n:init\r\n@rem Get command-line arguments, handling Windowz variants\r\n\r\nif not \"%OS%\" == \"Windows_NT\" goto win9xME_args\r\nif \"%@eval[2+2]\" == \"4\" goto 4NT_args\r\n\r\n:win9xME_args\r\n@rem Slurp the command line arguments.\r\nset CMD_LINE_ARGS=\r\nset _SKIP=2\r\n\r\n:win9xME_args_slurp\r\nif \"x%~1\" == \"x\" goto execute\r\n\r\nset CMD_LINE_ARGS=%*\r\ngoto execute\r\n\r\n:4NT_args\r\n@rem Get arguments from the 4NT Shell from JP Software\r\nset CMD_LINE_ARGS=%$\r\n\r\n:execute\r\n@rem Setup the command line\r\n\r\nset CLASSPATH=%APP_HOME%\\gradle\\wrapper\\gradle-wrapper.jar\r\n\r\n@rem Execute Gradle\r\n\"%JAVA_EXE%\" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% \"-Dorg.gradle.appname=%APP_BASE_NAME%\" -classpath \"%CLASSPATH%\" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%\r\n\r\n:end\r\n@rem End local scope for the variables with windows NT shell\r\nif \"%ERRORLEVEL%\"==\"0\" goto mainEnd\r\n\r\n:fail\r\nrem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\r\nrem the _cmd.exe /c_ return code!\r\nif  not \"\" == \"%GRADLE_EXIT_CONSOLE%\" exit 1\r\nexit /b 1\r\n\r\n:mainEnd\r\nif \"%OS%\"==\"Windows_NT\" endlocal\r\n\r\n:omega\r\n"
  },
  {
    "path": "settings.gradle",
    "content": "include ':app'\n"
  }
]