Showing posts with label Mobile pentesting. Show all posts
Showing posts with label Mobile pentesting. Show all posts

Friday, 18 May 2018

NIST CYBERSECURITY FRAMEWORK 1.1


NIST CYBERSECURITY FRAMEWORK 1.1

INTRODUCTION

The Framework 1.1  offers an agile way to address cybersecurity, including cybersecurity’s effect on physical, cyber, and people dimensions. It applies to organisations relying on technology, whether their cybersecurity focus is primarily on Information Technology (IT), Industrial Control Systems (ICS), Cyber-Physical Systems (CPS), or connected devices more generally, including the Internet of Things (IoT). The Framework 1.1 can enhance the organisations in addressing cybersecurity as affects the privacy of other data. Additionally, the Framework’s 1.1 outcomes serve as targets for workforce development and evolution activities.
The Framework 1.1 is not a one-size-fits-all method to manage cybersecurity risk for critical infrastructure. Organizations will continue to have static risks with different threats and vulnerabilities, and also with risk tolerances. They also will vary in how they customise practices described in the Framework 1.1. Organizations can determine activities that are important to critical service delivery and can prioritise investments to maximise the impact of each dollar spent. The Framework 1.1 is aiming to reduce the risk and better managing cybersecurity threats.
The Framework 1.1 is a living document and will continue to be updated and improved as the industry responds to implementation. NIST will continue coordinating with the private sector and government agencies at all levels. As the Framework 1.1 is placed into higher practice, additional lessons learned will be integrated into future versions. It will ensure the Framework 1.1 which meets the needs of infrastructure owners and operators in a critical environment of new threats and also the solutions.

USAGE OF FRAMEWORK 1.1

An organisation can use the Framework 1.1 as a critical part of its systematic process for identifying, assessing, and managing cybersecurity risk. The Framework is not used to replace existing methods, but companies can use its current method, and that can overlap it onto the Framework 1.1 to determine loopholes in its current cybersecurity risk approach. The Framework 1.1 can be used as a cybersecurity risk management tool; an organisation can identify activities that are most central to critical service delivery and prioritise expenditures to maximise the impact of the investment.
It is designed to complement cybersecurity operations. It can serve as the foundation for a new cybersecurity program or a mechanism for improving an existing application. The Framework  1.1 provides a means of articulating cybersecurity requirements to business partners and customers and can help identify gaps in an organisation’s cybersecurity practices.
The Framework 1.1 can be applied throughout the lifecycle phases of the plan, design, build/buy, deploy, operate, and decommission. The planning phase begins the cycle of any system and lays the groundwork for everything that follows. Overarching cybersecurity considerations should be declared and described as clearly as possible. The plan should be recognized that those requirements are to evolve during the remainder of the life cycle.
CYBERSECURITY USAGE FRAMEWORK 1.1

CONCLUSION

The Cybersecurity Framework 1.1 is intended to reduce risk by improving the management of cyber security risk to organisational objectives. Ideally, organisations using the Framework 1.1 will be able to measure and assign values to their risk along with the cost and benefits of steps taken to decrease risk to proper levels. The better an organisation can estimate its risk, costs, and advantages of cybersecurity strategies and actions, the more rational, useful, and valuable its cybersecurity approach and investments will be.
Over time, self-assessment and measurement should improve decision making about investment priorities. For example, measuring – or at least robustly characterising – aspects of an organisation’s cybersecurity state and trends over time can enable that organisation to understand and convey meaningful risk information to dependents, suppliers, buyers, and other parties. An organisation can accomplish this internally or by seeking a third-party assessment. If done correctly and with an appreciation of limitations, these measurements can provide a basis for healthy trusted relationships, both inside and outside of an organisation.

REFERENCE:

https://www.nist.gov/cyberframework
https://www.us-cert.gov/ccubedvp/cybersecurity-framework

AUTHOR

Dharmesh B
Security Engineer
Briskinfosec Technology and Consulting Pvt Ltd.,
https://www.linkedin.com/in/dharmeshbaskaran/

Tuesday, 8 May 2018

APKiD tool — Detecting Malware And Tampered Android Apps

APKID TOOL — DETECTING MALWARE AND TAMPERED ANDROID APPS

