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
76 changes: 76 additions & 0 deletions internal/sshserver/key_fallback_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
73 changes: 46 additions & 27 deletions internal/sshserver/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down Expand Up @@ -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) {
Expand All @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion specs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down