#!/bin/bash
##
##  David Fernandez Gonzalez: david.fernandezgonzalez@canonical.com
##

if [ "$EUID" -ne 0 ]; then
  echo "Please run as root"
  exit
fi

if [[ "$(dpkg -l | grep rsh-server)" ]]; then
    echo "Rsh-server package must be uninstalled"
    exit
fi

mkdir tmp-test-CVE-2019-7282-3
cd tmp-test-CVE-2019-7282-3
mkdir test

# Test 0: test_several_files_CVE_2019_7283
sudo python3 ../CVE-2019-7823-poc.py 0 &
sleep .2
rcp user@localhost:testfile.txt . 2> /dev/null

if [ -f "malicious.txt" ]; then
    echo "FAILED test_several_files_CVE_2019_7283"
else
    echo "OK test_several_files_CVE_2019_7283"
fi


# Test 1: test_lower_directory_CVE_2019_7283
sudo python3 ../CVE-2019-7823-poc.py 1 &
sleep .2
rcp user@localhost:testfile.txt . 2> /dev/null
if [ -f "../testfile.txt" ]; then
    echo "FAILED test_lower_directory_CVE_2019_7283"
else
    echo "OK test_lower_directory_CVE_2019_7283"
fi

# Test 2: test_upper_directory_CVE_2019_7283
sudo python3 ../CVE-2019-7823-poc.py 2 &
sleep .2
rcp user@localhost:testfile.txt . 2> /dev/null
if [ -f "test/testfile.txt" ]; then
    echo "FAILED test_upper_directory_CVE_2019_7283"
else
    echo "OK test_upper_directory_CVE_2019_7283"
fi

# Test 3: test_hidden_file_CVE_2019_7283
sudo python3 ../CVE-2019-7823-poc.py 3 &
sleep .2
rcp user@localhost:testfile.txt . 2> /dev/null
if [ -f ".test" ]; then
    echo "FAILED test_hidden_file_CVE_2019_7283"
else
    echo "OK test_hidden_file_CVE_2019_7283"
fi

# Test 4: test_other_file_CVE_2019_7283
sudo python3 ../CVE-2019-7823-poc.py 4 &
sleep .2
rcp user@localhost:testfile.txt . 2> /dev/null

if [ -f "malicious.txt" ]; then
    echo "FAILED test_other_file_CVE_2019_7283"
else
    echo "OK test_other_file_CVE_2019_7283"
fi

cd ../
rm -rf tmp-test-CVE-2019-7282-3