#!/bin/bash

# 严格错误检查机制
set -eo pipefail

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # 无颜色

# 依赖工具列表
REQUIRED_TOOLS=("hping3" "nmap" "tcpdump" "ip" "sysctl")

# 检测root权限
check_root() {
    if [[ $EUID -ne 0 ]]; then
        echo -e "${RED}[错误] 本脚本需要root权限执行${NC}"
        exit 1
    fi
}

# 多发行版软件安装函数
install_package() {
    local pkg=$1
    declare -A pm=(
        ["apt"]="apt-get install -y"
        ["yum"]="yum install -y"
        ["dnf"]="dnf install -y"
        ["zypper"]="zypper install -y"
        ["pacman"]="pacman -S --noconfirm"
    )

    for manager in "${!pm[@]}"; do
        if command -v $manager &> /dev/null; then
            if $manager ${pkg} &> /dev/null; then
                echo -e "${GREEN}成功通过${manager}安装${pkg}${NC}"
                return 0
            fi
        fi
    done

    # 备选安装方式
    echo -e "${YELLOW}尝试通过编译源码安装${pkg}...${NC}"
    case $pkg in
        "hping3")
            git clone https://github.com/antirez/hping.git
            cd hping && ./configure && make && make install
            ;;
        "nmap")
            wget https://nmap.org/dist/nmap-7.94.tar.bz2
            tar xjf nmap-7.94.tar.bz2
            cd nmap-7.94 && ./configure && make && make install
            ;;
        *)
            echo -e "${RED}无法安装${pkg}，请手动安装后重试${NC}"
            return 1
            ;;
    esac
}

# 检查并安装依赖
check_dependencies() {
    for tool in "${REQUIRED_TOOLS[@]}"; do
        if ! command -v $tool &> /dev/null; then
            echo -e "${YELLOW}未找到 $tool，尝试安装...${NC}"
            if ! install_package $tool; then
                echo -e "${RED}依赖安装失败，请手动安装以下工具：${NC}"
                printf '%s\n' "${REQUIRED_TOOLS[@]}"
                exit 1
            fi
        fi
    done
}

# 检测内核参数
check_rp_filter() {
    local rp_filter=$(sysctl -n net.ipv4.conf.all.rp_filter)
    if [[ $rp_filter -eq 0 ]]; then
        echo -e "${GREEN}[通过] RP过滤已禁用(rp_filter=0)${NC}"
        return 0
    else
        echo -e "${RED}[警告] RP过滤已启用(rp_filter=$rp_filter)${NC}"
        return 1
    fi
}

# 实际伪造测试函数
perform_spoof_test() {
    local test_ip="8.8.8.8"  # Google DNS 用于测试
    local test_port=53       # DNS端口
    local timeout=5

    echo -e "${YELLOW}开始发送伪造数据包测试...${NC}"
    
    # 后台抓包
    tcpdump -ni any "src ${test_ip}" -c 1 -w /tmp/spoof_test.pcap &
    local tcpdump_pid=$!
    
    # 发送伪造包
    hping3 -S -c 1 -s 12345 -p $test_port -a $test_ip 127.0.0.1 &> /dev/null
    
    sleep $timeout
    if kill -0 $tcpdump_pid &> /dev/null; then
        kill $tcpdump_pid
        echo -e "${RED}[失败] 未检测到伪造数据包${NC}"
        return 1
    else
        echo -e "${GREEN}[通过] 成功发送并捕获伪造数据包${NC}"
        return 0
    fi
}

# 检查网络接口权限
check_interface_permission() {
    local success=0
    for iface in $(ip link show | grep -E '^[0-9]+:' | cut -d ':' -f 2); do
        if [[ $(cat /sys/class/net/$iface/flags) -ge 0x1000 ]]; then
            echo -e "${RED}[警告] 接口 $iface 支持混杂模式${NC}"
            success=1
        fi
    done
    return $success
}

# 主检测函数
main_check() {
    check_root
    check_dependencies

    echo -e "\n${YELLOW}==== 开始IP伪造检测 ====${NC}"

    local total=0
    local passed=0

    # 检测项1：RP过滤设置
    if check_rp_filter; then
        ((passed++))
    fi
    ((total++))

    # 检测项2：实际伪造测试
    if perform_spoof_test; then
        ((passed++))
    fi
    ((total++))

    # 检测项3：接口权限检查
    if check_interface_permission; then
        ((passed++))
    fi
    ((total++))

    # 结果汇总
    echo -e "\n${YELLOW}==== 检测结果 ====${NC}"
    echo -e "总检测项: $total"
    echo -e "通过项: ${GREEN}$passed${NC}"
    echo -e "失败项: ${RED}$((total - passed))${NC}"

    if [[ $passed -eq $total ]]; then
        echo -e "${GREEN}[结论] 该服务器存在IP伪造漏洞${NC}"
    else
        echo -e "${YELLOW}[结论] 该服务器不存在IP伪造漏洞${NC}"
    fi
}

# 执行主函数
main_check