INTRODUCTION:

APKiD Tool finds what type of packers, obfuscator and compilers are used in the APK file. Using APKiD, We can analyse an APK file whether it is malware or pirated version of an original APK so it will be a useful tool for a malware analyser or security researcher who cares about analysing malware in android. Before getting into the APKiD installation let’s examine how APKiD tool is detecting compilers, packers and obfuscators by looking into APK or DEX file.
Mostly, we install the Android app from google play store from the original version, but in case of third-party app stores, we can download the same application which is available in google play store but can’t be trusted because there are chances of the app containing virus or malware. So what makes the differences between the original and modified APK file apart from the tampered code, the difference is in the compiling process. The original file is disassembled and recompiled by using the APKTOOL. APKTOOL uses smali, and they are part of the same dexlib project. So any android app which had malware injected code into original or pirated will have probably been disassembled and recompiled by dexlib. dexlib is a compiler, like dexlib there are several compilers available which is listed below:
  • dx – standard Android SDK compiler
  • dexmerge – used for incremental builds by some IDEs (after using dx)
  • dexlibx
  • dexlibx beta
  • dexlibx
APKid tool looks into the APK or Dex file for detecting the type of compilers.

APKID INSTALLATION:

There are two ways you can install the APKiD tool, by configuring Yara-python and installing APKiD tool or through Docker, you can install which is natural and works fine for me. Here, I will introduce through Docker:

INSTALLATION REQUIREMENT:

  • Docker
  • git

INSTALLATION STEPS:

After installing docker and git Start the docker and follow the below types in terminal:
git clone https://github.com/rednaga/APKiD

cd APKiD/

docker-compose build

cd docker/

./apkid.sh ~/example/example.apk
it can scan APK, DEX, ELF file formats to detect the compilers.

USAGE:

STEPS TO SCAN THE APK:

  • cd APKiD/
  • cd docker/
  • ./apkid.sh ~/example/example.apk
Here, I have scanned a vulnerable Apk called insecure bank application. As shown, below result is giving the details about its compiler, manipulator and its checking mechanisms.

CONCLUSION:

From this blog, we have discussed how we can detect the compilers, packers and obfuscators of an Android app through APKiD tool and also APKiD is developing a slack bot version of its tool which allows users to upload an APK file for analysing.
Briskinfosec provides the best mobile Security solutions. For further doubts and security, solution advice reach us@ Contact@briskinfosec.com

REFERENCE LINK:

https://github.com/rednaga/APKiD

AUTHOR

Dinesh C
Security Engineer
Briskinfosec Technology And Consulting Pvt Ltd.,
follow me @https://www.linkedin.com/in/dineshdinz/

Tuesday, 13 March 2018

Detection and Exploitation XML Entity Injection(XXE)

DETECTION AND EXPLOITATION XML ENTITY INJECTION(XXE)

INTRODUCTION

XML External Entity Attack is a type of injection or input validation vulnerability which occurs in an application that allows any input parameter or data to be XML input or input which is combined into XML form data, and it is passed to an XML parser running with sufficient privileges to include external or system files.
Recently, there has been an increase in the use of XML documents due to the growing use of the web services such as REST API and SOAP, which commonly use XML to process the data.
XML has a feature to create entities dynamically; some of the objects are predefined, and they referenced by using an ampersand (&) and a semicolon (;) at the end. However, XML also allows us to create custom entities, the most popular being the internal and external entities. Internal entities can be used to reference internal data and external entities to reference data from external sources.

EXAMPLE FOR INTERNAL ENTITY:

<!DOCTYPE profile [<!ENTITY name "Brisk Infosec">]>
<Profile>
<name>&name;</name>
<class>Cyber Security</class>
<service>Pentest</service>
</profile>
In the first line, we have defined an entity “name” having a value “Brisk”; the block used to define the entities is known as the DTD block. Next, in the third line, you can see that we have referenced the entity “&name;”, which holds the value “Brisk.” In this way, we don’t have to input the name each time. All we have to do is use a reference to the entity.

EXAMPLE FOR EXTERNAL ENTITY:

