<?php
/**
 * Script de Detección, Rate Limiting y Bloqueo Automático - Uniprotec
 */
if (!defined('ABSPATH') && !defined('WP_USE_THEMES')) {
    // Contexto seguro
}

$ip = $_SERVER['HTTP_CLIENT_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
$ip = filter_var($ip, FILTER_VALIDATE_IP) ? $ip : '0.0.0.0';

// Lista blanca para tu IP o servicios locales
$whitelist = array('127.0.0.1', '::1'); 
if (in_array($ip, $whitelist)) {
    return;
}

$request_uri = $_SERVER['REQUEST_URI'] ?? '';
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$request_method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

// 1. RATE LIMITING (Control de velocidad de peticiones)
$tmp_dir = sys_get_temp_dir();
$rate_file = $tmp_dir . '/rate_' . md5($ip) . '.json';
$current_time = time();
$limit_time_window = 10; // Ventana de 10 segundos
$max_requests = 35; // Máximo de peticiones permitidas en esa ventana

if (file_exists($rate_file)) {
    $rate_data = json_decode(file_get_contents($rate_file), true);
    if ($current_time - $rate_data['start'] < $limit_time_window) {
        $rate_data['count']++;
        if ($rate_data['count'] > $max_requests) {
            trigger_block($ip, "Rate Limiting Excedido ($max_requests peticiones en {$limit_time_window}s)", $request_uri);
        }
    } else {
        $rate_data = array('start' => $current_time, 'count' => 1);
    }
} else {
    $rate_data = array('start' => $current_time, 'count' => 1);
}
file_put_contents($rate_file, json_encode($rate_data));

// 2. PATRONES DE ATAQUE AVANZADOS (Base de datos, Inyecciones y Correos)
$bad_patterns = array(
    'eval\(',
    'base64_decode',
    'wp-config',
    '\.env',
    'union select',
    'concat\(',
    'information_schema',
    'auto_prepend_file',
    'etc/passwd',
    'xmlrpc.php',
    'content-type:', // Previene Email Header Injection en formularios
    'bcc:',
    'cc:'
);

$is_attacker = false;
$attack_reason = '';

foreach ($bad_patterns as $pattern) {
    if (stripos($request_uri, $pattern) !== false) {
        $is_attacker = true;
        $attack_reason = "Patrón malicioso detectado: $pattern";
        break;
    }
}

// Revisar datos enviados por POST (Protección extra para bases de datos y formularios)
if (!$is_attacker && $request_method === 'POST' && !empty($_POST)) {
    foreach ($_POST as $key => $value) {
        if (is_string($value)) {
            foreach ($bad_patterns as $pattern) {
                if (stripos($value, $pattern) !== false) {
                    $is_attacker = true;
                    $attack_reason = "Inyección maliciosa en campo POST [$key]";
                    break 2;
                }
            }
        }
    }
}

// 3. BLOQUEO DE BOTS MALICIOSOS CONOCIDOS
$bad_bots = array('sqlmap', 'nikto', 'scanner', 'masscan', 'nmap', 'zgrab', 'dirbuster', 'gobuster');
foreach ($bad_bots as $bot) {
    if (stripos($user_agent, $bot) !== false) {
        $is_attacker = true;
        $attack_reason = "Bot malicioso identificado: $bot";
        break;
    }
}

if ($is_attacker) {
    trigger_block($ip, $attack_reason, $request_uri);
}

// Función auxiliar para registrar y aplicar el bloqueo estricto
function trigger_block($ip, $reason, $uri) {
    $log_file = __DIR__ . '/attack_blocked.log';
    $log_data = date('Y-m-d H:i:s') . " - IP: $ip - Motivo: $reason - URI: $uri\n";
    file_put_contents($log_file, $log_data, FILE_APPEND);

    $htaccess_file = __DIR__ . '/.htaccess';
    $block_rule = "\n# Bloqueado por seguridad (" . $reason . ") - " . date('Y-m-d H:i:s') . "\nDeny from $ip\n";
    
    if (file_exists($htaccess_file) && is_writable($htaccess_file)) {
        $htaccess_content = file_get_contents($htaccess_file);
        if (strpos($htaccess_content, "Deny from $ip") === false) {
            file_put_contents($htaccess_file, $block_rule, FILE_APPEND);
        }
    }

    header('HTTP/1.1 403 Forbidden');
    exit('Acceso denegado por motivos de seguridad.');
}