package server import ( "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "errors" "fmt" "log" "strings" "sync" "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) // Step-up re-authentication (see internal/protocol/elevation.go). A web // session is enough to read, but the requests below act as the operator's // shell, so the operator must also confirm the sign-in password once. // // A confirmation is keyed by the web session the token-authenticated proxy // reports (trustedSession): every connection and reconnect of that session // stays elevated until the cap (DefaultElevationTTL) passes. The session ending // ends it too: the proxy closes the session's sockets and refuses its cookie, // and its derived id changes with every new sign-in and every password change // or revoke-all, so no later request can name the old elevation. A connection // without a trusted session id (no server token configured, a direct client) // is elevated by itself only, until it closes. // // The gate is on whenever the web sign-in password file exists; a server run // without the web proxy (tests, a bare loopback server) has nothing to verify // against and keeps its previous behaviour. A file that exists but cannot be // read safely keeps the gate on and every elevate fails (fail closed). // DefaultElevationTTL caps how long one confirmation lasts. const DefaultElevationTTL = 24 * time.Hour // Elevation attempt limits: a key waits elevationBackoffBase doubled for each // consecutive wrong password (at most elevationBackoffMax), and the whole // server refuses attempts after elevationGlobalFailures wrong passwords within // elevationGlobalWindow. At most elevationTokenLimit elevations live at once. const ( elevationBackoffBase = time.Second elevationBackoffMax = time.Minute elevationGlobalFailures = 10 elevationGlobalWindow = 5 * time.Minute elevationTokenLimit = 256 ) // Terminals are deliberately absent: terminal_open starts `su -l`, so the OS // account password is the barrier there. var elevationGated = map[string]bool{ protocol.ChatShellRun: true, protocol.ChatShellInput: true, protocol.RenamePath: true, protocol.MovePath: true, protocol.DeletePath: true, } const ( sessionKeyPrefix = "session:" connectionKeyPrefix = "conn:" ) // sessionElevationKey keys elevation by a trusted web session id. func sessionElevationKey(session string) string { return sessionKeyPrefix + session } // connectionElevationKey keys elevation by one websocket connection. func connectionElevationKey(client string) string { return connectionKeyPrefix + client } // elevationKeyFor is the key a connection elevates under: its web session // when the proxy reported one, else the connection itself. func elevationKeyFor(session, client string) string { if session != "" { return sessionElevationKey(session) } return connectionElevationKey(client) } type elevationGate struct { authFile string ttl time.Duration now func() time.Time // verify serializes scrypt work: one 32 MiB derivation at a time. verify sync.Mutex mu sync.Mutex until map[string]time.Time // key -> elevation end tokens map[string]elevationToken failures map[string]elevationFailures recent []time.Time // wrong passwords, server-wide, oldest first reported bool } type elevationToken struct { key string until time.Time } type elevationFailures struct { count int until time.Time } func newElevationGate(authFile string, ttl time.Duration) *elevationGate { if ttl <= 0 { ttl = DefaultElevationTTL } return &elevationGate{ authFile: authFile, ttl: ttl, now: time.Now, until: map[string]time.Time{}, tokens: map[string]elevationToken{}, failures: map[string]elevationFailures{}, } } // enabled reports whether gated requests need elevation. func (g *elevationGate) enabled() bool { if g == nil || g.authFile == "" { return false } _, err := readWebAuth(g.authFile) if errors.Is(err, errWebAuthMissing) { return false } if err != nil { g.mu.Lock() if !g.reported { log.Printf("elevation: web sign-in password file unusable, every elevate fails: %v", err) g.reported = true } g.mu.Unlock() } return true } func (g *elevationGate) elevated(key string) bool { g.mu.Lock() defer g.mu.Unlock() until, ok := g.until[key] if ok && !g.now().Before(until) { g.dropLocked(key) return false } return ok } // allows reports whether key may perform a gated request now. func (g *elevationGate) allows(key string) bool { return g.elevated(key) || !g.enabled() } // refuse answers a gated request whose key is not elevated with a typed error // and reports true; any other request passes (false). func (g *elevationGate) refuse(request protocol.Message, key string, write func(protocol.Message) error) bool { if !elevationGated[request.Type] || g.allows(key) { return false } _ = write(protocol.Message{ Type: protocol.Error, ID: request.ID, Code: protocol.ErrorElevationRequired, Error: "Confirm your password to run commands or change files on this machine.", }) return true } // handle answers an elevate request and reports true; other requests pass. func (g *elevationGate) handle(request protocol.Message, key string, write func(protocol.Message) error) bool { if request.Type != protocol.Elevate { return false } reply, err := g.elevate(key, request.Password) if err != nil { code := protocol.ErrorElevationFailed if errors.Is(err, errWebAuthMissing) { code = protocol.ErrorElevationUnavailable } _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Code: code, Error: err.Error()}) return true } _ = write(protocol.Message{Type: protocol.Elevated, ID: request.ID, Elevation: reply}) return true } func (g *elevationGate) elevate(key, password string) (*protocol.Elevation, error) { if g == nil || g.authFile == "" { return nil, fmt.Errorf("this server has no web sign-in password to confirm: %w", errWebAuthMissing) } if wait := g.blocked(key); wait > 0 { return nil, fmt.Errorf("too many wrong passwords; try again in %d seconds", int((wait+time.Second-1)/time.Second)) } verifier, err := readWebAuth(g.authFile) if errors.Is(err, errWebAuthMissing) { return nil, fmt.Errorf("this server has no web sign-in password to confirm: %w", err) } if err != nil { log.Printf("elevation: web sign-in password file unusable: %v", err) return nil, errors.New("the server's sign-in password file is unusable; see the server log") } g.verify.Lock() ok, err := verifier.verify(password) g.verify.Unlock() if err != nil { log.Printf("elevation: verify: %v", err) return nil, errors.New("the password could not be checked; see the server log") } if !ok { g.noteFailure(key) return nil, errors.New("wrong password") } return g.grant(key) } func (g *elevationGate) blocked(key string) time.Duration { g.mu.Lock() defer g.mu.Unlock() now := g.now() g.pruneLocked(now) if len(g.recent) >= elevationGlobalFailures { return g.recent[0].Add(elevationGlobalWindow).Sub(now) } if entry, ok := g.failures[key]; ok && now.Before(entry.until) { return entry.until.Sub(now) } return 0 } func (g *elevationGate) pruneLocked(now time.Time) { keep := 0 for keep < len(g.recent) && !now.Before(g.recent[keep].Add(elevationGlobalWindow)) { keep++ } g.recent = g.recent[keep:] } func (g *elevationGate) noteFailure(key string) { g.mu.Lock() defer g.mu.Unlock() now := g.now() g.recent = append(g.recent, now) // A session's failures outlive its connections; drop entries whose wait // is long over so the map stays bounded by recent activity. for other, entry := range g.failures { if !now.Before(entry.until.Add(elevationGlobalWindow)) { delete(g.failures, other) } } entry := g.failures[key] entry.count++ delay := elevationBackoffBase << min(entry.count-1, 6) entry.until = now.Add(min(delay, elevationBackoffMax)) g.failures[key] = entry } func (g *elevationGate) grant(key string) (*protocol.Elevation, error) { raw := make([]byte, 32) if _, err := rand.Read(raw); err != nil { return nil, err } token := base64.RawURLEncoding.EncodeToString(raw) g.mu.Lock() defer g.mu.Unlock() now := g.now() until := now.Add(g.ttl) g.dropLocked(key) delete(g.failures, key) for other, end := range g.until { if !now.Before(end) { g.dropLocked(other) } } if len(g.until) >= elevationTokenLimit { return nil, errors.New("too many elevated sessions on this server") } g.until[key] = until g.tokens[tokenKey(token)] = elevationToken{key: key, until: until} return &protocol.Elevation{ ExpiresAt: until.UTC().Format(time.RFC3339), Seconds: int(g.ttl / time.Second), Token: token, }, nil } func tokenKey(token string) string { sum := sha256.Sum256([]byte(token)) return hex.EncodeToString(sum[:]) } // dropLocked ends key's elevation and its upload token. func (g *elevationGate) dropLocked(key string) { delete(g.until, key) for hash, entry := range g.tokens { if entry.key == key { delete(g.tokens, hash) } } } // closed is called when a connection that elevated under key ends: a // connection's own elevation and attempt history end with it, a web session's // outlive it for that session's next connection. func (g *elevationGate) closed(key string) { if g == nil || !strings.HasPrefix(key, connectionKeyPrefix) { return } g.mu.Lock() defer g.mu.Unlock() g.dropLocked(key) delete(g.failures, key) } // tokenValid reports whether token belongs to a still live elevation. func (g *elevationGate) tokenValid(token string) bool { if token == "" { return false } g.mu.Lock() defer g.mu.Unlock() entry, ok := g.tokens[tokenKey(token)] if !ok { return false } if !g.now().Before(entry.until) { g.dropLocked(entry.key) return false } return true }