<!DOCTYPE profile [<!ENTITY name SYSTEM "http://target.com/profile ">]>
<Profile>
<name>&name;</name>
<class>Data</class>
<service>pentest</service>
</profile>
In the first line, in the DTD block, we have defined an external entity, which contains a link to an external resource. When this XML document is processed, it would request an external source and would replace values of all instances of “&name;” with the content of the external resource. If the content of the external resource is processed and displayed back to the user without proper validation, an attacker may be able to abuse the parser in conducting an XXE injection attack.
To find any XXE (XML External Entity) vulnerability, attacker or tester needs to inject XML characters in all input fields and observe if XML parsing errors are generated.

EXPLOITATION OF XXE VULNERABILITY:

Use information disclosed in error messages to determine at what file path the XML parser is parsing. Cause errors to occur using malformed XML.
Let us consider a test website (here I’m using OWASP Mutillidae application)
1. In below image, the application has an XML parser input page,
2. Let’s try giving some XML inputs and check the response from the server.
3. After that, we can try to inject XML inputs with multiple user-defined entities
4. Now we can try to include external data using <!Entity> section of XML input. The <!ENTITY> section of an XML document optionally defines external files to be included as part of the XML document. Interestingly these can even be files from the system parsing the XML.
We can use the <!ENTITY> section of XML input, we can try to access local files like /etc/ passwd files of a Linux server.
5. Once we have given the above XML payload, we can get the password files details from back-end Linux server.
6. Similarly, we can try to load the boot.ini files if the server is windows operating system, using an XML payload like below
          <?xml version="1.0"?>

            <!DOCTYPE change-log [
                        <!ENTITY systemEntity SYSTEM "../../../../boot.ini">
            ]>
            <change-log>
                        <text>&systemEntity;</text>
            </change-log>

MITIGATIONS FOR XXE INJECTION ATTACKS:

1. XML parser functions like unmarshaller should have a secure configuration to prevent allowing external entities as part of an incoming XML document input.
2.XML inputs should not be processed directly as java.io.File, java.io.inputstream.
References:
https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing
https://stackoverflow.com/questions/40649152/how-to-prevent-xxe-attack

Dawood Ansar
Security Engineer
BriskInfosec Technology and consulting PVT LTD
Find me @https://www.linkedin.com/in/dawood-ansar-29403213b/

Thursday, 15 February 2018

MARA FRAMEWORK


MARA FRAMEWORK


Mobile Application and Reverse Engineering and Analysis Framework and it’s a tool that contains some major reverse engineering and analysis tools for Mobile Application testing and using this framework we can decompile a particular APK file and analyze the major issues in OWASP Mobile Top and this tool is been mainly used by the Penetration testers, security researchers, and application developers.
We can also use the various features of the APK file like
  • APK Reverse Engineering
  • APK DE obfuscation
  • APK Analysis
  • APK Manifest Analysis
  • Domain Analysis
  • Security Analysis etc.

APK REVERSE ENGINEERING:

  • Disassembling Dalvik bytecode to smali bytecode via baksmali and apktool
  • Disassembling Dalvik bytecode to java bytecode via enjarify
  • Decompiling APK to Java source code via jadxgui

APK DEOBFUSCATION:

We can extract the APK and analyze the code using Jadx-gui and it shows the codes that has been available for a selected APK File

APK ANALYSIS:

  • Parsing smali files for analysis via smalisca
  • Dump all assets, libraries and resources
  • Extracting certificate data via openssl
  • Identify methods and classes via classyshark
  • It Extracts the Manifest File in XML format
  • Scan for apk vulnerabilities via androbug framework
  • Analyse the APK for Potential malicious behavior like androwarn

APK MANIFEST ANALYSIS:

  • It Extracts the Intent and exported activities
  • It Extracts the Manifest Files and services
  • Extract exported services
  • Checks if the APK is debuggable
  • Checks if the APK allows Databackup
  • Check if the APK receives any binary SMS

DOMAIN AND SECURITY ANALYSIS:

Domain analysis is been fetched from the WhatsWeb and the security analysis is checked from the OWASP mobile TOP 10 Checklist

INSTALLATION:

I have downloaded the MARA Framework from Github and listed the option in the framework
We need to launch MARA framework by using the command ./mara.sh

OPTIONS IN FRAMEWORK:

