Pentesting for Android Mobile Applications

Jaimin Gohel
Senior Technical Engagement Manager
Image
Pentesting for Android Mobile Applications

Today, digital connectivity is available "on the go" and mobile devices can be seen in the hands of nearly everyone. Ironically, even with their small sizes and portability, many have replaced the need to be mobile themselves in favor of virtual presence. Online banking and e-commerce applications have rendered in-branch and in-store visits obsolete. Social media allows friends, family, and complete strangers to connect with each other even with miles of distance between them. Home security systems can be monitored and controlled remotely. What used to be tactile buttons and switches have now been replaced by high-resolution touchscreens. Nowadays, even lightbulbs can be toggled on and off through an app.

Currently, Android is the leading mobile operating system worldwide, claiming 71.65% of the market share with over three billion active devices monthly. In 2023, the number of mobile application downloads amounted to 257 billion, generating $171 billion in gross spending. Within the United States, 91% of adults own a smartphone, an increase of 35% since 2011.

However, the instantaneous access to a wealth of resources and information that mobile devices and applications provide has introduced significant security risks. The exploitation of a vulnerability in an application can result in the data of entire userbases being compromised.

To harden your Android applications against attacks, HackerOne offers a methodology-driven penetration testing (pentesting) solution delivered via a Pentest as a Service (PTaaS) model. This approach connects organizations with a heavily vetted cohort of a global ethical hacker community for comprehensive, end-to-end pentesting. Frequently performing dedicated pentesting, using a community-driven PTaaS is crucial to finding vulnerabilities in your Android applications.

Testing Methodologies

HackerOne’s Android application testing methodologies are grounded in the principles of the OWASP Mobile Application Security Project using the project's associated Mobile Application Security Verification Standard (MASVS) and Mobile Application Security Testing Guide (MASTG). Additionally, our testing processes adhere to the Payment Card Industry Data Security Standard (PCI DSS)General Data Protection Regulation standard, and Health Insurance Portability and Accountability Act (HIPAA), required for regulatory compliance for applications that deal with financial transactions, handle user information, or deal with personal health data. This ensures comprehensive and reliable assessments across the attack surfaces of your applications. Organizations can now better protect against risk and attacks with highly skilled experts with specialized, proven expertise in vulnerabilities specific to Android applications.

Our methodology is continuously evolving to ensure comprehensive coverage for each engagement. This approach stems from:

  • Consultations with both internal and external industry experts.
  • Leveraging and adhering to recognized industry standards.
  • Gleaning insights from a vast array of global customer programs, spanning both time-bound and continuous engagements.
  • Detailed analysis of millions of vulnerability reports we receive through our platform (see the Hacktivity page for details).

Threats are constantly evolving, so our methodology can’t remain stagnant. HackerOne’s Delivery team, including experienced Technical Engagement Managers (TEMs), constantly refine and adapt based on feedback and real-world experiences, delivering unparalleled security assurance.

Common Vulnerabilities

Cleartext Communications

Data transmitted over insecure network protocols, such as the unencrypted variants of the HyperText Transfer Protocol (HTTP) and the File Transfer Protocol (FTP), is sent in cleartext, meaning it is human-readable. If a malicious attacker is in a position that allows them to monitor network traffic, this can lead to Man-in-the-Middle (MitM) attacks.

In a MitM attack, communication between a transmitting entity and the intended recipient is intercepted by a malicious, unauthorized third-party. Once captured, the data can be read and arbitrarily modified. This allows the attacker to impersonate either of the parties involved to deceive the other. Additionally, any sensitive information such as payment details or passwords can be stolen. If the client is authenticated with the server, any session cookies or tokens can be copied and reused, which can result in an account takeover.

In Android applications before 7.0 (API level 24), cleartext traffic was allowed by default. The 7.0 release introduced the Network Security Configuration (NSC) feature, allowing developers to customize network security settings through a declarative XML file. It wasn't until the release of Android 9 (API level 28) that cleartext traffic was disabled by default.

For applications targeting Android 7.0 to 8.1 (API 24 to 27), to use an NSC file, it must be declared in the application's AndroidManifest.xml file:

<manifest ... >
    <application
        android:networkSecurityConfig="@xml/network_security_config"
        ... >
        <!-- Place child elements of <application> element here. -->
    </application>
</manifest>

The res/xml/network_security_config.xml file must be manually created with the cleartextTrafficPermitted set to "false" to override the insecure default setting:

<base-config cleartextTrafficPermitted="false">
    <trust-anchors>
        <certificates src="system" />
    </trust-anchors>
</base-config>

This will enforce the use of the encrypted HyperText Transfer Protocol Secure (HTTPS) which uses Transport Layer Security (TLS) to only communicate with servers that have a signed certificate from a trusted Certificate Authority (CA).

If an application uses FTP, the secure variant, File Transfer Protocol Secure (FTPS) should be used instead as well.

