Cross-platform threats News and Insights | Microsoft Security Blog http://approjects.co.za/?big=en-us/security/blog/tag/cross-platform-threats/ Expert coverage of cybersecurity topics Wed, 03 Jul 2024 14:49:15 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 New macOS vulnerability, Migraine, could bypass System Integrity Protection http://approjects.co.za/?big=en-us/security/blog/2023/05/30/new-macos-vulnerability-migraine-could-bypass-system-integrity-protection/ Tue, 30 May 2023 16:00:00 +0000 A new vulnerability, which we refer to as “Migraine”, could allow an attacker with root access to bypass System Integrity Protection (SIP) in macOS and perform arbitrary operations on a device.

The post New macOS vulnerability, Migraine, could bypass System Integrity Protection appeared first on Microsoft Security Blog.

]]>
A new vulnerability, which we refer to as “Migraine” for its involvement with macOS migration, could allow an attacker with root access to automatically bypass System Integrity Protection (SIP) in macOS and perform arbitrary operations on a device. We shared these findings with Apple through Coordinated Vulnerability Disclosure (CVD) via Microsoft Security Vulnerability Research (MSVR). A fix for this vulnerability, now identified as CVE-2023-32369, was included in the security updates released by Apple on May 18, 2023.

SIP is a security technology in macOS that restricts a root user from performing operations that may compromise system integrity. Bypassing SIP could lead to serious consequences, such as increasing the potential for attackers and malware authors to successfully install rootkits, create persistent malware, and expand the attack surface for additional techniques and exploits. The technique uncovered in this blog post was discovered during routine malware hunting and is similar to the one used in the Shrootless vulnerability (CVE-2021-30892) that we published in 2021. By focusing on system processes that are signed by Apple and have the com.apple.rootless.install.heritable entitlement, we found two child processes that could be tampered with to gain arbitrary code execution in a security context that bypasses SIP checks.

In this blog post, we share some information about the relationship between SIP and entitlements, and we detail how the “Migraine” vulnerability could be exploited to bypass the SIP security enforcements. We’re sharing this research with the larger security community to emphasize the importance of collaboration in the effort to secure platforms and devices.

SIP and entitlements

As previously covered in our Shrootless vulnerability blog post, System Integrity Protection (SIP)—also known as “rootless”—was first introduced by Apple in macOS Yosemite. SIP essentially locks down the system from root by leveraging the Apple sandbox to protect the entire platform, conceptually similar to how SELinux protects Linux systems. One of the most dominant features of SIP is the filesystem restriction capability, which protects entire files and directories from being overridden. The files and directories that are protected by SIP by default are commonly ones that are related to the system’s integrity.

There is no way to turn off SIP on a live system—the user must use the recovery OS, which requires physical access to the device. A SIP bypass is a vulnerability that bypasses SIP restrictions, for example, bypassing restrictions to write to SIP-protected directories or create a SIP-protected file.

Another important macOS concept is entitlements. According to documentation, “an entitlement is a right or privilege that grants an executable particular capabilities”. As entitlements take part in the app signing process, there is no legitimate way of forging them. Apple uses entitlements extensively to enforce security on macOS, and Apple grants internal entitlements to very specific processes. Specifically, certain processes are assigned entitlements that allow the process to bypass System Integrity Protection checks by design. One particularly interesting entitlement is the com.apple.rootless.install.heritable entitlement that allows the process and the entire process tree rooted under it to bypass filesystem-based System Integrity Protection security enforcements.

Discovering a SIP bypass by design

Our research team regularly looks for malware and suspicious activity. During a routine malware hunt, we discovered the execution of a binary called drop_sip using the below advanced hunting query in Microsoft 365 Defender:

DeviceProcessEvents
| where FileName =~ "drop_sip"
| project InitiatingProcessFileName, ProcessCommandLine, SHA256

Thinking that we found an exploit in the wild, we found that it’s an Apple-signed binary that resides natively under the /System/Library/PrivateFrameworks/SystemMigrationUtils.framework/Resources/Tools/drop_sip path.

Upon analysis, the file appears to invoke the csops system call (undocumented, but available here) and starts a child process. The operation flag for the csops call is 12 (CS_OPS_CLEARINSTALLER), which re-enables SIP checks by clearing codesigning flags, specifically the CS_EXEC_INHERIT_SIP flag:

Code displaying drop_sip’s functionality
Figure 1. drop_sip’s functionality is to change the code signing flags and execute a child process
Code displaying re-enabling SIP
Figure 2. Modification of the p_csflags member as a result of the csops system call – re-enables SIP

Because of this behavior, we concluded the drop_sip process assumes it can bypass SIP. However, since drop_sip is not entitled with any SIP-bypassing entitlements, we concluded that it must inherit that capability. We discovered its parent process is systemmigrationd, which is a daemon designed to handle migration scenarios, but most importantly, it’s entitled with the com.apple.rootless.install.heritable entitlement that allows its child processes to bypass SIP security checks:

Code displaying systemmigrationd entitlements
Figure 3. systemmigrationd entitled with SIP-bypassing capabilities

Developing a “Migraine”

After discovering the parent process of drop_sip, we wondered if there are any other child processes of systemmigrationd. Just as before, we used the below advanced hunting query in Microsoft 365 Defender:

DeviceProcessEvents
| where InitiatingProcessFileName =~ "systemmigrationd"
| summarize Hits=count(), Cmdline=any(ProcessCommandLine) by FileName

We found two interesting child processes of systemmigrationd:

FileNameHitsCmdline
bash498/bin/bash /System/Library/PrivateFrameworks/SystemMigration.framework/Resources/MigrationData/Scripts/firstbootDirectoryServer
perl171/usr/bin/perl /usr/libexec/migrateLocalKDC –source “/Volumes/REDACTED/Backups.backupdb/REDACTED/Macintosh HD – Data” –source-REDACTED

The bash and perl binaries are interesting because they are both interpreters. Similar to how we tampered with the zsh codeflow back in 2021, we found similar ways to tamper with the code flow of bash and perl:

Code displaying running arbitrary commands in bash instances
Figure 4. The bash manual page states BASH_ENV as a way to run arbitrary commands in bash instances
Code displaying running arbitrary commands in perl instances
Figure 5. The “perlrun” manual page states PERL5OPT as a way to run arbitrary commands in perl instances

Assuming an attacker first gains code execution capabilities as root, setting environment variables that affect systemmigrationd and its child processes is straightforward using the launchctl utility. For instance, to make perl run our arbitrary code that resides under /private/tmp/migraine.sh, we use:

launchctl setenv PERL5OPT '-Mwarnings;system("/private/tmp/migraine.sh")'

And indeed, after triggering systemmigrationd to run perl, we were able to bypass SIP:

Code displaying SIP protections making a file undeletable
Figure 6. Creating an undeletable file due to its SIP protection.

Exploitation approach

Triggering migration normally requires using the Migration Assistant utility, which involves a complete sign-out from the system. While this works well for attackers with physical access (hands-on-keyboard), we wished to demonstrate that remote attackers can achieve a SIP bypass using this exploit. Therefore, we decided to research the migration flow and the interplay between the Migration Assistant and systemmigrationd.

Migration is a complicated procedure that involves several components. Here is the flow of key events:

  1. Migration Assistant uses a utility called Setup Assistant to help start migration. However, it does so indirectly by using XPC between itself and another process called MBSystemAdministration. It also signs out by invoking a method named SACLOStartLogoutWithOptions.
  2. The MBSystemAdministration utility proxies requests from Migration Assistant to Setup Assistant and also verifies that the caller (Migration Assistant) has the com.apple.private.mbsystemadministration entitlement. Otherwise, it refuses serving migration requests. Additionally, MBSystemAdministration runs as the hidden user _mbsetupuser, which allows migration to perform GUI interactions after sign out.
  3. Setup Assistant gets requests through MBSystemAdministration and performs XPC to several Mach services that are served by the launch daemon systemmigrationd. The systemmigrationd daemon enforces that the caller (Setup Assistant) has the com.apple.private.systemmigration.daemonclient entitlement. Otherwise, it refuses serving migration requests. The systemmigrationd daemon uses the private framework SystemMigration.framework and listens to new migration requests by invoking a method called startListeningForConnections. Interestingly, the daemon examines the contents of the directory /Library/SystemMigration/Queue (which is protected by SIP)—requests appear as files in that directory. Once a file is dropped, systemmigrationd renames the file to “In-Flight” and serves it, including running required scripts, which can cause perl or bash to run.

This complex flow can be illustrated with the following schematic:

Flow diagram of macOS migration
Figure 7. Flow diagram of the macOS migration
Code displaying systemmigrationd listening to incoming connections
Figure 8. systemmigrationd using the private SystemMigration framework to listen to incoming connections

Our first attempt at automating the exploit focused on patching Migration Assistant to prevent user sign-out:

Code displaying SACLOStartLogoutWithOptions
Figure 9. Reverse engineering the Migration Assistant reveals the SACLOStartLogoutWithOptions function,c which signs out

Simply patching Migration Assistant does not work due to codesign failure. Stripping the binary of signing information results in error (Figure 10) due to a kernel feature related to Pointer Authentication Codes (PAC) that’s available for the latest Apple Silicone architecture. If an arm64e binary with pointer authentication is not a code-signed platform binary, the kernel prevents execution, as shown in Figure 9. Extracting, stripping, and patching the x64 portion of the multiarchitecture binary avoids the arm64e issue, but it’s not functional due to losing the required entitlement (com.apple.private.mbsystemadministration).

Code displaying PAC requirements
Figure 10. Pointer Authentication Code requirements
Code displaying the failed patch and run attempt of the Migration Assistant
Figure 11. Attempting to patch and run the Migration Assistant fails

After reaching an impasse with patching Migration Assistant, we wondered if we could initiate later stages in the flow diagram, thus avoiding user sign-out. We continued to map and reverse-engineer the system behavior, including using an in-house researcher tool which leverages the Endpoint Security Framework that logs all relevant process and file events during migration, inspired by Patrick Wardle’s FileMonitor and ProcessMonitor tools for investigating system behaviors.

While mapping the sequence of events for Migration Assistant, MBSystemAdministration, Setup Assistant, and systemmigrationd, we noticed xpcproxy executing Setup Assistant with the argument ‑MiniBuddyYes.

Running Setup Assistant with that argument had no effect on the UI layout or its functionality, but it did highlight the usage of arguments within Setup Assistant. Closely examining Setup Assistant, we discovered other interesting command-line arguments:

Code displaying Setup Assistant's usage of -MiniBuddyYes
Figure 12. Setup Assistant’s usage of -MiniBuddyYes within useDebugParameters

Additionally, we discovered a function called useDebugParameters that parses an interesting command-line parameter ‑MBDebug.

Code displaying Setup Assistant –MBDebug
Figure 13. Setup Assistant –MBDebug

Running the Setup Assistant with the ‑MBDebug parameter results in a successful migration with no sign out. We further used the -ResumeBuddyYes parameter in conjunction with ‑MBDebug to automatically skip a few welcome screens.

Successful migration run without signing out
Figure 14. Running a migration without signing out

Since performing migration requires UI interaction, but no sign-out, we used AppleScript to automate the exploit.

Our final exploit does the following:

  1. Prepares a small 1GB Time Machine backup and attaches it with hdiutil.
  2. Prepares an arbitrary payload that is designed to run without SIP filesystem restrictions.
  3. Sets the environment variable PERL5OPT using launchctl to run the payload once perl starts.
  4. Runs Setup Assistant with the -MBDebug and -ResumeBuddyYes command-line flags.
  5. Uses AppleScript to automate the Setup Assistant screens to migrate “From a Mac, Time Machine backup or Startup disk”, followed by automatically clicking “continue”.

Implications of arbitrary SIP bypasses

The implications of arbitrary SIP bypasses are serious, as the potential for malware authors is significant. Code that maliciously bypasses SIP could have considerable consequences, such as:

  1. Create undeletable malware: The most straight-forward implication of a SIP bypass is that, by assigning files with the com.apple.rootless extended attribute (or overriding existing ones), an attacker can create files that are protected by SIP and therefore undeletable by ordinary means. This is quite important for security solutions, such as Microsoft Defender for Endpoint, that are required to quarantine malware but cannot quarantine files protected by SIP.
  2. Expand the attack surface for userland and kernel attacker techniques: As pointed out by Mickey Jin’s blog post on a different SIP bypass, it’s possible for attackers to gain arbitrary kernel code execution. As Apple slowly disallows third party kernel extensions and transitions the Mac ecosystem towards their Endpoint Security framework, security solutions will no longer be able to monitor the kernel for malicious activity, including malicious code executions.
  3. Tamper with the integrity of the system, effectively enabling rootkits: This is a derivation of arbitrary kernel code execution—once kernel code execution is established by an attacker, certain rootkit techniques are possible, such as hiding processes or files from all monitoring tools. These techniques might also include bypassing tamper protection, which is important for Microsoft Defender for Endpoint to protect against threats.
  4. Full TCC bypass: As pointed out by Mickey Jin’s blog post on a different SIP bypass, attackers could replace databases that control Transparency, Consent, and Control (TCC) policies (TCC.db), effectively granting arbitrary applications access to private data and peripherals. For further explanation about the implications, we’ve demonstrated a TCC bypass in the past called “Powerdir”.

Hardening device security through collaboration and research-driven protection

Attackers continue to seek new footholds into increasingly secure devices and networks, oftentimes by leveraging unpatched vulnerabilities and misconfigurations to access valuable systems and data. Gaining the ability to bypass SIP and similar security technology in macOS devices can be an attractive and even necessary capability for adversaries. Given SIP’s position as both a device’s built-in baseline protection and the last line of defense against malware and other threats, bypassing SIP can have considerable consequences for users. As such, it’s crucial that we strive to enrich our protection technologies across platforms against such issues through research-driven protection and collaboration with partners, customers, and industry experts.

This case displays how collaborative research and responsible vulnerability disclosure informs our comprehensive protection capabilities across platforms to provide organizations a complete picture of their security posture. Microsoft Defender Vulnerability Management quickly discovers and remediates such vulnerabilities while Microsoft Defender for Endpoint detects and alerts on anomalous device activities, including setting perl and bash environment variables through the launchctl utility, as shown below in Figure 15. Additionally, Defender for Endpoint has similar detections for sensitive file access, including system launch daemons, various sensitive configuration files, and many more.

Microsoft Defender for Endpoint detecting the PERL5OPT environment variable being suspiciously set
Figure 15. Microsoft Defender for Endpoint detecting the PERL5OPT environment variable being suspiciously set

This case further emphasizes the need for responsible vulnerability disclosures and expert cross-platform collaboration to mitigate issues such as CVE-2023-32369, regardless of the vulnerable device or platform in use. We wish to thank the Apple product security team again for their efforts and responsiveness in addressing the issue.

Defending against the evolving threat landscape requires the ability to protect and secure users’ computing experiences, whatever the platform. As cross-platform threats continue to grow, we will continue to share vulnerability discoveries and threat intelligence in addition to working with the security community to improve upon solutions that protect users and organizations each day.

Jonathan Bar Or, Michael Pearse, Anurag Bohra

Microsoft Threat Intelligence Community

References   

The post New macOS vulnerability, Migraine, could bypass System Integrity Protection appeared first on Microsoft Security Blog.

]]>
MCCrash: Cross-platform DDoS botnet targets private Minecraft servers http://approjects.co.za/?big=en-us/security/blog/2022/12/15/mccrash-cross-platform-ddos-botnet-targets-private-minecraft-servers/ Thu, 15 Dec 2022 18:00:00 +0000 The Microsoft Defender for IoT research team analyzed a cross-platform botnet that infects both Windows and Linux systems from PCs to IoT devices, to launch distributed denial of service (DDoS) attacks against private Minecraft servers.

The post MCCrash: Cross-platform DDoS botnet targets private Minecraft servers appeared first on Microsoft Security Blog.

]]>

April 2023 update – Microsoft Threat Intelligence has shifted to a new threat actor naming taxonomy aligned around the theme of weather. DEV-1028 is now tracked as Storm-1028.

To learn about how the new taxonomy represents the origin, unique traits, and impact of threat actors, and to get a complete mapping of threat actor names, read this blog: Microsoft shifts to a new threat actor naming taxonomy.

Malware operations continue to rapidly evolve as threat actors add new capabilities to existing botnets, increasingly targeting and recruiting new types of devices. Attackers update malware to target additional operating systems, ranging from PCs to IoT devices, growing their infrastructure rapidly. The Microsoft Defender for IoT research team recently analyzed a cross-platform botnet that originates from malicious software downloads on Windows devices and succeeds in propagating to a variety of Linux-based devices.

The botnet spreads by enumerating default credentials on internet-exposed Secure Shell (SSH)-enabled devices. Because IoT devices are commonly enabled for remote configuration with potentially insecure settings, these devices could be at risk to attacks like this botnet. The botnet’s spreading mechanism makes it a unique threat, because while the malware can be removed from the infected source PC, it could persist on unmanaged IoT devices in the network and continue to operate as part of the botnet.

