#!/bin/bash
set -e

apt update
apt install -y apache2 php

systemctl enable apache2
systemctl restart apache2

# Upload directory
mkdir -p /var/www/html/uploads
chown www-data:www-data /var/www/html/uploads

# Vulnerable upload.php
cat << 'EOF' > /var/www/html/upload.php
<!DOCTYPE html>
<html>
<head><title>Upload</title></head>
<body>
<h2>파일 업로드</h2>
<form action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="file"><br><br>
    <button type="submit">Upload</button>
</form>
<?php
if ($_FILES) {
    $name = $_FILES["file"]["name"];
    if (!preg_match("/\.(jpg|png|pdf)$/i", $name)) {
        echo "허용되지 않는 확장자입니다.";
        exit;
    }
    move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/".$name);
    echo "Uploaded: uploads/".$name;
}
?>
</body>
</html>
EOF

# Simple index
echo "<h2>BabyUpload</h2><a href='upload.php'>Upload Page</a>" > /var/www/html/index.html

# FLAG for user
mkdir -p /home/ctf
echo "USER_FLAG{BABY_UPLOAD_EASY_BOX}" > /home/ctf/user.txt
chmod 444 /home/ctf/user.txt

#######################################
# PRIVILEGE ESCALATION BINARY (EASY)
#######################################

cat << 'EOF' > /usr/local/bin/backup
#!/bin/bash
# 취약 SUID : 백업 한다는 명목으로 root 권한으로 tar 실행
tar -cf /tmp/backup.tar *
EOF

chmod 755 /usr/local/bin/backup
chmod u+s /usr/local/bin/backup       # SUID 적용

# root flag
echo "FLAG{ROOT_OWNED_THE_BOX}" > /root/root.txt
chmod 600 /root/root.txt

