Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<user>` to see every server they may access, or as `<user>+<server>` (or `<user>+<namespace>/<server>`) to open one server directly. There is no shell, command execution or port forwarding. Dotfiles are hidden.

Expand Down
29 changes: 24 additions & 5 deletions internal/apiclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
}

Expand Down Expand Up @@ -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)
Expand Down
70 changes: 70 additions & 0 deletions internal/apiclient/hardening_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
243 changes: 243 additions & 0 deletions internal/sshserver/hardening_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading