Archive

Archive for the ‘macOS’ Category

Unraveling the techniques of Mac ransomware

Ransomware continues to be one of the most prevalent and impactful threats affecting organizations, with attackers constantly evolving their techniques and expanding their tradecraft to cast a wider net of potential targets. This is evident in the range of industries, systems, and platforms affected by ransomware attacks. Understanding how ransomware works across these systems and platforms is critical in protecting today’s hybrid device and work environments.

This blog provides details from our analysis of known ransomware families affecting macOS devices. As in other platforms, the initial vector of Mac ransomware typically relies on user-assisted methods like downloading and running fake or trojanized applications. It can, however, also arrive as a second-stage payload dropped or downloaded by other malware or part of a supply chain attack. Once running on a device, ransomware attacks usually comprise gaining access, execution, encrypting target users’ files, and notifying the target with a ransom message.

To perform these actions, malware creators abuse legitimate functionalities and devise various techniques to exploit vulnerabilities, evade defenses, or coerce users to infect their devices. We describe these techniques in detail below, based on our analysis of four Mac ransomware families: KeRanger, FileCoder, MacRansom, and EvilQuest. In particular, we take a deeper look at EvilQuest and one of its variants that had its ransomware component removed but was further improved with additional techniques and anti-analysis logic.

While these malware families are old, they exemplify the range of capabilities and malicious behavior possible on the platform. Building durable detections for these techniques will help improve defenses for devices and networks against ransomware and other threats. As with any security research in Microsoft, this in-depth analysis of malware techniques informs the protection we provide through solutions like Microsoft Defender for Endpoint on Mac. We’re sharing this information with the rest of the community as a technical reference that researchers can use and build upon to understand Mac threats and improve protections.

File enumeration     

Targeting which files to encrypt is the most important step for any ransomware. We have seen various ways through which ransomware families have enumerated files and directories on Mac:

Using the Find binary

FileCoder and MacRansom use the find utility to search for files to encrypt. find is a common utility binary that is generally found across many Unix based systems like macOS, Linux, etc. and incorporates many features that could help attackers to search for and select files. The output of the command is then passed as an argument to the function or binary that carries out the encryption of the files.

Figure 1 shows part of the command used by FileCoder. It searches the “/Users” and “/Volumes” directories by invoking the said command twice, with a change on the path being enumerated and excluding its README file while searching the “/Users” path.

Screenshot of FileCoder’s enumeration logic.
Figure 1. FileCoder’s enumeration logic

In the case of MacRansom, it searches for files in “/Volumes” and the current user’s directory. It uses -type f to include regular files, -size +8c to select files that are greater than 8 bytes, -user `whoami` to select files that belong to the current user, and -perm -u=r to get files for which the current user has readable permission. The output of the command in Figure 2 is then passed to another instance of the malware.

Screenshot of MacRansom’s enumeration logic
Figure 2. MacRansom’s enumeration logic

Using library functions opendir, readdir, and closedir

KeRanger and EvilQuest use library functions to get the directory listing. It uses a sequence of opendir(), readdir(), and closedir() to get the list of files.

Screenshot of EvilQuest's code showing library functions used to enumerate files.
Figure 3. Library functions used in EvilQuest

First, it uses opendir() to open a directory by specifying the dirname. The handle returned from the opendir() function is used by the readdir() function to scan files. readdir() returns NULL if it reaches the end of the directory. It uses closedir() at the end to close the handle to the directory.

Using the NSFileManager class through Objective-C

There are open-source proofs-of-concept (POCs) and scripts where Objective-C functions are used to enumerate files. For example, the Gopher POC uses this technique to scan for .docx files in the User’s Documents directory.

In this technique, NSDirectoryEnumerator object is used to enumerate the directory’s contents, while the path is specified in the enumeratorAtPath: method. The function returns the enumerator, which is used to get all the paths of files and directories.

Screenshot of Gopher POC's code using the NSFileManager to enumerate files.
Figure 4. Gopher’s use of NSFileManager

This method is unique to the Gopher POC and is not found in the four ransomware families we analyzed.

Anti-analysis techniques

Malware creators deploy various anti-analysis techniques to evade or prevent the analysis of files by either analysts or automated analysis systems such as sandboxes. Among the Mac ransomware we studied, KeRanger, MacRansom, and EvilQuest employ hardware-based checks or use specific code apart from the usual obfuscation of strings to avoid analysis.

Hardware-based checks

Checking a device’s hardware model

This technique (T1497.001), used by MacRansom, involves getting the hardware model of the system and checking a substring to detect if the malware is running in a virtual environment. Running inside a virtual machine (VM) often indicates that the malware is being analyzed by analysts or in a sandbox.

Screenshots of results of checking the hardware model of a MacBook Pro and a device that is running macOS on a virtual machine.
Figure 5. The command used by MacRansom (above) determines the environment it is running on. Below the command is the comparison of the results between checking the hardware model of a MacBook Pro (left) and a Mac OS running on Parallels VM (right)

The result of the command on a host device contains the substring “Mac”, whereas the result on a Parallels VM setup doesn’t. The malware stops if it detects its presence in a virtual environment.

Checking the logical and physical processors of a device

MacRansom uses this technique (T1497.001) to check the count of the logical and physical CPU of the device.

Screenshots of results of the number of logical and physical CPUs in a MacBook Pro and in a macOS hosted on a Parallels virtual machine.
Figure 6. The command used by MacRansom’s  (above) counts logical and physical CPUs present in the device. Below that is the logical and physical processors check comparison between a MacBook Pro (left) and a Mac OS running on Parallels VM (right)

In this case, a host device’s logical CPU count is usually twice the physical CPU count, whereas the values are the same for a VM instance. The command above divides the values of these two counts and compares them with 2. It makes the comparison to determine if the malware is running in a virtual instance or not.

Checking the MAC OUI of the device

This technique (T1497.001), used by EvilQuest variants, involves checking the MAC organizational unique identifier (OUI) prefix, which comprises the first 24 bits of a MAC address, to determine the device vendor. Checking the OUI is another technique to determine if the malware is running in a virtual environment.

Screenshot of EvilQuest code checking the MAC OUI prefix of a device.
Figure 7. EvilQuest code that checks the MAC OUI prefix

Figure 7 shows the EvilQuest code that gets the MAC address of the en0 network interface, and compares the first three bytes with the OUI values hardcoded in EvilQuest. The values (v8, v7, and v6 in Figure 7) are attributed to many known virtualization platforms such as Parallels, VirtualBox, and VMware.

Checking the device’s CPU count and memory size

Analysis environments, specifically automated ones, are often deployed with minimal CPU and memory. EvilQuest checks the device’s CPU and memory size (T1497.001) to ensure it’s not running in a virtual environment.

The malware uses three different methods to check the number of CPUs. The first method uses the sysctl function by passing the MIB (Management Information Base) structure containing CTL_HW and HW_AVAILCPU identifiers. If this first method fails, the malware uses the second method where it replaces HW_AVAILCPU with HW_NCPU. If the second method also fails, it uses the command “sysctl -n hw.ncpu” as a third method to get the CPU count. EvilQuest further checks if the value of the CPU count is less than 2, which might indicate a virtual instance deployed with minimal hardware.

Screenshot of EvilQuest's code checking for CPU count on a device.
Figure 8. EvilQuest code that checks for CPU count

EvilQuest also checks the device’s physical memory size to avoid analysis environments. It uses sysctl function with the MIB structure CTL_HW and HW_MEMSIZE constants to check the physical RAM size. The result is then compared further with the size of 1GB, which might indicate a virtual instance.

Screenshot of EvilQuest's code checking a device's physical memory size.
Figure 9. EvilQuest code to check the device’s physical memory size

Code-related checks

Delayed execution

Malware creators often use the delayed execution (T1497.003) technique to prevent automated analysis systems from detecting the malware’s actual behavior. KeRanger uses this delayed execution technique where, upon launching, it sleeps for three days before performing its malicious routines.

Screenshot of KeRanger's code used in delaying its execution.
Figure 10. KeRanger code used to delay its execution

PT_DENY_ATTACH (PTRACE)

This technique (T1622), used by both EvilQuest and MacRansom, is a known anti-debugging trick that prevents debuggers from attaching to the current malware process. It is used to avoid the debugging of malware files.

Screenshot of MacRansom's code that invokes the PT_DENY_ATTACH argument.
Figure 11.  Code in MacRansom where it invokes ptrace with PT_DENY_ATTACH argument

As seen in MacRansom’s code (Figure 11), it first opens the handle to itself, where the ptrace symbol is searched, and the address is retrieved. It is then called with the argument 0x1F, a constant for PT_DENY_ATTACH.

EvilQuest implements the same technique in two ways. One method is a simple call to the ptrace function with the argument 0x1F as above. In another variant, the logic is implemented using syscall. This method invokes ptrace through syscall with the PT_DENY_ATTACH flag.

Screenshot of EvilQuest's code where it uses syscall.
Figure 12. Code in an EvilQuest variant where it uses Syscall(ptrace) to avoid debuggers  