Here In the particular folder of MARA Framework you can see the option by the command of ./mara.sh
And I have downloaded a vulnerable app and configured in the Mara framework

APK ANALYSIS AND REVERSE ENGINEERING:

And after the analysis of the APK it gets saved in the particular folder as given in the below screenshot
Particular Folder that has been saved on the PC is by the below screenshot
Here the decompiled files get saved on the MARA-Framework folders and by viewing this files you can check for the required issues by the vulnerable APK-file.

CONCLUSION:

A multiple set of test tools will be necessary for a more thorough and comprehensive testing process .I have given an overview of the MARA Framework setup process and how it can expedite your android app reverse engineering and static analysis process.
BriskInfosec holds utmost experience in Mobile App Penetration Test to identify potential vulnerabilities and insure coding practises in android application
To know more get in touch with us

AUTHOR

Rajesh
Security Researcher
BriskInfoSec Technology and Consulting PVT LTD

Wednesday, 3 January 2018

YSO – Opensource MOBILE SECURITY FRAMEWORK

YSO – OPENSOURCE MOBILE SECURITY FRAMEWORK

YSO is the Mobile Security Framework and they are capable of performing Static and Dynamic analysis on mobile Applications and Its supports only APK (Android) and IPA (IOS) files and they are various tools used to decompile, debug and code review in mobile app testing and it consumes lot of time and by this framework we can able to check over various mobile issues like
  • Insecure Data Storage
  • Insecure Communication
  • Insecure Authentication
  • Certificate Pinning
  • Backup Data’s Enabled etc.
The above issues are the major mobile issues that are occurred in a common way
In Static Analysis it used to detect automated Code review, insecure Permissions, Configuration issues, and it also detects over insecure code like SSL overriding, SSL bypass, weak crypto, obfuscated codes, improper permissions, hard coded secrets, improper usage of dangerous APIs, and leakage of sensitive/PII information.
In Dynamic Analysis is slightly difficult to configure it mainly runs on the VM or on a configured devices and detects the issues at run time and Further analysis is done on the captured network packets, decrypted HTTP traffic, dumps, logs, etc.
This tool is highly scalable by which you can add your custom rules in easy use and you can use this framework results as a source to detect the mobile application issues manually and finally the overall report gets saved on the required folder that you are selected.
Requirements:
Notes:

STATIC ANALYSIS APK RESULTS:

CERTIFICATE ISSUE:




Static Analysis in IOS result:

CONFIGURING STATIC ANALYZER:

Tested on Windows 7, 8, 8.1, Ubuntu, OSX Marvicks
Install Django version 1.8
Pip install Django==1.8
Here I have installed Django in Linux
Django is one of the Web application Framework that used to make the process easier because it has some automated tools in-build so it executes the result at short interval of time
YSO Framework Configuration in Linux:
I have configured the YSO Framework and configured the server and
Configuration Linkhttp://127.0.0.1:8000/
Once you have entered this URL in your browser U’ll get a Page as follows

YSO EXECUTION ON BROWSER:

Here In this Framework you can upload a particular APK file OR IPA File that you are going to test and it executes the result as in the above figure

CONCLUSION:

From this Blog we have discussed above the installation, Configuration and working Method of YOS Mobile application Framework and we also discussed the results executed for a particular APK or IPA files.
YSO Mobile Security Framework is an intelligent, all-in-one open source mobile application (Android/iOS) automated pen-testing framework capable of performing static and dynamic analysis. We’ve been depending on multiple tools to carry out reversing, decoding, debugging, code review, and pen-test and this process requires a lot of effort and time. YSO Mobile Security Framework can be used for effective and fast security analysis of Android and iOS Applications.
BiskInfosec provides the best mobile Security solutions. For further doubts and security solution advices reach us @ Contact@briskinfosec.com

AUTHOR

RamKumar
Security Engineer
BriskInfosec Technolagy And consulting PVT LTD
follow me @https://www.linkedin.com/in/ram-kumar-3439b511a/

Friday, 29 December 2017

How your employee’s smartphones are serious threat to your organization?

HOW YOUR EMPLOYEE’S SMARTPHONES ARE SERIOUS THREAT TO YOUR ORGANIZATION?

