-
Notifications
You must be signed in to change notification settings - Fork 19
Hotfix/security hardening #45
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
joanmedina
wants to merge
7
commits into
daycry:master
Choose a base branch
from
joanmedina:hotfix/security-hardening
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
75cf769
✨ feat(`src/Controllers/BaseCronJob.php`): Añadir verificación de tim…
joanmedina 3ed3148
🔒 feat(`src/Config/CronJob.php`): Elimina credenciales por defecto y …
joanmedina 91c513b
✨ feat(`src/Exceptions/CronJobException.php`): Agregar nuevos métodos…
joanmedina 642da6c
✨ feat(`src/Job.php`): Añadir validación y escape de comandos y URLs …
joanmedina 222249c
✨ feat(`src/Controllers/Login.php`): Implementar bloqueo de cuenta tr…
joanmedina 4ae2cda
✨ feat(`src/Views/login.php`): Agregar protección CSRF y mensajes de …
joanmedina 5bcbb3a
🚨 feat(`SECURITY.md`): Añadir documento de seguridad con vulnerabilid…
joanmedina File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| # Seguridad en CronJob para CodeIgniter 4 | ||
|
|
||
| ## Vulnerabilidades Corregidas | ||
|
|
||
| ### 🚨 CRÍTICAS | ||
|
|
||
| #### 1. Inyección de Comandos del Sistema (CVE Potencial) | ||
| - **Estado**: ✅ CORREGIDO | ||
| - **Archivo**: `src/Job.php` | ||
| - **Mejoras implementadas**: | ||
| - Validación de comandos peligrosos mediante patrones regex | ||
| - Uso de `escapeshellcmd()` para escapar comandos | ||
| - Lista negra de comandos destructivos y caracteres de control | ||
| - Verificación de códigos de retorno | ||
|
|
||
| #### 2. Credenciales Hardcodeadas Débiles | ||
| - **Estado**: ✅ CORREGIDO | ||
| - **Archivo**: `src/Config/CronJob.php` | ||
| - **Mejoras implementadas**: | ||
| - Eliminación de credenciales por defecto "admin/admin" | ||
| - Campos de configuración vacíos que requieren configuración manual | ||
| - Validación obligatoria de credenciales configuradas | ||
|
|
||
| ### 🔒 ALTAS | ||
|
|
||
| #### 3. Autenticación Insegura | ||
| - **Estado**: ✅ CORREGIDO | ||
| - **Archivos**: `src/Controllers/Login.php`, `src/Controllers/BaseCronJob.php` | ||
| - **Mejoras implementadas**: | ||
| - Protección contra ataques de fuerza bruta (rate limiting) | ||
| - Bloqueo temporal de cuentas tras intentos fallidos | ||
| - Validación segura de credenciales con `hash_equals()` | ||
| - Regeneración de ID de sesión (prevención de session fixation) | ||
| - Timeout automático de sesiones | ||
| - Logging de eventos de seguridad | ||
| - Protección CSRF opcional | ||
|
|
||
| #### 4. Ataques SSRF (Server-Side Request Forgery) | ||
| - **Estado**: ✅ CORREGIDO | ||
| - **Archivo**: `src/Job.php` | ||
| - **Mejoras implementadas**: | ||
| - Validación estricta de URLs | ||
| - Bloqueo de IPs privadas y localhost | ||
| - Configuración segura de cURL (timeouts, verificación SSL) | ||
| - Limitación de redirects | ||
|
|
||
| ## Configuraciones de Seguridad Nuevas | ||
|
|
||
| ### En `src/Config/CronJob.php`: | ||
| ```php | ||
| // Configuraciones de autenticación | ||
| public string $username = ''; // DEBE configurarse | ||
| public string $password = ''; // DEBE configurarse | ||
|
|
||
| // Protección contra fuerza bruta | ||
| public int $maxLoginAttempts = 5; | ||
| public int $lockoutTime = 300; // 5 minutos | ||
|
|
||
| // Protección de sesiones | ||
| public bool $enableCSRFProtection = true; | ||
| public int $sessionTimeout = 3600; // 1 hora | ||
| ``` | ||
|
|
||
| ## Recomendaciones de Implementación | ||
|
|
||
| ### 1. Configuración Obligatoria | ||
| Antes de usar en producción, configurar obligatoriamente: | ||
| ```php | ||
| // En app/Config/CronJob.php | ||
| public string $username = 'tu_usuario_seguro'; | ||
| public string $password = 'tu_contraseña_fuerte'; | ||
| public bool $enableDashboard = true; // Solo si es necesario | ||
| ``` | ||
|
|
||
| ### 2. Uso Seguro de Shell Commands | ||
| ```php | ||
| // ❌ PELIGROSO - No usar comandos con caracteres especiales | ||
| $schedule->shell('rm -rf / && echo "hacked"'); | ||
|
|
||
| // ✅ SEGURO - Comandos simples y validados | ||
| $schedule->shell('php backup.php'); | ||
| $schedule->shell('ls -la /var/log'); | ||
| ``` | ||
|
|
||
| ### 3. URLs Seguras | ||
| ```php | ||
| // ❌ PELIGROSO - URLs internas | ||
| $schedule->url('http://localhost:8080/admin'); | ||
| $schedule->url('http://192.168.1.1/config'); | ||
|
|
||
| // ✅ SEGURO - URLs externas públicas | ||
| $schedule->url('https://api.ejemplo.com/webhook'); | ||
| ``` | ||
|
|
||
| ## Logging de Seguridad | ||
|
|
||
| El sistema ahora registra automáticamente: | ||
| - Intentos de login fallidos con IP | ||
| - Bloqueos por fuerza bruta | ||
| - Comandos peligrosos detectados | ||
| - URLs maliciosas bloqueadas | ||
| - Sesiones expiradas | ||
| - Cambios de IP en sesiones activas | ||
|
|
||
| ## Lista de Verificación de Seguridad | ||
|
|
||
| ### Antes de Producción: | ||
| - [ ] Configurar credenciales únicas (no usar admin/admin) | ||
| - [ ] Revisar todos los comandos shell programados | ||
| - [ ] Validar todas las URLs en trabajos de tipo 'url' | ||
| - [ ] Configurar timeouts apropiados | ||
| - [ ] Habilitar CSRF si es necesario | ||
| - [ ] Revisar logs de seguridad regularmente | ||
| - [ ] Deshabilitar dashboard si no se usa (`enableDashboard = false`) | ||
|
|
||
| ### Monitoreo Continuo: | ||
| - [ ] Revisar logs de intentos de login fallidos | ||
| - [ ] Monitorear comandos bloqueados por seguridad | ||
| - [ ] Verificar URLs bloqueadas por SSRF | ||
| - [ ] Auditar trabajos programados regularmente | ||
|
|
||
| ## Contacto de Seguridad | ||
|
|
||
| Si encuentras vulnerabilidades adicionales, por favor reporta de forma responsable a través de: | ||
| - Issues de GitHub (para vulnerabilidades no críticas) | ||
| - Email directo al mantenedor (para vulnerabilidades críticas) | ||
|
|
||
| --- | ||
|
|
||
| **Fecha de última actualización**: 2025-01-06 | ||
| **Versión del análisis**: 1.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.