Microsoft tracks this cluster of activity as DEV-1028, a cross-platform botnet that infects Windows devices, Linux devices, and IoT devices. The DEV-1028 botnet is known to launch distributed denial of service (DDoS) attacks against private Minecraft servers.

Our analysis of the DDoS botnet revealed functionalities specifically designed to target private Minecraft Java servers using crafted packets, most likely as a service sold on forums or darknet sites. A breakdown of the systems affected by the botnet over the three months from the time of this analysis also revealed that most of the devices were in Russia:

A geographical map that presents the countries where the devices affected by the botnet are located. Countries with affected devices are highlighted on the map in blue.
Figure 1. IP distribution of devices infected by the botnet

This type of threat stresses the importance of ensuring that organizations manage, keep up to date, and monitor not just traditional endpoints but also IoT devices that are often less secure. In this blog post, we share details on how this botnet affects multiple platforms, its DDoS capabilities, and recommendations for organizations to prevent their devices from becoming part of a botnet. We also share Minecraft server version information for owners of private servers to update and ensure they are protected from this threat.

Cross-platform botnet targets SSH-enabled devices

Microsoft researchers observed that the initial infection points related to the botnet were devices infected through the installation of malicious cracking tools that purport to acquire illegal Windows licenses.

Two screenshots of the user interfaces of the cracking tools used to spread the MCCrash botnet.
Figure 2. Cracking tools used to spread the botnet.

The cracking tools contain additional code that downloads and launches a fake version of svchost.exe through a PowerShell command. In some cases, the downloaded file is named svchosts.exe.

A screenshot of malware code from an analysis tool, specifically the function where the malware downloads and runs the malicious file, svchost.exe.
Figure 3. The code of the .NET executable that downloads and runs svchost.exe

Next, svchost.exe launches malicious.py, the main Python script that contains all the logic of the botnet, whichthen scans the internet for SSH-enabled Linux-based devices (Debian, Ubuntu, CentOS, and IoT workloads such as Raspbian, which are commonly enabled for remote configuration) and launches a dictionary attack to propagate. Once a device is found, it downloads the file Updater.zip from repo[.]ark—event[.]net onto the device, which creates the file fuse. The fuse file then downloads a copy of malicious.py onto the device. Both svchost.exe and fuse are compiled using PyInstaller, which bundles all the Python runtime and libraries necessary to initiate malicious.py.

A graphic that presents the entire DDoS botnet attack flow from initial infection through a malicious cracking software to the running of DDoS commands from infected devices.
Figure 4. The DDoS botnet attack flow

While malicious.py has specific functionalities depending on whether the file launches on a Windows or Linux-based device (for Windows, the file establishes persistency by adding the registry key Software\Microsoft\Windows\CurrentVersion\Run with the executable as the value), the executable is compiled to operate on both Windows and Linux-based devices. The file communicates with its command-and-control (C2) server to launch the following commands:

  • Establish TCP connection to repo[.]ark-event[.]net on port 4676.
  • Send initial connection string.
  • Receive a key from the server for encryption and decryption, and then encrypt further communication using the Fernet symmetric algorithm.
  • Send version information to the server:
    • Windows device: The current Windows version
    • Linux device: Hardcoded version (2.19 in the sample we analyzed)
  • Continue receiving encrypted commands from the server

Based on our analysis, the botnet is primarily used to launch DDoS attacks against private Minecraft servers using known server DDoS commands and unique Minecraft commands. Below is the list of commands established in the code:

CommandDescription
SYNCCheck that malware is running
PROXY_<url>Set proxy servers
DOWNLOAD_<url>Download file
EXEC_<command >Run specific command line
SCANNER[ON|OFF]Default credentials attack on SSH servers to spread
ATTACK_TCPSend random TCP payloads
ATTACK_[HOLD|HANDSHAKE]Send random TCP payloads through proxy
ATTACK_UDPSend random UDP payload
ATTACK_VSEAttack on Valve Source Engine protocol
ATTACK_RAKNETAttack on RakNet protocol (used by Minecraft servers)
ATTACK_NETTYMinecraft – Login handshake Packet
ATTACK_[MCBOT|MINE]Minecraft – Login Start Packet
ATTACK_[MCPING|PING]Minecraft – Login Success Packet
ATTACK_MCDATAMinecraft – Login Handshake, Login Start and Close Window Packets
ATTACK_MCCRASHMinecraft – Login Handshake and Login Start packets, using Username with env variable
ATTACK_JUNKSend Tab-Complete packet
ATTACK_HTTP-GETSend GET request
ATTACK_HTTP-FASTSend HEAD request
STOP_ATTACKStop the previous attack

While most of the commands are methods of DDoS, the most notable command run by the botnet is ATTACK_MCCRASH. The command sends ${env:random payload of specific size:-a} as the username in order to exhaust the resources of the server and make it crash.

A screenshot of packet capture results that presents details of the malware's TCP payload.
Figure 5. MCCrash TCP payload seen in a packet capture

TCP payloads on port 25565 have the following binary structure:

  • Bytes [0:1] – Size of packet
  • Bytes [1:2] – Login Start command
  • Bytes [2:3] – Size of username
  • Bytes [3:18] – Username string

The usage of the env variable triggers the use of Log4j 2 library, which causes abnormal consumption of system resources (not related to Log4Shell vulnerability), demonstrating a specific and highly efficient DDoS method.

A wide range of Minecraft server versions could be affected

While testing the impact of the malware, researchers found that the malware itself was hardcoded to target a specific version of Minecraft server, 1.12.2. However, all versions between 1.7.2 and 1.18.2 can be affected by this method of attack. There is a slight modification in the Minecraft protocol in server version 1.19, which was released earlier in 2022, that prevents the use of the Minecraft specific commands, the ATTACK_MCCRASH, ATTACK_[MCBOT|MINE] and ATTACK_MCDATA, without modification of the attack code.

A pie chart that presents the distribution of Minecraft servers based on their version.
Figure 6. Distribution of Minecraft servers by version
A geographical map that presents the countries where Minecraft servers that can be affected by MCCrash are located. Countries with servers that can be affected are highlighted on the map in blue.
Figure 7. Distribution of Minecraft servers that could be affected by MCCrash

The wide range of at-risk Minecraft servers highlights the impact this malware could have had if it was specifically coded to affect versions beyond 1.12.2. The unique ability of this threat to utilize IoT devices that are often not monitored as part of the botnet substantially increases its impact and reduces its chances of being detected.

Protecting endpoints from cross-platform DDoS botnets like MCCrash

To harden devices networks against threats like MCCrash, organizations must implement the basics to secure identities and their devices, including access limitation. Solutions must detect downloads of malicious programs and malicious attempts to gain access to SSH-enabled devices and generate alerts on anomalous network behavior. Below are some of our recommendations for organizations:

  • Ensure employees are not downloading cracking tools as these are abused as an infection source for spreading malware.
  • Increase network security by enforcing multi-factor authentication (MFA) methods such as Azure Active Directory (now part of Microsoft Entra) MFA. Enable network protection to prevent applications or users from accessing malicious domains and other malicious content on the internet.

    Microsoft 365 Defender protects against attacks related to botnets by coordinating threat data across identities, endpoints, cloud apps, email, and documents. Such cross-domain visibility allows Microsoft 365 Defender to comprehensively detect and remediate end-to-end attack chains—from malicious downloads to its follow-on activities in endpoints. This rich set of tools like advanced hunting let defenders surface threats and gain insights for hardening networks from compromise.
  • Adopt a comprehensive IoT security solution such as Microsoft Defender for IoT to allow visibility and monitoring of all IoT and OT devices, threat detection and response, and integration with SIEM/SOAR and XDR platforms such as Microsoft Sentinel and Microsoft 365 Defender. Defender for IoT is updated regularly with indicators of compromise (IoCs) from threat research like the example described in this blog, alongside rules to detect malicious activity.

    On the IoT device level:
    • Ensure secure configurations for devices: Change the default password to a strong one, and block SSH from external access.
    • Maintain device health with updates: Make sure devices are up to date with the latest firmware and patches.
    • Use least privileges access: Use a secure virtual private network (VPN) service for remote access and restrict remote access to the device.
  • For users hosting private Minecraft servers, update to version 1.19.1 and above.
  • Adopt a comprehensive Windows security solution
    • Manage the apps your employees can use through Windows Defender Application Control and for unmanaged solutions, enabling Smart App Control.
    • For commercial customers, enable application and browser controls such as Microsoft Defender Application Guard for enhanced protection for Office and Edge.
    • Perform timely cleanup of all unused and stale executables sitting on your organizations’ devices.
    • Protect against advanced firmware attacks by enabling memory integrity, Secure Boot, and Trusted Platform Module 2.0, if not enabled by default, which hardens boot using capabilities built into modern CPUs.

