Skip to content

feat: add ssh key authentication support #1602

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,34 @@ conn := clickhouse.OpenDB(&clickhouse.Options{
})
```

## SSH Authentication (Native Protocol)

ClickHouse-go supports SSH key-based authentication (requires ClickHouse server with SSH auth enabled).

**Options struct:**
```go
conn, err := clickhouse.Open(&clickhouse.Options{
Addr: []string{"127.0.0.1:9000"},
Auth: clickhouse.Auth{
Database: "default",
Username: "default",
},
SSHKeyFile: "/path/to/id_ed25519",
SSHKeyPassphrase: "your_passphrase_if_any",
})
```

**DSN parameters:**
- `ssh_key_file` — path to SSH private key (RSA, ECDSA, Ed25519)
- `ssh_key_passphrase` — passphrase for encrypted key (optional)

Example DSN:
```
clickhouse://default@127.0.0.1:9000/default?ssh_key_file=/path/to/id_ed25519&ssh_key_passphrase=your_passphrase_if_any
```

See [`examples/ssh_auth.go`](examples/ssh_auth.go) for a complete example.

## Client info


Expand Down
8 changes: 8 additions & 0 deletions clickhouse_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,10 @@ type Options struct {
// Use this instead of Auth.Username and Auth.Password if you're using JWT auth.
GetJWT GetJWTFunc

// SSH authentication
SSHKeyFile string // path to SSH private key file
SSHKeyPassphrase string // passphrase for SSH key (if encrypted)

scheme string
ReadTimeout time.Duration
}
Expand Down Expand Up @@ -327,6 +331,10 @@ func (o *Options) fromDSN(in string) error {
return fmt.Errorf("clickhouse [dsn parse]: http_proxy: %s", err)
}
o.HTTPProxyURL = proxyURL
case "ssh_key_file":
o.SSHKeyFile = params.Get(v)
case "ssh_key_passphrase":
o.SSHKeyPassphrase = params.Get(v)
default:
switch p := strings.ToLower(params.Get(v)); p {
case "true":
Expand Down
56 changes: 56 additions & 0 deletions conn_handshake.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"fmt"
"time"

chssh "github.com/ClickHouse/ch-go/ssh"
"github.com/ClickHouse/clickhouse-go/v2/lib/proto"
)

Expand Down Expand Up @@ -79,6 +80,61 @@ func (c *connect) handshake(auth Auth) error {
c.debugf("[handshake] downgrade client proto")
}
c.debugf("[handshake] <- %s", c.server)

// Handle SSH authentication if configured
if c.opt.SSHKeyFile != "" {
if err := c.performSSHAuthentication(); err != nil {
return err
}
}

return nil
}

func (c *connect) performSSHAuthentication() error {
// Load SSH key
sshKey, err := chssh.LoadPrivateKeyFromFile(c.opt.SSHKeyFile, c.opt.SSHKeyPassphrase)
if err != nil {
return fmt.Errorf("failed to load SSH key: %w", err)
}

// Send SSH challenge request
c.buffer.Reset()
c.buffer.PutByte(proto.ClientSSHChallengeRequest)
if err := c.flush(); err != nil {
return fmt.Errorf("send SSH challenge request: %w", err)
}

// Read SSH challenge response
packet, err := c.reader.ReadByte()
if err != nil {
return fmt.Errorf("read SSH challenge response: %w", err)
}

if packet != proto.ServerSSHChallenge {
return fmt.Errorf("unexpected packet [%d] from server during SSH authentication", packet)
}

// Read challenge string
challenge, err := c.reader.Str()
if err != nil {
return fmt.Errorf("read SSH challenge string: %w", err)
}

// Sign the challenge
signature, err := sshKey.SignString(challenge)
if err != nil {
return fmt.Errorf("sign SSH challenge: %w", err)
}

// Send SSH challenge response
c.buffer.Reset()
c.buffer.PutByte(proto.ClientSSHChallengeResponse)
c.buffer.PutString(signature)
if err := c.flush(); err != nil {
return fmt.Errorf("send SSH challenge response: %w", err)
}

return nil
}

Expand Down
47 changes: 47 additions & 0 deletions conn_handshake_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package clickhouse

import (
"os"
"testing"
)

func TestSSHAuthenticationOptions(t *testing.T) {
t.Run("MissingKeyFile", func(t *testing.T) {
opt := &Options{
SSHKeyFile: "/nonexistent/path/to/key",
}
c := &connect{opt: opt}
err := c.performSSHAuthentication()
if err == nil {
t.Fatal("expected error for missing SSH key file")
}
})

t.Run("InvalidKeyFile", func(t *testing.T) {
f, err := os.CreateTemp("", "invalid_key*")
if err != nil {
t.Fatal(err)
}
defer os.Remove(f.Name())
f.WriteString("not a key")
f.Close()
opt := &Options{
SSHKeyFile: f.Name(),
}
c := &connect{opt: opt}
err = c.performSSHAuthentication()
if err == nil {
t.Fatal("expected error for invalid SSH key file")
}
})

t.Run("WrongPassphrase", func(t *testing.T) {
t.Skip("Needs a real encrypted key for full test")
// Provide a valid encrypted key and wrong passphrase, expect error
})

t.Run("Integration", func(t *testing.T) {
t.Skip("Integration test: requires ClickHouse server with SSH auth enabled and valid key")
// Provide valid key, connect, expect success
})
}
34 changes: 34 additions & 0 deletions examples/ssh_auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package main

import (
"context"
"fmt"
"log"

"github.com/ClickHouse/clickhouse-go/v2"
)

func main() {
// Using Options struct
conn, err := clickhouse.Open(&clickhouse.Options{
Addr: []string{"127.0.0.1:9000"},
Auth: clickhouse.Auth{
Database: "default",
Username: "default",
},
SSHKeyFile: "/path/to/id_ed25519",
SSHKeyPassphrase: "your_passphrase_if_any",
})
if err != nil {
log.Fatalf("failed to open connection: %v", err)
}
if err := conn.Ping(context.Background()); err != nil {
log.Fatalf("failed to ping: %v", err)
}
fmt.Println("SSH authentication succeeded (Options struct)")

// Using DSN
// dsn := "clickhouse://default@127.0.0.1:9000/default?ssh_key_file=/path/to/id_ed25519&ssh_key_passphrase=your_passphrase_if_any"
// conn, err := clickhouse.Open(&clickhouse.Options{})
// ...
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,5 @@ require (
golang.org/x/sys v0.34.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20240318140521-94a12d6c2237 // indirect
)

replace github.com/ClickHouse/ch-go => ../ch-go
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would update it once ClickHouse/ch-go#1075 is merged and a tag is released

6 changes: 2 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8af
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8=
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/ClickHouse/ch-go v0.66.1 h1:LQHFslfVYZsISOY0dnOYOXGkOUvpv376CCm8g7W74A4=
github.com/ClickHouse/ch-go v0.66.1/go.mod h1:NEYcg3aOFv2EmTJfo4m2WF7sHB/YFbLUuIWv9iq76xY=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg=
Expand Down Expand Up @@ -173,8 +171,8 @@ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0 h1:IeMey
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0/go.mod h1:oVdCUtjq9MK9BlS7TtucsQwUcXcymNiEDjgDD2jMtZU=
go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE=
go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E=
go.opentelemetry.io/otel/sdk v1.36.0 h1:b6SYIuLRs88ztox4EyrvRti80uXIFy+Sqzoh9kFULbs=
go.opentelemetry.io/otel/sdk v1.36.0/go.mod h1:+lC+mTgD+MUWfjJubi2vvXWcVxyr9rmlshZni72pXeY=
go.opentelemetry.io/otel/sdk v1.37.0 h1:ItB0QUqnjesGRvNcmAcU0LyvkVyGJ2xftD29bWdDvKI=
go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg=
go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4=
go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=
go.opentelemetry.io/proto/otlp v1.0.0 h1:T0TX0tmXU8a3CbNXzEKGeU5mIVOdf0oykP+u2lIVU/I=
Expand Down
13 changes: 8 additions & 5 deletions lib/proto/const.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,13 @@ const (
)

const (
ClientHello = 0
ClientQuery = 1
ClientData = 2
ClientCancel = 3
ClientPing = 4
ClientHello = 0
ClientQuery = 1
ClientData = 2
ClientCancel = 3
ClientPing = 4
ClientSSHChallengeRequest = 11
ClientSSHChallengeResponse = 12
)

const (
Expand Down Expand Up @@ -80,4 +82,5 @@ const (
ServerReadTaskRequest = 13
ServerProfileEvents = 14
ServerTreeReadTaskRequest = 15
ServerSSHChallenge = 18
)