diff --git a/.replit b/.replit index aa41490..095664e 100644 --- a/.replit +++ b/.replit @@ -30,6 +30,10 @@ externalPort = 3000 localPort = 45059 externalPort = 3001 +[[ports]] +localPort = 45559 +externalPort = 4200 + [env] PORT = "5000" diff --git a/MIKROTIK_API_FIX.md b/MIKROTIK_API_FIX.md index 1050107..2351910 100644 --- a/MIKROTIK_API_FIX.md +++ b/MIKROTIK_API_FIX.md @@ -2,33 +2,63 @@ ## πŸ› PROBLEMA RISOLTO -**Errore**: "All connection attempts failed" quando si tenta di bloccare IP sui router MikroTik. +**Errore**: Timeout connessione API MikroTik - router non rispondeva a richieste HTTP. -**Causa Root**: Bug nel file `python_ml/mikrotik_manager.py` - la porta API non veniva usata nella connessione HTTP. +**Causa Root**: Confusione tra **API Binary** (porta 8728) e **API REST** (porta 80/443). -### Bug Originale (Riga 36) -```python -base_url=f"http://{router_ip}" # ❌ Porta non specificata! +## πŸ” API MikroTik: Binary vs REST + +MikroTik RouterOS ha **DUE tipi di API completamente diversi**: + +| Tipo | Porta | Protocollo | RouterOS | CompatibilitΓ  | +|------|-------|------------|----------|---------------| +| **Binary API** | 8728 | Proprietario RouterOS | Tutte | ❌ Non HTTP (libreria `routeros-api`) | +| **REST API** | 80/443 | HTTP/HTTPS standard | **>= 7.1** | βœ… HTTP con `httpx` | + +**IDS usa REST API** (httpx + HTTP), quindi: +- βœ… **Porta 80** (HTTP) - **CONSIGLIATA** +- βœ… **Porta 443** (HTTPS) - Se necessario SSL +- ❌ **Porta 8728** - API Binary, NON REST (timeout) +- ❌ **Porta 8729** - API Binary SSL, NON REST (timeout) + +## βœ… SOLUZIONE + +### 1️⃣ Verifica RouterOS Versione + +```bash +# Sul router MikroTik (via Winbox/SSH) +/system resource print ``` -Il codice si connetteva sempre a: -- `http://185.203.24.2` (porta 80 HTTP standard) +**Se RouterOS >= 7.1** β†’ Usa **REST API** (porta 80/443) +**Se RouterOS < 7.1** β†’ REST API non esiste, usa API Binary -Invece di: -- `http://185.203.24.2:8728` (porta API REST MikroTik) -- `https://185.203.24.2:8729` (porta API-SSL REST MikroTik) +### 2️⃣ Configurazione Porta Corretta -### Fix Applicato -```python -protocol = "https" if use_ssl or port == 8729 else "http" -base_url=f"{protocol}://{router_ip}:{port}" # βœ… Porta corretta! +**Per RouterOS 7.14.2 (Alfabit):** + +```sql +-- Database: Usa porta 80 (REST API HTTP) +UPDATE routers SET api_port = 80 WHERE name = 'Alfabit'; ``` -Ora il codice: -1. βœ… Usa la porta configurata nel database (`api_port`) -2. βœ… Auto-rileva SSL se porta = 8729 -3. βœ… Supporta certificati self-signed (`verify=False`) -4. βœ… Include porta nella URL di connessione +**Porte disponibili**: +- **80** β†’ REST API HTTP (βœ… CONSIGLIATA) +- **443** β†’ REST API HTTPS (se SSL richiesto) +- ~~8728~~ β†’ API Binary (non compatibile) +- ~~8729~~ β†’ API Binary SSL (non compatibile) + +### 3️⃣ Test Manuale + +```bash +# Test connessione porta 80 +curl http://185.203.24.2:80/rest/system/identity \ + -u admin:password \ + --max-time 5 + +# Output atteso: +# {"name":"AlfaBit"} +``` --- @@ -45,59 +75,37 @@ psql $DATABASE_URL -c "SELECT name, ip_address, api_port, username, enabled FROM ``` name | ip_address | api_port | username | enabled --------------+---------------+----------+----------+--------- -Router Main | 185.203.24.2 | 8728 | admin | t -Router Office | 10.0.1.1 | 8729 | admin | t +Alfabit | 185.203.24.2 | 80 | admin | t ``` **Verifica**: -- βœ… `api_port` = **8728** (HTTP) o **8729** (HTTPS) +- βœ… `api_port` = **80** (REST API HTTP) - βœ… `enabled` = **true** - βœ… `username` e `password` corretti -### 2️⃣ Testa Connessione Manualmente +**Se porta errata**: +```sql +-- Cambia porta da 8728 a 80 +UPDATE routers SET api_port = 80 WHERE ip_address = '185.203.24.2'; +``` + +### 2️⃣ Testa Connessione Python ```bash # Su AlmaLinux cd /opt/ids/python_ml source venv/bin/activate -# Test connessione (sostituisci con IP/porta reali) -python3 << 'EOF' -import asyncio -from mikrotik_manager import MikroTikManager +# Test connessione automatico (usa dati dal database) +python3 test_mikrotik_connection.py +``` -async def test(): - manager = MikroTikManager() - - # Test router (SOSTITUISCI con dati reali dal database) - result = await manager.test_connection( - router_ip="185.203.24.2", - username="admin", # Dal database - password="your_password", # Dal database - port=8728 # Dal database - ) - - print(f"Connessione: {'βœ… OK' if result else '❌ FALLITA'}") - - if result: - # Test blocco IP - print("\nTest blocco IP 1.2.3.4...") - blocked = await manager.add_address_list( - router_ip="185.203.24.2", - username="admin", - password="your_password", - ip_address="1.2.3.4", - list_name="ddos_test", - comment="Test IDS API Fix", - timeout_duration="5m", - port=8728 - ) - print(f"Blocco: {'βœ… OK' if blocked else '❌ FALLITO'}") - - await manager.close_all() - -asyncio.run(test()) -EOF +**Output atteso**: +``` +βœ… Connessione OK! +βœ… Trovati X IP in lista 'ddos_blocked' +βœ… IP bloccato con successo! +βœ… IP sbloccato con successo! ``` --- @@ -159,27 +167,32 @@ curl http://localhost:8000/health ### Connessione Ancora Fallisce? -#### A. Verifica Firewall su Router +#### A. Verifica Servizio WWW su Router + +**REST API usa servizio `www` (porta 80) o `www-ssl` (porta 443)**: + ```bash -# Sul router MikroTik (via winbox/SSH) +# Sul router MikroTik (via Winbox/SSH) /ip service print -# Verifica che api o api-ssl sia enabled: -# 0 api 8728 * -# 1 api-ssl 8729 * +# Verifica che www sia enabled: +# 0 www 80 * ← REST API HTTP +# 1 www-ssl 443 * ← REST API HTTPS ``` **Fix su MikroTik**: -``` -# Abilita API REST -/ip service enable api -/ip service set api port=8728 +```bash +# Abilita servizio www per REST API +/ip service enable www +/ip service set www port=80 address=0.0.0.0/0 -# O con SSL -/ip service enable api-ssl -/ip service set api-ssl port=8729 +# O con SSL (porta 443) +/ip service enable www-ssl +/ip service set www-ssl port=443 ``` +**NOTA**: `api` (porta 8728) Γ¨ **API Binary**, NON REST! + #### B. Verifica Firewall AlmaLinux ```bash # Su AlmaLinux - consenti traffico verso router @@ -189,15 +202,20 @@ sudo firewall-cmd --reload #### C. Test Connessione Raw ```bash -# Test TCP connessione porta 8728 -telnet 185.203.24.2 8728 +# Test TCP connessione porta 80 +telnet 185.203.24.2 80 -# O con curl -curl -v http://185.203.24.2:8728/rest/system/identity \ +# Test REST API con curl +curl -v http://185.203.24.2:80/rest/system/identity \ -u admin:password \ --max-time 5 + +# Output atteso: +# {"name":"AlfaBit"} ``` +**Se timeout**: Servizio `www` non abilitato sul router + #### D. Credenziali Errate? ```sql -- Verifica credenziali nel database @@ -237,33 +255,57 @@ Dopo il deployment, verifica che: --- -## πŸ“Š PARAMETRI API CORRETTI +## πŸ“Š CONFIGURAZIONE CORRETTA -| Router Config | HTTP | HTTPS (SSL) | -|--------------|------|-------------| -| **api_port** | 8728 | 8729 | -| **Protocollo** | http | https | -| **Endpoint** | `/rest/ip/firewall/address-list` | `/rest/ip/firewall/address-list` | -| **Auth** | Basic (username:password) | Basic (username:password) | -| **Verify SSL** | N/A | False (self-signed certs) | +| Parametro | Valore (RouterOS >= 7.1) | Note | +|-----------|--------------------------|------| +| **api_port** | **80** (HTTP) o **443** (HTTPS) | βœ… REST API | +| **Servizio Router** | `www` (HTTP) o `www-ssl` (HTTPS) | Abilita su MikroTik | +| **Endpoint** | `/rest/system/identity` | Test connessione | +| **Endpoint** | `/rest/ip/firewall/address-list` | Gestione blocchi | +| **Auth** | Basic (username:password base64) | Header Authorization | +| **Verify SSL** | False | Self-signed certs OK | --- ## 🎯 RIEPILOGO -**Prima** (BUG): -``` -http://185.203.24.2/rest/... ❌ Porta 80 (HTTP standard) - FALLISCE +### ❌ ERRATO (API Binary - Timeout) +```bash +# Porta 8728 usa protocollo BINARIO, non HTTP REST +curl http://185.203.24.2:8728/rest/... +# Timeout: protocollo incompatibile ``` -**Dopo** (FIX): +### βœ… CORRETTO (API REST - Funziona) +```bash +# Porta 80 usa protocollo HTTP REST standard +curl http://185.203.24.2:80/rest/system/identity \ + -u admin:password + +# Output: {"name":"AlfaBit"} ``` -http://185.203.24.2:8728/rest/... βœ… Porta 8728 (API REST) - FUNZIONA -https://185.203.24.2:8729/rest/... βœ… Porta 8729 (API-SSL) - FUNZIONA + +**Database configurato**: +```sql +-- Router Alfabit configurato con porta 80 +SELECT name, ip_address, api_port FROM routers; +-- Alfabit | 185.203.24.2 | 80 ``` --- -**Fix applicato**: 25 Novembre 2024 -**Versione ML Backend**: 2.0.0 (Hybrid Detector) -**Test richiesto**: βœ… Connessione + Blocco IP manuale +## πŸ“ CHANGELOG + +**25 Novembre 2024**: +1. βœ… Identificato problema: porta 8728 = API Binary (non HTTP) +2. βœ… Verificato RouterOS 7.14.2 supporta REST API +3. βœ… Configurato router con porta 80 (REST API HTTP) +4. βœ… Test curl manuale: `{"name":"AlfaBit"}` βœ… +5. βœ… Router inserito in database con porta 80 + +**Test richiesto**: `python3 test_mikrotik_connection.py` + +**Versione**: IDS 2.0.0 (Hybrid Detector) +**RouterOS**: 7.14.2 (stable) +**API Type**: REST (HTTP porta 80)