Indicators of compromise (IOCs)

  • e3361727564b14f5ee19c40f4e8714fab847f41d9782b157ea49cc3963514c25 (KMSAuto++.exe)
  • 143614d31bdafc026827e8500bdc254fc1e5d877cb96764bb1bd03afa2de2320 (W10DigitalActivation.exe)
  • f9c7dd489dd56e10c4e003e38428fe06097aca743cc878c09bf2bda235c73e30 (dcloader.exe)
  • 4e65ec5dee182070e7b59db5bb414e73fe87fd181b3fc95f28fe964bc84d2f1f (updater.zip)
  • eb57788fd2451b90d943a6a796ac5e79f0faf7151a62c1d07b744a351dcfa382 (svchosts.exe)
  • 93738314c07ea370434ac30dad6569c59a9307d8bbde0e6df9be9e2a7438a251 (fuse)
  • 202ac3d32871cb3bf91b7c49067bfc935fbc7f0499d357efead1e9f7f5fcb9d1 (malicious.py)
  • repo[.]ark-event[.]net

Detections

Microsoft Defender Antivirus

Microsoft Defender Antivirus detects the malware used in this attack as the following:

  • TrojanDownloader:MSIL/MCCrash.NZM!MTB
  • Trojan:Win32/MCCrash.MA!MTB
  • TrojanDownloader:Python/MCCrash!MTB
  • Trojan:Python/MCCrash.A
  • TrojanDownloader:Linux/MCCrash!MTB
  • Trojan:Python/MCCrash.RPB!MTB
  • Trojan:Python/MCCrash.RPC!MTB

Microsoft Defender for Endpoint

Microsoft Defender for Endpoint alerts with the following titles can indicate threat activity on your network:

  • Emerging threat activity group DEV-1028 detected
  • System file masquerade
  • Anomaly detected in ASEP registry
  • Suspicious process launched using cmd.exe
  • Suspicious file launch

Microsoft Defender for IoT

MCCrash-related activity on IoT devices would raise the following alerts in Microsoft Defender for IoT:

  • Unauthorized SSH access
  • Excessive login attempts

Microsoft Defender for Cloud

Microsoft Defender for Cloud raises the following alert for related activity:

  • VM_SuspectDownload

Advanced hunting queries

Microsoft 365 Defender

Run the following queries to search for related files in your environment:

DeviceFileEvents
| where SHA256 in ("e3361727564b14f5ee19c40f4e8714fab847f41d9782b157ea49cc3963514c25","143614d31bdafc026827e8500bdc254fc1e5d877cb96764bb1bd03afa2de2320","f9c7dd489dd56e10c4e003e38428fe06097aca743cc878c09bf2bda235c73e30","4e65ec5dee182070e7b59db5bb414e73fe87fd181b3fc95f28fe964bc84d2f1f","eb57788fd2451b90d943a6a796ac5e79f0faf7151a62c1d07b744a351dcfa382","93738314c07ea370434ac30dad6569c59a9307d8bbde0e6df9be9e2a7438a251","202ac3d32871cb3bf91b7c49067bfc935fbc7f0499d357efead1e9f7f5fcb9d1")

DeviceFileEvents
| where FolderPath endswith @":\windows\svchost.exe"

DeviceRegistryEvents
| where RegistryKey contains "CurrentVersion\\Run"
| where RegistryValueName == "br" or RegistryValueData contains "svchost.exe" or RegistryValueData contains "svchosts.exe"

DeviceProcessEvents
| where FileName in~ ("cmd.exe", "powershell.exe")
| where ProcessCommandLine has_all ("-command", ".downloadfile(", "windows/svchost.exe")

Microsoft Sentinel

Microsoft Sentinel customers can use the TI Mapping analytic 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

To supplement this indicator matching, customers can use the following queries against data ingested into their workspaces to help find devices with exposed SSH endpoints, and devices that might be under SSH brute force attempts.

Potential SSH brute force attempt: https://github.com/Azure/Azure-Sentinel/blob/master/Detections/Syslog/ssh_potentialBruteForce.yaml

Exposed critical ports in Azure: https://github.com/Azure/Azure-Sentinel/blob/master/Hunting%20Queries/AzureDiagnostics/CriticalPortsOpened.yaml

David Atch, Maayan Shaul, Mae Dotan, Yuval Gordon, Microsoft Defender for IoT Research Team

Ross Bevington, Microsoft Threat Intelligence Center (MSTIC)

The post MCCrash: Cross-platform DDoS botnet targets private Minecraft servers 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.

]]>
New macOS vulnerability, “powerdir,” could lead to unauthorized user data access http://approjects.co.za/?big=en-us/security/blog/2022/01/10/new-macos-vulnerability-powerdir-could-lead-to-unauthorized-user-data-access/ Mon, 10 Jan 2022 17:00:00 +0000 A new macOS vulnerability, “powerdir,” could allow an attacker to bypass the operating system’s TCC technology and gain unauthorized access to a user’s protected data. We shared our findings with Apple through Coordinated Vulnerability Disclosure (CVD) and Apple released a fix.

The post New macOS vulnerability, “powerdir,” could lead to unauthorized user data access appeared first on Microsoft Security Blog.

]]>
Following our discovery of the “Shrootless” vulnerability, Microsoft uncovered a new macOS vulnerability, “powerdir,” that could allow an attacker to bypass the operating system’s Transparency, Consent, and Control (TCC) technology, thereby gaining unauthorized access to a user’s protected data. We shared our findings with Apple through Coordinated Vulnerability Disclosure (CVD) via Microsoft Security Vulnerability Research (MSVR). Apple released a fix for this vulnerability, now identified as CVE-2021-30970, as part of security updates released on December 13, 2021. We encourage macOS users to apply these security updates as soon as possible.

Introduced by Apple in 2012 on macOS Mountain Lion, TCC is essentially designed to help users configure the privacy settings of their apps, such as access to the device’s camera, microphone, or location, as well as access to the user’s calendar or iCloud account, among others. To protect TCC, Apple introduced a feature that prevents unauthorized code execution and enforced a policy that restricts access to TCC to only apps with full disk access. We discovered that it is possible to programmatically change a target user’s home directory and plant a fake TCC database, which stores the consent history of app requests. If exploited on unpatched systems, this vulnerability could allow a malicious actor to potentially orchestrate an attack based on the user’s protected personal data. For example, the attacker could hijack an app installed on the device—or install their own malicious app—and access the microphone to record private conversations or capture screenshots of sensitive information displayed on the user’s screen.

It should be noted that other TCC vulnerabilities were previously reported and subsequently patched before our discovery. It was also through our examination of one of the latest fixes that we came across this bug. In fact, during this research, we had to update our proof-of-concept (POC) exploit because the initial version no longer worked on the latest macOS version, Monterey. This shows that even as macOS or other operating systems and applications become more hardened with each release, software vendors like Apple, security researchers, and the larger security community, need to continuously work together to identify and fix vulnerabilities before attackers can take advantage of them.

Microsoft security researchers continue to monitor the threat landscape to discover new vulnerabilities and attacker techniques that could affect macOS and other non-Windows devices. The discoveries and insights from our research enrich our protection technologies and solutions, such as Microsoft Defender for Endpoint, which allows organizations to gain visibility to their networks that are increasingly becoming heterogeneous. For example, this research informed the generic detection of behavior associated with this vulnerability, enabling Defender for Endpoint to immediately provide visibility and protection against exploits even before the patch is applied. Such visibility also enables organizations to detect, manage, respond to, and remediate vulnerabilities and cross-platform threats faster.

In this blog post, we will share some information about TCC, discuss previously reported vulnerabilities, and present our own unique findings.

TCC overview

As mentioned earlier, TCC is a technology that prevents apps from accessing users’ personal information without their prior consent and knowledge. The user commonly manages it under System Preferences in macOS (System Preferences > Security & Privacy > Privacy):

Screenshot of the Security & Privacy pane on macOS
Figure 1. The macOS Security & Privacy pane that serves as the front end of TCC.

TCC maintains databases that contain consent history for app requests. Generally, when an app requests access to protected user data, one of two things can happen:

  1. If the app and the type of request have a record in the TCC databases, then a flag in the database entry dictates whether to allow or deny the request without automatically and without any user interaction.
  2. If the app and the type of request do not have a record in the TCC databases, then a prompt is presented to the user, who decides whether to grant or deny access. The said decision is backed into the databases so that succeeding similar requests will now fall under the first scenario.

Under the hood, there are two kinds of TCC databases. Each kind maintains only a subset of the request types:

  • User-specific database: contains stored permission types that only apply to the specific user profile; it is saved under ~/Library/Application Support/com.apple.TCC/TCC.db and can be accessed by the user who owns the said profile
  • System-wide database: contains stored permission types that apply on a system level; it is saved under /Library/Application Support/com.apple.TCC/TCC.db and can be accessed by users with root or full disk access

macOS implements the TCC logic by using a special daemon called tccd. Indeed, there are at least two instances of tccd: one run by the user and the other by root.

Screenshot of two tccd instances
Figure 2. Two tccd instances: per-user and system-wide.

Each type of request starts with a kTCCService prefix. While not an exhaustive list, below are some examples:

Request typeDescriptionHandled by
kTCCServiceLiverpoolLocation services accessUser-specific TCC database
kTCCServiceUbiquityiCloud accessUser-specific TCC database
kTCCServiceSystemPolicyDesktopFolderDesktop folder accessUser-specific TCC database
kTCCServiceCalendarCalendar accessUser-specific TCC database
kTCCServiceRemindersAccess to remindersUser-specific TCC database
kTCCServiceMicrophoneMicrophone accessUser-specific TCC database
kTCCServiceCameraCamera accessUser-specific TCC database
kTCCServiceSystemPolicyAllFilesFull disk access capabilitiesSystem-wide TCC database
kTCCServiceScreenCaptureScreen capture capabilitiesSystem-wide TCC database
Table 1. Types of TCC requests.

It should also be noted that the TCC.db file is a SQLITE database, so if a full disk access is granted to a user, they can view the database and even edit it:

Screenshot of TCC.db access table dump
Figure 3. Dumping the TCC.db access table, given a full disk access.

The database columns are self-explanatory, save for the csreq column. The csreq values contain a hexadecimal blob that encodes the code signing requirements for the app. These values can be calculated easily with the codesign and csreq utilities, as seen in Figure 4 below:

Screenshot of building the csreq blob
Figure 4. Building the csreq blob manually for an arbitrary app.

Given these, should a malicious actor gain full disk access to the TCC databases, they could edit it to grant arbitrary permissions to any app they choose, including their own malicious app. The affected user would also not be prompted to allow or deny the said permissions, thus allowing the app to run with configurations they may not have known or consented to.

Securing (and bypassing) TCC: Techniques and previously reported vulnerabilities

Previously, apps could access the TCC databases directly to view and even modify their contents. Given the risk of bypass mentioned earlier, Apple made two changes. First, Apple protected the system-wide TCC.db via System Integrity Protection (SIP), a macOS feature that prevents unauthorized code execution. Secondly, Apple enforced a TCC policy that only apps with full disk access can access the TCC.db files. Note, though, that this policy was also subsequently abused as some apps required such access to function properly (for example, the SSH daemon, sshd).

Interestingly, attackers can still find out whether a user’s Terminal has full disk access by simply trying to list the files under /Library/Application Support/com.apple.TCC. A successful attempt means that the Terminal has full disk access capabilities, and an attacker can, therefore, freely modify the user’s TCC.db.

In addition, there have been several previously reported vulnerabilities related to TCC bypass. These include the following:

  • Time Machine mounts (CVE-2020-9771): macOS offers a built-in backup and restore solution called Time Machine. It was discovered that Time Machine backups could be mounted (using the apfs_mount utility) with the “noowners” flag. Since these backups contain the TCC.db files, an attacker could mount those backups and determine the device’s TCC policy without having full disk access.
  • Environment variable poisoning (CVE-2020-9934): It was discovered that the user’s tccd could build the path to the TCC.db file by expanding $HOME/Library/Application Support/com.apple.TCC/TCC.db. Since the user could manipulate the $HOME environment variable (as introduced to tccd by launchd), an attacker could plant a chosen TCC.db file in an arbitrary path, poison the $HOME environment variable, and make TCC.db consume that file instead.
  • Bundle conclusion issue (CVE-2021-30713): First disclosed by Jamf in a blog post about the XCSSET malware family, this bug abused how macOS was deducing app bundle information. For example, suppose an attacker knows of a specific app that commonly has microphone access. In that case, they could plant their application code in the target app’s bundle and “inherit” its TCC capabilities.

Apple has since patched these vulnerabilities. However, based on our research, the potential bypass to TCC.db can still occur. The following section discusses the vulnerability we discovered and some details about the POC exploits we developed to prove the said vulnerability.

Modifying the home directory: The ‘powerdir’ vulnerability

In assessing the previous TCC vulnerabilities, we evaluated how Apple fixed each issue. One fix that caught our attention was for CVE-2020-9934 (the $HOME environment variable poisoning vulnerability). The fix can be seen in the _db_open function in tccd:

Screenshot of the tccd fix for CVE-2020-9934
Figure 5. The tccd fix for CVE-2020-9934.

We noted that instead of expanding the $HOME environment variable, Apple decided to invoke getpwuid() on the current user (retrieved with getuid()). First, the getpwuid function retrieves a structure in memory (struct password*) that contains information about the given user. Then, tccd extracts the pwdir member from it. This pwdir member includes the user’s home directory, and its value persists even after the $HOME environment variable is modified.

While the solution indeed prevents an attack by environment variable poisoning, it does not protect against the core issue. Thus, we set out to investigate: can an app programmatically change the user’s home directory and plant a fake TCC.db file?

The first POC exploit

Our first attempt to answer the above question was simple: plant a fake TCC.db file and change the home directory using the Directory Services command-line utility (dscl):

While requiring root access, we discovered that this works only if the app is granted with the TCC policy kTCCServiceSystemPolicySysAdminFiles, which the local or user-specific TCC.db maintains. That is weaker than having full disk access, but we managed to bypass that restriction with the dsexport and dsimport utilities.

Next, simply by exporting the Directory Services entry of a user, manipulating the output file, and importing the file again, we managed to bypass the dscl TCC policy restriction.

Our first POC exploit, therefore, does the following:

  1. Get a csreq blob for the target app.
  2. Plant a fake TCC.db file with required access and the csreq blob.
  3. Export the user’s Directory Services entry with dsexport.
  4. Modify the Directory Services entry to change the user’s home directory.
  5. Import the modified Directory Services entry with dsimport.
  6. Stop the user’s tccd and reboot the process.

Using this exploit, an attacker could change settings on any application. In the screenshot below, we show how the exploit could allow attackers to enable microphone and camera access on any app, for example, Teams.

Screenshot of the working exploit
Figure 6. Our first working POC exploit working without a popup notification from TCC.

We reported our initial findings to the Apple product security team on July 15, 2021, before becoming aware of a similar bypass presented by Wojciech Reguła and Csaba Fitzl at BlackHat USA 2021 in August. However, our exploit still worked even after Apple fixed the said similar finding (now assigned as CVE-2020-27937). Therefore, we still considered our research to be a new vulnerability.

Monterey release and the second POC exploit

We shared our findings to Apple through Coordinated Vulnerability Disclosure (CVD) via Microsoft Security Vulnerability Research (MSVR) before the release of macOS Monterey in October. However, upon the release of the said version, we noticed that our initial POC exploit no longer worked because of the changes made in how the dsimport tool works. Thus, we looked for another way of changing the home directory silently.

While examining macOS Monterey, we came across /usr/libexec/configd, an Apple binary shipped with the said latest macOS release that is a System Configuration daemon responsible for many configuration aspects of the local system. There are three aspects of configd that we took note and made use of:

  1. It is an Apple-signed binary entitled with “com.apple.private.tcc.allow” with the value kTCCServiceSystemPolicySysAdminFiles. This means it can change the home directory silently.
  2. It has extensibility in configuration agents, which are macOS Bundles under the hood. This hints that it might load a custom Bundle, meaning we could inject code for our purposes.
  3. It does not have the hardened runtime flag to load custom configuration agents. While this aspect is most likely by design, it also means we could load completely unsigned code into it.

By running configd with the -t option, an attacker could specify a custom Bundle to load. Therefore, our new POC exploit replaces the dsexport and dsimport method of changing the user’s home directory with a configd code injection. This results in the same outcome as our first POC exploit, which allows the modification of settings to grant, for example, any app like Teams, to access the camera, among other services.

As before, we shared our latest findings with Apple. Again, we want to thank their product security team for their cooperation.

Detecting the powerdir vulnerability with Microsoft Defender for Endpoint

Our research on the powerdir vulnerability is yet another example of the tight race between software vendors and malicious actors: that despite the continued efforts of the former to secure their applications through regular updates, other vulnerabilities will inevitably be uncovered, which the latter could exploit for their own gain. And as system vulnerabilities are possible entry points for attackers to infiltrate an organization’s network, comprehensive protection is needed to allow security teams to manage vulnerabilities and threats across all platforms.

