diff --git a/CHANGELOG-security.md b/CHANGELOG-security.md new file mode 100644 index 0000000..c4a99a0 --- /dev/null +++ b/CHANGELOG-security.md @@ -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_`**: 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/`. 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. diff --git a/app.py b/app.py index 54dbdbd..ec7d910 100644 --- a/app.py +++ b/app.py @@ -4,7 +4,9 @@ gevent.monkey.patch_all() import os import subprocess 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 # --- IMPORT MODULI CORE --- @@ -15,11 +17,12 @@ import core.state as state # --- IMPORT SERVIZI --- from services.push_service import push_worker 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 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 # Inizializzazione Flask @@ -52,6 +55,17 @@ def add_security_headers(resp): resp.headers['Cache-Control'] = 'no-store' 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(): try: 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(): return render_template('index.html', git_commit=SERVER_COMMIT) -from flask import session - @state.socketio.on('connect') def handle_connect(): state.connected_web_clients.add(request.sid) # Se l'utente è loggato (session), associamo il suo username al SID - user = session.get('user') - if user: - state.active_logged_users[request.sid] = user + auth = get_auth() + if auth: + 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}) @@ -85,21 +101,37 @@ def handle_connect(): def handle_disconnect(): state.connected_web_clients.discard(request.sid) state.active_logged_users.pop(request.sid, None) + state.socket_auth.pop(request.sid, None) logged_names = list(set(state.active_logged_users.values())) 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 --- init_db() state.seed_last_seen() mqtt_svc.start_mqtt() 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=watchdog_loop, daemon=True).start() logger.info(f"🚀 Fleet Control Console modulare pronta (Git Rev: {SERVER_COMMIT})") 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) diff --git a/config.json.example b/config.json.example index 692898b..599f8ff 100644 --- a/config.json.example +++ b/config.json.example @@ -17,7 +17,8 @@ "devices/#", "data/#", "aprs-gateway/aprs" - ] + ], + "tls": false }, "web_admin": { "default_user": "admin", @@ -41,5 +42,18 @@ }, "log_max_mb": 50, "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 } diff --git a/core/database.py b/core/database.py index 72a7387..efe1472 100644 --- a/core/database.py +++ b/core/database.py @@ -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}") diff --git a/core/permissions.py b/core/permissions.py new file mode 100644 index 0000000..2d7e23d --- /dev/null +++ b/core/permissions.py @@ -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()] diff --git a/core/state.py b/core/state.py index 6e084ad..f87edc2 100644 --- a/core/state.py +++ b/core/state.py @@ -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): diff --git a/install.txt b/install.txt index efa6e36..25e249f 100644 --- a/install.txt +++ b/install.txt @@ -36,7 +36,7 @@ Install project requirements: The server handles the web interface and user permissions. Steps: -1. Configure 'config.json' using 'config.example.json'. +1. Configure 'config.json' using 'config.json.example'. 2. Enter MQTT credentials and VAPID keys. 3. Define repeaters in the 'clients.json' file. 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) ------------------------------------------------------------ ⚠️ 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. Example: @@ -110,7 +110,7 @@ Installa i requisiti del progetto: 2. SETUP DEL SERVER ------------------------------------------------------------ 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. 3. Definisci i ripetitori in 'clients.json'. 4. Avvia il server di produzione: @@ -128,7 +128,7 @@ Passaggi: 4. ESECUZIONE COME SERVIZIO (SYSTEMD) ------------------------------------------------------------ ⚠️ 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! Esempio: diff --git a/routes/api_routes.py b/routes/api_routes.py index 445f765..432e71c 100644 --- a/routes/api_routes.py +++ b/routes/api_routes.py @@ -14,6 +14,7 @@ import core.state as state from services.mqtt_service import mqtt_publish from services.push_service import node_allowed 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 --- GLOBAL_SERVER_UPDATE_AVAILABLE = False @@ -254,7 +255,7 @@ def update_nodes(): return err("Non autorizzato", 403) if not mqtt_publish("devices/control/request", "update"): 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') return jsonify({"success": True}) @@ -411,6 +412,8 @@ def apply_server_update(): auth = get_auth() if not auth or auth['role'] != 'admin': 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: audit(auth['username'], 'SERVER', 'SERVER_OTA_UPDATE') @@ -660,6 +663,22 @@ def add_schedule(): if not start_time or not end_time: 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 if auth['role'] == 'node_admin': allowed = set(x.strip().lower() for x in auth['allowed_nodes'].split(',')) @@ -701,7 +720,7 @@ def cancel_schedule(sid): try: with closing(db_connect(row=True)) as conn: 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() if not row: return err("Schedulazione non trovata", 404) @@ -715,8 +734,9 @@ def cancel_schedule(sid): # Se era attiva, ripristina subito il profilo if row['status'] == 'ACTIVE' and row['restore_profile'] and row['restore_profile'] != 'NONE': - from services.scheduler_service import apply_scheduled_profile - apply_scheduled_profile(row['target_nodes'], row['restore_profile'], "CANCEL_RESTORE") + from services.scheduler_service import apply_scheduled_profile, _is_admin + 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.commit() diff --git a/routes/auth_routes.py b/routes/auth_routes.py index 91b481c..28e3c44 100644 --- a/routes/auth_routes.py +++ b/routes/auth_routes.py @@ -57,11 +57,20 @@ LOGIN_WINDOW_SEC = 300 login_attempts = {} login_lock = threading.Lock() +LOOPBACK_ADDRS = ('127.0.0.1', '::1') + def client_ip(): + fwd = request.headers.get('X-Forwarded-For', '') if config.get('web', {}).get('trust_proxy'): - fwd = request.headers.get('X-Forwarded-For', '') if fwd: 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' def login_blocked(ip): diff --git a/services/mqtt_service.py b/services/mqtt_service.py index 3a2fd71..a0c45ed 100644 --- a/services/mqtt_service.py +++ b/services/mqtt_service.py @@ -71,7 +71,7 @@ def on_message(client, userdata, msg): state.node_logs[cid].append(log_entry) # 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 if cid not in state.node_versions: @@ -134,7 +134,7 @@ def on_message(client, userdata, msg): state.aprs_msgs.append(aprs_data) 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 # e non bloccare eventuali altre logiche! @@ -399,7 +399,7 @@ def on_message(client, userdata, msg): from collections import deque state.aprs_msgs = deque(maxlen=100) state.aprs_msgs.append(data) - state.socketio.emit('aprs_msg', data) + state.emit_aprs(data) except Exception as 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_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', '')) +# 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_disconnect = on_disconnect mqtt_backend.on_message = on_message diff --git a/services/push_service.py b/services/push_service.py index 2d2a9de..89e155f 100644 --- a/services/push_service.py +++ b/services/push_service.py @@ -4,17 +4,10 @@ from contextlib import closing from pywebpush import webpush, WebPushException from core.config import config, logger from core.database import db_connect +from core.permissions import node_allowed # noqa: F401 (re-export per compatibilita') 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): if not config.get('webpush'): return diff --git a/services/scheduler_service.py b/services/scheduler_service.py index 2ab5889..20044ea 100644 --- a/services/scheduler_service.py +++ b/services/scheduler_service.py @@ -45,17 +45,33 @@ def auto_update_ids(): download_logic() prune_old_data() time.sleep(65) - - # Controllo schedulazioni profili + except Exception as e: + 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() except Exception as e: - logger.error(f"⚠️ Errore nel thread scheduler: {e}") + logger.error(f"⚠️ Errore nel thread schedulazioni: {e}") time.sleep(15) from contextlib import closing 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 core.config import CLIENTS_PATH import json @@ -111,7 +127,7 @@ def check_profile_schedules(): if status == 'SCHEDULED': if st_norm <= now_str < end_norm: 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.commit() audit("SCHEDULER", nodes, f"START_SCHED_{sid}_{target_prof}") @@ -125,7 +141,7 @@ def check_profile_schedules(): if now_str >= end_norm: logger.info(f"⏹️ Fine schedulazione ID {sid} - '{title}' -> Ripristino {restore_prof}") 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.commit() audit("SCHEDULER", nodes, f"RESTORE_SCHED_{sid}_{restore_prof}") diff --git a/systemd/fleet-console.hardened.service.example b/systemd/fleet-console.hardened.service.example new file mode 100644 index 0000000..9288d59 --- /dev/null +++ b/systemd/fleet-console.hardened.service.example @@ -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 diff --git a/templates/index.html b/templates/index.html index 2d1aa15..80b2298 100644 --- a/templates/index.html +++ b/templates/index.html @@ -620,7 +620,7 @@ - + diff --git a/test-push.py b/test-push.py index f44a7c5..a41e49f 100644 --- a/test-push.py +++ b/test-push.py @@ -1,11 +1,11 @@ -import sqlite3 -import json -from app import broadcast_push_notification, init_db +"""Invia una notifica push di prova a tutti gli iscritti, senza avviare MQTT e i thread dell'app. -# 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...") -broadcast_push_notification( - "⚠️ ALLERTA FLOTTA", - "Test Push Notification: System Online!" -) +_send_push("⚠️ ALLERTA FLOTTA", "Test Push Notification: System Online!", None) print("✅ Command sent.")