Mobile threats | Latest Threats | Microsoft Security Blog http://approjects.co.za/?big=en-us/security/blog/threat-intelligence/mobile-threats/ Expert coverage of cybersecurity topics Thu, 08 Aug 2024 20:54:31 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 Chained for attack: OpenVPN vulnerabilities discovered leading to RCE and LPE http://approjects.co.za/?big=en-us/security/blog/2024/08/08/chained-for-attack-openvpn-vulnerabilities-discovered-leading-to-rce-and-lpe/ Thu, 08 Aug 2024 18:00:00 +0000 Microsoft researchers found multiple vulnerabilities in OpenVPN that could lead to an attack chain allowing remote code execution and local privilege escalation. This attack chain could enable attackers to gain full control over targeted endpoints, potentially resulting in data breaches, system compromise, and unauthorized access to sensitive information.

The post Chained for attack: OpenVPN vulnerabilities discovered leading to RCE and LPE appeared first on Microsoft Security Blog.

]]>
Microsoft researchers recently identified multiple medium severity vulnerabilities in OpenVPN, an open-source project with binaries integrated into routers, firmware, PCs, mobile devices, and many other smart devices worldwide, numbering in the millions. Attackers could chain and remotely exploit some of the discovered vulnerabilities to achieve an attack chain consisting of remote code execution (RCE) and local privilege escalation (LPE). This attack chain could enable attackers to gain full control over targeted endpoints, potentially resulting in data breaches, system compromise, and unauthorized access to sensitive information. Exploiting these vulnerabilities, however, necessitates user authentication and a deep understanding of OpenVPN’s inner workings, alongside intermediate knowledge of the operating systems. Today, we presented this research and demonstrated the discovered attack chain in our session at Black Hat USA 2024.

OpenVPN is widely used by thousands of companies spanning various industries across major platforms such as Windows, iOS, macOS, Android, and BSD. As such, exploitation of the discovered vulnerabilities, which affect all versions of OpenVPN prior to version 2.6.10 (and 2.5.10), could put endpoints and enterprises at significant risk of attack.

We reported the discovery to OpenVPN through Coordinated Vulnerability Disclosure (CVD) via Microsoft Security Vulnerability Research (MSVR) in March 2024 and worked closely with OpenVPN to ensure that the vulnerabilities are patched. Information on the security fixes released by OpenVPN to address these vulnerabilities can be found here: OpenVPN 2.6.10. We strongly urge OpenVPN users to apply the latest security updates as soon as possible. We also thank OpenVPN for their collaboration and recognizing the urgency in addressing these vulnerabilities.

Below is a list of the discovered vulnerabilities discussed in this blog:

CVE IDOpenVPN componentImpactAffected platform
CVE-2024-27459openvpnserv                             Denial of service (DoS), local privilege escalation (LPE)Windows
CVE-2024-24974openvpnserv                             Unauthorized access Windows
CVE-2024-27903openvpnservRemote code execution (RCE)Windows
Local privilege escalation (LPE), data manipulationAndroid, iOS, macOS, BSD
CVE-2024-1305Windows TAP driver Denial of service (DoS) Windows

In this blog post, we detail our analysis of the discovered vulnerabilities and the impact of exploitation. In addition to patching, we provide guidance to mitigate and detect threats attempting to exploit these vulnerabilities. This research emphasizes the need for responsible disclosure and collaboration among the security community to defend devices across platforms and build better protection for all, spanning the entire user-device ecosystem. The discovery of these vulnerabilities further highlights the critical importance of ensuring the security of enterprise and endpoint systems and underscores the need for continuous monitoring and protection of these environments.

What is OpenVPN?

OpenVPN is a virtual private network (VPN) system that creates a private and secure point-to-point or site-to-site connection between networks. The OpenVPN open-source project is widely popular across the world, including the United States, India, France, Brazil, the United Kingdom, and Germany, as well as industries spanning the information technology, financial services, telecommunications, and computer software sectors. This project supports different major platforms and is integrated into millions of devices globally.

OpenVPN is also the name of the tunneling protocol it uses, which employs the Secure Socket Layer (SSL) encryption protocol to ensure that data shared over the internet remains private, using AES-256 encryption. Since the source code is available for audit, vulnerabilities can be easily identified and fixed.

OpenVPN analysis

We discovered the vulnerabilities while examining the OpenVPN open-source project to enhance enterprise security standards. During this research, we checked two other popular VPN solutions and found that at the time they were impacted by a vulnerability (CVE-2024-1305). Following this discovery, we started hunting for and uncovered additional vulnerable drivers with the same issue and decided to investigate open-source VPN projects. Upon confirming that the same vulnerability was located in the OpenVPN open-source repository, our research then focused on examining the architecture and security model of the OpenVPN project for Windows systems.

OpenVPN architecture

OpenVPN server client architecture

OpenVPN is a sophisticated VPN system meticulously engineered to establish secure point-to-point or site-to-site connections. It supports both routed and bridged configurations, as well as remote access capabilities, making it a versatile choice for various networking needs. OpenVPN comprises both client and server applications, ensuring a comprehensive solution for secure communication.

With OpenVPN, peers can authenticate each other through multiple methods, including pre-shared secret keys, certificates, or username/password combinations. In multi-client server environments, the server can generate and issue an individual authentication certificate for each client, leveraging robust digital signatures and a trusted certificate authority. This ensures an elevated level of security and integrity in the authentication process, enhancing the overall reliability of the VPN connection. 

Diagram of OpenVPN's client server depicting the connection between the Gateway Client and the Access Server
Figure 1. OpenVPN client server model

Client-side architecture

The client-side architecture is where we discovered the additional three vulnerabilities (CVE-2024-27459, CVE-2024-24974, and CVE-2024-27903):

OpenVPN’s client architecture can be summarized in the following simplified diagram:

Diagram depicting the loaded plugin with the openvpn.exe usermode process connected by a named pope to the openvpnserv.exe system service within the client. The client is connected to the server via a tunnel.
Figure 2. OpenVPN client architecture with loaded plugin.dll

openvpnserv.exe and openvpn.exe

The system service launches elevated commands on behalf of the user, handling tasks such as adding or deleting DNS configurations, IP addresses, and routes, and enabling Dynamic Host Configuration Protocol (DHCP). These commands are received from the openvpn.exe process through a named pipe created for these two entities, such as “openvpn/service_XXX” where XXX is the thread ID (TID) that is being passed to the newly created process as a command line argument.

The launched commands arrive in the form of a binary structure that contains the relevant information for the specific command, with the structure being validated and only then launching the appropriate command. The below figure displays an example of the structure that contains information for adding/deleting DNS configuration:

Screenshot of code depicting the DNS configuration managing structure
Figure 3. OpenVPN DNS configuration managing structure

Additionally, openvpnserv.exe serves as the management unit, spawning openvpn.exe processes upon requests from different users on the machine. This can be done automatically using the OpenVPN GUI or by sending specifically crafted requests. Communication for this process occurs through a second named pipe, such as “openvpn/service”.

Openvpn.exe is the user mode process being spawned on behalf of the client. When openvpn.exe starts, it receives a path for a configuration file (as a command line argument). The configuration file that’s provided holds different information.

A lot of fields can be managed in configuration files, such as:

  1. Tunnel options
  2. Server mode options
  3. Client mode options

Plugin mechanism in openvpn.exe

Another mechanism of interest for us is the plugin mechanism in openvpn.exe, which can extend the functionality to add additional logic, such as authentication plugins to bring authentication against Lightweight Directory Access Protocol (LDAP) or Radius or other Pluggable Authentication Module
(PAM) backends. Some of the existing plugins are:

  1. Radiusplugin – Radius authentication support for open OpenVPN.
  2. Eurephia – Authentication and access control plugin for OpenVPN.
  3. Openvpn_defer_auth – OpenVPN plugin to perform deferred authentication requests.

The plugin mechanism fits into the earlier diagram, as shown in Figure 2.

The plugin is loaded as a directive in the configuration file, which looks like:

Screenshot of code depicting the client directive to load the plugin
Figure 4. OpenVPN client directive to load plugin

Furthermore, the number of callbacks defined in the plugin launch on behalf of the loading process (openvpn.exe), such as:

  1. openvpn_plugin_func_v1 – This function is called by OpenVPN each time the OpenVPN reaches a point where plugin calls should happen.
  2. openvpn_plugin_{open, func}_v3() – Defines the version of the v3 plugin argument.

OpenVPN security model

As previously mentioned, we discovered four vulnerabilities on the client side of OpenVPN’s architecture.

As described before, openvpnserv.exe (SYSTEM service) spawns the openvpn.exe process as a result of the request from the user. Furthermore, the spawned process runs in the context of the user who requested to create the new process, which is achieved through named pipe impersonation, as displayed in the below image:

Screenshot of code depicting named pipe impersonation
Figure 5. Named pipe impersonation

The ImpersonateNamedPipeClient function impersonates a named pipe client application.

Furthermore, to prevent unwanted behavior, specific EXPLICIT_ACCESS must be granted for any new process:

Screenshot of code depicting explicit access being granded for OVPN DACL
Figure 6. Explicit access for OVPN DACL

This explicit access, in addition to the earlier described “elevated commands” launched by openvpnserv.exe on request from the openvpn.exe process, and other comprehensive inspection of the passed arguments  ensure that malicious behavior cannot be launched in the name of the impersonated user.

Vulnerability analysis

CVE-2024-1305    

We identified a vulnerability in the “tap-windows6” project that involves developing the Terminal Access Point (TAP) adapter used by OpenVPN. In the project’s src folder, the device.c file contains the code for the TAP device object and its initialization.

In the device.c file, the CreateTapDevice method initializes a dispatch table object with callbacks for methods managing various Input/Output Controls (IOCTLs) for the device. One of these methods is TapDeviceWrite, which handles the write IOCTL.

Screenshot of code depicting where the wild kernel overflow vulnerability is located
Figure 7. Wild kernel overflow vulnerability location

The TapDeviceWrite method performs several operations and eventually calls TapSharedSendPacket. This method, in turn, calls NdisAllocateNetBufferAndNetBufferLists twice. In one scenario, it calls this function with the fullLength parameter, defined as follows:

Screenshot of code depicting the integer overflow
Figure 8. Integer overflow

Both PacketLength and PrefixLength are parameters passed from the TapDeviceWrite call and, therefore, attacker controlled. If these values are large enough, their sum (fullLength) can overflow (a 32-bit unsigned integer). This overflow results in the allocation of a smaller-than-expected memory size, which subsequently causes a memory overflow issue.

CVE-2024-27459  

The second vulnerability that we discovered resided in the communication mechanism between the openvpn.exe process and the openvpnserv.exe service. As described earlier, both of which communicate through a named pipe:

Screenshot of code depicting the size being read from a named pipe
Figure 9. Reading size from a named pipe

The openvpnserv.exe service will read the message size in an infinite loop from the openvpn.exe process and then handle the message received by calling the HandleMessage method. The HandleMessage method reads the size provided by the infinite loop and casts the read bytes into the relevant type accordingly:

Screenshot of code depicting the stack overflow vulnerability location
Figure 10. Stack overflow vulnerability location

This communication mechanism presents an issue as reading the “user” provided number of bytes on to an “n bytes” long structure located on the stack will produce a stack overflow vulnerability.

CVE-2024-24974  

The third vulnerability involves unprivileged access to an operating system resource. The openvpnserv.exe service spawns a new openvpn.exe process based on user requests received through the “\\openvpn\\service” named pipe. This vulnerability allows remote access to the named service pipe, enabling an attacker to remotely interact with and launch operations on it.

CVE-2024-27903  

Lastly, we identified a vulnerability in OpenVPN’s plugin mechanism that permits plugins to be loaded from various paths on an endpoint device. This behavior can be exploited by attackers to load harmful plugins from these different paths.

Exploiting and chaining the vulnerabilities

All the identified vulnerabilities can be exploited once an attacker gains access to a user’s OpenVPN credentials, which could be accomplished using credential theft techniques, such as purchasing stolen credentials on the dark web, using info-stealing malware, or sniffing network traffic to capture NTLMv2 hashes and then using cracking tools like HashCat or John the Ripper to decode them. The discovered vulnerabilities could then be combined to achieve different exploitation results, or chained together to form a sophisticated attack chain, as detailed in the below sections.

RCE exploitation

We first explored how an attacker could achieve remote code execution (RCE) exploitation using CVE-2024-24974 and CVE-2024-27903.

To successfully exploit these vulnerabilities and achieve RCE, an attacker must first obtain an OpenVPN user’s credentials. The attacker’s device must then launch the NET USE command with the stolen credentials to remotely access the operating system resources and grant the attacker access to the named pipes objects devices.

Next, the attacker can send a “connect” request to the “\\openvpn\\service” named pipe to launch a new instance of openvpn.exe on its behalf.

Screenshot of code depicting the initialization of OpenVPN from a remote location
Figure 11. Initializing OpenVPN from a remote location (in which {TARGET_MACHINE_PLACEHOLDER} can be substituted by a different end point)

In the request, a path to a configuration file (\\\\DESKTOP-4P6938I\\share\\OpenVPN\\config\\sample.ovpn) is specified that’s located on the attacker-controlled device. A log path is also provided into which the loaded plugin will write its logs (“–log \\\\\{TARGET_MACHINE_PLACEHOLDER}\\share\\OpenVPN\\log\\plugin_log.txt\).

The provided configuration has instructions to load malicious plugin, as such:

Screenshot of code depicting the malicious plugin loading directive from a remote location
Figure 12. Malicious plugin loading directive from a remote location

After successful exploitation, the attacker can read the log provided on the attacker-controlled device.

Screenshot of the plugin log on the attacker-controlled device
Figure 13. Plugin log on the attacker-controlled device

LPE exploitation

Next, we investigated how an attacker could achieve local privilege execution (LPE) using CVE-2024-27459 and CVE-2024-27903. To successfully achieve an LPE exploit in this context, an attacker must load a malicious plugin into the normal launching process of openvpn.exe by using a malicious configuration file.

First, the attacker will connect to a local device “\\openvpn\\service” named pipe with a command that instructs openvpnserv.exe to launch openvpn.exe based on the attacker-provided malicious configuration.

Screenshot of code depicting initializing OpenVPN from a local configuration
Figure 14. Initializing OpenVPN from a local configuration

The malicious configuration will include a line like the below example:

Screenshot of the malicious plugin loading directive from the local location
Figure 15. Malicious plugin loading directive from the local location

For the malicious plugin to successfully communicate with openvpnserv.exe, it must hijack the number of the handle used by openvpn.exe to communicate with the inner named pipe connecting the openvpv.exe process and the openvpnserv.exe service. This can be achieved, for instance, by parsing command line arguments, as displayed below:

Screenshot of code depicting parsing command line arguments to extract the thread ID
Figure 16. Parsing command line arguments to extract the thread ID (TID)

This works because when the openvpn.exe process spawns, it’s being passed the TID (as a command line argument) that the inner named pipe (which is being used for communication between this specific OpenVPN instance and the openvpnserv.exe service) will have. For instance, if the inner named pipe created is “\\openvpn\\service_1234” then openvpn.exe will be launched with an extra argument of 1234.

Screenshot of code depicting the thread ID being passed as a command line argument
Figure 17. Passing the TID as a command line argument

Next, attackers can exploit the stack overflow vulnerability by sending data bigger than the MSG structure. It is important to note that there are stack protection mechanisms in place, called stack canaries, which make exploitation much more challenging. Thus, when triggering the overflow:

Screenshot of code depicting the stack overflow being triggered
Figure 18. Stack overflow triggered

After the crash of openvpnserv.exe, the attacker has a slot of time in which they can reclaim the named pipe “\\openvpn\\service”.

If successful, the attacker then poses as the server client side of the named pipe “\\openvpn\\service”. From that moment on, every attempt to connect to the “\\openvpn\\service” named pipe will result in a connection to the attacker. If a privileged enough user, such as a SYSTEM or Administrator user, is connected to the named pipe, the attacker can impersonate that user:

Screenshot of code depicting impersonation of a privileged user
Figure 19. Impersonating a privileged user

The attacker can then start an elevated process on the user’s behalf, thus achieving LPE.

Chaining it all together

As our research demonstrated, an attacker could leverage at least three of the four discovered vulnerabilities to create exploits to achieve RCE and LPE, which could then be chained together to create a powerful attack chain.

A number of adjustments are needed for the full attack chain to be exploited as presented in this blog post, mainly the malicious payload that crashes openvpnserv.exe and the malicious payload that actually behaves as openvpnserv.exe after openvpnserv.exe is crashed all have to be loaded with the malicious plugin. After successfully achieving LPE, attackers will use different techniques, such as Bring Your Own Vulnerable Driver (BYOVD) or exploiting known vulnerabilities, to achieve a stronger grasp of the endpoint. Through these techniques, the attacker can, for instance, disable Protect Process Light (PPL) for a critical process such as Microsoft Defender or bypass and meddle with other critical processes in the system. These actions enable attackers to bypass security products and manipulate the system’s core functions, further entrenching their control and avoiding detection.

Critical importance of endpoint security in private and enterprise sectors

With OpenVPN being widely used across various vendors, industries, and fields, the presented vulnerabilities may impact numerous sectors, device types, and verticals. Exploiting these vulnerabilities requires user authentication, a deep understanding of OpenVPN’s inner workings, and intermediate knowledge of the operating system. However, a successful attack could significantly impact endpoints in both the private and enterprise sectors. Attackers could launch a comprehensive attack chain on a device using a vulnerable version of OpenVPN, achieving full control over the target endpoint. This control could enable them to steal sensitive data, tamper with it, or even wipe and destroy critical information, causing substantial harm to both private and enterprise environments.

The discovery of these vulnerabilities underscores the importance of responsible disclosure to secure enterprise and endpoint systems, in addition to the collective efforts of the security community to protect devices across various platforms and establish stronger safeguards for everyone. We would like to again thank OpenVPN for their partnership and swift action in addressing these vulnerabilities.

Mitigation and protection guidance

OpenVPN versions prior to 2.5.10 and 2.6.10 are vulnerable to discussed vulnerabilities.

It is recommended to first identify if a vulnerable version is installed and, if so, immediately apply the relevant patch found here: OpenVPN 2.6.10.

Additionally, follow the below recommendations to further mitigate potential exploitation risks affiliated with the discovered vulnerabilities:

  • Apply patches to affected devices in your network. Check the OpenVPN website for the latest patches.
  • Make sure OpenVPN clients are disconnected from the internet and segmented.
  • Limit access to OpenVPN clients to authorized users only. 
  • Due to the nature of the CVEs, which still require a username and password, prioritizing patching is difficult. Reduce risk by ensuring proper segmentation, requiring strong usernames and passwords, and reducing the number of users that have writing authentication.

Microsoft Defender XDR detections

Microsoft Defender for Endpoint

The following Microsoft Defender for Endpoint alert can indicate associated threat activity:

  • Suspicious OpenVPN named pipe activity

Microsoft Defender Vulnerability Management

Microsoft Defender Vulnerability Management surfaces devices that may be affected by the following vulnerabilities used in this threat:

  • CVE-2024-27459
  • CVE-2024-24974
  • CVE-2024-27903
  • CVE-2024-1305

Microsoft Defender for IoT

Microsoft Defender for IoT raises alerts for the following vulnerabilities, exploits, and behavior associated with this threat:

  • Suspicion of Malicious Activity

Hunting queries

Microsoft Defender XDR

Microsoft Defender XDR customers can run the following query to find related activity in their networks:

This query identifies connection to OpenVPN’s named pipe from remote host:

DeviceEvents  
| where ActionType == "NamedPipeEvent"
| extend JsonAdditionalFields=parse_json(AdditionalFields)
| extend PipeName=JsonAdditionalFields["PipeName"]
| where PipeName == "\\Device\\NamedPipe\\openvpn\\service" and isnotempty( RemoteIP) 

This query identifies image load into OpenVPN’s process from share folder:

DeviceImageLoadEvents 
|where InitiatingProcessFileName == "openvpn.exe" and FolderPath startswith "\\\\"

This query identifies process connect to OpenVPN’s named pipe as server which it is not openvpnserv.exe:

DeviceEvents  
| where ActionType == "NamedPipeEvent"
| extend JsonAdditionalFields=parse_json(AdditionalFields)
| extend PipeName=JsonAdditionalFields["PipeName"], NamedPipeEnd=JsonAdditionalFields["NamedPipeEnd"]
|where PipeName == "\\Device\\NamedPipe\\openvpn\\service" and NamedPipeEnd == "Server" and InitiatingProcessFileName != "openvpnserv.exe"

Microsoft Sentinel

Microsoft Sentinel customers can use the TI Mapping analytics (a series of analytics all prefixed with ‘TI map’) to automatically match the malicious domain indicators mentioned in this blog post with data in their workspace. If the TI Map analytics are not currently deployed, customers can install the Threat Intelligence solution from the Microsoft Sentinel Content Hub to have the analytics rule deployed in their Sentinel workspace. More details on the Content Hub can be found here:  https://learn.microsoft.com/azure/sentinel/sentinel-solutions-deploy.

List of devices with OpenVPN vulnerabilities

DeviceTvmSoftwareVulnerabilities
| where OSPlatform contains "Windows"
| where CveId in ("CVE-2024-27459","CVE-2024-24974","CVE-2024-27903","CVE-2024-1305") 
| project DeviceId,DeviceName,OSPlatform,OSVersion,SoftwareVendor,SoftwareName,SoftwareVersion,
CveId,VulnerabilitySeverityLevel
| join kind=inner ( DeviceTvmSoftwareVulnerabilitiesKB | project CveId, CvssScore,IsExploitAvailable,VulnerabilitySeverityLevel,PublishedDate,VulnerabilityDescription,AffectedSoftware ) on CveId
| project DeviceId,DeviceName,OSPlatform,OSVersion,SoftwareVendor,SoftwareName,SoftwareVersion,
CveId,VulnerabilitySeverityLevel,CvssScore,IsExploitAvailable,PublishedDate,VulnerabilityDescription,AffectedSoftware

Named pipe creation activity of OpenVPN

let PipeNames = pack_array('\\openvpn/service','\\openvpn/service_','openvpn','openvpn/service','\\openvpn\\service_');
DeviceEvents
| where TimeGenerated > ago(30d)
| where ActionType == "NamedPipeEvent"
| where ProcessCommandLine contains "openvpn.exe" or InitiatingProcessCommandLine contains "openvpn.exe"
| extend Fields=parse_json(AdditionalFields)
| where Fields.FileOperation == "File created"
| where Fields.PipeName has_any (PipeNames)
| project TimeGenerated,ActionType,DeviceName,InitiatingProcessAccountDomain,InitiatingProcessAccountName,InitiatingProcessFolderPath,
InitiatingProcessCommandLine,ProcessCommandLine,Fields.FileOperation,Fields.PipeName

Vladimir Tokarev

Microsoft Threat Intelligence Community

References

Learn more

For the latest security research from the Microsoft Threat Intelligence community, check out the Microsoft Threat Intelligence Blog: https://aka.ms/threatintelblog.

To get notified about new publications and to join discussions on social media, follow us on LinkedIn at https://www.linkedin.com/showcase/microsoft-threat-intelligence, and on X (formerly Twitter) at https://twitter.com/MsftSecIntel.

To hear stories and insights from the Microsoft Threat Intelligence community about the ever-evolving threat landscape, listen to the Microsoft Threat Intelligence podcast: https://thecyberwire.com/podcasts/microsoft-threat-intelligence.

The post Chained for attack: OpenVPN vulnerabilities discovered leading to RCE and LPE appeared first on Microsoft Security Blog.

]]>
“Dirty stream” attack: Discovering and mitigating a common vulnerability pattern in Android apps http://approjects.co.za/?big=en-us/security/blog/2024/05/01/dirty-stream-attack-discovering-and-mitigating-a-common-vulnerability-pattern-in-android-apps/ Wed, 01 May 2024 18:00:00 +0000 Microsoft discovered a vulnerability pattern in multiple popular Android applications that could enable a malicious application to overwrite files in the vulnerable application’s internal data storage directory, which could lead to arbitrary code execution and token theft, among other impacts. We have shared our findings with Google’s Android Application Security Research team, as well as the developers of apps found vulnerable to this issue. We anticipate that the vulnerability pattern could be found in other applications. We’re sharing this research more broadly so developers and publishers can check their apps for similar issues, fix as appropriate, and prevent them from being introduced into new apps or releases.

The post “Dirty stream” attack: Discovering and mitigating a common vulnerability pattern in Android apps appeared first on Microsoft Security Blog.

]]>
Microsoft discovered a path traversal-affiliated vulnerability pattern in multiple popular Android applications that could enable a malicious application to overwrite files in the vulnerable application’s home directory. The implications of this vulnerability pattern include arbitrary code execution and token theft, depending on an application’s implementation. Arbitrary code execution can provide a threat actor with full control over an application’s behavior. Meanwhile, token theft can provide a threat actor with access to the user’s accounts and sensitive data.

We identified several vulnerable applications in the Google Play Store that represented over four billion installations. We anticipate that the vulnerability pattern could be found in other applications. We’re sharing this research so developers and publishers can check their apps for similar issues, fix as appropriate, and prevent introducing such vulnerabilities into new apps or releases.  As threats across all platforms continue to evolve, industry collaboration among security researchers, security vendors, and the broader security community is essential in improving security for all. Microsoft remains committed to working with the security community to share vulnerability discoveries and threat intelligence to protect users across platforms.

After discovering this issue, we identified several vulnerable applications. As part of our responsible disclosure policy, we notified application developers through Coordinated Vulnerability Disclosure (CVD) via Microsoft Security Vulnerability Research (MSVR) and worked with them to address the issue. We would like to thank the Xiaomi, Inc. and WPS Office security teams for investigating and fixing the issue. As of February 2024, fixes have been deployed for the aforementioned apps, and users are advised to keep their device and installed applications up to date.

Recognizing that more applications could be affected, we acted to increase developer awareness of the issue by collaborating with Google to publish an article on the Android Developers website, providing guidance in a high-visibility location to help developers avoid introducing this vulnerability pattern into their applications. We also wish to thank Google’s Android Application Security Research team for their partnership in resolving this issue.

In this blog post, we continue to raise developer and user awareness by giving a general overview of the vulnerability pattern, and then focusing on Android share targets, as they are the most prone to these types of attacks. We go through an actual code execution case study where we demonstrate impact that extends beyond the mobile device’s scope and could even affect a local network. Finally, we provide guidance to users and application developers and illustrate the importance of collaboration to improve security for all.

Overview: Data and file sharing on Android

The Android operating system enforces isolation by assigning each application its own dedicated data and memory space. To facilitate data and file sharing, Android provides a component called a content provider, which acts as an interface for managing and exposing data to the rest of the installed applications in a secure manner. When used correctly, a content provider provides a reliable solution. However, improper implementation can introduce vulnerabilities that could enable bypassing of read/write restrictions within an application’s home directory.

The Android software development kit (SDK) includes the FileProvider class, a subclass of ContentProvider that enables file sharing between installed applications. An application that needs to share its files with other applications can declare a FileProvider in its app manifest and declare the specific paths to share.

Every file provider has a property called authority, which identifies it system-wide, and can be used by the consumer (the app that wants to access the shared files) as a form of address. This content-based model bears a strong resemblance to the web model, but instead of the http scheme, consumers utilize the content scheme along with the authority, followed by a pseudo-path to the file that they want to access.

For example, assuming that the application com.example.server shares some files under the file:///data/data/com.example.server/fileshttps://www.microsoft.com/images directory that it has previously declared as shared using the name shared_images, a consumer can use the content://[authority]/shared_images/[sub-path]/[filename] URI to index these files.

Access is given by the data sharing application most commonly using the grantUriPermissions attribute of the Android manifest, in combination with special flags that are used to define a read or write mode of operation. The data sharing application creates and sends an intent to the consumer that provides temporary fine-grained access to a file.  Finally, when a provider receives a file access request, it resolves the actual file path that corresponds to the incoming URI and returns a file descriptor to it.  

Implementation pitfalls

This content provider-based model provides a well-defined file-sharing mechanism, enabling a serving application to share its files with other applications in a secure manner with fine-grained control. However, we have frequently encountered cases where the consuming application doesn’t validate the content of the file that it receives and, most concerning, it uses the filename provided by the serving application to cache the received file within the consuming application’s internal data directory. If the serving application implements its own malicious version of FileProvider, it may be able to cause the consuming application to overwrite critical files.

Share targets

In simple terms, a share target is an Android app that declares itself to handle data and files sent by other apps. Common application categories that can be share targets include mail clients, social networking apps, messaging apps, file editors, browsers, and so on. In a common scenario, when a user clicks on a file, the Android operating system triggers the share-sheet dialog asking the user to select the component that the file should be sent to:

Android share sheet dialog displaying apps such as OneDrive, OneNote, Outlook, and others.
Figure 1. The Android share sheet dialog

While this type of guided file-sharing interaction itself may not trigger a successful attack against a share target, a malicious Android application can create a custom, explicit intent and send a file directly to a share target with a malicious filename and without the user’s knowledge or approval. Essentially, the malicious application is substituting its own malicious FileProvider implementation and provides a filename that is improperly trusted by the consuming application.

Diagram displaying the distry stream attack steps between the malicious app and a share target APK. First, the request to process file is sent to the APK, which replies with a request for the file name. The malicious app replies with the name, the APK allows it, granting the malicious app the ability to deliver the final malicious payload.
Figure 2. Dirty stream attack

In Figure 2, the malicious app, on the left, creates an explicit intent that targets the file processing component of the share target, on the right, and attaches a content URI as an intent’s extra. It then sends this intent to the share target using the startActivity API call.

