Security fix
This commit is contained in:
+23
-4
@@ -95,6 +95,13 @@ def init_db():
|
||||
|
||||
def save_to_sqlite(client_id, data, protocol="DMR"):
|
||||
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()
|
||||
|
||||
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),
|
||||
str(data.get('src_ext', '')), rssi_val, str(data.get('source', '')), str(data.get('mode', ''))))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
notify_update('log_aggiornato')
|
||||
|
||||
def audit(username, client_id, command):
|
||||
try:
|
||||
@@ -133,9 +138,23 @@ def prune_old_data():
|
||||
n1 = c.rowcount
|
||||
c.execute("DELETE FROM audit_logs WHERE timestamp < datetime('now', 'localtime', ?)", (f"-{audit_days} days",))
|
||||
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()
|
||||
if n1 or n2:
|
||||
logger.info(f"🧹 Pulizia DB: {n1} ascolti e {n2} audit rimossi.")
|
||||
if n1 or n2 or n3 or n4:
|
||||
logger.info(f"🧹 Pulizia DB: {n1} ascolti, {n2} audit, {n3} telemetrie e {n4} backup config rimossi.")
|
||||
except Exception as 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 flask_socketio import SocketIO
|
||||
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 ---
|
||||
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
|
||||
connected_web_clients = set()
|
||||
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
|
||||
if os.path.exists(CACHE_FILE):
|
||||
|
||||
Reference in New Issue
Block a user