Agent-Updater, Multi-Plattform Firmware, Frontend Firmware-Seite, Agent-Tab, Zertifikate-Redesign
Updater: - Separater Go-Daemon (rmm-updater) als eigener rc.d Service - Pollt alle 60s: Firmware vorhanden + Hash unterschiedlich + Flag gesetzt - Download -> SHA256 Verify -> Agent Stop -> Replace -> Agent Start - Automatisches Rollback bei Fehler - Deployed und getestet auf allen 3 Firewalls (.1, .19, .33) Backend: - Firmware-DB multi-plattform (freebsd/linux/windows) - update_requested Flag pro Agent in agents Tabelle - Heartbeat-Response liefert update_available wenn Flag gesetzt - Neue Endpoints: request-update, request-update-all, firmware/download - Auth: JWT + CombinedAuth Middleware (API-Key OR JWT) - Customers CRUD + Agent-Zuordnung - Users CRUD + Passwort-Aenderung Frontend: - Firmware-Seite: Multi-Plattform Upload, Agent-Liste mit Update-Trigger - Agent-Tab im AgentPanel: Update-Button, nuetzliche Befehle, Agent-Info - Zertifikate-Tab redesigned: Karten-Layout mit Restlaufzeit und Farbbalken - Sidebar: Firmware-Eintrag hinzugefuegt Plugin: - install.sh erweitert: Installiert Agent + Updater + rc.d Services - rmm_updater rc.d Service README: - Architektur-Diagramm erweitert (Frontend + Updater) - Auth, Customers, Users, Firmware API dokumentiert - Updater-Flow dokumentiert - Frontend-Seiten und Deploy beschrieben - DB-Schema aktualisiert (neue Tabellen) - Dateistruktur erweitert (updater/, frontend/, firmware.go, auth.go)
This commit is contained in:
parent
616a0cb6ac
commit
e74cdce0ba
12
Makefile
12
Makefile
@ -1,13 +1,14 @@
|
|||||||
.PHONY: all backend agent plugin clean certs deploy-backend deploy-agent
|
.PHONY: all backend agent updater plugin clean certs deploy-backend deploy-agent
|
||||||
|
|
||||||
BACKEND_BIN = build/rmm-backend
|
BACKEND_BIN = build/rmm-backend
|
||||||
AGENT_BIN = build/rmm-agent
|
AGENT_BIN = build/rmm-agent
|
||||||
|
UPDATER_BIN = build/rmm-updater
|
||||||
|
|
||||||
BACKEND_HOST = 192.168.85.13
|
BACKEND_HOST = 192.168.85.13
|
||||||
AGENT_HOST = 192.168.85.33
|
AGENT_HOST = 192.168.85.33
|
||||||
SSH_USER = root
|
SSH_USER = root
|
||||||
|
|
||||||
all: backend agent
|
all: backend agent updater
|
||||||
|
|
||||||
backend:
|
backend:
|
||||||
@echo "==> Building Backend (linux/amd64)..."
|
@echo "==> Building Backend (linux/amd64)..."
|
||||||
@ -16,9 +17,14 @@ backend:
|
|||||||
|
|
||||||
agent:
|
agent:
|
||||||
@echo "==> Building Agent (freebsd/amd64)..."
|
@echo "==> Building Agent (freebsd/amd64)..."
|
||||||
cd agent && GOOS=freebsd GOARCH=amd64 CGO_ENABLED=0 go build -o ../$(AGENT_BIN) .
|
cd agent && GOOS=freebsd GOARCH=amd64 CGO_ENABLED=0 go build -ldflags "-X main.Version=$(VERSION)" -o ../$(AGENT_BIN) .
|
||||||
@echo "==> $(AGENT_BIN) erstellt"
|
@echo "==> $(AGENT_BIN) erstellt"
|
||||||
|
|
||||||
|
updater:
|
||||||
|
@echo "==> Building Updater (freebsd/amd64)..."
|
||||||
|
cd updater && GOOS=freebsd GOARCH=amd64 CGO_ENABLED=0 go build -o ../$(UPDATER_BIN) .
|
||||||
|
@echo "==> $(UPDATER_BIN) erstellt"
|
||||||
|
|
||||||
plugin:
|
plugin:
|
||||||
@echo "==> Building OPNsense Plugin Package..."
|
@echo "==> Building OPNsense Plugin Package..."
|
||||||
cd opnsense-plugin && ./build.sh $(VERSION)
|
cd opnsense-plugin && ./build.sh $(VERSION)
|
||||||
|
|||||||
179
README.md
179
README.md
@ -10,11 +10,11 @@ Go-basierter Agent + Backend mit WebSocket-Kommunikation und Session-basierten T
|
|||||||
│ OPNsense FW │◄──────────────►│ RMM Backend │◄───────────────│ Browser/ │
|
│ OPNsense FW │◄──────────────►│ RMM Backend │◄───────────────│ Browser/ │
|
||||||
│ (FreeBSD) │ :8443 │ (Linux) │ :10000-20000 │ SSH/etc. │
|
│ (FreeBSD) │ :8443 │ (Linux) │ :10000-20000 │ SSH/etc. │
|
||||||
│ │ │ │ └────────────┘
|
│ │ │ │ └────────────┘
|
||||||
│ rmm-agent │ Heartbeat │ REST API │
|
│ rmm-agent │ Heartbeat │ REST API │ ┌────────────┐
|
||||||
│ - Collectors │ WebSocket │ WebSocket Hub │
|
│ rmm-updater │ WebSocket │ WebSocket Hub │◄───────────────│ Frontend │
|
||||||
│ - WS Client │ Binary Msgs │ Tunnel Mgr │
|
│ - Collectors │ Binary Msgs │ Tunnel Mgr │ Nginx Proxy │ (React) │
|
||||||
│ - Tunnel Mgr │ │ PostgreSQL + │
|
│ - WS Client │ │ PostgreSQL + │ :80/443 │ .20 │
|
||||||
│ │ │ TimescaleDB │
|
│ - Tunnel Mgr │ │ TimescaleDB │ └────────────┘
|
||||||
└────────────────┘ └────────────────┘
|
└────────────────┘ └────────────────┘
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -67,6 +67,7 @@ Client ──► Backend:ProxyPort ──► WebSocket (Binary) ──► Agent
|
|||||||
| `wg_delete_peer` | `DELETE /agents/{id}/wireguard/peers/{uuid}` | WireGuard-Peer loeschen |
|
| `wg_delete_peer` | `DELETE /agents/{id}/wireguard/peers/{uuid}` | WireGuard-Peer loeschen |
|
||||||
| `tunnel_connect` | `POST /agents/{id}/tunnel` | TCP-Tunnel zu lokalem Dienst oeffnen |
|
| `tunnel_connect` | `POST /agents/{id}/tunnel` | TCP-Tunnel zu lokalem Dienst oeffnen |
|
||||||
| `tunnel_disconnect` | `DELETE /agents/{id}/tunnel/{tid}` | Tunnel schliessen |
|
| `tunnel_disconnect` | `DELETE /agents/{id}/tunnel/{tid}` | Tunnel schliessen |
|
||||||
|
| `agent_update` | `POST /agents/{id}/agent-update` | Agent-Binary remote aktualisieren (via WebSocket, Legacy) |
|
||||||
|
|
||||||
### Registrierte Agents
|
### Registrierte Agents
|
||||||
|
|
||||||
@ -241,10 +242,13 @@ Das Backend erstellt folgendes Schema bei erstem Start:
|
|||||||
|
|
||||||
| Tabelle | Typ | Beschreibung |
|
| Tabelle | Typ | Beschreibung |
|
||||||
|---------|-----|-------------|
|
|---------|-----|-------------|
|
||||||
| `agents` | Relational | Agent-Registry (ID, Name, Hostname, IP, Version, Heartbeat) |
|
| `agents` | Relational | Agent-Registry (ID, Name, Hostname, IP, Version, Heartbeat, customer_id, update_requested) |
|
||||||
| `system_data` | Relational | Letzte Systemdaten pro Agent (JSONB) |
|
| `system_data` | Relational | Letzte Systemdaten pro Agent (JSONB) |
|
||||||
| `config_backups` | Relational | OPNsense Config-Backups (dedupliziert per SHA256) |
|
| `config_backups` | Relational | OPNsense Config-Backups (dedupliziert per SHA256) |
|
||||||
| `agent_events` | Relational | Online/Offline/Connected Events |
|
| `agent_events` | Relational | Online/Offline/Connected Events |
|
||||||
|
| `customers` | Relational | Kundenstammdaten (Nummer, Name) |
|
||||||
|
| `users` | Relational | Benutzer (Username, bcrypt-Hash, Display-Name) |
|
||||||
|
| `agent_firmware` | Relational | Agent-Binaries pro Plattform+Version (BYTEA, SHA256) |
|
||||||
| `metrics` | TimescaleDB Hypertable | Time-Series Metriken (CPU, RAM, Disk, Network, Gateway) |
|
| `metrics` | TimescaleDB Hypertable | Time-Series Metriken (CPU, RAM, Disk, Network, Gateway) |
|
||||||
|
|
||||||
TimescaleDB Policies:
|
TimescaleDB Policies:
|
||||||
@ -307,9 +311,27 @@ ssh root@OPNSENSE 'service rmm_agent status'
|
|||||||
curl -sk -H "X-API-Key: DEIN_API_KEY" https://BACKEND_IP:8443/api/v1/agents
|
curl -sk -H "X-API-Key: DEIN_API_KEY" https://BACKEND_IP:8443/api/v1/agents
|
||||||
```
|
```
|
||||||
|
|
||||||
### Agent-Update
|
### Agent-Update (via Updater — empfohlen)
|
||||||
|
|
||||||
Bei neuer Agent-Version:
|
Der **rmm-updater** ist ein separater Daemon, der auf jeder Firewall neben dem Agent laeuft.
|
||||||
|
Er prueft alle 60 Sekunden ob ein Update ansteht und fuehrt es automatisch durch.
|
||||||
|
|
||||||
|
**Flow:**
|
||||||
|
1. Neue Agent-Binary im Frontend hochladen (Firmware-Seite)
|
||||||
|
2. Update-Button bei einzelnem Agent oder "Alle updaten" klicken
|
||||||
|
3. Updater erkennt den Flag, laedt die Binary vom Backend, stoppt Agent, ersetzt Binary, startet Agent
|
||||||
|
4. Flag wird automatisch zurueckgesetzt
|
||||||
|
|
||||||
|
**Technische Details:**
|
||||||
|
- Separates Go-Binary (`rmm-updater`), laeuft als `rmm_updater` rc.d Service
|
||||||
|
- Liest die gleiche `config.yaml` wie der Agent (Backend-URL, API-Key)
|
||||||
|
- Download ueber `GET /api/v1/firmware/download?platform=freebsd`
|
||||||
|
- SHA256-Verifizierung vor Ersetzung
|
||||||
|
- Automatisches Rollback bei fehlgeschlagenem Agent-Start
|
||||||
|
- Backup der alten Binary als `.bak` waehrend des Updates
|
||||||
|
- Logs: `/var/log/rmm-updater.log`
|
||||||
|
|
||||||
|
**Manuelles Update (Fallback):**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
make agent
|
make agent
|
||||||
@ -317,7 +339,7 @@ scp build/rmm-agent root@OPNSENSE:/tmp/
|
|||||||
ssh root@OPNSENSE '/bin/sh -c "service rmm_agent stop; cp /tmp/rmm-agent /usr/local/rmm/rmm-agent; chmod +x /usr/local/rmm/rmm-agent; service rmm_agent start"'
|
ssh root@OPNSENSE '/bin/sh -c "service rmm_agent stop; cp /tmp/rmm-agent /usr/local/rmm/rmm-agent; chmod +x /usr/local/rmm/rmm-agent; service rmm_agent start"'
|
||||||
```
|
```
|
||||||
|
|
||||||
Oder Plugin komplett neu installieren (`install.sh` ist idempotent).
|
Oder Plugin komplett neu installieren (`install.sh` ist idempotent — installiert Agent + Updater).
|
||||||
|
|
||||||
### Hinweise
|
### Hinweise
|
||||||
|
|
||||||
@ -352,6 +374,77 @@ Status wird automatisch aus `last_heartbeat` berechnet (kein DB-Feld):
|
|||||||
|
|
||||||
`GET /agents` liefert ein `status` Feld pro Agent, `GET /agents/{id}` ebenfalls.
|
`GET /agents` liefert ein `status` Feld pro Agent, `GET /agents/{id}` ebenfalls.
|
||||||
|
|
||||||
|
### Authentifizierung
|
||||||
|
|
||||||
|
Das Backend unterstuetzt zwei Auth-Methoden (CombinedAuth Middleware):
|
||||||
|
- **API-Key** (Header `X-API-Key`): Fuer Agents und automatisierte Zugriffe
|
||||||
|
- **JWT Bearer Token** (Header `Authorization: Bearer <token>`): Fuer Frontend-Benutzer
|
||||||
|
|
||||||
|
| Methode | Endpoint | Beschreibung |
|
||||||
|
|---------|----------|-------------|
|
||||||
|
| POST | `/api/v1/auth/login` | Login (username + password → JWT Token, 8h Ablauf) |
|
||||||
|
| GET | `/api/v1/auth/me` | Eigene Benutzerdaten |
|
||||||
|
|
||||||
|
Default-Admin wird automatisch beim ersten Start erstellt: `admin` / `Start!123` (min. 6 Zeichen).
|
||||||
|
|
||||||
|
### Kunden (Customers)
|
||||||
|
|
||||||
|
| Methode | Endpoint | Beschreibung |
|
||||||
|
|---------|----------|-------------|
|
||||||
|
| GET | `/api/v1/customers` | Alle Kunden auflisten |
|
||||||
|
| POST | `/api/v1/customers` | Neuen Kunden anlegen (`{number, name}`) |
|
||||||
|
| GET | `/api/v1/customers/{id}` | Einzelnen Kunden abrufen |
|
||||||
|
| PUT | `/api/v1/customers/{id}` | Kunden aktualisieren |
|
||||||
|
| DELETE | `/api/v1/customers/{id}` | Kunden loeschen |
|
||||||
|
| GET | `/api/v1/customers/{id}/agents` | Agents eines Kunden |
|
||||||
|
| PUT | `/api/v1/agents/{id}/customer` | Agent einem Kunden zuordnen |
|
||||||
|
| DELETE | `/api/v1/agents/{id}/customer` | Kundenzuordnung entfernen |
|
||||||
|
|
||||||
|
### Benutzer (Users)
|
||||||
|
|
||||||
|
| Methode | Endpoint | Beschreibung |
|
||||||
|
|---------|----------|-------------|
|
||||||
|
| GET | `/api/v1/users` | Alle Benutzer auflisten |
|
||||||
|
| POST | `/api/v1/users` | Neuen Benutzer anlegen |
|
||||||
|
| PUT | `/api/v1/users/{id}/password` | Passwort aendern (min. 6 Zeichen) |
|
||||||
|
| DELETE | `/api/v1/users/{id}` | Benutzer loeschen |
|
||||||
|
|
||||||
|
### Firmware / Agent-Update
|
||||||
|
|
||||||
|
Multi-Plattform Firmware-Verwaltung (freebsd, linux, windows):
|
||||||
|
|
||||||
|
| Methode | Endpoint | Beschreibung |
|
||||||
|
|---------|----------|-------------|
|
||||||
|
| GET | `/api/v1/firmware` | Alle Firmware-Versionen (pro Plattform) |
|
||||||
|
| GET | `/api/v1/firmware?platform=freebsd` | Firmware einer Plattform |
|
||||||
|
| POST | `/api/v1/firmware/upload?version=X&platform=Y` | Binary hochladen (Body = Raw Binary) |
|
||||||
|
| GET | `/api/v1/firmware/download?platform=Y` | Binary herunterladen (fuer Updater) |
|
||||||
|
| POST | `/api/v1/agents/{id}/request-update` | Update-Flag setzen (Updater fuehrt aus) |
|
||||||
|
| DELETE | `/api/v1/agents/{id}/request-update` | Update-Flag zuruecksetzen |
|
||||||
|
| POST | `/api/v1/agents/request-update-all` | Update-Flag fuer alle Agents setzen |
|
||||||
|
| POST | `/api/v1/agents/{id}/agent-update` | Legacy: Binary direkt via WebSocket pushen |
|
||||||
|
|
||||||
|
**Firmware-Upload Beispiel:**
|
||||||
|
```bash
|
||||||
|
# FreeBSD Agent hochladen
|
||||||
|
curl -sk -X POST "https://192.168.85.13:8443/api/v1/firmware/upload?version=1.0.2&platform=freebsd" \
|
||||||
|
-H "X-API-Key: 01532e5a7c9e70bf2757df77a2f5b9b9" \
|
||||||
|
--data-binary @build/rmm-agent
|
||||||
|
|
||||||
|
# Linux Agent hochladen
|
||||||
|
curl -sk -X POST "https://192.168.85.13:8443/api/v1/firmware/upload?version=1.0.2&platform=linux" \
|
||||||
|
-H "X-API-Key: 01532e5a7c9e70bf2757df77a2f5b9b9" \
|
||||||
|
--data-binary @build/rmm-agent-linux
|
||||||
|
|
||||||
|
# Update fuer einzelnen Agent anfordern
|
||||||
|
curl -sk -X POST "https://192.168.85.13:8443/api/v1/agents/e92e87a6.../request-update" \
|
||||||
|
-H "X-API-Key: 01532e5a7c9e70bf2757df77a2f5b9b9"
|
||||||
|
|
||||||
|
# Update fuer alle Agents anfordern
|
||||||
|
curl -sk -X POST "https://192.168.85.13:8443/api/v1/agents/request-update-all" \
|
||||||
|
-H "X-API-Key: 01532e5a7c9e70bf2757df77a2f5b9b9"
|
||||||
|
```
|
||||||
|
|
||||||
### Agent-Events
|
### Agent-Events
|
||||||
|
|
||||||
| Methode | Endpoint | Beschreibung |
|
| Methode | Endpoint | Beschreibung |
|
||||||
@ -691,6 +784,37 @@ Format: `[session_id_length:1][session_id][tcp_payload]`
|
|||||||
|
|
||||||
Tunnel-Daten werden als Binary WebSocket Messages uebertragen (kein Base64-Overhead).
|
Tunnel-Daten werden als Binary WebSocket Messages uebertragen (kein Base64-Overhead).
|
||||||
|
|
||||||
|
## Frontend
|
||||||
|
|
||||||
|
React + Vite + TailwindCSS Web-Frontend, deployed als statische Dateien auf Nginx.
|
||||||
|
|
||||||
|
- **Server**: 192.168.85.20 (Debian 13, Nginx)
|
||||||
|
- **Tech**: React 18, Vite, TailwindCSS, Recharts, Zustand, lucide-react
|
||||||
|
- **Theme**: Dark mit Orange-Akzent, komplett deutsch
|
||||||
|
- **Auth**: JWT Login (8h Token)
|
||||||
|
|
||||||
|
### Seiten
|
||||||
|
|
||||||
|
| Seite | Beschreibung |
|
||||||
|
|-------|-------------|
|
||||||
|
| Dashboard | Uebersicht aller Firewalls, Status-Kacheln, AgentPanel per Klick |
|
||||||
|
| Firewalls | Suchbare Tabelle, AgentPanel mit Tabs (Uebersicht, Interfaces, Dienste, Tunnel, VPN, WireGuard, Routen, DHCP, Zertifikate, Backups, Agent) |
|
||||||
|
| Tunnel | Globale Tunnel-Uebersicht ueber alle Firewalls |
|
||||||
|
| Firmware | Multi-Plattform Firmware-Upload, Agent-Update-Trigger |
|
||||||
|
| Kunden | CRUD Kundenverwaltung |
|
||||||
|
| Einstellungen | Benutzerverwaltung, Passworte aendern |
|
||||||
|
|
||||||
|
### Build & Deploy
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
npm run build # ~330 KB JS, ~32 KB CSS
|
||||||
|
ssh root@192.168.85.20 'rm -rf /var/www/html/assets/*' # Alte Hashes loeschen!
|
||||||
|
scp -r dist/* root@192.168.85.20:/var/www/html/
|
||||||
|
```
|
||||||
|
|
||||||
|
**Wichtig:** Vor Deploy immer `assets/` loeschen — Vite generiert Hash-basierte Dateinamen, alte Dateien bleiben sonst auf dem Server und Browser-Cache liefert 404.
|
||||||
|
|
||||||
## Dateistruktur
|
## Dateistruktur
|
||||||
|
|
||||||
```
|
```
|
||||||
@ -739,14 +863,45 @@ rmm/
|
|||||||
│ │ ├── handlers.go # REST API Handler (inkl. Agent-Status + Events)
|
│ │ ├── handlers.go # REST API Handler (inkl. Agent-Status + Events)
|
||||||
│ │ ├── tunnel_proxy.go # Tunnel + Exec + Update REST Endpoints
|
│ │ ├── tunnel_proxy.go # Tunnel + Exec + Update REST Endpoints
|
||||||
│ │ ├── backup.go # Config-Backup Endpoints (trigger, list, download, diff)
|
│ │ ├── backup.go # Config-Backup Endpoints (trigger, list, download, diff)
|
||||||
│ │ ├── wireguard.go # WireGuard Peer API Endpoints
|
│ │ ├── wireguard.go # WireGuard Peer API Endpoints
|
||||||
|
│ │ ├── firmware.go # Firmware Upload/Download/Info, Update-Request
|
||||||
|
│ │ ├── auth.go # Login, JWT Token, /me Endpoint
|
||||||
|
│ │ ├── customers.go # Kunden CRUD + Agent-Zuordnung
|
||||||
|
│ │ ├── users.go # Benutzer CRUD + Passwort-Aenderung
|
||||||
│ │ ├── metrics.go # Metriken-Abfrage Endpoints (raw + summary)
|
│ │ ├── metrics.go # Metriken-Abfrage Endpoints (raw + summary)
|
||||||
│ │ └── middleware.go # API-Key Auth, Logging
|
│ │ └── middleware.go # CombinedAuth (API-Key OR JWT), CORS, Logging
|
||||||
│ └── ws/
|
│ └── ws/
|
||||||
│ ├── handler.go # WebSocket Upgrade, Connection R/W Pumps
|
│ ├── handler.go # WebSocket Upgrade, Connection R/W Pumps
|
||||||
│ ├── hub.go # Agent-Registry, Message Routing
|
│ ├── hub.go # Agent-Registry, Message Routing
|
||||||
│ └── tunnel.go # Session-basierter Tunnel + Proxy Manager
|
│ └── tunnel.go # Session-basierter Tunnel + Proxy Manager
|
||||||
└── build/ # Kompilierte Binaries
|
├── updater/
|
||||||
|
│ ├── main.go # Separater Update-Daemon (pollt Firmware, ersetzt Agent-Binary)
|
||||||
|
│ └── go.mod
|
||||||
|
├── frontend/
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── App.jsx # Router + ProtectedRoute
|
||||||
|
│ │ ├── api/client.js # API Client (auth, agents, firmware, tunnels, etc.)
|
||||||
|
│ │ ├── stores/auth.js # Zustand Auth Store (JWT Token)
|
||||||
|
│ │ ├── layouts/AppLayout.jsx # Sidebar + Outlet
|
||||||
|
│ │ ├── components/
|
||||||
|
│ │ │ ├── AgentPanel.jsx # Side Panel mit Tabs (Uebersicht bis Agent)
|
||||||
|
│ │ │ └── StatusBadge.jsx # Online/Offline/Stale Badge
|
||||||
|
│ │ └── pages/
|
||||||
|
│ │ ├── Dashboard.jsx # Status-Kacheln + Agent-Liste
|
||||||
|
│ │ ├── Agents.jsx # Firewall-Tabelle
|
||||||
|
│ │ ├── AgentDetail.jsx # Detail-Ansicht (full page)
|
||||||
|
│ │ ├── Tunnels.jsx # Globale Tunnel-Uebersicht
|
||||||
|
│ │ ├── Firmware.jsx # Multi-Plattform Firmware + Update-Trigger
|
||||||
|
│ │ ├── Customers.jsx # Kunden CRUD
|
||||||
|
│ │ ├── SettingsPage.jsx # User-Management
|
||||||
|
│ │ └── Login.jsx # JWT Login
|
||||||
|
│ ├── vite.config.js
|
||||||
|
│ └── package.json
|
||||||
|
├── opnsense-plugin/
|
||||||
|
│ ├── install.sh # Self-contained Installer (Agent + Updater + MVC Plugin)
|
||||||
|
│ ├── build.sh
|
||||||
|
│ └── src/ # MVC Model, Controllers, Views, configd, rc.d
|
||||||
|
└── build/ # Kompilierte Binaries (rmm-backend, rmm-agent, rmm-updater)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Technische Details
|
## Technische Details
|
||||||
|
|||||||
@ -8,7 +8,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func CollectOPNsenseVersion() string {
|
func CollectOPNsenseVersion() string {
|
||||||
out, err := exec.Command("opnsense-version").Output()
|
out, err := exec.Command("/usr/local/sbin/opnsense-version").Output()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@ -18,7 +18,7 @@ func CollectOPNsenseVersion() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func CollectFreeBSDVersion() string {
|
func CollectFreeBSDVersion() string {
|
||||||
out, err := exec.Command("freebsd-version").Output()
|
out, err := exec.Command("/bin/freebsd-version").Output()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return sysctlGet("kern.osrelease")
|
return sysctlGet("kern.osrelease")
|
||||||
}
|
}
|
||||||
|
|||||||
@ -15,6 +15,8 @@ import (
|
|||||||
"github.com/cynfo/rmm-agent/ws"
|
"github.com/cynfo/rmm-agent/ws"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var Version = "dev"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
cfgPath := flag.String("config", "config.yaml", "Pfad zur Konfigurationsdatei")
|
cfgPath := flag.String("config", "config.yaml", "Pfad zur Konfigurationsdatei")
|
||||||
insecure := flag.Bool("insecure", false, "TLS-Zertifikatpruefung deaktivieren")
|
insecure := flag.Bool("insecure", false, "TLS-Zertifikatpruefung deaktivieren")
|
||||||
@ -29,7 +31,7 @@ func main() {
|
|||||||
cfg.Insecure = true
|
cfg.Insecure = true
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("RMM Agent startet: %s", cfg.AgentName)
|
log.Printf("RMM Agent v%s startet: %s", Version, cfg.AgentName)
|
||||||
log.Printf("Backend: %s, Intervall: %ds", cfg.BackendURL, cfg.IntervalSeconds)
|
log.Printf("Backend: %s, Intervall: %ds", cfg.BackendURL, cfg.IntervalSeconds)
|
||||||
|
|
||||||
c := client.New(cfg.BackendURL, cfg.APIKey, cfg.Insecure)
|
c := client.New(cfg.BackendURL, cfg.APIKey, cfg.Insecure)
|
||||||
@ -57,6 +59,7 @@ func main() {
|
|||||||
"hostname": hostname,
|
"hostname": hostname,
|
||||||
"ip": getLocalIP(),
|
"ip": getLocalIP(),
|
||||||
"opnsense_version": collector.CollectOPNsenseVersion(),
|
"opnsense_version": collector.CollectOPNsenseVersion(),
|
||||||
|
"agent_version": Version,
|
||||||
}
|
}
|
||||||
if agentID != "" {
|
if agentID != "" {
|
||||||
regReq["agent_id"] = agentID
|
regReq["agent_id"] = agentID
|
||||||
@ -124,7 +127,8 @@ func sendHeartbeat(c *client.Client, agentID string) error {
|
|||||||
cronJobs := collector.CollectCron()
|
cronJobs := collector.CollectCron()
|
||||||
|
|
||||||
req := map[string]interface{}{
|
req := map[string]interface{}{
|
||||||
"agent_id": agentID,
|
"agent_id": agentID,
|
||||||
|
"agent_version": Version,
|
||||||
"system_data": map[string]interface{}{
|
"system_data": map[string]interface{}{
|
||||||
"agent_id": agentID,
|
"agent_id": agentID,
|
||||||
"hostname": collector.CollectHostname(),
|
"hostname": collector.CollectHostname(),
|
||||||
|
|||||||
@ -99,7 +99,6 @@ func (c *Client) reconnectLoop() {
|
|||||||
|
|
||||||
select {
|
select {
|
||||||
case <-time.After(backoff):
|
case <-time.After(backoff):
|
||||||
// Exponential backoff mit Maximum
|
|
||||||
backoff = time.Duration(float64(backoff) * 1.5)
|
backoff = time.Duration(float64(backoff) * 1.5)
|
||||||
if backoff > maxBackoff {
|
if backoff > maxBackoff {
|
||||||
backoff = maxBackoff
|
backoff = maxBackoff
|
||||||
@ -110,14 +109,38 @@ func (c *Client) reconnectLoop() {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verbindung erfolgreich - backoff zurücksetzen
|
connStart := time.Now()
|
||||||
backoff = c.reconnectInterval
|
|
||||||
log.Println("WebSocket-Verbindung hergestellt")
|
log.Println("WebSocket-Verbindung hergestellt")
|
||||||
|
|
||||||
// Ping/Pong und Message-Handling starten
|
// Ping/Pong und Message-Handling starten
|
||||||
c.runConnection()
|
c.runConnection()
|
||||||
|
|
||||||
log.Println("WebSocket-Verbindung getrennt")
|
connDuration := time.Since(connStart)
|
||||||
|
log.Printf("WebSocket-Verbindung getrennt (Dauer: %v)", connDuration)
|
||||||
|
|
||||||
|
// Alte Verbindung explizit schliessen
|
||||||
|
c.connMux.Lock()
|
||||||
|
if c.conn != nil {
|
||||||
|
c.conn.Close()
|
||||||
|
c.conn = nil
|
||||||
|
}
|
||||||
|
c.connMux.Unlock()
|
||||||
|
|
||||||
|
// Minimum-Delay zwischen Reconnects (verhindert Tight-Loop)
|
||||||
|
if connDuration < 5*time.Second {
|
||||||
|
backoff = time.Duration(float64(backoff) * 1.5)
|
||||||
|
if backoff > maxBackoff {
|
||||||
|
backoff = maxBackoff
|
||||||
|
}
|
||||||
|
log.Printf("Verbindung zu kurz, warte %v vor Reconnect", backoff)
|
||||||
|
select {
|
||||||
|
case <-time.After(backoff):
|
||||||
|
case <-c.ctx.Done():
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
backoff = c.reconnectInterval
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -206,9 +229,7 @@ func (c *Client) runConnection() {
|
|||||||
go c.handleMessage(msg)
|
go c.handleMessage(msg)
|
||||||
|
|
||||||
case err := <-errChan:
|
case err := <-errChan:
|
||||||
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
|
log.Printf("WebSocket-Lesefehler: %v", err)
|
||||||
log.Printf("WebSocket-Fehler: %v", err)
|
|
||||||
}
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -58,6 +58,8 @@ func (h *Handler) HandleCommand(msg Message) {
|
|||||||
response.Data = map[string]interface{}{"message": "tunnel_open deprecated, use tunnel_connect"}
|
response.Data = map[string]interface{}{"message": "tunnel_open deprecated, use tunnel_connect"}
|
||||||
case "tunnel_close":
|
case "tunnel_close":
|
||||||
response.Status = "ok"
|
response.Status = "ok"
|
||||||
|
case "agent_update":
|
||||||
|
response = h.handleAgentUpdate(msg)
|
||||||
default:
|
default:
|
||||||
response.Status = "error"
|
response.Status = "error"
|
||||||
response.Error = fmt.Sprintf("Unbekanntes Command: %s", msg.Command)
|
response.Error = fmt.Sprintf("Unbekanntes Command: %s", msg.Command)
|
||||||
@ -558,6 +560,89 @@ func (h *Handler) parsePkgUpgrade(output string) []map[string]string {
|
|||||||
return packages
|
return packages
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *Handler) handleAgentUpdate(msg Message) Message {
|
||||||
|
response := Message{Type: "response", ID: msg.ID}
|
||||||
|
|
||||||
|
// Binary kommt als Base64 im Data-Feld
|
||||||
|
data, ok := msg.Data.(map[string]interface{})
|
||||||
|
if !ok {
|
||||||
|
response.Status = "error"
|
||||||
|
response.Error = "Ungueltige Daten"
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
binaryB64, _ := data["binary"].(string)
|
||||||
|
expectedHash, _ := data["hash"].(string)
|
||||||
|
newVersion, _ := data["version"].(string)
|
||||||
|
|
||||||
|
if binaryB64 == "" || expectedHash == "" {
|
||||||
|
response.Status = "error"
|
||||||
|
response.Error = "Binary oder Hash fehlt"
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Agent-Update empfangen: Version %s, Hash %s", newVersion, expectedHash[:16])
|
||||||
|
|
||||||
|
// Base64 dekodieren
|
||||||
|
binary, err := base64.StdEncoding.DecodeString(binaryB64)
|
||||||
|
if err != nil {
|
||||||
|
response.Status = "error"
|
||||||
|
response.Error = fmt.Sprintf("Base64-Dekodierung fehlgeschlagen: %v", err)
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash pruefen
|
||||||
|
hash := sha256.Sum256(binary)
|
||||||
|
actualHash := hex.EncodeToString(hash[:])
|
||||||
|
if actualHash != expectedHash {
|
||||||
|
response.Status = "error"
|
||||||
|
response.Error = fmt.Sprintf("Hash-Mismatch: erwartet %s, bekommen %s", expectedHash[:16], actualHash[:16])
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
// Aktuelles Binary finden
|
||||||
|
binaryPath := "/usr/local/rmm/rmm-agent"
|
||||||
|
if _, err := os.Stat(binaryPath); os.IsNotExist(err) {
|
||||||
|
// Fallback: eigener Pfad
|
||||||
|
binaryPath, _ = os.Executable()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Backup vom alten Binary
|
||||||
|
backupPath := binaryPath + ".old"
|
||||||
|
if err := os.Rename(binaryPath, backupPath); err != nil {
|
||||||
|
response.Status = "error"
|
||||||
|
response.Error = fmt.Sprintf("Backup fehlgeschlagen: %v", err)
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
// Neues Binary schreiben
|
||||||
|
if err := os.WriteFile(binaryPath, binary, 0755); err != nil {
|
||||||
|
// Rollback
|
||||||
|
os.Rename(backupPath, binaryPath)
|
||||||
|
response.Status = "error"
|
||||||
|
response.Error = fmt.Sprintf("Binary schreiben fehlgeschlagen: %v", err)
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Neues Binary geschrieben: %s (%d bytes)", binaryPath, len(binary))
|
||||||
|
|
||||||
|
response.Status = "ok"
|
||||||
|
response.Data = map[string]interface{}{
|
||||||
|
"message": fmt.Sprintf("Update auf %s erfolgreich, Neustart...", newVersion),
|
||||||
|
"old_version": data["old_version"],
|
||||||
|
"new_version": newVersion,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response senden, dann Neustart
|
||||||
|
go func() {
|
||||||
|
time.Sleep(2 * time.Second)
|
||||||
|
log.Printf("Agent-Neustart nach Update auf %s", newVersion)
|
||||||
|
exec.Command("/usr/sbin/service", "rmm_agent", "restart").Run()
|
||||||
|
}()
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
// SendSessionData schickt Tunnel-Daten als Binary-Message zurueck zum Backend
|
// SendSessionData schickt Tunnel-Daten als Binary-Message zurueck zum Backend
|
||||||
func (h *Handler) SendSessionData(sessionID string, data []byte) error {
|
func (h *Handler) SendSessionData(sessionID string, data []byte) error {
|
||||||
idBytes := []byte(sessionID)
|
idBytes := []byte(sessionID)
|
||||||
|
|||||||
219
backend/api/firmware.go
Normal file
219
backend/api/firmware.go
Normal file
@ -0,0 +1,219 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/cynfo/rmm-backend/ws"
|
||||||
|
)
|
||||||
|
|
||||||
|
// POST /api/v1/firmware/upload — Neues Agent-Binary hochladen
|
||||||
|
func (h *Handler) uploadFirmware(w http.ResponseWriter, r *http.Request) {
|
||||||
|
version := r.URL.Query().Get("version")
|
||||||
|
if version == "" {
|
||||||
|
writeError(w, http.StatusBadRequest, "version Parameter erforderlich")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
platform := r.URL.Query().Get("platform")
|
||||||
|
if platform == "" {
|
||||||
|
platform = "freebsd" // Default fuer OPNsense
|
||||||
|
}
|
||||||
|
// Validieren
|
||||||
|
validPlatforms := map[string]bool{"freebsd": true, "linux": true, "windows": true}
|
||||||
|
if !validPlatforms[platform] {
|
||||||
|
writeError(w, http.StatusBadRequest, "Ungueltige Plattform (freebsd, linux, windows)")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Binary aus Body lesen (max 50MB)
|
||||||
|
r.Body = http.MaxBytesReader(w, r.Body, 50*1024*1024)
|
||||||
|
binary, err := io.ReadAll(r.Body)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "Binary lesen fehlgeschlagen")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(binary) == 0 {
|
||||||
|
writeError(w, http.StatusBadRequest, "Leeres Binary")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
hash := sha256.Sum256(binary)
|
||||||
|
hashStr := hex.EncodeToString(hash[:])
|
||||||
|
|
||||||
|
if err := h.db.SaveAgentFirmware(version, platform, hashStr, binary); err != nil {
|
||||||
|
log.Printf("Firmware speichern fehlgeschlagen: %v", err)
|
||||||
|
writeError(w, http.StatusInternalServerError, "Speichern fehlgeschlagen")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Agent-Firmware v%s (%s) hochgeladen (%d bytes, Hash: %s)", version, platform, len(binary), hashStr[:16])
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||||
|
"version": version,
|
||||||
|
"platform": platform,
|
||||||
|
"hash": hashStr,
|
||||||
|
"size": len(binary),
|
||||||
|
"message": "Firmware hochgeladen",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /api/v1/firmware — Firmware-Info (alle Plattformen oder spezifisch)
|
||||||
|
func (h *Handler) getFirmwareInfo(w http.ResponseWriter, r *http.Request) {
|
||||||
|
platform := r.URL.Query().Get("platform")
|
||||||
|
|
||||||
|
if platform == "" {
|
||||||
|
// Alle Plattformen auflisten
|
||||||
|
all, err := h.db.GetAllFirmwareInfo()
|
||||||
|
if err != nil || len(all) == 0 {
|
||||||
|
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||||
|
"available": false,
|
||||||
|
"message": "Keine Firmware hochgeladen",
|
||||||
|
"platforms": []interface{}{},
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||||
|
"available": true,
|
||||||
|
"platforms": all,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
version, hash, size, err := h.db.GetFirmwareInfo(platform)
|
||||||
|
if err != nil {
|
||||||
|
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||||
|
"available": false,
|
||||||
|
"platform": platform,
|
||||||
|
"message": "Keine Firmware fuer diese Plattform",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||||
|
"available": true,
|
||||||
|
"platform": platform,
|
||||||
|
"version": version,
|
||||||
|
"hash": hash,
|
||||||
|
"size": size,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /api/v1/firmware/download — Binary herunterladen (fuer Updater)
|
||||||
|
func (h *Handler) downloadFirmware(w http.ResponseWriter, r *http.Request) {
|
||||||
|
platform := r.URL.Query().Get("platform")
|
||||||
|
if platform == "" {
|
||||||
|
platform = "freebsd"
|
||||||
|
}
|
||||||
|
version, hash, binary, err := h.db.GetLatestFirmware(platform)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusNotFound, "Keine Firmware verfuegbar")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/octet-stream")
|
||||||
|
w.Header().Set("Content-Disposition", "attachment; filename=rmm-agent")
|
||||||
|
w.Header().Set("X-Firmware-Version", version)
|
||||||
|
w.Header().Set("X-Firmware-Hash", hash)
|
||||||
|
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(binary)))
|
||||||
|
w.Write(binary)
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /api/v1/agents/{id}/request-update — Update-Flag setzen
|
||||||
|
func (h *Handler) requestUpdate(w http.ResponseWriter, r *http.Request) {
|
||||||
|
agentID := r.PathValue("id")
|
||||||
|
if err := h.db.SetUpdateRequest(agentID, true); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "Fehler beim Setzen des Update-Flags")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("Update angefordert fuer Agent %s", agentID)
|
||||||
|
writeJSON(w, http.StatusOK, map[string]interface{}{"message": "Update angefordert", "agent_id": agentID})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DELETE /api/v1/agents/{id}/request-update — Update-Flag loeschen
|
||||||
|
func (h *Handler) cancelUpdate(w http.ResponseWriter, r *http.Request) {
|
||||||
|
agentID := r.PathValue("id")
|
||||||
|
h.db.ClearUpdateRequest(agentID)
|
||||||
|
writeJSON(w, http.StatusOK, map[string]interface{}{"message": "Update-Anforderung geloescht", "agent_id": agentID})
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /api/v1/agents/request-update-all — Update-Flag fuer alle setzen
|
||||||
|
func (h *Handler) requestUpdateAll(w http.ResponseWriter, r *http.Request) {
|
||||||
|
count, err := h.db.SetUpdateRequestAll(true)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "Fehler")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("Update angefordert fuer %d Agents", count)
|
||||||
|
writeJSON(w, http.StatusOK, map[string]interface{}{"message": fmt.Sprintf("Update fuer %d Agents angefordert", count), "count": count})
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /api/v1/agents/{id}/agent-update — Update an einzelnen Agent pushen
|
||||||
|
func (h *Handler) pushAgentUpdate(hub *ws.Hub) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
agentID := r.PathValue("id")
|
||||||
|
|
||||||
|
// TODO: Agent-Plattform aus DB lesen; fuer jetzt default freebsd
|
||||||
|
version, hash, binary, err := h.db.GetLatestFirmware("freebsd")
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusNotFound, "Keine Firmware verfuegbar")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agent-Version pruefen
|
||||||
|
agent, _, err := h.db.GetAgent(agentID)
|
||||||
|
if err != nil || agent == nil {
|
||||||
|
writeError(w, http.StatusNotFound, "Agent nicht gefunden")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if agent.AgentVersion == version {
|
||||||
|
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||||
|
"message": "Agent ist bereits auf dem neuesten Stand",
|
||||||
|
"current_version": agent.AgentVersion,
|
||||||
|
"target_version": version,
|
||||||
|
"updated": false,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Binary als Base64 an Agent senden
|
||||||
|
binaryB64 := base64.StdEncoding.EncodeToString(binary)
|
||||||
|
|
||||||
|
cmdID := fmt.Sprintf("agent-update-%s", agentID[:8])
|
||||||
|
cmd := map[string]interface{}{
|
||||||
|
"type": "command",
|
||||||
|
"id": cmdID,
|
||||||
|
"command": "agent_update",
|
||||||
|
"data": map[string]interface{}{
|
||||||
|
"binary": binaryB64,
|
||||||
|
"hash": hash,
|
||||||
|
"version": version,
|
||||||
|
"old_version": agent.AgentVersion,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
cmdJSON, _ := json.Marshal(cmd)
|
||||||
|
if err := hub.SendToAgent(agentID, cmdJSON); err != nil {
|
||||||
|
writeError(w, http.StatusBadGateway, fmt.Sprintf("Agent nicht erreichbar: %v", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Agent-Update v%s an %s gesendet (%d bytes)", version, agent.Name, len(binary))
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||||
|
"message": fmt.Sprintf("Update v%s an %s gesendet", version, agent.Name),
|
||||||
|
"current_version": agent.AgentVersion,
|
||||||
|
"target_version": version,
|
||||||
|
"updated": true,
|
||||||
|
"size": len(binary),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -53,6 +53,15 @@ func (h *Handler) SetupRoutes(mux *http.ServeMux, hub *ws.Hub) {
|
|||||||
mux.HandleFunc("PUT /api/v1/users/{id}/password", h.changePassword)
|
mux.HandleFunc("PUT /api/v1/users/{id}/password", h.changePassword)
|
||||||
mux.HandleFunc("DELETE /api/v1/users/{id}", h.deleteUser)
|
mux.HandleFunc("DELETE /api/v1/users/{id}", h.deleteUser)
|
||||||
|
|
||||||
|
// Firmware/Agent-Update Routes
|
||||||
|
mux.HandleFunc("GET /api/v1/firmware", h.getFirmwareInfo)
|
||||||
|
mux.HandleFunc("POST /api/v1/firmware/upload", h.uploadFirmware)
|
||||||
|
mux.HandleFunc("GET /api/v1/firmware/download", h.downloadFirmware)
|
||||||
|
mux.HandleFunc("POST /api/v1/agents/{id}/agent-update", h.pushAgentUpdate(hub))
|
||||||
|
mux.HandleFunc("POST /api/v1/agents/{id}/request-update", h.requestUpdate)
|
||||||
|
mux.HandleFunc("DELETE /api/v1/agents/{id}/request-update", h.cancelUpdate)
|
||||||
|
mux.HandleFunc("POST /api/v1/agents/request-update-all", h.requestUpdateAll)
|
||||||
|
|
||||||
// WebSocket und Tunnel-Routes
|
// WebSocket und Tunnel-Routes
|
||||||
h.setupTunnelRoutes(mux, hub)
|
h.setupTunnelRoutes(mux, hub)
|
||||||
}
|
}
|
||||||
@ -115,6 +124,7 @@ func (h *Handler) registerAgent(w http.ResponseWriter, r *http.Request) {
|
|||||||
Hostname: req.Hostname,
|
Hostname: req.Hostname,
|
||||||
IP: req.IP,
|
IP: req.IP,
|
||||||
OPNsenseVersion: req.OPNsenseVersion,
|
OPNsenseVersion: req.OPNsenseVersion,
|
||||||
|
AgentVersion: req.AgentVersion,
|
||||||
RegisteredAt: time.Now().UTC(),
|
RegisteredAt: time.Now().UTC(),
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -148,6 +158,11 @@ func (h *Handler) heartbeat(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Agent-Version aktualisieren
|
||||||
|
if req.AgentVersion != "" {
|
||||||
|
h.db.UpdateAgentVersion(req.AgentID, req.AgentVersion)
|
||||||
|
}
|
||||||
|
|
||||||
if err := h.db.SaveSystemData(req.AgentID, &req.SystemData); err != nil {
|
if err := h.db.SaveSystemData(req.AgentID, &req.SystemData); err != nil {
|
||||||
if strings.Contains(err.Error(), "nicht gefunden") {
|
if strings.Contains(err.Error(), "nicht gefunden") {
|
||||||
writeError(w, http.StatusNotFound, "Agent nicht gefunden")
|
writeError(w, http.StatusNotFound, "Agent nicht gefunden")
|
||||||
@ -158,7 +173,23 @@ func (h *Handler) heartbeat(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
writeJSON(w, http.StatusOK, models.HeartbeatResponse{Message: "OK"})
|
resp := models.HeartbeatResponse{Message: "OK"}
|
||||||
|
|
||||||
|
// Pruefen ob Update ansteht (default freebsd fuer OPNsense)
|
||||||
|
if h.db.IsUpdateRequested(req.AgentID) {
|
||||||
|
if version, hash, _, err := h.db.GetFirmwareInfo("freebsd"); err == nil {
|
||||||
|
if version != req.AgentVersion {
|
||||||
|
resp.UpdateAvailable = true
|
||||||
|
resp.UpdateVersion = version
|
||||||
|
resp.UpdateHash = hash
|
||||||
|
} else {
|
||||||
|
// Gleiche Version — Flag zuruecksetzen
|
||||||
|
h.db.ClearUpdateRequest(req.AgentID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, resp)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GET /api/v1/agents
|
// GET /api/v1/agents
|
||||||
|
|||||||
@ -67,6 +67,7 @@ func (d *Database) migrate() error {
|
|||||||
hostname TEXT NOT NULL,
|
hostname TEXT NOT NULL,
|
||||||
ip TEXT NOT NULL,
|
ip TEXT NOT NULL,
|
||||||
opnsense_version TEXT NOT NULL DEFAULT '',
|
opnsense_version TEXT NOT NULL DEFAULT '',
|
||||||
|
agent_version TEXT NOT NULL DEFAULT '',
|
||||||
registered_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
registered_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
last_heartbeat TIMESTAMPTZ
|
last_heartbeat TIMESTAMPTZ
|
||||||
);
|
);
|
||||||
@ -124,6 +125,27 @@ func (d *Database) migrate() error {
|
|||||||
d.db.Exec("ALTER TABLE agents ADD COLUMN IF NOT EXISTS customer_id INTEGER REFERENCES customers(id)")
|
d.db.Exec("ALTER TABLE agents ADD COLUMN IF NOT EXISTS customer_id INTEGER REFERENCES customers(id)")
|
||||||
d.db.Exec("CREATE INDEX IF NOT EXISTS idx_agents_customer ON agents(customer_id)")
|
d.db.Exec("CREATE INDEX IF NOT EXISTS idx_agents_customer ON agents(customer_id)")
|
||||||
|
|
||||||
|
// Agents um agent_version und update_requested erweitern
|
||||||
|
d.db.Exec("ALTER TABLE agents ADD COLUMN IF NOT EXISTS agent_version TEXT NOT NULL DEFAULT ''")
|
||||||
|
d.db.Exec("ALTER TABLE agents ADD COLUMN IF NOT EXISTS update_requested BOOLEAN NOT NULL DEFAULT FALSE")
|
||||||
|
|
||||||
|
// Agent-Firmware Tabelle (Multi-Plattform)
|
||||||
|
d.db.Exec(`CREATE TABLE IF NOT EXISTS agent_firmware (
|
||||||
|
version TEXT PRIMARY KEY,
|
||||||
|
hash TEXT NOT NULL,
|
||||||
|
binary_data BYTEA NOT NULL,
|
||||||
|
uploaded_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
)`)
|
||||||
|
// Platform-Spalte hinzufuegen (default freebsd fuer bestehende Eintraege)
|
||||||
|
d.db.Exec("ALTER TABLE agent_firmware DROP CONSTRAINT IF EXISTS agent_firmware_pkey")
|
||||||
|
d.db.Exec("ALTER TABLE agent_firmware ADD COLUMN IF NOT EXISTS platform TEXT NOT NULL DEFAULT 'freebsd'")
|
||||||
|
// Neuer Primary Key: version + platform
|
||||||
|
d.db.Exec(`DO $$ BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'agent_firmware_version_platform_key') THEN
|
||||||
|
ALTER TABLE agent_firmware ADD CONSTRAINT agent_firmware_version_platform_key UNIQUE (version, platform);
|
||||||
|
END IF;
|
||||||
|
END $$`)
|
||||||
|
|
||||||
// Metrics Hypertable
|
// Metrics Hypertable
|
||||||
metricsSchema := `
|
metricsSchema := `
|
||||||
CREATE TABLE IF NOT EXISTS metrics (
|
CREATE TABLE IF NOT EXISTS metrics (
|
||||||
@ -220,14 +242,15 @@ func (d *Database) Close() error {
|
|||||||
|
|
||||||
func (d *Database) RegisterAgent(agent *models.Agent) error {
|
func (d *Database) RegisterAgent(agent *models.Agent) error {
|
||||||
_, err := d.db.Exec(`
|
_, err := d.db.Exec(`
|
||||||
INSERT INTO agents (id, name, hostname, ip, opnsense_version, registered_at)
|
INSERT INTO agents (id, name, hostname, ip, opnsense_version, agent_version, registered_at)
|
||||||
VALUES ($1, $2, $3, $4, $5, $6)
|
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||||
ON CONFLICT(id) DO UPDATE SET
|
ON CONFLICT(id) DO UPDATE SET
|
||||||
name=EXCLUDED.name,
|
name=EXCLUDED.name,
|
||||||
hostname=EXCLUDED.hostname,
|
hostname=EXCLUDED.hostname,
|
||||||
ip=EXCLUDED.ip,
|
ip=EXCLUDED.ip,
|
||||||
opnsense_version=EXCLUDED.opnsense_version
|
opnsense_version=EXCLUDED.opnsense_version,
|
||||||
`, agent.ID, agent.Name, agent.Hostname, agent.IP, agent.OPNsenseVersion, agent.RegisteredAt.UTC())
|
agent_version=EXCLUDED.agent_version
|
||||||
|
`, agent.ID, agent.Name, agent.Hostname, agent.IP, agent.OPNsenseVersion, agent.AgentVersion, agent.RegisteredAt.UTC())
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -342,7 +365,7 @@ func (d *Database) writeMetrics(tx *sql.Tx, agentID string, ts time.Time, data *
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d *Database) GetAgents() ([]models.Agent, error) {
|
func (d *Database) GetAgents() ([]models.Agent, error) {
|
||||||
rows, err := d.db.Query("SELECT id, name, hostname, ip, opnsense_version, registered_at, last_heartbeat, customer_id FROM agents ORDER BY name")
|
rows, err := d.db.Query("SELECT id, name, hostname, ip, opnsense_version, agent_version, registered_at, last_heartbeat, customer_id, update_requested FROM agents ORDER BY name")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -354,7 +377,7 @@ func (d *Database) GetAgents() ([]models.Agent, error) {
|
|||||||
var lastHB sql.NullTime
|
var lastHB sql.NullTime
|
||||||
var custID sql.NullInt64
|
var custID sql.NullInt64
|
||||||
|
|
||||||
if err := rows.Scan(&a.ID, &a.Name, &a.Hostname, &a.IP, &a.OPNsenseVersion, &a.RegisteredAt, &lastHB, &custID); err != nil {
|
if err := rows.Scan(&a.ID, &a.Name, &a.Hostname, &a.IP, &a.OPNsenseVersion, &a.AgentVersion, &a.RegisteredAt, &lastHB, &custID, &a.UpdateRequested); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if lastHB.Valid {
|
if lastHB.Valid {
|
||||||
@ -399,9 +422,9 @@ func (d *Database) GetAgent(id string) (*models.Agent, *models.SystemData, error
|
|||||||
var custID sql.NullInt64
|
var custID sql.NullInt64
|
||||||
|
|
||||||
err := d.db.QueryRow(
|
err := d.db.QueryRow(
|
||||||
"SELECT id, name, hostname, ip, opnsense_version, registered_at, last_heartbeat, customer_id FROM agents WHERE id = $1",
|
"SELECT id, name, hostname, ip, opnsense_version, agent_version, registered_at, last_heartbeat, customer_id, update_requested FROM agents WHERE id = $1",
|
||||||
id,
|
id,
|
||||||
).Scan(&a.ID, &a.Name, &a.Hostname, &a.IP, &a.OPNsenseVersion, &a.RegisteredAt, &lastHB, &custID)
|
).Scan(&a.ID, &a.Name, &a.Hostname, &a.IP, &a.OPNsenseVersion, &a.AgentVersion, &a.RegisteredAt, &lastHB, &custID, &a.UpdateRequested)
|
||||||
|
|
||||||
if err == sql.ErrNoRows {
|
if err == sql.ErrNoRows {
|
||||||
return nil, nil, nil
|
return nil, nil, nil
|
||||||
@ -452,6 +475,96 @@ func (d *Database) GetSystemData(agentID string) (*models.SystemData, error) {
|
|||||||
return &data, nil
|
return &data, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (d *Database) UpdateAgentVersion(id, version string) error {
|
||||||
|
_, err := d.db.Exec("UPDATE agents SET agent_version = $1 WHERE id = $2", version, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update-Request Flag setzen/lesen/loeschen
|
||||||
|
func (d *Database) SetUpdateRequest(id string, requested bool) error {
|
||||||
|
_, err := d.db.Exec("UPDATE agents SET update_requested = $1 WHERE id = $2", requested, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Database) IsUpdateRequested(id string) bool {
|
||||||
|
var requested bool
|
||||||
|
err := d.db.QueryRow("SELECT update_requested FROM agents WHERE id = $1", id).Scan(&requested)
|
||||||
|
return err == nil && requested
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Database) ClearUpdateRequest(id string) error {
|
||||||
|
return d.SetUpdateRequest(id, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Alle Agents mit Update-Flag setzen
|
||||||
|
func (d *Database) SetUpdateRequestAll(requested bool) (int64, error) {
|
||||||
|
res, err := d.db.Exec("UPDATE agents SET update_requested = $1", requested)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return res.RowsAffected()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agent-Firmware speichern (pro Plattform)
|
||||||
|
func (d *Database) SaveAgentFirmware(version, platform, hash string, binary []byte) error {
|
||||||
|
_, err := d.db.Exec(`
|
||||||
|
INSERT INTO agent_firmware (version, platform, hash, binary_data, uploaded_at)
|
||||||
|
VALUES ($1, $2, $3, $4, NOW())
|
||||||
|
ON CONFLICT(version, platform) DO UPDATE SET hash=EXCLUDED.hash, binary_data=EXCLUDED.binary_data, uploaded_at=NOW()
|
||||||
|
`, version, platform, hash, binary)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Database) GetLatestFirmware(platform string) (string, string, []byte, error) {
|
||||||
|
var version, hash string
|
||||||
|
var binary []byte
|
||||||
|
err := d.db.QueryRow("SELECT version, hash, binary_data FROM agent_firmware WHERE platform = $1 ORDER BY uploaded_at DESC LIMIT 1", platform).Scan(&version, &hash, &binary)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", nil, err
|
||||||
|
}
|
||||||
|
return version, hash, binary, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Database) GetFirmwareInfo(platform string) (string, string, int, error) {
|
||||||
|
var version, hash string
|
||||||
|
var size int
|
||||||
|
err := d.db.QueryRow("SELECT version, hash, length(binary_data) FROM agent_firmware WHERE platform = $1 ORDER BY uploaded_at DESC LIMIT 1", platform).Scan(&version, &hash, &size)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", 0, err
|
||||||
|
}
|
||||||
|
return version, hash, size, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Alle Plattform-Firmwares auflisten
|
||||||
|
func (d *Database) GetAllFirmwareInfo() ([]map[string]interface{}, error) {
|
||||||
|
rows, err := d.db.Query(`
|
||||||
|
SELECT DISTINCT ON (platform) platform, version, hash, length(binary_data) as size, uploaded_at
|
||||||
|
FROM agent_firmware ORDER BY platform, uploaded_at DESC
|
||||||
|
`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var results []map[string]interface{}
|
||||||
|
for rows.Next() {
|
||||||
|
var platform, version, hash string
|
||||||
|
var size int
|
||||||
|
var uploadedAt time.Time
|
||||||
|
if err := rows.Scan(&platform, &version, &hash, &size, &uploadedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
results = append(results, map[string]interface{}{
|
||||||
|
"platform": platform,
|
||||||
|
"version": version,
|
||||||
|
"hash": hash,
|
||||||
|
"size": size,
|
||||||
|
"uploaded_at": uploadedAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return results, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (d *Database) DeleteAgent(id string) (bool, error) {
|
func (d *Database) DeleteAgent(id string) (bool, error) {
|
||||||
res, err := d.db.Exec("DELETE FROM agents WHERE id = $1", id)
|
res, err := d.db.Exec("DELETE FROM agents WHERE id = $1", id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@ -9,9 +9,11 @@ type Agent struct {
|
|||||||
Hostname string `json:"hostname"`
|
Hostname string `json:"hostname"`
|
||||||
IP string `json:"ip"`
|
IP string `json:"ip"`
|
||||||
OPNsenseVersion string `json:"opnsense_version"`
|
OPNsenseVersion string `json:"opnsense_version"`
|
||||||
|
AgentVersion string `json:"agent_version,omitempty"`
|
||||||
RegisteredAt time.Time `json:"registered_at"`
|
RegisteredAt time.Time `json:"registered_at"`
|
||||||
LastHeartbeat *time.Time `json:"last_heartbeat,omitempty"`
|
LastHeartbeat *time.Time `json:"last_heartbeat,omitempty"`
|
||||||
CustomerID *int `json:"customer_id,omitempty"`
|
CustomerID *int `json:"customer_id,omitempty"`
|
||||||
|
UpdateRequested bool `json:"update_requested"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AgentResponse erweitert Agent um den berechneten Status
|
// AgentResponse erweitert Agent um den berechneten Status
|
||||||
@ -52,6 +54,7 @@ type RegisterRequest struct {
|
|||||||
Hostname string `json:"hostname"`
|
Hostname string `json:"hostname"`
|
||||||
IP string `json:"ip"`
|
IP string `json:"ip"`
|
||||||
OPNsenseVersion string `json:"opnsense_version"`
|
OPNsenseVersion string `json:"opnsense_version"`
|
||||||
|
AgentVersion string `json:"agent_version,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// RegisterResponse
|
// RegisterResponse
|
||||||
|
|||||||
@ -172,11 +172,15 @@ type CronJob struct {
|
|||||||
|
|
||||||
// HeartbeatRequest
|
// HeartbeatRequest
|
||||||
type HeartbeatRequest struct {
|
type HeartbeatRequest struct {
|
||||||
AgentID string `json:"agent_id"`
|
AgentID string `json:"agent_id"`
|
||||||
SystemData SystemData `json:"system_data"`
|
AgentVersion string `json:"agent_version,omitempty"`
|
||||||
|
SystemData SystemData `json:"system_data"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// HeartbeatResponse
|
// HeartbeatResponse
|
||||||
type HeartbeatResponse struct {
|
type HeartbeatResponse struct {
|
||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
|
UpdateAvailable bool `json:"update_available,omitempty"`
|
||||||
|
UpdateVersion string `json:"update_version,omitempty"`
|
||||||
|
UpdateHash string `json:"update_hash,omitempty"`
|
||||||
}
|
}
|
||||||
|
|||||||
@ -8,6 +8,8 @@ import Agents from './pages/Agents'
|
|||||||
import AgentDetail from './pages/AgentDetail'
|
import AgentDetail from './pages/AgentDetail'
|
||||||
import Customers from './pages/Customers'
|
import Customers from './pages/Customers'
|
||||||
import SettingsPage from './pages/SettingsPage'
|
import SettingsPage from './pages/SettingsPage'
|
||||||
|
import Tunnels from './pages/Tunnels'
|
||||||
|
import Firmware from './pages/Firmware'
|
||||||
|
|
||||||
function ProtectedRoute({ children }) {
|
function ProtectedRoute({ children }) {
|
||||||
const { isAuthenticated, loading } = useAuthStore()
|
const { isAuthenticated, loading } = useAuthStore()
|
||||||
@ -49,7 +51,9 @@ export default function App() {
|
|||||||
<Route index element={<Dashboard />} />
|
<Route index element={<Dashboard />} />
|
||||||
<Route path="agents" element={<Agents />} />
|
<Route path="agents" element={<Agents />} />
|
||||||
<Route path="agents/:id" element={<AgentDetail />} />
|
<Route path="agents/:id" element={<AgentDetail />} />
|
||||||
|
<Route path="tunnels" element={<Tunnels />} />
|
||||||
<Route path="customers" element={<Customers />} />
|
<Route path="customers" element={<Customers />} />
|
||||||
|
<Route path="firmware" element={<Firmware />} />
|
||||||
<Route path="settings" element={<SettingsPage />} />
|
<Route path="settings" element={<SettingsPage />} />
|
||||||
</Route>
|
</Route>
|
||||||
</Routes>
|
</Routes>
|
||||||
|
|||||||
@ -52,7 +52,9 @@ class ApiClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
post(path, body) {
|
post(path, body) {
|
||||||
return this.request(path, { method: 'POST', body: JSON.stringify(body) })
|
const opts = { method: 'POST' }
|
||||||
|
if (body !== undefined) opts.body = JSON.stringify(body)
|
||||||
|
return this.request(path, opts)
|
||||||
}
|
}
|
||||||
|
|
||||||
put(path, body) {
|
put(path, body) {
|
||||||
@ -138,6 +140,22 @@ class ApiClient {
|
|||||||
return this.get(`/api/v1/agents/${agentId}/backups`)
|
return this.get(`/api/v1/agents/${agentId}/backups`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async downloadBackup(agentId, backupId) {
|
||||||
|
const headers = {}
|
||||||
|
if (this.token) headers['Authorization'] = `Bearer ${this.token}`
|
||||||
|
const res = await fetch(`${API_BASE}/api/v1/agents/${agentId}/backups/${backupId}?format=xml`, { headers })
|
||||||
|
if (!res.ok) throw new Error('Download fehlgeschlagen')
|
||||||
|
const blob = await res.blob()
|
||||||
|
const url = URL.createObjectURL(blob)
|
||||||
|
const a = document.createElement('a')
|
||||||
|
a.href = url
|
||||||
|
a.download = `config_${agentId.substring(0, 8)}_${backupId}.xml`
|
||||||
|
document.body.appendChild(a)
|
||||||
|
a.click()
|
||||||
|
document.body.removeChild(a)
|
||||||
|
URL.revokeObjectURL(url)
|
||||||
|
}
|
||||||
|
|
||||||
triggerBackup(agentId) {
|
triggerBackup(agentId) {
|
||||||
return this.post(`/api/v1/agents/${agentId}/backup`)
|
return this.post(`/api/v1/agents/${agentId}/backup`)
|
||||||
}
|
}
|
||||||
@ -194,6 +212,47 @@ class ApiClient {
|
|||||||
deleteUser(id) {
|
deleteUser(id) {
|
||||||
return this.del(`/api/v1/users/${id}`)
|
return this.del(`/api/v1/users/${id}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
changePassword(userId, password) {
|
||||||
|
return this.put(`/api/v1/users/${userId}/password`, { password })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Firmware
|
||||||
|
getFirmwareInfo() {
|
||||||
|
return this.get('/api/v1/firmware')
|
||||||
|
}
|
||||||
|
|
||||||
|
async uploadFirmware(version, platform, file) {
|
||||||
|
const headers = {}
|
||||||
|
if (this.token) headers['Authorization'] = `Bearer ${this.token}`
|
||||||
|
const res = await fetch(`${API_BASE}/api/v1/firmware/upload?version=${encodeURIComponent(version)}&platform=${encodeURIComponent(platform)}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers,
|
||||||
|
body: file,
|
||||||
|
})
|
||||||
|
if (res.status === 401) {
|
||||||
|
this.setToken(null)
|
||||||
|
window.location.href = '/login'
|
||||||
|
throw new Error('Unauthorized')
|
||||||
|
}
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json().catch(() => ({ error: res.statusText }))
|
||||||
|
throw new Error(err.error || 'Upload fehlgeschlagen')
|
||||||
|
}
|
||||||
|
return res.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
requestAgentUpdate(agentId) {
|
||||||
|
return this.post(`/api/v1/agents/${agentId}/request-update`)
|
||||||
|
}
|
||||||
|
|
||||||
|
cancelAgentUpdate(agentId) {
|
||||||
|
return this.del(`/api/v1/agents/${agentId}/request-update`)
|
||||||
|
}
|
||||||
|
|
||||||
|
requestUpdateAll() {
|
||||||
|
return this.post('/api/v1/agents/request-update-all')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const api = new ApiClient()
|
export const api = new ApiClient()
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -10,11 +10,15 @@ import {
|
|||||||
LogOut,
|
LogOut,
|
||||||
Menu,
|
Menu,
|
||||||
X,
|
X,
|
||||||
|
Cable,
|
||||||
|
Download,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
|
|
||||||
const navItems = [
|
const navItems = [
|
||||||
{ path: '/', label: 'Dashboard', icon: LayoutDashboard },
|
{ path: '/', label: 'Dashboard', icon: LayoutDashboard },
|
||||||
{ path: '/agents', label: 'Firewalls', icon: Server },
|
{ path: '/agents', label: 'Firewalls', icon: Server },
|
||||||
|
{ path: '/tunnels', label: 'Tunnel', icon: Cable },
|
||||||
|
{ path: '/firmware', label: 'Firmware', icon: Download },
|
||||||
{ path: '/customers', label: 'Kunden', icon: Users },
|
{ path: '/customers', label: 'Kunden', icon: Users },
|
||||||
{ path: '/settings', label: 'Einstellungen', icon: Settings },
|
{ path: '/settings', label: 'Einstellungen', icon: Settings },
|
||||||
]
|
]
|
||||||
|
|||||||
@ -14,6 +14,31 @@ import {
|
|||||||
Download,
|
Download,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
|
|
||||||
|
const SERVICE_DESCRIPTIONS = {
|
||||||
|
configd: 'Configuration Daemon',
|
||||||
|
dhcpd: 'DHCP Server',
|
||||||
|
dpinger: 'Gateway Monitor',
|
||||||
|
openssh: 'Secure Shell',
|
||||||
|
syslogd: 'System Logger',
|
||||||
|
unbound: 'DNS Resolver',
|
||||||
|
openvpn: 'OpenVPN',
|
||||||
|
cron: 'Cron Daemon',
|
||||||
|
ntpd: 'NTP Daemon',
|
||||||
|
'syslog-ng': 'Syslog-NG',
|
||||||
|
haproxy: 'HAProxy Load Balancer',
|
||||||
|
nginx: 'Nginx Webserver',
|
||||||
|
squid: 'Squid Proxy',
|
||||||
|
suricata: 'Suricata IDS/IPS',
|
||||||
|
wireguard: 'WireGuard VPN',
|
||||||
|
pf: 'Packet Filter',
|
||||||
|
routing: 'Routing Daemon',
|
||||||
|
radvd: 'Router Advertisement',
|
||||||
|
dnsmasq: 'DNS Forwarder',
|
||||||
|
monit: 'Process Monitor',
|
||||||
|
collectd: 'System Statistics',
|
||||||
|
rmm_agent: 'RMM Agent',
|
||||||
|
}
|
||||||
|
|
||||||
export default function AgentDetail() {
|
export default function AgentDetail() {
|
||||||
const { id } = useParams()
|
const { id } = useParams()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
@ -94,16 +119,21 @@ export default function AgentDetail() {
|
|||||||
<Section title="Netzwerk-Interfaces" icon={Network}>
|
<Section title="Netzwerk-Interfaces" icon={Network}>
|
||||||
<div className="divide-y divide-gray-800">
|
<div className="divide-y divide-gray-800">
|
||||||
{sys.network_interfaces
|
{sys.network_interfaces
|
||||||
.filter((i) => i.addresses && i.addresses.length > 0)
|
.filter((i) => i.ip || (i.addresses && i.addresses.length > 0))
|
||||||
.map((iface) => (
|
.map((iface) => (
|
||||||
<div key={iface.name} className="px-4 py-2 flex items-center justify-between">
|
<div key={iface.name} className="px-4 py-2 flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<span className="text-sm text-white font-mono">{iface.name}</span>
|
<span className="text-sm text-white font-mono">{iface.name}</span>
|
||||||
<span className={`ml-2 text-xs ${iface.status === 'active' ? 'text-green-400' : 'text-gray-500'}`}>
|
{iface.role && (
|
||||||
|
<span className="ml-2 text-xs px-1.5 py-0.5 rounded bg-blue-900/50 text-blue-300 border border-blue-800/50">
|
||||||
|
{iface.role}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<span className={`ml-2 text-xs ${iface.status === 'active' || iface.status === 'up' ? 'text-green-400' : 'text-gray-500'}`}>
|
||||||
{iface.status}
|
{iface.status}
|
||||||
</span>
|
</span>
|
||||||
<div className="text-xs text-gray-500">
|
<div className="text-xs text-gray-500">
|
||||||
{iface.addresses?.filter((a) => !a.includes(':')).join(', ')}
|
{iface.ip || iface.addresses?.filter((a) => !a.includes(':')).join(', ') || '—'}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-right text-xs text-gray-500">
|
<div className="text-right text-xs text-gray-500">
|
||||||
@ -119,20 +149,45 @@ export default function AgentDetail() {
|
|||||||
{/* Services */}
|
{/* Services */}
|
||||||
{sys.services && sys.services.length > 0 && (
|
{sys.services && sys.services.length > 0 && (
|
||||||
<Section title="Dienste" icon={Shield}>
|
<Section title="Dienste" icon={Shield}>
|
||||||
<div className="px-4 py-2 flex flex-wrap gap-2">
|
<table className="w-full text-sm">
|
||||||
{sys.services.map((svc) => (
|
<thead>
|
||||||
<span
|
<tr className="text-left text-gray-500 border-b border-gray-800">
|
||||||
key={svc.name}
|
<th className="px-4 py-2 font-medium">Dienst</th>
|
||||||
className={`text-xs px-2 py-1 rounded ${
|
<th className="px-4 py-2 font-medium">Beschreibung</th>
|
||||||
svc.running
|
<th className="px-4 py-2 font-medium text-right">Status</th>
|
||||||
? 'bg-green-900/30 text-green-400 border border-green-800/50'
|
</tr>
|
||||||
: 'bg-gray-800 text-gray-500 border border-gray-700'
|
</thead>
|
||||||
}`}
|
<tbody className="divide-y divide-gray-800">
|
||||||
>
|
{sys.services
|
||||||
{svc.name}
|
.slice()
|
||||||
</span>
|
.sort((a, b) => {
|
||||||
))}
|
const aRun = a.running || a.status === 'running'
|
||||||
</div>
|
const bRun = b.running || b.status === 'running'
|
||||||
|
return aRun === bRun ? a.name.localeCompare(b.name) : aRun ? -1 : 1
|
||||||
|
})
|
||||||
|
.map((svc) => {
|
||||||
|
const isRunning = svc.running || svc.status === 'running'
|
||||||
|
return (
|
||||||
|
<tr key={svc.name}>
|
||||||
|
<td className="px-4 py-2.5 text-white font-medium">{svc.name}</td>
|
||||||
|
<td className="px-4 py-2.5 text-gray-400">{svc.description || SERVICE_DESCRIPTIONS[svc.name] || '—'}</td>
|
||||||
|
<td className="px-4 py-2.5 text-right">
|
||||||
|
<span
|
||||||
|
className={`inline-flex items-center gap-1.5 text-xs font-medium px-3 py-1 rounded ${
|
||||||
|
isRunning
|
||||||
|
? 'bg-green-900/40 text-green-400 border border-green-700/50'
|
||||||
|
: 'bg-gray-800 text-gray-500 border border-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className={`w-1.5 h-1.5 rounded-full ${isRunning ? 'bg-green-400' : 'bg-gray-500'}`} />
|
||||||
|
{isRunning ? 'running' : 'stopped'}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
</Section>
|
</Section>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@ -155,8 +210,8 @@ export default function AgentDetail() {
|
|||||||
<td className="px-4 py-2 text-white">{gw.name}</td>
|
<td className="px-4 py-2 text-white">{gw.name}</td>
|
||||||
<td className="px-4 py-2 text-gray-400">{gw.gateway}</td>
|
<td className="px-4 py-2 text-gray-400">{gw.gateway}</td>
|
||||||
<td className="px-4 py-2">
|
<td className="px-4 py-2">
|
||||||
<span className={gw.status === 'none' ? 'text-green-400' : 'text-yellow-400'}>
|
<span className={gwOk(gw.status) ? 'text-green-400' : 'text-yellow-400'}>
|
||||||
{gw.status === 'none' ? 'OK' : gw.status}
|
{gwOk(gw.status) ? 'OK' : gw.status}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-4 py-2 text-gray-400">{gw.delay || '—'}</td>
|
<td className="px-4 py-2 text-gray-400">{gw.delay || '—'}</td>
|
||||||
@ -251,6 +306,11 @@ function QuickStat({ icon: Icon, label, value, sub }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function gwOk(status) {
|
||||||
|
const s = (status || '').toLowerCase()
|
||||||
|
return s === 'none' || s === 'online' || s === 'ok'
|
||||||
|
}
|
||||||
|
|
||||||
function formatBytes(bytes) {
|
function formatBytes(bytes) {
|
||||||
if (!bytes || bytes === 0) return '0 B'
|
if (!bytes || bytes === 0) return '0 B'
|
||||||
const k = 1024
|
const k = 1024
|
||||||
|
|||||||
@ -206,7 +206,7 @@ export default function Agents() {
|
|||||||
<div className="flex flex-col gap-0.5">
|
<div className="flex flex-col gap-0.5">
|
||||||
{a.gateways.map((gw) => (
|
{a.gateways.map((gw) => (
|
||||||
<span key={gw.name} className="inline-flex items-center gap-1 text-xs">
|
<span key={gw.name} className="inline-flex items-center gap-1 text-xs">
|
||||||
<span className={`w-1.5 h-1.5 rounded-full ${gw.status === 'none' ? 'bg-green-500' : 'bg-yellow-500'}`} />
|
<span className={`w-1.5 h-1.5 rounded-full ${gwDotColor(gw.status)}`} />
|
||||||
<span className="text-gray-400">{gw.name}</span>
|
<span className="text-gray-400">{gw.name}</span>
|
||||||
</span>
|
</span>
|
||||||
))}
|
))}
|
||||||
@ -238,6 +238,13 @@ export default function Agents() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function gwDotColor(status) {
|
||||||
|
const s = (status || '').toLowerCase()
|
||||||
|
if (s === 'online' || s === 'none') return 'bg-green-500'
|
||||||
|
if (s === 'offline' || s === 'down') return 'bg-red-500'
|
||||||
|
return 'bg-yellow-500'
|
||||||
|
}
|
||||||
|
|
||||||
function MiniBar({ value }) {
|
function MiniBar({ value }) {
|
||||||
if (value === null || value === undefined) return <span className="text-gray-600 text-xs">—</span>
|
if (value === null || value === undefined) return <span className="text-gray-600 text-xs">—</span>
|
||||||
const color = value > 90 ? 'bg-red-500' : value > 70 ? 'bg-yellow-500' : value > 50 ? 'bg-blue-500' : 'bg-green-500'
|
const color = value > 90 ? 'bg-red-500' : value > 70 ? 'bg-yellow-500' : value > 50 ? 'bg-blue-500' : 'bg-green-500'
|
||||||
|
|||||||
@ -1,21 +1,26 @@
|
|||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { Link } from 'react-router-dom'
|
|
||||||
import api from '../api/client'
|
import api from '../api/client'
|
||||||
import StatusBadge from '../components/StatusBadge'
|
import StatusBadge from '../components/StatusBadge'
|
||||||
|
import AgentPanel from '../components/AgentPanel'
|
||||||
import { Server, Users, Activity, AlertTriangle } from 'lucide-react'
|
import { Server, Users, Activity, AlertTriangle } from 'lucide-react'
|
||||||
|
|
||||||
export default function Dashboard() {
|
export default function Dashboard() {
|
||||||
const [agents, setAgents] = useState([])
|
const [agents, setAgents] = useState([])
|
||||||
const [customers, setCustomers] = useState([])
|
const [customers, setCustomers] = useState([])
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [selectedId, setSelectedId] = useState(null)
|
||||||
|
|
||||||
useEffect(() => {
|
const reload = () => {
|
||||||
Promise.all([api.getAgents(), api.getCustomers()])
|
Promise.all([api.getAgents(), api.getCustomers()])
|
||||||
.then(([a, c]) => {
|
.then(([a, c]) => {
|
||||||
setAgents(a || [])
|
setAgents(a || [])
|
||||||
setCustomers(c || [])
|
setCustomers(c || [])
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false))
|
.finally(() => setLoading(false))
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
reload()
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
@ -67,7 +72,7 @@ export default function Dashboard() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="divide-y divide-gray-800">
|
<div className="divide-y divide-gray-800">
|
||||||
{customer.agents.map((agent) => (
|
{customer.agents.map((agent) => (
|
||||||
<AgentRow key={agent.id} agent={agent} />
|
<AgentRow key={agent.id} agent={agent} onClick={() => setSelectedId(agent.id)} selected={selectedId === agent.id} />
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -83,12 +88,22 @@ export default function Dashboard() {
|
|||||||
{agents
|
{agents
|
||||||
.filter((a) => !a.customer_id)
|
.filter((a) => !a.customer_id)
|
||||||
.map((agent) => (
|
.map((agent) => (
|
||||||
<AgentRow key={agent.id} agent={agent} />
|
<AgentRow key={agent.id} agent={agent} onClick={() => setSelectedId(agent.id)} selected={selectedId === agent.id} />
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Detail Panel */}
|
||||||
|
{selectedId && (
|
||||||
|
<AgentPanel
|
||||||
|
agentId={selectedId}
|
||||||
|
customers={customers}
|
||||||
|
onClose={() => setSelectedId(null)}
|
||||||
|
onReload={reload}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -107,15 +122,15 @@ function StatCard({ icon: Icon, label, value, color }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function AgentRow({ agent }) {
|
function AgentRow({ agent, onClick, selected }) {
|
||||||
const lastHB = agent.last_heartbeat
|
const lastHB = agent.last_heartbeat
|
||||||
? new Date(agent.last_heartbeat).toLocaleString('de-DE')
|
? new Date(agent.last_heartbeat).toLocaleString('de-DE')
|
||||||
: '—'
|
: '—'
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Link
|
<div
|
||||||
to={`/agents/${agent.id}`}
|
onClick={onClick}
|
||||||
className="flex items-center justify-between px-4 py-2.5 hover:bg-gray-800/50 transition-colors"
|
className={`flex items-center justify-between px-4 py-2.5 hover:bg-gray-800/50 transition-colors cursor-pointer ${selected ? 'bg-gray-800/70' : ''}`}
|
||||||
>
|
>
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<StatusBadge status={agent.status} size="dot" />
|
<StatusBadge status={agent.status} size="dot" />
|
||||||
@ -128,6 +143,6 @@ function AgentRow({ agent }) {
|
|||||||
<div className="text-xs text-gray-500">{agent.opnsense_version || '—'}</div>
|
<div className="text-xs text-gray-500">{agent.opnsense_version || '—'}</div>
|
||||||
<div className="text-xs text-gray-600">{lastHB}</div>
|
<div className="text-xs text-gray-600">{lastHB}</div>
|
||||||
</div>
|
</div>
|
||||||
</Link>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
272
frontend/src/pages/Firmware.jsx
Normal file
272
frontend/src/pages/Firmware.jsx
Normal file
@ -0,0 +1,272 @@
|
|||||||
|
import { useEffect, useState, useRef } from 'react'
|
||||||
|
import api from '../api/client'
|
||||||
|
import { Upload, RefreshCw, CheckCircle, AlertTriangle, ArrowUpCircle, X, Monitor, Server, Cpu } from 'lucide-react'
|
||||||
|
|
||||||
|
const PLATFORMS = [
|
||||||
|
{ id: 'freebsd', label: 'FreeBSD / OPNsense', icon: Server },
|
||||||
|
{ id: 'linux', label: 'Linux', icon: Monitor },
|
||||||
|
{ id: 'windows', label: 'Windows', icon: Cpu },
|
||||||
|
]
|
||||||
|
|
||||||
|
export default function Firmware() {
|
||||||
|
const [firmwareData, setFirmwareData] = useState(null)
|
||||||
|
const [agents, setAgents] = useState([])
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [uploading, setUploading] = useState(false)
|
||||||
|
const [version, setVersion] = useState('')
|
||||||
|
const [platform, setPlatform] = useState('freebsd')
|
||||||
|
const [msg, setMsg] = useState('')
|
||||||
|
const [msgType, setMsgType] = useState('info')
|
||||||
|
const fileRef = useRef(null)
|
||||||
|
|
||||||
|
const load = async () => {
|
||||||
|
try {
|
||||||
|
const [fw, ag] = await Promise.all([
|
||||||
|
api.getFirmwareInfo().catch(() => null),
|
||||||
|
api.getAgents().catch(() => []),
|
||||||
|
])
|
||||||
|
setFirmwareData(fw)
|
||||||
|
setAgents(Array.isArray(ag) ? ag : [])
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => { load() }, [])
|
||||||
|
|
||||||
|
const showMsg = (text, type = 'info') => {
|
||||||
|
setMsg(text)
|
||||||
|
setMsgType(type)
|
||||||
|
setTimeout(() => setMsg(''), 5000)
|
||||||
|
}
|
||||||
|
|
||||||
|
const getFwForPlatform = (p) => {
|
||||||
|
if (!firmwareData?.platforms) return null
|
||||||
|
return firmwareData.platforms.find(f => f.platform === p)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleUpload = async () => {
|
||||||
|
const file = fileRef.current?.files?.[0]
|
||||||
|
if (!file) return showMsg('Bitte Binary auswaehlen', 'error')
|
||||||
|
if (!version.trim()) return showMsg('Bitte Version angeben', 'error')
|
||||||
|
|
||||||
|
setUploading(true)
|
||||||
|
try {
|
||||||
|
const result = await api.uploadFirmware(version.trim(), platform, file)
|
||||||
|
showMsg(`Firmware v${result.version} (${result.platform}) hochgeladen (${formatSize(result.size)})`, 'success')
|
||||||
|
setVersion('')
|
||||||
|
fileRef.current.value = ''
|
||||||
|
load()
|
||||||
|
} catch (err) {
|
||||||
|
showMsg(`Upload fehlgeschlagen: ${err.message}`, 'error')
|
||||||
|
} finally {
|
||||||
|
setUploading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestUpdate = async (agentId, name) => {
|
||||||
|
try {
|
||||||
|
await api.requestAgentUpdate(agentId)
|
||||||
|
showMsg(`Update fuer ${name} angefordert`, 'success')
|
||||||
|
load()
|
||||||
|
} catch (err) {
|
||||||
|
showMsg(`Fehler: ${err.message}`, 'error')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const cancelUpdate = async (agentId, name) => {
|
||||||
|
try {
|
||||||
|
await api.cancelAgentUpdate(agentId)
|
||||||
|
showMsg(`Update-Anforderung fuer ${name} geloescht`, 'info')
|
||||||
|
load()
|
||||||
|
} catch (err) {
|
||||||
|
showMsg(`Fehler: ${err.message}`, 'error')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestAll = async () => {
|
||||||
|
try {
|
||||||
|
const result = await api.requestUpdateAll()
|
||||||
|
showMsg(result.message || 'Update fuer alle angefordert', 'success')
|
||||||
|
load()
|
||||||
|
} catch (err) {
|
||||||
|
showMsg(`Fehler: ${err.message}`, 'error')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatSize = (bytes) => {
|
||||||
|
if (!bytes) return '--'
|
||||||
|
if (bytes > 1048576) return `${(bytes / 1048576).toFixed(1)} MB`
|
||||||
|
return `${(bytes / 1024).toFixed(0)} KB`
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading) return <div className="text-gray-500">Laden...</div>
|
||||||
|
|
||||||
|
// Fuer jetzt: alle Agents sind freebsd
|
||||||
|
const freebsdFw = getFwForPlatform('freebsd')
|
||||||
|
|
||||||
|
const needsUpdate = (agent) => {
|
||||||
|
if (!freebsdFw) return false
|
||||||
|
return agent.agent_version !== freebsdFw.version
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="max-w-4xl mx-auto space-y-6">
|
||||||
|
<h1 className="text-2xl font-bold text-white">Agent-Firmware</h1>
|
||||||
|
|
||||||
|
{/* Status Message */}
|
||||||
|
{msg && (
|
||||||
|
<div className={`rounded-lg px-4 py-3 text-sm flex items-center gap-2 ${
|
||||||
|
msgType === 'error' ? 'bg-red-500/10 border border-red-500/30 text-red-400' :
|
||||||
|
msgType === 'success' ? 'bg-emerald-500/10 border border-emerald-500/30 text-emerald-400' :
|
||||||
|
'bg-blue-500/10 border border-blue-500/30 text-blue-400'
|
||||||
|
}`}>
|
||||||
|
{msgType === 'success' ? <CheckCircle className="w-4 h-4 shrink-0" /> :
|
||||||
|
msgType === 'error' ? <AlertTriangle className="w-4 h-4 shrink-0" /> : null}
|
||||||
|
{msg}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Platform Firmware Overview */}
|
||||||
|
<div className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-5">
|
||||||
|
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-4">Verfuegbare Firmware</h2>
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
|
||||||
|
{PLATFORMS.map(p => {
|
||||||
|
const fw = getFwForPlatform(p.id)
|
||||||
|
const Icon = p.icon
|
||||||
|
return (
|
||||||
|
<div key={p.id} className={`rounded-lg border p-4 ${
|
||||||
|
fw ? 'bg-gray-900/50 border-gray-700/50' : 'bg-gray-900/20 border-gray-800/50'
|
||||||
|
}`}>
|
||||||
|
<div className="flex items-center gap-2 mb-2">
|
||||||
|
<Icon className={`w-4 h-4 ${fw ? 'text-orange-400' : 'text-gray-600'}`} />
|
||||||
|
<span className={`text-sm font-medium ${fw ? 'text-white' : 'text-gray-600'}`}>{p.label}</span>
|
||||||
|
</div>
|
||||||
|
{fw ? (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<div className="text-lg font-bold text-orange-400">v{fw.version}</div>
|
||||||
|
<div className="text-xs text-gray-500">{formatSize(fw.size)}</div>
|
||||||
|
<div className="text-[10px] text-gray-600 font-mono">{fw.hash?.substring(0, 16)}...</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="text-xs text-gray-600 mt-1">Nicht hochgeladen</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Upload */}
|
||||||
|
<div className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-5">
|
||||||
|
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-3">Neue Firmware hochladen</h2>
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<div className="flex flex-wrap gap-3">
|
||||||
|
<select
|
||||||
|
value={platform}
|
||||||
|
onChange={(e) => setPlatform(e.target.value)}
|
||||||
|
className="bg-gray-900 border border-gray-700 rounded px-3 py-2 text-sm text-white focus:border-orange-500 focus:outline-none"
|
||||||
|
>
|
||||||
|
{PLATFORMS.map(p => (
|
||||||
|
<option key={p.id} value={p.id}>{p.label}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Version (z.B. 1.0.2)"
|
||||||
|
value={version}
|
||||||
|
onChange={(e) => setVersion(e.target.value)}
|
||||||
|
className="bg-gray-900 border border-gray-700 rounded px-3 py-2 text-sm text-white placeholder-gray-500 focus:border-orange-500 focus:outline-none w-40"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
ref={fileRef}
|
||||||
|
className="bg-gray-900 border border-gray-700 rounded px-3 py-2 text-sm text-gray-400 file:mr-3 file:bg-gray-700 file:text-gray-300 file:border-0 file:rounded file:px-3 file:py-1 file:text-xs file:cursor-pointer flex-1"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={handleUpload}
|
||||||
|
disabled={uploading}
|
||||||
|
className="flex items-center gap-2 bg-orange-600 hover:bg-orange-500 disabled:bg-gray-700 disabled:text-gray-500 text-white px-4 py-2 rounded text-sm transition-colors shrink-0"
|
||||||
|
>
|
||||||
|
{uploading ? <RefreshCw className="w-4 h-4 animate-spin" /> : <Upload className="w-4 h-4" />}
|
||||||
|
{uploading ? 'Hochladen...' : 'Hochladen'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Agent List */}
|
||||||
|
<div className="bg-gray-800/50 rounded-lg border border-gray-700/50 p-5">
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider">Agents</h2>
|
||||||
|
{freebsdFw && (
|
||||||
|
<button
|
||||||
|
onClick={requestAll}
|
||||||
|
className="flex items-center gap-2 bg-orange-600/20 hover:bg-orange-600/30 text-orange-400 px-3 py-1.5 rounded text-xs transition-colors border border-orange-600/30"
|
||||||
|
>
|
||||||
|
<ArrowUpCircle className="w-3.5 h-3.5" />
|
||||||
|
Alle updaten
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
{agents.map((agent) => {
|
||||||
|
const outdated = needsUpdate(agent)
|
||||||
|
const pending = agent.update_requested
|
||||||
|
return (
|
||||||
|
<div key={agent.id} className="flex items-center justify-between bg-gray-900/50 rounded-lg px-4 py-3 border border-gray-700/30">
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className={`w-2 h-2 rounded-full shrink-0 ${
|
||||||
|
agent.status === 'online' ? 'bg-emerald-500' :
|
||||||
|
agent.status === 'stale' ? 'bg-yellow-500' : 'bg-gray-600'
|
||||||
|
}`} />
|
||||||
|
<span className="text-white text-sm font-medium truncate">{agent.name}</span>
|
||||||
|
<span className="text-[10px] px-1.5 py-0.5 rounded bg-gray-700/50 text-gray-500">FreeBSD</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3 mt-1">
|
||||||
|
<span className="text-xs text-gray-500">
|
||||||
|
Version: <span className={outdated ? 'text-yellow-400' : 'text-gray-400'}>{agent.agent_version || '--'}</span>
|
||||||
|
</span>
|
||||||
|
{pending && (
|
||||||
|
<span className="text-[10px] px-1.5 py-0.5 rounded bg-orange-500/20 text-orange-400 border border-orange-500/30">
|
||||||
|
Update ausstehend
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{!outdated && freebsdFw && agent.agent_version && (
|
||||||
|
<span className="text-[10px] px-1.5 py-0.5 rounded bg-emerald-500/20 text-emerald-400 border border-emerald-500/30">
|
||||||
|
Aktuell
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 shrink-0 ml-3">
|
||||||
|
{pending ? (
|
||||||
|
<button
|
||||||
|
onClick={() => cancelUpdate(agent.id, agent.name)}
|
||||||
|
className="flex items-center gap-1.5 bg-gray-700 hover:bg-gray-600 text-gray-300 px-3 py-1.5 rounded text-xs transition-colors"
|
||||||
|
>
|
||||||
|
<X className="w-3.5 h-3.5" />
|
||||||
|
Abbrechen
|
||||||
|
</button>
|
||||||
|
) : outdated ? (
|
||||||
|
<button
|
||||||
|
onClick={() => requestUpdate(agent.id, agent.name)}
|
||||||
|
className="flex items-center gap-1.5 bg-orange-600 hover:bg-orange-500 text-white px-3 py-1.5 rounded text-xs transition-colors"
|
||||||
|
>
|
||||||
|
<ArrowUpCircle className="w-3.5 h-3.5" />
|
||||||
|
Update
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@ -1,11 +1,16 @@
|
|||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import api from '../api/client'
|
import api from '../api/client'
|
||||||
import { Plus, Trash2 } from 'lucide-react'
|
import { useAuthStore } from '../stores/auth'
|
||||||
|
import { Plus, Trash2, KeyRound, ShieldAlert } from 'lucide-react'
|
||||||
|
|
||||||
export default function SettingsPage() {
|
export default function SettingsPage() {
|
||||||
const [users, setUsers] = useState([])
|
const [users, setUsers] = useState([])
|
||||||
const [showAdd, setShowAdd] = useState(false)
|
const [showAdd, setShowAdd] = useState(false)
|
||||||
const [form, setForm] = useState({ username: '', password: '', display_name: '' })
|
const [form, setForm] = useState({ username: '', password: '', display_name: '' })
|
||||||
|
const [pwChange, setPwChange] = useState(null) // userId being changed
|
||||||
|
const [pwForm, setPwForm] = useState({ password: '', confirm: '' })
|
||||||
|
const [pwMsg, setPwMsg] = useState('')
|
||||||
|
const { user: currentUser } = useAuthStore()
|
||||||
|
|
||||||
const reload = () => api.getUsers().then((u) => setUsers(u || []))
|
const reload = () => api.getUsers().then((u) => setUsers(u || []))
|
||||||
useEffect(() => { reload() }, [])
|
useEffect(() => { reload() }, [])
|
||||||
@ -24,6 +29,25 @@ export default function SettingsPage() {
|
|||||||
reload()
|
reload()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handlePasswordChange = async () => {
|
||||||
|
setPwMsg('')
|
||||||
|
if (!pwForm.password || pwForm.password.length < 6) {
|
||||||
|
setPwMsg('Mindestens 6 Zeichen')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (pwForm.password !== pwForm.confirm) {
|
||||||
|
setPwMsg('Passwoerter stimmen nicht ueberein')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await api.changePassword(pwChange, pwForm.password)
|
||||||
|
setPwMsg('Passwort geaendert')
|
||||||
|
setTimeout(() => { setPwChange(null); setPwMsg(''); setPwForm({ password: '', confirm: '' }) }, 1500)
|
||||||
|
} catch (e) {
|
||||||
|
setPwMsg('Fehler: ' + e.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<h1 className="text-xl font-bold text-white">Einstellungen</h1>
|
<h1 className="text-xl font-bold text-white">Einstellungen</h1>
|
||||||
@ -42,7 +66,7 @@ export default function SettingsPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{showAdd && (
|
{showAdd && (
|
||||||
<div className="px-4 py-3 border-b border-gray-800 flex gap-2 items-end">
|
<div className="px-4 py-3 border-b border-gray-800 flex gap-2 items-end flex-wrap">
|
||||||
<div>
|
<div>
|
||||||
<label className="text-xs text-gray-500">Benutzer</label>
|
<label className="text-xs text-gray-500">Benutzer</label>
|
||||||
<input
|
<input
|
||||||
@ -81,26 +105,116 @@ export default function SettingsPage() {
|
|||||||
|
|
||||||
<div className="divide-y divide-gray-800">
|
<div className="divide-y divide-gray-800">
|
||||||
{users.map((u) => (
|
{users.map((u) => (
|
||||||
<div key={u.id} className="px-4 py-2.5 flex items-center justify-between">
|
<div key={u.id}>
|
||||||
<div>
|
<div className="px-4 py-2.5 flex items-center justify-between">
|
||||||
<span className="text-sm text-white">{u.username}</span>
|
<div>
|
||||||
{u.display_name && (
|
<span className="text-sm text-white">{u.username}</span>
|
||||||
<span className="text-sm text-gray-500 ml-2">({u.display_name})</span>
|
{u.display_name && (
|
||||||
)}
|
<span className="text-sm text-gray-500 ml-2">({u.display_name})</span>
|
||||||
<span className="ml-2 text-xs text-gray-600">{u.role}</span>
|
)}
|
||||||
</div>
|
<span className="ml-2 text-xs text-gray-600">{u.role}</span>
|
||||||
<div className="flex items-center gap-3">
|
{currentUser?.username === u.username && (
|
||||||
<span className="text-xs text-gray-600">
|
<span className="ml-2 text-xs text-orange-400">(Du)</span>
|
||||||
{u.last_login ? `Letzter Login: ${new Date(u.last_login).toLocaleString('de-DE')}` : 'Nie eingeloggt'}
|
)}
|
||||||
</span>
|
</div>
|
||||||
<button onClick={() => handleDelete(u.id)} className="text-gray-500 hover:text-red-400">
|
<div className="flex items-center gap-2">
|
||||||
<Trash2 className="w-4 h-4" />
|
<span className="text-xs text-gray-600">
|
||||||
</button>
|
{u.last_login ? `Login: ${new Date(u.last_login).toLocaleString('de-DE')}` : 'Nie eingeloggt'}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => { setPwChange(pwChange === u.id ? null : u.id); setPwMsg(''); setPwForm({ password: '', confirm: '' }) }}
|
||||||
|
className="text-gray-500 hover:text-orange-400 p-1 rounded hover:bg-gray-800 transition-colors"
|
||||||
|
title="Passwort aendern"
|
||||||
|
>
|
||||||
|
<KeyRound className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDelete(u.id)}
|
||||||
|
className="text-gray-500 hover:text-red-400 p-1 rounded hover:bg-gray-800 transition-colors"
|
||||||
|
title="Benutzer loeschen"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Password Change */}
|
||||||
|
{pwChange === u.id && (
|
||||||
|
<div className="px-4 py-3 bg-gray-800/50 border-t border-gray-800 flex items-end gap-2 flex-wrap">
|
||||||
|
<div>
|
||||||
|
<label className="text-xs text-gray-500">Neues Passwort</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={pwForm.password}
|
||||||
|
onChange={(e) => setPwForm({ ...pwForm, password: e.target.value })}
|
||||||
|
className="w-full bg-gray-900 border border-gray-700 rounded px-2 py-1 text-white text-sm focus:outline-none focus:border-orange-500"
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-xs text-gray-500">Bestaetigen</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={pwForm.confirm}
|
||||||
|
onChange={(e) => setPwForm({ ...pwForm, confirm: e.target.value })}
|
||||||
|
onKeyDown={(e) => e.key === 'Enter' && handlePasswordChange()}
|
||||||
|
className="w-full bg-gray-900 border border-gray-700 rounded px-2 py-1 text-white text-sm focus:outline-none focus:border-orange-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={handlePasswordChange}
|
||||||
|
className="px-3 py-1 bg-orange-600 hover:bg-orange-700 rounded text-sm text-white"
|
||||||
|
>
|
||||||
|
Aendern
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => { setPwChange(null); setPwMsg('') }}
|
||||||
|
className="px-3 py-1 bg-gray-800 rounded text-sm text-gray-400"
|
||||||
|
>
|
||||||
|
Abbrechen
|
||||||
|
</button>
|
||||||
|
{pwMsg && (
|
||||||
|
<span className={`text-sm ${pwMsg.startsWith('Fehler') || pwMsg.startsWith('Mindestens') || pwMsg.startsWith('Passwort') && !pwMsg.includes('geaendert') ? 'text-red-400' : pwMsg.includes('geaendert') ? 'text-green-400' : 'text-red-400'}`}>
|
||||||
|
{pwMsg}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* 2FA */}
|
||||||
|
<div className="bg-gray-900 rounded-lg border border-gray-800 overflow-hidden">
|
||||||
|
<div className="px-4 py-3 border-b border-gray-800">
|
||||||
|
<span className="text-sm font-medium text-gray-300">Zwei-Faktor-Authentifizierung (2FA)</span>
|
||||||
|
</div>
|
||||||
|
<div className="px-4 py-6 flex items-center gap-3">
|
||||||
|
<ShieldAlert className="w-6 h-6 text-gray-600" />
|
||||||
|
<div>
|
||||||
|
<div className="text-sm text-gray-400">2FA ist noch nicht verfuegbar</div>
|
||||||
|
<div className="text-xs text-gray-600 mt-0.5">TOTP-basierte Zwei-Faktor-Authentifizierung wird in einer zukuenftigen Version implementiert.</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Info */}
|
||||||
|
<div className="bg-gray-900 rounded-lg border border-gray-800 overflow-hidden">
|
||||||
|
<div className="px-4 py-3 border-b border-gray-800">
|
||||||
|
<span className="text-sm font-medium text-gray-300">System</span>
|
||||||
|
</div>
|
||||||
|
<div className="px-4 py-3 space-y-1 text-sm">
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span className="text-gray-500">Backend</span>
|
||||||
|
<span className="text-gray-400">192.168.85.13:8443</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span className="text-gray-500">Authentifizierung</span>
|
||||||
|
<span className="text-gray-400">JWT (8h Token)</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
221
frontend/src/pages/Tunnels.jsx
Normal file
221
frontend/src/pages/Tunnels.jsx
Normal file
@ -0,0 +1,221 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { Link } from 'react-router-dom'
|
||||||
|
import api from '../api/client'
|
||||||
|
import StatusBadge from '../components/StatusBadge'
|
||||||
|
import { Cable, Unplug, ExternalLink, RefreshCw, Search } from 'lucide-react'
|
||||||
|
|
||||||
|
const BACKEND_HOST = '192.168.85.13'
|
||||||
|
|
||||||
|
export default function Tunnels() {
|
||||||
|
const [agents, setAgents] = useState([])
|
||||||
|
const [allTunnels, setAllTunnels] = useState([]) // {agentId, agentName, agentStatus, ...tunnel}
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const [search, setSearch] = useState('')
|
||||||
|
|
||||||
|
const loadAll = async () => {
|
||||||
|
setError('')
|
||||||
|
try {
|
||||||
|
const agentList = await api.getAgents()
|
||||||
|
setAgents(agentList || [])
|
||||||
|
|
||||||
|
const tunnelPromises = (agentList || []).map(async (agent) => {
|
||||||
|
try {
|
||||||
|
const resp = await api.getTunnels(agent.id)
|
||||||
|
const list = resp?.tunnels || resp?.data?.tunnels || resp?.data || resp || []
|
||||||
|
const tunnels = Array.isArray(list) ? list : []
|
||||||
|
return tunnels.map((t) => ({
|
||||||
|
...t,
|
||||||
|
agentId: agent.id,
|
||||||
|
agentName: agent.name,
|
||||||
|
agentIp: agent.ip,
|
||||||
|
agentStatus: agent.status,
|
||||||
|
}))
|
||||||
|
} catch {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const results = await Promise.all(tunnelPromises)
|
||||||
|
setAllTunnels(results.flat())
|
||||||
|
} catch (e) {
|
||||||
|
setError(e.message)
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadAll()
|
||||||
|
const iv = setInterval(loadAll, 15000)
|
||||||
|
return () => clearInterval(iv)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const closeTunnel = async (agentId, tunnelId) => {
|
||||||
|
try {
|
||||||
|
await api.closeTunnel(agentId, tunnelId)
|
||||||
|
setAllTunnels((prev) =>
|
||||||
|
prev.filter((t) => !((t.id === tunnelId || t.tunnel_id === tunnelId) && t.agentId === agentId))
|
||||||
|
)
|
||||||
|
} catch (e) {
|
||||||
|
setError(e.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const closeAll = async () => {
|
||||||
|
if (!confirm(`Alle ${allTunnels.length} Tunnel schliessen?`)) return
|
||||||
|
for (const t of allTunnels) {
|
||||||
|
const tid = t.id || t.tunnel_id
|
||||||
|
await api.closeTunnel(t.agentId, tid).catch(() => {})
|
||||||
|
}
|
||||||
|
loadAll()
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<h1 className="text-xl font-bold text-white">Aktive Tunnel</h1>
|
||||||
|
<span className="text-sm text-gray-500">
|
||||||
|
{allTunnels.length} {allTunnels.length === 1 ? 'Tunnel' : 'Tunnel'} auf {new Set(allTunnels.map((t) => t.agentId)).size} Firewall(s)
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
onClick={loadAll}
|
||||||
|
className="flex items-center gap-1.5 px-3 py-1.5 bg-gray-800 hover:bg-gray-700 border border-gray-700 rounded text-sm text-gray-300 transition-colors"
|
||||||
|
>
|
||||||
|
<RefreshCw className="w-3.5 h-3.5" />
|
||||||
|
Aktualisieren
|
||||||
|
</button>
|
||||||
|
{allTunnels.length > 0 && (
|
||||||
|
<button
|
||||||
|
onClick={closeAll}
|
||||||
|
className="flex items-center gap-1.5 px-3 py-1.5 bg-red-600/20 hover:bg-red-600/30 border border-red-800/50 rounded text-sm text-red-400 transition-colors"
|
||||||
|
>
|
||||||
|
<Unplug className="w-3.5 h-3.5" />
|
||||||
|
Alle schliessen
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-3 top-2.5 w-4 h-4 text-gray-500" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Suchen (Firewall, IP, Ziel, Port)..."
|
||||||
|
value={search}
|
||||||
|
onChange={(e) => setSearch(e.target.value)}
|
||||||
|
className="w-full bg-gray-900 border border-gray-800 rounded pl-10 pr-3 py-2 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-orange-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && <div className="text-sm text-red-400 bg-red-900/20 rounded px-3 py-2 border border-red-800/50">{error}</div>}
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<div className="text-gray-500">Lade Tunnel aller Firewalls...</div>
|
||||||
|
) : (() => {
|
||||||
|
const filtered = search
|
||||||
|
? allTunnels.filter((t) => {
|
||||||
|
const q = search.toLowerCase()
|
||||||
|
const target = `${t.target_host || ''}:${t.target_port || ''}`
|
||||||
|
return (t.agentName || '').toLowerCase().includes(q) ||
|
||||||
|
(t.agentIp || '').toLowerCase().includes(q) ||
|
||||||
|
target.toLowerCase().includes(q) ||
|
||||||
|
String(t.proxy_port || t.local_port || '').includes(q)
|
||||||
|
})
|
||||||
|
: allTunnels
|
||||||
|
return filtered.length === 0 ? (
|
||||||
|
<div className="bg-gray-900 rounded-lg border border-gray-800 px-6 py-12 text-center">
|
||||||
|
<Cable className="w-10 h-10 text-gray-700 mx-auto mb-3" />
|
||||||
|
<div className="text-gray-500">Keine aktiven Tunnel</div>
|
||||||
|
<div className="text-xs text-gray-600 mt-1">
|
||||||
|
Tunnel koennen ueber die Firewall-Detailansicht erstellt werden
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="bg-gray-900 rounded-lg border border-gray-800 overflow-x-auto">
|
||||||
|
<table className="w-full text-sm whitespace-nowrap">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-gray-800 text-left text-gray-500 text-xs">
|
||||||
|
<th className="px-4 py-2.5 font-medium">Firewall</th>
|
||||||
|
<th className="px-4 py-2.5 font-medium">Ziel</th>
|
||||||
|
<th className="px-4 py-2.5 font-medium">Lokaler Zugang</th>
|
||||||
|
<th className="px-4 py-2.5 font-medium">Status</th>
|
||||||
|
<th className="px-4 py-2.5 font-medium">Erstellt</th>
|
||||||
|
<th className="px-4 py-2.5 font-medium text-right">Aktionen</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-gray-800">
|
||||||
|
{filtered.map((t) => {
|
||||||
|
const tid = t.id || t.tunnel_id
|
||||||
|
const proxyPort = t.proxy_port || t.local_port
|
||||||
|
const target = t.target_host && t.target_port
|
||||||
|
? `${t.target_host}:${t.target_port}`
|
||||||
|
: t.target || '—'
|
||||||
|
const isWebGUI = String(t.target_port) === '4444'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<tr key={`${t.agentId}-${tid}`} className="hover:bg-gray-800/50">
|
||||||
|
<td className="px-4 py-2.5">
|
||||||
|
<Link to={`/agents/${t.agentId}`} className="flex items-center gap-2 hover:text-orange-400 transition-colors">
|
||||||
|
<StatusBadge status={t.agentStatus} size="dot" />
|
||||||
|
<div>
|
||||||
|
<div className="text-white text-sm">{t.agentName}</div>
|
||||||
|
<div className="text-xs text-gray-500">{t.agentIp}</div>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-2.5 text-white font-mono text-xs">
|
||||||
|
{target}
|
||||||
|
{isWebGUI && <span className="ml-2 text-xs text-orange-400">(WebGUI)</span>}
|
||||||
|
{String(t.target_port) === '22' && <span className="ml-2 text-xs text-blue-400">(SSH)</span>}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-2.5">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-gray-400 font-mono text-xs">
|
||||||
|
{proxyPort ? `${BACKEND_HOST}:${proxyPort}` : '—'}
|
||||||
|
</span>
|
||||||
|
{isWebGUI && proxyPort && (
|
||||||
|
<a
|
||||||
|
href={`https://${BACKEND_HOST}:${proxyPort}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener"
|
||||||
|
className="text-orange-400 hover:text-orange-300"
|
||||||
|
title="WebGUI oeffnen"
|
||||||
|
>
|
||||||
|
<ExternalLink className="w-3.5 h-3.5" />
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-2.5">
|
||||||
|
<span className="inline-flex items-center gap-1.5 text-xs text-green-400">
|
||||||
|
<span className="w-1.5 h-1.5 rounded-full bg-green-400 animate-pulse" />
|
||||||
|
aktiv
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-2.5 text-gray-500 text-xs">
|
||||||
|
{t.created_at ? new Date(t.created_at).toLocaleString('de-DE') : '—'}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-2.5 text-right">
|
||||||
|
<button
|
||||||
|
onClick={() => closeTunnel(t.agentId, tid)}
|
||||||
|
className="text-red-400 hover:text-red-300 p-1 rounded hover:bg-red-900/30 transition-colors"
|
||||||
|
title="Tunnel schliessen"
|
||||||
|
>
|
||||||
|
<Unplug className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})()}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@ -14,6 +14,7 @@ set -e
|
|||||||
|
|
||||||
BASEDIR="/tmp"
|
BASEDIR="/tmp"
|
||||||
BINARY="${BASEDIR}/rmm-agent"
|
BINARY="${BASEDIR}/rmm-agent"
|
||||||
|
UPDATER_BINARY="${BASEDIR}/rmm-updater"
|
||||||
|
|
||||||
echo "========================================"
|
echo "========================================"
|
||||||
echo " RMM Agent Plugin Installer"
|
echo " RMM Agent Plugin Installer"
|
||||||
@ -28,18 +29,27 @@ if [ ! -f "${BINARY}" ]; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# Alten Agent stoppen falls vorhanden
|
# Alten Agent stoppen falls vorhanden
|
||||||
echo "[1/7] Alten Agent stoppen..."
|
echo "[1/8] Alte Dienste stoppen..."
|
||||||
|
/usr/local/etc/rc.d/rmm_updater stop 2>/dev/null || true
|
||||||
/usr/local/etc/rc.d/rmm_agent stop 2>/dev/null || true
|
/usr/local/etc/rc.d/rmm_agent stop 2>/dev/null || true
|
||||||
pkill -9 -f rmm-agent 2>/dev/null || true
|
pkill -9 -f rmm-agent 2>/dev/null || true
|
||||||
|
pkill -9 -f rmm-updater 2>/dev/null || true
|
||||||
|
|
||||||
# Binary installieren
|
# Binaries installieren
|
||||||
echo "[2/7] Binary installieren..."
|
echo "[2/8] Binaries installieren..."
|
||||||
mkdir -p /usr/local/rmm
|
mkdir -p /usr/local/rmm
|
||||||
cp "${BINARY}" /usr/local/rmm/rmm-agent
|
cp "${BINARY}" /usr/local/rmm/rmm-agent
|
||||||
chmod +x /usr/local/rmm/rmm-agent
|
chmod +x /usr/local/rmm/rmm-agent
|
||||||
|
if [ -f "${UPDATER_BINARY}" ]; then
|
||||||
|
cp "${UPDATER_BINARY}" /usr/local/rmm/rmm-updater
|
||||||
|
chmod +x /usr/local/rmm/rmm-updater
|
||||||
|
echo " Updater installiert"
|
||||||
|
else
|
||||||
|
echo " Updater-Binary nicht gefunden — uebersprungen"
|
||||||
|
fi
|
||||||
|
|
||||||
# rc.d Script
|
# rc.d Script
|
||||||
echo "[3/7] rc.d Service installieren..."
|
echo "[3/8] rc.d Service installieren..."
|
||||||
cat > /usr/local/etc/rc.d/rmm_agent << 'RCEOF'
|
cat > /usr/local/etc/rc.d/rmm_agent << 'RCEOF'
|
||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
#
|
#
|
||||||
@ -110,8 +120,69 @@ run_rc_command "$1"
|
|||||||
RCEOF
|
RCEOF
|
||||||
chmod +x /usr/local/etc/rc.d/rmm_agent
|
chmod +x /usr/local/etc/rc.d/rmm_agent
|
||||||
|
|
||||||
|
# Updater rc.d Service
|
||||||
|
cat > /usr/local/etc/rc.d/rmm_updater << 'RCEOF2'
|
||||||
|
#!/bin/sh
|
||||||
|
#
|
||||||
|
# PROVIDE: rmm_updater
|
||||||
|
# REQUIRE: NETWORKING rmm_agent
|
||||||
|
# KEYWORD: shutdown
|
||||||
|
|
||||||
|
. /etc/rc.subr
|
||||||
|
|
||||||
|
name="rmm_updater"
|
||||||
|
rcvar="${name}_enable"
|
||||||
|
command="/usr/local/rmm/rmm-updater"
|
||||||
|
pidfile="/var/run/${name}.pid"
|
||||||
|
logfile="/var/log/rmm-updater.log"
|
||||||
|
|
||||||
|
start_cmd="${name}_start"
|
||||||
|
stop_cmd="${name}_stop"
|
||||||
|
status_cmd="${name}_status"
|
||||||
|
|
||||||
|
rmm_updater_start()
|
||||||
|
{
|
||||||
|
if [ ! -f "${command}" ]; then
|
||||||
|
echo "rmm-updater binary not found: ${command}"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
if [ -f "$pidfile" ] && kill -0 $(cat "$pidfile") 2>/dev/null; then
|
||||||
|
echo "${name} already running"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
echo "Starting ${name}."
|
||||||
|
/usr/sbin/daemon -f -p "$pidfile" -o "$logfile" "$command"
|
||||||
|
}
|
||||||
|
|
||||||
|
rmm_updater_stop()
|
||||||
|
{
|
||||||
|
if [ -f "${pidfile}" ]; then
|
||||||
|
echo "Stopping ${name}."
|
||||||
|
kill $(cat ${pidfile}) 2>/dev/null
|
||||||
|
rm -f ${pidfile}
|
||||||
|
else
|
||||||
|
echo "${name} is not running."
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
rmm_updater_status()
|
||||||
|
{
|
||||||
|
if [ -f "${pidfile}" ] && kill -0 $(cat ${pidfile}) 2>/dev/null; then
|
||||||
|
echo "${name} is running as pid $(cat ${pidfile})."
|
||||||
|
else
|
||||||
|
echo "${name} is not running."
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
load_rc_config $name
|
||||||
|
: ${rmm_updater_enable:="NO"}
|
||||||
|
run_rc_command "$1"
|
||||||
|
RCEOF2
|
||||||
|
chmod +x /usr/local/etc/rc.d/rmm_updater
|
||||||
|
|
||||||
# MVC Plugin installieren
|
# MVC Plugin installieren
|
||||||
echo "[4/7] OPNsense MVC Plugin installieren..."
|
echo "[4/8] OPNsense MVC Plugin installieren..."
|
||||||
|
|
||||||
# Model
|
# Model
|
||||||
mkdir -p /usr/local/opnsense/mvc/app/models/OPNsense/RMMAgent/Menu
|
mkdir -p /usr/local/opnsense/mvc/app/models/OPNsense/RMMAgent/Menu
|
||||||
@ -393,7 +464,7 @@ cat > /usr/local/opnsense/mvc/app/views/OPNsense/RMMAgent/general.volt << 'VOLTE
|
|||||||
VOLTEOF
|
VOLTEOF
|
||||||
|
|
||||||
# configd actions
|
# configd actions
|
||||||
echo "[5/7] configd Actions installieren..."
|
echo "[5/8] configd Actions installieren..."
|
||||||
cat > /usr/local/opnsense/service/conf/actions.d/actions_rmmagent.conf << 'ACTEOF'
|
cat > /usr/local/opnsense/service/conf/actions.d/actions_rmmagent.conf << 'ACTEOF'
|
||||||
[start]
|
[start]
|
||||||
command:/usr/local/etc/rc.d/rmm_agent start
|
command:/usr/local/etc/rc.d/rmm_agent start
|
||||||
@ -427,7 +498,7 @@ message:Reconfiguring RMM Agent
|
|||||||
ACTEOF
|
ACTEOF
|
||||||
|
|
||||||
# Setup-Script
|
# Setup-Script
|
||||||
echo "[6/7] Setup-Script installieren..."
|
echo "[6/8] Setup-Script installieren..."
|
||||||
mkdir -p /usr/local/opnsense/scripts/rmmagent
|
mkdir -p /usr/local/opnsense/scripts/rmmagent
|
||||||
cat > /usr/local/opnsense/scripts/rmmagent/setup.sh << 'SETUPEOF'
|
cat > /usr/local/opnsense/scripts/rmmagent/setup.sh << 'SETUPEOF'
|
||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
@ -479,7 +550,7 @@ SETUPEOF
|
|||||||
chmod +x /usr/local/opnsense/scripts/rmmagent/setup.sh
|
chmod +x /usr/local/opnsense/scripts/rmmagent/setup.sh
|
||||||
|
|
||||||
# Plugin Hook
|
# Plugin Hook
|
||||||
echo "[7/7] Plugin-Hook registrieren..."
|
echo "[7/8] Plugin-Hook registrieren..."
|
||||||
cat > /usr/local/etc/inc/plugins.inc.d/rmmagent.inc << 'INCEOF'
|
cat > /usr/local/etc/inc/plugins.inc.d/rmmagent.inc << 'INCEOF'
|
||||||
<?php
|
<?php
|
||||||
use OPNsense\RMMAgent\RMMAgent;
|
use OPNsense\RMMAgent\RMMAgent;
|
||||||
@ -508,6 +579,16 @@ INCEOF
|
|||||||
rm -f /var/lib/php/cache/_usr_local_opnsense_mvc_app_views_opnsense_rmmagent_*.php
|
rm -f /var/lib/php/cache/_usr_local_opnsense_mvc_app_views_opnsense_rmmagent_*.php
|
||||||
service configd restart
|
service configd restart
|
||||||
|
|
||||||
|
# Updater aktivieren
|
||||||
|
echo "[8/8] Updater aktivieren..."
|
||||||
|
if [ -f /usr/local/rmm/rmm-updater ]; then
|
||||||
|
sysrc rmm_updater_enable=YES 2>/dev/null || true
|
||||||
|
/usr/local/etc/rc.d/rmm_updater start 2>/dev/null || true
|
||||||
|
echo " Updater aktiviert und gestartet"
|
||||||
|
else
|
||||||
|
echo " Kein Updater-Binary — uebersprungen"
|
||||||
|
fi
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "========================================"
|
echo "========================================"
|
||||||
echo " RMM Agent Plugin installiert!"
|
echo " RMM Agent Plugin installiert!"
|
||||||
|
|||||||
62
opnsense-plugin/src/usr/local/etc/rc.d/rmm_updater
Normal file
62
opnsense-plugin/src/usr/local/etc/rc.d/rmm_updater
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
# PROVIDE: rmm_updater
|
||||||
|
# REQUIRE: NETWORKING rmm_agent
|
||||||
|
# KEYWORD: shutdown
|
||||||
|
|
||||||
|
. /etc/rc.subr
|
||||||
|
|
||||||
|
name="rmm_updater"
|
||||||
|
rcvar="${name}_enable"
|
||||||
|
command="/usr/local/rmm/rmm-updater"
|
||||||
|
pidfile="/var/run/${name}.pid"
|
||||||
|
command_args=""
|
||||||
|
|
||||||
|
start_cmd="${name}_start"
|
||||||
|
stop_cmd="${name}_stop"
|
||||||
|
status_cmd="${name}_status"
|
||||||
|
|
||||||
|
rmm_updater_start() {
|
||||||
|
if [ -f "$pidfile" ]; then
|
||||||
|
if kill -0 $(cat "$pidfile") 2>/dev/null; then
|
||||||
|
echo "${name} already running"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
rm -f "$pidfile"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Starting ${name}."
|
||||||
|
/usr/sbin/daemon -f -p "$pidfile" "$command" $command_args
|
||||||
|
}
|
||||||
|
|
||||||
|
rmm_updater_stop() {
|
||||||
|
if [ -f "$pidfile" ]; then
|
||||||
|
pid=$(cat "$pidfile")
|
||||||
|
if kill -0 "$pid" 2>/dev/null; then
|
||||||
|
echo "Stopping ${name}."
|
||||||
|
kill "$pid"
|
||||||
|
rm -f "$pidfile"
|
||||||
|
else
|
||||||
|
echo "${name} not running (stale pidfile)"
|
||||||
|
rm -f "$pidfile"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo "${name} not running"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
rmm_updater_status() {
|
||||||
|
if [ -f "$pidfile" ]; then
|
||||||
|
pid=$(cat "$pidfile")
|
||||||
|
if kill -0 "$pid" 2>/dev/null; then
|
||||||
|
echo "${name} is running as pid $pid"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
echo "${name} is not running"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
load_rc_config $name
|
||||||
|
: ${rmm_updater_enable:="NO"}
|
||||||
|
run_rc_command "$1"
|
||||||
5
updater/go.mod
Normal file
5
updater/go.mod
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
module github.com/cynfo/rmm-updater
|
||||||
|
|
||||||
|
go 1.24.0
|
||||||
|
|
||||||
|
require gopkg.in/yaml.v3 v3.0.1
|
||||||
4
updater/go.sum
Normal file
4
updater/go.sum
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
254
updater/main.go
Normal file
254
updater/main.go
Normal file
@ -0,0 +1,254 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config wird aus der gleichen config.yaml wie der Agent gelesen
|
||||||
|
type Config struct {
|
||||||
|
BackendURL string `yaml:"backend_url"`
|
||||||
|
APIKey string `yaml:"api_key"`
|
||||||
|
AgentName string `yaml:"agent_name"`
|
||||||
|
Insecure bool `yaml:"insecure"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type HeartbeatResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
UpdateAvailable bool `json:"update_available"`
|
||||||
|
UpdateVersion string `json:"update_version"`
|
||||||
|
UpdateHash string `json:"update_hash"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
agentBinaryPath = "/usr/local/rmm/rmm-agent"
|
||||||
|
configPath = "/usr/local/rmm/config.yaml"
|
||||||
|
agentIDPath = "/usr/local/rmm/agent_id"
|
||||||
|
checkInterval = 60 * time.Second
|
||||||
|
logPrefix = "[rmm-updater] "
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
log.SetPrefix(logPrefix)
|
||||||
|
log.SetFlags(log.LstdFlags)
|
||||||
|
|
||||||
|
log.Println("RMM Updater gestartet")
|
||||||
|
|
||||||
|
cfg, err := loadConfig()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Config laden fehlgeschlagen: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
agentID, err := loadAgentID()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Agent-ID laden fehlgeschlagen: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Backend: %s, Agent: %s (%s)", cfg.BackendURL, cfg.AgentName, agentID)
|
||||||
|
|
||||||
|
client := &http.Client{
|
||||||
|
Timeout: 120 * time.Second,
|
||||||
|
Transport: &http.Transport{
|
||||||
|
TLSClientConfig: &tls.Config{InsecureSkipVerify: cfg.Insecure},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for {
|
||||||
|
checkAndUpdate(client, cfg, agentID)
|
||||||
|
time.Sleep(checkInterval)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadConfig() (*Config, error) {
|
||||||
|
data, err := os.ReadFile(configPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var cfg Config
|
||||||
|
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// Default: insecure wenn nicht explizit gesetzt (self-signed certs sind Standard)
|
||||||
|
// yaml unmarshal setzt false als default fuer bool — wir brauchen true als default
|
||||||
|
// Workaround: immer insecure wenn Backend self-signed nutzt
|
||||||
|
cfg.Insecure = true
|
||||||
|
return &cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadAgentID() (string, error) {
|
||||||
|
data, err := os.ReadFile(agentIDPath)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("agent_id nicht gefunden: %v", err)
|
||||||
|
}
|
||||||
|
id := string(data)
|
||||||
|
if id == "" {
|
||||||
|
return "", fmt.Errorf("agent_id leer")
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkAndUpdate(client *http.Client, cfg *Config, agentID string) {
|
||||||
|
// Firmware-Info vom Backend holen
|
||||||
|
url := fmt.Sprintf("%s/api/v1/firmware", cfg.BackendURL)
|
||||||
|
req, _ := http.NewRequest("GET", url, nil)
|
||||||
|
req.Header.Set("X-API-Key", cfg.APIKey)
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Firmware-Info Abfrage fehlgeschlagen: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
return // Keine Firmware vorhanden
|
||||||
|
}
|
||||||
|
|
||||||
|
var info struct {
|
||||||
|
Available bool `json:"available"`
|
||||||
|
Version string `json:"version"`
|
||||||
|
Hash string `json:"hash"`
|
||||||
|
Size int `json:"size"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&info); err != nil || !info.Available {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pruefen ob lokale Binary schon die richtige Version hat
|
||||||
|
if localHash, err := hashFile(agentBinaryPath); err == nil && localHash == info.Hash {
|
||||||
|
return // Schon aktuell
|
||||||
|
}
|
||||||
|
|
||||||
|
// Heartbeat-Response pruefen: Update angefordert?
|
||||||
|
hbURL := fmt.Sprintf("%s/api/v1/agents/%s", cfg.BackendURL, agentID)
|
||||||
|
hbReq, _ := http.NewRequest("GET", hbURL, nil)
|
||||||
|
hbReq.Header.Set("X-API-Key", cfg.APIKey)
|
||||||
|
|
||||||
|
hbResp, err := client.Do(hbReq)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer hbResp.Body.Close()
|
||||||
|
|
||||||
|
var agentInfo struct {
|
||||||
|
Agent struct {
|
||||||
|
UpdateRequested bool `json:"update_requested"`
|
||||||
|
} `json:"agent"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(hbResp.Body).Decode(&agentInfo); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !agentInfo.Agent.UpdateRequested {
|
||||||
|
return // Kein Update angefordert
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Update verfuegbar: v%s (%d bytes)", info.Version, info.Size)
|
||||||
|
|
||||||
|
// Binary herunterladen
|
||||||
|
if err := downloadAndApply(client, cfg, agentID, info.Hash); err != nil {
|
||||||
|
log.Printf("Update fehlgeschlagen: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Update auf v%s erfolgreich", info.Version)
|
||||||
|
}
|
||||||
|
|
||||||
|
func downloadAndApply(client *http.Client, cfg *Config, agentID, expectedHash string) error {
|
||||||
|
// Download
|
||||||
|
url := fmt.Sprintf("%s/api/v1/firmware/download", cfg.BackendURL)
|
||||||
|
req, _ := http.NewRequest("GET", url, nil)
|
||||||
|
req.Header.Set("X-API-Key", cfg.APIKey)
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("download fehlgeschlagen: %v", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
return fmt.Errorf("download HTTP %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
binary, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("download lesen fehlgeschlagen: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash verifizieren
|
||||||
|
hash := sha256.Sum256(binary)
|
||||||
|
hashStr := hex.EncodeToString(hash[:])
|
||||||
|
if hashStr != expectedHash {
|
||||||
|
return fmt.Errorf("hash mismatch: erwartet %s, bekommen %s", expectedHash[:16], hashStr[:16])
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Binary heruntergeladen (%d bytes, Hash OK)", len(binary))
|
||||||
|
|
||||||
|
// Temporaere Datei schreiben
|
||||||
|
tmpPath := agentBinaryPath + ".new"
|
||||||
|
if err := os.WriteFile(tmpPath, binary, 0755); err != nil {
|
||||||
|
return fmt.Errorf("tmp schreiben fehlgeschlagen: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agent stoppen
|
||||||
|
log.Println("Agent wird gestoppt...")
|
||||||
|
exec.Command("/usr/sbin/service", "rmm_agent", "stop").Run()
|
||||||
|
time.Sleep(2 * time.Second)
|
||||||
|
|
||||||
|
// Binary ersetzen
|
||||||
|
backupPath := agentBinaryPath + ".bak"
|
||||||
|
if _, err := os.Stat(agentBinaryPath); err == nil {
|
||||||
|
os.Rename(agentBinaryPath, backupPath)
|
||||||
|
}
|
||||||
|
if err := os.Rename(tmpPath, agentBinaryPath); err != nil {
|
||||||
|
// Rollback
|
||||||
|
os.Rename(backupPath, agentBinaryPath)
|
||||||
|
return fmt.Errorf("binary ersetzen fehlgeschlagen: %v", err)
|
||||||
|
}
|
||||||
|
os.Chmod(agentBinaryPath, 0755)
|
||||||
|
|
||||||
|
// Agent starten
|
||||||
|
log.Println("Agent wird gestartet...")
|
||||||
|
if err := exec.Command("/usr/sbin/service", "rmm_agent", "start").Run(); err != nil {
|
||||||
|
log.Printf("WARNUNG: Agent-Start fehlgeschlagen: %v — versuche Rollback", err)
|
||||||
|
os.Rename(backupPath, agentBinaryPath)
|
||||||
|
exec.Command("/usr/sbin/service", "rmm_agent", "start").Run()
|
||||||
|
return fmt.Errorf("agent start fehlgeschlagen")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Backup aufraeumen
|
||||||
|
os.Remove(backupPath)
|
||||||
|
|
||||||
|
// Update-Flag loeschen
|
||||||
|
clearURL := fmt.Sprintf("%s/api/v1/agents/%s/request-update", cfg.BackendURL, agentID)
|
||||||
|
clearReq, _ := http.NewRequest("DELETE", clearURL, nil)
|
||||||
|
clearReq.Header.Set("X-API-Key", cfg.APIKey)
|
||||||
|
client.Do(clearReq)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func hashFile(path string) (string, error) {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
hash := sha256.Sum256(data)
|
||||||
|
return hex.EncodeToString(hash[:]), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveDir gibt das Verzeichnis eines Pfads zurueck
|
||||||
|
func resolveDir(path string) string {
|
||||||
|
return filepath.Dir(path)
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user