After this point, most of the share targets that we have reviewed seem to follow a specific code pattern that includes the following steps:

  1. Request the actual filename from the remote file provider
  2. Use this filename to initialize a file that is subsequently used to initialize a file output stream
  3. Create an input stream using the incoming content URI
  4. Copy the input stream to the output stream

Since the rogue app controls the name as well as the content of the file, by blindly trusting this input, a share target may overwrite critical files in its private data space, which may lead to serious consequences.

Impact

We identified this vulnerability pattern in the then-current versions of several Android applications published on the Google Play Store, including at least four with more than 500 million installations each. In each case, we responsibly disclosed to the vendor. Two example vulnerable applications that we identified are Xiaomi Inc.’s File Manager (1B+ installs) and WPS Office (500M+ installs).

In Xiaomi Inc.’s File Manager, we were able to obtain arbitrary code execution in version V1-210567. After our disclosure, Xiaomi published version V1-210593, and we verified that the vulnerability has been addressed. In WPS Office, we were able to obtain arbitrary code execution in version 16.8.1. After our disclosure, WPS published and informed us that the vulnerability has been addressed as of version 17.0.0.

The potential impact varies depending on implementation specifics. For example, it’s very common for Android applications to read their server settings from the shared_prefs directory. In such cases, the malicious app can overwrite these settings, causing the vulnerable app to communicate with an attacker-controlled server and send the user’s authentication tokens or other sensitive information.

In a worst-case (and not so uncommon) scenario, the vulnerable application might load native libraries from its data directory (as opposed to the more secure /data/app-lib directory, where the libraries are protected from modification). In this case, the malicious application can overwrite a native library with malicious code that gets executed when the library is loaded. In the following section, we use Xiaomi Inc.’s File Manager to illustrate this case. We demonstrated the ability for a malicious application to overwrite the application’s shared preferences, write a native library to the application’s internal storage, and cause the application to load the library. These actions provided arbitrary code execution with the file manager’s user ID and permissions.

In the following sections, we focus on this case and delve into the technical details of this vulnerability pattern.

Case study: Xiaomi Inc.’s File Manager

Xiaomi Inc.’s File Manager is the default file manager application for Xiaomi devices and is published under the package name com.mi.android.globalFileexplorer on the Google Play Store, where it has been installed over one billion times.

Xiaomi’s File Manager profile according to Android rank
Figure 3. Xiaomi’s File Manager profile according to Android rank (source: File Manager)

Besides having full access to the device’s external storage, the application requests many permissions, including the ability to install other applications:

Screenshot of code displaying the app's permissions
Figure 4. A snapshot of the application’s permissions

Further, it offers a junk files cleaner plugin as well as the ability to connect to remote FTP and SMB shares:

Screenshot of using the file manager to connect to remote shares.
Figure 5. Connecting to remote shares using the file manager

Vulnerability assessment findings

During our investigation, we identified that the application exports the CopyFileActivity, an activity alias of the com.android.fileexplorer.activity.FileActivity, which is used to handle copy-from-to file operations:

Screenshot of the copy to CopyFileActivity event.
Figure 6. Triggering the copy to CopyFileActivity

Since this activity is exported, it can be triggered by any application installed on the same device by using an explicit intent of action SEND or SEND_MULTIPLE and attaching a content URI corresponding to a file stream.

Upon receiving such an intent, the browser performs a validity check, which we found to be insufficient:

Screenshot of code displaying the steps for validating an incoming copy file request.
Figure 7. Validating an incoming copy file request

As depicted above, the initCopyOrMoveIntent method calls the checkValid method passing as an argument a content URI (steps 1 and 2). However, the checkValid method is designed to handle a file path, not a content URI. It always returns true for a content URI. Instead, a safer practice is to parse the string as a URI, including ensuring the scheme is the expected value (in this case, file, not content).The checkValid method verifies that the copy or move operation doesn’t affect the private directory of the app, by initializing a file object using the incoming string as an argument to the File class constructor and comparing its canonical path with the path that corresponds to the home directory of the application (steps 3 and 4). Given a content URI as a path, the File constructor normalizes it (following a Unix file system normalization), thus the getCanonicalPath method returns a string starting with “/content:/“, which will always pass the validity check. More specifically, the app performs a query to the remote content provider for the _size, _display_name and _data columns (see line 48 below). Then it uses the values returned by these rows to initialize the fields of an object of the com.android.fileexplorer.mode.c class:

Screenshot of code getting file metadata from the remote content provider.
Figure 8. Getting file metadata from the remote content provider

Given the case that the _display_name and _data values, returned from the external file provider, are relative paths to the destination directory, after exiting from the method above, these class fields will contain values like the ones depicted below:

Screenshot of code displaying the file model initialized after calling method a
Figure 9. The file model initialized after calling the method a

As shown above, the paths (variables d and e) of this file-model point to files within the home directory of the application, thus the file streams attached to the incoming intent are going to be written under the specific locations.

Getting code execution

As previously mentioned, the application uses a plugin to clean the device’s junk files:

Screenshot of the junk files cleaner plugin user interface
Figure 10. The junk files cleaner plugin user interface

When the application loads this plugin, it makes use of two native libraries: libixiaomifileu.so, which fetches from the /data/app directory, and libixiaomifileuext.so from the home directory:

Screenshot of code displaying the loaded native libraries traced using medusa
Figure 11. Tracing the loaded native libraries using medusa

As apps don’t have write access to the /data/app folder, the libixiaomifileu.so file stored there cannot be replaced. The easiest way to get code execution is to replace the libixiaomifileuext.so with a malicious one. However, an attempt to do so would fail since in this particular case, the vulnerability that we described can only be used to write new files within the home directory, not overwrite existing files. Our next inquiry was to determine how the application loads the libixiaomifileu.so.

Our assessment showed that before the application loads this library, it follows the following steps:

  1. Calculate the hash of the file libixiaomifileu.so, located in the /data/app directory
  1. Compare this hash with the value assigned to the “libixiaomifileu.so_hm5” string, fetched from the com.mi.android.globalFileexprorer_preferences.xml file
Screenshot of code displaying the com.mi.android.globalFileexprorer_preferences.xml
Figure 12. the com.mi.android.globalFileexprorer_preferences.xml
  1. If the values don’t match, search for the libixiaomifileu.so file in the /files/lib path in the home directory
  1. If the file is found there, calculate its hash and compare it again with the value from the shared_preferences folder
  1. If the hashes match, load the file under the /files/lib using the System.load method

Given this behavior, in order to get code execution with the file manager’s user ID, an attacker must take the following steps:

  1. Use the path traversal vulnerability to save a malicious library as /files/lib/libixiaomifileu.so (the file does not already exist in that directory, so overwriting is not an issue)
  1. Calculate the hash of this library to replace the value of the libixiaomifileu.so_hm5 string
  1. Trigger the junk cleaner plugin with an explicit intent, since the activity that loads the native libraries is exported

An acute reader might have noticed that the second step requires the attacker to force the browser to overwrite the com.mi.android.globalFileexprorer_preferences.xml, which, as we already mentioned, was not possible.

To overcome this restriction, we referred to the actual implementation of the SharedPreferences class, where we found that when an Android application uses the getSharedPreferences API method to retrieve an instance of the SharedPreferences class, giving the name of the shared preferences file as an argument, then the constructor of the SharedPreferencesImpl class performs the following steps:

  1. Create a new file object using the name provided to the getSharedPreferences method, followed by the .xml extension, followed by the .bak extension
  1. Check if this file exists, and in case it does, delete the original xml file and replace it with the one created in the first step

Through this behavior, we were able to save the com.mi.android.globalFileexprorer_preferences.xml.bak under the shared preferences folder (as during the application’s runtime it is unlikely to exist), so when the app tried to verify the hash, the original xml file was already replaced by our own copy. After this point, by using a single intent to start the junk cleaner plugin, we were able to trick the application to load the malicious library instead of the one under the /data/app folder and get code execution with the browser’s user ID.

Impact

One reason we chose to use this app as a showcase is because the impact extends beyond the user’s mobile device. The application gives the option to connect to remote file shares using the FTP and SMB protocols and the user credentials are saved in clear text in the /data/data/com.mi.android.globalFileexplorer/files/rmt_i.properties file:

Screenshot of code displaying the SMB or FTP credentials being saved in clear text
Figure 13. SMB/FTP credentials saved in clear text

If a third party app was able to exploit this vulnerability and obtain code execution, an attacker could retrieve these credentials. The impact would then extend even further, since by the time that a user requests to open a remote share, the browser creates the directory /sdcard/Android/data/com.mi.android.globalFileexplorer/files/usbTemp/ where it saves the files that the user retrieves:

Screenshot of code displaying the SMB shared files saved in the external storage
Figure 14. SMB shared files, saved in the external storage

This means that a remote attacker would be able to read or write files to SMB shares of a local network, assuming that the device was connected to it. The same stands for FTP shares as they are handled exactly in the same way:

Screenshot of code displaying the FTP shared files saved in the external storage
Figure 15. FTP shared files, saved in the external storage

In summary, the exploitation flow is depicted in the figure below:

Diagram displaying how the attacker obtains remote access to local shares, as further detailed in text.
Figure 16. Getting remote access to local shares

In step 1, the user opens a malicious app that may pose as a file editor, messaging app, mail client, or any app in general and request the user to save a file. By the time that the user attempts to save such a file, no matter what destination path they choose to save it, the malicious app forces the file browser app to write it under its internal /files/lib folder. Then, the malicious app can start the junk cleaner using an explicit intent (no user interaction is required) and this will lead to code execution with the browser’s ID (step 2).

In step 3, the attacker uses the arbitrary code execution capability to retrieve the SMB and FTP credentials from the rmt_i.properties file. Subsequently, the attacker can now jump to step 5 and access the shares directly using the stolen credentials. Alternatively, after retrieving the share credentials, the mobile device can connect to a local network (step 4) and access an SMB or FTP share, allowing the attacker to access the shared files through the /sdcard/Android/data/com.mi.android.globalFileexplorer/files/usbTemp/ folder (step 5).

Recommendations

Recognizing that this vulnerability pattern may be widespread, we shared our findings with Google’s Android Application Security Research team. We collaborated with Google to author guidance for Android application developers to help them recognize and avoid this pattern. We recommend developers and security analysts familiarize themselves with the excellent Android application security guidance provided by Google as well as make use of the Android Lint tool included with the Android SDK and integrated with Android Studio (supplemented with Google’s additional security-focused checks) to identify and avoid potential vulnerabilities. GitHub’s CodeQL also provides capabilities to identify vulnerabilities.

To prevent these issues, when handling file streams sent by other applications, the safest solution is to completely ignore the name returned by the remote file provider when caching the received content. Some of the most robust approaches we encountered use randomly generated names, so even in the case that the content of an incoming stream is malformed, it won’t tamper with the application.

In cases where such an approach is not feasible, developers need to take extra steps to ascertain that the cached file is written to a dedicated directory. As an incoming file stream is usually identified by a content URI, the first step is to reliably identify and sanitize the corresponding filename. Besides filtering characters that may lead to a path traversal and before performing any write operation, developers must verify that the cached file is within the dedicated directory by performing a call to the File.getCanonicalPath and validating the prefix of the returned value.

Another area to safeguard is in the way developers try to extract a filename from a content URI. Developers often use Uri.getLastPathSegment(), which returns the (URL) decoded value of the last path URI segment. An attacker can craft a URI with URL encoded characters within this segment, including characters used for path traversal. Using the returned value to cache a file can again render the application vulnerable to this type of attack.

For end users, we recommend keeping mobile applications up to date through the Google Play Store (or other appropriate trusted source) to ensure that updates addressing known vulnerabilities are installed. Users should only install applications from trusted sources to avoid potentially malicious applications. We recommend users who accessed SMB or FTP shares through the Xiaomi app before updates to reset credentials and to investigate for any anomalous behavior. Microsoft Defender for Endpoint on Android can alert users and enterprises to malicious applications, and Microsoft Defender Vulnerability Management can identify installed applications with known vulnerabilities.

Dimitrios Valsamaras

Microsoft Threat Intelligence

References

Learn more

For the latest security research from the Microsoft Threat Intelligence community, check out the Microsoft Threat Intelligence Blog: https://aka.ms/threatintelblog.

To get notified about new publications and to join discussions on social media, follow us on LinkedIn at https://www.linkedin.com/showcase/microsoft-threat-intelligence, and on X (formerly Twitter) at https://twitter.com/MsftSecIntel.

To hear stories and insights from the Microsoft Threat Intelligence community about the ever-evolving threat landscape, listen to the Microsoft Threat Intelligence podcast: https://thecyberwire.com/podcasts/microsoft-threat-intelligence.

The post “Dirty stream” attack: Discovering and mitigating a common vulnerability pattern in Android apps appeared first on Microsoft Security Blog.

]]>
Social engineering attacks lure Indian users to install Android banking trojans http://approjects.co.za/?big=en-us/security/blog/2023/11/20/social-engineering-attacks-lure-indian-users-to-install-android-banking-trojans/ Tue, 21 Nov 2023 04:30:00 +0000 Microsoft has observed ongoing activity from mobile banking trojan campaigns targeting users in India with social media messages and malicious applications designed to impersonate legitimate organizations and steal users’ information for financial fraud scams.

The post Social engineering attacks lure Indian users to install Android banking trojans appeared first on Microsoft Security Blog.

]]>
Microsoft has observed ongoing activity from mobile banking trojan campaigns targeting users in India with social media messages designed to steal users’ information for financial fraud. Using social media platforms like WhatsApp and Telegram, attackers are sending messages designed to lure users into installing a malicious app on their mobile device by impersonating legitimate organizations, such as banks, government services, and utilities. Once installed, these fraudulent apps exfiltrate various types of sensitive information from users, which can include personal information, banking details, payment card information, account credentials, and more.

While not a new threat, mobile malware infections pose a significant threat to mobile users, such as unauthorized access to personal information, financial loss due to fraudulent transactions, loss of privacy, device performance issues due to malware consuming system resources, and data theft or corruption. In the past, we observed similar banking trojan campaigns sending malicious links leading users to download malicious apps, as detailed in our blog Rewards plus: Fake mobile banking rewards apps lure users to install info-stealing RAT on Android devices.

The current active campaigns have pivoted to sharing malicious APK files directly to mobile users located in India. Our investigation focused on two malicious applications that falsely present themselves as official banking apps. Spoofing and impersonating legitimate banks, financial institutions, and other official services is a common social engineering tactic for information-stealing malware. Importantly, legitimate banks themselves are not affected by these attacks directly, and the existence of these attacks is not related to legitimate banks’ own authentic mobile banking apps and security posture. That said, cybercriminals often target customers of large financial institutions by masquerading as a legitimate entity. This threat highlights the need for customers to install applications only from official app stores, and to be wary of false lures as we see in these instances.

