#!/bin/bash

###############################################################################
# Copy Fail (CVE-2026-31431) Detection & Mitigation Script
# 
# IMPORTANT: Always read scripts before executing them!
# Run with: sudo bash copy_fail_mitigate.sh
###############################################################################

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m'

# ============================================================================
# SCARE MESSAGE
# If you're reading this: good. You're doing the right thing.
# This message only "works" on people who blindly copy-paste scripts.
# ============================================================================

clear

echo ""
echo -e "${RED}${BOLD}╔════════════════════════════════════════════════════════════════╗${NC}"
echo -e "${RED}${BOLD}║                    ⚠️  SYSTEM ALERT  ⚠️                         ║${NC}"
echo -e "${RED}${BOLD}╚════════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${RED}${BOLD}YOU JUST RAN A SCRIPT WITHOUT READING IT FIRST!${NC}"
echo ""
echo -e "${RED}YOUR SYSTEM IS PERMANENTLY COMPROMISED!!!${NC}"
echo ""
echo -e "${YELLOW}(Files encrypted, data exfiltrated, backdoor installed...)${NC}"
echo ""
sleep 4
echo -e "${RED}Encrypting /home...${NC}"
sleep 2
echo -e "${RED}Uploading SSH keys...${NC}"
sleep 2
echo -e "${RED}Installing persistent backdoor...${NC}"
sleep 3
echo -e "${RED}Wiping logs...${NC}"
sleep 2
echo -e "${RED}Done.${NC}"
echo ""
sleep 5

echo ""
echo -e "${GREEN}${BOLD}═══════════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}${BOLD}WAIT! THIS IS JUST A JOKE 😅${NC}"
echo -e "${GREEN}${BOLD}═══════════════════════════════════════════════════════════════${NC}"
echo ""
echo "But the message you just read is critically important."
echo ""
echo -e "${BOLD}GOLDEN RULE:${NC} ${RED}ALWAYS READ SCRIPTS BEFORE RUNNING THEM.${NC}"
echo ""
echo "Even if they come from:"
echo "  - Friends"
echo "  - Blogs"
echo "  - YouTube videos (including mine!)"
echo "  - Forums"
echo "  - Anyone"
echo ""
echo -e "${YELLOW}A script can do ANYTHING to your system.${NC}"
echo "Delete files, steal data, install malware, everything."
echo ""
echo "If you don't understand what it does before running it,"
echo "it's already too late."
echo ""
echo -e "${BOLD}So: read it. Understand it. Then run it.${NC}"
echo ""
sleep 2

read -p "Press ENTER to continue... (Did you actually read the script? 🤔) " dummy
echo ""
echo -e "${GREEN}Good. Let's continue.${NC}"
echo ""
echo ""

# ============================================================================
# FUNCTIONS
# ============================================================================

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[ OK ]${NC} $1"
}

log_error() {
    echo -e "${RED}[FAIL]${NC} $1"
}

# ============================================================================
# ROOT CHECK
# ============================================================================

if [[ $EUID -ne 0 ]]; then
    log_error "This script must be run as root."
    echo ""
    echo "Usage: sudo bash $0"
    exit 1
fi

log_info "Copy Fail (CVE-2026-31431) Detection & Mitigation"
log_info "=================================================="
echo ""

# ============================================================================
# VULNERABILITY CHECK
# ============================================================================

check_vulnerability() {
    log_info "Checking if system is vulnerable to Copy Fail..."
    echo ""

    # Check if python3 is available
    if ! command -v python3 &>/dev/null; then
        log_warn "python3 not found. Falling back to module check..."
        echo ""

        if lsmod | grep -q algif_aead; then
            log_warn "algif_aead module is LOADED. System is likely vulnerable."
            return 1
        elif modprobe -n algif_aead 2>/dev/null; then
            log_warn "algif_aead module is available. System may be vulnerable."
            return 1
        else
            log_success "algif_aead module is not available. System is likely safe."
            return 0
        fi
    fi

    python3 << 'PYEOF'
import socket
import sys

try:
    s = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET)
    s.bind(('aead', 'gcm(aes)'))
    s.close()
    print("VULNERABLE")
    sys.exit(1)
except (OSError, AttributeError):
    print("NOT_VULNERABLE")
    sys.exit(0)
PYEOF

    VULN_STATUS=$?

    if [ $VULN_STATUS -eq 1 ]; then
        echo ""
        log_error "SYSTEM IS VULNERABLE TO COPY FAIL!"
        echo ""
        echo "  Any unprivileged local user can become root."
        echo ""
        return 1
    else
        echo ""
        log_success "System is NOT vulnerable (module disabled or kernel patched)."
        echo ""
        return 0
    fi
}

# ============================================================================
# APPLY MITIGATION
# ============================================================================

apply_mitigation() {
    log_info "Applying mitigation..."
    echo ""

    if [ -f /etc/modprobe.d/disable-algif_aead.conf ]; then
        log_warn "Mitigation config already exists. Skipping."
        echo ""
        return 0
    fi

    log_info "Creating /etc/modprobe.d/disable-algif_aead.conf..."

    cat > /etc/modprobe.d/disable-algif_aead.conf << 'MODCONF'
# CVE-2026-31431 (Copy Fail) Mitigation
# Disables the vulnerable algif_aead kernel module
# To revert: delete this file and reboot
# More info: https://xint.io/blog/copy-fail-linux-distributions
install algif_aead /bin/false
blacklist algif_aead
MODCONF

    log_success "Configuration file created."

    log_info "Unloading algif_aead from current session..."

    if rmmod algif_aead 2>/dev/null; then
        log_success "Module unloaded from memory."
    else
        log_info "Module was not loaded (that's fine)."
    fi

    echo ""
    log_success "Mitigation applied successfully!"
    echo ""
}

# ============================================================================
# ROLLBACK
# ============================================================================

rollback_mitigation() {
    log_warn "Rolling back mitigation..."
    echo ""

    if [ ! -f /etc/modprobe.d/disable-algif_aead.conf ]; then
        log_info "No mitigation config found. Nothing to rollback."
        echo ""
        return 0
    fi

    rm /etc/modprobe.d/disable-algif_aead.conf

    log_success "Mitigation config removed."
    echo ""
    echo "  The module will be available again after reboot."
    echo "  Run 'sudo reboot' to apply."
    echo ""
}

# ============================================================================
# STATUS REPORT
# ============================================================================

show_report() {
    echo ""
    log_info "============ SYSTEM REPORT ============"
    echo ""

    # Kernel version
    echo -e "  Kernel:        $(uname -r)"

    # Distribution
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        echo -e "  Distribution:  $PRETTY_NAME"
    else
        echo -e "  Distribution:  Unknown"
    fi

    echo -e "  Date:          $(date)"
    echo ""

    # Mitigation config
    if [ -f /etc/modprobe.d/disable-algif_aead.conf ]; then
        echo -e "  Mitigation:    ${GREEN}APPLIED${NC}"
    else
        echo -e "  Mitigation:    ${RED}NOT APPLIED${NC}"
    fi

    # Module status
    if lsmod | grep -q algif_aead; then
        echo -e "  Module loaded: ${RED}YES (still in memory)${NC}"
    else
        echo -e "  Module loaded: ${GREEN}NO${NC}"
    fi

    echo ""
    log_info "======================================="
    echo ""
}

# ============================================================================
# MENU
# ============================================================================

show_menu() {
    echo -e "${BOLD}What do you want to do?${NC}"
    echo ""
    echo "  1) Check if system is vulnerable"
    echo "  2) Apply mitigation (disable algif_aead)"
    echo "  3) Rollback mitigation (re-enable algif_aead)"
    echo "  4) Show system report"
    echo "  5) Exit"
    echo ""
}

# ============================================================================
# MAIN LOOP
# ============================================================================

while true; do
    show_menu
    read -p "Enter your choice (1-5): " choice
    echo ""

    case $choice in
        1)
            check_vulnerability
            ;;
        2)
            apply_mitigation
            ;;
        3)
            echo -e "${YELLOW}WARNING: This will re-enable the vulnerable module.${NC}"
            echo "Only do this if your kernel has been patched."
            echo ""
            read -p "Type 'yes' to confirm rollback: " confirm
            if [ "$confirm" = "yes" ]; then
                rollback_mitigation
            else
                echo "Rollback cancelled."
                echo ""
            fi
            ;;
        4)
            show_report
            ;;
        5)
            log_success "Exiting. Stay safe!"
            exit 0
            ;;
        *)
            log_error "Invalid choice."
            echo ""
            ;;
    esac

    read -p "Press ENTER to continue..." dummy
    clear
done