Employee’s smartphones are a serious threat to the organization since it is allowed to use in the production environment. Android is the most popular mobile OS with more than 60% market share. As Android is ruling smartphone and tablet markets, developers are also creating more apps for Android devices. This is the reason why the Android market has millions of apps. Like websites, apps also need penetration testing to check for various vulnerabilities. Security testing for Android apps will need to have a penetration testing environment on your Android device.
Almost all Useful Hacking Tools, Scripts can be used on Your Android Mobile. Termux is a Powerful app which can be used to install useful packages, Hacking Tools On your Android
By installing this program, you can hack anything that comes to mind. From targeting websites, hacking computers, sniffing networks, brute forcing passwords, information gathering and many more.
For more details about termux can be found in their official termux page. Link for the has given below
Installation
Google Play: https://play.google.com/store/apps/details?id=com.termux
F-Droid: https://f-droid.org/packages/com.termux/

INSTALLING PACKAGES FROM THE REPOSITORY

To install your favorite tool in termux you can run
pkg install <package name>
Example
pkg install nmap 
To get list of available packages in termux, run
pkg list-all
To search a package
pkg search nmap
To show more info about a package
pkg show nmap

INSTALLING .DEB FILES

Manual way of installing .deb files
pkg install ./package.deb
or
dpkg -i ./package.deb
Termux packages are built using Ubuntu 16.10, so this means that developers can compile any existing software from their machine and then add it to the package manager for anyone to download. It is a very simple and elegant solution to what otherwise could be a complex and difficult problem. One amazing side effect of this is that once the software is compiled, you have full-fledged versions of the software rather than half-baked, ported versions of desktop Linux packages.
Termux gives you a bash terminal by default, but if you are like me and prefer Zsh for its advanced features, the FISH shell is also available. Multiple different shell types are certainly welcome.
Anyone that has used a terminal emulator application on Android knows the pain when you need to enter special keys to control the terminal such as CTRL or ESC. These keys aren’t displayed on the standard touch keyboards used on android devices (save for Hacker Keyboard). Termux developer Fredrik Fornwall, though, has a very novel solution to this. He has bound CTRL to the Volume DOWN key and other special keys like ESC to the Volume UP key. Therefore, by pressing Volume Up + the touch keyboard ‘L’ you can input the terminal command CTRL + ‘L’ which clears the terminal window. The ESC key is sent by pressing volume UP + ‘E’ key for example. You can view all the keys available in Termux on the developer’s website

FEATURES OF TERMUX API

Secure. Access remote servers using the ssh client from OpenSSH. Termux combines standard packages with accurate terminal emulation in a beautiful open source solution.
Feature packed. Take your pick between Bash, fish or Zsh and nano, Emacs or Vim. Grep through your SMS inbox. Access API endpoints with curl and use rsync to store backups of your contact list on a remote server.
Customizable. Install what you want through the APT package management system known from Debian and Ubuntu GNU/Linux. Why not start with installing Git and syncing your dotfiles?
Explorable. Have you ever sat on a bus and wondered exactly which arguments tar accepts? Packages available in Termux are the same as those on Mac and Linux – install man pages on your phone and read them in one session while experimenting with them in another.
With batteries included. Can you imagine a more powerful yet elegant pocket calculator than a readline-powered Python console? Up-to-date versions of Perl, Python, Ruby, and Node.js are all available.
Ready to scale up. Connect a Bluetooth keyboard and hook up your device to an external display if you need to – Termux supports keyboard shortcuts and has full mouse support.
Tinkerable. Develop by compiling C files with Clang and build your own projects with CMake and pkg-config. Both GDB and storage are available if you get stuck and need to debug.
term up has a list of command, all those can be found at link given
https://github.com/termux/termux-packages/blob/master/packages/command-not-found/commands.h

INSTALL SQLMAP

Let’s do a practical session on how to install sqlmap on our android device.
As we know that sqlmap is a most amazing website vulnerability scanning tool which is mostly used by pen testers, Hackers, Security Researchers and so on.
Sqlmap is written in Python programming language environment, so that we need to have python installed in termux ,to install python in termux, run the command
pkg install python2
once the installation is complete, we need to install git package because we are going to download sqlmap from the git repository
to install git in termux
run the command :
pkg install git
now its time to install our favorite tool sqlmap
so run: git clone https://github.com/sqlmapproject/sqlmap.git
  the download process and the installation process will take some time, once it’s been done
