package server import ( "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "errors" "fmt" "log" "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 each connection must also confirm the sign-in password recently. // 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 is how long one confirmation lasts on a connection. const DefaultElevationTTL = 15 * time.Minute // Elevation attempt limits: a connection waits elevationBackoffBase doubled // for each consecutive wrong password (at most elevationBackoffMax), and the // whole server refuses attempts after elevationGlobalFailures wrong passwords // within elevationGlobalWindow. const ( elevationBackoffBase = time.Second elevationBackoffMax = time.Minute elevationGlobalFailures = 10 elevationGlobalWindow = 5 * time.Minute elevationTokenLimit = 256 ) var elevationGated = map[string]bool{ protocol.ChatShellRun: true, protocol.ChatShellInput: true, protocol.RenamePath: true, protocol.MovePath: true, protocol.DeletePath: true, protocol.TerminalOpen: true, protocol.TerminalInput: true, } 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 // client -> elevation end tokens map[string]elevationToken failures map[string]elevationFailures recent []time.Time // wrong passwords, server-wide, oldest first reported bool } type elevationToken struct { client 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(client string) bool { g.mu.Lock() defer g.mu.Unlock() until, ok := g.until[client] if ok && !g.now().Before(until) { g.dropLocked(client) return false } return ok } // allows reports whether client may perform a gated request now. func (g *elevationGate) allows(client string) bool { return g.elevated(client) || !g.enabled() } // refuse answers a gated request on a connection that is not elevated with a // typed error and reports true; any other request passes (false). func (g *elevationGate) refuse(request protocol.Message, client string, write func(protocol.Message) error) bool { if !elevationGated[request.Type] || g.allows(client) { return false } _ = write(protocol.Message{ Type: protocol.Error, ID: request.ID, Code: protocol.ErrorElevationRequired, Error: "Confirm your password to run commands, change files or use a terminal on this machine.", }) return true } // handle answers an elevate request and reports true; other requests pass. func (g *elevationGate) handle(request protocol.Message, client string, write func(protocol.Message) error) bool { if request.Type != protocol.Elevate { return false } reply, err := g.elevate(client, 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(client, 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(client); 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(client) return nil, errors.New("wrong password") } return g.grant(client) } func (g *elevationGate) blocked(client 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[client]; 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(client string) { g.mu.Lock() defer g.mu.Unlock() now := g.now() g.recent = append(g.recent, now) entry := g.failures[client] entry.count++ delay := elevationBackoffBase << min(entry.count-1, 6) entry.until = now.Add(min(delay, elevationBackoffMax)) g.failures[client] = entry } func (g *elevationGate) grant(client 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(client) delete(g.failures, client) for key, entry := range g.tokens { if !now.Before(entry.until) { delete(g.tokens, key) } } if len(g.tokens) >= elevationTokenLimit { return nil, errors.New("too many elevated connections on this server") } g.until[client] = until g.tokens[tokenKey(token)] = elevationToken{client: client, 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 client's elevation and its upload token. func (g *elevationGate) dropLocked(client string) { delete(g.until, client) for key, entry := range g.tokens { if entry.client == client { delete(g.tokens, key) } } } // forget ends a closed connection's elevation and attempt history. func (g *elevationGate) forget(client string) { if g == nil { return } g.mu.Lock() defer g.mu.Unlock() g.dropLocked(client) delete(g.failures, client) } // tokenValid reports whether token belongs to a still elevated connection. 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.client) return false } return true }