Microsoft Defender for Endpoint is an industry-leading, cloud-powered endpoint security solution that lets organizations manage their heterogeneous computing environments through a unified security console. Its threat and vulnerability management capabilities empower defenders to quickly discover, prioritize, and remediate misconfigurations and vulnerabilities, such as the powerdir vulnerability. In addition, Defender for Endpoint’s unparalleled threat optics are built on the industry’s deepest threat intelligence and backed by world-class security experts who continuously monitor the threat landscape.

One of the key strengths of Defender for Endpoint is its ability to generically detect and recognize malicious behavior. For example, as seen in the previous section, our POC exploits conduct many suspicious activities, including:

  • Dropping a new TCC.db file with an appropriate directory structure
  • Killing an existing tccd instance
  • Suspicious Directory Services invocations such as dsimport and dsexport

By generically detecting behavior associated with CVE-2020-9934 (that is, dropping a new TCC.db file fires an alert), Defender for Endpoint immediately provided protection against these exploits before the powerdir vulnerability was patched. This is a testament of Defender for Endpoint’s capabilities: with strong, intelligent generalization, it will detect similar bypass vulnerabilities discovered in the future.

Screenshot of Microsoft Defender for Endpoint alert for potential TCC bypass
Figure 7. Microsoft Defender for Endpoint detecting potential TCC bypass.

Learn how Microsoft Defender for Endpoint delivers a complete endpoint security solution across all platforms.

Jonathan Bar Or

Microsoft 365 Defender Research Team

The post New macOS vulnerability, “powerdir,” could lead to unauthorized user data access appeared first on Microsoft Security Blog.

]]>
Microsoft finds new macOS vulnerability, Shrootless, that could bypass System Integrity Protection http://approjects.co.za/?big=en-us/security/blog/2021/10/28/microsoft-finds-new-macos-vulnerability-shrootless-that-could-bypass-system-integrity-protection/ Thu, 28 Oct 2021 16:00:13 +0000 Microsoft found a vulnerability (CVE-2021-30892) that could allow an attacker to bypass System Integrity Protection (SIP) in macOS. We shared our findings with Apple via coordinated vulnerability disclosure, and a fix was released October 26.

The post Microsoft finds new macOS vulnerability, Shrootless, that could bypass System Integrity Protection appeared first on Microsoft Security Blog.

]]>
Microsoft has discovered a vulnerability that could allow an attacker to bypass System Integrity Protection (SIP) in macOS and perform arbitrary operations on a device. We also found a similar technique that could allow an attacker to elevate their privileges to root an affected device. We shared these findings with Apple through Coordinated Vulnerability Disclosure (CVD) via Microsoft Security Vulnerability Research (MSVR). A fix for this vulnerability, now identified as CVE-2021-30892, was included in the security updates released by Apple on October 26, 2021.

SIP is a security technology in macOS that restricts a root user from performing operations that may compromise system integrity. We discovered the vulnerability while assessing processes entitled to bypass SIP protections. We found that the vulnerability lies in how Apple-signed packages with post-install scripts are installed. A malicious actor could create a specially crafted file that would hijack the installation process. After bypassing SIP’s restrictions, the attacker could then install a malicious kernel driver (rootkit), overwrite system files, or install persistent, undetectable malware, among others.

This OS-level vulnerability and others that will inevitably be uncovered add to the growing number of possible attack vectors for attackers to exploit. As networks become increasingly heterogeneous, the number of threats that attempt to compromise non-Windows devices also increases. Microsoft Defender for Endpoint on Mac enables organizations to gain visibility and detect threats on macOS devices. Such visibility rolls up to Microsoft Defender for Endpoint, which provides organizations with a “single pane of glass” where they can detect, manage, respond, and remediate vulnerabilities and threats across different platforms.

In this blog post, we will share some information about SIP, examine the common types of SIP bypasses previously disclosed, and present the unique ones we discovered.

SIP overview

First introduced by Apple in macOS Yosemite, SIP—also known as “rootless”—essentially locks down the system from root by leveraging the Apple sandbox to protect the entire platform. Internally, it is controlled by the following NVRAM variables:

  • csr-active-config: bitmask of enabled protections
  • csr-data: stores netboot configuration

These variables cannot be legitimately modified in non-recovery mode. Therefore, the only legitimate way to disable SIP is by booting into recovery mode and turning SIP off. Turning SIP on or off is done using the built-in csrutil tool, which can also display the SIP status:

Screenshot of csrutil showing the SIP status

Figure 1: csrutil showing the SIP status. Note that SIP cannot be disabled from non-recovery OS.

The csr-active-config bitmask NVRAM variable describes the different protections SIP offers. While not an exhaustive list, below are a few honorable mentions; the rest can be freely examined in the XNU source code:

 

csr-active-config NVRAM bit Description
CSR_ALLOW_UNTRUSTED_KEXTS Controls the loading of untrusted kernel extensions
CSR_ALLOW_UNRESTRICTED_FS Controls write access to restricted filesystem locations
CSR_ALLOW_TASK_FOR_PID Controls whether to allow getting a task port for Apple processes (that is, invoke the task_for_pid API)
CSR_ALLOW_UNRESTRICTED_NVRAM Controls unrestricted NVRAM access
CSR_ALLOW_KERNEL_DEBUGGER Controls whether to allow kernel debugging

Compromising any of these protections could enable attackers to bypass SIP completely. Some scenarios include the following:

  • Loading untrusted kernel extensions could compromise the kernel and allow the said extensions to perform operations without any checks
  • Bypassing filesystem checks could allow a kernel extension to enforce SIP to itself completely
  • Freely modifying the NVRAM could control SIP itself

Filesystem restrictions

Over the years, Apple has hardened SIP against attacks by improving restrictions. One of the most notable SIP restrictions is the filesystem restriction. This is especially important for red teamers and malicious actors, as the amount of damage one can do to a device’s critical components is directly based on their ability to write unrestricted data to disk.

The file /System/Library/Sandbox/rootless.conf generally controls which files are SIP-protected. While the said file itself is also SIP-protected, one can run it using ls with the -O flag to list which files are similarly protected. SIP-protected files have the “restricted” marker.

Screenshot of /usr with the -O option

Figure 2: Listing /usr with the -O option. /usr/local is not SIP protected, but /usr/sbin is.

Files with the extended attribute com.apple.rootless are likewise SIP-protected. Of course, there’s no way to add that extended attribute to a file legitimately. Otherwise, malware could use SIP for its own protection. The filesystem restrictions are a great way of restricting attackers. For instance, many of the /System directory and its subdirectories are SIP-protected.

Screenshot of SIP blocking a malicious LaunchDaemon registration

Figure 3: SIP blocking a malicious LaunchDaemon registration that is frequently used for persistence.

Rootless entitlements

Since the filesystem restrictions are so powerful, Apple must consider a few exceptional cases. For example, system updates require unrestricted access to SIP-protected directories. Therefore, Apple introduced a particular set of entitlements that bypass SIP checks by design. These entitlements are fine-tuned to specific SIP checks, and only Apple can assign them. So naturally, Apple only assigns these entitlements to its processes.

In our research, we focused on two powerful entitlements, which have also been targets of vulnerability hunters:

 

Entitlement Description
com.apple.rootless.install Completely bypasses SIP filesystem checks
com.apple.rootless.install.heritable Inherits com.apple.rootless.install to child processes

Screenshot of "com.apple.rootless.install" entitled process

Figure 4: An example of a “com.apple.rootless.install” entitled process

A quick rundown of notable SIP bypasses

Before our discovery, there had been several interesting SIP bypass vulnerabilities already reported in the past. In this section, we categorize these vulnerabilities into several classes and provide an example for each. Note that this is not a complete list; for instance, we excluded vulnerabilities involving the kernel itself because SIP only protects userland.

Abusing dynamic libraries

Previously, entitled processes could still load arbitrary dynamic libraries. One such example was presented in 2016, where libBaseIA.dylib, which is local to the app, was used by an entitled binary and could be infected with malicious code. At that point, the SIP bypass could be completely implemented in the malicious dylib.

Mounting

In a security update for OSX 10.11.2, Apple fixed a security bug that was also abused by the MacDefender malware. The said vulnerability could allow a malicious .dmg file to be mounted (using hdiutil) over a SIP-protected folder, therefore completely bypassing SIP filesystem restrictions.

Abusing entitlements

Entitled processes have also been sources of security bypasses. One notable example is a bypass that used the entitled fsck_cs utility. The bypass exploited the fact that fsck_cs would follow symbolic links and attempt to fix the filesystem presented to it.

Therefore, an attacker could create a symbolic link pointing from /dev/diskX to /System/Library/Extensions/AppleKextExcludeList.kext/Contents/Info.plist and invoke fsck_cs on the former. As the Info.plist file gets corrupted, the operating system could no longer control kernel extension exclusions, therefore bypassing SIP.