Additionally, the EvilQuest variant also verifies if the PT_DENY_ATTACH operation is successful. To do so, it first registers a handler for the signal SIGSEGV and calls the ptrace method again with the argument PT_ATTACH. This ptrace() call with PT_ATTACH flag throws a SIGSEGV signal if it fails to attach to the process, which further invokes the handler. The handler sets a variable that is checked next to determine the success of PT_DENY_ATTACH operation.

P_TRACED flag

EvilQuest uses this technique (T1622) to check whether it is being debugged. The technique is used to get the process structure and check for the P_TRACED flag. If the flag is found to be set, it indicates that the process is being debugged. The malware then alters its behavior to avoid analysis.

Screenshot of EvilQuest's code checking for the P_TRACED flag.
Figure 13. Code in an EvilQuest variant where it checks for the P_TRACED flag

Time-based check

Malware using this technique (T1497.003) checks if it is running in a sandbox by checking if the device’s sleep function is patched. Sandboxes attempt to patch the sleep function to avoid execution delay, which is used by some malware. Ransomware like EvilQuest sleeps for a specified time between two time() calls. Next, the difference in the timestamp is calculated and checked with the duration specified in sleep() call.

Screenshot of EvilQuest's code where it checks the sleep patching function.
Figure 14. EvilQuest code that checks patching of sleep function

Persistence

Malware commonly uses persistence to ensure it runs even after a system restart. Among the Mac ransomware families analyzed, we’ve seen persistence techniques in EvilQuest and MacRansom. The following are persistence techniques implemented by these malware families.

Creating launch agents or launch daemons

Creating Launch Agents (T1543.001) or Launch Daemons (T1543.004) is a persistence method that uses launch items. This technique utilizes a property list (PLIST) file, which is used in macOS to specify configurations and properties in respective directories to gain persistence. EvilQuest can create both Launch Agent and Launch Daemon files, while MacRansom typically creates a Launch Agent file. 

Screenshot of EvilQuest's launch daemon PLIST file.
Figure 15. EvilQuest’s launch daemon PLIST file

The ProgramArguments key in the PLIST file (Figure 15) specifies the process to run with arguments if any, and RunAtLoad and KeepAlive keys are used to ensure that the process is continuously running.

Using kernel queues

The kernel queue (kqueue) provides a way for an application to get notifications based on various conditions and events. In the case of EvilQuest, it uses this method to restore itself based on notification it receives in case any modifications are made to the list of files it wants to monitor. Different EvilQuest variants use different versions of this implementation.

Screenshot of EvilQuest's file monitoring initialization and file restoring codes.
Figure 16. EvilQuest variant’s codes used to initialize file monitoring (left) and to restore files after modification (right)  

It first creates the kernel event (kevent) queue using the kqueue() system call. Next, it forms a structure for each file containing its file handle and the required filters and flags to register the files to monitor. The pointer to this array of structures is passed in the changelist argument to the kevent() call. The eventlist parameter then stores any changes observed. The malware invokes the kevent() call in a loop. If any modifications are made to the files being monitored, EvilQuest tries to restore them.

Encryption

The ransomware families we analyzed often share similar anti-analysis and persistence techniques. However, these same ransomware families differ in encryption logic. Some use AES-RSA encryptions, while others use system utilities, XOR routine, or custom encryption logic to encrypt files. These encryption methods range from in-place modification to creating a new file while deleting the original one. Common among the ransomware observed is adding a new extension or simply encrypting the file without adding any new one.

FileCoder

FileCoder ransomware uses the ZIP utility to encrypt files. Files enumerated using the find utility are passed to the ZIP utility with the flag -0 (no compression) and -P (password), along with a randomly generated key for encryption.

Screenshot of FileCoder’s encryption logic
Figure 17. FileCoder’s encryption logic

FileCoder appends the .crypt extension to encrypted files (Figure 17). It removes the original file and changes the timestamp of the newly created file, which also works as an evasion tactic. FileCoder only encrypts files present in the /Users and /Volumes directories. It invokes the command twice with the path change being enumerated. While enumerating files in the /Users directory, it skips its dropped ransom note.

KeRanger

KeRanger, on the other hand, uses AES encryption in Cipher block chaining (CBC) mode to encrypt files. It leverages the mbedtls library for performing cryptographic functions.

Illustration of how KeRanger generates its key.
Figure 18. KeRanger’s key generation process

The process begins by generating a key used for AES and hash-based message authentication code (HMAC). It generates a random number that is fed to the digest and an initialization vector, a value calculated by KeRanger and utilized in its key generation process. The result is then used as a key in the next iteration, along with the same random number. This process is done eight times, after which the result is used to set the key.

Screenshot of KeRanger's code showing its encryption logic.
Figure 19. KeRanger’s encryption logic

It then encrypts the random number generated earlier with the RSA key received from the server. To encrypt the files, it uses the generated AES key. It also calculates the HMAC of the original file content, which is written to the output file, along with keying information (data that can be used to decrypt the encrypted files such as key length, the encrypted random number, the initial vector, etc.) and encrypted content.

MacRansom

MacRansom uses a symmetric algorithm for encrypting files and decrypting its ransom note “._README_”. The ransom note contains encrypted data which MacRansom decrypts using a hardcoded key. It uses separate keys for encrypting the files and decrypting its ransom note.

First, it enumerates the target files using the find utility and passes it to another instance of the malware as mentioned in Figure 2. This new malware instance calculates the encryption key first by permuting a hardcoded key with a random number.

Screenshot of MacRansom's code used to generate keys.
Figure 20. MacRansom’s key generation logic

MacRansom reads the file’s content and encrypts it with the permuted key generated earlier. In the process of encryption, if MacRansom encounters its ransom note by checking the filename which is “._README_”, it uses a separate hardcoded key to decrypt its content.

Screenshot of MacRansom's encryption logic.
Figure 21. MacRansom’s encryption logic

EvilQuest

EvilQuest uses a custom symmetric key encryption routine to encrypt target files. For each target file, the malware creates a temporary file name using the format “.<FILENAME>.e” and then checks if the file has already been encrypted by checking the presence of the marker 0xDDBEBABE. If not, it reads the target file, encrypts the content, and writes the content to the temporary file. After encrypting the content, the malware encodes the file encryption key and appends the keying information to the file along with the marker. It then proceeds to delete the target file and rename the temporary file to the original target file’s name.

Screenshot of EvilQuest's code showing its encryption process
Figure 22. EvilQuest’s encryption process

EvilQuest’s other capabilities

Further analysis of some variants of EvilQuest shows interesting capabilities on top of encrypting files. In this section, we discuss other behavior that we have observed in the two EvilQuest variants analyzed apart from their encryption routine. We noted behaviors such as file infection, keylogging, info stealing, disabling security solutions, and in-memory execution.

Over the past years, we have observed many variants of EvilQuest that removed its ransomware component. Tracking behavior changes in malware is important to understand how these affect devices and data and how to prevent these attacks effectively. These additions and changes in behavior might also provide clues about EvilQuest’s future attacks.

File infection

EvilQuest can infect Mach-O files by inserting its code (T1554). To identify files to infect, it scans through the /Users directory. It calls a routine for each file found. This routine checks the magic bytes of the file to determine whether the file is a Mach-O binary. It also skips the file if the path contains .app or if the file size exceeds 25 MB.

Screenshot of EvilQuest's code used to check for magic bytes.
Figure 23. EvilQuest’s code checking for the magic bytes

After scanning and finding target files, EvilQuest prepends its code to the target file and appends a trailer, which contains data such as marker and offset to the original binary code. EvilQuest uses the marker 0xDEADFACE in the trailer data to check whether a file is infected.

Illustration of a file infected by EvilQuest's code. The illustration shows the last three parts of the file as the trailer, and the code offset is written in the original binary's code.
Figure 24. Structure of a file infected by EvilQuest

If any of the infected file is executed, EvilQuest has checks to identify, if it’s running from an infected file and to execute the original binary using the following logic:

  1. Extract the trailer to check if the current process is infected.
  2. Go to the offset present in the trailer.
  3. Read the original binary content from the offset of the calculated size to a buffer.
  4. Format and form another path: <PATH>/.<FILE_NAME>1.
  5. The original binary content is written in the above file.
  6. Provide executable permissions to this newly created file and execute the file.

Keylogging

We observed two mechanisms of keylogging (T1056.001) in two EvilQuest variants we analyzed. The first mechanism uses the API CGEventTapCreate, while the second uses the IOHIDManagerCreate API.

Using the CGEventTapCreate API

This API creates an event tap to monitor human interface devices (HID) like keyboards. Keylogging starts upon receiving commands from a command and control (C2) server.

Screenshot of EvilQuest's code used for logging keystrokes.
Figure 25. EvilQuest code for logging keystrokes using the CGEventTapCreate API

The malware creates an event tap using CGEventTapCreate and uses CGEventTapEnable to activate it. The callback function seen in this EvilQuest variant converts the constant and prints it on the standard output.

Using the IOHIDManagerCreate API

This API is used to communicate with and monitor HID devices. To achieve this, EvilQuest uses the following functions:

  • It uses IOHIDManagerCreate to create the HID manager handle.
  • CreateMatchingDirectory method is used with argument value 6 (kHIDUsage_GD_Keyboard) for setting the device type filtering.
  • It uses IOHIDManagerRegisterInputValueCallback to set the callback function.
  • IOHIDManagerOpen further opens the HIDManager.
  • IOHIDManagerScheduleWithRunLoop for scheduling the manager with run loop.
Screenshot of an EvilQuest variant's code that uses the IOHIDManager API to monitor devices.
Figure 26. An EvilQuest variant using the IOHIDManager API

Figure 27 shows the callback code that is specified in the IOHIDManagerRegisterInputValueCallback function. It uses IOHIDValueGetElement and IOHIDElementGetUsage to get the usage for the element. It then gets the ASCII mapping, which is written to the .DS_State file.

Screenshot of an EvilQuest variant's code using the callback function.
Figure 27. EvilQuest’s callback function

Disabling security programs

EvilQuest tries to stop security processes to evade detection. Microsoft Defender for Endpoint on Mac’s tamper protection feature safeguards the application from this disabling behavior.

First, it gets the process list by forming the MIB structure, which contains CTL_KERN, KERN_PROC, KERN_PROC_ALL identifiers. The first systcl call gets the output’s size, which is then passed to the second sysctl call. This returns the structure for each process.

Screenshot of an EvilQuest variant's code getting the structure of running processes on the device.
Figure 28. EvilQuest getting the structure of running processes on the device

Next, it parses these structures and gets the process ID, passed along with CTL_KERN,KERN_PROCARGS2 identifiers to get the process arguments. The results are then searched against known patterns for security programs that are hardcoded in EvilQuest. Finding a matching pattern in the hardcoded list leads to EvilQuest stopping the process and removing executable permissions from the process file.

Screenshot of an EvilQuest variant's code where it stops security processes.
Figure29. Code that stops the security process EvilQuest finds

In-memory execution

This technique (T1620) is a way to execute any file from memory without dropping hence, leaving no trace of the malware on disk. EvilQuest uses the following APIs to implement in-memory execution:

  • NSCreateObjectFileImageFromMemory – used for creating an object file image from the data present in memory
  • NSLinkModule – used to link the object file image
  • NSLookupSymbolInModule – used for looking for a specific symbol
  • NSAddressOfSymbol – used to get the address of the symbol.

The address of the function returned from the previous call is then executed.

Screenshot of an EvilQuest variant's API use for in-memory execution.
Figure 30. EvilQuest’s API use for its in-memory execution

Defending against macOS ransomware

Ransomware continues to be one of the most significant threats affecting any platform. Our analysis of ransomware on Mac operating systems shows how its creators use various techniques to remain hidden from automated analysis systems or make manual inspection by analysts challenging. Understanding ransomware routines and their effects on any device or platform is essential for individual users to take steps toward device and data protection. Organizations can benefit from knowing these malicious behaviors and protect their networks in the age of securing multiple systems and devices operating in their networks.

Defenders can take the following mitigation steps to defend against these ransomware attacks:

  • Install apps from trusted sources only, such as a software platform’s official app store.
  • Restrict access to privileged resources like LaunchDaemons or LaunchAgents folders and sudoers files through OSX enterprise management solutions. This helps mitigate common persistence and privilege escalation techniques.
  • Use web browsers like Microsoft Edge—available on macOS and various platforms—that support Microsoft Defender SmartScreen. SmartScreen identifies and blocks malicious websites, including phishing sites, scam sites, and sites that contain exploits and host malware.
  • Run the latest version of your operating systems and applications. Deploy the latest security updates as soon as they become available. These ensure your device is benefiting from the latest cloud-delivered protections.
  • Use Microsoft Defender for Endpoint on Mac, which detects, stops, and quarantines the malware discussed in this blog using the following detection names:
    • Ransom:MacOS/EvilQuest
    • Ransom:MacOS/Filecoder.YC!MTB
    • Ransom:MacOS_X/Ratatonilly.A
    • Ransom:MacOS/Crypat.A!MTB
    • Ransom:MacOS_X/KeRanger.A

Microsoft Defender for Endpoint tracks the techniques mentioned in the MITRE ATT&CK® tactics and techniques table below and creates alerts where applicable. Defender for Endpoint provides cross-platform defense and a unified investigation experience that gives organizations visibility across all endpoints in the network.

Screenshot of Mac ransomware-related alerts on Microsoft Defender for Endpoint.
Figure 31. Mac ransomware-related alerts on Microsoft Defender for Endpoint

MITRE ATT&CK® tactics and techniques observed

Execution

  • T1204.002 User Execution: Malicious File
  • T1059.002 Command and Scripting Interpreter: AppleScript
  • T1569.001 System Services: Launchctl

Persistence

  • T1543.001 Create or Modify System Process: Launch Agent
  • T1543.004 Create or Modify System Process: Launch Daemon
  • T1554 Compromise Client Software Binary

Privilege Escalation

  • T1548.003 Abuse Elevation Control Mechanism: Sudo and Sudo caching
  • T1543.004 Create or Modify System Process: Launch Daemon

Defense Evasion

  • T1140 Deobfuscate/Decode Files or Information
  • T1222.002 File and Directory Permissions Modification: Linux and MAC File and Directory Permissions

Modification

  • T1562.001 Impair Defences: Disable or Modify tools
  • T1070.004 Indicator Removal on Host: File Deletion
  • T1070.006 Indicator Removal on Host: Timestomp
  • T1036.005 Masquerading: Match Legitimate Name or Location

Discovery

  • T1083 File and Directory Discovery
  • T1057 Process Discovery
  • T1518.001 Software Discovery: Security Software Discovery
  • T1082 System Information Discovery
  • T1033 System Owner/User Discovery

Collection

  • T1005 Data from Local System

Command & Control

  • T1071.001 Application Layer Protocol: Web protocols
  • T1132.002 Data Encoding: Non-Standard Encoding
  • T1105 Ingress Tool Transfer

Exfiltration

  • T1041 Exfiltration over C2 channel

Impact

  • T1486 Data Encrypted for Impact

Indicators of compromise

  • b34738e181a6119f23e930476ae949fc0c7c4ded6efa003019fa946c4e5b287a (EvilQuest)
  • bcdb0ca7c51e9de4cf6c5c346fd28a4ed28e692319177c8a94c86dc676ee8e48 (EvilQuest variant)
  • 617f7301fd67e8b5d8ad42d4e94e02cb313fe5ad51770ef93323c6115e52fe98 (MacRansom)
  • d19b903adbd0f8c119d0d8f25b194bdd24b737357a517f23ca5cdc6c75b35038 (FileCoder)
  • 31b6adb633cff2a0f34cefd2a218097f3a9a8176c9363cc70fe41fe02af810b9 (KeRanger)

The post Unraveling the techniques of Mac ransomware appeared first on Microsoft Security Blog.

Gatekeeper’s Achilles heel: Unearthing a macOS vulnerability

On July 27, 2022, Microsoft discovered a vulnerability in macOS that can allow attackers to bypass application execution restrictions imposed by Apple’s Gatekeeper security mechanism, designed to ensure only trusted apps run on Mac devices. We developed a proof-of-concept exploit to demonstrate the vulnerability, which we call “Achilles”. Gatekeeper bypasses such as this could be leveraged as a vector for initial access by malware and other threats and could help increase the success rate of malicious campaigns and attacks on macOS.

After carefully reviewing the implications, we shared the vulnerability with Apple in July 2022 through Coordinated Vulnerability Disclosure (CVD) via Microsoft Security Vulnerability Research (MSVR). Fixes for the vulnerability, now identified as CVE-2022-42821, were quickly released by Apple to all their OS versions. We note that Apple’s Lockdown Mode, introduced in macOS Ventura as an optional protection feature for high-risk users that might be personally targeted by a sophisticated cyberattack, is aimed to stop zero-click remote code execution exploits, and therefore does not defend against Achilles. End-users should apply the fix regardless of their Lockdown Mode status. We thank Apple for the collaboration in addressing this issue.

In this blog post, we share information about Gatekeeper and the vulnerability able to bypass it. We also share this research to emphasize the importance of collaboration among researchers and the security community to improve defenses for the larger ecosystem.

Unlocking the Gatekeeper security mechanism

Many macOS infections are the result of users running malware, oftentimes inadvertently. Fake app bundles might masquerade themselves as different apps, like Flash Player, or as a legitimate file, such as using a PDF icon and using the app name “Resume”. To combat this highly popular infection vector, Apple has imposed strong security mechanisms. When downloading apps from a browser, like Safari, the browser assigns a special extended attribute to the downloaded file. That attribute is named com.apple.quarantine and is later used to enforce policies such as Gatekeeper or certain mitigations that prevent sandbox escapes. In recent years, Apple has tightened the security policies even further, and the current Gatekeeper design dictates the following behavior for downloaded apps:

  1. If the app is validly signed and notarized, meaning approved by Apple, then a prompt requires the user’s consent before its launched.
  2. Otherwise, the user is informed that the app cannot be run as it’s untrusted.

Extended attributes are a filesystem feature supported on common macOS filesystems, like APFS and HFS+, and their main purpose is to save file metadata. Specifically, the com.apple.quarantine attribute saves information regarding the source of the downloaded file, as well as data instructing Gatekeeper how to process the file. The attribute format is generally:

flag;date;agent_name;UUID

Extended attributes can be viewed or modified with the xattr command line utility.

A flag value of “0083” enforces Gatekeeper restrictions on the file, as displayed below:

Graphical user interface; text
Figure 1. A common com.apple.quarantine extended attribute value
Graphical user interface; text
Figure 2. Gatekeeper blocking an untrusted downloaded file

Due to its essential role in stopping malware on macOS, Gatekeeper is a helpful and effective security feature. However, considering there have been numerous bypass techniques targeting the security feature in the past, Gatekeeper is not bulletproof. Gaining the ability to bypass Gatekeeper has dire implications as sometimes malware authors leverage those techniques for initial access.

Historical overview of Gatekeeper bypasses

Numerous Gatekeeper bypasses have been identified in the past years, some even abused by malware families such as Shlayer. When examining Gatekeeper bypasses from recent years, we see two approaches:

  1. Misuse the com.apple.quarantine extended attribute assignment.
  2. Find a vulnerability in the components that enforce policy checks on quarantined files.

Two cases that we don’t consider to constitute a “true” Gateway bypass are:

  1. Using unsupported filesystems, like a USB mass storage device using FAT32, as these require non-trivial user interaction to run macOS applications.
  2. MITRE’s definition of “Gatekeeper Bypass” (T1553.001), which requires code execution to forcefully modify or remove the com.apple.quarantine extended attribute.

Here are some examples of Gatekeeper bypass vulnerabilities discovered over the last several years:

Vulnerability Exploits Description
CVE-2022-22616 Assignment of the quarantine attribute. Gzip files archived in BOM archives are not assigned with the quarantine extended attribute, further detailed here.
CVE-2021-1810 Assignment of the quarantine attribute. Paths longer than 886 characters were not assigned with extended attributes. Therefore, creating a symbolic link that points to an app that resides in a long path results in a Gatekeeper bypass. Since symbolic links are not assigned with the quarantine attribute, it was possible to completely bypass Gatekeeper, as outlined here.
CVE-2021-30657 Component(s) that enforce policy checks. App bundles with a missing Info.plist and a shell script main executable component are treated incorrectly by syspolicyd, a component that enforces policy restrictions on apps. Writeups can be found here and here.
CVE-2021-30853 Component(s) that enforce policy checks. A security bug in the way files with a “Shebang” (#!) header are interpreted by syspolicyd cause it to consider the app bundle to be safe, as detailed here.
CVE-2019-8656 Assignment of the quarantine attribute. Since symbolic links are not assigned with the quarantine extended attribute, an archive that contains a symbolic link to an app that resides in an external filesystem (NFS) results in a Gatekeeper bypass. Apple fixed the issue by blocking the execution of applications from remote shared locations, documented here.
CVE-2014-8826 Component(s) that enforce policy checks. Quarantine attributes are not checked for JAR files, which are run by Java, as summarized here.

Metadata persistence over AppleDouble

Intrigued by CVE-2021-1810, as listed in the above table, we wondered what mechanism could be leveraged in archives. Considering symbolic links are preserved in archives and aren’t assigned with quarantine attributes—we looked for a mechanism that could persist different kinds of metadata over archives.

After some investigation, we discovered a way to persist important file metadata through a mechanism called AppleDouble.

Even though extended attributes are common on different filesystems, they might be implemented differently or even not supported, so copying files with their metadata becomes a challenging task. To solve this problem, back in 1994, Apple introduced the concept of AppleSingle and AppleDouble formats. In a nutshell, AppleSingle is a binary blob that is added as a part of the original file contents so that there’s only a “single” file to process, whereas AppleDouble saves the metadata in a different file side-by-side next to the original file, with a “._” prefix.

Interestingly, when extracting an archive, macOS processes any attached AppleDouble file and assigns the target file with the appropriate metadata.

The AppleDouble binary file format is quite complicated, but the code that parses it can be read in the XNU git repository in the file that handles extended attributes, which also includes ASCII-art depiction of the format. To demonstrate the AppleDouble file information, we used the ditto utility as such:

Graphical user interface; text
Figure 3. AppleDouble file created as “._somefile”

When the file is archived alongside its original file and then extracted by macOS, extended attributes are fully restored, as demonstrated here:

Graphical user interface; text
Figure 4. Using AppleDouble in a zip file to preserve extended attributes

Using this newfound knowledge, we examined how we could use the AppleDouble mechanism to trick Gatekeeper in some way.

Our first approach was to generate many large extended attributes in the AppleDouble format such that there won’t be enough space to assign the com.apple.quarantine extended attribute. Interestingly, it doesn’t work—AppleDouble is ignored if the overall size is over 2 GB, and there is no limitation on the number of extended attributes a file could get (besides the size of the disk).

Researching further, we decided to examine the source code of the unarchiving mechanism. Carefully studying the copyfile_unpack implementation, we discovered an option for a special extended attribute named com.apple.acl.text (saved in the XATTR_SECURITY_NAME constant in the source code), which is used to set arbitrary Access Control Lists.

Graphical user interface; text
Figure 5. The code that allows setting arbitrary Access Control Lists

Using ACLs for exploitation

Access Control Lists (ACLs) are a mechanism in macOS that further extends the traditional permission model. The traditional permission model saves permission for each file in a file “mode”, which can be changed by using the chmod utility. It enforces permissions on the owning user, owning group, and others in terms of reading (r), writing (w) and launching (x). A file’s mode can be viewed by listing files with the “-l” (long) flag:

Graphical user interface; text
Figure 6. Viewing the “hello.sh” file mode, the owner can do anything while others can only read or launch it

Unlike the traditional permission mechanism, ACLs allow fine-grained permissions to files and directories. Each ACL has one or more Access Control Entries (ACEs) that dictate what each principal can or cannot do, much like firewall rules. Like the file mode, ACLs can be modified with the chmod utility and viewed with the ls utility. It’s important to note that file access checks are dictated by both ACLs and the traditional permission model mechanisms, as demonstrated by the following example:

Graphical user interface; text
Figure 7. Denying file reads from everyone makes it impossible to read the file despite its mode

The set of authorizations supported by ACLs is well-documented by Apple in the chmod manual, which contain more than the traditional reading, writing, or launching abilities, including:

  • writeattr: controls the ability to write attributes to the file
  • writeextattr: controls the ability to write extended attributes to the file
  • writesecurity: controls the ability to set ACLs to the file
  • chown: controls the ability to set the owner of the file
  • delete: controls the ability to delete the file

Equipped with this information, we decided to add very restrictive ACLs to the downloaded files. Those ACLs prohibit Safari (or any other program) from setting new extended attributes, including the com.apple.quarantine attribute.

Two minor challenges that we had to overcome during the proof-of-concept (POC) development were:

  • The format of the ACL text as saved in the AppleDouble file isn’t identical to the format of the chmod command line. This can easily be overcome by invoking the macOS acl_to_text API and saving the ACL with the correct format.
  • When using the ditto utility, the com.apple.acl.text extended attribute is lost in the resulting AppleDouble file. This can be overcome by either manually creating the binary AppleDouble or, as we chose in this case, simply patching the resulting AppleDouble file before archiving it.

Therefore, our POC is as follows:

  1. Create a fake directory structure with an arbitrary icon and payload.
  2. Create an AppleDouble file with the com.apple.acl.text extended attribute key and a value that represents a restrictive ACL (we chose the equivalent of “everyone deny write,writeattr,writeextattr,writesecurity,chown”). Perform the correct AppleDouble patching if using ditto to generate the AppleDouble file.
  3. Create an archive with the application alongside its AppleDouble file and host it on a web server.

We named our POC exploit Achilles after its use of ACLs to bypass Gatekeeper. Our POC recorded video can be viewed here:

The AppleDouble file we used for this Gatekeeper bypass can be generated, as displayed below:

Graphical user interface; text
Figure 8. Generic AppleDouble file that can be used for any Gatekeeper bypass

Improving security for all through research and threat intelligence sharing

The threat landscape continues to evolve, delivering new threats and attack capabilities that take advantage of unpatched vulnerabilities and misconfigurations as a vector to access systems and data. Our data shows that fake apps remain one of the top entry vectors on macOS, indicating Gatekeeper bypass techniques are an attractive and even a necessary capability for adversaries to leverage in attacks. Nonetheless, through research-driven protections and collaboration with customers, partners, and industry experts, we strive to enrich our protection technologies to defend against such issues—regardless of the platform or device in use.

As environments continue to rely on a diverse range of devices and operating systems, organizations need security solutions that can provide protection across platforms and a complete picture of their security posture. Collaborative research such as this informs our comprehensive protection capabilities across platforms, allowing Microsoft Defender for Endpoint to deliver and coordinate threat defense across all major OS platforms including Windows, macOS, Linux, Android, and iOS. On macOS devices, Microsoft Defender for Endpoint detects and exposes threats and vulnerabilities, including CVE-2022-42821, using antivirus, endpoint detection and response (EDR), and threat and vulnerability management capabilities. This research also improved Microsoft Defender’s Vulnerability Management capabilities to discover, prioritize, and remediate misconfigurations and vulnerabilities. This includes detecting CVE-2022-42821 on macOS devices by examining AppleDouble files misusing ACLs.

This case also emphasized the need for responsible vulnerability disclosures and expert, cross-platform collaboration to effectively mitigate issues, protecting users against present and future threats. We wish to again thank the Apple product security team for their efforts and responsiveness in addressing the issue.

Microsoft Defender for Endpoint detecting and preventing an AppleDouble file
Figure 8. Generic AppleDouble file that can be used for any Gatekeeper bypass

Our Microsoft security researchers continue to discover new threats and vulnerabilities as part of our effort to secure users’ computing experiences, be it a Windows or non-Windows device. In the effort to improve security for all, we will continue to share intelligence and work with the security community to create and improve upon solutions that protect users and organizations across platforms every single day.

Jonathan Bar Or

Microsoft 365 Defender Research Team

The post Gatekeeper’s Achilles heel: Unearthing a macOS vulnerability appeared first on Microsoft Security Blog.

Uncovering a macOS App Sandbox escape vulnerability: A deep dive into CVE-2022-26706

July 13th, 2022 No comments

Microsoft uncovered a vulnerability in macOS that could allow specially crafted codes to escape the App Sandbox and run unrestricted on the system. We shared these findings with Apple through Coordinated Vulnerability Disclosure (CVD) via Microsoft Security Vulnerability Research (MSVR) in October 2021. A fix for this vulnerability, now identified as CVE-2022-26706, was included in the security updates released by Apple on May 16, 2022. Microsoft shares the vulnerability disclosure credit with another researcher, Arsenii Kostromin (0x3c3e), who discovered a similar technique independently.

We encourage macOS users to install these security updates as soon as possible. We also want to thank the Apple product security team for their responsiveness in fixing this issue.

The App Sandbox is Apple’s access control technology that application developers must adopt to distribute their apps through the Mac App Store. Essentially, an app’s processes are enforced with customizable rules, such as the ability to read or write specific files. The App Sandbox also restricts the processes’ access to system resources and user data to minimize the impact or damage if the app becomes compromised. However, we found that specially crafted codes could bypass these rules. An attacker could take advantage of this sandbox escape vulnerability to gain elevated privileges on the affected device or execute malicious commands like installing additional payloads.

We found the vulnerability while researching potential ways to run and detect malicious macros in Microsoft Office on macOS. For backward compatibility, Microsoft Word can read or write files with an “~$” prefix. Our findings revealed that it was possible to escape the sandbox by leveraging macOS’s Launch Services to run an open –stdin command on a specially crafted Python file with the said prefix.

Our research shows that even the built-in, baseline security features in macOS could still be bypassed, potentially compromising system and user data. Therefore, collaboration between vulnerability researchers, software vendors, and the larger security community remains crucial to helping secure the overall user experience. This includes responsibly disclosing vulnerabilities to vendors.

In addition, insights from this case study not only enhance our protection technologies, such as Microsoft Defender for Endpoint, but they also help strengthen the security strategies of software vendors and the computing landscape at large. This blog post thus provides details of our research and overviews of similar sandbox escape vulnerabilities reported by other security researchers that helped enrich our analysis.

How macOS App Sandbox works

In a nutshell, macOS apps can specify sandbox rules for the operating system to enforce on themselves. The App Sandbox restricts system calls to an allowed subset, and the said system calls can be allowed or disallowed based on files, objects, and arguments. Simply put, the sandbox rules are a defense-in-depth mechanism that dictates the kind of operations an application can or can’t do, regardless of the type of user running it. Examples of such operations include:

  • the kind of files an application can or can’t read or write;
  • whether the application can access specific resources such as the camera or the microphone, and;
  • whether the application is allowed to perform inbound or outbound network connections.
Diagram comparing how user data and system resources access an app without and with App Sandbox. 

Without App Sandbox, all user data and system resources will have unrestricted access to the app.

With App Sandbox, only the data and resources confined within the said sandbox will have unrestricted access to the app. All other user data and resources won't have access.
Figure 1. Illustration of a sandboxed app, from the App Sandbox documentation (photo credit: Apple)

Therefore, the App Sandbox is a useful tool for all macOS developers in providing baseline security for their applications, especially for those that have large attack surfaces and run user-provided code. One example of these applications is Microsoft Office.

Sandboxing Microsoft Office in macOS

Attackers have targeted Microsoft Office in their attempts to gain a foothold on devices and networks. One of their techniques is abusing Office macros, which they use in social engineering attacks to trick users into downloading malware and other payloads.

On Windows systems, Microsoft Defender Application Guard for Office helps secure Microsoft Office against such macro abuse by isolating the host environment using Hyper-V. With this feature enabled, an attacker must first be equipped with a Hyper-V guest-to-host vulnerability to affect the host system—a very high bar compared to simply running a macro. Without a similar isolation technology and default setting on macOS, Office must rely on the operating system’s existing mitigation strategies. Currently, the most promising technology is the macOS App Sandbox.

Viewing the Microsoft sandbox rules is quite straightforward with the codesign utility. Figure 2 below shows the truncated sandbox rules for Microsoft Word:

Partial screenshot of a command line interface showing different keys and values related to the App Sandbox rules for Microsoft Word in macOS.
Figure 2. Viewing the Microsoft Word sandbox rules with the codesign utility

One of the rules dictates the kind of files the application is allowed to read or write. As seen in the screenshot of the syntax below, Word is allowed to read or write files with filenames that start with the “~$” prefix. The reason for this rule is rooted in the way Office works internally and remains intact for backward compatibility.

One of the rules dictates the kind of files the application is allowed to read or write. As seen in the screenshot of the syntax below, Word is allowed to read or write files with filenames that start with the “~$” prefix. The reason for this rule is rooted in the way Office works internally and remains intact for backward compatibility.

Partial screenshot of a command line interface showing the read/write App Sandbox rule for Microsoft Word in macOS.
Figure 3. File read and write sandbox rule for Microsoft Word

Despite the security restrictions imposed by the App Sandbox’s rules on applications, it’s possible for attackers to bypass the said rules and let malicious codes “escape” the sandbox and execute arbitrary commands on an affected device. These codes could be hidden in a specially crafted Word macro, which, as mentioned earlier, is one of the attackers’ preferred entry points.

Previously reported Office-specific sandbox escape vulnerability

For example, in 2018, MDSec reported a vulnerability in Microsoft Office on macOS that could allow an attacker to bypass the App Sandbox. As explained in their blog post, MDSec’s proof-of-concept (POC) exploit took advantage of the fact that Word could drop files with arbitrary contents to arbitrary directories (even after passing traditional permission checks), as long as these files’ filenames began with a “~$” prefix. This bypass was relatively straightforward: have a specially crafted macro drop a .plist file in the user’s LaunchAgents directory.

The LaunchAgents directory is a well-known persistence mechanism in macOS. PLIST files that adhere to a specific structure describe (that is, contain the metadata of) macOS launch agents initiated by the launchd process when a user signs in. Since these launch agents will be the children of launchd, they won’t inherit the sandbox rules enforced onto Word, and therefore will be out of the Office sandbox.

Shortly after the above vulnerability was reported, Microsoft deployed a fix that denied file writes to the LaunchAgents directory and other folders with similar implications. The said disclosure also prompted us to look into different possible sandbox escapes in Microsoft Word and other applications.

Exploring Launch Services as means of escaping the sandbox

In 2020, several blog posts described a generic sandbox escape vulnerability in macOS’s /usr/bin/open utility, a command commonly used to launch files, folders, and applications just as if a user double-clicked them. While open is a handy command, it doesn’t create child processes on its own. Instead, it performs an inter-process communication (IPC) with the macOS Launch Services, whose logic is implemented in the context of the launchd process. Launch Services then performs the heavy lifting by resolving the handler and launching the right app. Since launchd creates the process, it’s not restricted by the caller’s sandbox, similar to how MDSec’s POC exploit worked in 2018.

However, using open for sandbox escape purposes isn’t trivial because the destination app must be registered within Launch Services. This means that, for example, one couldn’t run files like osascript outside the sandbox using open. Our internal offensive security team therefore decided to reassess the open utility for sandbox escape purposes and use it in a larger end-to-end attack simulation.

Our obvious first attempt in creating a POC exploit was to create a macro that launches a shell script with the Terminal app. Surprisingly, the POC didn’t work because files dropped from within the sandboxed Word app were automatically given the extended attribute com.apple.quarantine (the same one used by Safari to keep track of internet-downloaded files, as well as by Gatekeeper to block malicious files from executing), and Terminal simply refused to run files with that attribute. We also tried using Python scripts, but the Python app had similar issues running files having the said attribute.

Our second attempt was to use application extensibility features. For example, Terminal would run the default macOS shell (zsh), which would then run arbitrary commands from files like ~/.zshenv before running its own command line. This meant that dropping a .zshenv file in the user’s home directory and launching the Terminal app would cause the sandbox escape. However, due to Word’s sandbox rules, dropping a .zshenv file wasn’t straightforward, as the rules only allowed an application to write to files that begin with the “~$” prefix.

However, there is an interesting way of writing such a file indirectly. macOS was shipped with an application called Archive Utility responsible of extracting archive files (such as ZIP files). Such archives were extracted without any user interaction, and the files inside an archive were extracted in the same directory as the archive itself. Therefore, our second POC worked as follows:

  1. Prepare the payload by creating a .zshenv file with arbitrary commands and placing it in a ZIPfile. Encode the ZIPfile contents in a Word macro and drop those contents into a file “~$exploit.zip” in the user’s home directory.
  2. Launch Archive Utility with the open command on the “~$exploit.zip” file. Archive Utility ran outside the sandbox (since it’s the child process of /usr/bin/open) and was therefore permitted to create files with arbitrary names. By default, Archive Utility extracted the files next to the archive itself—in our case, the user’s home directory. Therefore, this step successfully created a .zshenv file with arbitrary contents in the user’s home directory.
  3. Launch the Terminal app with the open command. Since Terminal hosted zsh and zsh ran commands from the .zshenv file, the said file could escape the Word sandbox successfully.
Screenshot of a command line interface showing proof-of-concept exploit code.
Figure 4. Preparing a Word macro with our sandbox escape for an internal Red Team operation

Perception Point’s CVE-2021-30864

In October 2021, Perception Point published a blog post that discussed a similar finding (and more elegant, in our opinion). In the said post, Perception Point released details about their sandbox escape (now identified as CVE-2021-30864), which used the following facts:

  1. Every sandboxed process had its own container directory that’s used as a “scratch space.” The sandboxed process could write arbitrary files, including arbitrary filenames, to that directory unrestricted.
  2. The open command had an interesting –env option that could set or override arbitrary environment variables for the launched app.

Therefore, Perception Point’s POC exploit was cleverly simple:

  1. Drop a .zshenv file in the container directory. This was allowed because sandbox rules weren’t enforced on that directory.
  2. Launch Terminal with the open command but use the –env option to override the HOME environment variable to point to the container directory. This made zsh consider the user’s home directory to be the container directory, and run commands from the planted .zshenv file.

Apple has since patched the vulnerability Perception Point reported in the latest version of macOS, Monterey. While we could still create the “~$exploit.zip” file in the user’s home directory, using open to launch the Archive Utility on the ZIP file now resulted in it being extracted to the Downloads folder. While this is an interesting behavior, we could no longer use it for sandbox escape purposes.

Final exploit attempt: Revisiting the ‘open’ command

After discovering that Apple has fixed both variants that abuse .zshenv, , we decided to examine all the command line options of the open command. Soon after, we came across the following:

Screenshot of a command line interface with the following text:

--stdin PATH
       Launches the application with stdin connected to PATH.
Figure 5. The –stdin option in the open utility as presented by its manual entry

As mentioned earlier, we couldn’t run Python with a dropped .py file since Python refuses to run files with the “com.apple.quarantine” extended attribute. We also considered abusing the PYTHONSTARTUP environment variable, but Apple’s fix to CVE-2021-30864 apparently prevented that option, too. However, –stdin bypassed the “com.apple.quarantine” extended attribute restriction, as there was no way for Python to know that the contents from its standard input originated from a quarantined file.

Our POC exploit thus became simply as follows:

  1. Drop a “~$exploit.py” file with arbitrary Python commands.
  2. Run open –stdin=’~$exploit.py’ -a Python, which runs the Python app with our dropped file serving as its standard input. Python happily runs our code, and since it’s a child process of launchd, it isn’t bound to Word’s sandbox rules.
Screenshot of a proof-of-concept exploit code.
Figure 6. Sample minimal POC exploit code

We also came up with a version that’s short enough to be a Twitter post:

Screenshot of a proof-of-concept exploit code.
Figure 7. “Tweetable” POC exploit

Detecting App Sandbox escapes with Microsoft Defender for Endpoint

Since our initial discovery of leveraging Launch Services in macOS for generic sandbox escapes, we have been using our POC exploits in Red Team operations to emulate end-to-end attacks against Microsoft Defender for Endpoint, improve its capabilities, and challenge our detections. Shortly after our Red Team used our first POC exploit, our Blue Team members used it to train artificial intelligence (AI) models to detect our exploit not only in Microsoft Office but also on any app used for a similar Launch Services-based sandbox escape.

After we learned of Perception Point’s technique and created our own new exploit technique (the Python POC), our Red Team saw another opportunity to fully test our own detection durability. Indeed, the same set of detection rules that handled our first sandbox escape vulnerability still turned out to be durable—even before the vulnerability related to our second POC exploit was patched.

Partial screenshot of Microsoft Defender for Endpoint detecting an Office sandbox escape vulnerability. 

The left panel shows the Alert Story with timestamps. The right panel shows the Alert details, including category, MITRE ATT&CK techniques, detection source, service source, detection status, and other information.
Figure 8. Microsoft Defender for Endpoint detecting Office sandbox escape

For Defender for Endpoint customers, such detection durability feeds into the product’s threat and vulnerability management capabilities, which allows them to quickly discover, prioritize, and remediate misconfigurations and vulnerabilities—including those affecting non-Windows devices—through a unified security console.

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 Uncovering a macOS App Sandbox escape vulnerability: A deep dive into CVE-2022-26706 appeared first on Microsoft Security Blog.

The evolution of a Mac trojan: UpdateAgent’s progression

Our discovery and analysis of a sophisticated Mac trojan in October exposed a year-long evolution of a malware family—and depicts the rising complexity of threats across platforms. The trojan, tracked as UpdateAgent, started as a relatively basic information-stealer but was observed distributing secondary payloads in the latest campaign, a capability that it added in one of its multiple iterations. Reminiscent of the progression of info-stealing trojans in other platforms, UpdateAgent may similarly become a vector for other threats to infiltrate target systems.

Since its first appearance in September 2020, the malware displayed an increasing progression of sophisticated capabilities, and while the latest two variants were sporting much more refined behavior compared with earlier versions, they show signs that the malware is still in the development stage and more updates are likely to come. The latest campaign saw the malware installing the evasive and persistent Adload adware, but UpdateAgent’s ability to gain access to a device can theoretically be further leveraged to fetch other, potentially more dangerous payloads.

UpdateAgent lures its victims by impersonating legitimate software and can leverage Mac device functionalities to its benefit. One of the most advanced techniques found in UpdateAgent’s latest toolbox is bypassing Gatekeeper controls, which are designed to ensure only trusted apps run on Mac devices. The trojan can leverage existing user permissions to quietly perform malicious activities before deleting the evidence to cover its tracks. UpdateAgent also misuses public cloud infrastructure, namely Amazon S3 and CloudFront services, to host its additional payloads. We shared our findings with the team at Amazon Web Services, and they have taken down the malicious URLs–another example of how intelligence sharing and collaboration results in better security for the broader community.

Threats like UpdateAgent are proof that, as environments continue to rely on a diverse range of devices and operating systems, organizations need security solutions that can provide protection across platforms and a complete picture of their security posture. Microsoft Defender for Endpoint delivers and coordinates threat defense across all major OS platforms including Windows, macOS, Linux, Android and iOS. On macOS devices, Microsoft Defender for Endpoint detects and exposes threats and vulnerabilities through its antivirus, endpoint detection and response (EDR), and threat and vulnerability management capabilities.

In this blog post, we share the evolving development of the UpdateAgent trojan targeting Mac users and detail the malware’s recent campaign to compromise devices, steal sensitive information, and distribute adware as a secondary payload.

Progression of UpdateAgent

UpdateAgent is uniquely characterized by its gradual upgrading of persistence techniques, a key feature that indicates this trojan will likely continue to use more sophisticated techniques in future campaigns. Like many information-stealers found on other platforms, the malware attempts to infiltrate macOS machines to steal data and it is associated with other types of malicious payloads, increasing the chances of multiple infections on a device.

The trojan is likely distributed via drive-by downloads or advertisement pop-ups, which impersonate legitimate software such as video applications and support agents. This action of impersonating or bundling itself with legitimate software increases the likelihood that users are tricked into installing the malware. Once installed, UpdateAgent starts to collect system information that is then sent to its command-and-control (C2) server.

Notably, the malware’s developer has periodically updated the trojan over the last year to improve upon its initial functions and add new capabilities to the trojan’s toolbox. The timeline below illustrates a series of techniques adopted by UpdateAgent from September 2020 through October 2021:

A timeline detailing UpdateAgent's evolution between September 2020 and October 2021 and the techniques the trojan adopted with each update. The timeline is further detailed in the following section:
Figure 1. Tracking the evolution of UpdateAgent
  • September–December 2020: The initial version of UpdateAgent was considered to be a fairly basic information-stealer. At the time, the malware was only capable of performing reconnaissance to scan and collect system information such as product names and versions. Once gathered, the data was then sent as heartbeats to the malware’s C2 server.
  • January–February 2021: Approximately two months later, UpdateAgent maintained its original capabilities and added a new one: the ability to fetch secondary payloads as .dmg files from public cloud infrastructure. DMG files are mountable disk images used to distribute software and apps to macOS, allowing the trojan to easily install additional programs on affected devices.
  • March 2021: Upon its third update, the malware altered one of its prior functions to fetch secondary payloads as .zip files instead of .dmg files. The malware’s developer also included two new capabilities: the ability to bypass Gatekeeper by removing the downloaded file’s quarantine attribute and the ability to create a PLIST file that is added to the LaunchAgent folder. The quarantine attribute forces Gatekeeper to block the launch of any file downloaded from the web or other unknown sources, and it also displays a pop-up warning that users cannot open the respective file as “it is from an unidentified developer”. By removing the attribute, the malware both prevented the pop-up message warning users and allowed the files to launch without being blocked by Gatekeeper. Moreover, as the LaunchAgent folder specifies which apps and code automatically run each time a user signs into the machine, adding the malware’s PLIST file allowed it to be included in these automatic launches for persistence upon users signing into the affected device.
  • August 2021: The malware’s fourth update further altered some of its prior capabilities. For one, it expanded its reconnaissance function to scan and collect System_profile and SPHardwaretype information. Additionally, UpdateAgent was changed to create and add PLIST files to the LaunchDaemon folder instead of the LaunchAgent folder. While targeting the LaunchDaemon folder instead of the LaunchAgent folder required administrative privileges, it permitted the malware to inject persistent code that ran as root. This code generally takes the form of background processes that don’t interact with users, thus it also improved the trojan’s evasiveness.
  • October 2021: We detected the latest variants of UpdateAgent just over a year since its release into the wild. Sporting many of the updates found in the August 2021 variant, UpdateAgent still performed system reconnaissance, communicated with the C2 server as heartbeats, and bypassed Gatekeeper. Additionally, the October update expanded the malware’s ability to fetch secondary payloads as both .dmg or .zip files from public cloud infrastructure, rather than choosing between filetypes. Among its new capabilities, UpdateAgent included the ability to enumerate LSQuarantineDataURLString using SQLite in order to validate whether the malware’s downloaded app is within the Quarantine Events database where it would be assigned a quarantine attribute. The upgrade also allowed the malware to leverage existing user profiles to run commands requiring sudo access in addition to the ability to add arguments using PlistBuddy to create and edit PLIST files more easily. Lastly, the trojan included the ability to modify sudoers list, allowing the malware to bypass a prompt requiring high privilege user credentials while running UpdateAgent’s downloaded app.

October 2021 Campaign

In the October 2021 campaign, UpdateAgent included a larger set of sophisticated techniques than ever previously observed. The attackers distributed the trojanized app in .zip or .pkg format, conforming with a campaign observed in early 2021:

The attack chain of the latest UpdateAgent campaign depicts the trojan first arriving by posing as legitimate software and is distributed via drive-by download. Once installed, it then performs reconnaissance and collects system information before leveraging existing user privileges to create folders and elevate permissions. It then downloads Adload adware from public cloud infrastructure and bypasses Gatekeeper by removing the downloaded file's quarantine attribute. UpdateAgent then adds and modifies the PLIST file using PLIST buddy and adds the modified PLIST to created LaunchAgents or LaunchDaemon folder for persistence. The trojan sends heartbeats to the C2 server with the collected information and then covers its tracks by removing the files and folders from the device.
Figure 2. Attack chain of the latest UpdateAgent campaign

Upon analyzing UpdateAgent’s infrastructure, we determined that the infrastructure used in the October 2021 campaign was created at the end of September 2021, and we also discovered additional domains with payloads. This indicates that the trojan is still in the developmental stage and is likely to add or modify its capabilities in future updates and continue its track of improving its overall level of sophistication.

We further observed two separate variants of the UpdateAgent trojan in its October 2021 campaign. Each variant leveraged different tactics to infect a device, as detailed below:

Variant 1

The first variant of UpdateAgent takes the following steps to infect a device:

  1. A .zip file named HelperModule.zip downloads and installs UpdateAgent using a specific file path – /Library/Application Support/xxx/xxx. This .zip file is installed in /Library/Application Support/Helper/HelperModule.
  2. UpdateAgent collects operating system and hardware information about the affected device. Once the compromised device connects to the C2 server, the trojan uses a curl request to send this data to the C2 server.
  3. Upon successful connection, UpdateAgent requests a secondary payload, usually a .dmg or .zip file, which is hosted on a CloudFront instance.
  4. Once the secondary payload downloads, UpdateAgent uses the xattr command – /usr/bin/xattr -rc /tmp/setup.dmg, to remove the quarantine attribute of downloaded files and bypass Gatekeeper controls.
  5. UpdateAgent then extracts the secondary payload (.dmg or .zip). Once the file is mounted, it unzips and copies the payload files to a temporary folder, assigning executable permissions, and launches these files. UpdateAgent also uses PlistBuddy to create PLIST files under the LaunchAgent folder to remain persistent through system restart.
  6. UpdateAgent removes evidence by deleting the secondary payload, temporary folders, PLIST files, and all other downloaded artifacts.

Variant 2

The second variant of UpdateAgent takes the following steps to infect a device:

  1. A third-party WebVideoPlayer application (WebVideoPlayer.pkg) with a post-install script downloads additional apps or .zip files as /Applications/WebVideoPlayer.app/Contents/MacOS/WebVideoPlayer. Notably, this application included a valid certificate that was later revoked by Apple in October 2021.
  2. The application scans the user profile to identify existing user IDs and assigned groups.
  3. The WebVideoPlayer application uses SQLite3 commands to determine if the .pkg file is within the Quarantine Events database, which contains URLs of downloaded files, mail addresses, and subjects for saved attachments.
  4. The .pkg payload extracts and drops UpdateAgent in /Library/Application Support/WebVideoPlayer/WebVideoPlayerAgent.
  5. The WebVideoPlayer application also assigns executable permissions to UpdateAgent and attempts to remove the quarantine attribute of the file using the xattr command to bypass Gatekeeper controls.
  6. The application then launches UpdateAgent and collects and sends the OS information to the attacker’s C2 server. Like the first variant, the second variant sends curl requests that download additional payloads, such as adware, and removes evidence by deleting all files and folders that it created.

Adload adware

UpdateAgent is further characterized by its ability to fetch secondary payloads that can increase the chances of multiple infections on a device, with the latest campaign pushing adware. We first observed UpdateAgent distributing adware as a secondary payload in its October 2021 campaign, identified as part of the Adload adware family by Microsoft Defender Antivirus.

Similar to UpdateAgent, adware is often included in potentially unwanted or malicious software bundles that install the adware alongside impersonated or legitimate copies of free programs. In Adload’s case, we previously observed the adware family targeting macOS users had spread via rogue installers often found on malicious websites.

Once adware is installed, it uses ad injection software and techniques to intercept a device’s online communications and redirect users’ traffic through the adware operators’ servers, injecting advertisements and promotions into webpages and search results. More specifically, Adload leverages a Person-in-The-Middle (PiTM) attack by installing a web proxy to hijack search engine results and inject advertisements into webpages, thereby siphoning ad revenue from official website holders to the adware operators.

Adload is also an unusually persistent strain of adware. It is capable of opening a backdoor to download and install other adware and payloads in addition to harvesting system information that is sent to the attackers’ C2 servers. Considering both UpdateAgent and Adload have the ability to install additional payloads, attackers can leverage either or both of these vectors to potentially deliver more dangerous threats to target systems in future campaigns.

Defending against macOS threats

UpdateAgent’s evolution displays the increasing complexity of threats across platforms. Its developers steadily improved the trojan over the last year, turning a basic information-stealer into a persistent and more sophisticated piece of malware. This threat also exemplifies the trend of common malware increasingly harboring more dangerous threats, a pattern also observed in other platforms. UpdateAgent’s ability to gain access to a device can theoretically be leveraged by attackers to introduce potentially more dangerous payloads, emphasizing the need to identify and block threats such as this.

Defenders can take the following mitigation steps to defend against this threat:

  • Encourage the use of Microsoft Edge—available on macOS and various platforms—or other web browsers that support Microsoft Defender SmartScreen, which identifies and blocks malicious websites, including phishing sites, scam sites, and sites that contain exploits and host malware.
  • Restrict access to privileged resources, such as LaunchDaemons or LaunchAgents folders and sudoers files, through OSX enterprise management solutions. This helps to mitigate common persistence and privilege escalation techniques.
  • Install apps from trusted sources only, such as a software platform’s official app store. Third-party sources may have lax standards for the applications that they host, allowing malicious actors to upload and distribute malware.
  • Run the latest version of your operating systems and applications. Deploy the latest security updates as soon as they become available.

As organizational environments are intricate and heterogenous, running multiple applications, clouds, and devices, they require solutions that can protect across platforms. Microsoft Defender for Endpoint offers cross-platform security and a unified investigation experience that gives customers visibility across all endpoints and enables them to detect, manage, respond, and remediate threats, such as the capability to detect UpdateAgent’s anomalous use of PlistBuddy.

Microsoft Defender for Endpoint customers can apply the following mitigations to reduce the environmental attack surface and mitigate the impact of this threat and its payloads:

  • Turn on cloud-delivered protection and automatic sample submission on Microsoft Defender Antivirus. These capabilities use artificial intelligence and machine learning to quickly identify and stop new and unknown threats. 
  • Enable potentially unwanted application (PUA) protection in block mode to automatically quarantine PUAs like adware. PUA blocking takes effect on endpoint clients after the next signature update or computer restart. PUA blocking takes effect on endpoint clients after the next signature update or computer restart.
  • Turn on network protection to block connections to malicious domains and IP addresses.

Defender for Endpoint’s next-generation protection reinforces network security perimeters and includes antimalware capabilities to catch emerging threats, including UpdateAgent and its secondary payloads, C2 communications, and other malicious artifacts affiliated with the trojan’s reconnaissance activities. Moreover, macOS antimalware detections provide insight into where a threat originated and how the malicious process or activity was created, providing security teams a comprehensive view of incidents and attack chains.

Finally, this research underscores the importance of understanding a macOS threat’s progression to not only remedy its current abilities, but to prepare for increased capabilities and sophistication of the threat. As threats on other OS platforms continue to grow, our security solutions must secure users’ computing experiences be it a Windows or non-Windows machine. By sharing our research and other forms of threat intelligence, collaboration across the larger security community can aid in enriching our protection technologies, regardless of the platform or device in use.

Detection details

Antivirus

Microsoft Defender Antivirus detects threat components and behavior as the following malware:

Endpoint detection and response (EDR)

Alerts with the following titles in the Microsoft 365 Security Center can indicate threat activity within your network:

  • macOS Gatekeeper bypass
  • Executable permission added to file or directory
  • Suspicious database access
  • Suspicious System Hardware Discovery
  • Suspicious binary dropped and launched

Advanced hunting

To locate activity related to UpdateAgent, run the following advanced hunting queries in Microsoft 365 Defender or Microsoft Defender Security Center.

File quarantine attribute

Look for file quarantine attribute removal for the specific packages involved in the campaign. 

DeviceProcessEvents
| where FileName has "xattr" and (ProcessCommandLine has "-rc Library/Application Support/WebVideoPlayer/WebVideoPlayerAgent" or ProcessCommandLine has "-r -d /Library/Application Support/Helper/HelperModule")

Quarantine Event database

Look for quarantine event database enumeration through sqlite3 for the packages involved in the campaign. 

DeviceProcessEvents
| where FileName has "sqlite3" and ProcessCommandLine has "WebVideoPlayer.pkg"

Curl request

Look for UpdateAgent’s  curl requests.

DeviceProcessEvents
| where FileName has "curl" and ProcessCommandLine has "--connect-timeout 900 -L"

Indicators

Files (SHA-256)

  • 1966d64e9a324428dec7b41aca852034cbe615be1179ccb256cf54a3e3e242ee
  • ef23a1870d84e164a4234074251205190a5dfda9f465c8eee6c7e0d6878c2b05
  • 519339e67b1d421d51a0f096e80a57083892bac8bb16c7e4db360bb0fda3cb11
  • cc2f246dda46b17e9302242879788aa114ee64327c8de43ef2b9ab56e8fb57b2
  • 5c1704367332a659f6e10d55d08a3e0ab1bd26aa97654365dc82575356c80502
  • c60e210f73d5335f57f367bd7e166ff4c17f1073fd331370eb63342ab1c82238
  • f01dec606db8f66489660615c777113f9b1180a09db2f5d19fb5bca7ba3c28c7
  • 4f1399e81571a1fa1dc822b468453122f89ac323e489f57487f6b174940e9c2e
  • 9863bc1917af1622fdeebb3bcde3f7bebabcb6ef13eae7b571c8a8784d708d57
  • a1fba0bb0f52f25267c38257545834a70b82dbc98863aee01865a2661f814723
  • 81cfa53222fa473d91e2a7d3a9591470480d17535d49d91a1d4a7836ec943d3a
  • 78b4478cd3f91c42333561abb9b09730a88154084947182b2ec969995b25ad78
  • 91824c6a36ef60881b4f502102b0c068c8a3acd4bceb86eb4ffd1043f7990763
  • 86b45b861a8f0855c97cc38d2be341cc76b4bc1854c0b42bdca573b39da026ac
  • 84ff961552abd742cc2393dde20b7b3b7b2cfb0019c80a02ac24de6d5fcc0db4
  • 0ee6c8fd43c03e8dc7ea081dfa428f22209ed658f4ae358b867de02030cfc69b
  • 443b6173ddfbcc3f19d69f60a1e5d72d68d28b7323fe2953d051b32b4171aa9a
  • 409f1b4aeb598d701f6f0ed3b49378422c860871536425f7835ed671ba4dd908
  • 77f084b5fc81c9c885a9b1683a12224642072f884df9e235b78941a1ad69b80d
  • cbabbbb270350d07444984aa0ce1bb47078370603229a3f03a431d6b7a815820
  • 053fbb833ac1287d21ae96b91d9f5a9cfdd553bc41f9929521d4043e91e96a98
  • 29e3d46867caddde8bb429ca578dd04e5d7112dd730cd69448e5fb54017a2e30
  • 356d429187716b9d5562fe6eee35ea60b252f1845724b0a7b740fbddec73350f
  • a98ecd8f482617670aaa7a5fd892caac2cfd7c3d2abb8e5c93d74c344fc5879c
  • c94760fe237da5786464ec250eadf6f7f687a3e7d1a47e0407811a586c6cb0fc
  • eb71d15308bfcc00f1b80bedbe1c73f1d9e96fd55c86cf420f1f4147f1604f67
  • 0c08992841d5a97e617e72ade0c992f8e8f0abc9265bdca6e09e4a3cb7cb4754
  • 738822e109f1b14413ee4af8d3d5b2219293ea1a387790f207d937ca11590a14
  • 0d9f861fe4910af8299ac3cb109646677049fa9f3188f52065a47e268438b107
  • a586ef06ab8dd6ad1df77b940028becd336a5764caf097103333975a637c51fa
  • 73a465170feed88048dbc0519fbd880aca6809659e011a5a171afd31fa05dc0b
  • d5c808926000bacb67ad2ccc4958b2896ea562f27c0e4fc4d592c5550e39a741
  • 7067e6a69a8f5fdbabfb00d03320cfc2f3584a83304cbeeca7e8edc3d57bbbd4
  • 939cebc99a50989ffbdbb2a6727b914fc9b2382589b4075a9fd3857e99a8c92a
  • c5017798275f054ae96c69f5dd0b378924c6504a70c399279bbf7f33d990d45b
  • 57d46205a5a1a5d6818ecd470b61a44aba0d935f256265f5a26d3ce791038fb4
  • e8d4be891c518898dd3ccdff4809895ed21558d90d415cee868bebdab2da7397
  • 9f1989a04936cd8de9f5f4cb1f5f573c1871b63737b42d18ac4fa337b089cbdc
  • b55c806367946a70d619f25e836b6883a36c9ad22d694a173866b57dfe8b29c9
  • e46b09b270552c7de1311a8b24e3fcc32c8db220c03ca0d8db05e08c76e536f1
  • f9842e31ed16fe0173875c38a41ed3a766041350b4efcd09da62718557ca3033
  • bad5dc1dd6ff19f9fb1af853a8989c1b0fdfeaa4c588443607de03fccf0e21c9

Download URLs

  • hxxps://d35ep4bg5x8d5j[.]cloudfront[.]net/pkg
  • hxxps://d7rp2fva69arq[.]cloudfront[.]net/pkg
  • hxxps://daqi268hfl8ov[.]cloudfront[.]net/pkg
  • hxxps://events[.]optimizerservices[.]com/pkg
  • hxxps://ekogidekinvgwyzmeydw[.]s3[.]amazonaws[.]com/OptimizerProcotolStatus[.]zip
  • hxxps://lnzjvpeyarvvvtljxsws[.]s3[.]amazonaws[.]com/ConsoleSoftwareUpdateAgent[.]zip
  • hxxps://qqirhvehhnvuemxezfxc[.]s3[.]amazonaws[.]com/ModuleAgent[.]zip
  • hxxps://dpqsxofvslaxjaiyjdok[.]s3[.]amazonaws[.]com/ProtocolStatus[.]zip
  • hxxps://oldbrlauserz[.]s3[.]amazonaws[.]com/setup[.]zip
  • hxxps://grxqorfazgqbmzeetpus[.]s3[.]amazonaws[.]com/SetupUpdateAgent[.]zip
  • hxxps://phdhrhdsp[.]s3[.]amazonaws[.]com/setup[.]zip
  • hxxps://xyxeaxtugahkwrcvbzsw[.]s3[.]amazonaws[.]com/BundleAgent[.]zip
  • [.]s3[.]amazonaws[.]com/GuideServices[.]zip
  • hxxps://tnkdcxekehzpnpvimdwquzwzgpehlnwgizrlmzev[.]s3[.]amazonaws[.]com/HelperModule[.]zip
  • hxxps://svapnilpkasjmwtygfstkhsdfrraa[.]s3[.]amazonaws[.]com/WizardUpdate[.]zip

The post The evolution of a Mac trojan: UpdateAgent’s progression appeared first on Microsoft Security Blog.

New macOS vulnerability, “powerdir,” could lead to unauthorized user data access

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 type Description Handled by
kTCCServiceLiverpool Location services access User-specific TCC database
kTCCServiceUbiquity iCloud access User-specific TCC database
kTCCServiceSystemPolicyDesktopFolder Desktop folder access User-specific TCC database
kTCCServiceCalendar Calendar access User-specific TCC database
kTCCServiceReminders Access to reminders User-specific TCC database
kTCCServiceMicrophone Microphone access User-specific TCC database
kTCCServiceCamera Camera access User-specific TCC database
kTCCServiceSystemPolicyAllFiles Full disk access capabilities System-wide TCC database
kTCCServiceScreenCapture Screen capture capabilities System-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

October 28th, 2021 No comments

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.inheritable 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.inheritable 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.inheritable”

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.