More information about secure network communication practices can be found in the official documentation.

ZipSlip

Files within ZIP bundles are stored with a fully qualified name, meaning they can contain the same characters used to traverse directories (../). The default Android library from the java.util.zip package, for reading and writing compressed archives, does not check for these characters.

Without proper checks, a malicious ZIP could contain a file named ../../data/data/com.example.app/files/sensitive_file.txt. As the file name determines the location, if the name matches a legitimate application file in the targeted directory, it could be overwritten. This could result in malware replacing program files or data being destroyed.

It is critical that any code that extracts from compressed archives contains the final destination of each file within the intended extraction folder.

For examples of secure handling, view the official documentation.

Insecure Clipboard Handling

In Android versions older equal to or under 10 (API level 29), applications running in the background can access the clipboard content of foreground applications. Calls to the android.text.ClipboardManager API can read from or write to the clipboard without user approval or requiring any permission.

This functionality can expose sensitive data such as banking information, contact details, passwords, cryptocurrency wallet addresses, or any other data a user may copy out of convenience.

Although Android 10 and above requires an application to be focused in order to access the clipboard, if the running application itself has this functionality, it can still exfiltrate the data.

Version 12 (API level 31 and 32) and above will display a Toast message to notify the user when an application accesses the clipboard and also introduced security flags. The ClipDescription.EXTRA_IS_SENSITIVE and android.content.extra.IS_SENSITIVE flags can be used to visually obfuscate the clipboard content preview in the keyboard GUI:

// If your app is compiled with the API level 33 SDK or higher.
PersistableBundle extras = new PersistableBundle();
extras.putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true);
clipData.getDescription().setExtras(extras);

// If your app is compiled with API level 32 SDK or lower.
PersistableBundle extras = new PersistableBundle();
extras.putBoolean("android.content.extra.IS_SENSITIVE", true);
clipData.getDescription().setExtras(extras);

In Android 13 (API level 33) and above, the clipboard will be automatically cleared after a period of time. In older versions this must be manually implemented.

For more information on secure clipboard handling, view the official documentation.

FileProvider Misconfigurations

The FileProvider class available in the AndroidX Core Library enables secure file sharing between applications without directly exposing them. However, misconfigurations can lead to unauthorized access to files. A FileProvider is defined by adding a <provider> element to an application's AndroidManifest.xml file:

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="com.example.myapp.fileprovider"
    android:grantUriPermissions="true"
    android:exported="false">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

The authorities attribute specifies the URI authority that will be used for generating unique content URIs. In order to grant temporary read and write permissions, grantUriPermissions is set to true. With the exported attribute set to false,  the FileProvider is not available publicly.

The <meta-data /> attribute points to the file_paths.xml file in the /res/resource directory that defines the accessible location, through the use of the resource child element. In the file, the <paths> element must contain at least one of the following child elements that reference the storage area: files-path, cache-path, external-path, external-files-path, external-cache-path, or external-media-path. All of these child elements use the same attributes: name and path. The name acts as an alias to the value of the path which references the actual subdirectory name to grant access to:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
   <files-path name="my_images" path="images/"/>
   ...
</paths>

Content URIs are generated by passing a File to getUriForFile() and then returning the URI to another application in an Intent:

File imagePath = new File(Context.getFilesDir(), "my_images"); 
File newFile = new File(imagePath, "default_image.jpg"); 
Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);

This will return a content URI of:

content://com.mydomain.fileprovider/my_images/default_image.jpg

Read and write permissions can then be granted to specific packages or by including directives in an Intent using either FLAG_GRANT_READ_URI_PERMISSION, FLAG_GRANT_WRITE_URI_PERMISSION, or both.

Although this functionality is intended to provide a secure method of exchanging files, oversights can lead to vulnerabilities caused by excessive permissions. With permissions granted, internal files can be exposed if the configuration includes path=".". In extreme cases, if path="/" is used, all directories and files on the device will be exposed.

In May of 2020, security researcher KANYTU reported a vulnerability in the Brave Android application that allowed the download and retrieval of the cookies database due to an insecure content URI.

Cryptographic Failures

The implementation of weak or outdated cryptographic algorithms can be exploited by malicious attackers to reveal the underlying data. While using reliably secure algorithms applies to data in all states (at rest, in transit, and in use), this protection outside of transmission is especially important for mobile devices as they can be easily lost or stolen. This emphasis is due to the fact that if an attacker has physical access to a device, encryption can be "cracked" offline – with their only limitation being the processing power of the machine used.

Encryption keys can be unintentionally exposed in client-side code. If an attacker obtains a symmetric key, they can directly encrypt data. If they are able to obtain the private key used in asymmetric encryption, they can decrypt any data with the corresponding public key, which is available to anyone.