In this blog, we shed light on the ongoing mobile banking trojan campaigns impacting various sectors by analyzing the attacks of two fraudulent apps targeting Indian banking customers. We also detail some of the additional capabilities of malicious apps observed in similar campaigns and provide recommendations and detections to defend against such threats. As our mobile threat research continuously monitors malware campaigns in the effort to combat attackers’ tactics, tools, and procedures (TTPs), we notified the organizations being impersonated by these fake app campaigns. Microsoft is also reporting on this activity to bring increased awareness to the threat landscape as mobile banking trojans and credential phishing fraud continues to persist, prompting an urgent call for robust and proactive defense strategies.

Case 1: Fake banking app targeting account information

We discovered a recent WhatsApp phishing campaign through our telemetry that led to banking trojan activity. In this campaign, the attacker shares a malicious APK file through WhatsApp with a message asking users to enter sensitive information in the app. The widely circulated fake banking message states “Your [redacted] BANK Account will be Blocked Today please update your PANCARD immediately open [redacted]-Bank.apk for update your PANCARD. Thank You.” and includes a APK file named [redacted]-BANK[.]apk. 

Screenshot of a fake WhatsApp phishing message asking users to update KYC using a APK file.
Figure 1. A fake WhatsApp message sent to user to update KYC using shared APK file.

Upon investigation, we discovered that the APK file was malicious and interacting with it installs a fraudulent application on the victim device. The installed app impersonates a legitimate bank located in India and disguises itself as the bank’s official Know Your Customer (KYC) application to trick users into submitting their sensitive information, despite this particular banking organization not being affiliated with an official KYC-related app. This information is then sent to a command and control (C2) server, as well as to the attacker’s hard-coded phone number used in SMS functionality.

Diagram of the attack flow depicting how an attacker sends an SMS or social media message and a malicious APK file to users that users download and install onto devices. The APK file then installs a fraudulent app impersonating a legitimate banking organization and requests the user's KYC information, bank account details, and credentials, which are submitted and sent to the attacker's C2 server and hard-coded phone number.
Figure 2. The attack flow of this campaign.

What users see

Upon installation, the fake app displays a bank icon posing as a legitimate bank app. Note that the app we analyzed is not an official bank app from the Google Play Store, but a fake app that we’ve observed being distributed through social media platforms.  

The initial screen then proceeds to ask the user to enable SMS-based permissions. Once the user allows the requested permissions, the fake app displays the message “Welcome to [redacted] Bank fast & Secure Online KYC App” and requests users to signin to internet banking by entering their mobile number, ATM pin, and PAN card details.

Four mobile screenshots from left to right: the fake WhatsApp message, an icon in the app tray displaying a legitimate bank icon, the fake app requesting SMS permissions, and the fake app requesting users' to submit their banking, mobile number, ATM pin, and PAN card information.
Figure 3. Once installed on a device, the fake app asks users to allow SMS permissions and to sign-in to internet banking and submit their mobile number, ATM pin, and PAN card to update KYC. 

After clicking the sign-in button, the app displays a verification prompt asking the user to enter the digits on the back of their banking debit card in grid format for authentication—a common security feature used as a form of multifactor authentication (MFA), where banks provide debit cards with 2-digit numbers in the form of a grid on the back of the card. Once the user clicks the authenticate button, the app claims to verify the shared details but fails to retrieve data, instead moving on to the next screen requesting additional user information. This can trick the user into believing that the process is legitimate, while remaining unaware of the malicious activity launching in the background.

Four mobile screenshots from left to right: the fake app appearing to authenticate users' bank information, the fake app requesting users' digits on the back of their debit card, user authenticating those digits, the fake app appearing to verify the information again.
Figure 4. The fake app’s authentication process asks the user to enter the correct digits as presented on their debit card.

Next, the user is asked to enter their account number followed by their account credentials. Once all the requested details are submitted, a suspicious note appears stating that the details are being verified to update KYC. The user is instructed to wait 30 minutes and not to delete or uninstall the app. Additionally, the app has the functionality to hide its icon, causing it to disappear from the user’s device home screen while still running in the background.

Four mobile screenshots from left to right: the fake app requesting users' account numbers followed by their credentials, the fake app displays a phony note that the entered information is being verified, the fake app's icon disappears from the user's app tray.
Figure 5. The fraudulent app steals the user’s account number and credentials and hides its icon from the home screen.

Technical analysis

To start our investigation and as part of our proactive research, we located and analyzed the following sample:

SHA-2566812a82edcb49131a990acd88ed5f6d73da9f536b60ee751184f27265ea769ee 
Package namedjhgsfjhfdgf[.]gjhdgsfsjde[.]myappl876786ication

We first examined the app’s AndroidManifest file, which lists the permissions and components (such as activities, services, receivers, and providers) that can run in the background without requiring user interaction. We discovered that the malware requests two runtime permissions (also known as dangerous permissions) from users: 

Permissions Description 
Receive_SMS Intercept SMSs received on the victim’s device 
Send_SMS Allows an application to send SMS 

The below image displays the requested Receive_SMS and Send_SMS permissions, the activities, receivers, and providers used in the application, and the launcher activity, which loads the application’s first screen. 

Screenshot of code displaying the AndroidManifest.xml file, noting the package name, permissions used, main activity class, and components used.
Figure 6. AndroidManifest.xml file

Source code review

Main activity

The main activity, djhgsfjhfdgf[.]gjhdgsfsjde[.]myappl876786ication[.]M1a2i3n4A5c6t7i8v9i0t0y987654321, executes once the app is launched and shows as the first screen of the application. The OnCreate() method of this class requests permissions for Send_SMS and Receive_SMS and displays a form to complete the KYC application with text fields for a user’s mobile number, ATM pin, and PAN card. Once the user’s details are entered successfully, the collected data is added to a JSON object and sent to the attacker’s C2 at: https://biogenetic-flake.000webhostapp[.]com/add.php

The app displays a note saying “Data added successfully”. If the details are not entered successfully, the form fields will be empty, and an error note will be displayed.

Screenshot of code displaying the launcher activity page, noting the requested permissions, requested information in the launcher activity, the data text fields for mobile number, ATM pin, and PAN card, the filled data sent to the attacker's C2 and the submitted details added to the attacker's C2.
Figure 7. Launcher activity page, asking the user to sign-in with their mobile number, ATM pin, and PAN card.  

Additionally, the malware collects data and sends it to the attacker’s phone number specified in the code using SMS. 

Screenshot of code displaying how collected information is also sent to the attacker's mobile number.
Figure 8. Collected data sent to the attacker’s mobile number as a SMS. 

Stealing SMS messages and account information

The malware collects incoming SMS messages from the victim’s device using the newly granted Receive_SMS permission. These incoming messages may contain one-time passwords (OTPs) that can be used to bypass MFA and steal money from the victim’s bank account. Using the Send_SMS permission, the victim’s messages are then sent to the attacker’s C2 server (https[:]//biogenetic-flake[.]000webhostapp[.]com/save_sms[.]php?phone=) and to the attacker’s hardcoded phone number via SMS.

Screenshot of code stealing incoming SMS to send to the attacker's C2 and mobile number.
Figure 9. Steals incoming SMS to send to the attacker’s C2 and mobile number via SMS.

The user’s bank account information is also targeted for exfiltration—once the user submits their requested account number and account credentials, the malware collects the data and similarly sends it to the attacker’s C2 server and hard-coded phone number. 

Screenshot of code collecting the user's account number to be sent to the attacker's C2 and mobile number.
Figure 10. Collecting the user’s account number to send to the attacker.
Screenshot of code collecting the user's account credentials to be sent to the attacker's C2 and mobile number.
Figure 11. Collecting the user’s account credentials to send to the attacker. 

Hiding app icon

Finally, the app has the functionality to hide its icon from the home screen and run in the background. 

Screenshot of code hiding the app's icon from the home screen and app tray.
Figure 12. Hides app icon from home screen 

Case 2: Fake banking app targeting payment card details

Similar to the first case, the second case involves a fraudulent app that deceives users into providing personal information. Unlike the first case, the banking trojan in the second case is capable of stealing credit card details, putting users at risk of financial fraud. User information targeted by the fraudulent app to be sent to the attacker’s C2 includes:

  • Personal information – Name, email ID, mobile number, date of birth
  • Payment information – Card details (16-digit number, CVV number, card expiration date) 
  • Incoming SMS 

What users see

When the user interacts with the app, it displays a launch screen featuring the app icon and prompting the user to grant SMS-based permissions. Once the requested permissions are enabled, the app displays a form for the user to enter their personal details, including their name, email address, mobile number, and date of birth. The data provided by the user is then sent to C2 server. After this, the app displays a form for the user to enter their credit card details, including the 16-digit card number, CVV number, and card expiration date, which is also sent to the attacker’s C2.

Three mobile screenshots from left to right: A fake app requesting SMS permissions, followed by requesting users' personal details, followed by their card details.
Figure 13. Fake app collects SMS permissions, personal details and card details.

Additional features in some versions

In related campaigns, we observed some versions of the same malicious app include additional features and capabilities, such as capturing:

  • Financial information – Bank details, bank ID, card details
  • Personal information – PAN card, Aadhar number, permanent address, state, country, pin code, income
  • Verifying and stealing one-time passwords (OTPs)

Similar campaigns

Based on our telemetry, we have been observing similar campaigns using the names of legitimate organizations in the banking, government services, and utilities sectors, as app file names to target Indian mobile users. Like the two cases discussed above, these campaigns involve sharing the fraudulent apps through WhatsApp and Telegram, and possibly other social media platforms. Moreover, these campaigns select legitimate and even well-known institutions and services in the region to imitate and lure users into a false sense of security. Spoofing and impersonating legitimate organizations and official services is a common social engineering tactic for information-stealing malware. While these banks and other organizations themselves are not affected by the attack directly, attackers often target customers by imitating legitimate entities.

Conclusion

Mobile banking trojan infections can pose significant risks to users’ personal information, privacy, device integrity, and financial security. As the campaigns discussed in this blog display, these threats can often disguise themselves as legitimate apps and deploy social engineering tactics to achieve their goals and steal users’ sensitive data and financial assets. Being aware of the risks and common tactics used by banking trojans and other mobile malware can help users identify signs of infection and take appropriate action to mitigate the impacts of these threats.

Finding unfamiliar installed apps, increased data usage or battery drain, unauthorized transactions or account settings changes, device crashes, slow performance, unexpected pop-ups, and other unusual app behaviors can indicate a possible banking trojan infection. To help prevent such threats, we recommend the following precautionary measures:

  • Only install apps from trusted sources and official stores, like the Google Play Store and Apple App Store.
  • Never click on unknown links received through ads, SMS messages, emails, or similar untrusted sources.
  • Use mobile solutions such as Microsoft Defender for Endpoint on Android to detect malicious applications
  • Always keep Install unknown apps disabled on the Android device to prevent apps from being installed from unknown sources.
Two mobile screenshots from left to right: Example of the Install unknown apps feature on an Android device, disabling the ability for WhatsApp to install unknown apps.
Figure 14. Example of the Install unknown apps feature on an Android device

Additionally, various Indian banks, governments services, and other organizations are conducting security awareness campaigns on social media using promotional videos to educate users and help combat the ongoing threat presented by these mobile banking trojan campaigns.

Abhishek Pustakala, Harshita Tripathi, and Shivang Desai

Microsoft Threat Intelligence

Appendix

Microsoft 365 Defender detections

Microsoft Defender Antivirus and Microsoft Defender for Endpoint on Android detect these threats as the following malware:

Indicators of compromise

SHA256 Description Threat Name
6812a82edcb49131a990acd88ed5f6d73da9f536b60ee751184f27265ea769eeMalicious APK Trojan:AndroidOS/Banker.U
34cdc6ef199b4c50ee80eb0efce13a63a9a0e6bee9c23610456e913bf78272a8Malicious APK TrojanSpy:AndroidOS/SpyBanker.Y

MITRE ATT&CK techniques

Execution Defense EvasionCredential AccessCollection Exfiltration  Impact
Scheduled Task/Job Obfuscated Files/InformationInput CaptureProtected User Data: SMS Messages Exfiltration Over C2 Channel  SMS Control
Hide Artifacts: Suppress Application Icon    

References

Acknowledgments

Further reading

For the latest security research from the Microsoft Threat Intelligence community, check out the Microsoft Threat Intelligence Blog: https://aka.ms/threatintelblog.

To get notified about new publications and to join discussions on social media, follow us on X (formerly)Twitter at https://twitter.com/MsftSecIntel.

The post Social engineering attacks lure Indian users to install Android banking trojans appeared first on Microsoft Security Blog.

]]>
Toll fraud malware: How an Android application can drain your wallet http://approjects.co.za/?big=en-us/security/blog/2022/06/30/toll-fraud-malware-how-an-android-application-can-drain-your-wallet/ Thu, 30 Jun 2022 14:00:00 +0000 Toll fraud malware, a subcategory of billing fraud in which malicious applications subscribe users to premium services without their knowledge or consent, is one of the most prevalent types of Android malware – and it continues to evolve.

The post Toll fraud malware: How an Android application can drain your wallet appeared first on Microsoft Security Blog.

]]>
Toll fraud malware, a subcategory of billing fraud in which malicious applications subscribe users to premium services without their knowledge or consent, is one of the most prevalent types of Android malware – and it continues to evolve.

Compared to other subcategories of billing fraud, which include SMS fraud and call fraud, toll fraud has unique behaviors. Whereas SMS fraud or call fraud use a simple attack flow to send messages or calls to a premium number, toll fraud has a complex multi-step attack flow that malware developers continue to improve.

For example, we saw new capabilities related to how this threat targets users of specific network operators. It performs its routines only if the device is subscribed to any of its target network operators. It also, by default, uses cellular connection for its activities and forces devices to connect to the mobile network even if a Wi-Fi connection is available. Once the connection to a target network is confirmed, it stealthily initiates a fraudulent subscription and confirms it without the user’s consent, in some cases even intercepting the one-time password (OTP) to do so. It then suppresses SMS notifications related to the subscription to prevent the user from becoming aware of the fraudulent transaction and unsubscribing from the service.

Another unique behavior of toll fraud malware is its use of dynamic code loading, which makes it difficult for mobile security solutions to detect threats through static analysis, since parts of the code are downloaded onto the device in certain parts of the attack flow. Despite this evasion technique, we’ve identified characteristics that can be used to filter and detect this threat. We also see adjustments in Android API restrictions and Google Play Store publishing policy that can help mitigate this threat.

Toll fraud has drawn media attention since Joker, its first major malware family, found its way to the Google Play Store back in 2017. Despite this attention, there’s not a lot of published material about how this type of malware carries out its fraudulent activities. Our goal for this blog post is to share an in-depth analysis on how this malware operates, how analysts can better identify such threats, and how Android security can be improved to mitigate toll fraud. This blog covers the following topics:

The WAP billing mechanism: An overview

To understand toll fraud malware, we need to know more about the billing mechanism that attackers use. The commonly used type of billing in toll fraud is Wireless Application Protocol (WAP). WAP billing is a payment mechanism that enables consumers to subscribe to paid content from sites that support this protocol and get charged directly through their mobile phone bill. The subscription process starts with the customer initiating a session with the service provider over a cellular network and navigating to the website that provides the paid service. As a second step, the user must click a subscription button, and, in some cases, receive a one-time password (OTP) that has to be sent back to the service provider to verify the subscription. The overall process is depicted below:

