Knowledge Base

List of JNI methods

Risk: info

Description

Java Native Interface (JNI) allows Java code to interact with native applications and libraries written in Rust, C, C++ and assembly.

Improper use of the Java Native Interface renders the application vulnerable to security flaws present in other programming languages, like memory corruption.

Recommendation

Native code must adhere to Secure Coding best practices to protect against vulnerabilities in unmanaged code like memory corruption.

APK attack surface

Risk: info

Description

List of componenets potentially accepting user input:

  • service: Service.
  • activity: Activity.
  • reciver: Broadcast Receiver
  • provider: Content Provider

Recommendation

This entry is informative, no recommendations applicable.

Backup mode disabled

Risk: secure

Description

Android performs by default a full backup of applications including the private files stored on /data partition. The Backup Manager service uploads those data to the user's Google Drive account.

Recommendation

The implementation is secure, no recommendation apply.

Backup mode enabled

Risk: potentially

Description

Android performs by default a full backup of applications including the private files stored on /data partition. The Backup Manager service uploads those data to the user's Google Drive account.

Recommendation

if the application contains sensitive data that you don't want to be restored, you can disable backup mode by setting the attribute android:allowBackup to false in the application tag.

Application certificate information

Risk: info

Description

List of all information related to the application signing certificate.

Recommendation

This entry is informative, no recommendations applicable.

Application signed with an expired certificate

Risk: medium

Description

The Application signing certificate has expired.

Recommendation

You need to re-sign your app with a valid certificate, otherwise, users will not be able to install it from an App Catalog

Application checks rooted device

Risk: info

Description

Presence of strings and methods indicating potential check for rooted device

Recommendation

This entry is informative, no recommendations applicable.

Classes list

Risk: info

Description

List of all Java classes declared in the application.

Recommendation

This entry is informative, no recommendations applicable.

Hardcoded strings list

Risk: info

Description

List of all hardcoded strings used in the application.

Recommendation

This entry is informative, no recommendations applicable.

Debug mode disabled

Risk: secure

Description

The application is compiled with debug mode disabled. Debug mode allows attackers to access the application filesystem and attach a debugger to access sensitive data or perform malicious actions.

For instance attach a Java (JDWP) debugger:

$adb forward tcp:7777 jdwp:$(adb shell ps | grep "package-id")
$jdb -attach localhost:7777

To access the applicatin filesystem:

$adb shell
$run-as package-id
$...insert malicious action...

Attacker can debug the application without access to source code and leverage it to perform malicious actions on behalf ot the user, modify the application behavior or access sensitive data like credentials and session cookies.

Recommendation

The implementation is secure, no recommendation apply.

Debug mode enabled

Risk: hardening

Description

The application is compiled with debug mode enabled. This allows attackers to access the application filesystem and attach a debugger to access sensitive data or perform malicious actions.

For instance attach a Java (JDWP) debugger:

$adb forward tcp:7777 jdwp:$(adb shell ps | grep "package-id")
$jdb -attach localhost:7777

To access the applicatin filesystem:

$adb shell
$run-as package-id
$...insert malicious action...

Attacker can debug the application without access to source code and leverage it to perform malicious actions on behalf ot the user, modify the application behavior or access sensitive data like credentials and session cookies.

Recommendation

Disable debug mode by setting the attribute android:debuggeable to false in the application tag.

<application android:icon="@drawable/icon" android:debuggable="false">

Recorded calls to dynamic code loading API

Risk: info

Description

List of all dynamic code loading API calls in the application. Loading code from untrusted sources could allow the execution of malicious code in the context of the current application.

Recommendation

This entry is informative, no recommendations applicable.

Recorded calls to command execution API

Risk: info

Description

List of all command execution API calls

Recommendation

This entry is informative, no recommendations applicable.

Recorded calls to Crypto API

Risk: info

Description

List of all calls to cryptographic methods.

Recommendation

Do not use insecure or weak cryptographic algorithms. For example, the Data Encryption Standard (DES) encryption algorithm is considered highly insecure

Do not use Object.equals() to compare cryptographic keys

Cryptographic keys should never be serialized

Recorded calls to FileSystem API

Risk: info

Description

List of all FileSystem methods used in the application.

Recommendation

This entry is informative, no recommendations applicable.

Recorded calls to Hash API

Risk: info

Description

List of all Hash methods used in the application.

Recommendation

This entry is informative, no recommendations applicable.

Recorded calls to HTTP API

Risk: info

Description

List of all HTTP methods used in the application.

Recommendation

This entry is informative, no recommendations applicable.

Recorded calls to Intent API

Risk: info

Description

List of all Intent methods used in the application.

Recommendation

This entry is informative, no recommendations applicable.

Recorded calls to Inter-Process-Communication (IPC) API

Risk: info

Description

List of all calls to Android IPC API.

Recommendation

This entry is informative, no recommendations applicable.

Recorded calls to logging API

Risk: info

Description

List of all command execution API calls

Recommendation

This entry is informative, no recommendations applicable.

Recorded calls to Process API

Risk: info

Description

List of all Process methods used in the application.

Recommendation

This entry is informative, no recommendations applicable.

Exported activites, services and broadcast receivers list

Risk: important

Description

List of all exported components in the application. Exported component are accessible to external applications and present an entry point to the application.

Recommendation

This entry is informative, no recommendations applicable.

Exported activites, services and broadcast receivers list

Risk: important

Description

List of all exported components in the application. Exported component are accessible to external applications and present an entry point to the application.

Recommendation

This entry is informative, no recommendations applicable.

Recorded calls to Serialization API

Risk: info

Description

List of all Serialization methods used in the application.

Recommendation

This entry is informative, no recommendations applicable.

Recorded calls to Shared Preferences API

Risk: info

Description

List of all Shared Preferences methods used in the application.

Recommendation

This entry is informative, no recommendations applicable.

Recorded calls to SQLite query API

Risk: info

Description

Improper SQL query construction could lead to SQL injection. An SQL injection attack consists of injecting of an SQL query via the input data from the client to the application.

Recommendation

This entry is informative, no recommendations applicable.

Recorded calls to TLS Pinning API

Risk: info

Description

List of all TLS Pinning methods used in the application.

Recommendation

This entry is informative, no recommendations applicable.

Recorded calls to TLS API

Risk: info

Description

List of all TLS methods used in the application.

Recommendation

This entry is informative, no recommendations applicable.

Recorded calls to dangerous WebView settings API

Risk: info

Description

List of all WebView methods used in the application.

Recommendation

If your application accesses sensitive data with a WebView, you may want to use the clearCache() method to delete any files stored locally.

Any URI received via an intent from outside a trust-boundary should be validated before rendering it with WebView

ELF binaries do not enforce secure binary properties

Risk: hardening

Description

RELRO: RELRO is a memory protection technique to harden against memory corruption exploitation techniques. RELRO prevents GOT overwrite attacks.

ASLR: ASLR is a memory protection technique to harden against memory corruption exploitation technique. ASLR randomizes the address space of binary to prevent controlled address jumps.

No eXecute: Mark memory region as non-executable to harden against memory corruption exploitation technique.

Stack canary: Add a canary to memory that gets overwritten in the case of a memory corruption. The canary is checked at runtime to prevent the exploitation of the memory corruption vulnerability.

Recommendation

If Stack canary is missing, Compilers such as GCC enable this feature if requested through compiler options:

  • -fstack-protector: Check for stack smashing in functions with vulnerable objects. This includes functions with buffers larger than 8 bytes or calls to alloca.
  • -fstack-protector-strong: Like -fstack-protector, but also includes functions with local arrays or references to local frame addresses.
  • -fstack-protector-all: Check for stack smashing in every function.

Exported activites, services and broadcast receivers list

Risk: important

Description

List of all exported components in the application. Exported component are accessible to external applications and present an entry point to the application.

Recommendation

This entry is informative, no recommendations applicable.

Facebook Sdk debug mode enabled

Risk: medium

Description

The application is compiled with Facebook Sdk debug mode enabled. The debug logs contain detailed requests and JSON responses, which might expose sensitive information.

Recommendation

Disable debug logs before deploying your app to the public.

FacebookSdk.setIsDebugEnabled(false);

Method signature:

public static void setIsDebugEnabled(boolean enabled)

Documentation:

Used to enable or disable logging, and other debug features. Defaults to BuildConfig.DEBUG.

Parameters: enabled - Debug features (like logging) are enabled if true, disabled if false.

Implementation of a FileObserver

Risk: info

Description

Monitors files (using inotify) to fire an event after files are accessed or changed by any process on the device (including this one). FileObserver is an abstract class; subclasses must implement the event handler onEvent(int, java.lang.String).

Each FileObserver instance can monitor multiple files or directories. If a directory is monitored, events will be triggered for all files and subdirectories inside the monitored directory.

An event mask is used to specify which changes or actions to report. Event type constants are used to describe the possible changes in the event mask as well as what actually happened in event callbacks.

Recommendation

This entry is informative, no recommendations applicable.

APK files list

Risk: info

Description

APK files are an archive file in ZIP format based on the JAR file format. The APK file usually contains the following directories:

  • META-INF directory:
    • MANIFEST.MF: the manifest file
    • CERT.RSA or CERT.DSA: the certificate of the application
    • CERT.SF: list of ressources and SHA-1 digest
  • lib: directory containing compiled code. The directory is split into more directories for each processor architecture (x86, x86_64, armeabi, arm64-v8a ...)
  • res: directory containing not compiled resources
  • assets: directory containing application assets
  • AndroidManifest.xml: binary XML file describing the application (permissions, version, libraries ...)
  • classes.dex: file in the DEX file format containing compiled Java code
  • resources.arsc: file containing precompiled resources

Recommendation

This entry is informative, no recommendations applicable.

Hardcoded SQL queries list

Risk: info

Description

List of all hardcoded SQL queries constant strings in the application.

Recommendation

This entry is informative, no recommendations applicable.

Hardcoded urls list

Risk: info

Description

List of all hardcoded URLs constant strings in the application.

Recommendation

This entry is informative, no recommendations applicable.

Attribute hasFragileUserData not set

Risk: low

Description

The android:hasFragileUserData attribute specifies when the user uninstalls an app, whether or not to show the user a prompt to keep the app's data. The default value is "false".

This value should be set explicitly in the application to indicate whether the application is handling important user data or not.

Recommendation

Explicitly set the attribute android:hasFragileUserData to the appropriate value.

<application android:icon="@drawable/icon" android:hasFragileUserData="true">

Abuse of mobile network connection

Risk: medium

Description

The download manager is a system service that handles long-running HTTP downloads. The application should not force using only the mobile network connection

Recommendation

The application should allow the users to use either the Wi-Fi or a mobile network connection. A common strategy for apps is to only fetch large data if a Wi-Fi network is available.

Command Injection

Risk: high

Description

Command injection is an attack in which the goal is execution of arbitrary commands on the Android operating system via a vulnerable application. Command injection attacks are possible when an application passes unsafe user supplied data (forms, cookies, HTTP headers etc.) to the system shell. In this attack, the attacker-supplied operating system commands are usually executed with the privileges of the vulnerable application. Command injection attacks are possible largely due to insufficient input validation.

Recommendation

The application should allow the users to use either the Wi-Fi or a mobile network connection. A common strategy for apps is to only fetch large data if a Wi-Fi network is available.

Insecure Network Configuration Settings

Risk: hardening

Description

Android Network Security Configuration enables a declarative setting of the application network security.

The features enable configuring:

  • Custom Certificate Authority with support for debug only settings
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <debug-overrides>
        <trust-anchors>
            <certificates src="@raw/debug_cas"/>
        </trust-anchors>
    </debug-overrides>
</network-security-config>
  • Declarative opt-out for cleartext traffic
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="false">
        <domain includeSubdomains="true">secure.example.com</domain>
    </domain-config>
</network-security-config>
  • Declartive setting of certificate pinning keys
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config>
        <domain includeSubdomains="true">example.com</domain>
        <pin-set expiration="2018-01-01">
            <pin digest="SHA-256">7HIpactkIAq2Y49orFOOQKurWxmmSFZhBCoQYcRhJ3Y=</pin>
            <!-- backup pin -->
            <pin digest="SHA-256">fwza0LRMXouZHRC8Ei+4PyuldPDcf3UKgO/04cDM1oE=</pin>
        </pin-set>
    </domain-config>
</network-security-config>

Recommendation

It is strongly recommended to add a Network Security Configuration settings enabling encrypted traffic only.

Use of a custom Certificate Authority with certificate pinnging increases the security of you application and is recommended for security sensitive application.

Secure Network Configuration Settings

Risk: secure

Description

Android Network Security Configuration enables a declarative setting of the application network security.

The features enable configuring:

  • Custom Certificate Authority with support for debug only settings
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <debug-overrides>
        <trust-anchors>
            <certificates src="@raw/debug_cas"/>
        </trust-anchors>
    </debug-overrides>
</network-security-config>
  • Declarative opt-out for cleartext traffic
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="false">
        <domain includeSubdomains="true">secure.example.com</domain>
    </domain-config>
</network-security-config>
  • Declartive setting of certificate pinning keys
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config>
        <domain includeSubdomains="true">example.com</domain>
        <pin-set expiration="2018-01-01">
            <pin digest="SHA-256">7HIpactkIAq2Y49orFOOQKurWxmmSFZhBCoQYcRhJ3Y=</pin>
            <!-- backup pin -->
            <pin digest="SHA-256">fwza0LRMXouZHRC8Ei+4PyuldPDcf3UKgO/04cDM1oE=</pin>
        </pin-set>
    </domain-config>
</network-security-config>

Recommendation

The implementation is secure, no recommendation apply.

Android Class Load Hijacking

Risk: medium

Description

The applications loads jar/apk stored in an insecure location.

This load process can be hijacked, allowing access to private data and unexpected arbitrary code execution by malicious applications

Recommendation

If you use DexClassLoader to load and execute additional DEX code:

  • Do NOT use a world-writable directory (such as the SD card) for the dexPath
  • Do NOT use a world-writable directory (such as the SD card) for the ODEX (optimized DEX which is the second paramter of the DexClassLoader constructor)

If you use PathClassLoader to load and execute additional jar/resources:

  • Do NOT use a world-writable directory (such as the SD card) for the path
  • Do NOT use a world-writable directory (such as the SD card) for the libpath. By default, the external storage is mounted with the noexec flag to prevent the execution of any native binaries on the mounted file system.

Unused permissions (overprivileged)

Risk: low

Description

The application requests permissions, but never uses the resource granted.

Recommendation

Remove unused permissions

Declared permissions list

Risk: info

Description

To protect the system's integrity and the user's privacy, Android runs each app in a limited access sandbox.

If the app wants to use resources or information outside of its sandbox, the app has to explicitly request permission.

Depending on the type of permission the app requests, the system may grant the permission automatically, or the system may ask the user to grant the permission.

Recommendation

This entry is informative, no recommendations applicable.

Android Manifest

Risk: info

Description

The manifest file presents essential information about your app to the Android system, information the system must have before it can run any of the app's code. Among other things, the manifest does the following:

  • It names the Java package for the application. The package name serves as a unique identifier for the application.
  • It describes the components of the application - the activities, services, broadcast receivers, and content providers that the application is composed of.It names the classes that implement each of the components and publishes their capabilities (for example, which Intent messages they can handle).These declarations let the Android system know what the components are and under what conditions they can be launched.
  • It determines which processes will host application components.
  • It declares which permissions the application must have in order to access protected parts of the API and interact with other applications.
  • It also declares the permissions that others are required to have in order to interact with the application's components.
  • It lists the Instrumentation classes that provide profiling and other information as the application is running. These declarations are present in the manifest only while the application is being developed and tested; they're removed before the application is published.
  • It declares the minimum level of the Android API that the application requires.
  • It lists the libraries that the application must be linked against.

Recommendation

This entry is informative, no recommendations applicable.

Application code not obfuscated

Risk: hardening

Description

Obfuscation refers to methods to obscure code and make it hard to understand. Compiled Java classes can be decompiled if there is no obfuscation during compilation step.

Adversaries can steal code and repurpose it and sell it in a new application or create a malicious fake application based on the initial one.

Code obfuscation only slows the attacker from reverse engineering but does not make it impossible.

Recommendation

Design the application to add the following protections and slow reverse engineering of the application:

  • Obfuscate Java source code with tools like Proguard or Dexguard
    buildTypes {
            release {
                minifyEnabled true
                proguardFiles getDefaultProguardFile('proguard-android.txt'),
                'proguard-rules.pro'
            }
        }
  • Verification application signing certificate during runtime by checking context.getPackageManager().signature
  • Check application installer to ensure it matches the Android Market by calling context.getPackageManager().getInstallerPackageName
  • Check running environment at runtime
    private static String getSystemProperty(String name) throws Exception {
        Class systemPropertyClazz = Class.forName("android.os.SystemProperties");
        return (String) systemPropertyClazz.getMethod("get", new Class[] { String.class }).invoke(systemPropertyClazz, new Object[] { name });
    }
    
    public static boolean checkEmulator() {
    
        try {
            boolean goldfish = getSystemProperty("ro.hardware").contains("goldfish");
            boolean qemu = getSystemProperty("ro.kernel.qemu").length() > 0;
            boolean sdk = getSystemProperty("ro.product.model").equals("sdk");
    
            if (qemu || goldfish || sdk) {
                return true;
            }
    
        } catch (Exception e) {
        }
    
        return false;
      }
  • Check debug flag at runtime
    context.getApplicationInfo().applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE;

Obfuscated methods

Risk: info

Description

Obfuscation refers to methods to obscure code and make it hard to understand. Compiled Java classes can be decompiled if there is no obfuscation during compilation step.

Adversaries can steal code and repurpose it and sell it in a new application or create a malicious fake application based on the initial one.

Code obfuscation only slows the attacker from reverse engineering but does not make it impossible.

Recommendation

Design the application to add the following protections and slow reverse engineering of the application:

  • Obfuscate Java source code with tools like Proguard or Dexguard
buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } }
  • Verification application signing certificate during runtime by checking context.getPackageManager().signature
  • Check application installer to ensure it matches the Android Market by calling context.getPackageManager().getInstallerPackageName
  • Check running environment at runtime
    private static String getSystemProperty(String name) throws Exception {
        Class systemPropertyClazz = Class.forName("android.os.SystemProperties");
        return (String) systemPropertyClazz.getMethod("get", new Class[] { String.class }).invoke(systemPropertyClazz, new Object[] { name });
    }
    
    public static boolean checkEmulator() {
    
        try {
            boolean goldfish = getSystemProperty("ro.hardware").contains("goldfish");
            boolean qemu = getSystemProperty("ro.kernel.qemu").length() > 0;
            boolean sdk = getSystemProperty("ro.product.model").equals("sdk");
    
            if (qemu || goldfish || sdk) {
                return true;
            }
    
        } catch (Exception e) {
        }
    
        return false;
      }
  • Check debug flag at runtime
    context.getApplicationInfo().applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE;

Attribute requestLegacyExternalStorage set

Risk: low

Description

The android:requestLegacyExternalStorage attribute grants access to directories and different types of media files stored in external storage.

This attribute works only for Android 10 (API level 29), on Android 11 and later, the system ignores the requestLegacyExternalStorage flag.

Recommendation

Avoid setting the attribute android:requestLegacyExternalStorage and use only scoped storage to guarantee a better protection to app and user data on external storage.

<application android:icon="@drawable/icon" android:requestLegacyExternalStorage="true">

Services declared without permissions

Risk: potentially

Description

service is an application component that can take care of actions to be done in the background, without user interaction. service can also be used to expose functionalities to other applications. This corresponds to calls to Context.bindService() to establish a connection to the service and interact with it.

Unprotected services can be invoked by other applications and potentially access sensitive information or perform privileged actions

Recommendation

service can expose several methods to external componenets. It is possible to define arbitrary permissions for each method using the method checkPermission.

It is also possible to seperate services and restrict access by enforcing permissions in the manifest's <service> tag.

<permission android:name="co.ostorlab.custom_permission" android:label="custom_permission" android:protectionLevel="dangerous"></permission>

<service android:name="co.ostorlab.custom_service" android:permission="co.ostorlab.custom_permission">
    <intent-filter>
        <action android:name="co.ostorlab.ACTION" />
    </intent-filter>
</service>

The service can enforce permissions on individual IPC calls by calling the method checkCallingPermissionbefore executing the implementation of that call.

Task Hijacking

Risk: medium

Description

An Android task is a collection of activities that users interact with when performing a certain job. Activities from different apps can reside in the same task which might be used to relocate a malicious activity to your application's task by manipulating the following parameters:

  • Task Affinity controlled by attribute taskAffinity
  • Task Reparenting controlled by attribute allowTaskReparenting

Task Affinity is an activity attribute defined in the <activity> tag in the AndroidManifest.xml file. Task Affinity specifies which task that the activity desires to join. By default, all activities in an app have the same affinity, which is the app package name.

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="co.secureApp.app" >
<application>
    <activity android:name=".ActivityA"></activity>
    <activity android:name=".ActivityB" android:taskAffinity="co.ostorlab.Myapp:taskB"></activity>
</application>
</manifest>

allowTaskReparenting when set to true for an activity A, and when a new task with the same affinity is brought to the front, the system moves the relocatable activity A from its original hosting task to the new foreground task stack.

Task Hijacking attacks come in different flavors:

  • Task Affinity Control: application has a package name com.mySecureApp.app and activity A1. A malicious application has two activities M1 and M2 where M2.taskAffinity = com.mySecureApp.app and M2.allowTaskReparenting = true. If the malicious app is open on M2, once you start your application, M2 is relocated to the front and the user will interact with the malicious application.

  • Single Task Mode: the application has set launch mode to singleTask. A malicious application with M2.taskAffinity = com.mySecureApp.app can hijack the target application task stack.

  • Task Reparenting: application has set taskReparenting to true. A malicious application can move the target application task to the malicious application stack.

Task hijacking can be used to perform phishing, denial of use attack, and has been exploited in the past by banking malware trojans. New flavors of the attacks (StandHogg 2.0) are extremely hard to detect, as they are code-based attacks.

Recommendation

Different forms of Task Hijacking vulnerabilities require different fixes:

  • Set the task affinity of the application activity to ""(empty string) in the <activity> tag of the AndroidManifest.xml to force the activities to use a randomly generated task affinity.

  • Do not specify launch mode set to singleTask or add support for a monitoring service to detect the presence of malicious foreground tasks.

  • Do not set the flag FLAG_ACTIVITY_NEW_TASK in activity launch intents, or use with the FLAG_ACTIVITY_CLEAR_TASK:

