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
This commit is contained in:
+206
-6
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user