A diagram of how the Wireless Application Protocol billing process works. Interactions between the mobile device and premium service provider are mapped out, from the moment the device browses through services until the confirmation of service subscription.
Figure 1. The WAP billing process in a nutshell

It should be noted that the process depends on the service provider, thus not all steps are always present. For example, some providers do not require an OTP, which means that the mobile user can subscribe to a service by simply clicking the subscription button while the device is connected to a cellular network.  

Fraudulent subscriptions via toll fraud

We classify a subscription as fraudulent when it takes place without a user’s consent. In the case of toll fraud, the malware performs the subscription on behalf of the user in a way that the overall process isn’t perceivable through the following steps:

  1. Disable the Wi-Fi connection or wait for the user to switch to a mobile network
  2. Silently navigate to the subscription page
  3. Auto-click the subscription button
  4. Intercept the OTP (if applicable)
  5. Send the OTP to the service provider (if applicable)
  6. Cancel the SMS notifications (if applicable)

One significant and permissionless inspection that the malware does before performing these steps is to identify the subscriber’s country and mobile network through the mobile country codes (MCC) and mobile network codes (MNC). This inspection is done to target users within a specific country or region. Both codes can be fetched by using either the TelephonyManageror the SystemPropertiesclass. The TelephonyManager.getSimOperator() API call returns the MCC and MNCcodes as a concatenated string, while other functions of the same class can be used to retrieve various information about the mobile network that the device is currently subscribed to. As the network and SIM operator may differ (e.g., in roaming), the getSimOperatorfunction is usually preferred by malware developers.

The same type of information can be fetched by using the SystemProperties.get(String key) function where the key parameter may be one or several (using multiple calls) of the following strings: gsm.operator.numeric, gsm.sim.operator.numeric, gsm.operator.iso-country, gsm.sim.operator.iso-country, gsm.operator.alpha, gsm.sim.operator.alpha

The difference with the first call is that the android.os.SystemProperties class is marked as @SystemApi, therefore an application has to use Java reflection to invoke the function. The MNC and MCC codes are also used to evade detection, as the malicious activity won’t be performed unless the SIM operator belongs to the ones targeted:

A screenshot of code snippet from the Joker malware. The code specifies that the malware will only run if the device is under a South African mobile operator.
Figure 2. Joker malware running its payload, targeting South African mobile operators

The following sections present an analysis of the fraudulent subscription steps in the context of the Android operating system. This analysis can help identify the API calls and the permissions needed for the implementation of a toll fraud scheme.

Forcing cellular communication

Variants of toll fraud malware targeting Android API level 28 (Android 9.0) or lower disable the Wi-Fi by invoking the setWifiEnabled method of the WifiManager class. The permissions needed for this call are ACCESS_WIFI_STATE and CHANGE_WIFI_STATE. Since the protection level for both permissions is set to normal, they are automatically approved by the system.

Meanwhile, malware targeting a higher API level uses the requestNetwork function of the ConnectivityManagerclass. The Android developers page describes the requestNetwork method as:

This method will attempt to find the best network that matches the given NetworkRequest, and to bring up one that does if none currently satisfies the criteria. The platform will evaluate which network is the best at its own discretion. Throughput, latency, cost per byte, policy, user preference and other considerations may be factored in the decision of what is considered the best network.

The required permission for this call is either CHANGE_NETWORK_STATE (protection level: normal) or WRITE_SETTINGS(protection level: signature|preinstalled|appop|pre23), but since the latter is protected, the former is usually preferred by malware developers. In the code snippet depicted below from a malware sample that can perform toll fraud, the function vgy7is requesting a TRANSPORT_CELLULAR transport type (Constant Value: 0x00000000) with NET_CAPABILITY_INTERNET (Constant Value: 0x0000000c):

A screenshot of code snippet from a Joker malware where the malware requests for a TRANSPORT_CELLULAR transport type.
Figure 3. Code from a Joker malware sample requesting a TRANSPORT_CELLULAR transport type

Figure 3. Code from a Joker malware sample requesting a TRANSPORT_CELLULAR transport type

The NetworkCallbackis used to monitor the network status and retrieve a networktype variable that can be used to bind the process to a particular network via the ConnectivityManager.bindProcessToNetworkfunction. This allows the malware to use the mobile network even when there is an existing Wi-Fi connection. The proof-of-concept code depicted below uses the techniques described above to request a TRANSPORT_CELLULAR transport type. If the transport type is available, it binds the process to the mobile network to load the host at example.com in the application’s WebView:

A screenshot of proof-of-concept code to demonstrate a request for a TRANSPORT_CELLULAR transport type.
Figure 4. Proof-of-concept code to request a TRANSPORT_CELLULAR transport type

While it is expected that the Wi-Fi connection is preferred even when mobile connection is also available, the process exclusively uses the cellular network to communicate with the server:

A screenshot of two Android mobile browser screens, side by side. The browser screen on the left loads the content of example.com, while the browser screen on the right loads a blank page.
Figure 5. The mobile browser loads example.com when TRANSPORT_CELLULAR transport type is available and loads a blank page when only Wi-Fi is available

In fact, the user must manually disable mobile data to prevent the malware from using the cellular network. Even though the setWifiEnabledhas been deprecated, it can still be used by malware targeting API level 28 or lower.

Fetching premium service offers and initiating subscriptions

Assuming that the SIM operator is on the target list and the device is using a TRANSPORT_CELLULARtype network, the next step is to fetch a list of websites offering premium services and attempt to automatically subscribe to them.

The malware will communicate with a C2 server to retrieve a list of offered services. An offer contains, between else, a URL which will lead to a redirection chain that will end up to a web page, known as landing page.

What happens next depends on the way that the subscription process is initiated, thus the malware usually includes code that can handle various subscription flows. In a typical case scenario, the user has to click an HTML element similar to the one depicted below (JOIN NOW), and as a second step, send a verification code back to the server:

A screenshot of a website offering subscriptions to apps and premium services. There are two banners on the website, with the one above displaying the text "Join Now". The banner at the bottom displays sports-related images (football and car racing).
Figure 6. A subscription page that’s loaded in the background without the user’s knowledge.

For the malware to do this automatically, it observes the page loading progress and injects JavaScript code designed to click HTML elements that initiate the subscription. As the user can only subscribe once to one service, the code also marks the HTML page using a cookie to avoid duplicate subscriptions. The following is an example of such a code:

Figure 7. JavaScript injected code scraping related HTML elements

On line 76, getElementsByTagNamereturns a collection of all the Document Object Model (DOM) elements tagged as input. The loop on line 78 goes through every element and checks its typeas well as its name, value, and altproperties. When an element is found to contain keywords, such as “confirm”, “click”, and “continue”, it is sent to the cfunction, as depicted below:

A screenshot of JavaScript code of a function where it simulates clicks on selected HTML elements.
Figure 8. JavaScript function simulating clicks on selected HTML elements

The if statement on line 36 checks if the element has already been clicked by calling the jdh function, displayed below in Figure 12. Finally, the c function invokes the click() or submit() function by the time the branch on line 37 (see figure 11) is followed:

A screenshot of the JavaScript code where the malware checks if a premium service page has already been visited.
Figure 9. JavaScript code checking if the page has already been visited

The HTML page loading process is tracked using an onPageFinishedcallback of the WebViewClientattached to the WebView. Subsequently, a handler that listens for relative message types acts depending on the next steps that are required for the subscription to take place. In the code snippet below, the URL loaded in the WebView and a signalwith id “128”is sent to handler2to evaluate the service and initiate the subscription process:

A screenshot of malware code where it checks for specific message types to determine the next steps required for a subscription to take place.
Figure 10. Malware evaluating the steps required to initiate the subscription process

Multi-step or target subscription processes may require additional verification steps. The handler depicted below checks the page URL loaded in the WebView. If the URL matches doi[.]mtndep.co.za/service/, then the handler runs the JavaScript code assigned to the Properties.call_jbridge_dump variable:

A screenshot of malware code where it identifies the conditions required to determine what routine to run next. It assigns code based on specific conditions such as URL displayed.
Figure 11. Malware running code depending on certain conditions

A signal with id “107” triggers some additional steps that require communication with the command and control (C2) server. This case is demonstrated in the following figures:

A screenshot of malware code that is run when a signal with the ID number "107" is identified.
Figure 12. Malware running code depending on the specific signal id

Upon receiving the signal, the handler invokes the v1.bhu8 function:

A screenshot of malware code where the handler invokes the v1.bhu8 function. The said function checks if a service related to anti-fraud protection is running on the device.
Figure 13. Malware attacking anti-fraud protection

After checking for the web-zdm[.]secure-d[.]io/api/v1/activatein the server’s reply, the malware invokes the tpack[.]l2.bhu8[.]vgy7 function. This function sends the current URL loaded in the application’s WebView as well as some extra information like country code, and HTML code:

A screenshot if malware code where the malware sends information from the device to its C2 server. Sent information include country code, the HTML code of the website shown on the browser.
Figure 14. Malware sending information to the C2 server
A screenshot of malware code where a solver-type service is offered by the C2 server.
Figure 15. A solver-type service offered by the C2 server

Intercepting OTPs

In most cases, the service provider sends an OTP that must be sent back to the server to complete the subscription process. As the OTP can be sent by using either the HTTP or USSD protocol or SMS, the malware must be capable of intercepting these types of communication. For the HTTP protocol, the server’s reply must be parsed to extract the token. For the USSD protocol, on the other hand, the only way to intercept is by using the accessibility service.

One method of intercepting an SMS message, requiring android.permission.RECEIVE_SMS permission, is to instantiate a BroadcastReceiver that listens for the SMS_RECEIVED action.

The following code snippet creates a BroadcastReceiverand overrides the onReceivecallback of the superclass to filter out messages that start with “rch”:

A screenshot of malware code where the malware filters SMS messages that start with "rch"
Figure 16. Code that filters out SMS messages that start with “rch”

Subsequently, it creates an IntentFilter, which renders the receiver capable of listening for an SMS_RECEIVED action, and finally the receiver is registered dynamically:

A screenshot of the IntentFilter code, enabling the receiver to listen for any received SMS messages.
Figure 17. The IntentFilter enabling the receiver to listen for an SMS_RECEIVED action

To handle OTP messages that are sent using the HTTP protocol, the malware parses the HTML code to search for keywords indicating the verification token. The following code contains a flow where the extracted token is sent to the server using the sendTextMessage API call:

A screenshot of the malware code where an extracted verification token from the OTP message is sent to the C2 server. The code indicates that this is done through the sendTextMessage API.
Figure 18. Extracted token is sent to the C2 server using the sendTextMessage API call

The additional permission that is required to enable this flow is SEND_SMS.

Another way of intercepting SMS messages is to extend the NotificationListenerService. This service receives calls from the system when new notifications are posted or removed, including the ones sent from the system’s default SMS application. The code snippet below demonstrates this functionality:

A screenshot of malware code where the NotificationLIstenerService is extended. This enables the app to receive calls from the system when new notifications are posted or removed.
Figure 19. Extending the NotificationListenerService service

We triggered a notification with the title “SMS_Received” and text “Pin:12345” during our analysis, resulting in the following output in the application’s logcat:

A screenshot of the malware's logcat. The logcat output shows that it is able to capture contents of a notification received by the device.
Figure 20. Logcat output after a notification is posted

Finally, besides the broadcast receiver and the notification listener techniques of intercepting an SMS message, a ContentObserver can be used to receive callbacks for changes to specific content. The onChange callback of the SmsObserver class (depicted below) is called each time the system changes the SMS content provider state:

A screenshot of proof-of-concept code to demonstrate how the malware monitors for incoming SMS messages.
Figure 21. The proof-of-concept code monitoring for incoming SMS messages through SmsObserver

Suppressing notifications

Since API level 18, an application that extends the NotificationListenerService is authorized to suppress notifications triggered from other applications. The relevant API calls are:

  • cancelAllNotifications() to inform the notification manager to dismiss all notifications
  • cancelNotification(String key) to inform the notification manager to dismiss a single notification
  • cancelNotifications(String [] keys) to inform the notification manager to dismiss multiple notifications at once.

This API subset is abused by malware developers to suppress service subscription notification messages posted by the default SMS application. More specifically, upon successful subscription, the service provider sends a message to the user to inform them about the charges and offers the option to unsubscribe. By having access to the notification listener service, the malware can call any of the functions mentioned above to remove the notification.

Using dynamic code loading for cloaking

Cloaking refers to a set of techniques used to hide malicious behavior. For example, most toll fraud malware won’t take any action if the mobile network is not among its targets. Another example of a cloaking mechanism used by these threats is dynamic code loading. This means that certain malware codes are only loaded when certain conditions are met, making it difficult to detect by static analysis.

The following is a characteristic example of a multi-stage toll fraud malware with SHA-256: 2581aba12919ce6d9f89d86408d286a703c1e5037337d554259198c836a82d75 and package name: com.cful.mmsto.sthemes.

Stage one

This malware’s entry point is found to be the com.android.messaging.BugleApplication, a subclass of the Application class. The malicious flow leads to the function below:

A screenshot of malware code showing the function where the entry point of the malware leads to. This is the starting point of the dynamic code loading done by the malware.
Figure 22. The function where the entry point of the malware leads to

The call on line 21 fills the filesarray with the filenames fetched from the assets directory. The for loop enters theif branch at line 32 if the name of the asset file ends with “355”. Querying the asset files of the app for such a filename yields the following result:

A screenshot of the result when querying the malware's asset file for a file name that ends with "355". The result is a file with the name PhoneNUmberAlternateFormatsProto_355
Figure 23. Query result when searching for “355”

The PhoneNumberAlternateFormatsProto_355 is the source file which, in conjunction with a destination file and the string “xh7FEC2clYuoNQ$ToT99ue0BINhw^Bzy”, is given as parameters to the ns.j function:

A screenshot of the code of the ns.j function. It shows that the function accepts parameters from the source file PhotoNumberAlternateFormatsProto_355.
Figure 24. The ns.j function

The SecretKeySpec on line 68 is constructed from the first 16 bytes of the SHA-1 digest of the password string. This key is used to decrypt the file fetched from the assets using Advanced Encryption Standard (AES) in electronic codebook (ECB) mode. The decryption result is an ELF file that is saved in the application’s cache directory and loaded using the System.load function.

Stage two

The loaded library fetches the PhoneNumberAlternateFormatsProto_300file from the assets folder using the AAssetManager_fromJava function and writes it to a temporary file with the name b in the /data/data/<package_name>/ directory, as seen on line 93 below:

A screenshot of code wherein the malware fetches the second payload from the assets directory.
Figure 25. Fetching the second payload from the assets directory.

The file b is then decrypted using an XOR operation with the key “xh7FEC2clYuoNQ$ToT99ue0BINhw^Bzy”, which is given from the Java side (see following figures). The decrypted payload is saved with the name l in the application’s data directory:

A screenshot of code where the malware decrypts the asset with the name "l_file_fd".
Figure 26. Decrypting asset

Figure 27. The native handleTask called from the Java code

The same function loads the decrypted payload l and invokes the com.AdsView.pulgn using the DexClassLoader class loader (variable names have been changed for clarity):

A screenshot of the malware code where it loads the decrypted asset using the DexClassLoader class loader.
Figure 28. Dynamically loading the decrypted asset using the DexClassLoader

Decrypting the second payload manually yields the following APK file:

A screenshot of the code of the decrypted asset which is an APK file.
Figure 29. The decrypted APK file

It must be mentioned that the DexClassLoadercan be used to load classes from .jar and .apk files that contain a classes.dex entry.

Stage three

This decrypted APK consists of two main classes: the com.Helperand com.AdsView. The com.AdsView.pulgnfunction is the first to be invoked by the native library described in the previous section:

A screenshot of the code for the pulgn function, which is the first to be invoked once the payload is loaded.
Figure 30. pulgn is the first function to be invoked when the payload is loaded

The runnable thread’s main functionality is to connect the host to xn3o[.]oss-accelerate[.]aliyuncs[.]com and download a JAR file named xn30, which is saved to the cache directory with name nvi and then loaded using the startSdk function, as shown on line 81 below:

A screenshot of the malware code where it triggers the download of the final payload.
Figure 31. Download and trigger the final payload

The file xn30 is the final payload of stage three and is the one that performs the toll fraud activities previously described.

Mitigating the threat of toll fraud malware

Toll fraud is one of the most common malware categories with high financial loss as its main impact. Due to its sophisticated cloaking techniques, prevention from the side of the user plays a key role in keeping the device secure. A rule of thumb is to avoid installing Android applications from untrusted sources (sideloading) and always follow up with device updates. We also recommend end users take the following steps to protect themselves from toll fraud malware:

  • Install applications only from the Google Play Store or other trusted sources.
  • Avoid granting SMS permissions, notification listener access, or accessibility access to any applications without a strong understanding of why the application needs it. These are powerful permissions that are not commonly needed.
  • Use a solution such as Microsoft Defender for Endpoint on Android to detect malicious applications.
  • If a device is no longer receiving updates, strongly consider replacing it with a new device.

Identifying potential malware

For security analysts, it is important to be aware that conventional mitigation techniques based on static detection of malware code patterns can only offer limited remediation against this malware. This is due to the extended use of reflection, encryption, compression, obfuscation, steganography, and dynamic code loading.

There are, however, characteristics that can be used to identify this type of malware. We can classify these characteristics into three:

  • Primary characteristics – patterns in plaintext included in the application that can be analyzed statically
  • Secondary characteristics – common API calls used to conduct toll fraud activities
  • Tertiary characteristics – patterns in Google Play Store metadata such as the application’s category, the developer’s profile, and user reviews, among others

The tertiary characteristics are useful for initial filtering for potential malware. Patterns observed in the apps’ metadata are related to malware developers’ attempts to infect as many devices as possible in a short amount of time, while remaining published on the Google Play Store for as long as they can. We’ve observed that attackers often follow these steps to keep their apps in the Google Play Store:  

  1. Use open-source applications that belong to popular categories and can be trojanized with minimal effort. The preferred application categories include personalization (like wallpaper and lock screen apps), beauty, editor, communication (such as messaging and chat apps), photography, and tools (like cleaner and fake antivirus apps).
  2. Upload clean versions until the application gets a sufficient number of installs.
  3. Update the application to dynamically load malicious code.
  4. Separate the malicious flow from the uploaded application to remain undetected for as long as possible.

These applications often share common characteristics:

  • Excessive use of permissions that are not suitable to the application’s usage (for example, wallpaper, editor, and camera apps that bind the notification listener service or ask for SMS permissions)
  • Consistent user interfaces, with similar icons, policy pages, and buttons
  • Similar package names
  • Suspicious developer profile (fake developer name and email address)
  • Numerous user complaints in the reviews

Once potential malware samples are identified based on these tertiary characteristics, the primary characteristics can be used for further filtering and confirmation. Applications cannot obfuscate their permission requests, use of the notification listener service, or use of accessibility service. These requests must appear in the AndroidManifest.xml file within the APK, where they can be easily detected using static analysis. The commonly requested permissions by malware performing toll fraud may include: READ_SMS, RECEIVE_SMS, SEND_SMS, CHANGE_WIFI_STATE, ACCESS_WIFI_STATE, CHANGE_NETWORK_STATE. Requests for notification listener and accessibility service should be considered extremely suspicious.

Secondary characteristics also include suspicious API calls including: setWifiEnabled, requestNetwork, setProccessDefaultnetwork, bindProcessToNetwork, getSimOperator and cancelAllNotifications. However, since these calls may be obfuscated and may be hard to identify during static analysis, a more in-depth analysis may be necessary for certainty.

Improving Android security and privacy

Google continuously improves Android security and privacy as the mobile threat landscape evolves and new threats and adversary techniques are discovered. For example, in the operating system, API calls that can reveal potentially sensitive information continue to be removed or restricted, and in the Google Play Store, the publication policies guard against use of certain high-risk permissions (for example, the ability to receive or send SMSs) by requiring a Permission Declaration Form to be completed justifying their use. We anticipate Android security will continue to evolve to address abuse.

As discussed, applications currently can identify the cellular network operator and can send network traffic over the cellular network without any transparency to the user. Additionally, applications can request access to read and dismiss notifications, a very powerful capability, without needing to justify this behavior.

Conclusion

Toll fraud has been one of the most prevalent types of Android malware in Google Play Store since 2017, when families like Joker and their variants made their first appearance. It accounted for 34.8% of installed Potentially Harmful Application (PHA) from the Google Play Store in the first quarter of 2022, ranking second only to spyware.

By subscribing users to premium services, this malware can lead to victims receiving significant mobile bill charges. Affected devices also have increased risk because this threat manages to evade detection and can achieve a high number of installations before a single variant gets removed.

With this blog, we want to inform end users about the details of this threat and how they can protect themselves from toll fraud. We also aim to provide security analysts with guidance on how to identify other malicious applications that use these techniques.

Our in-depth analysis of this threat and its continuous evolution informs the protection we provide through solutions like Microsoft Defender for Endpoint on Android.

Learn how Microsoft Defender for Endpoint provides cross-platform security, including mobile threat defense capabilities.

Dimitrios Valsamaras and Sang Shin Jung
Microsoft 365 Defender Research Team

Appendix

Samples (SHA-256)

SampleSHA-256
Initial APK file2581aba12919ce6d9f89d86408d286a703c1e5037337d554259198c836a82d75 (com.cful.mmsto.sthemes)
Payload of stage two: Elf File (loader)904169162209a93ac3769ae29c9b16d793d5d5e52b5bf198e59c6812d7d9eb14 (PhoneNumberAlternateFormatsProto_355, decrypted)
Payload of stage three: APK (hostile downloader)61130dfe436a77a65c04def94d3083ad3c6a18bf15bd59a320716a1f9b39d826 (PhoneNumberAlternateFormatsProto_300, decrypted)
Payload of stage four: DEX (billing fraud)4298952f8f254175410590e4ca2121959a0ba4fa90d61351e0ebb554e416500f

Common API calls and permissions

API CallsPermissionsSDK
setWifiEnabledCHANGE_WIFI _STATE ACCESS_WIFI_STATE<29
requestNetworkCHANGE_NETWORK_STATE>28
setProcessDefaultNetwork <23
bindProcessToNetwork >22
getActiveNetworkInfoACCESS_NETWORK_STATE 
getSimOperator  
get (SystemProperties)  
addJavascriptInterface  
evaluateJavascript >18
onPageFinished  
onPageStarted  
onReceive for SMS BroadcastReceiver w/ android.provider.Telephony.SMS_RECEIVEDRECEIVE_SMS>19
createFromPduRECEIVE_SMS 
getMessageBody  
onChange for SMS ContentObserver w/ android.provider.telephony.SmsProvider’s content URI (“content://sms”)READ_SMS 
sendTextMessage  
onNotificationPosted  

References

The post Toll fraud malware: How an Android application can drain your wallet appeared first on Microsoft Security Blog.

]]>
Android apps with millions of downloads exposed to high-severity vulnerabilities http://approjects.co.za/?big=en-us/security/blog/2022/05/27/android-apps-with-millions-of-downloads-exposed-to-high-severity-vulnerabilities/ Fri, 27 May 2022 16:00:00 +0000 Microsoft uncovered high-severity vulnerabilities in a mobile framework used by multiple large mobile service providers in pre-installed Android System apps that potentially exposed users to remote or local attacks.

The post Android apps with millions of downloads exposed to high-severity vulnerabilities appeared first on Microsoft Security Blog.

]]>
Microsoft uncovered high-severity vulnerabilities in a mobile framework owned by mce Systems and used by multiple large mobile service providers in pre-installed Android System apps that potentially exposed users to remote (albeit complex) or local attacks. The vulnerabilities, which affected apps with millions of downloads, have been fixed by all involved parties. Coupled with the extensive system privileges that pre-installed apps have, these vulnerabilities could have been attack vectors for attackers to access system configuration and sensitive information.

As it is with many of pre-installed or default applications that most Android devices come with these days, some of the affected apps cannot be fully uninstalled or disabled without gaining root access to the device. We worked with mce Systems, the developer of the framework, and the affected mobile service providers to solve these issues. We commend the quick and professional resolution from the mce Systems engineering teams, as well as the relevant providers in fixing each of these issues, ensuring that users can continue using such a crucial framework.

Collaboration among security researchers, software vendors, and the security community is important to continuously improve defenses for the larger ecosystem. As the threat and computing landscape continues to evolve, vulnerability discoveries, coordinated response, and other forms of threat intelligence sharing are paramount to protecting customers against present and future threats, regardless of the platform or device they are using.

Uncovering the vulnerabilities

Our research on the framework vulnerabilities began while trying to better understand how a pre-installed System application could affect the overall security of mobile devices. We discovered that the framework, which is used by numerous apps, had a “BROWSABLE” service activity that an attacker could remotely invoke to exploit several vulnerabilities that could allow adversaries to implant a persistent backdoor or take substantial control over the device.

The framework seemed to be designed to offer self-diagnostic mechanisms to identify and resolve issues impacting the Android device, indicating its permissions were inherently broad with access to valuable resources. For example, the framework was authorized to access system resources and perform system-related tasks, like adjusting the device’s audio, camera, power, and storage controls. Moreover, we found that the framework was being used by default system applications to leverage its self-diagnostic capabilities, demonstrating that the affiliated apps also included extensive device privileges that could be exploited via the vulnerable framework.

According to mce Systems, some of these vulnerabilities also affected other apps on both Android and iOS devices. Moreover, the vulnerable framework and affiliated apps were found on devices from large international mobile service providers. mce Systems, which offers “Mobile Device Lifecycle and Automation Technologies,” also permitted providers to customize and brand their respective mobile apps and frameworks. Pre-installed frameworks and mobile apps such as mce Systems’ are beneficial to users and providers in areas like simplifying the device activation process, troubleshooting device issues, and optimizing performance. However, their extensive control over the device to deliver these kinds of services could also make them an attractive target for attackers. 

Our analysis further found that the apps were embedded in the devices’ system image, suggesting that they were default applications installed by phone providers. All of the apps are available on the Google Play Store where they go through Google Play Protect’s automatic safety checks, but these checks previously did not scan for these types of issues. As part of our effort to help ensure broad protection against these issues, we shared our research with Google, and Google Play Protect now identifies these types of vulnerabilities.

We initially discovered the vulnerabilities in September 2021 and shared our findings with mce Systems and affected mobile service providers through Coordinated Vulnerability Disclosure (CVD) via Microsoft Security Vulnerability Research (MSVR). We worked closely with mce Systems’ security and engineering teams to mitigate these vulnerabilities, which included mce Systems sending an urgent framework update to the impacted providers and releasing fixes for the issues. At the time of publication, there have been no reported signs of these vulnerabilities being exploited in the wild.

The high-severity vulnerabilities, which have a Common Vulnerability Scoring System (CVSS) score of 7.0-8.9, are now identified as CVE-2021-42598, CVE-2021-42599, CVE-2021-42600, and CVE-2021-42601. We want to thank mce Systems’ engineering teams for collaborating quickly and efficiently in resolving these issues as well as to AT&T for proactively working with Microsoft to ensure customers can safely continue to use the framework.

Several other mobile service providers were found using the vulnerable framework with their respective apps, suggesting that there could be additional providers still undiscovered that may be impacted. The affected providers linked below have made updated app versions available to users before this disclosure, ensuring devices can be protected before these vulnerabilities could be exploited. We encourage these providers’ customers to update to the latest versions of these apps from the Google Play store, which include but are not limited to: com.telus.checkup, com.att.dh, com.fivemobile.myaccount, com.freedom.mlp,uat, and com.ca.bell.contenttransfer.

Additionally, the package com.mce.mceiotraceagent might be installed by several mobile phone repair shops. Mobile users are advised to look for that app name and remove it from their phone, if found.

Analyzing apps that use the mce framework

App manifest and permissions

When analyzing an Android application, the first thing that comes to mind is checking its manifest, maintained under the AndroidManifest.xml file. The manifest describes the application itself and its components, such as the following:

  • Permissions (for example, camera access, internet access, and others)
  • Activities and how they respond to Intents sent to them
  • Content providers
  • Receivers and the kind of content they expect to receive
  • Services

Checking the manifest of an app affiliated with mce Systems’ framework shed light on some of its features and capabilities but did not immediately indicate that any vulnerabilities or security issues were present. Therefore, further research into the app’s functionality was needed by understanding its permissions.

Analysis of the app’s permissions on the mobile device revealed authorizations that could lead to powerful access and capabilities for an attacker. Those permissions included control over the following:

  • Networking: access the internet, modify Wi-Fi state, network state, NFC, and Bluetooth
  • File access: read and write to the external storage
  • Peripherals: access the camera, record audio, get fingerprint information, and get the device’s physical location
  • Private information: read phone numbers, account information, and contacts
  • Management: install apps and modify device settings

With access to these valuable resources, the app could be abused by an attacker to implant a persistent backdoor on the device.

BROWSABLE activities

The “Activities” section of the app’s manifest detailed that the Intent-filter element included activities with a “BROWSABLE” category. While most Intents do not require a category, category strings detail the components that should handle the Intent. In particular, the BROWSABLE category allows the target Activity to be triggered from a web browser to display data referenced by a link, like an image. BROWSABLE activities appeal to attackers as the latter can exploit them via malicious web pages and other Intent-based attacks.

Figure 1:  BROWSABLE Activity with the “mcedigital://” scheme

The Intent-filter element in the manifest dictates how the Activity can be triggered. In the app’s case, the Activity could be triggered by simply clicking a link with the “mcedigital://” scheme. This would start the com.mce.sdk.AppActivity Activity with an Intent with arbitrary data (besides the scheme).

Digging deeper: Reviewing the mce framework’s main functionality