Intent i = new Intent(this, AnActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
  • Do not specify allowReparenting with taskAffinity or add support a monitoring service to detect the presence of malicious foreground tasks.

  • Prefer the use of Explicit intent, which specify which application will satisfy the intent, by supplying the target application package name or a fully-qualified component class name. Implicit intent only specifies the general action.

Attribute usesCleartextTraffic set

Risk: low

Description

The android:usesCleartextTraffic attribute indicates whether the app intends to use cleartext network traffic, such as cleartext HTTP.

The default value for apps that target API level 27 or lower is "true". Apps that target API level 28 or higher default to "false".

Recommendation

Explicitly set the attribute android:usesCleartextTraffic value to true and define an Android Network Security Config.

The default value for apps that target API level 27 or lower is "true". Apps that target API level 28 or higher default to "false".

<application android:icon="@drawable/icon" android:usesCleartextTraffic="false">

Implementation of a WebViewClient

Risk: info

Description

List of Webview client implementations.

Recommendation

This entry is informative, no recommendations applicable.

Enforcer proper authentication

Risk: secure

Description

To keep the data private and secure, it’s important to authenticate users properly so that only those with the requisite credentials can access the accounts

HIPAA Access Control Requirements: In the case of access control, this is a standard element of data security and means that access to electronic protected health information will be restricted through a login and authentication method. Thus, a login mechanism is used to secure and control access to information, and only persons who have been granted the required access rights can log into information systems containing the protected data.

Recommendation

  • Implement electronic mechanisms to verify the identity of any person or entity requesting access to ePHI, prior to granting access to the ePHI.
  • Use an appropriate authentication method to take reasonable steps to ensure that only properly authenticated workforce members access ePHI.

Public AWS S3 bucket with file listing enabled

Risk: medium

Description

AWS provide S3 web service storage to easily store and retrieve data. Access to S3 bucket can enable access control and implement few security settings. S3 bucket has been behind several high profile data compromises and are a common misconfiguration.

A publicly accessible AWS S3 bucket was detected with potentially sensitive information. The information was detected as the bucket enables file listing and attacker can navigate all content in the bucket.

Recommendation

To ensure the proper configuration of the AWS S3 bucket:

  • Ensure public access is required, if not, restrict access to authorized users only.
  • If public access is required, ensure that file listing is required, if not, remove list object permission from all users access.
  • If public access is required, ensure that no sensitive information is stored in the bucket.

Binary disassembly

Risk: info

Description

Disassmbly of listed binaries.

Recommendation

This entry is informative, no recommendations applicable.

Broadcast receiver dynamic registration

Risk: potentially

Description

One or more of the application's broadcast receivers is dynamically registered in the code and not protected by signature permission in the AndroidManifest.xml file. All of the dynamically registered receivers are exported. Using a malware application, an attacker can broadcast arbitrary data to the exported receiver, which can lead to invocation of different components of the application or to code execution. For example, a lot of broadcast receivers are programmed to receive SMS messages or GCM messages. To work properly, these receivers should always be exported to receive data from other applications, such as the SMS app or the GCM framework. To secure receivers like this, you should always declare appropriate permissions during the call to the registerReceiver method. Broadcast receivers represent a likely exploitable component which is often used to start services, so it's highly recommended to check all of the external data is passed to them. To enable the most restrictive and therefore secure policy, you should minimize the number of exported intents by using the signature permissions.

Recommendation

Make sure you are only exporting broadcast receivers that really need the ability to be started by any third-party applications; or create a permission with android:protectionLevel="signature" in the AndroidManifest.xml file and use it for all broadcast receivers that are to be started only by your applications, setting exported="false" for all broadcast receivers that should not be started by third-party applications at all.

Cordova Cross-Site Scripting (XSS)

Risk: medium

Description

Mobile Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted content. XSS attacks occur when an attacker can inject malicious code through:

  • Untrusted Inter-Process Communication (IPC) input
  • Man-in-the-Middle attack
  • Untrusted content stored on the webserver application
  • Untrusted local file input

Example script to test presence of XSS

<script>alert("Ostorlab XSS!")</script>
<img src="http://ostorlab.co/js_xss2" onerror=alert(document.cookie)>

XSS vulnerabilities for Cordova applications are critical as they allow access to native functionality on the target phone and could lead to unauthorized access to contacts, messages, camera, audio and location.

Recommendation

The application must validate all provided input and use secure HTML formating API. The recommended approach is defining a list of acceptable characters and allow only those characters. Acceptable characters would be upper case letters, lower case letters, and numbers (i.e. a-z, A-Z, and 0-9).

Frameworks offer methods to validate input and prevent XSS vulnerabilities and modern frameworks (Angular JS 2, React JS) automatically escapes user input:

To escape input using Sencha Ext JS, the following methods could be used:

  • Ext.util.Format.stripTags
  • Ext.util.Format.stripScripts
  • Ext.util.Format.htmlEncode/Decode

Insecure Cross-Origin Resource Sharing (CORS) policy

Risk: medium

Description

Cross-Origin Resource Sharing (CORS) uses HTTP headers to let a web client gain access resources from a server on a different domain. Browsers restrict cross-origin HTTP requests initiated from within scripts for security purposes.

If another domain is allowed by the policy, then that domain can attack users of the application. If a user is logged in to the application, and visits a domain allowed by the policy, then any malicious content running on that domain can retrieve content from the application, and carry out actions within the security context of the logged in user.

Recommendation

CORS is an appropriate choice for cross domain sharing, access must be however restricted to authorized domains only, particularly if Access-Control-Allow-Credentials is enabled.

All unauthorized domains must be restricted in addition to domains that allows running untrusted code like jsfiddle.com.

Cryptographic Vulnerability: Insecure Algorithm

Risk: medium

Description

The mode of operation used to encrypt the data is vulnerable

Recommendation

We recommend AES for general-purpose use. If you're willing to go against the grain and are paranoid, you can use Serpent, which isn't quite as fast as AES but is believed to have a much higher security margin.

If you really feel that you need the fastest possible secure solution, consider the SNOW 2.0 stream cipher, which currently looks very good. It appears to have a much better security margin than the popular favorite, RC4, and is even faster. However, it is fairly new. If you're highly risk-adverse, we recommend AES or Serpent. Although popular, RC4 would never be the best available choice.

Cryptographic Vulnerability: Hardcoded Key

Risk: medium

Description

The main purpose of encrypting and decrypting data is to guarantee the confidentiality of the information and prevent the third parties from viewing private data. Pre-shared keys may be used when working with large data sets or to protect the confidentiality of an application’s or a user’s assets. However, the usage of a hardcoded key increases the possibility of an attacker to decrypt and recover the data in case of a stolen device

Recommendation

  • Keys must be unique to the device and may use input from the user to compute the key.
  • When generating a key from password, use salt.
  • When generating a key from password, specify an appropriate hash iteration count.
  • Use a key of length sufficient to guarantee this strength of encryption.

Cryptographic Vulnerability: Insecure mode

Risk: medium

Description

The algorithm used to encrypt the data is vulnerable. If AES is used without specifying the mode, the default mode is the insecure ECB mode.

Recommendation

We recommend AES for general-purpose use. If you're willing to go against the grain and are paranoid, you can use Serpent, which isn't quite as fast as AES but is believed to have a much higher security margin.

If you really feel that you need the fastest possible secure solution, consider the SNOW 2.0 stream cipher, which currently looks very good. It appears to have a much better security margin than the popular favorite, RC4, and is even faster. However, it is fairly new. If you're highly risk-adverse, we recommend AES or Serpent. Although popular, RC4 would never be the best available choice.

Use non-random initialization vector (IV)

Risk: medium

Description

Use of a non-random initialization vector makes the application vulnerable to dictionary attacks.

The following example demonstrates improper settings of hardcoded static IV:

public; class InsecureExample {
    @Override
    public void; run() throws; Exception;{
        byte;[]; IV = "0123456789abcdef".getBytes();
        String; clearText = "Jan van Eyck was here 1434";
        String; key = "ThisIs128bitSize";
        SecretKeySpec; skeySpec = new SecretKeySpec(key.getBytes(), "AES");
        Cipher; cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher;.init(Cipher.ENCRYPT_MODE;, skeySpec;, new; IvParameterSpec(IV))
        byte;[]; encryptedMessage = cipher.doFinal(clearText.getBytes());
        Log;.i(TAG, String.format("Message: %s";, Base64;.encodeToString(encryptedMessage, Base64.DEFAULT;)))
    }
}

Recommendation

  • Random numbers play a key role in ensuring unguessable Initialization Vectors generation
  • In Android applications, SecureRandom class generates random numbers secure enough for use in encryption
  • There exists multiple providers, which are the internal SecureRandom class implementations, and their role is to provide a hash function
  • A Default provider will be selected if not specified
  • Crypto Provider was deprecated in Android 7.0 (API level 24) and removed in Android 9.0 (API level 28) due to it's unsafe SHA1PRNG algorithm
  • It is recommended not to use Crypto Provider
  • If Crypto Provider is specified and SecureRandom is used, NoSuchProviderException will always occur in devices running Android 9.0 and higher, and NoSuchProviderException will occur even in devices running Android 7.0 and higher if targetSdkVersion>=24
  • For this reason, generally, the use of SecureRandom without specifying the provider is recommended
import java.security.SecureRandom;
[...]
    SecureRandom random = new SecureRandom();
    byte [] IV = new byte [128];
    random.nextBytes(IV);
    IvParameterSpec ivParams = new IvParameterSpec(iv)
[...]

Call to Android Security API

Risk: info

Description

List of all API calls to the Android Keystore and Keychain API.

Recommendation

This entry is informative, no recommendations applicable.

Call to Bluetooth and BLE API

Risk: info

Description

List of all calls to methods that interact with the Bluetooth and BLE.

Recommendation

This entry is informative, no recommendations applicable.

Call to Crypto API

Risk: info

Description

List of all calls to cryptographic methods.

Recommendation

Do not use insecure or weak cryptographic algorithms. For example, the Data Encryption Standard (DES) encryption algorithm is considered highly insecure

Do not use Object.equals() to compare cryptographic keys

Cryptographic keys should never be serialized

Call to delete file API

Risk: info

Description

Call to file.delete() do not securely erase the file unless overwritten. Due to way NAND manages block allocation, traditional file overwriting approaches are inefficient.

Recommendation

This entry is informative, no recommendations applicable.

Call to dynamic code loading API

Risk: info

Description

List of all dynamic code loading API calls in the application. Loading code from untrusted sources could allow the execution of malicious code in the context of the current application.

Recommendation

This entry is informative, no recommendations applicable.

Call to command execution API

Risk: info

Description

List of all command execution API calls.

Recommendation

This entry is informative, no recommendations applicable.

Call to External Storage API

Risk: info

Description

List of all external storage API calls. Insecure storage of sensitive information by setting insecure permissions or storing data without encryption might expose this information to an attacker.

Recommendation

We can distinguish four types of files based on the access permission and storage location:

  • Private files:

    • A very safe way to use files
    • Must be created in the application's directory
    • Can store sensitive information and must use encryption when storing PII
    • Can be used for files that can be read/written only in the same application
    • The access privilege must be set to private mode in order to restrict access from other applications
    • Content Provider, Service or other inter-application linkage system are recommended to exchange information between applications
        public void onCreateFileClick(View view) {
            FileOutputStream fos = null;
            try {
                fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
    
                fos.write(new String("Not sensitive information (File Activity)\n").getBytes());
            } catch (FileNotFoundException e) {
                mFileView.setText(R.string.file_view);
            } catch (IOException e) {
                android.util.Log.e("PrivateFileActivity","failed to read file");
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        android.util.Log.e("PrivateFileActivity","failed to close file");
                    }
                }
            }
            finish();
        }
    
    
  • Public Read Only files:

    • Used to disclose content to unspecified number of applications
    • The access privilege must be set to read only
    • Must not contain sensitive information
    • Using the MODE_WORLD_READABLE variable to create a public file is deprecated in API Level 17 and later versions, and will trigger a security exception in API Level 24 and later versions
    • File-sharing methods using Content Provider are preferable
        public void onCreateFileClick(View view) {
            FileOutputStream fos = null;
            try {
    
                fos = openFileOutput(FILE_NAME, MODE_WORLD_READABLE);
    
                fos.write(new String("Not sensitive information (Public File Activity)\n").getBytes());
    
    
            } catch (FileNotFoundException e) {
                mFileView.setText(R.string.file_view);
            } catch (IOException e) {
                android.util.Log.e("PublicFileActivity","failed to read file");
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        android.util.Log.e("PublicFileActivity","failed to close file");
                    }
                }
            }
            finish();
        }
    
  • Public Read/Write files:

    • Used to permit Read/Write access to unspecified number of applications
    • Confidentiality and Integrity can’t be guaranteed
    • This type of file is not practical and should be avoided
  • External memory (Read Write Public) files:

    • It's supposed to be used when storing huge files, or when there is a need to bring out data to outside (e.g. backup, ...)
    • In addition to having the equal characteristics of "Read Write Public file" to unspecified large number of applications, it has also the same characteristics of "Read Write Public file" to applications which declare android.permission.WRITE.EXTERNAL.STORAGE permission
    • In applications that output backup, some contrivances to minimize risks in terms of application spec or designing like displaying a caution “Copy Backup files to the safety location like PC etc., a.s.a.p.”, are necessary
    • Using external memory devices should be avoided, unless necessary, and encryption must be used
    • When reading in files in external memory device, validate the input data read from external memory device
    • Applications should be designed supposing that files in external memory device can be deleted
        public void onCreateFileClick(View view) {
            FileOutputStream fos = null;
            try {
                File file = new File(getExternalFilesDir(TARGET_TYPE), FILE_NAME);
                fos = new FileOutputStream(file, false);
                fos.write(new String("Non-Sensitive Information(ExternalFileActivity)\n").getBytes());
            } catch (FileNotFoundException e) {
                mFileView.setText(R.string.file_view);
            } catch (IOException e) {
                android.util.Log.e("ExternalFileActivity","failed to read file");
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        android.util.Log.e("ExternalFileActivity","failed to close file");
                    }
                }
            }
            finish();
        }
    

