Skip to content

Hotfix/security hardening#45

Open
joanmedina wants to merge 7 commits into
daycry:masterfrom
joanmedina:hotfix/security-hardening
Open

Hotfix/security hardening#45
joanmedina wants to merge 7 commits into
daycry:masterfrom
joanmedina:hotfix/security-hardening

Conversation

@joanmedina
Copy link
Copy Markdown

🛠️ Pull Request: Hotfix/security-hardening

SECURITY PATCH

🛡️ Corrección de vulnerabilidades críticas y refuerzo de seguridad

Este pull request aplica una serie de mejoras destinadas a eliminar vectores de ataque críticos y reforzar el uso seguro del sistema CronJob para CodeIgniter 4.


✅ Vulnerabilidades corregidas

1. Inyección de comandos del sistema

  • Validación estricta de comandos mediante expresiones regulares
  • Uso de escapeshellcmd() y lista negra de comandos peligrosos
  • Verificación de códigos de salida para asegurar integridad

2. Credenciales por defecto eliminadas

  • Eliminación de admin/admin por defecto
  • Validación obligatoria de usuario y contraseña antes de habilitar el dashboard

3. Autenticación insegura

  • Protección contra fuerza bruta
  • Validación segura con hash_equals()
  • Regeneración de sesión y timeout configurable

4. Protección ante ataques SSRF

  • Bloqueo de IPs privadas y rangos internos
  • Validación segura de URLs externas

🔧 Nuevas configuraciones de seguridad

En src/Config/CronJob.php se añaden opciones para:

  • Limitar intentos de login
  • Configurar duración de sesiones
  • Activar protección CSRF

📝 Recomendaciones de uso en producción

  • Configurar credenciales antes de desplegar
  • Validar comandos shell y URLs externas
  • Revisar logs de seguridad de forma periódica
  • Deshabilitar el dashboard si no es necesario

📄 Registro de seguridad

El sistema ahora registra:

  • Intentos de login fallidos y bloqueos
  • Comandos sospechosos
  • URLs peligrosas
  • Cambios en sesiones activas

Fecha de implementación: 2025-01-06
Autor: Joan Medina

Copilot AI review requested due to automatic review settings July 6, 2025 07:56
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This hotfix strengthens the security of the CronJob module by patching shell‐injection and SSRF vectors, removing default credentials, and bolstering login/session protections.

  • Added CSRF protection and tightened input constraints in the login view
  • Hardened shell command execution and URL requests in Job.php
  • Implemented brute-force protection, secure session handling, and session expiry in controllers

Reviewed Changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/Views/login.php Added CSRF field, error alerts, and required/maxlength on inputs
src/Job.php Validates & escapes shell commands, enforces URL checks, throws exceptions
src/Exceptions/CronJobException.php New exception factories for invalid command/url and failures
src/Controllers/Login.php Rate limiting, lockouts, secure credential checks, CSRF validation
src/Controllers/BaseCronJob.php Session timeout and optional IP-change detection
src/Config/CronJob.php Removed hardcoded creds, added security config options
SECURITY.md Documented vulnerabilities fixed and recommended production setup
Comments suppressed due to low confidence (2)

src/Views/login.php:30

  • The label’s for="floatingInput" doesn’t match any input id. Add an id="floatingInput" to this input for proper label association.
                <input type="text" class="form-control" name="username" placeholder="Username" required maxlength="100">

src/Job.php:264

  • The square brackets inside this character class are not escaped properly and may break the regex. Use \[ and \] to escape them.
            '/[;&|`$(){}[\]<>]/',  // Caracteres de control de shell

Comment thread src/Job.php
Comment on lines +262 to +275
// Lista de comandos/caracteres peligrosos
$dangerousPatterns = [
'/[;&|`$(){}[\]<>]/', // Caracteres de control de shell
'/\b(rm|del|format|fdisk|mkfs)\b/i', // Comandos destructivos
'/\b(wget|curl|nc|netcat)\b.*http/i', // Comandos de red sospechosos
];

foreach ($dangerousPatterns as $pattern) {
if (preg_match($pattern, $command)) {
return false;
}
}

return true;
Copy link

Copilot AI Jul 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Relying on a blacklist of dangerous patterns can be bypassed. Consider switching to a whitelist of explicitly allowed commands or syntax for stronger protection.

Suggested change
// Lista de comandos/caracteres peligrosos
$dangerousPatterns = [
'/[;&|`$(){}[\]<>]/', // Caracteres de control de shell
'/\b(rm|del|format|fdisk|mkfs)\b/i', // Comandos destructivos
'/\b(wget|curl|nc|netcat)\b.*http/i', // Comandos de red sospechosos
];
foreach ($dangerousPatterns as $pattern) {
if (preg_match($pattern, $command)) {
return false;
}
}
return true;
// Lista de comandos explícitamente permitidos
$allowedCommands = [
'ls', 'pwd', 'whoami', 'date', 'uptime', // Comandos básicos
'echo', 'cat', 'head', 'tail', 'grep', // Comandos de manipulación de texto
];
// Verificar si el comando coincide exactamente con uno de los permitidos
return in_array($command, $allowedCommands, true);

Copilot uses AI. Check for mistakes.
Comment thread src/Job.php
return $response->getBody();
// Resolver IP del host
$host = $parsedUrl['host'] ?? '';
$ip = gethostbyname($host);
Copy link

Copilot AI Jul 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using gethostbyname can return the input string on resolution failure, potentially allowing SSRF. Use dns_get_record or similar to verify valid IP resolution and handle failures.

Suggested change
$ip = gethostbyname($host);
$dnsRecords = dns_get_record($host, DNS_A + DNS_AAAA);
if (!$dnsRecords) {
return false; // Hostname could not be resolved
}
$ip = $dnsRecords[0]['ip'] ?? '';

Copilot uses AI. Check for mistakes.
Comment on lines +26 to +28
return new self("Comando peligroso detectado: {$command}. Contiene caracteres o comandos no permitidos.");
}

Copy link

Copilot AI Jul 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Embedding raw commands in exception messages may leak sensitive data in logs. Consider sanitizing or redacting parts of the command before including it in the error.

Suggested change
return new self("Comando peligroso detectado: {$command}. Contiene caracteres o comandos no permitidos.");
}
$sanitizedCommand = self::sanitizeCommand($command);
return new self("Comando peligroso detectado: {$sanitizedCommand}. Contiene caracteres o comandos no permitidos.");
}
private static function sanitizeCommand(string $command): string
{
// Redact sensitive data or sanitize the command
return preg_replace('/(--password[= ]\S+|--key[= ]\S+)/i', '--REDACTED', $command);
}

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants