Files
MatikandClaude Opus 5.5 9bcca5d9e3 Etap 3: broker EMQX z TLS i ACL, symulator czujnika ciśnienia, instrukcja
- docker-compose: EMQX 5.8.6 (1883/8883/18083), symulator (FastAPI, MQTT 5), sniffer tcpdump
- emqx.conf, acl.conf: uwierzytelnianie, autoryzacja (default deny), TLS
- hasła wyłącznie w pliku .env (poza repozytorium), konta tworzone przy starcie brokera
- skrypty: generowanie certyfikatów, podgląd w Wiresharku, klient SCADA
- INSTRUKCJA.md: wykonanie zadań i zbieranie dowodów do sprawozdania
- screeny/: zrzuty ekranu do sprawozdania

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 19:26:25 +01:00

342 lines
14 KiB
Python

"""Obsługa połączenia MQTT (paho-mqtt 2.x, protokół MQTT 5) - jawnie lub przez TLS."""
import json
import os
import ssl
import threading
import time
from collections import deque
from datetime import datetime
import paho.mqtt.client as mqtt
from paho.mqtt.properties import Properties
from paho.mqtt.packettypes import PacketTypes
TLS_VERSIONS = {
"auto": (ssl.TLSVersion.TLSv1_2, ssl.TLSVersion.MAXIMUM_SUPPORTED),
"1.2": (ssl.TLSVersion.TLSv1_2, ssl.TLSVersion.TLSv1_2),
"1.3": (ssl.TLSVersion.TLSv1_3, ssl.TLSVersion.TLSv1_3),
}
class EventLog:
"""Bufor zdarzeń wyświetlanych w panelu (z rosnącym ID do odpytywania przyrostowego)."""
def __init__(self, maxlen: int = 600):
self._items = deque(maxlen=maxlen)
self._next_id = 1
self._lock = threading.Lock()
def add(self, level: str, message: str, detail: str | None = None) -> None:
with self._lock:
self._items.append({
"id": self._next_id,
"time": datetime.now().strftime("%H:%M:%S.%f")[:-3],
"level": level, # info | ok | warn | error | tx | rx
"message": message,
"detail": detail,
})
self._next_id += 1
print(f"[{level.upper():5}] {message}" + (f" | {detail}" if detail else ""), flush=True)
def since(self, after: int) -> list[dict]:
with self._lock:
return [e for e in self._items if e["id"] > after]
def clear(self) -> None:
with self._lock:
self._items.clear()
class MqttManager:
def __init__(self, log: EventLog, on_message=None):
self.log = log
self.on_message_cb = on_message
self.client: mqtt.Client | None = None
self.settings: dict = {}
self.state = "disconnected" # disconnected | connecting | connected
self.tls_info: dict | None = None
self.stats = {"sent": 0, "acked": 0, "denied": 0, "received": 0}
self._lock = threading.RLock()
self._pending: dict[int, dict] = {} # mid -> opis publikacji/subskrypcji
self._early: dict[int, tuple] = {} # odpowiedzi, które przyszły przed zapisaniem mid
self._connack = threading.Event()
self._connack_result: tuple[bool, str] = (False, "")
self._subscriptions: list[str] = []
# ------------------------------------------------------------------ connect
def connect(self, s: dict) -> dict:
self.disconnect(quiet=True)
self.settings = dict(s)
mode = "TLS" if s["tls"] else "bez szyfrowania"
self.log.add("info", f"Łączenie z {s['host']}:{s['port']} ({mode}) jako '{s['username'] or '(anonim)'}'"
f", client_id='{s['client_id']}'")
client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
client_id=s["client_id"], protocol=mqtt.MQTTv5)
if s["username"]:
client.username_pw_set(s["username"], s["password"] or None)
if s["tls"]:
client.tls_set_context(self._build_tls_context(s))
# Ostatnia wola (LWT): broker sam opublikuje "offline", gdy czujnik zniknie bez pożegnania.
if s.get("status_topic"):
client.will_set(s["status_topic"], json.dumps({"sensor_id": s.get("sensor_id"), "state": "offline"}),
qos=1, retain=True)
client.on_connect = self._on_connect
client.on_disconnect = self._on_disconnect
client.on_publish = self._on_publish
client.on_subscribe = self._on_subscribe
client.on_message = self._on_message
client.reconnect_delay_set(min_delay=2, max_delay=10)
with self._lock:
self.client = client
self.state = "connecting"
self.tls_info = None
self._connack.clear()
try:
client.connect(s["host"], int(s["port"]), keepalive=30, clean_start=True)
except ssl.SSLCertVerificationError as e:
return self._fail(f"Błąd weryfikacji certyfikatu TLS: {e.verify_message}", str(e))
except ssl.SSLError as e:
return self._fail(f"Błąd TLS: {e.reason or e}", str(e))
except (OSError, ValueError) as e:
return self._fail(f"Nie można połączyć z {s['host']}:{s['port']}: {e}", None)
if s["tls"]:
self._capture_tls_info(client)
client.loop_start()
if not self._connack.wait(8):
self.disconnect(quiet=True)
return self._fail("Brak odpowiedzi CONNACK od brokera (timeout)", None)
ok, msg = self._connack_result
if not ok:
with self._lock:
self.client = None
threading.Thread(target=client.loop_stop, daemon=True).start()
return {"ok": False, "error": msg}
return {"ok": True}
def _build_tls_context(self, s: dict) -> ssl.SSLContext:
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
lo, hi = TLS_VERSIONS.get(s.get("tls_version", "auto"), TLS_VERSIONS["auto"])
ctx.minimum_version, ctx.maximum_version = lo, hi
if s.get("verify", True):
ca = s.get("ca_file") or "/certs/ca.crt"
if not os.path.isfile(ca):
raise ValueError(f"Brak pliku CA: {ca}")
ctx.load_verify_locations(cafile=ca)
ctx.check_hostname = True
ctx.verify_mode = ssl.CERT_REQUIRED
else:
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
# Opcjonalnie: zapis kluczy sesji TLS, aby Wireshark mógł odszyfrować ruch (demonstracja).
keylog = os.getenv("TLS_KEYLOG_FILE")
if keylog:
ctx.keylog_filename = keylog
return ctx
def _capture_tls_info(self, client: mqtt.Client) -> None:
sock = client.socket()
if not isinstance(sock, ssl.SSLSocket):
return
cert = sock.getpeercert() or {}
subject = ", ".join("=".join(x) for rdn in cert.get("subject", ()) for x in rdn)
issuer = ", ".join("=".join(x) for rdn in cert.get("issuer", ()) for x in rdn)
cipher = sock.cipher()
self.tls_info = {
"version": sock.version(),
"cipher": cipher[0] if cipher else None,
"subject": subject or "(certyfikat niezweryfikowany)",
"issuer": issuer or "-",
"not_after": cert.get("notAfter"),
}
self.log.add("ok", f"Uścisk dłoni TLS zakończony: {sock.version()}, {cipher[0] if cipher else '?'}",
f"serwer: {subject or '?'} | wystawca: {issuer or '?'}")
def _fail(self, msg: str, detail: str | None) -> dict:
self.log.add("error", msg, detail)
with self._lock:
client, self.client = self.client, None
self.state = "disconnected"
if client:
try:
client.loop_stop()
except Exception:
pass
return {"ok": False, "error": msg}
def disconnect(self, quiet: bool = False) -> None:
with self._lock:
client, self.client = self.client, None
was = self.state
self.state = "disconnected"
self.tls_info = None
self._subscriptions = []
if client is None:
return
try:
if was == "connected" and self.settings.get("status_topic"):
client.publish(self.settings["status_topic"],
json.dumps({"sensor_id": self.settings.get("sensor_id"), "state": "offline"}),
qos=1, retain=True).wait_for_publish(2)
except Exception:
pass
client.disconnect()
client.loop_stop()
if not quiet:
self.log.add("info", "Rozłączono z brokerem")
# ------------------------------------------------------------------ callbacks
def _on_connect(self, client, userdata, flags, reason_code, properties):
if client is not self.client:
return
if reason_code.is_failure:
msg = f"Broker odrzucił połączenie: {reason_code} (kod 0x{reason_code.value:02X})"
self.log.add("error", msg)
self._connack_result = (False, msg)
client.disconnect()
with self._lock:
self.state = "disconnected"
else:
with self._lock:
self.state = "connected"
self._connack_result = (True, "")
self.log.add("ok", f"Połączono (CONNACK: {reason_code})")
s = self.settings
if s.get("status_topic"):
self.publish(s["status_topic"], {"sensor_id": s.get("sensor_id"), "state": "online"},
qos=1, retain=True, kind="status")
if s.get("command_topic"):
self.subscribe(s["command_topic"], qos=1)
self._connack.set()
def _on_disconnect(self, client, userdata, flags, reason_code, properties):
if client is not self.client:
return
with self._lock:
if self.state == "connected":
self.state = "connecting"
self.log.add("warn", f"Utracono połączenie z brokerem ({reason_code}) - ponawiam...")
def _on_publish(self, client, userdata, mid, reason_code, properties):
with self._lock:
info = self._pending.pop(mid, None)
if info is None:
self._early[mid] = (reason_code,)
return
self._report_publish(info, reason_code)
def _report_publish(self, info: dict, reason_code) -> None:
if info["qos"] == 0:
return # QoS 0 - brak potwierdzenia od brokera (wpis TX dodany przy wysyłce)
if reason_code.is_failure:
with self._lock:
self.stats["denied"] += 1
self.log.add("error", f"ODMOWA publikacji na '{info['topic']}': PUBACK {reason_code} "
f"(0x{reason_code.value:02X})",
"Broker odrzucił wiadomość - sprawdź logi brokera (authorization_permission_denied).")
else:
with self._lock:
self.stats["acked"] += 1
if info.get("kind") != "telemetry":
self.log.add("ok", f"Broker potwierdził publikację na '{info['topic']}' (PUBACK: {reason_code})")
def _on_subscribe(self, client, userdata, mid, reason_codes, properties):
with self._lock:
info = self._pending.pop(mid, None)
if info is None:
self._early[mid] = (reason_codes,)
return
self._report_subscribe(info, reason_codes)
def _report_subscribe(self, info: dict, reason_codes) -> None:
for rc in reason_codes:
if rc.is_failure:
with self._lock:
self.stats["denied"] += 1
self.log.add("error", f"ODMOWA subskrypcji '{info['topic']}': SUBACK {rc} (0x{rc.value:02X})")
else:
with self._lock:
if info["topic"] not in self._subscriptions:
self._subscriptions.append(info["topic"])
self.log.add("ok", f"Zasubskrybowano '{info['topic']}' (przyznane QoS {rc.value})")
def _on_message(self, client, userdata, msg):
with self._lock:
self.stats["received"] += 1
text = msg.payload.decode("utf-8", errors="replace")
self.log.add("rx", f"Odebrano z '{msg.topic}'", text)
if self.on_message_cb:
try:
self.on_message_cb(msg.topic, text)
except Exception as e: # nie przerywamy pętli MQTT
self.log.add("warn", f"Błąd obsługi wiadomości: {e}")
# ------------------------------------------------------------------ actions
def publish(self, topic: str, payload, qos: int = 1, retain: bool = False, kind: str = "custom") -> dict:
with self._lock:
client = self.client
connected = self.state == "connected"
if not client or not connected:
return {"ok": False, "error": "Brak połączenia z brokerem"}
if not topic or any(c in topic for c in "+#"):
return {"ok": False, "error": "Nieprawidłowy temat publikacji (bez znaków + i #)"}
data = payload if isinstance(payload, str) else json.dumps(payload, ensure_ascii=False)
info = {"topic": topic, "qos": qos, "kind": kind}
props = Properties(PacketTypes.PUBLISH)
props.ContentType = "application/json"
result = client.publish(topic, data, qos=qos, retain=retain, properties=props)
if result.rc != mqtt.MQTT_ERR_SUCCESS:
msg = f"Publikacja nieudana: {mqtt.error_string(result.rc)}"
self.log.add("error", msg)
return {"ok": False, "error": msg}
with self._lock:
self.stats["sent"] += 1
early = self._early.pop(result.mid, None)
if early is None:
self._pending[result.mid] = info
self.log.add("tx", f"Wysłano PUBLISH na '{topic}' (QoS {qos}{', retain' if retain else ''})", data)
if early is not None:
self._report_publish(info, early[0])
return {"ok": True, "mid": result.mid}
def subscribe(self, topic: str, qos: int = 1) -> dict:
with self._lock:
client = self.client
connected = self.state == "connected"
if not client or not connected:
return {"ok": False, "error": "Brak połączenia z brokerem"}
rc, mid = client.subscribe(topic, qos=qos)
if rc != mqtt.MQTT_ERR_SUCCESS:
return {"ok": False, "error": mqtt.error_string(rc)}
info = {"topic": topic}
with self._lock:
early = self._early.pop(mid, None)
if early is None:
self._pending[mid] = info
self.log.add("tx", f"Wysłano SUBSCRIBE '{topic}' (QoS {qos})")
if early is not None:
self._report_subscribe(info, early[0])
return {"ok": True}
def status(self) -> dict:
with self._lock:
s = self.settings
return {
"state": self.state,
"host": s.get("host"),
"port": s.get("port"),
"tls": bool(s.get("tls")),
"username": s.get("username"),
"client_id": s.get("client_id"),
"tls_info": self.tls_info,
"subscriptions": list(self._subscriptions),
"stats": dict(self.stats),
}