diff --git a/README.md b/README.md index f2274aa..5f29727 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ sftp serve \ --service-token-file /etc/sftp/service-token ``` -Every flag has a `GAMEPLANE_SFTP_*` environment variable; the flag wins. Required: `--host-key` (a key file or a directory of keys, kept stable so clients can verify it), `--api-url`, `--service-token-file`. Optional: `--listen` (`:2222`), `--ca-file`, `--idle-timeout` (`15m`), `--max-sessions-per-user` (`4`), `--max-preauth-connections` (`64`, connections still authenticating; more are closed at once), `--max-transfers-per-user` (`8`), `--default-namespace` (`gameplane-games`, must match the API), `--metrics-addr` (`:9102`, empty disables). `sftp version` prints the build version. The full contract is in [`specs.md`](specs.md). +Every flag has a `GAMEPLANE_SFTP_*` environment variable; the flag wins. Required: `--host-key` (a key file or a directory of keys, kept stable so clients can verify it), `--api-url`, `--service-token-file`. Optional: `--listen` (`:2222`), `--ca-file`, `--idle-timeout` (`15m`), `--max-sessions-per-user` (`4`), `--max-preauth-connections` (`64`, connections still authenticating; more are closed at once), `--max-preauth-per-ip` (`8`, the same per source IP), `--max-transfers-per-user` (`8`), `--default-namespace` (`gameplane-games`, must match the API), `--metrics-addr` (`127.0.0.1:9102`, unauthenticated so loopback-only by default; empty disables), `--allow-insecure-api` (accept an `http` API URL; only for a hop inside one cluster). The API URL must be `https` otherwise, and redirects are never followed. `sftp version` prints the build version. The full contract is in [`specs.md`](specs.md). Clients log in as `` to see every server they may access, or as `+` (or `+/`) to open one server directly. There is no shell, command execution or port forwarding. Dotfiles are hidden. diff --git a/internal/apiclient/client.go b/internal/apiclient/client.go index 7902d30..900e66f 100644 --- a/internal/apiclient/client.go +++ b/internal/apiclient/client.go @@ -86,8 +86,14 @@ func (e *Error) Unwrap() error { return e.Err } // Config configures a Client. type Config struct { // BaseURL is the API origin, for example https://gameplane-api.gameplane.svc:8080. - // A trailing slash is trimmed. Only http and https are accepted. + // A trailing slash is trimmed. It must use https unless AllowInsecureHTTP + // is set. BaseURL string + // AllowInsecureHTTP lets New accept an http:// BaseURL. The service token, + // passwords and session tokens then cross the network in clear text, so + // set it only when the hop never leaves a trusted network, such as the + // pod network between the SFTP pod and the API Service of one cluster. + AllowInsecureHTTP bool // ServiceToken is the contents of the service token file, trimmed. It is // used only for Login and CheckSessions. ServiceToken string @@ -109,13 +115,19 @@ type Client struct { streamHC *http.Client // no overall timeout; context only } -// New builds a Client with a TLS 1.2+ transport. CAFile, when set, must hold -// at least one PEM certificate. +// New builds a Client with a TLS 1.2+ transport that verifies the API's +// certificate. BaseURL must be https unless AllowInsecureHTTP is set. CAFile, +// when set, must hold at least one PEM certificate. Redirects are never +// followed: a redirected request fails, so credentials are never re-sent to +// another URL. func New(cfg Config) (*Client, error) { base, err := validateBaseURL(cfg.BaseURL) if err != nil { return nil, err } + if u, _ := url.Parse(base); u.Scheme == "http" && !cfg.AllowInsecureHTTP { + return nil, errors.New("apiclient: base URL must use https (http needs AllowInsecureHTTP)") + } pool, err := loadCAPool(cfg.CAFile) if err != nil { return nil, err @@ -133,8 +145,8 @@ func New(cfg Config) (*Client, error) { if timeout <= 0 { timeout = defaultTimeout } - hc := &http.Client{Transport: tr, Timeout: timeout} - stream := &http.Client{Transport: tr} + hc := &http.Client{Transport: tr, Timeout: timeout, CheckRedirect: refuseRedirect} + stream := &http.Client{Transport: tr, CheckRedirect: refuseRedirect} return newClient(base, cfg, hc, stream), nil } @@ -180,6 +192,13 @@ func newClient(base string, cfg Config, hc, stream *http.Client) *Client { } } +// refuseRedirect stops the client at the first redirect and returns the 3xx +// response, which maps to ErrFailure. Following it would re-send the login +// body (password or key) and the bearer token to wherever the API pointed. +func refuseRedirect(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse +} + func validateBaseURL(raw string) (string, error) { s := strings.TrimRight(strings.TrimSpace(raw), "/") u, err := url.Parse(s) diff --git a/internal/apiclient/hardening_test.go b/internal/apiclient/hardening_test.go new file mode 100644 index 0000000..7cbadb6 --- /dev/null +++ b/internal/apiclient/hardening_test.go @@ -0,0 +1,70 @@ +package apiclient + +import ( + "context" + "encoding/pem" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "sync/atomic" + "testing" +) + +func TestNewRequiresHTTPSByDefault(t *testing.T) { + for _, raw := range []string{"http://gameplane-api.gameplane.svc", "HTTP://gameplane-api.gameplane.svc", " Http://api.example/ "} { + if _, err := New(Config{BaseURL: raw}); err == nil { + t.Errorf("New(%q) accepted an http base URL without AllowInsecureHTTP", raw) + } + } + c, err := New(Config{BaseURL: "http://gameplane-api.gameplane.svc", AllowInsecureHTTP: true}) + if err != nil { + t.Fatalf("New with AllowInsecureHTTP: %v", err) + } + if c.baseURL != "http://gameplane-api.gameplane.svc" { + t.Errorf("baseURL = %q", c.baseURL) + } +} + +// A redirect from the API is never followed: the login body and the bearer +// token must not be re-sent to another URL. +func TestClientRefusesRedirects(t *testing.T) { + var elsewhere atomic.Int32 + target := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + elsewhere.Add(1) + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(target.Close) + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target.URL+r.URL.Path, http.StatusTemporaryRedirect) + })) + t.Cleanup(srv.Close) + + dir := t.TempDir() + caPEM := filepath.Join(dir, "ca.pem") + var bundle []byte + for _, s := range []*httptest.Server{srv, target} { + bundle = append(bundle, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: s.Certificate().Raw})...) + } + if err := os.WriteFile(caPEM, bundle, 0o600); err != nil { + t.Fatalf("write: %v", err) + } + c, err := New(Config{BaseURL: srv.URL, CAFile: caPEM, ServiceToken: testServiceToken}) + if err != nil { + t.Fatalf("New: %v", err) + } + ctx := context.Background() + if _, err := c.Login(ctx, LoginRequest{Username: "alice", Password: "pw"}); !errors.Is(err, ErrFailure) { + t.Errorf("Login through a redirect = %v, want ErrFailure", err) + } + if _, err := c.Servers(ctx, "gpsftp_x"); !errors.Is(err, ErrFailure) { + t.Errorf("Servers through a redirect = %v, want ErrFailure", err) + } + if _, err := c.Files("gpsftp_x", "", "survival").Download(ctx, "/a", 0); !errors.Is(err, ErrFailure) { + t.Errorf("Download through a redirect = %v, want ErrFailure", err) + } + if n := elsewhere.Load(); n != 0 { + t.Fatalf("redirect target received %d requests, want 0", n) + } +} diff --git a/internal/sshserver/hardening_test.go b/internal/sshserver/hardening_test.go new file mode 100644 index 0000000..08e04c8 --- /dev/null +++ b/internal/sshserver/hardening_test.go @@ -0,0 +1,243 @@ +package sshserver + +import ( + "context" + "errors" + "net" + "os" + "slices" + "testing" + "time" + + "github.com/pkg/sftp" + "github.com/prometheus/client_golang/prometheus/testutil" + "golang.org/x/crypto/ssh" +) + +// A connection may hold at most maxSessionChannels session channels; one +// more is rejected before it is accepted. +func TestSessionChannelCapRejectsExtraChannels(t *testing.T) { + h := newHarness(t, nil, &fakeAPI{}) + c := h.mustDial("alice", ssh.Password("pw")) + for i := range maxSessionChannels { + ch, reqs, err := c.OpenChannel("session", nil) + if err != nil { + t.Fatalf("channel %d: %v", i+1, err) + } + go ssh.DiscardRequests(reqs) + t.Cleanup(func() { _ = ch.Close() }) + } + _, _, err := c.OpenChannel("session", nil) + var open *ssh.OpenChannelError + if !errors.As(err, &open) || open.Reason != ssh.ResourceShortage { + t.Fatalf("channel over the cap: err %v, want a ResourceShortage rejection", err) + } +} + +// A slot is freed when a channel ends, so a client can open a new one later. +func TestSessionChannelCapFreesSlots(t *testing.T) { + h := newHarness(t, func(c *Config) { c.LoginTimeout = 100 * time.Millisecond }, &fakeAPI{}) + c := h.mustDial("alice", ssh.Password("pw")) + for range maxSessionChannels { + _, reqs, err := c.OpenChannel("session", nil) + if err != nil { + t.Fatalf("open: %v", err) + } + go ssh.DiscardRequests(reqs) + } + // Both channels time out without starting SFTP and are closed, which + // frees their slots. + eventually(t, "a channel slot to be freed", func() bool { + ch, reqs, err := c.OpenChannel("session", nil) + if err != nil { + return false + } + go ssh.DiscardRequests(reqs) + _ = ch.Close() + return true + }) +} + +// A session channel that never asks for the SFTP subsystem is closed after +// LoginTimeout. +func TestSessionChannelWithoutSFTPIsClosed(t *testing.T) { + h := newHarness(t, func(c *Config) { c.LoginTimeout = 100 * time.Millisecond }, &fakeAPI{}) + c := h.mustDial("alice", ssh.Password("pw")) + ch, reqs, err := c.OpenChannel("session", nil) + if err != nil { + t.Fatalf("open: %v", err) + } + go ssh.DiscardRequests(reqs) + done := make(chan error, 1) + go func() { + _, err := ch.Read(make([]byte, 1)) + done <- err + }() + select { + case err := <-done: + if err == nil { + t.Fatal("read on an idle channel returned data, want the channel closed") + } + case <-time.After(5 * time.Second): + t.Fatal("idle session channel was not closed") + } +} + +// The SFTP subsystem started in time keeps working past LoginTimeout. +func TestSFTPChannelOutlivesInitDeadline(t *testing.T) { + h := newHarness(t, func(c *Config) { c.LoginTimeout = 100 * time.Millisecond }, &fakeAPI{}) + c := h.mustDial("alice", ssh.Password("pw")) + sc, err := sftp.NewClient(c) + if err != nil { + t.Fatalf("sftp: %v", err) + } + defer func() { _ = sc.Close() }() + time.Sleep(300 * time.Millisecond) + if _, err := sc.ReadDir("/"); err != nil { + t.Fatalf("sftp after the init deadline: %v", err) + } +} + +// When every session check fails, a connection is closed once the API has +// not confirmed its session for RevalidateWithin (fail closed). +func TestUnconfirmedSessionIsClosed(t *testing.T) { + api := &fakeAPI{checkErr: errors.New("api down")} + h := newHarness(t, func(c *Config) { + c.CheckInterval = 20 * time.Millisecond + c.RevalidateWithin = 150 * time.Millisecond + }, api) + c := h.mustDial("alice", ssh.Password("pw")) + waitClosed(t, c) + if got := testutil.ToFloat64(h.metrics.stale); got != 1 { + t.Fatalf("unconfirmed_closed_total = %v, want 1", got) + } + if got := testutil.ToFloat64(h.metrics.revokes); got != 0 { + t.Fatalf("revoked_total = %v, want 0", got) + } +} + +// Successful checks keep confirming the session, so the connection outlives +// RevalidateWithin. +func TestConfirmedSessionOutlivesRevalidateWindow(t *testing.T) { + h := newHarness(t, func(c *Config) { + c.CheckInterval = 20 * time.Millisecond + c.RevalidateWithin = 150 * time.Millisecond + }, &fakeAPI{}) + c := h.mustDial("alice", ssh.Password("pw")) + time.Sleep(500 * time.Millisecond) + if err := readRoot(c); err != nil { + t.Fatalf("connection dropped although every check succeeded: %v", err) + } + if got := testutil.ToFloat64(h.metrics.stale); got != 0 { + t.Fatalf("unconfirmed_closed_total = %v, want 0", got) + } +} + +// A login whose session has already expired is refused. +func TestExpiredSessionAtLoginIsRefused(t *testing.T) { + api := &fakeAPI{expiresIn: -time.Hour} + h := newHarness(t, nil, api) + // Authentication itself succeeds at the API; the server refuses the + // expired session right after the handshake, so no SFTP is ever served. + if c, err := h.dialErr("alice", ssh.Password("pw")); err == nil { + defer func() { _ = c.Close() }() + if err := readRoot(c); err == nil { + t.Fatal("expired session served SFTP") + } + } + // Either way the server ends the unused API session. + eventually(t, "the expired session to be ended at the API", func() bool { + return slices.Contains(api.endedTokens(), "gpsftp_test_1") + }) + if got := testutil.ToFloat64(h.metrics.sessions); got != 0 { + t.Fatalf("session gauge = %v, want 0", got) + } +} + +// Revoke closes the connection that holds the token at once. +func TestRevokeClosesConnection(t *testing.T) { + api := &fakeAPI{} + srv, err := New(Config{HostKeys: []ssh.Signer{newEd25519Signer(t)}, CheckInterval: time.Hour}, api, testHandlers) + if err != nil { + t.Fatalf("New: %v", err) + } + l, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- srv.Serve(ctx, l) }() + t.Cleanup(func() { + cancel() + <-done + }) + h := &harness{t: t, addr: l.Addr().String(), api: api} + c := h.mustDial("alice", ssh.Password("pw")) + if err := readRoot(c); err != nil { + t.Fatalf("sftp: %v", err) + } + srv.Revoke("gpsftp_unknown") // unknown tokens are ignored + srv.Revoke("gpsftp_test_1") + waitClosed(t, c) +} + +// One source IP may hold at most MaxPreAuthPerIP connections before +// authentication; the next one is closed at once. +func TestPreAuthPerIPCap(t *testing.T) { + h := newHarness(t, func(c *Config) { c.MaxPreAuthPerIP = 1 }, &fakeAPI{}) + first := rawBanner(t, h.addr) + second, err := (&net.Dialer{}).DialContext(context.Background(), "tcp", h.addr) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer func() { _ = second.Close() }() + if err := second.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil { + t.Fatalf("deadline: %v", err) + } + if n, err := second.Read(make([]byte, 1)); err == nil || errors.Is(err, os.ErrDeadlineExceeded) { + t.Fatalf("over-cap connection read %d bytes, err %v; want it closed", n, err) + } + _ = first.Close() + eventually(t, "the per-IP slot to be freed", func() bool { + c, err := h.dialErr("alice", ssh.Password("pw")) + if err != nil { + return false + } + _ = c.Close() + return true + }) +} + +func TestNegativeRevalidateAndPerIPCapAreRefused(t *testing.T) { + key := newEd25519Signer(t) + for name, cfg := range map[string]Config{ + "revalidate": {HostKeys: []ssh.Signer{key}, RevalidateWithin: -time.Second}, + "per ip": {HostKeys: []ssh.Signer{key}, MaxPreAuthPerIP: -1}, + } { + if _, err := New(cfg, &fakeAPI{}, testHandlers); err == nil { + t.Errorf("%s: New accepted a negative value", name) + } + } +} + +func TestSourceIP(t *testing.T) { + for in, want := range map[string]string{ + "203.0.113.7:51234": "203.0.113.7", + "[2001:db8::1]:2222": "2001:db8::1", + } { + addr, err := net.ResolveTCPAddr("tcp", in) + if err != nil { + t.Fatalf("resolve %s: %v", in, err) + } + if got := sourceIP(addr); got != want { + t.Errorf("sourceIP(%s) = %q, want %q", in, got, want) + } + } + if got := sourceIP(nil); got != "" { + t.Errorf("sourceIP(nil) = %q", got) + } + if got := sourceIP(&net.UnixAddr{Name: "sock", Net: "unix"}); got != "sock" { + t.Errorf("sourceIP(unix) = %q", got) + } +} diff --git a/internal/sshserver/metrics.go b/internal/sshserver/metrics.go index 5742430..bed8342 100644 --- a/internal/sshserver/metrics.go +++ b/internal/sshserver/metrics.go @@ -20,6 +20,7 @@ type Metrics struct { sessions prometheus.Gauge logins *prometheus.CounterVec revokes prometheus.Counter + stale prometheus.Counter preAuth prometheus.Counter bytes *prometheus.CounterVec } @@ -40,6 +41,10 @@ func NewMetrics(reg prometheus.Registerer) (*Metrics, error) { Name: "gameplane_sftp_revoked_total", Help: "Connections closed because their session was revoked.", }), + stale: prometheus.NewCounter(prometheus.CounterOpts{ + Name: "gameplane_sftp_unconfirmed_closed_total", + Help: "Connections closed because the API had not confirmed their session in time (failed checks or expiry).", + }), preAuth: prometheus.NewCounter(prometheus.CounterOpts{ Name: "gameplane_sftp_preauth_rejected_total", Help: "Connections closed at once because too many were still authenticating.", @@ -49,7 +54,7 @@ func NewMetrics(reg prometheus.Registerer) (*Metrics, error) { Help: "File bytes transferred, by direction (read or write).", }, []string{"direction"}), } - for _, c := range []prometheus.Collector{m.sessions, m.logins, m.revokes, m.preAuth, m.bytes} { + for _, c := range []prometheus.Collector{m.sessions, m.logins, m.revokes, m.stale, m.preAuth, m.bytes} { if err := reg.Register(c); err != nil { return nil, fmt.Errorf("register sftp metrics: %w", err) } @@ -108,3 +113,10 @@ func (m *Metrics) preAuthRejected() { } m.preAuth.Inc() } + +func (m *Metrics) unconfirmed() { + if m == nil { + return + } + m.stale.Inc() +} diff --git a/internal/sshserver/server.go b/internal/sshserver/server.go index 0010ace..4259078 100644 --- a/internal/sshserver/server.go +++ b/internal/sshserver/server.go @@ -26,12 +26,19 @@ const ( defaultIdleTimeout = 15 * time.Minute defaultMaxSessions = 4 defaultMaxPreAuth = 64 + defaultMaxPreAuthIP = 8 defaultCheckInterval = 30 * time.Second defaultLoginTimeout = 10 * time.Second + defaultRevalidate = 2 * time.Minute acceptRetryDelay = 100 * time.Millisecond - serverVersion = "SSH-2.0-Gameplane-SFTP" - maxAuthTries = 3 - sftpSubsystem = "sftp" + // maxSessionChannels caps the session channels one connection may hold + // open at once: the SFTP channel plus one extra that is refused and + // closed. Further channel opens are rejected before they are accepted, + // so no goroutine or channel buffer is spent on them. + maxSessionChannels = 2 + serverVersion = "SSH-2.0-Gameplane-SFTP" + maxAuthTries = 3 + sftpSubsystem = "sftp" extSessionToken = "sessionToken" extUser = "user" @@ -77,12 +84,22 @@ type Config struct { // finished authentication. A connection over the cap is closed at once. // Default 64. MaxPreAuthConnections int + // MaxPreAuthPerIP caps the connections one source IP may have before + // authentication, so a single address cannot take every pre-auth slot. + // A connection over the cap is closed at once. Default 8. + MaxPreAuthPerIP int // CheckInterval is how often the server asks the API which of its // session tokens were revoked. Default 30s. CheckInterval time.Duration // LoginTimeout bounds each API call and the SSH handshake before - // authentication completes. Default 10s. + // authentication completes, and how long an accepted session channel + // may take to start the SFTP subsystem. Default 10s. LoginTimeout time.Duration + // RevalidateWithin closes a connection whose session the API has not + // confirmed as valid for this long, for example because every session + // check failed. A connection is also closed once its session's known + // expiry passes without a confirmation. Default 2m. + RevalidateWithin time.Duration // Logger receives operational logs. Never passwords, tokens or keys. Logger *slog.Logger // Metrics receives counters and gauges. Nil disables them. @@ -98,15 +115,16 @@ type Server struct { log *slog.Logger metrics *Metrics - mu sync.Mutex - listener net.Listener - base context.Context // Serve's context; Background before Serve - open map[net.Conn]struct{} // every accepted connection, until it ends - tokens map[string]*connState // session token -> authenticated connection - perUser map[string]int // lowercased user -> authenticated connections - closing bool // set once Serve's context ends - preAuth int // connections still before authentication - pending map[string]apiclient.Session // remote address -> password login awaiting handshake end + mu sync.Mutex + listener net.Listener + base context.Context // Serve's context; Background before Serve + open map[net.Conn]struct{} // every accepted connection, until it ends + tokens map[string]*connState // session token -> authenticated connection + perUser map[string]int // lowercased user -> authenticated connections + closing bool // set once Serve's context ends + preAuth int // connections still before authentication + preAuthIP map[string]int // source IP -> connections still before authentication + pending map[string]apiclient.Session // remote address -> password login awaiting handshake end } // New validates cfg and returns a Server. It does not listen. @@ -125,16 +143,17 @@ func New(cfg Config, api API, hf HandlerFactory) (*Server, error) { return nil, err } s := &Server{ - cfg: cfg, - api: api, - hf: hf, - log: cfg.Logger, - metrics: cfg.Metrics, - open: make(map[net.Conn]struct{}), - tokens: make(map[string]*connState), - perUser: make(map[string]int), - pending: make(map[string]apiclient.Session), - base: context.Background(), + cfg: cfg, + api: api, + hf: hf, + log: cfg.Logger, + metrics: cfg.Metrics, + open: make(map[net.Conn]struct{}), + tokens: make(map[string]*connState), + perUser: make(map[string]int), + pending: make(map[string]apiclient.Session), + preAuthIP: make(map[string]int), + base: context.Background(), } sc := &ssh.ServerConfig{ PasswordCallback: s.passwordCallback, @@ -154,13 +173,13 @@ func (c Config) withDefaults() (Config, error) { if c.Addr == "" { c.Addr = defaultAddr } - if c.IdleTimeout < 0 || c.CheckInterval < 0 || c.LoginTimeout < 0 { + if c.IdleTimeout < 0 || c.CheckInterval < 0 || c.LoginTimeout < 0 || c.RevalidateWithin < 0 { return c, errors.New("sshserver: negative timeout") } if c.MaxSessionsPerUser < 0 { return c, errors.New("sshserver: negative session cap") } - if c.MaxPreAuthConnections < 0 { + if c.MaxPreAuthConnections < 0 || c.MaxPreAuthPerIP < 0 { return c, errors.New("sshserver: negative pre-auth connection cap") } if c.IdleTimeout == 0 { @@ -172,12 +191,18 @@ func (c Config) withDefaults() (Config, error) { if c.MaxPreAuthConnections == 0 { c.MaxPreAuthConnections = defaultMaxPreAuth } + if c.MaxPreAuthPerIP == 0 { + c.MaxPreAuthPerIP = defaultMaxPreAuthIP + } if c.CheckInterval == 0 { c.CheckInterval = defaultCheckInterval } if c.LoginTimeout == 0 { c.LoginTimeout = defaultLoginTimeout } + if c.RevalidateWithin == 0 { + c.RevalidateWithin = defaultRevalidate + } if c.Logger == nil { c.Logger = slog.New(slog.DiscardHandler) } @@ -239,7 +264,8 @@ func (s *Server) Serve(ctx context.Context, l net.Listener) error { _ = raw.Close() continue } - if !s.acquirePreAuth() { + ip := sourceIP(raw.RemoteAddr()) + if !s.acquirePreAuth(ip) { s.untrack(raw) _ = raw.Close() s.metrics.preAuthRejected() @@ -250,7 +276,7 @@ func (s *Server) Serve(ctx context.Context, l net.Listener) error { go func() { defer wg.Done() defer s.untrack(raw) - s.handle(ctx, raw, sync.OnceFunc(s.releasePreAuth)) + s.handle(ctx, raw, sync.OnceFunc(func() { s.releasePreAuth(ip) })) }() } s.shutdown() @@ -287,22 +313,57 @@ func (s *Server) track(c net.Conn) bool { return true } -// acquirePreAuth takes one pre-authentication slot, or reports that the cap -// is reached. -func (s *Server) acquirePreAuth() bool { +// acquirePreAuth takes one pre-authentication slot for source IP ip, or +// reports that the global or the per-IP cap is reached. +func (s *Server) acquirePreAuth(ip string) bool { s.mu.Lock() defer s.mu.Unlock() - if s.preAuth >= s.cfg.MaxPreAuthConnections { + if s.preAuth >= s.cfg.MaxPreAuthConnections || s.preAuthIP[ip] >= s.cfg.MaxPreAuthPerIP { return false } s.preAuth++ + s.preAuthIP[ip]++ return true } -func (s *Server) releasePreAuth() { +func (s *Server) releasePreAuth(ip string) { s.mu.Lock() defer s.mu.Unlock() s.preAuth-- + if n := s.preAuthIP[ip] - 1; n > 0 { + s.preAuthIP[ip] = n + } else { + delete(s.preAuthIP, ip) + } +} + +// sourceIP returns the IP part of a connection's remote address, or the whole +// address when it has no port. +func sourceIP(a net.Addr) string { + if a == nil { + return "" + } + host, _, err := net.SplitHostPort(a.String()) + if err != nil { + return a.String() + } + return host +} + +// Revoke closes the connection that holds session token tok, as when the +// API reports it revoked. The file system calls it when the API refuses the +// session on a file request, so a revoked session does not wait for the next +// check. An unknown token is ignored. +func (s *Server) Revoke(tok string) { + s.mu.Lock() + st := s.tokens[tok] + s.mu.Unlock() + if st == nil || !st.revoked.CompareAndSwap(false, true) { + return + } + s.log.Info("session refused by the API; connection closed", "user", st.user) + s.metrics.revoked() + _ = st.sconn.Close() } // endSession tells the API to close a session this server created but will @@ -345,6 +406,17 @@ type connState struct { key string // lowercased user, the per-user cap key sftpStarted atomic.Bool revoked atomic.Bool + channels atomic.Int32 // session channels accepted and not yet finished + // ttl is how long the API keeps the session valid without use, taken + // from the expiry at login. validUntil (Unix nanoseconds) is the latest + // time the session can still be valid without a new confirmation. + ttl time.Duration + validUntil atomic.Int64 +} + +// confirm records that the API reported the session valid at t. +func (st *connState) confirm(t time.Time, within time.Duration) { + st.validUntil.Store(t.Add(min(within, st.ttl)).UnixNano()) } // handle runs one TCP connection from handshake to close. releasePreAuth @@ -385,7 +457,9 @@ func (s *Server) handle(ctx context.Context, raw net.Conn, releasePreAuth func() dc.idle.Store(int64(s.cfg.IdleTimeout)) dc.touch() - st := &connState{sconn: sconn, sess: sess, user: sess.User, key: strings.ToLower(sess.User)} + now := time.Now() + st := &connState{sconn: sconn, sess: sess, user: sess.User, key: strings.ToLower(sess.User), ttl: sess.ExpiresAt.Sub(now)} + st.confirm(now, s.cfg.RevalidateWithin) if !s.admit(st) { s.endSession(ctx, sess) s.metrics.login(loginLimit) @@ -406,9 +480,15 @@ func (s *Server) handle(ctx context.Context, raw net.Conn, releasePreAuth func() _ = nc.Reject(ssh.UnknownChannelType, "only session channels") continue } + if st.channels.Add(1) > maxSessionChannels { + st.channels.Add(-1) + _ = nc.Reject(ssh.ResourceShortage, "too many channels") + continue + } channels.Add(1) go func() { defer channels.Done() + defer st.channels.Add(-1) s.serveSession(nc, st) }() } @@ -428,6 +508,9 @@ func (s *Server) establish(ctx context.Context, sconn *ssh.ServerConn, pwSess ap return apiclient.Session{}, errPermissionDenied } sess, err := sessionFromExtensions(perms.Extensions) + if err == nil && !sess.ExpiresAt.After(time.Now()) { + err = errors.New("sshserver: session already expired") + } if err != nil { if hasPW { s.endSession(ctx, pwSess) @@ -556,6 +639,16 @@ func (s *Server) serveSession(nc ssh.NewChannel, st *connState) { if err != nil { return } + // A channel must start the SFTP subsystem within LoginTimeout, or it is + // closed. initState is 0 while waiting, 1 once a subsystem request won the + // race, 2 once the deadline closed the channel. + var initState atomic.Int32 + initTimer := time.AfterFunc(s.cfg.LoginTimeout, func() { + if initState.CompareAndSwap(0, 2) { + _ = ch.Close() + } + }) + defer initTimer.Stop() var sftpDone sync.WaitGroup // mine is set once this channel runs the connection's sftp subsystem. // While another channel runs it, this one is an extra: every request is @@ -570,7 +663,7 @@ func (s *Server) serveSession(nc ssh.NewChannel, st *connState) { for req := range reqs { switch req.Type { case "subsystem": - if name, ok := subsystemName(req.Payload); !ok || name != sftpSubsystem || !st.sftpStarted.CompareAndSwap(false, true) { + if name, ok := subsystemName(req.Payload); !ok || name != sftpSubsystem || !initState.CompareAndSwap(0, 1) || !st.sftpStarted.CompareAndSwap(false, true) { refuse(req) continue } @@ -635,16 +728,23 @@ func (s *Server) checkOnce(ctx context.Context) { if len(tokens) == 0 { return } + // The confirmation time is taken before the request, so a slow answer + // never extends a session past what the API actually saw. + asked := time.Now() cctx, cancel := context.WithTimeout(ctx, s.cfg.LoginTimeout) defer cancel() revoked, err := s.api.CheckSessions(cctx, tokens) if err != nil { - // Keep the connections. Failing open is not a revocation, and - // closing on a transient API error would drop healthy users. - s.log.Warn("session check failed; connections kept", "err", err) + // One failed check keeps the connections, so a short API blip does + // not drop healthy users. A session left unconfirmed for + // RevalidateWithin, or past its expiry, is closed by expireStale. + s.log.Warn("session check failed", "err", err) + s.expireStale(time.Now()) return } + gone := make(map[string]struct{}, len(revoked)) for _, tok := range revoked { + gone[tok] = struct{}{} s.mu.Lock() st := s.tokens[tok] s.mu.Unlock() @@ -655,6 +755,38 @@ func (s *Server) checkOnce(ctx context.Context) { s.metrics.revoked() _ = st.sconn.Close() } + s.mu.Lock() + for _, tok := range tokens { + if _, isGone := gone[tok]; isGone { + continue + } + if st := s.tokens[tok]; st != nil { + st.confirm(asked, s.cfg.RevalidateWithin) + } + } + s.mu.Unlock() + s.expireStale(time.Now()) +} + +// expireStale closes every connection whose session has not been confirmed +// by the API recently enough to still be valid (fail closed). +func (s *Server) expireStale(now time.Time) { + s.mu.Lock() + var stale []*connState + for _, st := range s.tokens { + if now.UnixNano() > st.validUntil.Load() { + stale = append(stale, st) + } + } + s.mu.Unlock() + for _, st := range stale { + if !st.revoked.CompareAndSwap(false, true) { + continue + } + s.log.Info("session not confirmed by the API; connection closed", "user", st.user) + s.metrics.unconfirmed() + _ = st.sconn.Close() + } } // deadlineConn pushes the connection deadline forward on every read and diff --git a/internal/sshserver/server_test.go b/internal/sshserver/server_test.go index 4dd59b7..cff293e 100644 --- a/internal/sshserver/server_test.go +++ b/internal/sshserver/server_test.go @@ -34,6 +34,10 @@ type fakeAPI struct { ended []string endErr error seq int + // checkErr, when set, fails every session check. + checkErr error + // expiresIn is the session lifetime a login returns. Zero means 1h. + expiresIn time.Duration } func (f *fakeAPI) Login(_ context.Context, r apiclient.LoginRequest) (apiclient.Session, error) { @@ -45,9 +49,13 @@ func (f *fakeAPI) Login(_ context.Context, r apiclient.LoginRequest) (apiclient. } f.seq++ user, target, hasTarget := strings.Cut(r.Username, "+") + expiresIn := f.expiresIn + if expiresIn == 0 { + expiresIn = time.Hour + } sess := apiclient.Session{ Token: fmt.Sprintf("gpsftp_test_%d", f.seq), - ExpiresAt: time.Now().Add(time.Hour).UTC().Truncate(time.Second), + ExpiresAt: time.Now().Add(expiresIn).UTC().Truncate(time.Second), User: user, } if hasTarget { @@ -58,8 +66,11 @@ func (f *fakeAPI) Login(_ context.Context, r apiclient.LoginRequest) (apiclient. func (f *fakeAPI) CheckSessions(_ context.Context, tokens []string) ([]string, error) { f.mu.Lock() - fn := f.revoke + fn, checkErr := f.revoke, f.checkErr f.mu.Unlock() + if checkErr != nil { + return nil, checkErr + } if fn == nil { return nil, nil } diff --git a/internal/vfs/errors.go b/internal/vfs/errors.go index b07dd1f..3e71fb3 100644 --- a/internal/vfs/errors.go +++ b/internal/vfs/errors.go @@ -72,5 +72,8 @@ func (f *FS) fail(op string, err error) error { return nil } f.log.Debug("sftp operation failed", "op", op, "user", f.user, "err", err.Error()) + if f.onUnauth != nil && errors.Is(err, apiclient.ErrUnauthorized) { + f.onUnauth() + } return toSFTP(err) } diff --git a/internal/vfs/unauthorized_test.go b/internal/vfs/unauthorized_test.go new file mode 100644 index 0000000..b5aa63d --- /dev/null +++ b/internal/vfs/unauthorized_test.go @@ -0,0 +1,32 @@ +package vfs + +import ( + "errors" + "testing" + + "github.com/GameplanePanel/gameplane/sftp/internal/apiclient" + "github.com/pkg/sftp" +) + +// A 401 from the API on a file request reports the session as refused, so +// the server can close the connection at once. Other errors do not. +func TestFailReportsUnauthorized(t *testing.T) { + calls := 0 + f := New(nil, apiclient.Session{Token: testToken, User: "alice"}, Options{OnUnauthorized: func() { calls++ }}) + if err := f.fail("list", &apiclient.Error{Op: "list", Status: 404, Err: apiclient.ErrNotFound}); !errors.Is(err, sftp.ErrSSHFxNoSuchFile) { + t.Fatalf("not found mapped to %v", err) + } + if calls != 0 { + t.Fatalf("OnUnauthorized called %d times for a 404", calls) + } + if err := f.fail("list", &apiclient.Error{Op: "list", Status: 401, Err: apiclient.ErrUnauthorized}); !errors.Is(err, sftp.ErrSSHFxPermissionDenied) { + t.Fatalf("unauthorized mapped to %v", err) + } + if calls != 1 { + t.Fatalf("OnUnauthorized called %d times for a 401, want 1", calls) + } + // Without a hook a 401 is only mapped. + if err := New(nil, apiclient.Session{Token: testToken}, Options{}).fail("list", apiclient.ErrUnauthorized); !errors.Is(err, sftp.ErrSSHFxPermissionDenied) { + t.Fatalf("unauthorized without hook mapped to %v", err) + } +} diff --git a/internal/vfs/vfs.go b/internal/vfs/vfs.go index 3f898de..07e8c9c 100644 --- a/internal/vfs/vfs.go +++ b/internal/vfs/vfs.go @@ -55,20 +55,25 @@ type Options struct { OnBytes func(direction string, n int) // Logger receives debug logs. Nil discards them. Logger *slog.Logger + // OnUnauthorized is called when the API refuses the session token (HTTP + // 401) on a file request, so the connection can be closed at once. May + // be nil. + OnUnauthorized func() } // FS is the virtual file system of one authenticated SSH connection. It is // safe for concurrent use by the SFTP request workers. type FS struct { - api API - token string - user string - target *apiclient.Target - started time.Time - defNS string - limiter *Limiter - onBytes func(direction string, n int) - log *slog.Logger + api API + token string + user string + target *apiclient.Target + started time.Time + defNS string + limiter *Limiter + onBytes func(direction string, n int) + onUnauth func() + log *slog.Logger mu sync.Mutex loaded bool @@ -88,15 +93,16 @@ func New(api API, session apiclient.Session, opts Options) *FS { lg = slog.New(slog.DiscardHandler) } return &FS{ - api: api, - token: session.Token, - user: strings.ToLower(session.User), - target: session.Target, - started: time.Now(), - defNS: ns, - limiter: opts.Limiter, - onBytes: opts.OnBytes, - log: lg, + api: api, + token: session.Token, + user: strings.ToLower(session.User), + target: session.Target, + started: time.Now(), + defNS: ns, + limiter: opts.Limiter, + onBytes: opts.OnBytes, + onUnauth: opts.OnUnauthorized, + log: lg, } } diff --git a/main.go b/main.go index 24ab090..7869998 100644 --- a/main.go +++ b/main.go @@ -36,27 +36,34 @@ var errUsage = errors.New("usage: sftp serve [flags] | sftp version") // Defaults and environment variable names for the serve subcommand. A flag // overrides its variable, and the variable overrides the default. const ( - defaultListen = ":2222" - defaultMetricsAddr = ":9102" + defaultListen = ":2222" + // The metrics listener is loopback-only by default: it has no + // authentication, so exposing it is an explicit choice (the chart binds + // it to the pod address only when a scrape is configured). + defaultMetricsAddr = "127.0.0.1:9102" defaultIdleTimeout = 15 * time.Minute defaultMaxSessionsPerUser = 4 defaultMaxTransfersPerUser = 8 defaultMaxPreAuth = 64 + defaultMaxPreAuthPerIP = 8 envListen = "GAMEPLANE_SFTP_LISTEN" envHostKey = "GAMEPLANE_SFTP_HOST_KEY" envAPIURL = "GAMEPLANE_SFTP_API_URL" envSvcAuthFile = "GAMEPLANE_SFTP_SERVICE_TOKEN_FILE" envCAFile = "GAMEPLANE_SFTP_CA_FILE" + envAllowInsecureAPI = "GAMEPLANE_SFTP_ALLOW_INSECURE_API" envIdleTimeout = "GAMEPLANE_SFTP_IDLE_TIMEOUT" envMaxSessionsPerUser = "GAMEPLANE_SFTP_MAX_SESSIONS_PER_USER" envMaxTransfersPerUser = "GAMEPLANE_SFTP_MAX_TRANSFERS_PER_USER" envMaxPreAuth = "GAMEPLANE_SFTP_MAX_PREAUTH_CONNECTIONS" + envMaxPreAuthPerIP = "GAMEPLANE_SFTP_MAX_PREAUTH_PER_IP" envMetricsAddr = "GAMEPLANE_SFTP_METRICS_ADDR" envDefaultNamespace = "GAMEPLANE_SFTP_DEFAULT_NAMESPACE" metricsShutdownTimeout = 5 * time.Second metricsReadHeaderLimit = 10 * time.Second + metricsIOLimit = 30 * time.Second ) func main() { @@ -93,19 +100,23 @@ func run(args []string, out io.Writer) error { // serveConfig is the parsed serve subcommand. type serveConfig struct { - Listen string - HostKeyPath string - APIURL string - ServiceTokenFile string - CAFile string + Listen string + HostKeyPath string + APIURL string + ServiceTokenFile string + CAFile string + // AllowInsecureAPI accepts an http:// API URL. Off by default. + AllowInsecureAPI bool IdleTimeout time.Duration MaxSessionsPerUser int // MaxTransfersPerUser is handed to the virtual file system's per-user // transfer limiter. MaxTransfersPerUser int // MaxPreAuth caps concurrent connections still before authentication. - MaxPreAuth int - MetricsAddr string + MaxPreAuth int + // MaxPreAuthPerIP caps those connections per source IP. + MaxPreAuthPerIP int + MetricsAddr string // DefaultNamespace is the namespace shown as / at the top of a // tree login. It must match the API's default games namespace. DefaultNamespace string @@ -132,6 +143,15 @@ func parseServeConfig(args []string, getenv func(string) string, errOut io.Write return serveConfig{}, err } + maxPreAuthIP, err := envInt(getenv, envMaxPreAuthPerIP, defaultMaxPreAuthPerIP) + if err != nil { + return serveConfig{}, err + } + allowInsecure, err := envBool(getenv, envAllowInsecureAPI) + if err != nil { + return serveConfig{}, err + } + var c serveConfig fs := flag.NewFlagSet("serve", flag.ContinueOnError) fs.SetOutput(errOut) @@ -140,10 +160,12 @@ func parseServeConfig(args []string, getenv func(string) string, errOut io.Write fs.StringVar(&c.APIURL, "api-url", getenv(envAPIURL), "Gameplane API base URL, for example https://gameplane-api.gameplane.svc:8080 (required)") fs.StringVar(&c.ServiceTokenFile, "service-token-file", getenv(envSvcAuthFile), "file holding the service token (required)") fs.StringVar(&c.CAFile, "ca-file", getenv(envCAFile), "optional PEM bundle of extra CA certificates for the API") + fs.BoolVar(&c.AllowInsecureAPI, "allow-insecure-api", allowInsecure, "accept an http:// API URL; credentials then cross the network unencrypted (only for a hop inside one cluster's pod network)") fs.DurationVar(&c.IdleTimeout, "idle-timeout", idle, "close a connection with no traffic for this long") fs.IntVar(&c.MaxSessionsPerUser, "max-sessions-per-user", maxSessions, "concurrent SSH connections allowed per user") fs.IntVar(&c.MaxTransfersPerUser, "max-transfers-per-user", maxTransfers, "concurrent file transfers allowed per user") fs.IntVar(&c.MaxPreAuth, "max-preauth-connections", maxPreAuth, "concurrent connections allowed before authentication finishes; more are closed at once") + fs.IntVar(&c.MaxPreAuthPerIP, "max-preauth-per-ip", maxPreAuthIP, "concurrent connections allowed per source IP before authentication finishes; more are closed at once") fs.StringVar(&c.MetricsAddr, "metrics-addr", envString(getenv, envMetricsAddr, defaultMetricsAddr), "address for /metrics; empty disables it") fs.StringVar(&c.DefaultNamespace, "default-namespace", envString(getenv, envDefaultNamespace, vfs.DefaultNamespace), "namespace whose servers appear as /; must match the API's default games namespace") if err := fs.Parse(args); err != nil { @@ -174,6 +196,9 @@ func parseServeConfig(args []string, getenv func(string) string, errOut io.Write if c.MaxPreAuth < 1 { return serveConfig{}, errors.New("serve: --max-preauth-connections must be at least 1") } + if c.MaxPreAuthPerIP < 1 { + return serveConfig{}, errors.New("serve: --max-preauth-per-ip must be at least 1") + } return c, nil } @@ -184,6 +209,18 @@ func envString(getenv func(string) string, key, def string) string { return def } +func envBool(getenv func(string) string, key string) (bool, error) { + v := getenv(key) + if v == "" { + return false, nil + } + b, err := strconv.ParseBool(v) + if err != nil { + return false, fmt.Errorf("%s: %w", key, err) + } + return b, nil +} + func envDuration(getenv func(string) string, key string, def time.Duration) (time.Duration, error) { v := getenv(key) if v == "" { @@ -224,7 +261,7 @@ func runServe(args []string, getenv func(string) string, errOut io.Writer) error if err != nil { return err } - api, err := apiclient.New(apiclient.Config{BaseURL: cfg.APIURL, ServiceToken: token, CAFile: cfg.CAFile}) + api, err := apiclient.New(apiclient.Config{BaseURL: cfg.APIURL, ServiceToken: token, CAFile: cfg.CAFile, AllowInsecureHTTP: cfg.AllowInsecureAPI}) if err != nil { return fmt.Errorf("api client: %w", err) } @@ -235,20 +272,25 @@ func runServe(args []string, getenv func(string) string, errOut io.Writer) error return err } limiter := vfs.NewLimiter(cfg.MaxTransfersPerUser) + // srv is set right below, before Serve starts any connection, so the + // handlers never see it nil. + var srv *sshserver.Server factory := func(sess apiclient.Session, _ string) sftp.Handlers { return vfs.New(api, sess, vfs.Options{ DefaultNamespace: cfg.DefaultNamespace, Limiter: limiter, OnBytes: metrics.AddBytes, Logger: logger, + OnUnauthorized: func() { srv.Revoke(sess.Token) }, }).Handlers() } - srv, err := sshserver.New(sshserver.Config{ + srv, err = sshserver.New(sshserver.Config{ Addr: cfg.Listen, HostKeys: hostKeys, IdleTimeout: cfg.IdleTimeout, MaxSessionsPerUser: cfg.MaxSessionsPerUser, MaxPreAuthConnections: cfg.MaxPreAuth, + MaxPreAuthPerIP: cfg.MaxPreAuthPerIP, Logger: logger, Metrics: metrics, }, api, factory) @@ -265,10 +307,15 @@ func runServe(args []string, getenv func(string) string, errOut io.Writer) error var metricsSrv *http.Server if cfg.MetricsAddr != "" { + mux := http.NewServeMux() + mux.Handle("GET /metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{})) metricsSrv = &http.Server{ Addr: cfg.MetricsAddr, - Handler: promhttp.HandlerFor(reg, promhttp.HandlerOpts{}), + Handler: mux, ReadHeaderTimeout: metricsReadHeaderLimit, + ReadTimeout: metricsIOLimit, + WriteTimeout: metricsIOLimit, + IdleTimeout: metricsIOLimit, } go func() { if err := metricsSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { diff --git a/main_hardening_test.go b/main_hardening_test.go new file mode 100644 index 0000000..a4d5427 --- /dev/null +++ b/main_hardening_test.go @@ -0,0 +1,98 @@ +package main + +import ( + "bytes" + "crypto/ed25519" + "crypto/rand" + "encoding/pem" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "golang.org/x/crypto/ssh" +) + +func writeHostKey(t *testing.T, dir string) string { + t.Helper() + _, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatalf("generate key: %v", err) + } + block, err := ssh.MarshalPrivateKey(priv, "") + if err != nil { + t.Fatalf("marshal key: %v", err) + } + p := filepath.Join(dir, "host_key") + if err := os.WriteFile(p, pem.EncodeToMemory(block), 0o600); err != nil { + t.Fatalf("write key: %v", err) + } + return p +} + +func writeToken(t *testing.T, dir string) string { + t.Helper() + p := filepath.Join(dir, "token") + if err := os.WriteFile(p, []byte("gpsftps_test\n"), 0o600); err != nil { + t.Fatalf("write token: %v", err) + } + return p +} + +func TestParseServeConfigAllowInsecureAPI(t *testing.T) { + c, err := parseServeConfig(nil, envFunc(fullServeEnv()), io.Discard) + if err != nil || c.AllowInsecureAPI { + t.Fatalf("default = %v, %v; want false", c.AllowInsecureAPI, err) + } + c, err = parseServeConfig(nil, envFunc(withEnv(fullServeEnv(), envAllowInsecureAPI, "true")), io.Discard) + if err != nil || !c.AllowInsecureAPI { + t.Fatalf("env = %v, %v; want true", c.AllowInsecureAPI, err) + } + c, err = parseServeConfig([]string{"--allow-insecure-api=false"}, envFunc(withEnv(fullServeEnv(), envAllowInsecureAPI, "true")), io.Discard) + if err != nil || c.AllowInsecureAPI { + t.Fatalf("flag = %v, %v; want false", c.AllowInsecureAPI, err) + } + if _, err := parseServeConfig(nil, envFunc(withEnv(fullServeEnv(), envAllowInsecureAPI, "maybe")), io.Discard); err == nil { + t.Fatal("bad boolean accepted") + } +} + +func TestParseServeConfigMaxPreAuthPerIP(t *testing.T) { + c, err := parseServeConfig(nil, envFunc(fullServeEnv()), io.Discard) + if err != nil || c.MaxPreAuthPerIP != defaultMaxPreAuthPerIP { + t.Fatalf("default = %d, %v; want %d", c.MaxPreAuthPerIP, err, defaultMaxPreAuthPerIP) + } + c, err = parseServeConfig([]string{"--max-preauth-per-ip=3"}, envFunc(withEnv(fullServeEnv(), envMaxPreAuthPerIP, "5")), io.Discard) + if err != nil || c.MaxPreAuthPerIP != 3 { + t.Fatalf("flag = %d, %v; want 3", c.MaxPreAuthPerIP, err) + } + for _, v := range []string{"0", "lots"} { + if _, err := parseServeConfig(nil, envFunc(withEnv(fullServeEnv(), envMaxPreAuthPerIP, v)), io.Discard); err == nil { + t.Errorf("per-IP cap %q accepted", v) + } + } +} + +func TestDefaultMetricsAddrIsLoopback(t *testing.T) { + if !strings.HasPrefix(defaultMetricsAddr, "127.0.0.1:") { + t.Fatalf("default metrics address %q is not loopback-only", defaultMetricsAddr) + } +} + +// serve refuses a plain-HTTP API URL unless it is explicitly allowed. +func TestServeRefusesHTTPAPIURL(t *testing.T) { + dir := t.TempDir() + env := map[string]string{ + envHostKey: writeHostKey(t, dir), + envAPIURL: "http://api.example", + envSvcAuthFile: writeToken(t, dir), + envListen: "127.0.0.1:0", + envMetricsAddr: "", + } + var errOut bytes.Buffer + err := runServe(nil, envFunc(env), &errOut) + if err == nil || !strings.Contains(err.Error(), "https") { + t.Fatalf("runServe with an http API URL = %v, want an https error", err) + } +} diff --git a/specs.md b/specs.md index 9d143d6..85790e3 100644 --- a/specs.md +++ b/specs.md @@ -37,15 +37,17 @@ Optional SFTP endpoint, one per cluster, that gives users SFTP access to the fil |---|---|---|---| | `--listen` | `GAMEPLANE_SFTP_LISTEN` | `:2222` | SSH listen address | | `--host-key` | `GAMEPLANE_SFTP_HOST_KEY` | required | host key file, or a directory of keys (a mounted Secret works; `.pub` and hidden names are skipped) | -| `--api-url` | `GAMEPLANE_SFTP_API_URL` | required | Gameplane API base URL | +| `--api-url` | `GAMEPLANE_SFTP_API_URL` | required | Gameplane API base URL; must be `https` unless `--allow-insecure-api` is set | +| `--allow-insecure-api` | `GAMEPLANE_SFTP_ALLOW_INSECURE_API` | `false` | accept an `http` API URL. Credentials then cross the network in clear text, so use it only for a hop inside one cluster's pod network (the chart's local mode) | | `--service-token-file` | `GAMEPLANE_SFTP_SERVICE_TOKEN_FILE` | required | file holding the service token (`gpsftps_...`) | | `--ca-file` | `GAMEPLANE_SFTP_CA_FILE` | none | extra PEM CA bundle for the API, added to the system roots | | `--idle-timeout` | `GAMEPLANE_SFTP_IDLE_TIMEOUT` | `15m` | close a connection with no traffic for this long | | `--max-sessions-per-user` | `GAMEPLANE_SFTP_MAX_SESSIONS_PER_USER` | `4` | concurrent SSH connections per user | | `--max-preauth-connections` | `GAMEPLANE_SFTP_MAX_PREAUTH_CONNECTIONS` | `64` | concurrent connections still before authentication; further ones are closed at once | +| `--max-preauth-per-ip` | `GAMEPLANE_SFTP_MAX_PREAUTH_PER_IP` | `8` | the same, per source IP, so one address cannot take every pre-auth slot | | `--max-transfers-per-user` | `GAMEPLANE_SFTP_MAX_TRANSFERS_PER_USER` | `8` | concurrent file transfers per user, across connections | | `--default-namespace` | `GAMEPLANE_SFTP_DEFAULT_NAMESPACE` | `gameplane-games` | namespace shown as `/`; must equal the API's default games namespace | -| `--metrics-addr` | `GAMEPLANE_SFTP_METRICS_ADDR` | `:9102` | address for `/metrics`; empty disables it | +| `--metrics-addr` | `GAMEPLANE_SFTP_METRICS_ADDR` | `127.0.0.1:9102` | address for `/metrics` (unauthenticated, so loopback-only by default); empty disables it | Exit code 2 with a message on stderr for a usage or startup error. @@ -70,13 +72,15 @@ Exit code 2 with a message on stderr for a usage or startup error. ### Metrics -On `--metrics-addr` at `/metrics` (private registry): `gameplane_sftp_sessions` (gauge), `gameplane_sftp_logins_total{result="ok|denied|error|limit"}`, `gameplane_sftp_revoked_total`, `gameplane_sftp_preauth_rejected_total` (connections closed at once because the pre-auth cap was reached), `gameplane_sftp_bytes_total{direction="read|write"}`. +On `--metrics-addr` at `GET /metrics` only (private registry; read, write and idle timeouts of 30 s): `gameplane_sftp_sessions` (gauge), `gameplane_sftp_logins_total{result="ok|denied|error|limit"}`, `gameplane_sftp_revoked_total` (closed because the API reported the session revoked, or refused it with 401 on a file request), `gameplane_sftp_unconfirmed_closed_total` (closed because the API had not confirmed the session in time), `gameplane_sftp_preauth_rejected_total` (connections closed at once because the pre-auth cap was reached), `gameplane_sftp_bytes_total{direction="read|write"}`. ## Key invariants - Only session channels with the `sftp` subsystem are served. `shell`, `exec`, `pty-req`, `env`, `x11-req`, agent forwarding and every other request are refused; `direct-tcpip` and other channel types are rejected; global forwarding requests are discarded. Only one SFTP subsystem runs per connection, and a further session channel is accepted, but its requests (including a second `sftp` subsystem) are refused and the channel is closed right after the refusal, so it never sits idle until the idle timeout. A non-`sftp` subsystem, `shell` and `exec` are refused. -- Every authenticated connection is registered by session token. Every 30 seconds the server sends the tokens to `POST /sftp/v1/sessions/check` and closes the connections whose tokens are reported revoked. A failed check keeps the connections (it never fails open into a kill, nor a grant). -- At most `--max-preauth-connections` connections may be before authentication at once (the slot is freed when the handshake and the API login finish). A connection over the cap is closed immediately, before any SSH exchange, and counted in `gameplane_sftp_preauth_rejected_total`. +- A connection holds at most 2 session channels at once (the SFTP channel and one extra that is refused and closed). A further channel open is rejected with `resource-shortage` before it is accepted, so it costs no goroutine. An accepted session channel that has not started the SFTP subsystem within `LoginTimeout` (10 s) is closed. +- Every authenticated connection is registered by session token. Every 30 seconds the server sends the tokens to `POST /sftp/v1/sessions/check` and closes the connections whose tokens are reported revoked; the API reports expired sessions as revoked too. One failed check keeps the connections, so a short API outage does not drop users, but the server fails closed: a connection whose session the API has not confirmed for `RevalidateWithin` (2 min), or whose expiry from login (or from its last confirmation, the API's 15-minute sliding lifetime) has passed without a confirmation, is closed and counted in `gameplane_sftp_unconfirmed_closed_total`. A login whose session is already expired is refused. +- A file request the API refuses with 401 (the session token is no longer valid) closes the connection at once instead of waiting for the next check. +- At most `--max-preauth-connections` connections, and at most `--max-preauth-per-ip` from one source IP, may be before authentication at once (the slot is freed when the handshake and the API login finish). A connection over the cap is closed immediately, before any SSH exchange, and counted in `gameplane_sftp_preauth_rejected_total`. - An API session the server creates but does not use is ended with `POST /sftp/v1/sessions/end` (service token, body `{"sessionTokens": ["gpsftp_…"]}`): a login refused by the per-user cap (password or key), and a password login whose SSH handshake does not finish. A failed end call is only logged; the session still expires on its own. - Per-user caps are keyed by the lowercased API user name and enforced after authentication. - The session token is used only as the bearer for the API calls of its own connection and is never logged. Passwords and keys are never logged. @@ -91,7 +95,8 @@ On `--metrics-addr` at `/metrics` (private registry): `gameplane_sftp_sessions` - Authentication failures are generic (core rule 3); rate limiting of failed logins is done by the API per user and per source address, using the client address this server forwards. - The service token authorises only login and session checks; file operations use the user's own short-lived session token, which the API restricts to the SFTP routes. - Host keys must be stable across restarts (mounted from a Secret); they are read through `os.Root`, so a path cannot escape its directory. -- The API URL should be `https`; use `--ca-file` for a private CA. +- The API URL must be `https`, with the certificate checked against the system roots plus `--ca-file`; plain `http` needs `--allow-insecure-api`, which the chart sets only in local mode, where the hop is pod to pod inside the cluster behind the SFTP NetworkPolicy. The client never follows a redirect: a 3xx answer fails the call, so the password, key or token is never re-sent to another URL. +- `/metrics` has no authentication and is loopback-only by default. The chart binds it to the pod address only when a ServiceMonitor scrapes it, behind a NetworkPolicy rule for the scrape namespace, and never adds it to the public SFTP Service. - The session-end route `POST /sftp/v1/sessions/end` is not yet in the Gameplane API contract (`specs/040-sftp-access/contracts/api.md`). Until the API implements it, the call fails (logged at debug level) and an unused session expires on its own. ## Testing & coverage