# Fix Connessione MikroTik API ## πŸ› PROBLEMA RISOLTO **Errore**: Timeout connessione API MikroTik - router non rispondeva a richieste HTTP. **Causa Root**: Confusione tra **API Binary** (porta 8728) e **API REST** (porta 80/443). ## πŸ” 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 ``` **Se RouterOS >= 7.1** β†’ Usa **REST API** (porta 80/443) **Se RouterOS < 7.1** β†’ REST API non esiste, usa API Binary ### 2️⃣ Configurazione 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'; ``` **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"} ``` --- ## πŸ“‹ VERIFICA CONFIGURAZIONE ROUTER ### 1️⃣ Controlla Database ```sql -- Su AlmaLinux psql $DATABASE_URL -c "SELECT name, ip_address, api_port, username, enabled FROM routers WHERE enabled = true;" ``` **Output Atteso**: ``` name | ip_address | api_port | username | enabled --------------+---------------+----------+----------+--------- Alfabit | 185.203.24.2 | 80 | admin | t ``` **Verifica**: - βœ… `api_port` = **80** (REST API HTTP) - βœ… `enabled` = **true** - βœ… `username` e `password` corretti **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 automatico (usa dati dal database) python3 test_mikrotik_connection.py ``` **Output atteso**: ``` βœ… Connessione OK! βœ… Trovati X IP in lista 'ddos_blocked' βœ… IP bloccato con successo! βœ… IP sbloccato con successo! ``` --- ## πŸš€ DEPLOYMENT SU ALMALINUX ### Workflow Completo #### 1️⃣ **Su Replit** (GIΓ€ FATTO βœ…) - File `python_ml/mikrotik_manager.py` modificato - Fix giΓ  committato su Replit #### 2️⃣ **Locale - Push GitLab** ```bash # Dalla tua macchina locale (NON su Replit - Γ¨ bloccato) ./push-gitlab.sh ``` Input richiesti: ``` Commit message: Fix MikroTik API - porta non usata in base_url ``` #### 3️⃣ **Su AlmaLinux - Pull & Deploy** ```bash # SSH su ids.alfacom.it ssh root@ids.alfacom.it # Pull ultimi cambiamenti cd /opt/ids ./update_from_git.sh # Riavvia ML Backend per applicare fix sudo systemctl restart ids-ml-backend # Verifica servizio attivo systemctl status ids-ml-backend # Verifica API risponde curl http://localhost:8000/health ``` #### 4️⃣ **Test Blocco IP** ```bash # Dalla dashboard web: https://ids.alfacom.it/routers # 1. Verifica router configurati # 2. Clicca "Test Connessione" su router 185.203.24.2 # 3. Dovrebbe mostrare βœ… "Connessione OK" # Dalla dashboard detections: # 1. Seleziona detection con score >= 80 # 2. Clicca "Blocca IP" # 3. Verifica blocco su router ``` --- ## πŸ”§ TROUBLESHOOTING ### Connessione Ancora Fallisce? #### 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) /ip service print # Verifica che www sia enabled: # 0 www 80 * ← REST API HTTP # 1 www-ssl 443 * ← REST API HTTPS ``` **Fix su MikroTik**: ```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 (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 sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" destination address="185.203.24.2" port protocol="tcp" port="8728" accept' sudo firewall-cmd --reload ``` #### C. Test Connessione Raw ```bash # Test TCP connessione porta 80 telnet 185.203.24.2 80 # 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 psql $DATABASE_URL -c "SELECT name, ip_address, username FROM routers WHERE ip_address = '185.203.24.2';" -- Se password errata, aggiorna: -- UPDATE routers SET password = 'nuova_password' WHERE ip_address = '185.203.24.2'; ``` --- ## βœ… VERIFICA FINALE Dopo il deployment, verifica che: 1. **ML Backend attivo**: ```bash systemctl status ids-ml-backend # must be "active (running)" ``` 2. **API risponde**: ```bash curl http://localhost:8000/health # {"status":"healthy","database":"connected",...} ``` 3. **Auto-blocking funziona**: ```bash # Controlla log auto-blocking journalctl -u ids-auto-block.timer -n 50 ``` 4. **IP bloccati su router**: - Dashboard: https://ids.alfacom.it/detections - Filtra: "Bloccati" - Verifica badge verde "Bloccato" visibile --- ## πŸ“Š CONFIGURAZIONE CORRETTA | 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 ### ❌ ERRATO (API Binary - Timeout) ```bash # Porta 8728 usa protocollo BINARIO, non HTTP REST curl http://185.203.24.2:8728/rest/... # Timeout: protocollo incompatibile ``` ### βœ… 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"} ``` **Database configurato**: ```sql -- Router Alfabit configurato con porta 80 SELECT name, ip_address, api_port FROM routers; -- Alfabit | 185.203.24.2 | 80 ``` --- ## πŸ“ 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)