# Fix Connessione MikroTik API ## ๐Ÿ› PROBLEMA RISOLTO **Errore**: "All connection attempts failed" quando si tenta di bloccare IP sui router MikroTik. **Causa Root**: Bug nel file `python_ml/mikrotik_manager.py` - la porta API non veniva usata nella connessione HTTP. ### Bug Originale (Riga 36) ```python base_url=f"http://{router_ip}" # โŒ Porta non specificata! ``` Il codice si connetteva sempre a: - `http://185.203.24.2` (porta 80 HTTP standard) Invece di: - `http://185.203.24.2:8728` (porta API REST MikroTik) - `https://185.203.24.2:8729` (porta API-SSL REST MikroTik) ### Fix Applicato ```python protocol = "https" if use_ssl or port == 8729 else "http" base_url=f"{protocol}://{router_ip}:{port}" # โœ… Porta corretta! ``` 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 --- ## ๐Ÿ“‹ 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 --------------+---------------+----------+----------+--------- Router Main | 185.203.24.2 | 8728 | admin | t Router Office | 10.0.1.1 | 8729 | admin | t ``` **Verifica**: - โœ… `api_port` = **8728** (HTTP) o **8729** (HTTPS) - โœ… `enabled` = **true** - โœ… `username` e `password` corretti ### 2๏ธโƒฃ Testa Connessione Manualmente ```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 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 ``` --- ## ๐Ÿš€ 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 Firewall su Router ```bash # Sul router MikroTik (via winbox/SSH) /ip service print # Verifica che api o api-ssl sia enabled: # 0 api 8728 * # 1 api-ssl 8729 * ``` **Fix su MikroTik**: ``` # Abilita API REST /ip service enable api /ip service set api port=8728 # O con SSL /ip service enable api-ssl /ip service set api-ssl port=8729 ``` #### 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 8728 telnet 185.203.24.2 8728 # O con curl curl -v http://185.203.24.2:8728/rest/system/identity \ -u admin:password \ --max-time 5 ``` #### 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 --- ## ๐Ÿ“Š PARAMETRI API CORRETTI | 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) | --- ## ๐ŸŽฏ RIEPILOGO **Prima** (BUG): ``` http://185.203.24.2/rest/... โŒ Porta 80 (HTTP standard) - FALLISCE ``` **Dopo** (FIX): ``` http://185.203.24.2:8728/rest/... โœ… Porta 8728 (API REST) - FUNZIONA https://185.203.24.2:8729/rest/... โœ… Porta 8729 (API-SSL) - FUNZIONA ``` --- **Fix applicato**: 25 Novembre 2024 **Versione ML Backend**: 2.0.0 (Hybrid Detector) **Test richiesto**: โœ… Connessione + Blocco IP manuale