Call to Inter-Process-Communication (IPC) API

Risk: info

Description

List of all calls to Android IPC API.

Recommendation

This entry is informative, no recommendations applicable.

Call to logging API

Risk: info

Description

This entry describes all the logging API calls used to write log entries. In Android, a logging mechanism called Logcat is introduced to view and filter series of circular buffers that contain logs from various applications and portions of the system. Log information in Logcat can be read out from other applications in the same device. Thus, the output of sensitive information to Logcat is considered that it has a vulnerability of the information leakage.

Recommendation

To output log messages to LogCat in a safe manner, pursue the following recommendations:

  • Sensitive information must not be included in operation log information. Construct the build system to Auto-delete codes which output development log information: For example, Log.d() and Log.v() should be deleted when building an application for release. ProGuard is a tool that can automatically delete them by specifying Log.d() and Log(v) as parameter of -assumenosideeffects option.
  • Use Log.d() or Log.v() when Outputting throwable Objects: When exceptions occur, stack trace is often output to LogCat by Log.e(), Log.w() or Log.i() methods. Thus, detail internal structure can be shown. For example, when SQLiteException is output as it is, type of SQL statement is revealed and it may give a clue for SQL injection attack.
  • Use only Methods of the android.util.Log class for Log Output.
  • Do not output log information using print() or println() method of System.out and System.err class since log information and development log information are output by the same method and it fosters the danger of dropped deletion by oversight. Moreover, using both android.util.Log and System.out/err will increase considered needs and, as a result the danger of occurring mistakes will increase.
  • Choose the right log level based on the information criticity. ( ERROR, WARN, INFO, DEBUG, VERBOSE )

Call to native methods

Risk: info

Description

List of all calls to methods using Java Native Interface to interact with native code (written in C/C++).

Recommendation

Data passed to NewStringUTF must be in Modified UTF-8 format

UTF-16 strings are not zero-terminated

Object references should never be compared using == or != in native code. When testing for object equality, the IsSameObject() function should be used instead of ==.

Call to Random API

Risk: info

Description

List of all calls to methods that return pseudo-random values.

Recommendation

Do not seed Random with the current time because that value is more predictable to an attacker than the default seed.

The java.util.Random class must not be used either for security-critical applications or for protecting sensitive data. Use a more secure random number generator, such as the java.security.SecureRandom class.

Call to Reflection API

Risk: info

Description

List of calls allowing the application to examine and modify the structure and behavior of an object at runtime.

Recommendation

This entry is informative, no recommendations applicable.

addJavaScriptInterface Remote Code Execution.

Risk: medium

Description

The addJavascriptInterface() method on API level JELLY_BEAN or below can be abused via reflection to execute commands remotely in the context of the running application

The addJavascriptInterface method exposes a supplied Java object from within a WebView to JavaScript. For applications compiled or linked against and API level less than 17; all public methods (including the inherited ones) can be accessed. Through the use of reflection it is also possible to invoke any other unregistered Java class.

Recommendation

This issue has been resolved in applications developed for Android 4.2 (API level 17) and above. Starting from Android 4.2 (API level 17) and above, only methods explicitly marked with the @JavascriptInterface annotation are available to JavaScript code within the WebView. The @JavascriptInterface annotation must be added to any method that is intended to be exposed via the native bridge (the method must also be public). An example is presented below:

    @JavascriptInterfacepublic void method() {dostuff();}

To resolve the issue, you need to build you application for API 17 or above and redistribute it. The users would need to upgrade their applications to use the new non-vulnerable application.

Call to Socket API

Risk: info

Description

List of all calls to Server Socket API.

Recommendation

This entry is informative, no recommendations applicable.

Call to SQLite query API

Risk: info

Description

Improper SQL query construction could lead to SQL injection. An SQL injection attack consists of injecting of an SQL query via the input data from the client to the application

Recommendation

This entry is informative, no recommendations applicable.

Call to TLS API

Risk: info

Description

List of all TLS methods used in the application.

Recommendation

This entry is informative, no recommendations applicable.

Call to dangerous WebView settings API

Risk: info

Description

List of all WebView methods used in the application.

Recommendation

If your application accesses sensitive data with a WebView, you may want to use the clearCache() method to delete any files stored locally.

Any URI received via an intent from outside a trust-boundary should be validated before rendering it with WebView

Call to XML parsing API

Risk: info

Description

Improper XML parsing could lead to several vulnerabilities which could to arbitrary file access (External XML Entities injection, XML injection) or denial of service (Billion laughs, quadratic blowup).

Recommendation

This entry is informative, no recommendations applicable.

Call to ZIP API

Risk: info

Description

List of all ZIP handling API.

Recommendation

This entry is informative, no recommendations applicable.

Use of Deprecated Component

Risk: low

Description

The application is using a deprecated component. New vulnerabilities will not be fixed and hackers might succeed in exploiting this weakness.

Recommendation

Switch to an up-to-date component/library which has security fixes for newly identified vulnerabilities.

Expansion APK enabled

Risk: info

Description

For applications with more than 100MB, using expansion files can be a good alternative to store additional APK assets.

The application can have two expansion files and each expansion file can be up to 2GB in size.

Unlike APK files, any files saved on the shared storage can be read by the user and other applications.

Recommendation

This entry is informative, no recommendations applicable.

External DNS interaction

Risk: potentially

Description

User-controlled parameters has resulted in triggering a server side DNS request. The ability to control server-side is not a vulnerability, however it is a serious indication of potential high risk vulnerability.

An attacked may leverage this functionality to send requests to remote systems for denial of service attacks or to remotely exploit potential vulnerabilities. It is also potentially possible to access internal systems protected with external network filtering.

Recommendation

Server-side triggered DNS requests might be an intended behavior, it is recommended to review the purpose of the service and evaluate the potential risks, like the participation in distributed denial of service (DDoS) attack, and interaction with remote services,

If this functionality is not an intended behavior, it is recommended to disable the service if possible or enforce whitelist-based filtering blocking all unauthorized domains.

Secure Firebase Database Permissions

Risk: secure

Description

Firebase Realtime Database Rules determine who has read and write access to your database, how your data is structured, and what indexes exist.

Insecure Database permissions is a common issue, which can lead to unauthorized access to your database. Firebase provides tools to enforce Authentication, Authorization and even Data Validation.

The following are common misconfiguration issues to avoid:

Read and write access to all users:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Any logged-in user has read and write access to your entire database:

{
  "rules": {
      ".read": "auth !== null",
      ".write": "auth !== null"
   }
}

Realtime Database Rules cascade, with rules at more shallow, parent paths overriding rules at deeper, child nodes. When you write a rule at a child node, remember that it can only grant additional privileges. You can't refine or revoke access to data at a deeper path in your database.

{
  "rules": {
     "foo": {
        // allows read to /foo/*
        ".read": "data.child('baz').val() === true",
        "bar": {
          /* ignored, since read was allowed already */
          ".read": false
        }
     }
  }
}

Recommendation

This entry is secure and has no applicable recommendation.

Use of an insecure Bluetooth connection

Risk: medium

Description

The app uses an insecure Bluetooth connection, with encryption switched off. An attacker who is in the physical vicinity of connected devices can use a Man in the Middle attack to intercept and/or modify transmitted data.

Recommendation

It is recommended that you use secure means of connection and information exchange with Bluetooth, which is possible with the createRfcommSocketToServiceRecord, listenUsingRfcommWithServiceRecord and similar methods.

Android Class Loading Hijacking

Risk: medium

Description

Android provides APIs that allow an application to dynamically load code to be executed. For example, an application may support plug-ins that are downloaded and then loaded at a later time. Unfortunately, if these plug-ins are stored in an insecure location, this process can be hijacked, allowing access to private data and unexpected arbitrary code execution by malicious applications

Two classes allow the loading of additional code:

    DexClassLoader (String dexPath, String dexOutputDir, String libPath, ClassLoader parent)
    PathClassLoader (String path, String libPath, ClassLoader parent)

Recommendation

When loading additional code in Android applications, a developer should ensure that both the loaded code and the generated alternative versions of the code are placed in a secured directory, typically within the application's private directory

Insecure Direct Object Reference

Risk: high

Description

A direct object reference occurs when an Application exposes a direct reference to an internal object without proper authorization.

This class of vulnerability results in an insecure direct, which may result in access to sensitive data and authorization bypass.

Recommendation

There multiple ways to prevent Indirect Object Reference vulnerabilities:

  1. Perform proper access control check.
  2. Use indirect reference using the user's session or account.

Insecure hostname validation check

Risk: high

Description

The application performs insecure hostname validation using easy to bypass methods like startsWith or endsWith. An attacker can easily bypass this check by registering a domain that matches the check pattern.

Composite checks with both startsWith and endsWith are equally insecure as the attack can still create domain with random middle input that matches the checked pattern.

Recommendation

Hostname validation must use a whitelist approach that checks against the full value of the hostname against or use secure regular expression that match against the full hostname.

Insecure password storage

Risk: medium

Description

Insecure storage of password could lead to account compromise. The vulnerability is the result of storing password using insecure methods that are susceptible to unauthorized access or compromise.

The following example shows insecure storage of password credentials in cookies:

response.addCookie(new Cookie("password", password));

Recommendation

Mobile applications must use secure API to store credentials. Android applications may AccountManager to store account credentials. It also highly recommended for mobile application to use OAuth-based authentication to avoid storing credentials and prevent attacks like password reuse.

To implement OAuth-based authentication, Cordova application may use the jquery-cordova-oauth2 library. Android application may use AccountManager API and iOS application may use OAuth2Client library.

Insecure Filesystem Access

Risk: medium

Description

The application handles files using insecure permissions (world-readable or world-writable) or is targeting external memory devices like SD card with weak permissions.

According to Android security designing idea, files are used only for making information persistence and temporarily saved (cache), and it should be private in principle. Exchanging information between applications should not be direct access to files, but it should be exchanged by an inter-application linkage system, like Content Provider or Service. By using this, inter-application access control can be achieved.

World readable permission

World readable may present a risk if they store sensitive information that may present a risk if accessed by an unauthorized party, like bank account statement or session key storage file.

World writable permission

World writable may present a risk if it is to perform sensitive actions, like URL list or session parameters.

External storage

Accessing External storage in apps targeting Android 9 (API level 28) and lower using getExternalFilesDir() gives other apps the right to read and change those files.

The method that apps access files in the external storage of devices running Android 10 (API level 29) or higher has been changed. For apps targeting Android 10, a filtered view for displaying files in external storage is provided by default. Each app can save the app files in the app-specific directory and constantly has read-write access permissions for created files, and so permission does not need to be declared.

Recommendation

  • File Must Be Created as a Private File in Principle: Regardless of the contents of the information to be stored, files should be set private, in principle. From Android security designing point of view, exchanging information and its access control should be done in Android system like Content Provider and Service, etc., and in case there’s a reason that is impossible, it should be considered to be substituted by file access permission as alternative method.

  • Must Not Create Files that Be Allowed to Read/Write Access from Other Applications: When permitting other applications to read/write files, information stored in files cannot be controlled. So, sharing information by using read/write public files should not be considered from both security and function/designing points of view.

  • Using Files Stored in External Device (e.g. SD Card) Should Be Requisite Minimum: Storing files in external memory device like SD card, leads to holding the potential problems from security and functional points of view

    • Sensitive information should not be saved in a file of external memory device, in principle
    • In case sensitive information is saved in a file of external memory device, it should be encrypted.
    • In case saving in a file of external memory device information that will be trouble if it’s tampered by other application or users, it should be saved with electrical signature.
    • When reading in files in external memory device, use data after verifying the safety of data to read in.
    • Application should be designed supposing that files in external memory device can be always deleted.
  • Use of world access permissions should be used only when strictly required. Other means of sharing data between applications are recommended instead of sharing file using insecure permissions.

  • Application Should Be Designed Considering the Scope of File

Insecure Shared Preferences Permissions

Risk: medium

Description

Setting Shared Preferences with insecure permissions either world readable or world writable may expose sensitive information stored in shared preferences to arbitrary read or write by a malicious attacker.

Recommendation

Shared Preferences are XML files to store private primitive data in key-value pairs. Data Types include Booleans, floats, ints, longs, and strings.

Shared preferences must be set with the permission MODE_WORLD_READABLE, unless explicity required for sharing information across apps.

Insecure Random Seed

Risk: medium

Description

Random number generator is seeded using constant value which results in the generation of predictable numbers.

Recommendation

Do not seed Random with the current time because that value is more predictable to an attacker than the default seed.

The java.util.Random class must not be used either for security-critical applications or for protecting sensitive data. Use a more secure random number generator, such as the java.security.SecureRandom class.

Intent Spoofing

Risk: potentially

Description

Intent Spoofing consists of sending an intent toward an application components (Exported Activity, Broadcast Receiver, Content Provider, Service) to achieve unauthorized access.

The access may to different objectives like unauthorized data modification and information leakage, untrusted input injection, etc.

Recommendation

To limit one's exposure to this type of attack, developers should avoid exporting components unless the component is specifically designed to handle requests from untrusted applications. Developers should be aware that declaring an intent filter will automatically export the component, exposing it to public access. Critical, state-changing actions should not be placed in exported components. If a single component handles both inter- and intra-application requests, the developer should consider dividing that component into separate components.

If a component must be exported (e.g., to receive system broadcasts), then the component should dynamically check the caller's identity prior to performing any operations. Requiring Signature or SignatureOrSystem permissions is an effective way of limiting a component's exposure to a set of trusted applications. Finally, the return values of exported components can also leak private data, so developers should check the caller's identity prior to returning sensitive values.

Application implements anti-debug techniques

Risk: secure

Description

Debugging and dynamically exploring the application is a common technique during reverse engineering. Reverse engineers can trace the execution of the application, snoop sensitive data and modify memory to alter its behavior.

To complicate the task of analyzing the application dynamically, the application should implement anti-debugging techniques.

Recommendation

To implement anti-debugging techniques, use several of these techniques:

ptrace: Use the ptrace system call with the PT_DENY_ATTACH flag to prevent debuggers from attaching to the process. The system call is not part of iOS public API and requires using the dlsym function to obtain a function pointer to call it.

#import <dlfcn.h>
#import <sys/types.h>
#import <stdio.h>
typedef int (*ptrace_ptr_t)(int _request, pid_t _pid, caddr_t _addr, int _data);
void anti_debug() {
  ptrace_ptr_t ptrace_ptr = (ptrace_ptr_t)dlsym(RTLD_SELF, "ptrace");
  ptrace_ptr(31, 0, 0, 0); // PTRACE_DENY_ATTACH = 31
}

sysctl: The function can be used to retrieve information about the current process, including determining if the application is being debugged.

#include <assert.h>
#include <stdbool.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/sysctl.h>

static bool AmIBeingDebugged(void)
    // Returns true if the current process is being debugged (either
    // running under the debugger or has a debugger attached post facto).
{
    int                 junk;
    int                 mib[4];
    struct kinfo_proc   info;
    size_t              size;

    // Initialize the flags so that, if sysctl fails for some bizarre
    // reason, we get a predictable result.

    info.kp_proc.p_flag = 0;

    // Initialize mib, which tells sysctl the info we want, in this case
    // we're looking for information about a specific process ID.

    mib[0] = CTL_KERN;
    mib[1] = KERN_PROC;
    mib[2] = KERN_PROC_PID;
    mib[3] = getpid();

    // Call sysctl.

    size = sizeof(info);
    junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
    assert(junk == 0);

    // We're being debugged if the P_TRACED flag is set.

    return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
}
   

getppid: iOS application can check the parent PID to detect if the application has been started with a debugger.

Automatic Reference Counting (ARC) not enforced

Risk: hardening

Description

Automatic Reference Counting (ARC) is a memory managment that autmates objects managemnt by the compiler to unburden the developer.

Recommendation

Automatic Reference Counting (ARC) may be explicitly enabled with the compiler flag -fobjc-arc.

Address Space Layout Randomization (ASLR) not enforced

Risk: medium

Description

Address Space Layout Randomization (ASLR) is a memory protection that randomizes the layout space to to mitigate memory exploitation techniques.

Recommendation

Address Space Layout Randomization (ASLR) is enabled by default on XCode. Do not disable it

IPA contains only bitcode

Risk: important

Description

Bitcode refers to the type of code that is sent to iTunes Connect which allows Apple to use certain calculations to re-optimize apps further. Bitcode applications are impossible to analyze dynamically and will limit the scan results of Ostorlab.

Recommendation

Please provide an application where the Enable Bitcode option is set to No.

Debug Symbols Present in the Application

Risk: low

Description

Application should provide as little explanatory information as possible with the compiled code. Metadata such as debugging information, line numbers, and descriptive function or method names makes the binary or byte-code easier to reverse engineer.

These symbols can be saved in "Stabs" format, the DWARF format or in .symbols r .symbolsmap files. It is noteworthy that most crash reporting tool support uploading symbols to perform stack trace symblication and don't require symbols to be present in the application.

Recommendation

Remove all symbols and debug data from the application. To do so, ensure the setting Strip Debug Symbols During Copy to YES. The settings is at the Deployment / Settings menu.

Mach-O encrypted

Risk: important

Description

Apps distributed by the AppStore are encrypted using an encryption scheme similar to the FairPlay DRM.

The encryption is specific to the device that retrieved the application from AppStore and can only be decrypted on that device.

Encrypted applications are impossible to analyze and will limit the scan results of Ostorlab.

Recommendation

Please provide an unencrypted application with tools like lldb-dumpdecrypted or Clutch.

Mach-O entitlements

Risk: info

Description

Entitlements are used to grant privileges to applications, like enabling Apple Pay, Push notifications, debugging privileges, running unsigned code, etc.

Reviewing this list to identify the application capabilities and attack surface.

Recommendation

This entry is informative, no recommendations applicable.

IPA files list

Risk: info

Description

IPA file is an iOS application archive in ZIP format. The IPA file usually contains the following directories:

  • Payload: directory containing all application data
  • iTunesArtwork and iTunesArtwork@2x: iTunes Artwork file containing the application's icon
  • iTunesMetadata.plist: file in binary PLIST file format describing the application (developpers's name and ID, bundle identifier, name ...)

Recommendation

This entry is informative, no recommendations applicable.

IPA Frameworks list

Risk: info

Description

List of Swift frameworks included in the application.

Recommendation

This entry is informative, no recommendations applicable.

Insecure App Transport Security (ATS) Settings

Risk: medium

Description

App Transport Security (ATS) enforces best practices in the secure connections between an app and its back end. ATS prevents accidental disclosure, provides secure default behavior, and is easy to adopt; it is also on by default in iOS 9 and OS X v10.11. You should adopt ATS as soon as possible, regardless of whether you're creating a new app or updating an existing one.

  • NSAllowsArbitraryLoads: If set to YES, disables all ATS restrictions for all network connections, apart from the connections to domains that you configure individually in the optional NSExceptionDomains dictionary. Default value is NO.
  • NSAllowsArbitraryLoadsForMedia: If set to YES, disables all ATS restrictions for media that your app loads using the AV Foundation framework. Employ this key only for loading media that are already encrypted, such as files protected by FairPlay or by secure HLS, and that do not contain personalized information. Default value is NO.
  • NSAllowsArbitraryLoadsInWebContent: If set to YES, disables all ATS restrictions for requests made from web views. This lets your app use an embedded browser that can display arbitrary content, without disabling ATS for the rest of your app. Default value is NO.
  • NSExceptionAllowsInsecureHTTPLoads: If set to YES, allows insecure HTTP loads for the named domain, but does not change Transport Layer Security (TLS) requirements and does not affect HTTPS loads for the named domain. Default value is NO.
  • NSExceptionMinimumTLSVersion: Specifies the minimum TLS version for network connections for the named domain, allowing connection using an older, less secure version of Transport Layer Security.

Recommendation

If you're developing a new app, you should use HTTPS exclusively. If you have an existing app, you should use HTTPS as much as you can right now, and create a plan for migrating the rest of your app as soon as possible. In addition, your communication through higher-level APIs needs to be encrypted using TLS version 1.2 with forward secrecy. If you try to make a connection that doesn't follow this requirement, an error is thrown. If your app needs to make a request to an insecure domain, you have to specify this domain in your app's Info.plist file.

Sensitive data stored in keyboard cache

Risk: low

Description

iOS stores almost all non-numeric words in the keyboard cache. Sensitive information like login or passwords may leak if the auto-correction feature is not disabled.

Recommendation

Keyboard caching is caused by the UITextInputTraits protocol supported by UITextField, UITextView and UISearchBar

  • var autocorrectionType: UITextAutocorrectionType determines whether auto-correction is enabled during typing. When auto-correction is enabled, the text object tracks unknown words and suggests suitable replacements, replacing the typed text automatically unless the user overrides the replacement. The default value of this property is UITextAutocorrectionTypeDefault, which for most input methods enables autoc-orrection.

  • var secureTextEntry: BOOL determines whether text copying and text caching are disabled and hides the text being entered for UITextField. The default value of this property is NO.

textInput.autocorrectionType = UITextAutocorrectionTypeNo;
textInput.secureTextEntry = YES;

IPA Plist files

Risk: info

Description

Property list files are files that store serialized objects. They often store users settings. They are also used to store information about bundles and applications.

Recommendation

This entry is informative, no recommendations applicable.

Stack smashing protection not enforced

Risk: hardening

Description

Stack Smashing Protection is an exploit mitigation that helps detect buffer overflows being exploited and abort execution beforce malicious code is executed. This feature is implemented by selecting appropriate functions, storing a canary canary at the function prologue and checking the value at the epilogue

Recommendation

Eanble Stack Smashing Protection (SSP) by specifying the -fstack-protector-all compiler flag.

IPA symbol table

Risk: info

Description

List of Mach-o exported symbols.

Recommendation

This entry is informative, no recommendations applicable.

URL Scheme list

Risk: info

Description

URL schemes expose an attack surface that can be triggered by visiting a malicious website in Safari or from a malicious application. It is important that the application validates parameters and restricts actions permitted from the URL scheme.

Recommendation

This entry is informative, no recommendations applicable.

Credentials exposed in logs

Risk: medium

Description

While logging all information may be helpful during development stages, it is important that logging levels be set appropriately before a product ships so that sensitive user data and system information are not accidentally exposed to potential attackers.

Recommendation

  • Remove debug log files before deploying the application into production
  • Adjust configurations appropriately when software is transitioned from a debug state to production.

Credentials exposed in URLs

Risk: medium

Description

Credentials in URLs may be stored in different places, including the user's device, the web server, and any forward or reverse proxy servers between the two endpoints. URLs may also be displayed on-screen, bookmarked or emailed around by users. They may be disclosed to third parties via the Referer header when any off-site links are followed. Placing session tokens into the URL increases the risk that they will be captured by an attacker.

Recommendation

Use a secure layer to send session tokens, such as HTTP cookies or hidden fields in forms that are submitted using the POST method.

Protected Health Information were detected on the system

Risk: high

Description

Under the Health Insurance Portability and Accountability Act (HIPAA), Protected Health Information includes any part of the patient's medical record of payment history.

PHI that is linked based on the following list of 18 identifiers must be treated with special care:

  • Names
  • All geographical identifiers smaller than a state, except for the initial three digits of a zip code if, according to the current publicly available data from the U.S. Bureau of the Census: the geographic unit formed by combining all zip codes with the same three initial digits contains more than 20,000 people; and the initial three digits of a zip code for all such geographic units containing 20,000 or fewer people is changed to 000
  • Dates (other than year) directly related to an individual
  • Phone Numbers
  • Fax numbers
  • Email addresses
  • Social Security numbers
  • Medical record numbers
  • Health insurance beneficiary numbers
  • Account numbers
  • Certificate/license numbers
  • Vehicle identifiers and serial numbers, including license plate numbers
  • Device identifiers and serial numbers
  • Web Uniform Resource Locators (URLs)
  • Internet Protocol (IP) address numbers
  • Biometric identifiers, including finger, retinal and voice prints
  • Full face photographic images and any comparable images
  • Any other unique identifying number, characteristic, or code except the unique code assigned by the investigator to code the data

Recommendation

  • Securely delete PHI when there is no longer a business need for its retention on the device
  • Do not cache sensitive data
  • Minimize the frequency of asking for user credentials.
  • Minimize the use of APIs that access sensitive or personal user data
  • Consider a logical way to hash and de-anonymize the user data
  • Some jurisdictions may require you to provide a privacy policy for accessing personal information.

Personally Information were detected on the system

Risk: medium

Description

Personally Identifiable Information (PII) is, according to NIST Special Publication 800-122, a collective term for any information that can be used to distinguish or trace an individual's identity, such as name, social security number, date and place of birth, mother's maiden name, or biometric records; and any other information that is linked or linkable to an individual, such as medical, educational, financial, and employment information.

Recommendation

  • Securely delete PII when there is no longer a business need for its retention on the device
  • Do not cache sensitive data
  • Minimize the frequency of asking for user credentials.
  • Minimize the use of APIs that access sensitive or personal user data
  • Consider a logical way to hash the user data
  • Some jurisdictions may require you to provide a privacy policy for accessing personal information.

Network Port Scan

Risk: info

Description

List of identified open ports which corresponds to the application internet facing attack surface.

Recommendation

This entry is informative, no recommendations applicable.

Use of Outdated Vulnerable Component

Risk: low

Description

The application is using an outdated component with publicly known vulnerabilities. Exploitation of this issue varies from easily accessible off the shelf exploit to requiring custom exploit.

Recommendation

Update to the latest versions to fix the issue. It is also recommended to implement a patch management process to prevent future similar issues and remove all unused dependencies.

Cordova debug mode enabled

Risk: low

Description

"Phonegap application log is set to DEBUG, this may cause it to leak too much information to Android logs"

Recommendation

Disable debug mode

Insecure whitelist

Risk: medium

Description

The application's whitelist may be bypassed since the url may be used as a prefix to another domain. Eg: 127.0.0.1* may be bypassed by accessing the domain 127.0.0.1.badsite.net

Recommendation

Cordova offer a powerful security model to provide developers with the tools to prevent unauthorised access and Cross-Site Scripting vulnerabilities

Cordova whitelist manages network security access and must authorise explicitly accessible ressources only.

Insecure whitelist configuration

Risk: hardening

Description

The application's whitelist allows unrestricted access to all ressources *.

Recommendation

Cordova offer a powerful security model to provide developers with the tools to prevent unauthorised access and Cross-Site Scripting vulnerabilities

Cordova whitelist manages network security access and must authorise explicitly accessible ressources only.

port open on localhost

Risk: potentially

Description

The application has started servers listening on localhost. Access to the open port is not restricted to other application on the phone, which may be exploited to perform unauthorized actions.

Drive-by attacks using the browser and DNS rebinding are forms of exploitation techniques that can be used to access the open ports remotely.

Recommendation

Access to the port should be restricted to authorized applications only. It is also critical to ensure the server is immune from vulnerabilities and does not expose any critical functionality.

Calls to Privacy API

Risk: info

Description

Ostorlab Mobile Application Security Scanner checks multiple privacy features:

Telephony identifiers leakage:

  • The application reads the Location Area Code value.
  • The application reads the Cell ID value.
  • The application reads the phone's current state.
  • The application reads the current location of the device.
  • The application reads the type of activity on a data connection.
  • The application reads the current data connection state.
  • The application reads the unique device ID, i.e the IMEI for GSM and the MEID or ESN for CDMA phones.
  • The application reads the software version number for the device, for example, the IMEI/SV for GSM phones.
  • The application reads the phone number string for line 1, for example, the MSISDN for a GSM phone.
  • The application reads the neighboring cell information of the device.
  • The application reads the ISO country code equivalent of the current registered operator's MCC (Mobile Country Code).
  • The application reads the numeric name (MCC+MNC) of current registered operator.
  • The application reads the operator name.
  • The application reads the radio technology (network type) currently in use on the device for data transmission.
  • The application reads the device phone type value.
  • The application reads the ISO country code equivalent for the SIM provider's country code.
  • The application reads the MCC+MNC of the provider of the SIM.
  • The application reads the Service Provider Name (SPN).
  • The application reads the SIM's serial number.
  • The application reads the constant indicating the state of the device SIM card.
  • The application reads the unique subscriber ID, for example, the IMSI for a GSM phone.
  • The application reads the alphabetic identifier associated with the voice mail number.
  • The application reads the voice mail number.

Location lookup:

  • The application reads location information from all available providers (WiFi, GPS etc.).

Connection interfaces exfiltration:

  • The application reads details about the currently active data network.
  • The application tries to find out if the currently active data network is metered.
  • The application reads the WiFi credentials.

Telephony services abuse:

  • The application sends SMS messages.
  • The application intercepts the incoming SMS.
  • The application disables incoming SMS notifications.
  • The application makes phone calls.

Audio video eavesdropping:

  • The application records audio from mobile sources.
  • The application captures video from mobile sources.

Personal information manager data leakage:

  • The application reads or edits contact data.
  • The application reads the SMS inbox.

Recommendation

This entry is informative, no recommendations applicable.

Continuous collection of GPS location

Risk: potentially

Description

The application continuously accesses and collects device GPS location. GPS tracking is subject to compliance requirements and is subject to strict restrictions under certain jurisdiction.

GPS tracking may also be abused by malware or attackers who gained access to the device with the permissions of the application.

Recommendation

To enable continuous GPS tracking, it is recommended:

  • Consult legal counsel on the legality of GPS tracking
  • Notify user of the reason requiring GPS tracking with the possibility for users to opt-out
  • Avoid storage of GPS location locally, and if needed encrypt GPS with device specific key

Process crashes

Risk: low

Description

A crash is the result of unexpected or unhandled behaviours. It might be the result of missing input validations, incorrect serializations, or unallowed operations etc.

An attacker may try to find the code path that leads to the faulty procedure and attempt to execute arbitrary code through potential vulnerabilities.

Crashes may give an attacker valuable information about the system and its internal details. Crashes may also create temporary vulnerabilities or leave unprotected files (e.g. memory dumps) that may be exploited.

Recommendation

  • Catch all the errors and handle them correctly
  • Validate the type and the length of all the inputs
  • DO NOT generate logs or throw errors containing personal information

Redis Library detected

Risk: medium

Description

Redis library is not suited for mobile applications since the Redis framework only has one user and the application needs to be given access to the users credentials

Recommendation

This entry is informative, no recommendations applicable.

Secret information stored in the application

Risk: potentially

Description

The application is detected to contain secret credentials, like SSH keys or private API keys.

Recommendation

Sensitive data must not be package with the application. If access to this data is required, apply procedures to securely encrypt, store, and retrieve credentials for your services. You can for example use AWS Secrets Manager to encrypt and retrieve your credentials whenever needed

Source to Sink

Risk: potentially

Description

Source method or user-controlled parameter is used to call a sink method.

Source refers to untrusted data input, that may originate from an untrusted user. Sink refers to dangerous method, that if accessible by attacker, may leverage it to perform an attack.

Source and Sinks must be reviewed for vulnerabilities, like Injection, Indirect Object Reference or Unauthorized data access.

Recommendation

Recommendation varies on the class of vulnerability identified.

SQL injection

Risk: medium

Description

Improper SQL query construction could lead to SQL injection. An SQL injection attack consists of injecting of an SQL query via the input data from the client to the application

Recommendation

Without sufficient removal or quoting of SQL syntax in user-controllable inputs, the generated SQL query can cause those inputs to be interpreted as SQL instead of ordinary user data. This can be used to alter query logic to bypass security checks or access unauthorized content.

Stack traces reveal technical information

Risk: medium

Description

When the server application receives unexpected input, an error is triggered returning technical information about the application internals.

An attacker can use this information to understand how the application is handling inputs. It becomes possible to investigate the inner workings and formulate further attack strategies. Information leakage should be suppressed to discourage attackers and prevent access to potential critical information.

Recommendation

A custom exception page should be returned that does not include technical information. The exception should be logged server side but not visible to a user. The stack trace should never be included within the page's HTML source even if client side source code viewing has been disabled as it is still possible to recover this information though other mechanisms.

Strings Bplist files

Risk: info

Description

Property list files are files that store serialized objects. They often store users settings. They are also used to store information about bundles and applications.

Recommendation

This entry is informative, no recommendations applicable.

Anonymous unauthenticated server accepted

Risk: medium

Description

Server accepts anonymous authentication.

Recommendation

Use of deprecated TLS/SSL protocol version

Risk: medium

Description

There are six protocols in the SSL/TLS family: SSL v2, SSL v3, TLS v1.0, TLS v1.1, TLS v1.2, and TLS v1.3:

  • SSL v2 is insecure and must not be used. This protocol version can be used to attack RSA keys and sites with the same name using the DROWN attack.
  • SSL v3 is insecure when used with HTTP due to the SSLv3 POODLE attack. The protocol is considered weak when used with other protocols. The protocol is deprecated and must not be used.
  • TLS v1.0 and TLS v1.1 are legacy protocol that suffers from the BEAST attack. Although modern have implemented some mitigations, the protocol still suffers from known weaknesses and has been deprecated by PCI DSS and browsers starting January 2020.
  • TLS v1.2 and v1.3 are not known to have security issues.

Recommendation

TLS v1.2 or TLS v1.3 should the main supported protocol as these version offers modern authenticated encryption.

Heartbleed (CVE-2014-0160)

Risk: high

Description

Application suffers from heartbleed (CVE-2014-0160) vulnerability

Recommendation

Heartbleed is a security bug in the OpenSSL cryptography library, which is a widely used implementation of the Transport Layer Security (TLS) protocol. It was introduced into the software in 2012 and publicly disclosed in April 2014.

Heartbleed may be exploited regardless of whether the vulnerable OpenSSL instance is running as a TLS server or client. It results from improper input validation (due to a missing bounds check) in the implementation of the TLS heartbeat extension, thus the bug's name derives from heartbeat. The vulnerability is classified as a buffer over-read, a situation where more data can be read than should be allowed.

Clear text HTTP request

Risk: medium

Description

Mobile Applications must use Transport Layer Security (TLS) to provide encryption at the transport layer and ensure the confidentiality and integrity of data in transit.This application does not use SSL/TLS and is vulnerable to traffic interception and modification.

An attacker performing a man-in-the-middle (MITM) attack may:

  • Passively intercept the communication to access any sensitive data in transit like usernames, passwords or credit card number
  • Actively inject or remove content to forge and omit information or inject malicious scripts
  • Actively redirect the communication to the attacker in the context of the initial trusted party

Recommendation

It is recommended to ensure the use of an encrypted channel for requests transmitting sensitive data, it is however highly recommended to encrypt all requests made by the application, as the interception and modification of non sensitive requests could be leveraged to access sensitive data.

The encrypted channel should use secure protocols and cipher suites, do not develop custom encryption protocols or algorithms.

Insecure TLS Ciphers supported

Risk: medium

Description

Transport Layer Security (TLS) starts by the client requesting a secure connection and presenting a list of suppored cipher suites.

Cipher suite is a list of authentication, encryption, message authentication code (MAC) and key exchange algorithms. Each algorithm serve a specific role during the protocol negotiation. Use of a week algorithm might ciriticaly impact the security of the whole channel.

It was identified that the endpoint supports a combination of cipher suites and Secure Sockets Layer / Transport Layer Security (SSL/TLS) protocols that suffer from known cryptographic weaknesses. Therefore they should not be relied upon for effective transport layer security. An attacker with the ability to eavesdrop the connection could influence or even decrypt the traffic that is passing by.

Cryptographic weaknesses have been demonstrated for all the following configurations:

  • Support for deprecated SSL protocol (v2 or v3)
  • Support of cipher suites offering keys smaller than 128bit
  • Support of cipher suites offering CBC mode in combination with TLS protocol lower than version 1.1 vulnerable to the BEAST attack
  • Use of compression within TLS vulnerable to the CRIME attack
  • Support of cipher suites offering RC4 as cipher
  • Support of cipher suites offering DES as cipher
  • Support of cipher suites offering MD5 as signature algorithm

Recommendation

The recommended TLS configuration should enforce the following recommendations:

  • Restrict to TLSv1 and above, with TLS1.2 being preferred
  • If SSLv3 is required, it is advised to implement the TLS Fallback SCSV feature to prevent protocol downgrade attacks
  • Disable Anonymous Diffie-Hellman (ADH)
  • Disable aNULL and eNull cipher suites
  • Disable Export key exchange suites
  • Remove RC4 support
  • Remove DES support
  • Remove MD5 support
  • Prefere SHA256 over SHA1
  • Prefer AES128 over AES256 as 256 offer little security advantages and is less robust to timing attacks
  • Disable Client-Initiated Renegotiation
  • Disable TLS compression
  • Offer only ciphers with a key length of greater than 128bit
  • Offer cipher suites with Perfect-Forward Secrecy protocol properties (DHE, ECDHE)
  • Use custom Diffie-Hellman group to protect against Logjam attack
  • Implement the HTTP Strict Transport Security header field
  • Implement OSCP stapling

Sample of a secure TLS configuration for Nginx generated with Mozilla SSL Configuration Generator

    server {
        listen 443 ssl;
    
        # certs sent to the client in SERVER HELLO are concatenated in ssl_certificate
        ssl_certificate /path/to/signed_cert_plus_intermediates;
        ssl_certificate_key /path/to/private_key;
        ssl_session_timeout 1d;
        ssl_session_cache shared:SSL:50m;
        ssl_session_tickets off;
    
        # Diffie-Hellman parameter for DHE ciphersuites, recommended 2048 bits
        ssl_dhparam /path/to/dhparam.pem;
    
        # modern configuration. tweak to your needs.
        ssl_protocols TLSv1.1 TLSv1.2;
        ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK';
        ssl_prefer_server_ciphers on;
    
        # HSTS (ngx_http_headers_module is required) (15768000 seconds = 6 months)
        add_header Strict-Transport-Security max-age=15768000;
    
        # OCSP Stapling ---
        # fetch OCSP records from URL in ssl_certificate and cache them
        ssl_stapling on;
        ssl_stapling_verify on;
    
        ## verify chain of trust of OCSP response using Root CA and Intermediate certs
        ssl_trusted_certificate /path/to/root_CA_cert_plus_intermediates;
    
        resolver <IP DNS resolver>;
    
        ....
    }

Insecure TLS certificate domain name validation

Risk: medium

Description

The application does not perform proper TLS certificate validation which makes it vulnerable to man-in-the-middle attacks.

Recommendation

It is recommended to apply proper TLS certificate validation. Compliant solution depends on actual implementation.

Secure TLS certificate validation

Risk: secure

Description

The application performs proper TLS certificate validation.

Recommendation

The implementation is secure, no recommendation apply.

Insecure TLS certificate validation (accept self-signed certificate)

Risk: high

Description

Application accepts self-signed certificate making it vulnerable to man-in-the-middle (MITM) attacks.

Recommendation

When a certificate is invalid or malicious, it might allow an attacker to spoof a trusted entity by using a man-in-the-middle (MITM) attack. The software might connect to a malicious host while believing it is a trusted host, or the software might be deceived into accepting spoofed data that appears to originate from a trusted host.

TLS/SSL Server Configuration Settings

Risk: info

Description

TLS scan listing supported ciphers, protocols and checks for known vulnerabilities.

Recommendation

This entry is informative, no recommendations applicable.

Insecure TLS Ciphers supported

Risk: medium

Description

The application accepts insecure TLS Ciphers.

Recommendation

Assign a unique name and/or number for

identifying and tracking user identity

Risk: secure

Description

Maintaining separate credentials for each user of information systems is critical to ensuring individual accountability and easing investigation of potential data breaches.

The HIPAA Security Rule requires Covered Entities to implement a “Unique User Identification” standard for systems holding electronic protected health information (EPHI). Unique User Identification is a “required” specification under the Access Control standard and should be employed for all EPHI systems.

As the name implies, unique user identification refers to the use of a unique name or number to identify and track specific individuals using EPHI systems, frequently referred to as “Logon name” or “User ID”. Use of this unique name or number provides a means to verify the identity of the person using the system. An effective unique user identification practice ensures that system activity can be traced to a specific individual. Never share your user ID on any system as you would not like to be held responsible for someone else’s actions.

Recommendation

Assign unique user identifiers (user IDs) that identify members, enable activities performed on ePHI Systems with user identifiers to be traced to an individual workforce member, and provide access to ePHI Systems.

Untrusted External Storage File Access

Risk: medium

Description

Files saved to the external storage prior to Android 4.1 are world-readable. Prior to Android 1, files saved to external storage are world-writable. From Android 1 to Android 4.3, only the WRITE_EXTERNAL_STORAGE permission is required for an app to write to any external storage file stored by any app. Starting with Android 4.4, groups and modes of files are created based on a directory structure, which allows an app permission to manage/read/write files within a directory structure based on its package name. Starting with Android 4.4, users (including apps as users) are isolated from primary external storage spaces of other apps controlled by the Android device.

Consequent to the lack of restrictions described above, files written to external storage can be modified or read by other apps installed on the device (for the Android versions which allow read/write) and by anyone with access to the files if stored on an off-device external storage device such as a PC (or if the in-device external storage media is removed and mounted elsewhere).

Source: CERT Secure Coding

Recommendation

It is recomended to set proper permissions on file stored on the external storage and encrypt sensitive data that may need to be stored on the external storage.

Username enumeration

Risk: low

Description

Enumeration techniques are a very fast way to identify registered users. With valid usernames, effective brute force attacks can be attempted to guess the password of the user accounts.

Recommendation

Making sure no pages or APIs can be used to differentiate between a valid and invalid username

  • Login:

    Make sure to return a generic "No such username or password" message when a login failure occurs. Make sure the HTTP response, and the time taken to respond are no different when a username does not exist, and an incorrect password is entered.

  • Password Reset:

    Make sure your "forgotten password" page does not reveal usernames. If your password reset process involves sending an email, have the user enter their email address. Then send an email with a password reset link if the account exists.

  • Registration:

    Avoid having your site tell people that a supplied username is already taken. If your usernames are email addresses, send a password reset email if a user tries to sign-up with an existing address. If usernames are not email addresses, protect your sign-up page with a CAPTCHA.

  • Profile Pages:

    If your users have profile pages, make sure they are only visible to other users who are already logged in. If you hide a profile page, ensure a hidden profile is indistinguishable from a non-existent profile.

Risk: info

Description

Malware analysis by multiple Antiviruses using VirusTotal MD5 hash based search.

Recommendation

This entry is informative, no recommendations applicable.

Webview loadurl injection

Risk: medium

Description

Webview.loadurl loads a given URL into a webview session. Webview url accepts different urls schemes and paths that can lead to loading of insecure content, perform phishing attacks or in some cases exploit a remote code execution vulnerability.

Several settings controls the capabilities of the webview session, like enabling javascript or local file access using the Websettings class.

Attackers can exploit the vulnerability by crafting malicious HTML or Javascript. A phishing attack can pass as a fake login form to steal the user's credentials.

The following is an example a vulnerable Java code accepting untrusted URL from an intent:

public class VulnerableBrowserActivity extends Activity {
      @override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Create a new wevbiew session.
        WebView webView = (WebView) findViewById(R.id.webview);

        // Enable javascript.
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);

        // Accept url from untrusted intent.
        String url = getIntent().getStringExtra("URL");
        webView.loadUrl(url);
      }
    }