The ‘Shrootless’ vulnerability

While assessing macOS processes entitled to bypass SIP protections, we came across the daemon system_installd, which has the powerful com.apple.rootless.install.heritable entitlement. With this entitlement, any child process of system_installd would be able to bypass SIP filesystem restrictions altogether.

Screenshot of system_installd entitlements

Figure 5: system_installd entitlements. Note the “com.apple.rootless.install.heritable”

Since Microsoft Defender for Endpoint has a post-breach component, we decided to examine all the child processes of system_installd. To our surprise, we saw a few cases that could allow attackers to abuse its functionality and bypass SIP.

For instance, when installing an Apple-signed package (.pkg file), the said package invokes system_installd, which then takes charge of installing the former. If the package contains any post-install scripts, system_installd runs them by invoking a default shell, which is zsh on macOS. Interestingly, when zsh starts, it looks for the file /etc/zshenv, and—if found—runs commands from that file automatically, even in non-interactive mode. Therefore, for attackers to perform arbitrary operations on the device, a fully reliable path they could take would be to create a malicious /etc/zshenv file and then wait for system_installd to invoke zsh.

To create a fully functional proof-of-concept (POC) exploit, we implemented the following algorithm:

  1. Download an Apple-signed package (using wget) that is known to have a post-install script
  2. Plant a malicious /etc/zshenv that would check for its parent process; if it’s system_installd, then it would write to restricted locations
  3. Invoke the installer utility to install the package

As seen in Figure 6 below, the POC exploit was able to override the kernel extension exclusion list:

Screenshot of proof of concept exploit for CVE-2021-30892

Figure 6: Our POC exploit overriding the kernel extension exclusion list with arbitrary data

zshenv as an attack technique

During our research, we also found out that zshenv could also be used as a general attack technique besides being used for a SIP bypass. We discovered that /etc/zshenv has an equivalent for each user profile under ~/.zshenv, which has the same function and behavior but doesn’t require root permissions to write to.

Generally, zshenv could be used as the following:

  • A persistence mechanism. It could simply wait for zsh to start (either globally under /etc or per user).
  • An elevation of privilege mechanism. The home directory doesn’t change when an admin user elevates to root using sudo -s or sudo <command>. Thus, placing a ~/.zshenv file as the admin and waiting for the admin to use sudo later would trigger the ~/.zshenv file, hence elevating to root.

We shared our findings to Apple through Coordinated Vulnerability Disclosure (CVD) via Microsoft Security Vulnerability Research (MSVR). We want to thank the Apple product security team for their professionalism and responsiveness in fixing the issue.

Hardening device security through vulnerability management and behavioral monitoring

Security technology like SIP in macOS devices serves both as the device’s built-in baseline protection and the last line of defense against malware and other cybersecurity threats. Unfortunately, malicious actors continue to find innovative ways of breaching these barriers for these very same reasons. They can take complete control of the device and run any files or processes they wish without getting detected by traditional security solutions.

Our research on the CVE-2021-30892 vulnerability exemplifies this. It highlights the need for organizations to have a security solution like Microsoft Defender for Endpoint that empowers them to quickly discover and remediate vulnerabilities through threat and vulnerability management. This allows defenders to detect vulnerabilities and misconfigurations on devices in real time and prioritize which need to be addressed immediately based on the threat landscape, business context, and other factors.

In addition, Microsoft Defender for Endpoint uses advanced behavioral analytics and machine learning to detect anomalous activities on a device, such as overwriting arbitrary SIP-protected files that our POC exploit is capable of. In the example provided in the previous section, it is anomalous for zsh to override the kernel extension exclusion list. As such, Defender for Endpoint detects it. Extending the concept, Defender for Endpoint has similar detections for sensitive file access, including system launch daemons, the rootless.conf file, and many more.

Finally, this research underscores the importance of collaboration among security researchers, software vendors, and the larger security community. As cross-platform threats continue to increase, vulnerability discoveries, coordinated response, and other forms of threat intelligence sharing help enrich our protection technologies that secure users’ computing experience regardless of the platform or device they’re using.

Learn how Microsoft Defender for Endpoint delivers a complete endpoint security solution across all platforms.

 

Jonathan Bar Or

Microsoft 365 Defender Research Team

The post Microsoft finds new macOS vulnerability, Shrootless, that could bypass System Integrity Protection appeared first on Microsoft Security Blog.

]]>
When coin miners evolve, Part 1: Exposing LemonDuck and LemonCat, modern mining malware infrastructure http://approjects.co.za/?big=en-us/security/blog/2021/07/22/when-coin-miners-evolve-part-1-exposing-lemonduck-and-lemoncat-modern-mining-malware-infrastructure/ Thu, 22 Jul 2021 16:00:57 +0000 LemonDuck, an actively updated and robust malware that’s primarily known for its botnet and cryptocurrency mining objectives, adopted more sophisticated behavior and escalated its operations. Today, beyond using resources for its traditional bot and mining activities, LemonDuck steals credentials, removes security controls, spreads via emails, moves laterally, and ultimately drops more tools for human-operated activity.

The post When coin miners evolve, Part 1: Exposing LemonDuck and LemonCat, modern mining malware infrastructure appeared first on Microsoft Security Blog.

]]>
[Note: In this two-part blog series, we expose a modern malware infrastructure and provide guidance for protecting against the wide range of threats it enables. Part 1 covers the evolution of the threat, how it spreads, and how it impacts organizations. Part 2 is a deep dive on the attacker behavior and will provide investigation guidance.]

Combating and preventing today’s threats to enterprises require comprehensive protection focused on addressing the full scope and impact of attacks. Anything that can gain access to machines—even so-called commodity malware—can bring in more dangerous threats. We’ve seen this in banking Trojans serving as entry point for ransomware and hands-on-keyboard attacks. LemonDuck, an actively updated and robust malware that’s primarily known for its botnet and cryptocurrency mining objectives, followed the same trajectory when it adopted more sophisticated behavior and escalated its operations. Today, beyond using resources for its traditional bot and mining activities, LemonDuck steals credentials, removes security controls, spreads via emails, moves laterally, and ultimately drops more tools for human-operated activity.

LemonDuck’s threat to enterprises is also in the fact that it’s a cross-platform threat. It’s one of a few documented bot malware families that targets Linux systems as well as Windows devices. It uses a wide range of spreading mechanisms—phishing emails, exploits, USB devices, brute force, among others—and it has shown that it can quickly take advantage of news, events, or the release of new exploits to run effective campaigns. For example, in 2020, it was observed using COVID-19-themed lures in email attacks. In 2021, it exploited newly patched Exchange Server vulnerabilities to gain access to outdated systems.

This threat, however, does not just limit itself to new or popular vulnerabilities. It continues to use older vulnerabilities, which benefit the attackers at times when focus shifts to patching a popular vulnerability rather than investigating compromise. Notably, LemonDuck removes other attackers from a compromised device by getting rid of competing malware and preventing any new infections by patching the same vulnerabilities it used to gain access.

In the early years, LemonDuck targeted China heavily, but its operations have since expanded to include many other countries, focusing on the manufacturing and IoT sectors. Today, LemonDuck impacts a very large geographic range, with the United States, Russia, China, Germany, the United Kingdom, India, Korea, Canada, France, and Vietnam seeing the most encounters.

World map showing geographic distribution of LemonDuck activity

Figure 1. Global distribution of LemonDuck botnet activity

In 2021, LemonDuck campaigns started using more diversified command and control (C2) infrastructure and tools. This update supported the marked increase in hands-on-keyboard actions post-breach, which varied depending on the perceived value of compromised devices to the attackers. Despite all these upgrades, however, LemonDuck still utilizes C2s, functions, script structures, and variable names for far longer than the average malware. This is likely due to its use of bulletproof hosting providers such as Epik Holdings, which are unlikely to take any part of the LemonDuck infrastructure offline even when reported for malicious actions, allowing LemonDuck to persist and continue to be a threat.

In-depth research into malware infrastructures of various sizes and operations provides invaluable insight into the breadth of threats that organizations face today. In the case of LemonDuck, the threat is cross-platform, persistent, and constantly evolving. Research like this emphasizes the importance of having comprehensive visibility into the wide range of threats, as well as the ability to correlate simple, disparate activity such as coin mining to more dangerous adversarial attacks.

LemonDuck and LemonCat infrastructure