then navigate to the sqlmap directory using the following command
cd
then list the files using ls command
now navigate to the sqlmap-dev folder using “cd sqlmap-dev”
once you entered into the folder, list the files using ls command
so you will see the executable file of sqlmap
since sqlmap run under python, so we need to run using the following command
python2 sqlmap.py
bingo … now we have successfully installed sqlmap on our android device itself. Using the same method we can able install different tools on our android device.
Termux: Hackers Perspective
Before termux was originated, hackers were using so many application to perform different attacks. But now everything has come into single app, which is termux. Now this the time where hackers will take over every system easily.
Hackers install Kali Linux on their android phone but it requires some time and patient, but this app looks alternative for the kali.
So now hackers got the best handy tool. Hackers can able to get into your network and he/she can able to perform post exploitation techniques such as MITM, exploitation, etc.
Mitigation from hackers attacks
  • The users need to take necessary precautions in order to protect their devices, as the hackers can exploit any network using termux without the knowledge of the user.
  • Patch anything and everything. Keep in mind that your secure environment from a month ago is now wide open thanks to Patch Tuesday
  • The second Tuesday of each month when Microsoft releases security patches.
  • Some months there are in excess of 30 patches released. That’s 30 potential vulnerabilities. Miss a month … 60 … two months … 120. Hackers are always finding new attack holes and methods into the system software.
  • Patches and new versions of system software are frequently released to fix these newfound problems.
  • Hackers are a close-knit community and they are more than willing to share your network’s flaws with their neighbors.

Be prepared and Be secured!!!

Author
Venkatesh C>S
Security Engineer
BriskInfosec Technology and consulting PVT LTD
Follow me @ https://www.linkedin.com/in/venkatesh-c-s-44174711b/

Saturday, 16 December 2017

MAN IN THE MIDDLE ATTACK ON MOBILE APPLICATIONS

MAN IN THE MIDDLE ATTACK ON MOBILE APPLICATION BECOMES SERIOUS THREAT

WHAT IS MAN IN THE MIDDLE ATTACK?

Man in the middle attacks (MITM) is one of the attacks where the attacker interrupts between the sender and receiver and gathers the sensitive data. MITM attacks, which are a form of session hijacking are not new. However, what might not be known is that mobile devices are vulnerable to MITM attacks too. It is quite complex for the attacker to inject the MITM attack on mobile applications than on web applications.

HOW DOES A MAN-IN-THE-MIDDLE ATTACK WORK?

A man-in-the-middle attack (MITM) is like eavesdropping. Data is sent from point A (Mobile) to point B (server/website), and an attacker can get in-between these transmissions. They then set up tools programmed to “listen in” on transmissions, intercept data that is specifically targeted as valuable, and capture the data. Sometimes this data can be modified in the process of transmission to try to trick the end user to expose sensitive information, such as login credentials. Once the user has fallen into the trap, the data is collected from the target, and the original data is then forwarded to the planned destination unaltered.

MAN IN THE MIDDLE ATTACK ON MOBILE APPLICATIONS

For mobile apps to prevent these types of attacks it is important to look at how the mobile app performs authentication. Using certificate pinning within the mobile app helps ensure that the mobile app is communicating with the device it is expecting to communicate with.

TYPES OF MITM ATTACKS

  • ARP Poisoning
  • DNS Spoofing
  • Port stealing
  • Invisible Proxy
  • Certificate Forgeing
In this blog, we will discuss the major attack (SSL PINNING)

SSL PINNING

Certificate pinning is hard-coding the certificate known to be used by the server in the mobile application. The app can then ignore the device’s trust store and rely on its own, and allow only SSL connections to hosts signed with certificates stored inside the application.
The client makes a connection to the server and the server responds with its SSL certificate. If that certificate was issued by a Certificate Authority that is trusted by the OS, then the connection is allowed.

 CERTIFICATE PINNING FOR ANDROID AND IOS APPS