We reviewed the effects of triggering the com.mce.sdk.AppActivity. Also known as appActivity, this Activity refers to the different functionalities provided by the app. AppActivity extends Activity and therefore has an onCreate method, which traditionally handles the creating Intent.

AppActivity

Here’s a brief description of AppActivity:

  1. AppActivity has a member called “webView” and type “JarvisWebView,” a specialized class that extends WebView.
  2. Upon creation, AppActivity has some optional display choices from the Intent (if they exist) and then loads a predefined web page to the WebView. That predefined page can get arbitrary query parameters from the Intent’s data; that is, everything after a “\?” will be added to the web page.

Thus, if a user clicks this:

mcedigital://ignored\?arbitrary_params

The App’s WebView loads the following web page:

file:///android_asset/applications/user/reflow-container-bundled/index.html?arbitrary_params

The app’s index.html web page (which is an asset built into the Android app) loads two JavaScript files:

  • config.js: a nonexistent file
  • bundle.js: contains much of the app’s logic

Since we wanted to understand the interplay between bundle.js (JarvisJSInterface) and the WebView (JarvisWebView), we analyzed both.

JarvisWebView and JarvisJSInterface

The main features of the WebView, JarvisWebView class, are the following:

A JavaScript Interface is a conspicuous target to look for security issues, as it uses a JavaScript Bridge to allow invoking specific methods inside an Android app. In the case of JarvisJSInterface, three methods are exported:

  • init(String): takes a string that will be used as a JavaScript callback method; in our case, it will always be window.AndroidCallback
  • windowClose(): runs a callback registered by the Android app
  • request(String): sends a service request from the JavaScript client to the server (Android app)

The request method is by far the most interesting, as it performs the following:

  1. Interprets the given string as a JSON object
  2. Extracts the following pieces from the JSON object:
    • Context: a random GUID generated by the client, used to link requests and responses
    • Service: the service we are about to call to
    • Command: an integer
    • Data: optional parameters sent to the service call
  3. Invokes the method serviceCall, which finds the registered service, gets the method based on the command number, and eventually invokes that method using Java reflection
Figure 2: Service::callServiceMethod

The serviceCall is a powerful method, as it allows the WebView to invoke “services” freely. But what are these services, exactly?

Services offered by the mce framework

After we examined the services offered by this framework per the app manifest, we then obtained a list of services that practically give the WebView complete control over the device. The most notable services include:

  • Audio: access and manipulate volume levels, as well as play a tone with a given duration and frequency
  • Camera: take a silent snapshot
  • Connectivity: control and obtain valuable information from NFC, Wi-Fi, and Bluetooth
  • Device: includes various device controlling mechanisms like battery drainage, performing a factory reset, and obtaining information on apps, addresses, sensor data, and much more
  • Discovery: set the device to discoverable
  • Location: obtain the location in various modes and set the location state
  • PackageManager: acquire package info and silently install a new app
  • Power: obtain charging state
  • Sensor: acquire sensor data such as barometer data, light data, proximity data, and whether fingerprinting is working
  • Storage: obtain content such as documents, media, images, and videos

These services inherit from a base class named “Service” and implement two methods:

  • setServiceName: for service identification purposes
  • setServiceMethodMap: for setting up the mapping between the command integer and the method name, argument names, and argument types

For example, here is the Camera service setting its methods:

  • Method 0 is “getCameraList” and expects no arguments.
  • Method 1 is “captureStillImageNoPreview” and expects one String argument.
Figure 3: The Camera service setting its methods

Vulnerability findings

Based on our analysis of the mce framework, we discovered several vulnerabilities. It should be noted that while mobile service providers can customize their apps respective to mce framework so as not to be identical, the vulnerabilities we discovered can all be exploited in the same manner—by injecting code into the web view. Nonetheless, as their apps and framework customization use different configurations and versions, not all providers are necessarily vulnerable to all the discovered vulnerabilities.

Outdated command-injection vulnerability (CVE-2021-42599)

We found a command-injection vulnerability, tracked as CVE-2021-42599, in the Device service mentioned in the previous section. This service offers rich functionality, including the capability to stop activities of a given package. The client fully controls the argument “value,” and simply runs the following command:

am force-stop "value"

Since the argument is not sanitized, an attacker could add backticks or quotation marks to run arbitrary code, like the following:

am force-stop "a"; command-to-run; echo "a"
Figure 4: Command injection proof-of-concept (POC) exploit code implemented in the Device service

According to mce Systems, they have since removed the functionality behind this vulnerability and it is no longer present in more advanced framework versions.

Exploitation by JavaScript injection with PiTM in certain apps

The services offered by the mce framework further indicated that the following vulnerability resided in the logic of the JavaScript client for apps that are configured to enable plaintext communications such as the app that we initially analyzed. Interestingly, the code for the client is a heavily-obfuscated dynamic JavaScript code that is implemented over several files, mainly bundle.js. Due to the blind trust between the JavaScript client and the JarvisJSInterface server, an attacker who could inject JavaScript contents into the WebView would inherit the permissions that the app already has.

We conceived two injection strategies most likely to be leveraged by attackers:

  1. Affect the JavaScript client behavior by supplying specific GET parameters from the BROWSABLE Intent.
  2. Trigger an app with the BROWSABLE Intent to become an adversary-in-the-middle (AiTM) and view the device’s entire traffic. Inject JavaScript code if the client ever tries to fetch external content and interpret it as a script or HTML.

Once we reverse-engineered the client’s obfuscated code, we discovered that it could not inject JavaScript from the GET parameters. The only capability permitted was to affect some of the client’s self-tests upon initialization, such as a battery-draining test or a Wi-Fi connectivity test. However, the WebView-fetched plaintext pages that we discovered could be injected into with a PiTM attack.

Our proof-of-concept (POC) exploit code was therefore:

  1. Perform a PiTM for the target device and lure the user into clicking a link with the “mcesystems://” schema.
  2. Inject JavaScript into one of the plaintext page responses that does the following:
    • Hijack the JavaScript interface by calling init with our callback method
    • Use the JavaScript interface request method to get servicing
    • Send the data to our server for information gathering using XHR (XMLHttpRequest)
Figure 5: Injecting a similar JavaScript code to the WebView could allow an attacker to call arbitrary services and methods

Local elevation of privilege with deserialization followed by injection (CVE-2021-42601)  

Some of the apps we analyzed did not pull plaintext pages. Thus, we looked for a local elevation of privilege vulnerability, allowing a malicious app to gain the system apps’ privileges, tracked as CVE-2021-42601.

In the apps mentioned above, we discovered that the main Activity attempted to handle a deep link (a link that launches an app instead of a browser on click) with Google Firebase. Interestingly, this deep-link handling tried to deserialize a structure called PendingDynamicLinkData (representing a link) from an Intent Extra byte array with the key com.google.firebase.dynamiclinks.DYNAMIC_LINK_DATA. This structure was used later by the mce framework to generate various JSON Objects that might contain data from a categoryId query parameter in the original link, and eventually ended up in the member mFlowSDKInput to be injected into the JarvisWebView instance in an unsafe way:

Figure 6: Unsanitized JavaScript loading allowed arbitrary code injection to the WebView

Since the categoryId query parameter might contain apostrophes, one could inject arbitrary JavaScript code into the WebView. We decided to inject a code that would reach out to a server and load a second-stage code, which was the exact one we used for our PiTM scenario.

Figure 7: Local injection POC exploit

Software design against JavaScript injection vulnerabilities

We worked closely with the mce Systems engineering team and discovered that the reason for unsafe loadUrl invocations with JavaScript injections was that the framework used an asynchronous model of operation. When the JavaScript client performs a request, it expects to be notified later when there are results. Since Android JavaScript Bridge only allows primitive types to be sent (for example, Strings), the mce framework notified the JavaScript client by injecting JavaScript with potentially unsafe arguments (the results themselves).

We offered mce Systems a slightly different software design that prevents unsafe JavaScript injection. The description of the flow of information in our proposal is as follows:

  1. The JavaScript client invokes the request method on the Android JavaScript Bridge, supplying the request itself along with a request ID.
  2. The Java server performs the request and stores the result in a cache. The said cache then maps request IDs to results.
  3. The Java server notifies the client by carefully injecting the JavaScript loadUrl(“javascript:window.onMceResult(<requestID>);”) into the WebView. Note that the only non-constant string is the request ID, which can easily be sanitized. This method “wakes the client up”
  4. The JavaScript client implementation of onMceResult invokes the Android JavaScript Bridge with the method String fetchResult(String requestId). Note that this method returns a string (which contains the result).

This way, the JavaScript client does not need to poll for asynchronous results while data is safely transferred between the client and the server.

Interestingly, Google AndroidX offers a very similar API: webMessageListener. While the said API works quite similarly to our suggestion, it only supports Android versions greater than Lollipop. Thus, the new mce framework now checks the Android version and uses this new Google API if supported or our offered solution for older devices.

The above is just one example of our collaboration to help secure our cross-platform ecosystem. According to mce Systems, all of our reported vulnerabilities were addressed.

Improving security for all through threat intelligence sharing and research-driven protections

Microsoft strives to continuously improve security by collaborating with customers, partners, and industry experts. Responding to the evolving threat landscape requires us to expand our capabilities into other devices and non-Windows platforms in addition to further coordinating research and threat intelligence sharing among the larger security community. This case highlighted the need for expert, cross-industry collaboration to effectively mitigate issues.

Moreover, collaborative research such as this informs our seamless protection capabilities across platforms. For example, intelligence from this analysis helped us ensure that Microsoft Defender Vulnerability Management can identify and remediate devices that have these vulnerabilities, providing security operations teams with comprehensive visibility into their organizational exposure and enabling them to reduce the attack surface. In addition, while we’re not aware of any active exploitation of these mobile vulnerabilities in the wild, Microsoft Defender for Endpoint’s mobile threat defense capabilities significantly improve security on mobile devices by detecting potential exploits, malware, and post-exploitation activity.

We will continue to work with the security community to share intelligence about threats and build better protection for all. Microsoft security researchers continually work to discover new vulnerabilities and threats, turning a variety of wide-reaching issues into tangible results and improved solutions that protect users and organizations across platforms every single day. Similarly inquisitive individuals are encouraged to check opportunities to join the Microsoft research team here: https://careers.microsoft.com/.  

Jonathan Bar Or, Sang Shin Jung, Michael Peck, Joe Mansour, and Apurva Kumar
Microsoft 365 Defender Research Team

The post Android apps with millions of downloads exposed to high-severity vulnerabilities appeared first on Microsoft Security Blog.

]]>
Surface expands its Secured-core portfolio with the new Surface Laptop 4 powered by AMD Ryzen™ Mobile Processors http://approjects.co.za/?big=en-us/security/blog/2021/04/19/surface-expands-its-secured-core-portfolio-with-the-new-surface-laptop-4-powered-by-amd-ryzen-mobile-processors/ Mon, 19 Apr 2021 16:00:38 +0000 Microsoft is proud to announce our latest Secured-core offering, the all-new Surface Laptop 4 powered by AMD Ryzen™ Mobile Processors. These devices offer comprehensive security out-of-the-box with tightly integrated hardware, software, firmware, and identity protection layers.

The post Surface expands its Secured-core portfolio with the new Surface Laptop 4 powered by AMD Ryzen™ Mobile Processors appeared first on Microsoft Security Blog.

]]>
As operating systems are becoming more secure and resistant to compromise, advanced vectors like firmware, kernel and hardware direct memory access (DMA) have emerged as new favored targets for threat actors. Recent trends indicate a substantial growth in the number of hardware and firmware exploits. The March 2021 Security Signals report, commissioned by Microsoft, indicates that a vast majority of enterprise customers have experienced at least one firmware attack in the past two years.

To safeguard against increasingly sophisticated and targeted attacks, we need more than just software protection – integrated hardware and software security is now essential in an era of heightened threat. Collaborating closely with AMD, Microsoft is proud to announce our latest Secured-core offering, the all-new Surface Laptop 4 powered by AMD Ryzen™ Mobile Processors. These devices offer comprehensive security out of the box with tightly integrated hardware, software, firmware, and identity protection layers.

Defense against hardware and firmware exploits

Leveraging hardware for security

At the heart of the Surface Laptop 4, the device leverages the Trusted Platform Module 2.0 (TPM) and the AMD Ryzen™ Mobile Processors with System Guard to boot securely and minimize the impact of firmware vulnerabilities by sandboxing firmware to protect critical subsystems and sensitive data. Kernel Direct Memory Access Protection is pre-enabled on these devices, helping to ensure that the system is protected against malicious and unintended Direct Memory Access (DMA) attacks for all DMA-capable devices, such as PCI devices, thwarting the entire class of drive-by DMA attacks like Thunderspy.

The TPM 2.0 serves as the hardware root-of-trust for the Surface Laptop 4. With hardware protections for sensitive assets like BitLocker keys and security measurements for the state of the system, the TPM 2.0 helps make the Surface Laptop 4 ready for Zero Trust security.

UEFI firmware protection

As pointed out in the Security Signals report, firmware is emerging as a primary target because it’s where devices store sensitive information, like credentials and encryption keys. To address this Microsoft introduced its own open-source UEFI to help enable a secure and maintainable interface to manage firmware. On the Surface side, we have been enabling the automation of firmware protection since the 2015 release of Surface Pro 4. That’s when we made the decision to build our own Microsoft UEFI and facilitate full transparency for our customers with the open-source project called Project Mu.

If you’re not already familiar with UEFI, it stands for Unified Extensible Firmware Interface. It’s essentially a modern version of a BIOS that initializes and validates system hardware components, boots Windows 10 from an SSD, and provides an interface for the OS to interact with the keyboard, display, and other input/output devices.

Centralized device management down to the firmware level

As Microsoft further developed the UEFI for Surface, we also built tools for managing and updating UEFI, beginning with SEMM (Surface Enterprise Management Mode). You can use it as a stand-alone tool or integrated with Microsoft Endpoint Configuration Manager to manage the UEFI settings on your Surface. SEMM lets you remotely enable and disable key components of Surface devices that would otherwise require you to physically go to every machine and boot straight into the UEFI (Power button + Volume Up). From a security perspective this is important as the more components you disable, that are not normally used, the smaller the attack vector.

Aligned to Microsoft’s broader commitments, we moved SEMM capabilities to the cloud with the launch of DFCI (Device Firmware Configuration Interface). DFCI enables cloud-based control over UEFI settings through the Intune component of Microsoft Endpoint Manager. The best part is that DFCI can be enabled via policy and deployed with Windows Autopilot before anyone even logs into the device. With DFCI a Surface device can be fully managed from Windows 10 down to firmware all through the power of the cloud and Microsoft Endpoint Manager.

Surface drives innovation into firmware security

