From d66da619681000ec136913255a13c31a15fae572 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 21:46:22 +0000 Subject: [PATCH] fix: let a refused SSH key fall back to the password The SSH layer accepted any offered key and the API was asked only after the handshake, so an unregistered key ended in "connection closed by remote host" and OpenSSH never prompted for the SFTP password. Ask the API in VerifiedPublicKeyCallback instead, after the signature check but still during authentication: a refused key now fails only that attempt. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Claude --- internal/sshserver/key_fallback_test.go | 76 +++++++++++++++++++++++++ internal/sshserver/server.go | 73 +++++++++++++++--------- specs.md | 2 +- 3 files changed, 123 insertions(+), 28 deletions(-) create mode 100644 internal/sshserver/key_fallback_test.go diff --git a/internal/sshserver/key_fallback_test.go b/internal/sshserver/key_fallback_test.go new file mode 100644 index 0000000..478908e --- /dev/null +++ b/internal/sshserver/key_fallback_test.go @@ -0,0 +1,76 @@ +package sshserver + +import ( + "context" + "log/slog" + "net" + "testing" + "time" + + "golang.org/x/crypto/ssh" + + "github.com/GameplanePanel/gameplane/sftp/internal/apiclient" +) + +// keyRefusingAPI refuses every public-key login and accepts passwords, like a +// user whose client offers a key that is not registered in the panel. +type keyRefusingAPI struct{ fakeAPI } + +func (k *keyRefusingAPI) Login(ctx context.Context, r apiclient.LoginRequest) (apiclient.Session, error) { + if r.PublicKey != "" { + k.mu.Lock() + k.logins = append(k.logins, r) + k.mu.Unlock() + return apiclient.Session{}, apiclient.ErrUnauthorized + } + return k.fakeAPI.Login(ctx, r) +} + +// A key the API refuses fails only that authentication attempt: the client +// goes on to the password and the session works. Before, the SSH layer +// accepted the key, the API refused it after the handshake and the server +// closed the connection, so OpenSSH never asked for the password. +func TestRefusedKeyFallsBackToPassword(t *testing.T) { + api := &keyRefusingAPI{} + srv, err := New(Config{ + HostKeys: []ssh.Signer{newEd25519Signer(t)}, + CheckInterval: time.Hour, + Logger: slog.New(slog.DiscardHandler), + }, 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() + if err := <-done; err != nil { + t.Errorf("Serve returned %v", err) + } + }) + + c, err := ssh.Dial("tcp", l.Addr().String(), &ssh.ClientConfig{ + User: "valgul", + Auth: []ssh.AuthMethod{ssh.PublicKeys(newEd25519Signer(t)), ssh.Password("pw")}, + HostKeyCallback: ssh.InsecureIgnoreHostKey(), + Timeout: 5 * time.Second, + }) + if err != nil { + t.Fatalf("dial with an unregistered key then a password: %v", err) + } + defer func() { _ = c.Close() }() + if err := readRoot(c); err != nil { + t.Fatalf("sftp after password fallback: %v", err) + } + + api.mu.Lock() + defer api.mu.Unlock() + if len(api.logins) != 2 || api.logins[0].PublicKey == "" || api.logins[1].Password != "pw" { + t.Fatalf("logins = %+v, want the key refused, then the password", api.logins) + } +} diff --git a/internal/sshserver/server.go b/internal/sshserver/server.go index 45fafca..0010ace 100644 --- a/internal/sshserver/server.go +++ b/internal/sshserver/server.go @@ -137,10 +137,11 @@ func New(cfg Config, api API, hf HandlerFactory) (*Server, error) { base: context.Background(), } sc := &ssh.ServerConfig{ - PasswordCallback: s.passwordCallback, - PublicKeyCallback: s.publicKeyCallback, - MaxAuthTries: maxAuthTries, - ServerVersion: serverVersion, + PasswordCallback: s.passwordCallback, + PublicKeyCallback: s.publicKeyCallback, + VerifiedPublicKeyCallback: s.verifiedPublicKeyCallback, + MaxAuthTries: maxAuthTries, + ServerVersion: serverVersion, } for _, k := range cfg.HostKeys { sc.AddHostKey(k) @@ -358,7 +359,7 @@ func (s *Server) handle(ctx context.Context, raw net.Conn, releasePreAuth func() dc.hard.Store(time.Now().Add(s.cfg.LoginTimeout).UnixNano()) sconn, chans, reqs, err := ssh.NewServerConn(dc, s.sshCfg) - // A password login already created an API session in the callback. + // A password or public-key login already created an API session in its callback. pwSess, hasPW := s.takePending(remote) if err != nil { s.log.Debug("ssh handshake ended", "remote", remote, "err", err) @@ -372,8 +373,7 @@ func (s *Server) handle(ctx context.Context, raw net.Conn, releasePreAuth func() dc.hard.Store(0) // The SSH mux is already blocked in a read whose deadline came from the - // handshake. Push it out so a public-key login call to the API, which may - // take up to LoginTimeout, is not cut off by it. + // handshake. Push it out to the session's own timeout. dc.idle.Store(int64(max(s.cfg.IdleTimeout, s.cfg.LoginTimeout))) dc.touch() sess, err := s.establish(ctx, sconn, pwSess, hasPW) @@ -415,10 +415,10 @@ func (s *Server) handle(ctx context.Context, raw net.Conn, releasePreAuth func() channels.Wait() } -// establish returns the session for a finished handshake. Password logins -// were checked in the password callback. Public-key logins are checked here, -// after the SSH layer has verified the signature, so the API only ever sees -// keys the client proved it holds. +// establish returns the session for a finished handshake. Password and +// public-key logins were both checked with the API during authentication (the +// key only after the SSH layer verified its signature), and their session +// travels in the permissions. func (s *Server) establish(ctx context.Context, sconn *ssh.ServerConn, pwSess apiclient.Session, hasPW bool) (apiclient.Session, error) { perms := sconn.Permissions if perms == nil { @@ -427,20 +427,6 @@ func (s *Server) establish(ctx context.Context, sconn *ssh.ServerConn, pwSess ap } return apiclient.Session{}, errPermissionDenied } - if line := perms.Extensions[extPublicKey]; line != "" { - lctx, cancel := context.WithTimeout(ctx, s.cfg.LoginTimeout) - defer cancel() - sess, err := s.api.Login(lctx, apiclient.LoginRequest{ - Username: sconn.User(), - PublicKey: line, - RemoteAddr: sconn.RemoteAddr().String(), - }) - if err != nil { - s.loginFailed(sconn.User(), sconn.RemoteAddr().String(), err) - return apiclient.Session{}, errPermissionDenied - } - return sess, nil - } sess, err := sessionFromExtensions(perms.Extensions) if err != nil { if hasPW { @@ -496,6 +482,13 @@ func (s *Server) passwordCallback(conn ssh.ConnMetadata, pw []byte) (*ssh.Permis s.loginFailed(conn.User(), conn.RemoteAddr().String(), err) return nil, errPermissionDenied } + return s.loggedIn(conn, sess) +} + +// loggedIn finishes a login the API accepted during authentication: it +// refuses a user already at the session cap and remembers the session until +// the handshake ends. +func (s *Server) loggedIn(conn ssh.ConnMetadata, sess apiclient.Session) (*ssh.Permissions, error) { // Fast refusal for a user already at the cap. admit enforces it again // after the handshake, which is the authoritative check. if s.atLimit(sess.User) { @@ -513,13 +506,39 @@ func (s *Server) passwordCallback(conn ssh.ConnMetadata, pw []byte) (*ssh.Permis } // publicKeyCallback only records the offered key. The SSH layer calls it -// before the signature is checked, so the API is not asked here; establish -// does that after the handshake. +// before the signature is checked, so the API is not asked here; +// verifiedPublicKeyCallback does that once the signature is verified. func (s *Server) publicKeyCallback(_ ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { line := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))) return &ssh.Permissions{Extensions: map[string]string{extPublicKey: line}}, nil } +// verifiedPublicKeyCallback logs the user in through the API with a key whose +// signature the SSH layer has verified. A key the API refuses fails only that +// authentication attempt, so the client goes on to its next key or to the +// password prompt instead of losing the connection. +func (s *Server) verifiedPublicKeyCallback(conn ssh.ConnMetadata, _ ssh.PublicKey, perms *ssh.Permissions, _ string) (*ssh.Permissions, error) { + line := "" + if perms != nil { + line = perms.Extensions[extPublicKey] + } + if line == "" { + return nil, errPermissionDenied + } + ctx, cancel := context.WithTimeout(context.Background(), s.cfg.LoginTimeout) + defer cancel() + sess, err := s.api.Login(ctx, apiclient.LoginRequest{ + Username: conn.User(), + PublicKey: line, + RemoteAddr: conn.RemoteAddr().String(), + }) + if err != nil { + s.loginFailed(conn.User(), conn.RemoteAddr().String(), err) + return nil, errPermissionDenied + } + return s.loggedIn(conn, sess) +} + func (s *Server) loginFailed(user, remote string, err error) { result := loginError if errors.Is(err, apiclient.ErrUnauthorized) || errors.Is(err, apiclient.ErrBusy) { diff --git a/specs.md b/specs.md index 06f3557..9d143d6 100644 --- a/specs.md +++ b/specs.md @@ -52,7 +52,7 @@ Exit code 2 with a message on stderr for a usage or startup error. ### Login - Password: the callback sends the full SSH username (including a `+target` suffix), the password and the client address to `POST /sftp/v1/login` with the service token. -- Public key: the SSH layer verifies the signature, then the server logs in through the API with the key's authorized_keys line. Because the SSH library accepts the key before the API is asked, a refused key shows to the client as a connection that closes right after authentication, not as an authentication failure. Documented limitation. +- Public key: the SSH layer verifies the signature, then (in `VerifiedPublicKeyCallback`, still during authentication) the server logs in through the API with the key's authorized_keys line. A key the API refuses fails only that authentication attempt, so the client tries its next key or falls back to the password. Each refused key is one failed login at the API. - Every failure is a generic "permission denied" to the client; the cause is only logged at debug level and counted in metrics. - A login as `user+server` or `user+namespace/server` roots the connection at that server. Otherwise the root lists the user's servers.