Security fix
This commit is contained in:
@@ -0,0 +1,41 @@
|
|||||||
|
# Modifiche di sicurezza e correzioni / Security fixes & changes
|
||||||
|
|
||||||
|
Tutte le modifiche mantengono il comportamento precedente **per default**; ciò che cambia
|
||||||
|
visibilmente è indicato esplicitamente. / Every change keeps the previous behaviour **by default**;
|
||||||
|
visible differences are listed explicitly.
|
||||||
|
|
||||||
|
## Correzioni attive subito / Active immediately
|
||||||
|
|
||||||
|
| # | Modifica | Effetto visibile |
|
||||||
|
|---|----------|------------------|
|
||||||
|
| 1 | **Scheduler**: i profili/comandi vengono validati come in `/api/command`. `REBOOT`, `RESET_HAT`, `UPDATE_AGENT` possono essere schedulati solo da un `admin` (controllo al salvataggio **e** all'esecuzione). I nodi target vengono validati. | Un `node_admin` non può più programmare comandi riservati agli admin. Schedulazioni già presenti create da non-admin con quei comandi non vengono più eseguite (warning nel log). |
|
||||||
|
| 2 | **WebSocket `live_log_<nodo>`**: inviato solo ai socket con sessione valida **e** autorizzati su quel nodo (ruolo/`allowed_nodes` rivalidati ogni 2 min). | Nessuno per l'uso normale: la console log già richiedeva il login via `/api/logs/<nodo>`. Chi non è loggato non riceve più i log in diretta. |
|
||||||
|
| 3 | **Rate limit login dietro reverse proxy**: se la richiesta arriva da loopback con `X-Forwarded-For`, si usa l'IP reale (ultimo valore, aggiunto dal proxy). Con `trust_proxy: true` il comportamento è invariato. | Un utente che sbaglia la password non blocca più il login a tutti gli altri. |
|
||||||
|
| 4 | **Scheduler su thread dedicato**: non è più ritardato dal download degli ID DMR/NXDN. | Le schedulazioni partono puntuali anche durante i download. |
|
||||||
|
| 5 | **Pruning**: `telemetry_logs` (default 90 giorni) e `config_backups` (ultimi 100 per nodo/servizio) ora vengono potati. | Dati più vecchi di quelle soglie vengono eliminati; configurabile (0 = disattiva). |
|
||||||
|
| 6 | `save_to_sqlite` chiude sempre la connessione; `__main__` usa `web.port`; emoji corrotta nel log; `test-push.py` funzionante; nomi file in `install.txt` corretti; `chart.js` fissato alla versione 4.4.1. | Nessuno. |
|
||||||
|
|
||||||
|
## Opzioni nuove (tutte disattivate / invariate di default) / New opt-in options
|
||||||
|
|
||||||
|
Nel blocco `web` di `config.json` (vedi `config.json.example`):
|
||||||
|
|
||||||
|
* `require_login_for_read: true` – richiede il login per `/api/states`, `/api/logs`, `/api/stats`, `/api/clients` e limita `aprs_msg` ai soli utenti loggati. **Attenzione:** la vista pubblica della dashboard resterà vuota finché non si fa il login.
|
||||||
|
* `cors_origins: "https://tuo.dominio"` – restringe le origini ammesse per Socket.IO (default `"*"`, invariato).
|
||||||
|
* `ota_enabled: false` – disabilita l'aggiornamento OTA da interfaccia (`git pull` + riavvio).
|
||||||
|
* `trust_proxy`, `cookie_secure` (consigliato `true` dietro HTTPS), `session_hours`.
|
||||||
|
|
||||||
|
Nel blocco `mqtt`: `"tls": true` (+ `"ca_certs"`, porta tipicamente 8883) per cifrare la connessione al broker.
|
||||||
|
Altre chiavi: `telemetry_retention_days`, `config_backups_keep`.
|
||||||
|
|
||||||
|
## Non modificato di proposito / Deliberately left as is
|
||||||
|
|
||||||
|
* **Servizio come root e bind su 0.0.0.0**: cambiarlo di default romperebbe le installazioni esistenti
|
||||||
|
(permessi su cartella/log, accesso diretto alla porta 9000). È incluso
|
||||||
|
`systemd/fleet-console.hardened.service.example` con utente dedicato e hardening, da adottare quando vuoi.
|
||||||
|
* **CSP e SRI**: la UI usa molti stili e handler inline, quindi una CSP rigida la romperebbe; l'SRI richiede
|
||||||
|
gli hash delle librerie (calcolabili con `curl -s URL | openssl dgst -sha384 -binary | openssl base64 -A`).
|
||||||
|
* **Broker MQTT**: l'autenticazione dei messaggi e le ACL per nodo si configurano sul broker (es. Mosquitto
|
||||||
|
`acl_file`), non nel server.
|
||||||
|
* **Backup di config in chiaro**: i file `.ini` salvati in `config_backups` possono contenere password di rete.
|
||||||
|
Proteggere `monitor.db` con permessi `600`.
|
||||||
|
* **Schedulazioni sovrapposte** sugli stessi nodi e ripristino del "profilo precedente": non gestiti.
|
||||||
@@ -4,7 +4,9 @@ gevent.monkey.patch_all()
|
|||||||
import os
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import threading
|
import threading
|
||||||
from flask import Flask, render_template, request
|
import time
|
||||||
|
from contextlib import closing
|
||||||
|
from flask import Flask, render_template, request, jsonify
|
||||||
from flask_socketio import emit
|
from flask_socketio import emit
|
||||||
|
|
||||||
# --- IMPORT MODULI CORE ---
|
# --- IMPORT MODULI CORE ---
|
||||||
@@ -15,11 +17,12 @@ import core.state as state
|
|||||||
# --- IMPORT SERVIZI ---
|
# --- IMPORT SERVIZI ---
|
||||||
from services.push_service import push_worker
|
from services.push_service import push_worker
|
||||||
from services.watchdog_service import watchdog_loop
|
from services.watchdog_service import watchdog_loop
|
||||||
from services.scheduler_service import auto_update_ids
|
from services.scheduler_service import auto_update_ids, schedule_loop
|
||||||
import services.mqtt_service as mqtt_svc
|
import services.mqtt_service as mqtt_svc
|
||||||
|
|
||||||
# --- IMPORT ROTTE / BLUEPRINTS ---
|
# --- IMPORT ROTTE / BLUEPRINTS ---
|
||||||
from routes.auth_routes import auth_bp
|
from routes.auth_routes import auth_bp, get_auth
|
||||||
|
from core.database import db_connect
|
||||||
from routes.api_routes import api_bp
|
from routes.api_routes import api_bp
|
||||||
|
|
||||||
# Inizializzazione Flask
|
# Inizializzazione Flask
|
||||||
@@ -52,6 +55,17 @@ def add_security_headers(resp):
|
|||||||
resp.headers['Cache-Control'] = 'no-store'
|
resp.headers['Cache-Control'] = 'no-store'
|
||||||
return resp
|
return resp
|
||||||
|
|
||||||
|
# Se in config.json -> "web": {"require_login_for_read": true} le API di sola lettura richiedono il login.
|
||||||
|
# Default: disattivato (la dashboard pubblica funziona come prima).
|
||||||
|
READ_PROTECTED_PATHS = ('/api/states', '/api/logs', '/api/stats', '/api/clients')
|
||||||
|
|
||||||
|
@app.before_request
|
||||||
|
def enforce_read_login():
|
||||||
|
if web_cfg.get('require_login_for_read') and request.path in READ_PROTECTED_PATHS:
|
||||||
|
if not get_auth():
|
||||||
|
return jsonify({"success": False, "error": "Login richiesto"}), 401
|
||||||
|
return None
|
||||||
|
|
||||||
def get_git_commit():
|
def get_git_commit():
|
||||||
try:
|
try:
|
||||||
return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], cwd=BASE_DIR).decode('utf-8').strip()
|
return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], cwd=BASE_DIR).decode('utf-8').strip()
|
||||||
@@ -64,16 +78,18 @@ SERVER_COMMIT = get_git_commit()
|
|||||||
def index():
|
def index():
|
||||||
return render_template('index.html', git_commit=SERVER_COMMIT)
|
return render_template('index.html', git_commit=SERVER_COMMIT)
|
||||||
|
|
||||||
from flask import session
|
|
||||||
|
|
||||||
@state.socketio.on('connect')
|
@state.socketio.on('connect')
|
||||||
def handle_connect():
|
def handle_connect():
|
||||||
state.connected_web_clients.add(request.sid)
|
state.connected_web_clients.add(request.sid)
|
||||||
|
|
||||||
# Se l'utente è loggato (session), associamo il suo username al SID
|
# Se l'utente è loggato (session), associamo il suo username al SID
|
||||||
user = session.get('user')
|
auth = get_auth()
|
||||||
if user:
|
if auth:
|
||||||
state.active_logged_users[request.sid] = user
|
state.active_logged_users[request.sid] = auth['username']
|
||||||
|
state.socket_auth[request.sid] = {
|
||||||
|
"username": auth['username'], "role": auth['role'],
|
||||||
|
"allowed_nodes": auth['allowed_nodes'], "ts": time.time()
|
||||||
|
}
|
||||||
|
|
||||||
emit('mqtt_status', {'connected': mqtt_svc.mqtt_connected_status})
|
emit('mqtt_status', {'connected': mqtt_svc.mqtt_connected_status})
|
||||||
|
|
||||||
@@ -85,21 +101,37 @@ def handle_connect():
|
|||||||
def handle_disconnect():
|
def handle_disconnect():
|
||||||
state.connected_web_clients.discard(request.sid)
|
state.connected_web_clients.discard(request.sid)
|
||||||
state.active_logged_users.pop(request.sid, None)
|
state.active_logged_users.pop(request.sid, None)
|
||||||
|
state.socket_auth.pop(request.sid, None)
|
||||||
|
|
||||||
logged_names = list(set(state.active_logged_users.values()))
|
logged_names = list(set(state.active_logged_users.values()))
|
||||||
state.socketio.emit('web_users_count', {'count': len(state.connected_web_clients), 'users': logged_names})
|
state.socketio.emit('web_users_count', {'count': len(state.connected_web_clients), 'users': logged_names})
|
||||||
|
|
||||||
|
def _lookup_auth(username):
|
||||||
|
"""Ruolo/nodi aggiornati di un utente (usato per rivalidare i socket gia' connessi)."""
|
||||||
|
try:
|
||||||
|
with closing(db_connect(row=True)) as conn:
|
||||||
|
row = conn.execute("SELECT role, allowed_nodes FROM users WHERE username = ?", (username,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return {"role": row['role'], "allowed_nodes": row['allowed_nodes'] or ''}
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"lookup auth socket: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
state.auth_lookup = _lookup_auth
|
||||||
|
|
||||||
# --- INIZIALIZZAZIONE SISTEMA & THREAD ---
|
# --- INIZIALIZZAZIONE SISTEMA & THREAD ---
|
||||||
init_db()
|
init_db()
|
||||||
state.seed_last_seen()
|
state.seed_last_seen()
|
||||||
mqtt_svc.start_mqtt()
|
mqtt_svc.start_mqtt()
|
||||||
|
|
||||||
threading.Thread(target=auto_update_ids, daemon=True).start()
|
threading.Thread(target=auto_update_ids, daemon=True).start()
|
||||||
|
threading.Thread(target=schedule_loop, daemon=True).start()
|
||||||
threading.Thread(target=push_worker, daemon=True).start()
|
threading.Thread(target=push_worker, daemon=True).start()
|
||||||
threading.Thread(target=watchdog_loop, daemon=True).start()
|
threading.Thread(target=watchdog_loop, daemon=True).start()
|
||||||
|
|
||||||
logger.info(f"🚀 Fleet Control Console modulare pronta (Git Rev: {SERVER_COMMIT})")
|
logger.info(f"🚀 Fleet Control Console modulare pronta (Git Rev: {SERVER_COMMIT})")
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
port = int(config.get('web', {}).get('port', 9000)) if 'config' in locals() else 9000
|
port = int(web_cfg.get('port', 9000))
|
||||||
state.socketio.run(app, host='0.0.0.0', port=port)
|
state.socketio.run(app, host='0.0.0.0', port=port)
|
||||||
|
|||||||
+16
-2
@@ -17,7 +17,8 @@
|
|||||||
"devices/#",
|
"devices/#",
|
||||||
"data/#",
|
"data/#",
|
||||||
"aprs-gateway/aprs"
|
"aprs-gateway/aprs"
|
||||||
]
|
],
|
||||||
|
"tls": false
|
||||||
},
|
},
|
||||||
"web_admin": {
|
"web_admin": {
|
||||||
"default_user": "admin",
|
"default_user": "admin",
|
||||||
@@ -41,5 +42,18 @@
|
|||||||
},
|
},
|
||||||
"log_max_mb": 50,
|
"log_max_mb": 50,
|
||||||
"log_backup_count": 10,
|
"log_backup_count": 10,
|
||||||
"last_heard_limit": 60
|
"last_heard_limit": 60,
|
||||||
|
"web": {
|
||||||
|
"port": 9000,
|
||||||
|
"cookie_secure": false,
|
||||||
|
"session_hours": 12,
|
||||||
|
"trust_proxy": false,
|
||||||
|
"cors_origins": "*",
|
||||||
|
"require_login_for_read": false,
|
||||||
|
"ota_enabled": true
|
||||||
|
},
|
||||||
|
"retention_days": 90,
|
||||||
|
"audit_retention_days": 365,
|
||||||
|
"telemetry_retention_days": 90,
|
||||||
|
"config_backups_keep": 100
|
||||||
}
|
}
|
||||||
|
|||||||
+23
-4
@@ -95,6 +95,13 @@ def init_db():
|
|||||||
|
|
||||||
def save_to_sqlite(client_id, data, protocol="DMR"):
|
def save_to_sqlite(client_id, data, protocol="DMR"):
|
||||||
conn = sqlite3.connect(DB_PATH, timeout=10)
|
conn = sqlite3.connect(DB_PATH, timeout=10)
|
||||||
|
try:
|
||||||
|
_save_to_sqlite(conn, client_id, data, protocol)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
notify_update('log_aggiornato')
|
||||||
|
|
||||||
|
def _save_to_sqlite(conn, client_id, data, protocol):
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
|
|
||||||
rssi_val = 0
|
rssi_val = 0
|
||||||
@@ -110,8 +117,6 @@ def save_to_sqlite(client_id, data, protocol="DMR"):
|
|||||||
data.get('slot', 0), round(data.get('duration', 0), 1), round(data.get('ber', 0), 2),
|
data.get('slot', 0), round(data.get('duration', 0), 1), round(data.get('ber', 0), 2),
|
||||||
str(data.get('src_ext', '')), rssi_val, str(data.get('source', '')), str(data.get('mode', ''))))
|
str(data.get('src_ext', '')), rssi_val, str(data.get('source', '')), str(data.get('mode', ''))))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
|
||||||
notify_update('log_aggiornato')
|
|
||||||
|
|
||||||
def audit(username, client_id, command):
|
def audit(username, client_id, command):
|
||||||
try:
|
try:
|
||||||
@@ -133,9 +138,23 @@ def prune_old_data():
|
|||||||
n1 = c.rowcount
|
n1 = c.rowcount
|
||||||
c.execute("DELETE FROM audit_logs WHERE timestamp < datetime('now', 'localtime', ?)", (f"-{audit_days} days",))
|
c.execute("DELETE FROM audit_logs WHERE timestamp < datetime('now', 'localtime', ?)", (f"-{audit_days} days",))
|
||||||
n2 = c.rowcount
|
n2 = c.rowcount
|
||||||
|
# Telemetria e backup config non venivano mai potati (default generosi, configurabili)
|
||||||
|
tele_days = int(cfg.get("telemetry_retention_days", 90))
|
||||||
|
n3 = 0
|
||||||
|
if tele_days > 0:
|
||||||
|
c.execute("DELETE FROM telemetry_logs WHERE timestamp < datetime('now', 'localtime', ?)", (f"-{tele_days} days",))
|
||||||
|
n3 = c.rowcount
|
||||||
|
keep = int(cfg.get("config_backups_keep", 100))
|
||||||
|
n4 = 0
|
||||||
|
if keep > 0:
|
||||||
|
c.execute("""DELETE FROM config_backups WHERE id NOT IN (
|
||||||
|
SELECT id FROM config_backups b
|
||||||
|
WHERE b.client_id = config_backups.client_id AND b.service = config_backups.service
|
||||||
|
ORDER BY id DESC LIMIT ?)""", (keep,))
|
||||||
|
n4 = c.rowcount
|
||||||
conn.commit()
|
conn.commit()
|
||||||
if n1 or n2:
|
if n1 or n2 or n3 or n4:
|
||||||
logger.info(f"🧹 Pulizia DB: {n1} ascolti e {n2} audit rimossi.")
|
logger.info(f"🧹 Pulizia DB: {n1} ascolti, {n2} audit, {n3} telemetrie e {n4} backup config rimossi.")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"❌ Errore pulizia DB: {e}")
|
logger.error(f"❌ Errore pulizia DB: {e}")
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
"""Controllo permessi sui nodi, condiviso da API, push e WebSocket (nessuna dipendenza interna)."""
|
||||||
|
|
||||||
|
|
||||||
|
def node_allowed(role, allowed_nodes, cid):
|
||||||
|
if role == 'admin':
|
||||||
|
return True
|
||||||
|
allowed = (allowed_nodes or '').strip().lower()
|
||||||
|
if allowed == 'all':
|
||||||
|
return True
|
||||||
|
return cid in [x.strip().lower() for x in allowed.split(',') if x.strip()]
|
||||||
@@ -6,6 +6,7 @@ import sqlite3
|
|||||||
from contextlib import closing
|
from contextlib import closing
|
||||||
from flask_socketio import SocketIO
|
from flask_socketio import SocketIO
|
||||||
from core.config import CACHE_FILE, DB_PATH, DMR_IDS_PATH, NXDN_IDS_PATH, logger, web_cfg
|
from core.config import CACHE_FILE, DB_PATH, DMR_IDS_PATH, NXDN_IDS_PATH, logger, web_cfg
|
||||||
|
from core.permissions import node_allowed
|
||||||
|
|
||||||
# --- WEBSOCKET SOCKETIO ---
|
# --- WEBSOCKET SOCKETIO ---
|
||||||
socketio = SocketIO(cors_allowed_origins=web_cfg.get('cors_origins', '*'))
|
socketio = SocketIO(cors_allowed_origins=web_cfg.get('cors_origins', '*'))
|
||||||
@@ -51,6 +52,35 @@ operating_modes = {}
|
|||||||
node_logs = {} # In-memory circular buffer for live logs
|
node_logs = {} # In-memory circular buffer for live logs
|
||||||
connected_web_clients = set()
|
connected_web_clients = set()
|
||||||
active_logged_users = {}
|
active_logged_users = {}
|
||||||
|
socket_auth = {} # sid -> {"username","role","allowed_nodes","ts"} (solo socket con sessione valida)
|
||||||
|
auth_lookup = None # impostato da app.py: username -> dict auth aggiornato oppure None
|
||||||
|
|
||||||
|
AUTH_REFRESH_SEC = 120
|
||||||
|
|
||||||
|
def emit_to_authorized(event, data, cid=None):
|
||||||
|
"""Invia l'evento solo ai socket autenticati (e, se cid e' dato, autorizzati su quel nodo)."""
|
||||||
|
now = time.time()
|
||||||
|
for sid, a in list(socket_auth.items()):
|
||||||
|
try:
|
||||||
|
# Rilegge periodicamente ruolo/nodi: utenti rimossi o declassati perdono l'accesso live
|
||||||
|
if auth_lookup and now - a.get('ts', 0) > AUTH_REFRESH_SEC:
|
||||||
|
fresh = auth_lookup(a['username'])
|
||||||
|
if not fresh:
|
||||||
|
socket_auth.pop(sid, None)
|
||||||
|
continue
|
||||||
|
a.update(fresh)
|
||||||
|
a['ts'] = now
|
||||||
|
if cid is None or node_allowed(a.get('role'), a.get('allowed_nodes'), cid):
|
||||||
|
socketio.emit(event, data, to=sid)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"emit_to_authorized '{event}': {e}")
|
||||||
|
|
||||||
|
def emit_aprs(data):
|
||||||
|
"""APRS live: broadcast come prima, oppure solo utenti loggati se web.require_login_for_read."""
|
||||||
|
if web_cfg.get('require_login_for_read'):
|
||||||
|
emit_to_authorized('aprs_msg', data)
|
||||||
|
else:
|
||||||
|
socketio.emit('aprs_msg', data)
|
||||||
|
|
||||||
# Caricamento iniziale cache telemetria
|
# Caricamento iniziale cache telemetria
|
||||||
if os.path.exists(CACHE_FILE):
|
if os.path.exists(CACHE_FILE):
|
||||||
|
|||||||
+4
-4
@@ -36,7 +36,7 @@ Install project requirements:
|
|||||||
The server handles the web interface and user permissions.
|
The server handles the web interface and user permissions.
|
||||||
|
|
||||||
Steps:
|
Steps:
|
||||||
1. Configure 'config.json' using 'config.example.json'.
|
1. Configure 'config.json' using 'config.json.example'.
|
||||||
2. Enter MQTT credentials and VAPID keys.
|
2. Enter MQTT credentials and VAPID keys.
|
||||||
3. Define repeaters in the 'clients.json' file.
|
3. Define repeaters in the 'clients.json' file.
|
||||||
4. Install production WSGI server packages (if not in requirements):
|
4. Install production WSGI server packages (if not in requirements):
|
||||||
@@ -59,7 +59,7 @@ They will NOT work over standard HTTP.
|
|||||||
4. RUNNING AS A SERVICE (SYSTEMD)
|
4. RUNNING AS A SERVICE (SYSTEMD)
|
||||||
------------------------------------------------------------
|
------------------------------------------------------------
|
||||||
⚠️ IMPORTANT (VENV USERS): Before copying the service file,
|
⚠️ IMPORTANT (VENV USERS): Before copying the service file,
|
||||||
open 'fleet-control.service' and ensure the paths point to your
|
open 'fleet-console.service' and ensure the paths point to your
|
||||||
virtual environment.
|
virtual environment.
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
@@ -110,7 +110,7 @@ Installa i requisiti del progetto:
|
|||||||
2. SETUP DEL SERVER
|
2. SETUP DEL SERVER
|
||||||
------------------------------------------------------------
|
------------------------------------------------------------
|
||||||
Passaggi:
|
Passaggi:
|
||||||
1. Configura 'config.json' partendo da 'config.example.json'.
|
1. Configura 'config.json' partendo da 'config.json.example'.
|
||||||
2. Inserisci credenziali MQTT e chiavi VAPID.
|
2. Inserisci credenziali MQTT e chiavi VAPID.
|
||||||
3. Definisci i ripetitori in 'clients.json'.
|
3. Definisci i ripetitori in 'clients.json'.
|
||||||
4. Avvia il server di produzione:
|
4. Avvia il server di produzione:
|
||||||
@@ -128,7 +128,7 @@ Passaggi:
|
|||||||
4. ESECUZIONE COME SERVIZIO (SYSTEMD)
|
4. ESECUZIONE COME SERVIZIO (SYSTEMD)
|
||||||
------------------------------------------------------------
|
------------------------------------------------------------
|
||||||
⚠️ IMPORTANTE (PER UTENTI VENV): Prima di copiare il file di
|
⚠️ IMPORTANTE (PER UTENTI VENV): Prima di copiare il file di
|
||||||
servizio, apri 'fleet-control.service' e assicurati che i percorsi
|
servizio, apri 'fleet-console.service' e assicurati che i percorsi
|
||||||
puntino al tuo ambiente virtuale!
|
puntino al tuo ambiente virtuale!
|
||||||
|
|
||||||
Esempio:
|
Esempio:
|
||||||
|
|||||||
+24
-4
@@ -14,6 +14,7 @@ import core.state as state
|
|||||||
from services.mqtt_service import mqtt_publish
|
from services.mqtt_service import mqtt_publish
|
||||||
from services.push_service import node_allowed
|
from services.push_service import node_allowed
|
||||||
from routes.auth_routes import get_auth, json_body, err
|
from routes.auth_routes import get_auth, json_body, err
|
||||||
|
from services.scheduler_service import PRIVILEGED_COMMANDS as SCHED_PRIVILEGED
|
||||||
|
|
||||||
# --- AGGIUNTE PER GITEA BACKGROUND CHECK ---
|
# --- AGGIUNTE PER GITEA BACKGROUND CHECK ---
|
||||||
GLOBAL_SERVER_UPDATE_AVAILABLE = False
|
GLOBAL_SERVER_UPDATE_AVAILABLE = False
|
||||||
@@ -254,7 +255,7 @@ def update_nodes():
|
|||||||
return err("Non autorizzato", 403)
|
return err("Non autorizzato", 403)
|
||||||
if not mqtt_publish("devices/control/request", "update"):
|
if not mqtt_publish("devices/control/request", "update"):
|
||||||
return err("Broker MQTT non raggiungibile", 503)
|
return err("Broker MQTT non raggiungibile", 503)
|
||||||
logger.info(f"討 REQ CONFIG inviata a tutta la flotta da {auth['username']}")
|
logger.info(f"🔄 REQ CONFIG inviata a tutta la flotta da {auth['username']}")
|
||||||
audit(auth['username'], '*', 'REQ_CONFIG_ALL')
|
audit(auth['username'], '*', 'REQ_CONFIG_ALL')
|
||||||
return jsonify({"success": True})
|
return jsonify({"success": True})
|
||||||
|
|
||||||
@@ -411,6 +412,8 @@ def apply_server_update():
|
|||||||
auth = get_auth()
|
auth = get_auth()
|
||||||
if not auth or auth['role'] != 'admin':
|
if not auth or auth['role'] != 'admin':
|
||||||
return err("Non autorizzato", 403)
|
return err("Non autorizzato", 403)
|
||||||
|
if read_config().get('web', {}).get('ota_enabled', True) is False:
|
||||||
|
return err("Aggiornamento OTA disabilitato dalla configurazione", 403)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
audit(auth['username'], 'SERVER', 'SERVER_OTA_UPDATE')
|
audit(auth['username'], 'SERVER', 'SERVER_OTA_UPDATE')
|
||||||
@@ -660,6 +663,22 @@ def add_schedule():
|
|||||||
if not start_time or not end_time:
|
if not start_time or not end_time:
|
||||||
return err("Date di inizio e fine obbligatorie")
|
return err("Date di inizio e fine obbligatorie")
|
||||||
|
|
||||||
|
# Validazione profili: stessa logica di /api/command (i comandi privilegiati solo per admin)
|
||||||
|
profiles_to_check = [target_profile] + ([restore_profile] if restore_profile != 'NONE' else [])
|
||||||
|
for prof in profiles_to_check:
|
||||||
|
if prof in SCHED_PRIVILEGED:
|
||||||
|
if auth['role'] != 'admin':
|
||||||
|
return err("Solo gli amministratori possono schedulare questo comando.", 403)
|
||||||
|
elif not (PROFILE_KEY_RE.match(prof) or prof in SIMPLE_COMMANDS):
|
||||||
|
return err("Profilo non valido")
|
||||||
|
|
||||||
|
# Validazione nodi target
|
||||||
|
if target_nodes != 'all':
|
||||||
|
node_list = [x.strip() for x in target_nodes.split(',') if x.strip()]
|
||||||
|
if not node_list or not all(CID_RE.match(x) for x in node_list):
|
||||||
|
return err("ID nodo non valido")
|
||||||
|
target_nodes = ','.join(node_list)
|
||||||
|
|
||||||
# Verifica permessi per node_admin
|
# Verifica permessi per node_admin
|
||||||
if auth['role'] == 'node_admin':
|
if auth['role'] == 'node_admin':
|
||||||
allowed = set(x.strip().lower() for x in auth['allowed_nodes'].split(','))
|
allowed = set(x.strip().lower() for x in auth['allowed_nodes'].split(','))
|
||||||
@@ -701,7 +720,7 @@ def cancel_schedule(sid):
|
|||||||
try:
|
try:
|
||||||
with closing(db_connect(row=True)) as conn:
|
with closing(db_connect(row=True)) as conn:
|
||||||
c = conn.cursor()
|
c = conn.cursor()
|
||||||
c.execute("SELECT id, title, target_nodes, status, restore_profile FROM profile_schedules WHERE id = ?", (sid,))
|
c.execute("SELECT id, title, target_nodes, status, restore_profile, created_by FROM profile_schedules WHERE id = ?", (sid,))
|
||||||
row = c.fetchone()
|
row = c.fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
return err("Schedulazione non trovata", 404)
|
return err("Schedulazione non trovata", 404)
|
||||||
@@ -715,8 +734,9 @@ def cancel_schedule(sid):
|
|||||||
|
|
||||||
# Se era attiva, ripristina subito il profilo
|
# Se era attiva, ripristina subito il profilo
|
||||||
if row['status'] == 'ACTIVE' and row['restore_profile'] and row['restore_profile'] != 'NONE':
|
if row['status'] == 'ACTIVE' and row['restore_profile'] and row['restore_profile'] != 'NONE':
|
||||||
from services.scheduler_service import apply_scheduled_profile
|
from services.scheduler_service import apply_scheduled_profile, _is_admin
|
||||||
apply_scheduled_profile(row['target_nodes'], row['restore_profile'], "CANCEL_RESTORE")
|
apply_scheduled_profile(row['target_nodes'], row['restore_profile'], "CANCEL_RESTORE",
|
||||||
|
allow_privileged=_is_admin(conn, row['created_by']))
|
||||||
|
|
||||||
conn.execute("UPDATE profile_schedules SET status = 'CANCELLED' WHERE id = ?", (sid,))
|
conn.execute("UPDATE profile_schedules SET status = 'CANCELLED' WHERE id = ?", (sid,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|||||||
+10
-1
@@ -57,11 +57,20 @@ LOGIN_WINDOW_SEC = 300
|
|||||||
login_attempts = {}
|
login_attempts = {}
|
||||||
login_lock = threading.Lock()
|
login_lock = threading.Lock()
|
||||||
|
|
||||||
|
LOOPBACK_ADDRS = ('127.0.0.1', '::1')
|
||||||
|
|
||||||
def client_ip():
|
def client_ip():
|
||||||
|
fwd = request.headers.get('X-Forwarded-For', '')
|
||||||
if config.get('web', {}).get('trust_proxy'):
|
if config.get('web', {}).get('trust_proxy'):
|
||||||
fwd = request.headers.get('X-Forwarded-For', '')
|
|
||||||
if fwd:
|
if fwd:
|
||||||
return fwd.split(',')[0].strip()
|
return fwd.split(',')[0].strip()
|
||||||
|
elif fwd and request.remote_addr in LOOPBACK_ADDRS:
|
||||||
|
# Connessione dal proxy locale: solo lui puo' avere remote_addr loopback, quindi
|
||||||
|
# fidarsi dell'ultimo valore (quello aggiunto dal proxy) e' sicuro e evita che
|
||||||
|
# tutti gli utenti condividano 127.0.0.1 (lockout globale del login).
|
||||||
|
last = fwd.split(',')[-1].strip()
|
||||||
|
if last:
|
||||||
|
return last
|
||||||
return request.remote_addr or 'unknown'
|
return request.remote_addr or 'unknown'
|
||||||
|
|
||||||
def login_blocked(ip):
|
def login_blocked(ip):
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ def on_message(client, userdata, msg):
|
|||||||
state.node_logs[cid].append(log_entry)
|
state.node_logs[cid].append(log_entry)
|
||||||
|
|
||||||
# Inoltra in tempo reale via WebSocket
|
# Inoltra in tempo reale via WebSocket
|
||||||
state.socketio.emit(f"live_log_{cid}", log_entry)
|
state.emit_to_authorized(f"live_log_{cid}", log_entry, cid=cid)
|
||||||
|
|
||||||
# B) Parsa le versioni
|
# B) Parsa le versioni
|
||||||
if cid not in state.node_versions:
|
if cid not in state.node_versions:
|
||||||
@@ -134,7 +134,7 @@ def on_message(client, userdata, msg):
|
|||||||
|
|
||||||
state.aprs_msgs.append(aprs_data)
|
state.aprs_msgs.append(aprs_data)
|
||||||
logger.info(f"📍 APRS (da log {svc_name}): {src_part} -> {dest_part}")
|
logger.info(f"📍 APRS (da log {svc_name}): {src_part} -> {dest_part}")
|
||||||
state.socketio.emit('aprs_msg', aprs_data)
|
state.emit_aprs(aprs_data)
|
||||||
|
|
||||||
# NOTA: Rimosso il return incondizionato qui, perché il log deve completare la sua corsa
|
# NOTA: Rimosso il return incondizionato qui, perché il log deve completare la sua corsa
|
||||||
# e non bloccare eventuali altre logiche!
|
# e non bloccare eventuali altre logiche!
|
||||||
@@ -399,7 +399,7 @@ def on_message(client, userdata, msg):
|
|||||||
from collections import deque
|
from collections import deque
|
||||||
state.aprs_msgs = deque(maxlen=100)
|
state.aprs_msgs = deque(maxlen=100)
|
||||||
state.aprs_msgs.append(data)
|
state.aprs_msgs.append(data)
|
||||||
state.socketio.emit('aprs_msg', data)
|
state.emit_aprs(data)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Errore parsing APRS: {e}")
|
logger.error(f"Errore parsing APRS: {e}")
|
||||||
|
|
||||||
@@ -527,6 +527,16 @@ def on_message(client, userdata, msg):
|
|||||||
mqtt_id = config.get('mqtt', {}).get('client_id', 'flask_backend_generic')
|
mqtt_id = config.get('mqtt', {}).get('client_id', 'flask_backend_generic')
|
||||||
mqtt_backend = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, mqtt_id)
|
mqtt_backend = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, mqtt_id)
|
||||||
mqtt_backend.username_pw_set(config.get('mqtt', {}).get('user', ''), config.get('mqtt', {}).get('password', ''))
|
mqtt_backend.username_pw_set(config.get('mqtt', {}).get('user', ''), config.get('mqtt', {}).get('password', ''))
|
||||||
|
# TLS opzionale (default: disattivato, comportamento invariato). In config.json:
|
||||||
|
# "mqtt": { ..., "port": 8883, "tls": true, "ca_certs": "/etc/ssl/certs/ca-certificates.crt" }
|
||||||
|
if config.get('mqtt', {}).get('tls'):
|
||||||
|
import ssl
|
||||||
|
try:
|
||||||
|
mqtt_backend.tls_set(ca_certs=config.get('mqtt', {}).get('ca_certs') or None,
|
||||||
|
cert_reqs=ssl.CERT_REQUIRED)
|
||||||
|
logger.info("🔒 MQTT: TLS abilitato")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"MQTT TLS non configurabile: {e}")
|
||||||
mqtt_backend.on_connect = on_connect
|
mqtt_backend.on_connect = on_connect
|
||||||
mqtt_backend.on_disconnect = on_disconnect
|
mqtt_backend.on_disconnect = on_disconnect
|
||||||
mqtt_backend.on_message = on_message
|
mqtt_backend.on_message = on_message
|
||||||
|
|||||||
@@ -4,17 +4,10 @@ from contextlib import closing
|
|||||||
from pywebpush import webpush, WebPushException
|
from pywebpush import webpush, WebPushException
|
||||||
from core.config import config, logger
|
from core.config import config, logger
|
||||||
from core.database import db_connect
|
from core.database import db_connect
|
||||||
|
from core.permissions import node_allowed # noqa: F401 (re-export per compatibilita')
|
||||||
|
|
||||||
push_queue = queue.Queue(maxsize=200)
|
push_queue = queue.Queue(maxsize=200)
|
||||||
|
|
||||||
def node_allowed(role, allowed_nodes, cid):
|
|
||||||
if role == 'admin':
|
|
||||||
return True
|
|
||||||
allowed = (allowed_nodes or '').strip().lower()
|
|
||||||
if allowed == 'all':
|
|
||||||
return True
|
|
||||||
return cid in [x.strip().lower() for x in allowed.split(',') if x.strip()]
|
|
||||||
|
|
||||||
def broadcast_push_notification(title, body, cid=None):
|
def broadcast_push_notification(title, body, cid=None):
|
||||||
if not config.get('webpush'):
|
if not config.get('webpush'):
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -45,17 +45,33 @@ def auto_update_ids():
|
|||||||
download_logic()
|
download_logic()
|
||||||
prune_old_data()
|
prune_old_data()
|
||||||
time.sleep(65)
|
time.sleep(65)
|
||||||
|
except Exception as e:
|
||||||
# Controllo schedulazioni profili
|
logger.error(f"⚠️ Errore nel thread aggiornamento ID: {e}")
|
||||||
|
time.sleep(15)
|
||||||
|
|
||||||
|
def schedule_loop():
|
||||||
|
"""Thread dedicato alle schedulazioni: non e' piu' bloccato dai download degli ID."""
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
check_profile_schedules()
|
check_profile_schedules()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"⚠️ Errore nel thread scheduler: {e}")
|
logger.error(f"⚠️ Errore nel thread schedulazioni: {e}")
|
||||||
time.sleep(15)
|
time.sleep(15)
|
||||||
|
|
||||||
from contextlib import closing
|
from contextlib import closing
|
||||||
from core.database import db_connect, audit
|
from core.database import db_connect, audit
|
||||||
|
|
||||||
def apply_scheduled_profile(target_nodes, profile, action_type="SWITCH"):
|
# Comandi che le API riservano agli admin: una schedulazione li puo' inviare solo se creata da un admin.
|
||||||
|
PRIVILEGED_COMMANDS = {'REBOOT', 'RESET_HAT', 'UPDATE_AGENT'}
|
||||||
|
|
||||||
|
def _is_admin(conn, username):
|
||||||
|
row = conn.execute("SELECT role FROM users WHERE username = ?", (username,)).fetchone()
|
||||||
|
return bool(row) and row[0] == 'admin'
|
||||||
|
|
||||||
|
def apply_scheduled_profile(target_nodes, profile, action_type="SWITCH", allow_privileged=False):
|
||||||
|
if str(profile).strip().upper() in PRIVILEGED_COMMANDS and not allow_privileged:
|
||||||
|
logger.warning(f"🚫 Scheduler: comando privilegiato '{profile}' ignorato (schedulazione non creata da un admin)")
|
||||||
|
return
|
||||||
from services.mqtt_service import mqtt_publish
|
from services.mqtt_service import mqtt_publish
|
||||||
from core.config import CLIENTS_PATH
|
from core.config import CLIENTS_PATH
|
||||||
import json
|
import json
|
||||||
@@ -111,7 +127,7 @@ def check_profile_schedules():
|
|||||||
if status == 'SCHEDULED':
|
if status == 'SCHEDULED':
|
||||||
if st_norm <= now_str < end_norm:
|
if st_norm <= now_str < end_norm:
|
||||||
logger.info(f"▶️ Avvio schedulazione ID {sid} - '{title}' -> Profilo {target_prof}")
|
logger.info(f"▶️ Avvio schedulazione ID {sid} - '{title}' -> Profilo {target_prof}")
|
||||||
apply_scheduled_profile(nodes, target_prof, "START")
|
apply_scheduled_profile(nodes, target_prof, "START", allow_privileged=_is_admin(conn, row['created_by']))
|
||||||
conn.execute("UPDATE profile_schedules SET status = 'ACTIVE' WHERE id = ?", (sid,))
|
conn.execute("UPDATE profile_schedules SET status = 'ACTIVE' WHERE id = ?", (sid,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
audit("SCHEDULER", nodes, f"START_SCHED_{sid}_{target_prof}")
|
audit("SCHEDULER", nodes, f"START_SCHED_{sid}_{target_prof}")
|
||||||
@@ -125,7 +141,7 @@ def check_profile_schedules():
|
|||||||
if now_str >= end_norm:
|
if now_str >= end_norm:
|
||||||
logger.info(f"⏹️ Fine schedulazione ID {sid} - '{title}' -> Ripristino {restore_prof}")
|
logger.info(f"⏹️ Fine schedulazione ID {sid} - '{title}' -> Ripristino {restore_prof}")
|
||||||
if restore_prof and restore_prof.upper() != 'NONE':
|
if restore_prof and restore_prof.upper() != 'NONE':
|
||||||
apply_scheduled_profile(nodes, restore_prof, "RESTORE")
|
apply_scheduled_profile(nodes, restore_prof, "RESTORE", allow_privileged=_is_admin(conn, row['created_by']))
|
||||||
conn.execute("UPDATE profile_schedules SET status = 'COMPLETED' WHERE id = ?", (sid,))
|
conn.execute("UPDATE profile_schedules SET status = 'COMPLETED' WHERE id = ?", (sid,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
audit("SCHEDULER", nodes, f"RESTORE_SCHED_{sid}_{restore_prof}")
|
audit("SCHEDULER", nodes, f"RESTORE_SCHED_{sid}_{restore_prof}")
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# VERSIONE PIU' SICURA (opzionale) del servizio. Il file fleet-console.service originale resta invariato.
|
||||||
|
#
|
||||||
|
# Preparazione (una tantum, da root):
|
||||||
|
# useradd --system --home /opt/fleet-control-server --shell /usr/sbin/nologin fleet
|
||||||
|
# chown -R fleet:fleet /opt/fleet-control-server
|
||||||
|
# cp systemd/fleet-console.hardened.service.example /etc/systemd/system/fleet-console.service
|
||||||
|
# systemctl daemon-reload && systemctl restart fleet-console
|
||||||
|
#
|
||||||
|
# Se usi un reverse proxy (consigliato) cambia anche il bind in 127.0.0.1:9000 qui sotto.
|
||||||
|
# L'aggiornamento OTA (git pull) continua a funzionare perche' l'utente "fleet" possiede la cartella.
|
||||||
|
[Unit]
|
||||||
|
Description=Fleet Control Console - Central Hub
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=fleet
|
||||||
|
Group=fleet
|
||||||
|
WorkingDirectory=/opt/fleet-control-server
|
||||||
|
ExecStart=/opt/fleet-control-server/venv/bin/gunicorn -k "geventwebsocket.gunicorn.workers.GeventWebSocketWorker" -w 1 --graceful-timeout 2 --bind 0.0.0.0:9000 app:app
|
||||||
|
TimeoutStopSec=3
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
# Hardening
|
||||||
|
NoNewPrivileges=true
|
||||||
|
PrivateTmp=true
|
||||||
|
ProtectSystem=full
|
||||||
|
ProtectHome=true
|
||||||
|
ReadWritePaths=/opt/fleet-control-server
|
||||||
|
|
||||||
|
StandardOutput=syslog
|
||||||
|
StandardError=syslog
|
||||||
|
SyslogIdentifier=fleet-console
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -620,7 +620,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- LIBRERIE ESTERNE -->
|
<!-- LIBRERIE ESTERNE -->
|
||||||
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.js"></script>
|
||||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/diff_match_patch/20121119/diff_match_patch.js"></script>
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/diff_match_patch/20121119/diff_match_patch.js"></script>
|
||||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/socket.io.min.js"></script>
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/socket.io.min.js"></script>
|
||||||
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
|
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
|
||||||
|
|||||||
+8
-8
@@ -1,11 +1,11 @@
|
|||||||
import sqlite3
|
"""Invia una notifica push di prova a tutti gli iscritti, senza avviare MQTT e i thread dell'app.
|
||||||
import json
|
|
||||||
from app import broadcast_push_notification, init_db
|
|
||||||
|
|
||||||
# Proviamo a inviare una notifica a tutti gli iscritti nel DB
|
Uso (dalla cartella del progetto, con il venv attivo): python test-push.py
|
||||||
|
"""
|
||||||
|
from core.database import init_db
|
||||||
|
from services.push_service import _send_push
|
||||||
|
|
||||||
|
init_db()
|
||||||
print("🚀 Starting notification test...")
|
print("🚀 Starting notification test...")
|
||||||
broadcast_push_notification(
|
_send_push("⚠️ ALLERTA FLOTTA", "Test Push Notification: System Online!", None)
|
||||||
"⚠️ ALLERTA FLOTTA",
|
|
||||||
"Test Push Notification: System Online!"
|
|
||||||
)
|
|
||||||
print("✅ Command sent.")
|
print("✅ Command sent.")
|
||||||
|
|||||||
Reference in New Issue
Block a user