The earliest documentation of LemonDuck was from its cryptocurrency campaigns in May 2019. These campaigns included PowerShell scripts that employed additional scripts kicked off by a scheduled task. The task was used to bring in the PCASTLE tool to achieve a couple of goals: abuse the EternalBlue SMB exploit, as well as use brute force or pass-the-hash to move laterally and begin the operation again. Many of these behaviors are still observed in LemondDuck campaigns today.

LemonDuck is named after the variable “Lemon_Duck” in one of the said PowerShell scripts. The variable is often used as the user agent, in conjunction with assigned numbers, for infected devices. The format used two sets of alphabetical characters separated by dashes, for example: “User-Agent: Lemon-Duck-[A-Z]-[A-Z]”. The term still appears in PowerShell scripts, as well as in many of the execution scripts, specifically in a function called SIEX, which is used to assign a unique user-agent during botnet connection in attacks as recently as June 2021.

LemonDuck frequently utilizes open-source material built off of resources also used by other botnets, so there are many components of this threat that would seem familiar. Microsoft researchers are aware of two distinct operating structures, which both use the LemonDuck malware but are potentially operated by two different entities for separate goals.

The first, which we call the “Duck” infrastructure, uses historical infrastructures discussed in this report. It is highly consistent in running campaigns and performs limited follow-on activities. This infrastructure is seldom seen in conjunction with edge device compromise as an infection method, and is more likely to have random display names for its C2 sites, and is always observed utilizing “Lemon_Duck” explicitly in script.

The second infrastructure, which we call “Cat” infrastructure—for primarily using two domains with the word “cat” in them (sqlnetcat[.]com, netcatkit[.]com)—emerged in January 2021. It was used in attacks exploiting vulnerabilities in Microsoft Exchange Server. Today, the Cat infrastructure is used in attacks that typically result in backdoor installation, credential and data theft, and malware delivery. It is often seen delivering the malware Ramnit.

 

Sample Duck domains Sample Cat domains
  • cdnimages[.]xyz
  • bb3u9[.]com
  • zz3r0[.]com
  • pp6r1[.]com
  • amynx[.]com
  • ackng[.]com
  • hwqloan[.]com
  • js88[.]ag
  • zer9g[.]com
  • b69kq[.]com
  • sqlnetcat[.]com
  • netcatkit[.]com
  • down[.]sqlnetcat[.]com

 

The Duck and Cat infrastructures use similar subdomains, and they use the same task names, such as “blackball”. Both infrastructures also utilize the same packaged components hosted on similar or identical sites for their mining, lateral movement, and competition-removal scripts, as well as many of the same function calls.

The fact that the Cat infrastructure is used for more dangerous campaigns does not deprioritize malware infections from the Duck infrastructure. Instead, this intelligence adds important context for understanding this threat: the same set of tools, access, and methods can be re-used at dynamic intervals, to greater impact. Despite common implications that cryptocurrency miners are less threatening than other malware, its core functionality mirrors non-monetized software, making any botnet infection worthy of prioritization.

Diagram showing attacker activity following infection of LemonDuck malware, highlight activities common to the LemonDuck and LemonCat infrastructure, and showing unique behavior for each

Figure 2. LemonDuck attack chain from the Duck and Cat infrastructures

Initial access

LemonDuck spreads in a variety of ways, but the two main methods are (1) compromises that are either edge-initiated or facilitated by bot implants moving laterally within an organization, or (2) bot-initiated email campaigns.

LemonDuck acts as a loader for many other follow-on activities, but one if its main functions is to spread by compromising other systems. Since its first appearance, the LemonDuck operators have leveraged scans against both Windows and Linux devices for open or weakly authenticated SMB, Exchange, SQL, Hadoop, REDIS, RDP, or other edge devices that might be vulnerable to password spray or application vulnerabilities like CVE-2017-0144 (EternalBlue), CVE-2017-8464 (LNK RCE), CVE-2019-0708 (BlueKeep), CVE-2020-0796 (SMBGhost), CVE-2021-26855 (ProxyLogon), CVE-2021-26857 (ProxyLogon), CVE-2021-26858 (ProxyLogon), and CVE-2021-27065 (ProxyLogon).

Once inside a system with an Outlook mailbox, as part of its normal exploitation behavior, LemonDuck attempts to run a script that utilizes the credentials present on the device. The script instructs the mailbox to send copies of a phishing message with preset messages and attachments to all contacts.

Because of this method of contact messaging, security controls that rely on determining if an email is sent from a suspicious sender don’t apply. This means that email security policies that reduce scanning or coverage for internal mail need to be re-evaluated, as sending emails through contact scraping is very effective at bypassing email controls.

From mid-2020 to March 2021, LemonDuck’s email subjects and body content have remained static, as have the attachment names and formats. These attachment names and formats have changed very little from similar campaigns that occurred in early 2020.

 

Sample email subjects Sample email body content
  • The Truth of COVID-19
  • COVID-19 nCov Special info WHO
  • HALTH ADVISORY:CORONA VIRUS
  • WTF
  • What the fcuk
  • good bye
  • farewell letter
  • broken file
  • This is your order?
  • Virus actually comes from United States of America
  • very important infomation for Covid-19
  • see attached document for your action and discretion.
  • the outbreak of CORONA VIRUS is cause of concern especially where forign personal have recently arrived or will be arriving at various intt in near future.
  • what’s wrong with you?are you out of your mind!!!!!
  • are you out of your mind!!!!!what ‘s wrong with you?
  • good bye, keep in touch
  • can you help me to fix the file,i can’t read it
  • file is brokened, i can’t open it

The attachment used for these lures is one of three types: .doc, .js, or a .zip containing a .js file. Whatever the type, the file is named “readme”. Occasionally, all three types are present in the same email.

Screenshot of email related to LemonDuck attack

Figure 3. Sample email

While the JavaScript is detected by many security vendors, it might be classified with generic detection names. It could be valuable for organizations to sanitize JavaScript or VBScript executing or calling prompts (such as PowerShell) directly from mail downloads through solutions such as custom detection rules.

Since LemonDuck began operating, the .zip to .js file execution method is the most common. The JavaScript has replaced the scheduled task that LemonDuck previously used to kickstart the PowerShell script. This PowerShell script has looked very similar throughout 2020 and 2021, with minor changes depending on the version, indicating continued development. Below is a comparison of changes from the most recent iterations of the email-delivered downloads and those from April of 2020.

After the emails are sent, the inbox is cleaned to remove traces of these mails. This method of self-spreading is attempted on any affected device that has a mailbox, regardless of whether it is an Exchange server.

Other common methods of infection include movement within the compromised environment, as well as through USB and connected drives. These processes are often kicked off automatically and have occurred consistently throughout the entirety of LemonDuck’s operation.

These methods run as a series of C# scripts that gather available drives for infection. They also create a running list of drives that are already infected based on whether it finds the threat already installed. Once checked against the running list of infected drives, these scripts attempt to create a set of hidden files in the home directory, including a copy of readme.js. Any device that has been affected by the LemonDuck implants at any time could have had any number of drives attached to it that are compromised in this manner. This makes this behavior a possible entry vector for additional attacks.

Comprehensive protection against a wide-ranging malware operation

The cross-domain visibility and coordinated defense delivered by Microsoft 365 Defender is designed for the wide range and increasing sophistication of threats that LemonDuck exemplifies. Microsoft 365 Defender has AI-powered industry-leading protections that can stop multi-component threats like LemonDuck across domains and across platforms. Microsoft 365 Defender for Office 365 detects the malicious emails sent by the LemonDuck botnet to deliver malware payloads as well as spread the bot loader. Microsoft Defender for Endpoint detects and blocks LemonDuck implants, payloads, and malicious activity on Linux and Windows.

More importantly, Microsoft 365 Defender provides rich investigation tools that can expose detections of LemonDuck activity, including attempts to compromise and gain a foothold on the network, so security operations teams can efficiently and confidently respond to and resolve these attacks. Microsoft 365 Defender correlates cross-platform, cross-domain signals to paint the end-to-end attack chain, allowing organizations to see the full impact of an attack. We also published a threat analytics article on this threat. Microsoft 365 Defender customers can use this report to get important technical details, guidance for investigation, consolidated incidents, and steps to mitigate this threat in particular and modern cyberattacks in general.

In Part 2 of this blog series, we share our in-depth technical analysis of the malicious actions that follow a LemonDuck infection. These include general, automatic behavior as well as human-initialized behavior. We will also provide guidance for investigating LemonDuck attacks, as well as mitigation recommendations for strengthening defenses against these attacks. READ: When coin miners evolve, Part 2: Hunting down LemonDuck and LemonCat attacks.

 

Microsoft 365 Defender Threat Intelligence Team

The post When coin miners evolve, Part 1: Exposing LemonDuck and LemonCat, modern mining malware infrastructure appeared first on Microsoft Security Blog.

]]>