Recommendation

All untrusted URLs must have proper input validation to ensure only trusted content is accessible. For instance, if the application is loading local assets, the list of loaded URL must be whitelisted.

The Webview settings must also be hardened, removing all non required settings, like javascript or file access.

public class WhitelistBrowserActivity extends Activity {
  private static WHITELISTED_URLS = ImmutableList.of(
    "url1",
    "url2");

  @override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    WebView webView = (WebView) findViewById(R.id.webview);

    String url = getIntent().getStringExtra("url");
    if (!WHITELISTED_URLS.contains(url)) {  /* Note: "https".startsWith("http") == true */
        url = "about:blank";
    }

    webView.loadUrl(url);
  }
}

Risk: medium

Description

Secure cookie: is only sent to the server with an encrypted request over the HTTPS protocol.Cookies missing the Secure flag can be sent over unencrypted channels. The presence of the flag should not justify the storage of sensitive data, as the flag remains an unsafe place to store data.

HttpOnly cookie: helps mitigate cross-site scripting (XSS) vulnerabilities, HttpOnly cookies are inaccessible from javascript using the document.cookie API.

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly

Recommendation

Add missing security attributes to the cookies. Adding the flag depends on the framework used and can either be a global setting or be done manually by adding the flags to the request.

For session cookies managed by PHP, the flag is set either in php.ini:

session.cookie_secure = True

or in code:

setcookie ( string $name [, string $value = "" [, int $expires = 0 [, string $path = "" [, string $domain = "" [, bool $secure = FALSE [, bool $httponly = FALSE ]]]]]] ) : bool
setcookie ( string $name [, string $value = "" [, array $options = [] ]] ) : bool

For accurate details on how to add the flag, check the documentation of your framework.

Generic Web Entry

Risk: low

Description

Generic Web Vulnerability.

Recommendation

N/A

Insecure Direct Object Reference (IDOR)

Risk: medium

Description

Insecure Direct Object Reference (IDOR) occurs when a user input is not validated and accesses directly the requested object.

Consider for instance a website that grants access to bank account information by bank id:

https://insecure-bank.com/bank/account?id=12345

An attacker might be able to access the information of other accounts by referencing its id.

Another manifestation of this weakness is when the id is not easily guessable, UUID for instance, but can be leaked through other means and used to access the object:

https://insecure-bank.com/user/12/account?id=12345-abcd-12345-abcd

Recommendation

IDORs are caused by missing access controls. If the object is accessible to authenticated users only, the endpoint must implements check to verify the user making the request has the permissions to access the object.

Insecure Access Control

Risk: medium

Description

The application does not enforoce propoer access control, allowing an attacker to access unauthorized data or perform unauthorized business functions.

Access control vulnerabilities may be caused by:

  • Referencing content using primary keys and lack of validation of the content access permissions.
  • CORS misconfiguration allowing unauthorized API access.
  • Metadata manipulation, such as replaying or tampering with a access control tokens.

Recommendation

Access control is only effective if enforced in trusted server-side code or server-less API, where the attacker cannot modify the access control check or metadata.

  • With the exception of public resources, deny by default. l* Implement access control mechanisms once and re-use them throughout the application, including minimizing CORS usage.
  • Model access controls should enforce record ownership, rather than accepting that the user can create, read, update, or delete any record.
  • Unique application business limit requirements should be enforced by domain models.
  • Disable web server directory listing and ensure file metadata (e.g. .git) and backup files are not present within web roots.
  • Log access control failures, alert admins when appropriate (e.g. repeated failures).
  • Rate limit API and controller access to minimize the harm from automated attack tooling.
  • JWT tokens should be invalidated on the server after logout. Developers and QA staff should include functional access control unit and integration tests.

Insecure Object Serialization

Risk: high

Description

The application uses an insecure deserialization scheme from untrusted data.

Insecure object deserialization may result in

  • Arbitrary remote code execution
  • Modification of the application logic
  • Data tampering, such as bypassing access control

Exploitation of deserialization vulnerabilties is difficult, due to the absence of off the shelf exploits and the need to to tweak them for the targetted exploit.

Recommendation

To prevent object serialization vulneravilities, the application must either:

  • Accept serialized objects from trusted sources only
  • Use serialization primitive data types only

If these measures are not possible, consider the following:

  • Implementing integrity checks such as digital signatures on any serialized objects to prevent hostile object creation or data tampering.
  • Enforcing strict type constraints during deserialization before object creation as the code typically expects a definable set of classes. Bypasses to this technique have been demonstrated, so reliance solely on this is not advisable.
  • Isolating and running code that deserializes in low privilege environments when possible.
  • Logging deserialization exceptions and failures, such as where the incoming type is not the expected type, or the deserialization throws exceptions.
  • Restricting or monitoring incoming and outgoing network connectivity from containers or servers that deserialize.
  • Monitoring deserialization, alerting if a user deserializes constantly.

Intersting response

Risk: info

Description

The backend response is considered as interesting. This is not necessarily a vulnerability, but is worth investigating the cause of the response.

Recommendation

This entry is informative, no recommendations applicable.

Strict-Transport-Security (HSTS) not enforced

Risk: hardening

Description

The HTTP Strict-Transport-Security response header ( abbreviated HSTS) lets a web site tell browsers that it should only be accessed using HTTPS, instead of using HTTP.

To exploit this vulnerability, an attacker must intercept and modify the network traffic from the target.

This requires the client to communicate with the server over an insecure connection such as public Wi-Fi.

Recommendation

The server must add the header Strict-Transport-Security to all HTTP responses to instructs the browser to use transport security.

HSTS is only true on first use, a user who has never accessed the application is still vulnerable to SSL stripping attacks.

Unrestricted file upload

Risk: medium

Description

Unrestricted File Upload is a major risk for applications, the may result in system takeover, file system overload, client-side attacks, or defacement. This vulnerability can be caused by insecure file metadata validation, like HTTP Multi-part fields or insecure content and size validation, like uploading unauthorized file formats.

Recommendation

Recommendation to limit and prevent unrestricted file upload:

  • The file types allowed to be uploaded should be restricted to only those that are necessary for business functionality.
  • Never accept a filename and its extension directly without having a whitelist filter.
  • The application should perform filtering and content checking on any files which are uploaded to the server. Files should be thoroughly scanned and validated before being made available to other users. If in doubt, the file should be discarded.
  • It is necessary to have a list of only permitted extensions on the web application. And, file extension can be selected from the list. For instance, it can be a “select case” syntax (in case of having VBScript) to choose the file extension in regards to the real file extension.
  • All the control characters and Unicode ones should be removed from the filenames and their extensions without any exception. Also, the special characters such as ;, :, >, <, / ,\, additional ., *, %, $, and so on should be discarded as well. If it is applicable and there is no need to have Unicode characters, it is highly recommended to only accept Alpha-Numeric characters and only 1 dot as an input for the file name and the extension; in which the file name and also the extension should not be empty at all (regular expression: [a-zA-Z0-9]{1,200}\.[a-zA-Z0-9]{1,10}).
  • Limit the filename length. For instance, the maximum length of the name of a file plus its extension should be less than 255 characters (without any directory) in an NTFS partition.
  • It is recommended to use an algorithm to determine the filenames. For instance, a filename can be a MD5 hash of the name of file plus the date of the day.
  • Uploaded directory should not have any execute permission and all the script handlers should be removed from these directories.
  • Limit the file size to a maximum value in order to prevent denial of service attacks (on file space or other web application’s functions such as the image resizer).
  • Restrict small size files as they can lead to denial of service attacks. So, the minimum size of files should be considered.
  • Use Cross Site Request Forgery protection methods.
  • Prevent from overwriting a file in case of having the same hash for both.
  • Use a virus scanner on the server (if it is applicable). Or, if the contents of files are not confidential, a free virus scanner website can be used. In this case, file should be stored with a random name and without any extension on the server first, and after the virus checking (uploading to a free virus scanner website and getting back the result), it can be renamed to its specific name and extension.
  • Use POST method instead of PUT or GET
  • Log users’ activities. However, the logging mechanism should be secured against log forgery and code injection itself.
  • In case of having compressed file extract functions, contents of the compressed file should be checked one by one as a new file.
  • If it is possible, consider saving the files in a database rather than on the filesystem.
  • If files should be saved in a filesystem, consider using an isolated server with a different domain to serve the uploaded files.
  • File uploaders should be only accessible to authenticated and authorised users if possible.
  • Write permission should be removed from files and folders other than the upload folders. The upload folders should not serve any
  • Ensure that configuration files such as .htaccess or web.config cannot be replaced using file uploaders. Ensure that appropriate settings are available to ignore the .htaccess or web.config files if uploaded in the upload directories.
  • Ensure that files with double extensions (e.g. file.php.txt) cannot be executed especially in Apache.
  • Ensure that uploaded files cannot be accessed by unauthorised users.
  • Adding the Content-Disposition: Attachment and X-Content-Type-Options: nosniff headers to the response of static files will secure the website against Flash or PDF-based cross-site content-hijacking attacks. It is recommended that this practice be performed for all of the files that users need to download in all the modules that deal with a file download. Although this method does not fully secure the website against attacks using Silverlight or similar objects, it can mitigate the risk of using Adobe Flash and PDF objects, especially when uploading PDF files is permitted.
  • Flash/PDF (crossdomain.xml) or Silverlight (clientaccesspolicy.xml) cross-domain policy files should be removed if they are not in use and there is no business requirement for Flash or Silverlight applications to communicate with the website.
  • Browser caching should be disabled for the crossdomain.xml and clientaccesspolicy.xml files. This enables the website to easily update the file or restrict access to the Web services if necessary. Once the client access policy file is checked, it remains in effect for the browser session so the impact of non-caching to the end-user is minimal. This can be raised as a low or informational risk issue based on the content of the target website and security and complexity of the policy file(s).
  • CORS headers should be reviewed to only be enabled for static or publicly accessible data. Otherwise, the Access-Control-Allow-Origin header should only contain authorised addresses. Other CORS headers such as Access-Control-Allow-Credentials should only be used when they are required. Items within the CORS headers such as “Access-Control-Allow-Methods” or Access-Control-Allow-Headers should be reviewed and removed if they are not required.

Cross-Site Scripting (XSS)

Risk: medium

Description

Cross-site-scripting (XSS) vulnerabilities occur when unsanitized user-controlled input is served to user.

XSS vulnerabilities bypasses same-Origin-Policy, which is a core principal of web security. SOP ensures that a page from http://evil.com can't access the content of a page from http://bank.com.

XSS are commonly separated into 3 familities

  • Reflected: the user-controlled input is directly reflected in the page response
  • Stored: the user-controled input is stored on the server-side, for instance in a database, and is later returned to user
  • DOM-based: the user-controlled input is injected on the client-side to the DOM, triggering the injection of malicious JavaScript

XSS vulnerabilities allow an attacker to perform a variety of malcious actions, like exfiltration of personal data, including user session or account information; perform actions on behalf of the user.

Recommendation

In general cases, preventing XSS vulnerabilities requires a 2-step protection:

  • Input validation: user-controlled input should be validated to forbid all unauthorized characters, phone number should for instance only contain numbers; names should only contain alphabetical characters, etc.
  • Output encoding: all input shown to user is properly encoded using standard proven API. Use of safe template engines with native support for output encoding and secure defaults is highly recommended.