#!/bin/bash

set -e

cat << EOT
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
EOT

echo -n "Do you agree with this license? [y/N]: "
read yn

if ! [[ "$yn" =~ (y|Y|yes|Yes|YES) ]]; then
	exit 1
fi

mkdir -p /usr/share/ewheelerinc/
cat << 'EOT' > /usr/share/ewheelerinc/cve-2016-5195.stp

probe kernel.function("mem_write").call ? {
        $count = 0
}

probe syscall.ptrace {  // includes compat ptrace as well
        $request = 0xfff
}

probe begin {
        printk(0, "CVE-2016-5195 mitigation loaded")
}


probe end {
        printk(0, "CVE-2016-5195 mitigation unloaded")
}
EOT

PACKAGES="kernel-debuginfo-$(uname -r) kernel-devel-$(uname -r) kernel-devel systemtap"
REMOVE_LATER=$(for i in cpp gcc glibc-devel glibc-headers kernel-devel kernel-headers $PACKAGES; do
	rpm -qi $i &> /dev/null || echo $i
done)

yum install --enablerepo=base-debuginfo -y $PACKAGES systemtap-client

MODULE=$(stap -g -p 4 /usr/share/ewheelerinc/cve-2016-5195.stp)

mv "$MODULE" /usr/share/ewheelerinc/
MODULE=/usr/share/ewheelerinc/$(basename $MODULE)
staprun -L $MODULE

perl -i -lne '
	if (! $done && ! /^#/) {
		print "\n# CVE-2016-5195";
		print "staprun -L '$MODULE'\n";
		$done++;
	};
	print $_;
' /etc/rc.local

chmod 755 /etc/rc.local

echo "The following NEW packages were installed to build this systemtap module:"
echo "  " $REMOVE_LATER
echo "You may wish to remove these from your system with the following command:"
echo "  " yum remove $REMOVE_LATER