Cryptography also includes what is known as "hashing" – the process converting data into irreversible, fixed-length strings called "hash digests". These digests uniquely identify the original data while making it unrecoverable. However, certain hash functions that were once thought to be cryptographically secure have been found to be vulnerable to "collisions". A collision occurs when two different input values produce the same hash digest.

The Message Digest 5 (MD5) algorithm, once widely trusted, uses 128-bit hashes. While this theoretically allows for over 340 undecillion unique combinations, its illusion of security was broken by a probability theory known as the Birthday Problem. The theory demonstrated a 50% chance of a collision in MD5 after 264 operations. It was also discovered that MD5 was vulnerable to preimage attacks, which allows attackers to reverse-engineer hash digests into their original value, even though the process is supposed to be irreversible.

If an application uses a vulnerable algorithm such as MD5 to obfuscate sensitive data, attackers can attempt to match values against precomputed lists with known cleartext equivalents, known as "rainbow tables". Websites such as CrackStation provide billions of entries in their rainbow tables that can be used for comparison.

SQL Injection

In an SQL injection (SQLi) attack, a malicious user input is concatenated with a database query statement in order to extract, update, add or delete additional information. These attacks can expose sensitive data, sabotage database contents, and even result in backend infrastructure being compromised.

In the absence of sufficient protections, SQL statements using valid syntax can be added to the original query. If the normal query generated when a user submits their account credentials in a log in form is:

SELECT * FROM users WHERE username = 'user_input' AND password = 'pass_input';

An attacker could enter the following payload as the value into the username field:

admin' or 1=1--

The submitted password could be any value as the resulting query becomes:

SELECT * FROM users WHERE username = 'admin' or 1=1--' AND password = 'anything';

The single quote character after admin closes the username string and -- comments out the rest of the query. Since '1'='1' always evaluates to true, then the or operator will cause the entire WHERE clause to evaluate to true, regardless of the actual username or password values. This effectively bypasses authentication, typically using the first account returned by the database which is often the administrative account.

If an Android application is not validating and sanitizing user supplied input, SQLi attacks are possible. It is recommended that user input is bound by placeholder parameters in prepared statements so submitted values are not interpreted as statement syntax. For examples on secure implementations of these measures, view the official documentation.

Best Practices

Comprehensive Assessment Approach

Having the right approach is crucial to a successful mobile application security assessment. Android applications are complex systems that require comprehensive testing across all components and functionalities. A thorough assessment combines static analysis, dynamic analysis, and backend service testing to evaluate the application's complete security posture. This approach ensures everything from client-side weaknesses to server-side flaws are discovered.

A complete Android application security assessment examines:

  • Native code components.
  • Application code and its implementation.
  • Third-party library implementation.
  • API usage.
  • User input areas.
  • Coss application communication.
  • Data storage mechanisms.
  • Network communication methods.
  • Authentication and authorization.
  • The use of platform security controls.
  • Runtime behavior.

Skills-Based Tester Matching

Traditional consultancies often rely on in-house pentesters with general skills. However, Android security testing requires specialized knowledge of the Android platform architecture and the unique risks associated with mobile applications.

With HackerOne, customers gain access to a diverse pool of elite, vetted security researchers who bring a wide range of skills, certifications, and experience. The HackerOne platform tracks each researcher's skill set based on their track record and matches the most suitable researchers for each engagement. The community-driven PTaaS approach delivers comprehensive coverage, versatility, and the highest-quality results tailored to the security needs of your Android mobile applications.

Case Study: Suspicious SHEIN Clipboard Behavior

Microsoft Advisory published in March of 2023, discloses a security issue that was discovered in an old version of the SHEIN Android application. At the time of disclosure, the SHEIN application had over 100 million downloads.

The application for the Chinese fashion company was found to periodically read the contents of the device clipboard searching for the $ character and :// sequence.

If these characters were present, the SHEIN application would use the android.text.ClipboardManager API to transmit the clipboard contents to a remote server by generating a POST request to api-service.shein.com. This exfiltration posed a serious threat to any URLs copied to the clipboard containing sensitive query parameters. Any financial data, sourced from another Android application or from the web, that contained the U.S. currency symbol was also at risk.

In collaboration with Google's Android Security Team, this functionality was removed in May of 2022.

Why HackerOne Is The Best Option For Android Mobile Application Security Testing

By choosing HackerOne as your partner in security, your organization can fully benefit from the community-driven PTaaS model. This model leverages a combination of HackerOne security experts, who are skill-matched and vetted, working together with your teams to deliver the best overall ROI in risk reduction.

The HackerOne Platform simplifies the process of requesting a new assessment, onboarding new assets, and enlisting expert researchers in just a few days. Its purpose-built UI for reporting vulnerabilities and Zero Trust Access for fast, secure application access makes evaluations more seamless and efficient.

With the right blend of people and technology, HackerOne is the ideal choice for your Android application security assessments.