When we, developers, are working in the development of any kind of software, we can’t forget about security. The minimum security measure we should use is HTTPS as the protocol to share information between a client (in this case, an Android/iOS app) and a server, followed by an updated cryptographic protocol like TLS 1.2 (SSL 3.0 is vulnerable!)
You may think that using an HTTPS is enough but in some cases like banking applications, where sensitive data may be sent between our client and our server, could be risky.
By default, when making a TLS connection, the client check two things:
  • The server’s certificate matches the requested hostname.
  • The server’s certificate has a chain of truth back to a trusted root certificate.
What it doesn’t do is check, if the certificate is the specific certificate you know your server is using, and that’s a possible security vulnerability, if the client is compromised and an unsafe certificate is installed(certificate forging), someone could do a man-in-the-middle attack.
Root CA, intermediate CA and Medium certificate
The solution to this problem is certificate pinning. Storing a certificate on our client application to ensure that any SSL request made matches the server’s certificate provided by a trusted CA (certificate authority). Let us see how to do it on both Android and iOS apps.

ANDROID

OkHttp lib provides a CertificatePinner class to be added to an OkHttpClient instance. The easiest way to pin a host is turned on pinning with a broken configuration and read the expected configuration when the connection fails.
CertificatePinner certificatePinner = new CertificatePinner.Builder()
          .add("mydomain.com", "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
          .build();
      OkHttpClient client = OkHttpClient.Builder()
          .certificatePinner(certificatePinner)
          .build();
After a request is executed, you’ll see this message on the console:
javax.net.ssl.SSLPeerUnverifiedException: Certificate pinning failure!
    Peer certificate chain:
      sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=: CN=mydomain.com, OU=PositiveSSL
      sha256/klO23nT2ehFDXCfx3eHTDRESMz3asj1muO+4aIdjiuY=: CN=COMODO RSA Secure Server CA
      sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=: CN=COMODO RSA Certification Authority
      sha256/lCppFqbkrlJ3EcVFAkeip0+44VaoJUymbnOaEUk7tEU=: CN=AddTrust External CA Root
    Pinned certificates for mydomain.com:
      sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
    at okhttp3.CertificatePinner.check(CertificatePinner.java)
    at okhttp3.Connection.upgradeToTls(Connection.java)
    at okhttp3.Connection.connect(Connection.java)
    at okhttp3.Connection.connectAndSetOwner(Connection.java)
The exception will provide you the server’s certificate public key hashes. Paste them on the CertifinatePinner and done! Once the certificate pinner function is enabled in the Android app it will have protection against        SSL MITM attacks
CertificatePinner certificatePinner = new CertificatePinner.Builder()
        .add("mydomain.com", "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=")
        .add("mydomain.com", "sha256/klO23nT2ehFDXCfx3eHTDRESMz3asj1muO+4aIdjiuY=")
        .add("mydomain.com", "sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=")
        .add("mydomain.com", "sha256/lCppFqbkrlJ3EcVFAkeip0+44VaoJUymbnOaEUk7tEU=")
        .build();

IOS

The iOS solution is not so straightforward because you need to store the certificate itself inside your app. In my case, I’ve used Alamofire as HTTP client lib for Swift.
First, you need to get the server’s certificate in .der format and add it to your iOS project.
openssl s_client -showcerts -server name mydomain.com -connect mydomain.com:443 </dev/null | openssl x509 -outform DER > mydomainCert.der
And now, let’s enable certificate pinning: to do it we need both ServerTrustPolicy and SessionManager objects. The first one will define the hostname and certificates that will be used in the process:
var serverTrustPolicies = [
     "mydomain.com": .pinCertificates(
     certificates: ServerTrustPolicy.certificates(),
     validateCertificateChain: true,
     validateHost: true
   ),
 ]
ServerTrustPolicy.certificates() will return all stored certificates and the booleans will validate the certificate chain and the hostname.
Lastly, create a SessionManager object using this trust policies:
var sessionManager = SessionManager(serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies!))
Done! Just use this sessionManager object to execute request
sessionManager.request(“https://mydomain.com/api”, method: .get, headers: headers)…
Conclusion:
Since MITM attacks are stealthier and it does not need any physical access to the victim device, a robust protection mechanism is required to prevent it. Hence SSL pinning is a much needed robust protection as it protects the application against MITM attacks by only allowing the connections to the server based on the trusted CA certificates.