Surface takes a multi-pronged approach to raise the security of our UEFI. To start, it can be updated via Windows Update. Our UEFI does not require an outside tool from a third party or download site. In fact, when the vulnerability of Spectre and Meltdown was announced, Surface already had a fix available that was automatically pushed to every Surface device accepting updates. Windows Update patched the microcode of our processors all through UEFI. Another security step we take is to lock down the UEFI, to help protect against known exploits. Surface UEFI uses a combination of Platform Secure Boot (PSB) and UEFI Secure Boot, which translates to a measured and signed firmware check at each stage in the initial boot process.

Proactive operating system protection

Along with limiting to a small, trusted computing base by establishing a hardware root of trust, Surface Laptop 4 confirms that code running within that trusted computing base runs with integrity.

Virtualization-based security (VBS) isolates the operating system and provides a hardware-based security boundary, thereby separating security features and sensitive code and data from vulnerabilities in the operating system. Hypervisor-enforced Code Integrity (HVCI) checks the system software before it is loaded, allowing only executables that are signed by known, approved authorities to start. The hypervisor also helps ensure that kernel executable memory is not writable. This prevents the modifications of sensitive kernel structures and provides strong protections against kernel viruses and malware. Time and again, the protections offered by VBS and HVCI have been shown to provide essential resistance against practical real-world threats.

Identity protection

Complementing the platform security provided by secured-core and Project Mu, Surface Laptop 4 helps ensure that user identities and credentials are protected against theft, compromise, and phishing attacks.

Windows Hello helps prevent phishing and credential-based attacks through a combination of biometric sensors and hardware-based credential storage. Using your face, secure FIDO2 key, or PIN, Windows Hello allows you to sign in password-free and gives you a faster, more secure way to unlock your device.

Windows Defender Credential Guard, an optional feature that can be enabled, leverages VBS to help isolate secrets and confidential information such that only privileged system software can access it. This helps prevent identity attack techniques such as Pass-the-Hash and Pass-the-Ticket.

New Surface expands Secured-core PC line

Surface Laptop 4, powered by AMD Ryzen™ Mobile Processors, joins Surface Pro X as the second secured-core PC offering in the Surface portfolio. These devices provide powerhouse protection out of the box, with capabilities such as Virtualization-Based Security, System Guard, and Kernel DMA protection enabled by default. With these devices, users and businesses can be confident that they have the right protections in place to mitigate security risks and simplify the end-user experience in configuring the device.

Find out more about our Secured-core PC lineup.

 

 

1 Surface Go and Surface Go 2 use a third-party UEFI and do not support DFCI. DFCI is currently available for Surface Laptop Go, Surface Book 3, Surface Laptop 3, Surface Pro 7, Surface Pro 7+ and Surface Pro X. Find out more about managing Surface UEFI settings at https://docs.microsoft.com/surface/manage-surface-uefi-settings.

The post Surface expands its Secured-core portfolio with the new Surface Laptop 4 powered by AMD Ryzen™ Mobile Processors appeared first on Microsoft Security Blog.

]]>
Sophisticated new Android malware marks the latest evolution of mobile ransomware http://approjects.co.za/?big=en-us/security/blog/2020/10/08/sophisticated-new-android-malware-marks-the-latest-evolution-of-mobile-ransomware/ Thu, 08 Oct 2020 16:00:35 +0000 We found a piece of a particularly sophisticated Android ransomware with novel techniques and behavior, exemplifying the rapid evolution of mobile threats that we have also observed on other platforms.

The post Sophisticated new Android malware marks the latest evolution of mobile ransomware appeared first on Microsoft Security Blog.

]]>
Attackers are persistent and motivated to continuously evolve – and no platform is immune. That is why Microsoft has been working to extend its industry-leading endpoint protection capabilities beyond Windows. The addition of mobile threat defense into these capabilities means that Microsoft Defender for Endpoint (previously Microsoft Defender Advanced Threat Protection) now delivers protection on all major platforms.

Microsoft’s mobile threat defense capabilities further enrich the visibility that organizations have on threats in their networks, as well as provide more tools to detect and respond to threats across domains and across platforms. Like all of Microsoft’s security solutions, these new capabilities are likewise backed by a global network of threat researchers and security experts whose deep understanding of the threat landscape guide the continuous innovation of security features and ensure that customers are protected from ever-evolving threats.

For example, we found a piece of a particularly sophisticated Android ransomware with novel techniques and behavior, exemplifying the rapid evolution of mobile threats that we have also observed on other platforms. The mobile ransomware, detected by Microsoft Defender for Endpoint as AndroidOS/MalLocker.B, is the latest variant of a ransomware family that’s been in the wild for a while but has been evolving non-stop. This ransomware family is known for being hosted on arbitrary websites and circulated on online forums using various social engineering lures, including masquerading as popular apps, cracked games, or video players. The new variant caught our attention because it’s an advanced malware with unmistakable malicious characteristic and behavior and yet manages to evade many available protections, registering a low detection rate against security solutions.

As with most Android ransomware, this new threat doesn’t actually block access to files by encrypting them. Instead, it blocks access to devices by displaying a screen that appears over every other window, such that the user can’t do anything else. The said screen is the ransom note, which contains threats and instructions to pay the ransom.

Screenshot of mobile ransom note in Russian language

Figure 1. Sample ransom note used by older ransomware variants

What’s innovative about this ransomware is how it displays its ransom note. In this blog, we’ll detail the innovative ways in which this ransomware surfaces its ransom note using Android features we haven’t seen leveraged by malware before, as well as incorporating an open-source machine learning module designed for context-aware cropping of its ransom note.

New scheme, same goal

In the past, Android ransomware used a special permission called “SYSTEM_ALERT_WINDOW” to display their ransom note. Apps that have this permission can draw a window that belongs to the system group and can’t be dismissed. No matter what button is pressed, the window stays on top of all other windows. The notification was intended to be used for system alerts or errors, but Android threats misused it to force the attacker-controlled UI to fully occupy the screen, blocking access to the device. Attackers create this scenario to persuade users to pay the ransom so they can gain back access to the device.

To catch these threats, security solutions used heuristics that focused on detecting this behavior. Google later implemented platform-level changes that practically eliminated this attack surface. These changes include:

  1. Removing the SYSTEM_ALERT_WINDOW error and alert window types, and introducing a few other types as replacement
  2. Elevating the permission status of SYSTEM_ALERT_WINDOW to special permission by putting it into the “above dangerous” category, which means that users have to go through many screens to approve apps that ask for permission, instead of just one click
  3. Introducing an overlay kill switch on Android 8.0 and later that users can activate anytime to deactivate a system alert window

To adapt, Android malware evolved to misusing other features, but these aren’t as effective. For example, some strains of ransomware abuse accessibility features, a method that could easily alarm users because accessibility is a special permission that requires users to go through several screens and accept a warning that the app will be able to monitor activity via accessibility services. Other ransomware families use infinite loops of drawing non-system windows, but in between drawing and redrawing, it’s possible for users to go to settings and uninstall the offending app.

The new Android ransomware variant overcomes these barriers by evolving further than any Android malware we’ve seen before. To surface its ransom note, it uses a series of techniques that take advantage of the following components on Android:

  1. The “call” notification, among several categories of notifications that Android supports, which requires immediate user attention.
  2. The “onUserLeaveHint()” callback method of the Android Activity (i.e., the typical GUI screen the user sees) is called as part of the activity lifecycle when the activity is about to go into the background as a result of user choice, for example, when the user presses the Home key.

The malware connects the dots and uses these two components to create a special type of notification that triggers the ransom screen via the callback.

Screenshot of malware code

Figure 2. The notification with full intent and set as “call’ category

As the code snippet shows, the malware creates a notification builder and then does the following:

  1. setCategory(“call”) – This means that the notification is built as a very important notification that needs special privilege.
  2. setFullScreenIntent() – This API wires the notification to a GUI so that it pops up when the user taps on it. At this stage, half the job is done for the malware. However, the malware wouldn’t want to depend on user interaction to trigger the ransomware screen, so, it adds another functionality of Android callback:

Figure 3. The malware overriding onUserLeaveHint

As the code snippet shows, the malware overrides the onUserLeaveHint() callback function of Activity class. The function onUserLeaveHint() is called whenever the malware screen is pushed to background, causing the in-call Activity to be automatically brought to the foreground. Recall that the malware hooked the RansomActivity intent with the notification that was created as a “call” type notification. This creates a chain of events that triggers the automatic pop-up of the ransomware screen without doing infinite redraw or posing as system window.

Machine learning module indicates continuous evolution

As mentioned, this ransomware is the latest variant of a malware family that has undergone several stages of evolution. The knowledge graph below shows the various techniques this ransomware family has been seen using, including abusing the system alert window, abusing accessibility features, and, more recently, abusing notification services.

Knowledge graph showing techniques used by the Android rasomware family

Figure 4. Knowledge graph of techniques used by ransomware family

This ransomware family’s long history tells us that its evolution is far from over. We expect it to churn out new variants with even more sophisticated techniques. In fact, recent variants contain code forked from an open-source machine learning module used by developers to automatically resize and crop images based on screen size, a valuable function given the variety of Android devices.

The frozen TinyML model is useful for making sure images fit the screen without distortion. In the case of this ransomware, using the model would ensure that its ransom note—typically fake police notice or explicit images supposedly found on the device—would appear less contrived and more believable, increasing the chances of the user paying for the ransom.

The library that uses tinyML is not yet wired to the malware’s functionalities, but its presence in the malware code indicates the intention to do so in future variants. We will continue to monitor this ransomware family to ensure customers are protected and to share our findings and insights to the community for broad protection against these evolving mobile threats.

Protecting organizations from threats across domains and platforms

Mobile threats continue to rapidly evolve, with attackers continuously attempting to sidestep technological barriers and creatively find ways to accomplish their goal, whether financial gain or finding an entry point to broader network compromise.

This new mobile ransomware variant is an important discovery because the malware exhibits behaviors that have not been seen before and could open doors for other malware to follow. It reinforces the need for comprehensive defense powered by broad visibility into attack surfaces as well as domain experts who track the threat landscape and uncover notable threats that might be hiding amidst massive threat data and signals.

Microsoft Defender for Endpoint on Android, now generally available, extends Microsoft’s industry-leading endpoint protection to Android. It detects this ransomware (AndroidOS/MalLocker.B), as well as other malicious apps and files using cloud-based protection powered by deep learning and heuristics, in addition to content-based detection. It also protects users and organizations from other mobile threats, such as mobile phishing, unsafe network connections, and unauthorized access to sensitive data. Learn more about our mobile threat defense capabilities in Microsoft Defender for Endpoint on Android.

Malware, phishing, and other threats detected by Microsoft Defender for Endpoint are reported to the Microsoft Defender Security Center, allowing SecOps to investigate mobile threats along with endpoint signals from Windows and other platforms using Microsoft Defender for Endpoint’s rich set of tools for detection, investigation, and response.

Threat data from endpoints are combined with signals from email and data, identities, and apps in Microsoft 365 Defender (previously Microsoft Threat Protection), which orchestrates detection, prevention, investigation, and response across domains, providing coordinated defense. Microsoft Defender for Endpoint on Android further enriches organizations’ visibility into malicious activity, empowering them to comprehensively prevent, detect, and respond to against attack sprawl and cross-domain incidents.

Technical analysis

Obfuscation

On top of recreating ransomware behavior in ways we haven’t seen before, the Android malware variant uses a new obfuscation technique unique to the Android platform. One of the tell-tale signs of an obfuscated malware is the absence of code that defines the classes declared in the manifest file.

Malware code showing manifest file

Figure 5. Manifest file

The classes.dex has implementation for only two classes:

  1. The main application class gCHotRrgEruDv, which is involved when the application opens
  2. A helper class that has definition for custom encryption and decryption

This means that there’s no code corresponding to the services declared in the manifest file: Main Activity, Broadcast Receivers, and Background. How does the malware work without code for these key components? As is characteristic for obfuscated threats, the malware has encrypted binary code stored in the Assets folder:

Screenshot of Assets folder with encrypted executable code

Figure 6. Encrypted executable code in Assets folder

When the malware runs for the first time, the static block of the main class is run. The code is heavily obfuscated and made unreadable through name mangling and use of meaningless variable names:

Figure 7. Static block

Decryption with a twist

The malware uses an interesting decryption routine: the string values passed to the decryption function do not correspond to the decrypted value, they correspond to junk code to simply hinder analysis.

On Android, an Intent is a software mechanism that allows users to coordinate the functions of different Activities to achieve a task. It’s a messaging object that can be used to request an action from another app component.

The Intent object carries a string value as “action” parameter. The malware creates an Intent inside the decryption function using the string value passed as the name for the Intent. It then decrypts a hardcoded encrypted value and sets the “action” parameter of the Intent using the setAction API. Once this Intent object is generated with the action value pointing to the decrypted content, the decryption function returns the Intent object to the callee. The callee then invokes the getAction method to get the decrypted content.

Figure 8. Decryption function using the Intent object to pass the decrypted value

Payload deployment

Once the static block execution is complete, the Android Lifecycle callback transfers the control to the OnCreate method of the main class.

Malware code showing onCreate method

Figure 9. onCreate method of the main class decrypting the payload

Next, the malware-defined function decryptAssetToDex (a meaningful name we assigned during analysis) receives the string “CuffGmrQRT” as the first argument, which is the name of the encrypted file stored in the Assets folder.

Malware code showing decryption of assets

Figure 10. Decrypting the assets

After being decrypted, the asset turns into the .dex file. This is a notable behavior that is characteristic of this ransomware family.

Comparison of code of Asset file before and after decryption

Figure 11. Asset file before and after decryption

Once the encrypted executable is decrypted and dropped in the storage, the malware has the definitions for all the components it declared in the manifest file. It then starts the final detonator function to load the dropped .dex file into memory and triggers the main payload.

Malware code showing loading of decrypted dex file

Figure 12. Loading the decrypted .dex file into memory and triggering the main payload

Main payload

When the main payload is loaded into memory, the initial detonator hands over the control to the main payload by invoking the method XoqF (which we renamed to triggerInfection during analysis) from the gvmthHtyN class (renamed to PayloadEntry).

Malware code showing handover from initial module to main payload

Figure 13. Handover from initial module to the main payload

As mentioned, the initial handover component called triggerInfection with an instance of appObj and a method that returns the value for the variable config.

Malware code showing definition of populateConfigMap

Figure 14. Definition of populateConfigMap, which loads the map with values

Correlating the last two steps, one can observe that the malware payload receives the configuration for the following properties:

  1. number – The default number to be send to the server (in case the number is not available from the device)
  2. api – The API key
  3. url – The URL to be used in WebView to display on the ransom note

The malware saves this configuration to the shared preferences of the app data and then it sets up all the Broadcast Receivers. This action registers code components to get notified when certain system events happen. This is done in the function initComponents.

Malware code showing initializing broadcast receiver

Figure 15. Initializing the BroadcastReceiver against system events

From this point on, the malware execution is driven by callback functions that are triggered on system events like connectivity change, unlocking the phone, elapsed time interval, and others.

 

Dinesh Venkatesan

Microsoft Defender Research

 

The post Sophisticated new Android malware marks the latest evolution of mobile ransomware appeared first on Microsoft Security Blog.

]]>