From 10684dfc0a0406d3111dad2077e5d10ee559f07e Mon Sep 17 00:00:00 2001 From: cynfo3000 Date: Sun, 8 Mar 2026 19:17:43 +0100 Subject: [PATCH] feat: TOTP 2FA + diverse Verbesserungen 2FA (TOTP): - backend/api/auth.go: zweistufiger Login-Flow mit Pending-Token (5min), Endpunkte /2fa/validate, /2fa/setup, /2fa/confirm, /2fa/disable - backend/db/users.go: GetUserByID, SetTOTPSecret, EnableTOTP, DisableTOTP - backend/db/postgres.go: Migration totp_secret + totp_enabled Spalten - backend/models/user.go: TOTPEnabled/TOTPSecret Felder, neue Request-Typen - backend/main.go: neue Routen registriert (/2fa/validate ohne Auth, rest geschuetzt) - backend/go.mod+sum: github.com/pquerna/otp hinzugefuegt - frontend/src/pages/Login.jsx: zweistufiger Login (Passwort -> TOTP) - frontend/src/pages/SettingsPage.jsx: TwoFactorSection mit Setup/Deaktivieren - frontend/src/stores/auth.js: validateTOTP Action - frontend/src/api/client.js: setupTOTP, confirmTOTP, disableTOTP, validateTOTP Weitere Aenderungen (unstaged -> jetzt committed): - frontend/src/components/ScriptModal.jsx: neu - frontend/src/components/AgentPanel.jsx: Erweiterungen - frontend/src/components/ProxmoxPanel.jsx: Erweiterungen - agent-linux/ws/handler.go: Erweiterungen - backend/api/scheduler.go + tasks.go: Erweiterungen - backend/db/tasks.go + models/task.go: Erweiterungen --- agent-linux/ws/handler.go | 55 ++++++ backend/api/auth.go | 212 ++++++++++++++++++++++- backend/api/scheduler.go | 41 +++++ backend/api/tasks.go | 11 +- backend/db/postgres.go | 6 + backend/db/tasks.go | 29 +++- backend/db/users.go | 46 ++++- backend/go.mod | 2 + backend/go.sum | 4 + backend/main.go | 6 + backend/models/task.go | 2 + backend/models/user.go | 29 +++- frontend/src/api/client.js | 20 ++- frontend/src/components/AgentPanel.jsx | 14 +- frontend/src/components/ProxmoxPanel.jsx | 96 +++++++--- frontend/src/components/ScriptModal.jsx | 119 +++++++++++++ frontend/src/pages/Login.jsx | 153 +++++++++++----- frontend/src/pages/SettingsPage.jsx | 167 ++++++++++++++++-- frontend/src/stores/auth.js | 12 +- 19 files changed, 926 insertions(+), 98 deletions(-) create mode 100644 frontend/src/components/ScriptModal.jsx diff --git a/agent-linux/ws/handler.go b/agent-linux/ws/handler.go index e16ee47..d90d79b 100644 --- a/agent-linux/ws/handler.go +++ b/agent-linux/ws/handler.go @@ -45,6 +45,8 @@ func (h *Handler) HandleCommand(msg Message) { response = h.handleUpdateCheck(msg) case "update": response = h.handleUpdate(msg) + case "zpoolscrub": + response = h.handleZpoolScrub(msg) case "pty_start": response = h.handlePTYStart(msg) case "pty_stop": @@ -426,3 +428,56 @@ func (h *Handler) handleUpdate(msg Message) Message { return response } + +// handleZpoolScrub: alle ZFS-Pools scrubben +func (h *Handler) handleZpoolScrub(msg Message) Message { + response := Message{Type: "response", ID: msg.ID} + + log.Println("ZFS Scrub gestartet (alle Pools)...") + + // Alle Pools ermitteln + poolOutput, err := h.runCommand("zpool list -H -o name 2>&1", 30) + if err != nil || strings.TrimSpace(poolOutput) == "" { + response.Status = "error" + response.Error = "Keine ZFS-Pools gefunden oder zpool nicht verfügbar" + return response + } + + pools := []string{} + for _, line := range strings.Split(strings.TrimSpace(poolOutput), "\n") { + name := strings.TrimSpace(line) + if name != "" { + pools = append(pools, name) + } + } + + results := map[string]string{} + scrubErrors := 0 + + // Jeden Pool scrubben (nicht-blockierend: scrub startet sofort und läuft im Hintergrund) + for _, pool := range pools { + log.Printf("ZFS Scrub starte: %s", pool) + out, err := h.runCommand(fmt.Sprintf("zpool scrub %s 2>&1", pool), 60) + if err != nil { + results[pool] = fmt.Sprintf("Fehler: %v — %s", err, strings.TrimSpace(out)) + scrubErrors++ + } else { + results[pool] = "Scrub gestartet" + } + } + + if scrubErrors > 0 { + response.Status = "error" + response.Error = fmt.Sprintf("%d Pool(s) konnten nicht gestartet werden", scrubErrors) + } else { + response.Status = "ok" + } + + log.Printf("ZFS Scrub: %d Pool(s) gestartet, %d Fehler", len(pools), scrubErrors) + response.Data = map[string]interface{}{ + "pools": pools, + "results": results, + "message": fmt.Sprintf("Scrub auf %d Pool(s) gestartet", len(pools)-scrubErrors), + } + return response +} diff --git a/backend/api/auth.go b/backend/api/auth.go index ebfceb6..63a9194 100644 --- a/backend/api/auth.go +++ b/backend/api/auth.go @@ -12,6 +12,7 @@ import ( "github.com/cynfo/rmm-backend/db" "github.com/cynfo/rmm-backend/models" "github.com/golang-jwt/jwt/v5" + "github.com/pquerna/otp/totp" "golang.org/x/crypto/bcrypt" ) @@ -21,9 +22,10 @@ type AuthHandler struct { } type JWTClaims struct { - UserID int `json:"user_id"` - Username string `json:"username"` - Role string `json:"role"` + UserID int `json:"user_id"` + Username string `json:"username"` + Role string `json:"role"` + TOTPPending bool `json:"totp_pending,omitempty"` // temp token während 2FA-Schritt jwt.RegisteredClaims } @@ -70,6 +72,22 @@ func (a *AuthHandler) GenerateToken(user *models.User) (string, time.Time, error return signed, expiresAt, err } +// Kurzlebiger Token nur für den TOTP-Schritt (5 Minuten, kein echter API-Zugriff) +func (a *AuthHandler) generateTOTPPendingToken(user *models.User) (string, error) { + claims := JWTClaims{ + UserID: user.ID, + Username: user.Username, + Role: user.Role, + TOTPPending: true, + RegisteredClaims: jwt.RegisteredClaims{ + ExpiresAt: jwt.NewNumericDate(time.Now().Add(5 * time.Minute)), + IssuedAt: jwt.NewNumericDate(time.Now()), + }, + } + token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + return token.SignedString(a.secret) +} + func (a *AuthHandler) ValidateToken(tokenStr string) (*JWTClaims, error) { token, err := jwt.ParseWithClaims(tokenStr, &JWTClaims{}, func(t *jwt.Token) (interface{}, error) { if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { @@ -84,6 +102,10 @@ func (a *AuthHandler) ValidateToken(tokenStr string) (*JWTClaims, error) { if !ok || !token.Valid { return nil, fmt.Errorf("invalid token") } + // Echte API-Calls mit Pending-Token ablehnen + if claims.TOTPPending { + return nil, fmt.Errorf("totp pending token not valid for api access") + } return claims, nil } @@ -106,6 +128,22 @@ func (a *AuthHandler) Login(w http.ResponseWriter, r *http.Request) { return } + // 2FA aktiv → Pending-Token zurückgeben + if user.TOTPEnabled { + pendingToken, err := a.generateTOTPPendingToken(user) + if err != nil { + writeError(w, http.StatusInternalServerError, "Token-Generierung fehlgeschlagen") + return + } + go a.db.AddAuditLog(user.Username, "login_2fa_pending", "user", "", user.Username, "", r.RemoteAddr) + writeJSON(w, http.StatusOK, models.LoginResponse{ + TOTPRequired: true, + TOTPToken: pendingToken, + }) + return + } + + // Kein 2FA → direkt JWT token, expiresAt, err := a.GenerateToken(user) if err != nil { writeError(w, http.StatusInternalServerError, "Token-Generierung fehlgeschlagen") @@ -113,17 +151,178 @@ func (a *AuthHandler) Login(w http.ResponseWriter, r *http.Request) { } a.db.UpdateUserLastLogin(user.ID) - - // Audit log go a.db.AddAuditLog(user.Username, "login", "user", "", user.Username, "", r.RemoteAddr) writeJSON(w, http.StatusOK, models.LoginResponse{ Token: token, ExpiresAt: expiresAt.Format(time.RFC3339), - User: *user, + User: user, }) } +// POST /api/v1/auth/2fa/validate — zweiter Schritt beim Login +func (a *AuthHandler) TOTPValidate(w http.ResponseWriter, r *http.Request) { + var req models.TOTPValidateRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeError(w, http.StatusBadRequest, "Ungueltige Anfrage") + return + } + + // Pending-Token parsen (ohne ValidateToken, der lehnt Pending-Tokens ab) + jwtToken, err := jwt.ParseWithClaims(req.TOTPToken, &JWTClaims{}, func(t *jwt.Token) (interface{}, error) { + if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, fmt.Errorf("unexpected signing method") + } + return a.secret, nil + }) + if err != nil { + writeError(w, http.StatusUnauthorized, "Ungueltige Session") + return + } + claims, ok := jwtToken.Claims.(*JWTClaims) + if !ok || !jwtToken.Valid || !claims.TOTPPending { + writeError(w, http.StatusUnauthorized, "Ungueltige Session") + return + } + + user, err := a.db.GetUserByID(claims.UserID) + if err != nil || user == nil || !user.TOTPEnabled { + writeError(w, http.StatusUnauthorized, "Ungueltige Session") + return + } + + if !totp.Validate(req.Code, user.TOTPSecret) { + writeError(w, http.StatusUnauthorized, "Ungültiger 2FA-Code") + return + } + + token, expiresAt, err := a.GenerateToken(user) + if err != nil { + writeError(w, http.StatusInternalServerError, "Token-Generierung fehlgeschlagen") + return + } + + a.db.UpdateUserLastLogin(user.ID) + go a.db.AddAuditLog(user.Username, "login_2fa_success", "user", "", user.Username, "", r.RemoteAddr) + + writeJSON(w, http.StatusOK, models.LoginResponse{ + Token: token, + ExpiresAt: expiresAt.Format(time.RFC3339), + User: user, + }) +} + +// POST /api/v1/auth/2fa/setup — Secret generieren, QR-URI zurückgeben +func (a *AuthHandler) TOTPSetup(w http.ResponseWriter, r *http.Request) { + claims, ok := r.Context().Value(UserContextKey).(*JWTClaims) + if !ok { + writeError(w, http.StatusUnauthorized, "Nicht authentifiziert") + return + } + + user, err := a.db.GetUserByID(claims.UserID) + if err != nil || user == nil { + writeError(w, http.StatusNotFound, "User nicht gefunden") + return + } + + key, err := totp.Generate(totp.GenerateOpts{ + Issuer: "cynfo RMM", + AccountName: user.Username, + Period: 30, + Digits: 6, + }) + if err != nil { + writeError(w, http.StatusInternalServerError, "TOTP-Generierung fehlgeschlagen") + return + } + + if err := a.db.SetTOTPSecret(user.ID, key.Secret()); err != nil { + writeError(w, http.StatusInternalServerError, "Speichern fehlgeschlagen") + return + } + + writeJSON(w, http.StatusOK, models.TOTPSetupResponse{ + Secret: key.Secret(), + URI: key.URL(), + }) +} + +// POST /api/v1/auth/2fa/confirm — ersten Code prüfen und 2FA aktivieren +func (a *AuthHandler) TOTPConfirm(w http.ResponseWriter, r *http.Request) { + claims, ok := r.Context().Value(UserContextKey).(*JWTClaims) + if !ok { + writeError(w, http.StatusUnauthorized, "Nicht authentifiziert") + return + } + + var req models.TOTPConfirmRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeError(w, http.StatusBadRequest, "Ungueltige Anfrage") + return + } + + user, err := a.db.GetUserByID(claims.UserID) + if err != nil || user == nil || user.TOTPSecret == "" { + writeError(w, http.StatusBadRequest, "Kein Setup gefunden — bitte zuerst /2fa/setup aufrufen") + return + } + + if !totp.Validate(req.Code, user.TOTPSecret) { + writeError(w, http.StatusUnauthorized, "Ungültiger Code") + return + } + + if err := a.db.EnableTOTP(user.ID); err != nil { + writeError(w, http.StatusInternalServerError, "Aktivierung fehlgeschlagen") + return + } + + go a.db.AddAuditLog(claims.Username, "2fa_enabled", "user", "", claims.Username, "", r.RemoteAddr) + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) +} + +// POST /api/v1/auth/2fa/disable — 2FA deaktivieren (Passwort + aktueller Code nötig) +func (a *AuthHandler) TOTPDisable(w http.ResponseWriter, r *http.Request) { + claims, ok := r.Context().Value(UserContextKey).(*JWTClaims) + if !ok { + writeError(w, http.StatusUnauthorized, "Nicht authentifiziert") + return + } + + var req models.TOTPDisableRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeError(w, http.StatusBadRequest, "Ungueltige Anfrage") + return + } + + user, err := a.db.GetUserByID(claims.UserID) + if err != nil || user == nil { + writeError(w, http.StatusNotFound, "User nicht gefunden") + return + } + + if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil { + writeError(w, http.StatusUnauthorized, "Falsches Passwort") + return + } + + if user.TOTPEnabled { + if !totp.Validate(req.Code, user.TOTPSecret) { + writeError(w, http.StatusUnauthorized, "Ungültiger 2FA-Code") + return + } + } + + if err := a.db.DisableTOTP(user.ID); err != nil { + writeError(w, http.StatusInternalServerError, "Deaktivierung fehlgeschlagen") + return + } + + go a.db.AddAuditLog(claims.Username, "2fa_disabled", "user", "", claims.Username, "", r.RemoteAddr) + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) +} + // GET /api/v1/auth/me func (a *AuthHandler) Me(w http.ResponseWriter, r *http.Request) { claims, ok := r.Context().Value(UserContextKey).(*JWTClaims) @@ -144,4 +343,5 @@ func (a *AuthHandler) Me(w http.ResponseWriter, r *http.Request) { // SetupAuthRoutes registriert Auth-Routes (ohne Auth-Middleware) func (a *AuthHandler) SetupAuthRoutes(mux *http.ServeMux) { mux.HandleFunc("POST /api/v1/auth/login", a.Login) + mux.HandleFunc("POST /api/v1/auth/2fa/validate", a.TOTPValidate) } diff --git a/backend/api/scheduler.go b/backend/api/scheduler.go index ab15fe0..b2bdacb 100644 --- a/backend/api/scheduler.go +++ b/backend/api/scheduler.go @@ -63,6 +63,17 @@ func (s *TaskScheduler) executeTask(task models.Task) { result, taskErr = s.executeBackup(task.AgentID) case "update": result, taskErr = s.executeUpdateWithHealthCheck(task.AgentID, task.Reboot, task.HealthCheck, task.HealthCheckTimeout, task.SecurityOnly) + case "zpoolscrub": + result, taskErr = s.executeSimpleCommand(task.AgentID, "zpoolscrub", map[string]interface{}{}) + case "script": + timeout := task.ScriptTimeout + if timeout <= 0 { + timeout = 300 + } + result, taskErr = s.executeSimpleCommand(task.AgentID, "exec", map[string]interface{}{ + "command": task.Script, + "timeout": timeout, + }) default: taskErr = fmt.Errorf("unbekannte Aktion: %s", task.Action) } @@ -106,6 +117,36 @@ func (s *TaskScheduler) executeTask(task models.Task) { } } +// executeSimpleCommand schickt einen beliebigen Command an den Agenten und wartet auf Antwort +func (s *TaskScheduler) executeSimpleCommand(agentID, command string, params map[string]interface{}) (interface{}, error) { + if !s.hub.IsAgentConnected(agentID) { + return nil, fmt.Errorf("Agent nicht verbunden") + } + cmdID := generateID() + cmd := map[string]interface{}{ + "type": "command", + "id": cmdID, + "command": command, + "params": params, + } + responseCh := s.hub.RegisterResponseWaiter(cmdID) + defer s.hub.UnregisterResponseWaiter(cmdID) + cmdJSON, _ := json.Marshal(cmd) + if err := s.hub.SendToAgent(agentID, cmdJSON); err != nil { + return nil, fmt.Errorf("Senden fehlgeschlagen: %w", err) + } + select { + case resp := <-responseCh: + if status, _ := resp["status"].(string); status == "error" { + errMsg, _ := resp["error"].(string) + return resp["data"], fmt.Errorf("%s", errMsg) + } + return resp["data"], nil + case <-time.After(120 * time.Second): + return nil, fmt.Errorf("Timeout nach 120s") + } +} + func (s *TaskScheduler) executeBackup(agentID string) (interface{}, error) { if !s.hub.IsAgentConnected(agentID) { return nil, fmt.Errorf("Agent nicht verbunden") diff --git a/backend/api/tasks.go b/backend/api/tasks.go index b5f0d75..6227732 100644 --- a/backend/api/tasks.go +++ b/backend/api/tasks.go @@ -80,6 +80,8 @@ func (h *Handler) createTask(hub *ws.Hub) http.HandlerFunc { HealthCheck bool `json:"health_check"` HealthCheckTimeout int `json:"health_check_timeout"` SecurityOnly bool `json:"security_only"` + Script string `json:"script"` + ScriptTimeout int `json:"script_timeout"` WebhookURL string `json:"webhook_url"` Active *bool `json:"active"` } @@ -93,8 +95,12 @@ func (h *Handler) createTask(hub *ws.Hub) http.HandlerFunc { return } - if req.Action != "backup" && req.Action != "update" { - writeError(w, http.StatusBadRequest, "Ungueltige Aktion (backup, update)") + if req.Action != "backup" && req.Action != "update" && req.Action != "zpoolscrub" && req.Action != "script" { + writeError(w, http.StatusBadRequest, "Ungueltige Aktion (backup, update, zpoolscrub, script)") + return + } + if req.Action == "script" && req.Script == "" { + writeError(w, http.StatusBadRequest, "Skript-Inhalt darf nicht leer sein") return } @@ -119,6 +125,7 @@ func (h *Handler) createTask(hub *ws.Hub) http.HandlerFunc { req.Name, req.ScheduleType, req.ScheduleTime, req.ScheduleWeekday, req.ScheduleMonthday, req.Reboot, req.HealthCheck, req.HealthCheckTimeout, req.SecurityOnly, active, + req.Script, req.ScriptTimeout, ) if err != nil { log.Printf("Task erstellen fehlgeschlagen: %v", err) diff --git a/backend/db/postgres.go b/backend/db/postgres.go index 0f68b1e..1a3ff65 100644 --- a/backend/db/postgres.go +++ b/backend/db/postgres.go @@ -128,6 +128,10 @@ func (d *Database) migrate() error { return fmt.Errorf("Schema anlegen: %w", err) } + // TOTP 2FA Spalten + d.db.Exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_secret TEXT") + d.db.Exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT false") + // Agents um customer_id erweitern 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)") @@ -266,6 +270,8 @@ func (d *Database) migrate() error { d.db.Exec(`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS last_run TIMESTAMPTZ`) d.db.Exec(`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS next_run TIMESTAMPTZ`) d.db.Exec(`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS run_count INT DEFAULT 0`) + d.db.Exec(`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS script TEXT`) + d.db.Exec(`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS script_timeout INT DEFAULT 300`) d.db.Exec(`CREATE INDEX IF NOT EXISTS idx_tasks_active_next_run ON tasks(active, next_run) WHERE active = TRUE`) // Retention Policy (90 Tage) diff --git a/backend/db/tasks.go b/backend/db/tasks.go index 42b2861..8358136 100644 --- a/backend/db/tasks.go +++ b/backend/db/tasks.go @@ -62,9 +62,10 @@ func CalculateNextRun(scheduleType, scheduleTime string, weekday, monthday *int, func (d *Database) CreateTask(agentID, action, scheduledAt, webhookURL, createdBy string, name, scheduleType, scheduleTime string, weekday, monthday *int, - reboot, healthCheck bool, healthCheckTimeout int, securityOnly bool, active bool) (*models.Task, error) { + reboot, healthCheck bool, healthCheckTimeout int, securityOnly bool, active bool, + script string, scriptTimeout int) (*models.Task, error) { - validActions := map[string]bool{"backup": true, "update": true} + validActions := map[string]bool{"backup": true, "update": true, "zpoolscrub": true, "script": true} if !validActions[action] { return nil, fmt.Errorf("ungueltige Aktion: %s", action) } @@ -103,16 +104,22 @@ func (d *Database) CreateTask(agentID, action, scheduledAt, webhookURL, createdB nextRun = CalculateNextRun(scheduleType, scheduleTime, weekday, monthday, now) } + if scriptTimeout <= 0 { + scriptTimeout = 300 + } + var taskID int err := d.db.QueryRow(` INSERT INTO tasks (agent_id, name, action, scheduled_at, webhook_url, created_by, schedule_type, schedule_time, schedule_weekday, schedule_monthday, - reboot, health_check, health_check_timeout, security_only, active, next_run) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) + reboot, health_check, health_check_timeout, security_only, active, next_run, + script, script_timeout) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) RETURNING id `, agentID, name, action, schedTime, webhookURL, createdBy, scheduleType, scheduleTime, weekday, monthday, - reboot, healthCheck, healthCheckTimeout, securityOnly, active, nextRun).Scan(&taskID) + reboot, healthCheck, healthCheckTimeout, securityOnly, active, nextRun, + script, scriptTimeout).Scan(&taskID) if err != nil { return nil, fmt.Errorf("Task erstellen: %w", err) } @@ -130,7 +137,8 @@ func scanTask(scan func(dest ...interface{}) error) (*models.Task, error) { var name, scheduleType, scheduleTime sql.NullString var scheduleWeekday, scheduleMonthday sql.NullInt32 var reboot, healthCheck, securityOnly, active sql.NullBool - var healthCheckTimeout, runCount sql.NullInt32 + var healthCheckTimeout, runCount, scriptTimeout sql.NullInt32 + var script sql.NullString err := scan( &t.ID, &t.AgentID, &agentName, &customerName, &customerNumber, @@ -139,6 +147,7 @@ func scanTask(scan func(dest ...interface{}) error) (*models.Task, error) { &createdBy, &createdAt, &scheduleType, &scheduleTime, &scheduleWeekday, &scheduleMonthday, &reboot, &healthCheck, &healthCheckTimeout, &securityOnly, &active, &lastRun, &nextRun, &runCount, + &script, &scriptTimeout, ) if err != nil { return nil, err @@ -171,6 +180,11 @@ func scanTask(scan func(dest ...interface{}) error) (*models.Task, error) { t.HealthCheckTimeout = int(healthCheckTimeout.Int32) } t.SecurityOnly = securityOnly.Valid && securityOnly.Bool + t.Script = script.String + t.ScriptTimeout = 300 + if scriptTimeout.Valid && scriptTimeout.Int32 > 0 { + t.ScriptTimeout = int(scriptTimeout.Int32) + } t.Active = !active.Valid || active.Bool t.RunCount = int(runCount.Int32) @@ -215,7 +229,8 @@ const taskSelectCols = `t.id, t.agent_id, COALESCE(a.name, ''), COALESCE(c.name, t.result, t.webhook_url, t.webhook_sent, t.webhook_response, t.created_by, t.created_at, t.schedule_type, t.schedule_time, t.schedule_weekday, t.schedule_monthday, - t.reboot, t.health_check, t.health_check_timeout, COALESCE(t.security_only, FALSE), t.active, t.last_run, t.next_run, t.run_count` + t.reboot, t.health_check, t.health_check_timeout, COALESCE(t.security_only, FALSE), t.active, t.last_run, t.next_run, t.run_count, + COALESCE(t.script, ''), COALESCE(t.script_timeout, 300)` const taskFromJoin = `FROM tasks t LEFT JOIN agents a ON a.id = t.agent_id diff --git a/backend/db/users.go b/backend/db/users.go index 5eb37c7..ba22cd3 100644 --- a/backend/db/users.go +++ b/backend/db/users.go @@ -27,10 +27,11 @@ func (d *Database) CreateUser(username, password, displayName, role string) (*mo func (d *Database) GetUserByUsername(username string) (*models.User, error) { var u models.User var lastLogin sql.NullTime + var totpSecret sql.NullString err := d.db.QueryRow( - "SELECT id, username, password_hash, display_name, role, created_at, last_login FROM users WHERE username = $1", + "SELECT id, username, password_hash, display_name, role, totp_enabled, totp_secret, created_at, last_login FROM users WHERE username = $1", username, - ).Scan(&u.ID, &u.Username, &u.PasswordHash, &u.DisplayName, &u.Role, &u.CreatedAt, &lastLogin) + ).Scan(&u.ID, &u.Username, &u.PasswordHash, &u.DisplayName, &u.Role, &u.TOTPEnabled, &totpSecret, &u.CreatedAt, &lastLogin) if err == sql.ErrNoRows { return nil, nil } @@ -40,9 +41,50 @@ func (d *Database) GetUserByUsername(username string) (*models.User, error) { if lastLogin.Valid { u.LastLogin = &lastLogin.Time } + if totpSecret.Valid { + u.TOTPSecret = totpSecret.String + } return &u, nil } +func (d *Database) GetUserByID(id int) (*models.User, error) { + var u models.User + var lastLogin sql.NullTime + var totpSecret sql.NullString + err := d.db.QueryRow( + "SELECT id, username, password_hash, display_name, role, totp_enabled, totp_secret, created_at, last_login FROM users WHERE id = $1", + id, + ).Scan(&u.ID, &u.Username, &u.PasswordHash, &u.DisplayName, &u.Role, &u.TOTPEnabled, &totpSecret, &u.CreatedAt, &lastLogin) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, err + } + if lastLogin.Valid { + u.LastLogin = &lastLogin.Time + } + if totpSecret.Valid { + u.TOTPSecret = totpSecret.String + } + return &u, nil +} + +func (d *Database) SetTOTPSecret(userID int, secret string) error { + _, err := d.db.Exec("UPDATE users SET totp_secret = $1, totp_enabled = false WHERE id = $2", secret, userID) + return err +} + +func (d *Database) EnableTOTP(userID int) error { + _, err := d.db.Exec("UPDATE users SET totp_enabled = true WHERE id = $1", userID) + return err +} + +func (d *Database) DisableTOTP(userID int) error { + _, err := d.db.Exec("UPDATE users SET totp_enabled = false, totp_secret = NULL WHERE id = $1", userID) + return err +} + func (d *Database) GetUsers() ([]models.User, error) { rows, err := d.db.Query("SELECT id, username, display_name, role, created_at, last_login FROM users ORDER BY username") if err != nil { diff --git a/backend/go.mod b/backend/go.mod index 5c62797..be4be8b 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -9,11 +9,13 @@ require ( ) require ( + github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect github.com/golang-jwt/jwt/v5 v5.3.1 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/kr/text v0.2.0 // indirect + github.com/pquerna/otp v1.5.0 // indirect github.com/rogpeppe/go-internal v1.14.1 // indirect golang.org/x/crypto v0.48.0 // indirect golang.org/x/sync v0.19.0 // indirect diff --git a/backend/go.sum b/backend/go.sum index 1ad8e69..20cdf49 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -1,3 +1,5 @@ +github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI= +github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= @@ -20,6 +22,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs= +github.com/pquerna/otp v1.5.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= diff --git a/backend/main.go b/backend/main.go index aabcf1e..cdcd841 100644 --- a/backend/main.go +++ b/backend/main.go @@ -84,9 +84,15 @@ func main() { // GET /api/v1/auth/me braucht JWT protectedMux.HandleFunc("GET /api/v1/auth/me", authHandler.Me) + // Geschuetzte 2FA-Routen + protectedMux.HandleFunc("POST /api/v1/auth/2fa/setup", authHandler.TOTPSetup) + protectedMux.HandleFunc("POST /api/v1/auth/2fa/confirm", authHandler.TOTPConfirm) + protectedMux.HandleFunc("POST /api/v1/auth/2fa/disable", authHandler.TOTPDisable) + // Combined router: auth routes ungeschuetzt, rest mit DB-basierter Auth mux := http.NewServeMux() mux.Handle("POST /api/v1/auth/login", authMux) + mux.Handle("POST /api/v1/auth/2fa/validate", authMux) // 2FA-Schritt 2 ebenfalls ohne JWT mux.Handle("/", api.CombinedAuthWithCache(apiKeyCache, authHandler, protectedMux)) // Middleware-Chain: CORS -> Logging -> Handler diff --git a/backend/models/task.go b/backend/models/task.go index 3d2dd9f..1179c6c 100644 --- a/backend/models/task.go +++ b/backend/models/task.go @@ -21,6 +21,8 @@ type Task struct { HealthCheck bool `json:"health_check"` HealthCheckTimeout int `json:"health_check_timeout"` SecurityOnly bool `json:"security_only,omitempty"` + Script string `json:"script,omitempty"` + ScriptTimeout int `json:"script_timeout,omitempty"` WebhookURL string `json:"webhook_url,omitempty"` WebhookSent bool `json:"webhook_sent"` WebhookResponse string `json:"webhook_response,omitempty"` diff --git a/backend/models/user.go b/backend/models/user.go index 7e4492c..fa5e87f 100644 --- a/backend/models/user.go +++ b/backend/models/user.go @@ -8,6 +8,8 @@ type User struct { PasswordHash string `json:"-"` DisplayName string `json:"display_name"` Role string `json:"role"` + TOTPEnabled bool `json:"totp_enabled"` + TOTPSecret string `json:"-"` CreatedAt time.Time `json:"created_at"` LastLogin *time.Time `json:"last_login,omitempty"` } @@ -18,7 +20,28 @@ type LoginRequest struct { } type LoginResponse struct { - Token string `json:"token"` - ExpiresAt string `json:"expires_at"` - User User `json:"user"` + Token string `json:"token,omitempty"` + ExpiresAt string `json:"expires_at,omitempty"` + User *User `json:"user,omitempty"` + TOTPRequired bool `json:"totp_required,omitempty"` + TOTPToken string `json:"totp_token,omitempty"` +} + +type TOTPValidateRequest struct { + TOTPToken string `json:"totp_token"` + Code string `json:"code"` +} + +type TOTPSetupResponse struct { + Secret string `json:"secret"` + URI string `json:"uri"` +} + +type TOTPConfirmRequest struct { + Code string `json:"code"` +} + +type TOTPDisableRequest struct { + Password string `json:"password"` + Code string `json:"code"` } diff --git a/frontend/src/api/client.js b/frontend/src/api/client.js index 6290418..466359f 100644 --- a/frontend/src/api/client.js +++ b/frontend/src/api/client.js @@ -68,10 +68,28 @@ class ApiClient { // Auth async login(username, password) { const data = await this.post('/api/v1/auth/login', { username, password }) - this.setToken(data.token) + if (data.token) this.setToken(data.token) return data } + async validateTOTP(totpToken, code) { + const data = await this.post('/api/v1/auth/2fa/validate', { totp_token: totpToken, code }) + if (data.token) this.setToken(data.token) + return data + } + + async setupTOTP() { + return this.post('/api/v1/auth/2fa/setup') + } + + async confirmTOTP(code) { + return this.post('/api/v1/auth/2fa/confirm', { code }) + } + + async disableTOTP(password, code) { + return this.post('/api/v1/auth/2fa/disable', { password, code }) + } + logout() { this.setToken(null) } diff --git a/frontend/src/components/AgentPanel.jsx b/frontend/src/components/AgentPanel.jsx index 19e2d3d..8a17b75 100644 --- a/frontend/src/components/AgentPanel.jsx +++ b/frontend/src/components/AgentPanel.jsx @@ -4,10 +4,11 @@ import StatusBadge from './StatusBadge' import { copyToClipboard } from '../utils/clipboard' import { useSettingsStore } from '../stores/settings' import TerminalModal from './TerminalModal' +import ScriptModal from './ScriptModal' import { X, Cpu, MemoryStick, HardDrive, Clock, Network, Shield, Route, Globe, Key, Download, Terminal, Wifi, Search, Plus, Trash2, Copy, Check, ExternalLink, Unplug, Plug, MonitorSmartphone, Ban, - FileKey, UserCheck, Database, CalendarClock, Cable, Settings, Server, GitBranch, Play, Power, ChevronDown, ChevronRight, Pencil, + FileKey, UserCheck, Database, CalendarClock, Cable, Settings, Server, GitBranch, Play, Power, ChevronDown, ChevronRight, Pencil, FileCode, } from 'lucide-react' // Two-level navigation structure (DATAZONE style) @@ -909,6 +910,7 @@ function TunnelTab({ agentId, agent }) { const [error, setError] = useState('') const [sshCopied, setSshCopied] = useState(null) const [terminalOpen, setTerminalOpen] = useState(false) + const [scriptOpen, setScriptOpen] = useState(false) const backendHost = useSettingsStore.getState().getBackendHost() @@ -981,6 +983,9 @@ function TunnelTab({ agentId, agent }) { {terminalOpen && ( setTerminalOpen(false)} /> )} + {scriptOpen && ( + setScriptOpen(false)} /> + )} {/* Quick Buttons */}
@@ -1008,6 +1013,13 @@ function TunnelTab({ agentId, agent }) { Web Terminal +
)} - {/* Update-Optionen */} -
- - - - {form.health_check && ( -
- - setForm({...form, health_check_timeout: e.target.value})} className={inputCls + ' max-w-[160px]'} /> -
- )} + {/* Aktion wählen */} +
+ +
+ {/* Script-Eingabe (nur bei action=script) */} + {form.action === 'script' && ( +
+
+ +