ssh: add AuthCallback to ClientConfig

Add ClientAuthCallback, a hook invoked before each authentication
attempt that allows the client to dynamically select an auth method
based on server capabilities, partial successes, or previous failures.

clientAuthenticate tracks partial successes in a slice and passes
them to AuthCallback via ClientAuthContext.PartialSuccessMethods,
along with the list of failed methods and currently allowed methods.
When AuthCallback returns a non-nil AuthMethod, it is used for the
next attempt, bypassing the static findNext selection. When it
returns (nil, nil), the static config.Auth selection proceeds as
before. If AuthCallback returns (nil, error) the handshake aborts
immediately with that error.

To bound resource use when AuthCallback keeps supplying methods, the
client caps the total number of authentication attempts (failures and
partial successes combined) at 64; exceeding the cap aborts the
handshake with an error.

Fixes golang/go#76146

Change-Id: I0d02bea7b9dd724e95e5d9d49d85306666c0df7a
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/717140
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
This commit is contained in:
Nicola Murino
2026-05-21 19:36:57 -07:00
parent 4aab0d9d6a
commit d59570d1a3
4 changed files with 525 additions and 14 deletions
+409
View File
@@ -443,6 +443,415 @@ func TestStaticMultiKeyPartialThenKbdInteractive(t *testing.T) {
}
}
func TestAuthMethodDynamic(t *testing.T) {
config := &ClientConfig{
User: "testuser",
Auth: nil,
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
if len(ctx.Metadata.SessionID()) == 0 {
t.Error("empty sessionID")
}
if ctx.Algorithms.HostKey == "" {
t.Error("empty Host Key")
}
if slices.Contains(ctx.AllowedMethods, "password") {
return Password(clientPassword), nil
}
return nil, errors.New("auth callback error")
},
}
if err := tryAuth(t, config); err != nil {
t.Fatalf("unable to dial remote side: %s", err)
}
}
func TestAuthCallbackError(t *testing.T) {
config := &ClientConfig{
User: "testuser",
Auth: []AuthMethod{
Password(clientPassword),
},
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
return nil, errors.New("auth callback error")
},
}
if err := tryAuth(t, config); err == nil {
t.Fatal("authentication unexpectedly succeeded after AuthCallback returned an error")
}
}
func TestAuthCallbackPartialSuccess(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
clientConf := &ClientConfig{
User: "user",
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
if slices.Contains(ctx.AllowedMethods, "publickey") && !slices.Contains(ctx.PartialSuccessMethods, "publickey") {
return PublicKeys(testSigners["rsa"]), nil
}
if slices.Contains(ctx.PartialSuccessMethods, "publickey") && slices.Contains(ctx.AllowedMethods, "keyboard-interactive") {
return KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
return []string{"correct-token"}, nil
}), nil
}
return nil, fmt.Errorf("unexpected auth state: allowed=%v partial=%v", ctx.AllowedMethods, ctx.PartialSuccessMethods)
},
}
go NewServerConn(c1, partialSuccessPublicKeyAndKbdInteractiveServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
}
func TestAuthCallbackMultiKeyPartialSuccess(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
clientConf := &ClientConfig{
User: "user",
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
if slices.Contains(ctx.AllowedMethods, "publickey") && !slices.Contains(ctx.PartialSuccessMethods, "publickey") {
return PublicKeys(testSigners["rsa"]), nil
}
if slices.Contains(ctx.PartialSuccessMethods, "publickey") && slices.Contains(ctx.AllowedMethods, "publickey") {
return PublicKeys(testSigners["ecdsa"]), nil
}
return nil, fmt.Errorf("unexpected auth state: allowed=%v partial=%v", ctx.AllowedMethods, ctx.PartialSuccessMethods)
},
}
go NewServerConn(c1, partialSuccessMultiKeyServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
}
func TestAuthCallbackMultiKeyPartialThenKbdInteractive(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
clientConf := &ClientConfig{
User: "user",
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
partialCount := len(ctx.PartialSuccessMethods)
if partialCount == 0 && slices.Contains(ctx.AllowedMethods, "publickey") {
return PublicKeys(testSigners["rsa"]), nil
}
if partialCount == 1 && slices.Contains(ctx.AllowedMethods, "publickey") {
return PublicKeys(testSigners["ecdsa"]), nil
}
if partialCount >= 2 && slices.Contains(ctx.AllowedMethods, "keyboard-interactive") {
return KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
return []string{"correct-token"}, nil
}), nil
}
return nil, fmt.Errorf("unexpected auth state: allowed=%v partial=%v tried=%v",
ctx.AllowedMethods, ctx.PartialSuccessMethods, ctx.TriedMethods)
},
}
go NewServerConn(c1, partialSuccessMultiKeyThenKbdInteractiveServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
}
func TestAuthCallbackPartialSuccessKeyAThenKeyB(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
clientConf := &ClientConfig{
User: "user",
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
if len(ctx.PartialSuccessMethods) == 0 && slices.Contains(ctx.AllowedMethods, "publickey") {
return PublicKeys(testSigners["rsa"]), nil
}
if len(ctx.PartialSuccessMethods) == 1 && slices.Contains(ctx.AllowedMethods, "publickey") {
return PublicKeys(testSigners["ecdsa"]), nil
}
return nil, fmt.Errorf("unexpected auth state: allowed=%v partial=%v",
ctx.AllowedMethods, ctx.PartialSuccessMethods)
},
}
go NewServerConn(c1, partialSuccessKeyAThenKeyBServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
}
func TestAuthCallbackPartialSuccessWithStaticAuth(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
clientConf := &ClientConfig{
User: "user",
Auth: []AuthMethod{
PublicKeys(testSigners["rsa"]),
},
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
if slices.Contains(ctx.PartialSuccessMethods, "publickey") && slices.Contains(ctx.AllowedMethods, "keyboard-interactive") {
return KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
return []string{"correct-token"}, nil
}), nil
}
return nil, nil
},
}
go NewServerConn(c1, partialSuccessPublicKeyAndKbdInteractiveServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
}
func partialSuccessPubKeyForbiddenAfterPartialServer(maxTries int) *ServerConfig {
serverConf := &ServerConfig{
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
return nil, nil
}
return nil, errors.New("invalid credentials")
},
VerifiedPublicKeyCallback: func(conn ConnMetadata, key PublicKey, permissions *Permissions, signatureAlgorithm string) (*Permissions, error) {
if bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
return nil, &PartialSuccessError{
Next: ServerAuthCallbacks{
PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
return nil, errors.New("legacy public key authentication is forbidden")
},
KeyboardInteractiveCallback: func(conn ConnMetadata, client KeyboardInteractiveChallenge) (*Permissions, error) {
answers, err := client("", "", []string{"token: "}, []bool{true})
if err != nil {
return nil, err
}
if len(answers) == 1 && answers[0] == "correct-token" {
return nil, nil
}
return nil, errors.New("invalid token")
},
},
}
}
return nil, errors.New("invalid credentials")
},
MaxAuthTries: maxTries,
}
serverConf.AddHostKey(testSigners["rsa"])
return serverConf
}
func TestAuthCallbackPartialSuccessWithStaticMultiKey(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
clientConf := &ClientConfig{
User: "user",
Auth: []AuthMethod{
PublicKeys(
testSigners["rsa"],
testSigners["ecdsa"],
testSigners["ed25519"],
),
},
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
if slices.Contains(ctx.PartialSuccessMethods, "publickey") && slices.Contains(ctx.AllowedMethods, "keyboard-interactive") {
return KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
return []string{"correct-token"}, nil
}), nil
}
return nil, nil
},
}
go NewServerConn(c1, partialSuccessPubKeyForbiddenAfterPartialServer(2))
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
}
func TestAuthCallbackPartialSuccessShortCircuit(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
serverConf := partialSuccessPubKeyForbiddenAfterPartialServer(2)
pubkeyAttempts := 0
clientConf := &ClientConfig{
User: "user",
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
if slices.Contains(ctx.AllowedMethods, "publickey") && !slices.Contains(ctx.PartialSuccessMethods, "publickey") {
pubkeyAttempts++
return PublicKeys(testSigners["rsa"], testSigners["ecdsa"], testSigners["ed25519"]), nil
}
if slices.Contains(ctx.PartialSuccessMethods, "publickey") && slices.Contains(ctx.AllowedMethods, "keyboard-interactive") {
return KeyboardInteractive(func(name, instruction string, questions []string, echos []bool) ([]string, error) {
return []string{"correct-token"}, nil
}), nil
}
return nil, fmt.Errorf("unexpected auth state: allowed=%v partial=%v tried=%v",
ctx.AllowedMethods, ctx.PartialSuccessMethods, ctx.TriedMethods)
},
}
go NewServerConn(c1, serverConf)
_, _, _, err = NewClientConn(c2, "", clientConf)
if err != nil {
t.Fatalf("client login error: %s", err)
}
if pubkeyAttempts != 1 {
t.Errorf("expected publickey to be attempted once before short-circuit, got %d", pubkeyAttempts)
}
}
func TestAuthCallbackTriedLoopBound(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
serverConf := &ServerConfig{
MaxAuthTries: -1,
PasswordCallback: func(conn ConnMetadata, pass []byte) (*Permissions, error) {
return nil, errors.New("password rejected")
},
}
serverConf.AddHostKey(testSigners["rsa"])
invocations := 0
clientConf := &ClientConfig{
User: "user",
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
invocations++
return Password("wrong"), nil
},
}
go NewServerConn(c1, serverConf)
_, _, _, err = NewClientConn(c2, "", clientConf)
if err == nil {
t.Fatal("expected the client to abort after exceeding the attempts cap")
}
if !strings.Contains(err.Error(), "too many authentication attempts") {
t.Errorf("unexpected error: %v", err)
}
if invocations != maxAuthClientTried {
t.Errorf("AuthCallback invoked %d times; expected %d",
invocations, maxAuthClientTried)
}
}
func alwaysPartialPubKeyServer() *ServerConfig {
var alwaysPartial func(ConnMetadata, PublicKey) (*Permissions, error)
alwaysPartial = func(conn ConnMetadata, key PublicKey) (*Permissions, error) {
if !bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) {
return nil, errors.New("invalid credentials")
}
return nil, &PartialSuccessError{
Next: ServerAuthCallbacks{
PublicKeyCallback: alwaysPartial,
},
}
}
serverConf := &ServerConfig{
MaxAuthTries: -1,
PublicKeyCallback: alwaysPartial,
}
serverConf.AddHostKey(testSigners["rsa"])
return serverConf
}
func TestAuthCallbackPartialSuccessLoopBound(t *testing.T) {
c1, c2, err := netPipe()
if err != nil {
t.Fatalf("netPipe: %v", err)
}
defer c1.Close()
defer c2.Close()
invocations := 0
clientConf := &ClientConfig{
User: "user",
HostKeyCallback: InsecureIgnoreHostKey(),
AuthCallback: func(ctx *ClientAuthContext) (AuthMethod, error) {
invocations++
return PublicKeys(testSigners["rsa"]), nil
},
}
go NewServerConn(c1, alwaysPartialPubKeyServer())
_, _, _, err = NewClientConn(c2, "", clientConf)
if err == nil {
t.Fatal("expected the client to abort after exceeding the attempts cap")
}
if !strings.Contains(err.Error(), "too many authentication attempts") {
t.Errorf("unexpected error: %v", err)
}
if invocations != maxAuthClientTried {
t.Errorf("AuthCallback invoked %d times; expected %d",
invocations, maxAuthClientTried)
}
}
func TestAuthMethodPassword(t *testing.T) {
config := &ClientConfig{
User: "testuser",