Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
0c23e7d4bf
|
|||
|
ad7c8b0587
|
|||
|
1625997d8f
|
|||
|
b29246a9c4
|
@@ -0,0 +1,454 @@
|
||||
package starssh
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
sshagent "golang.org/x/crypto/ssh/agent"
|
||||
)
|
||||
|
||||
var requestSSHAgentForwarding = func(session *ssh.Session) error {
|
||||
return sshagent.RequestAgentForwarding(session)
|
||||
}
|
||||
|
||||
const sshAgentChannelType = "auth-agent@openssh.com"
|
||||
|
||||
var routeSSHAgentForwarding = func(client *ssh.Client, timeouts sshAgentTimeouts) (io.Closer, error) {
|
||||
return startSSHAgentForwardProxy(client, timeouts)
|
||||
}
|
||||
|
||||
var probeSSHAgentForwarding = func(timeouts sshAgentTimeouts) error {
|
||||
conn, _, err := dialSSHAgentWithDebug("forward-probe", timeouts)
|
||||
if err != nil {
|
||||
return wrapSSHAgentForwardingUnavailable(err)
|
||||
}
|
||||
if conn == nil {
|
||||
return wrapSSHAgentForwardingUnavailable(errors.New("empty agent connection"))
|
||||
}
|
||||
return conn.Close()
|
||||
}
|
||||
|
||||
var errSSHAgentForwardingDenied = errors.New("ssh-agent forwarding request denied")
|
||||
var errSSHAgentForwardingUnavailable = errors.New("ssh-agent forwarding unavailable")
|
||||
|
||||
type sshAgentForwardProxy struct {
|
||||
stopOnce sync.Once
|
||||
stopCh chan struct{}
|
||||
|
||||
activeMu sync.Mutex
|
||||
active map[*sshAgentForwardBridge]struct{}
|
||||
}
|
||||
|
||||
func (p *sshAgentForwardProxy) Close() error {
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
p.stopOnce.Do(func() {
|
||||
close(p.stopCh)
|
||||
})
|
||||
p.closeActive()
|
||||
return nil
|
||||
}
|
||||
|
||||
type sshAgentForwardBridge struct {
|
||||
proxy *sshAgentForwardProxy
|
||||
channel ssh.Channel
|
||||
conn net.Conn
|
||||
idleTimeout time.Duration
|
||||
|
||||
closeOnce sync.Once
|
||||
signalOnce sync.Once
|
||||
done chan struct{}
|
||||
activity chan struct{}
|
||||
}
|
||||
|
||||
func (s *StarSSH) RequestAgentForwarding(session *ssh.Session) error {
|
||||
if s == nil {
|
||||
return errors.New("ssh client is nil")
|
||||
}
|
||||
if session == nil {
|
||||
return errors.New("ssh session is nil")
|
||||
}
|
||||
if err := s.ensureAgentForwarding(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := requestSSHAgentForwarding(session); err != nil {
|
||||
if isSSHAgentForwardingDeniedError(err) {
|
||||
return fmt.Errorf("%w: %v", errSSHAgentForwardingDenied, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *StarSSH) maybeRequestAgentForwarding(session *ssh.Session) error {
|
||||
if s == nil || !s.LoginInfo.ForwardSSHAgent {
|
||||
return nil
|
||||
}
|
||||
err := s.RequestAgentForwarding(session)
|
||||
if isSSHAgentForwardingDeniedError(err) || isSSHAgentForwardingUnavailableError(err) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *StarSSH) ensureAgentForwarding() error {
|
||||
if s == nil {
|
||||
return errors.New("ssh client is nil")
|
||||
}
|
||||
|
||||
s.agentForwardMu.Lock()
|
||||
defer s.agentForwardMu.Unlock()
|
||||
|
||||
if s.agentForwarder != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
client, err := s.requireSSHClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
timeouts := effectiveSSHAgentTimeouts(s.LoginInfo)
|
||||
if err := probeSSHAgentForwarding(timeouts); err != nil {
|
||||
return wrapSSHAgentForwardingUnavailable(err)
|
||||
}
|
||||
if s.closing.Load() {
|
||||
return errSSHClientClosing
|
||||
}
|
||||
closer, err := routeSSHAgentForwarding(client, timeouts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !s.canAttachAgentForwarder(client) {
|
||||
if closer != nil {
|
||||
_ = closer.Close()
|
||||
}
|
||||
return errSSHClientClosing
|
||||
}
|
||||
s.agentForwarder = closer
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *StarSSH) takeAgentForwarder() io.Closer {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
s.agentForwardMu.Lock()
|
||||
defer s.agentForwardMu.Unlock()
|
||||
|
||||
closer := s.agentForwarder
|
||||
s.agentForwarder = nil
|
||||
return closer
|
||||
}
|
||||
|
||||
func isSSHAgentForwardingDeniedError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, errSSHAgentForwardingDenied) {
|
||||
return true
|
||||
}
|
||||
message := strings.ToLower(err.Error())
|
||||
return strings.Contains(message, "forwarding request denied") ||
|
||||
strings.Contains(message, "agent forwarding disabled")
|
||||
}
|
||||
|
||||
func isSSHAgentForwardingUnavailableError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, errSSHAgentForwardingUnavailable) {
|
||||
return true
|
||||
}
|
||||
message := strings.ToLower(err.Error())
|
||||
return strings.Contains(message, "ssh-agent forwarding unavailable") ||
|
||||
strings.Contains(message, "ssh-agent unavailable")
|
||||
}
|
||||
|
||||
func wrapSSHAgentForwardingUnavailable(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, errSSHAgentForwardingUnavailable) {
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, errSSHAgentUnavailable) {
|
||||
return fmt.Errorf("%w: %w", errSSHAgentForwardingUnavailable, err)
|
||||
}
|
||||
return fmt.Errorf("%w: %v", errSSHAgentForwardingUnavailable, err)
|
||||
}
|
||||
|
||||
func startSSHAgentForwardProxy(client *ssh.Client, timeouts sshAgentTimeouts) (io.Closer, error) {
|
||||
if client == nil {
|
||||
return nil, errors.New("ssh client is nil")
|
||||
}
|
||||
channels := client.HandleChannelOpen(sshAgentChannelType)
|
||||
if channels == nil {
|
||||
return nil, errors.New("agent: already have handler for " + sshAgentChannelType)
|
||||
}
|
||||
|
||||
proxy := &sshAgentForwardProxy{
|
||||
stopCh: make(chan struct{}),
|
||||
active: make(map[*sshAgentForwardBridge]struct{}),
|
||||
}
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-proxy.stopCh:
|
||||
return
|
||||
case ch, ok := <-channels:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
go handleSSHAgentForwardChannel(proxy, ch, timeouts)
|
||||
}
|
||||
}
|
||||
}()
|
||||
return proxy, nil
|
||||
}
|
||||
|
||||
func handleSSHAgentForwardChannel(proxy *sshAgentForwardProxy, ch ssh.NewChannel, timeouts sshAgentTimeouts) {
|
||||
if ch == nil {
|
||||
return
|
||||
}
|
||||
conn, _, err := dialSSHAgentWithDebug("forward-channel", timeouts)
|
||||
if err != nil {
|
||||
_ = ch.Reject(ssh.ConnectionFailed, err.Error())
|
||||
return
|
||||
}
|
||||
if conn == nil {
|
||||
_ = ch.Reject(ssh.ConnectionFailed, "ssh-agent connection unavailable")
|
||||
return
|
||||
}
|
||||
channel, reqs, err := ch.Accept()
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
go ssh.DiscardRequests(reqs)
|
||||
|
||||
bridge := &sshAgentForwardBridge{
|
||||
proxy: proxy,
|
||||
channel: channel,
|
||||
conn: conn,
|
||||
idleTimeout: timeouts.Forward,
|
||||
}
|
||||
if !proxy.registerBridge(bridge) {
|
||||
bridge.close()
|
||||
return
|
||||
}
|
||||
go bridge.run()
|
||||
}
|
||||
|
||||
func proxySSHAgentChannel(channel ssh.Channel, conn net.Conn) {
|
||||
bridge := &sshAgentForwardBridge{
|
||||
channel: channel,
|
||||
conn: conn,
|
||||
}
|
||||
bridge.run()
|
||||
}
|
||||
|
||||
func (b *sshAgentForwardBridge) run() {
|
||||
if b == nil {
|
||||
return
|
||||
}
|
||||
b.ensureSignals()
|
||||
stopWatchdog := b.startIdleWatchdog()
|
||||
defer stopWatchdog()
|
||||
defer b.unregister()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, _ = io.Copy(
|
||||
sshAgentForwardActivityWriter{Writer: b.channel, touch: b.touch},
|
||||
sshAgentForwardActivityReader{Reader: b.conn, touch: b.touch},
|
||||
)
|
||||
b.close()
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, _ = io.Copy(
|
||||
sshAgentForwardActivityWriter{Writer: b.conn, touch: b.touch},
|
||||
sshAgentForwardActivityReader{Reader: b.channel, touch: b.touch},
|
||||
)
|
||||
b.close()
|
||||
}()
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (b *sshAgentForwardBridge) close() {
|
||||
if b == nil {
|
||||
return
|
||||
}
|
||||
b.closeOnce.Do(func() {
|
||||
b.ensureSignals()
|
||||
close(b.done)
|
||||
closeWriter(b.channel)
|
||||
closeWriter(b.conn)
|
||||
if b.channel != nil {
|
||||
_ = b.channel.Close()
|
||||
}
|
||||
if b.conn != nil {
|
||||
_ = b.conn.Close()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (b *sshAgentForwardBridge) ensureSignals() {
|
||||
if b == nil {
|
||||
return
|
||||
}
|
||||
b.signalOnce.Do(func() {
|
||||
b.done = make(chan struct{})
|
||||
b.activity = make(chan struct{}, 1)
|
||||
})
|
||||
}
|
||||
|
||||
func (b *sshAgentForwardBridge) startIdleWatchdog() func() {
|
||||
if b == nil || b.idleTimeout <= 0 {
|
||||
return func() {}
|
||||
}
|
||||
b.ensureSignals()
|
||||
timer := time.NewTimer(b.idleTimeout)
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
defer timer.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-timer.C:
|
||||
b.close()
|
||||
return
|
||||
case <-b.activity:
|
||||
resetTimer(timer, b.idleTimeout)
|
||||
case <-b.done:
|
||||
return
|
||||
case <-stopped:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
return func() {
|
||||
close(stopped)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *sshAgentForwardBridge) touch() {
|
||||
if b == nil || b.idleTimeout <= 0 || b.activity == nil {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case b.activity <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
type sshAgentForwardActivityReader struct {
|
||||
io.Reader
|
||||
touch func()
|
||||
}
|
||||
|
||||
func (r sshAgentForwardActivityReader) Read(p []byte) (int, error) {
|
||||
n, err := r.Reader.Read(p)
|
||||
if n > 0 && r.touch != nil {
|
||||
r.touch()
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
type sshAgentForwardActivityWriter struct {
|
||||
io.Writer
|
||||
touch func()
|
||||
}
|
||||
|
||||
func (w sshAgentForwardActivityWriter) Write(p []byte) (int, error) {
|
||||
n, err := w.Writer.Write(p)
|
||||
if n > 0 && w.touch != nil {
|
||||
w.touch()
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func resetTimer(timer *time.Timer, timeout time.Duration) {
|
||||
if !timer.Stop() {
|
||||
select {
|
||||
case <-timer.C:
|
||||
default:
|
||||
}
|
||||
}
|
||||
timer.Reset(timeout)
|
||||
}
|
||||
|
||||
func (b *sshAgentForwardBridge) unregister() {
|
||||
if b == nil || b.proxy == nil {
|
||||
return
|
||||
}
|
||||
b.proxy.unregisterBridge(b)
|
||||
}
|
||||
|
||||
func (p *sshAgentForwardProxy) registerBridge(bridge *sshAgentForwardBridge) bool {
|
||||
if p == nil || bridge == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
p.activeMu.Lock()
|
||||
defer p.activeMu.Unlock()
|
||||
|
||||
select {
|
||||
case <-p.stopCh:
|
||||
return false
|
||||
default:
|
||||
}
|
||||
if p.active == nil {
|
||||
p.active = make(map[*sshAgentForwardBridge]struct{})
|
||||
}
|
||||
p.active[bridge] = struct{}{}
|
||||
return true
|
||||
}
|
||||
|
||||
func (p *sshAgentForwardProxy) unregisterBridge(bridge *sshAgentForwardBridge) {
|
||||
if p == nil || bridge == nil {
|
||||
return
|
||||
}
|
||||
|
||||
p.activeMu.Lock()
|
||||
defer p.activeMu.Unlock()
|
||||
|
||||
delete(p.active, bridge)
|
||||
}
|
||||
|
||||
func (p *sshAgentForwardProxy) closeActive() {
|
||||
if p == nil {
|
||||
return
|
||||
}
|
||||
|
||||
p.activeMu.Lock()
|
||||
active := make([]*sshAgentForwardBridge, 0, len(p.active))
|
||||
for bridge := range p.active {
|
||||
active = append(active, bridge)
|
||||
}
|
||||
p.active = make(map[*sshAgentForwardBridge]struct{})
|
||||
p.activeMu.Unlock()
|
||||
|
||||
for _, bridge := range active {
|
||||
bridge.close()
|
||||
}
|
||||
}
|
||||
|
||||
func closeWriter(value any) {
|
||||
type closeWriter interface {
|
||||
CloseWrite() error
|
||||
}
|
||||
if cw, ok := value.(closeWriter); ok {
|
||||
_ = cw.CloseWrite()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,665 @@
|
||||
package starssh
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type testCloser struct {
|
||||
closed atomic.Int32
|
||||
}
|
||||
|
||||
func (c *testCloser) Close() error {
|
||||
c.closed.Add(1)
|
||||
return nil
|
||||
}
|
||||
|
||||
type trackedConn struct {
|
||||
net.Conn
|
||||
closed atomic.Int32
|
||||
}
|
||||
|
||||
func (c *trackedConn) Close() error {
|
||||
c.closed.Add(1)
|
||||
if c.Conn == nil {
|
||||
return nil
|
||||
}
|
||||
return c.Conn.Close()
|
||||
}
|
||||
|
||||
type testSSHChannel struct {
|
||||
readFunc func([]byte) (int, error)
|
||||
|
||||
stderr bytes.Buffer
|
||||
closed atomic.Int32
|
||||
closeOnce sync.Once
|
||||
closeCh chan struct{}
|
||||
}
|
||||
|
||||
type testNewChannel struct {
|
||||
channel ssh.Channel
|
||||
accepted atomic.Bool
|
||||
rejected atomic.Bool
|
||||
}
|
||||
|
||||
func (c *testNewChannel) Accept() (ssh.Channel, <-chan *ssh.Request, error) {
|
||||
c.accepted.Store(true)
|
||||
requests := make(chan *ssh.Request)
|
||||
close(requests)
|
||||
return c.channel, requests, nil
|
||||
}
|
||||
|
||||
func (c *testNewChannel) Reject(reason ssh.RejectionReason, message string) error {
|
||||
c.rejected.Store(true)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *testNewChannel) ChannelType() string {
|
||||
return sshAgentChannelType
|
||||
}
|
||||
|
||||
func (c *testNewChannel) ExtraData() []byte {
|
||||
return nil
|
||||
}
|
||||
|
||||
func newTestSSHChannel(readFunc func([]byte) (int, error)) *testSSHChannel {
|
||||
return &testSSHChannel{
|
||||
readFunc: readFunc,
|
||||
closeCh: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func newBlockingTestSSHChannel() *testSSHChannel {
|
||||
ch := newTestSSHChannel(nil)
|
||||
ch.readFunc = func(p []byte) (int, error) {
|
||||
<-ch.closeCh
|
||||
return 0, io.EOF
|
||||
}
|
||||
return ch
|
||||
}
|
||||
|
||||
func (c *testSSHChannel) Read(p []byte) (int, error) {
|
||||
if c == nil {
|
||||
return 0, io.EOF
|
||||
}
|
||||
if c.readFunc != nil {
|
||||
return c.readFunc(p)
|
||||
}
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
func (c *testSSHChannel) Write(p []byte) (int, error) {
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (c *testSSHChannel) Close() error {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
c.closeOnce.Do(func() {
|
||||
c.closed.Add(1)
|
||||
close(c.closeCh)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *testSSHChannel) CloseWrite() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *testSSHChannel) SendRequest(name string, wantReply bool, payload []byte) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (c *testSSHChannel) Stderr() io.ReadWriter {
|
||||
return &c.stderr
|
||||
}
|
||||
|
||||
func TestNewExecSessionEnablesAgentForwardingOnce(t *testing.T) {
|
||||
oldNewSSHSession := newSSHSession
|
||||
oldProbeSSHAgentForwarding := probeSSHAgentForwarding
|
||||
oldRouteSSHAgentForwarding := routeSSHAgentForwarding
|
||||
oldRequestSSHAgentForwarding := requestSSHAgentForwarding
|
||||
oldCloseSSHClient := closeSSHClient
|
||||
t.Cleanup(func() {
|
||||
newSSHSession = oldNewSSHSession
|
||||
probeSSHAgentForwarding = oldProbeSSHAgentForwarding
|
||||
routeSSHAgentForwarding = oldRouteSSHAgentForwarding
|
||||
requestSSHAgentForwarding = oldRequestSSHAgentForwarding
|
||||
closeSSHClient = oldCloseSSHClient
|
||||
})
|
||||
|
||||
baseClient := &ssh.Client{}
|
||||
star := &StarSSH{
|
||||
LoginInfo: LoginInput{
|
||||
ForwardSSHAgent: true,
|
||||
Timeout: time.Second,
|
||||
SSHAgentTimeout: 3 * time.Second,
|
||||
SSHAgentForwardTimeout: 4 * time.Second,
|
||||
},
|
||||
}
|
||||
star.setTransport(baseClient, nil)
|
||||
|
||||
newSSHSession = func(client *ssh.Client) (*ssh.Session, error) {
|
||||
if client != baseClient {
|
||||
t.Fatalf("unexpected ssh client %p", client)
|
||||
}
|
||||
return &ssh.Session{}, nil
|
||||
}
|
||||
|
||||
var probeCalls atomic.Int32
|
||||
closer := &testCloser{}
|
||||
probeSSHAgentForwarding = func(timeouts sshAgentTimeouts) error {
|
||||
probeCalls.Add(1)
|
||||
if timeouts.Dial != time.Second {
|
||||
t.Fatalf("unexpected forwarding dial timeout: %v", timeouts.Dial)
|
||||
}
|
||||
if timeouts.Operation != 3*time.Second {
|
||||
t.Fatalf("unexpected forwarding operation timeout: %v", timeouts.Operation)
|
||||
}
|
||||
if timeouts.Forward != 4*time.Second {
|
||||
t.Fatalf("unexpected forwarding idle timeout: %v", timeouts.Forward)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var routeCalls atomic.Int32
|
||||
routeSSHAgentForwarding = func(client *ssh.Client, timeouts sshAgentTimeouts) (io.Closer, error) {
|
||||
routeCalls.Add(1)
|
||||
if client != baseClient {
|
||||
t.Fatalf("unexpected routed client %p", client)
|
||||
}
|
||||
if timeouts.Dial != time.Second {
|
||||
t.Fatalf("unexpected routed dial timeout: %v", timeouts.Dial)
|
||||
}
|
||||
if timeouts.Operation != 3*time.Second {
|
||||
t.Fatalf("unexpected routed operation timeout: %v", timeouts.Operation)
|
||||
}
|
||||
if timeouts.Forward != 4*time.Second {
|
||||
t.Fatalf("unexpected routed idle timeout: %v", timeouts.Forward)
|
||||
}
|
||||
return closer, nil
|
||||
}
|
||||
|
||||
var requestCalls atomic.Int32
|
||||
requestSSHAgentForwarding = func(session *ssh.Session) error {
|
||||
requestCalls.Add(1)
|
||||
if session == nil {
|
||||
t.Fatal("expected non-nil ssh session")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, err := star.NewExecSession(); err != nil {
|
||||
t.Fatalf("first exec session: %v", err)
|
||||
}
|
||||
if _, err := star.NewExecSession(); err != nil {
|
||||
t.Fatalf("second exec session: %v", err)
|
||||
}
|
||||
|
||||
if probeCalls.Load() != 1 {
|
||||
t.Fatalf("expected one agent probe, got %d", probeCalls.Load())
|
||||
}
|
||||
if routeCalls.Load() != 1 {
|
||||
t.Fatalf("expected one agent route registration, got %d", routeCalls.Load())
|
||||
}
|
||||
if requestCalls.Load() != 2 {
|
||||
t.Fatalf("expected agent forwarding request on each session, got %d", requestCalls.Load())
|
||||
}
|
||||
|
||||
closeSSHClient = func(client sshClientRequester) error { return nil }
|
||||
if err := star.Close(); err != nil {
|
||||
t.Fatalf("close starssh: %v", err)
|
||||
}
|
||||
if closer.closed.Load() != 1 {
|
||||
t.Fatalf("expected forwarded agent closer to run once, got %d", closer.closed.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewPTYSessionEnablesAgentForwardingWhenConfigured(t *testing.T) {
|
||||
oldNewSSHSession := newSSHSession
|
||||
oldRequestSessionPTY := requestSessionPTY
|
||||
oldProbeSSHAgentForwarding := probeSSHAgentForwarding
|
||||
oldRouteSSHAgentForwarding := routeSSHAgentForwarding
|
||||
oldRequestSSHAgentForwarding := requestSSHAgentForwarding
|
||||
t.Cleanup(func() {
|
||||
newSSHSession = oldNewSSHSession
|
||||
requestSessionPTY = oldRequestSessionPTY
|
||||
probeSSHAgentForwarding = oldProbeSSHAgentForwarding
|
||||
routeSSHAgentForwarding = oldRouteSSHAgentForwarding
|
||||
requestSSHAgentForwarding = oldRequestSSHAgentForwarding
|
||||
})
|
||||
|
||||
star := &StarSSH{
|
||||
LoginInfo: LoginInput{
|
||||
ForwardSSHAgent: true,
|
||||
},
|
||||
}
|
||||
star.setTransport(&ssh.Client{}, nil)
|
||||
|
||||
newSSHSession = func(client *ssh.Client) (*ssh.Session, error) {
|
||||
return &ssh.Session{}, nil
|
||||
}
|
||||
|
||||
var ptyCalls atomic.Int32
|
||||
requestSessionPTY = func(session *ssh.Session, config TerminalConfig) error {
|
||||
ptyCalls.Add(1)
|
||||
return nil
|
||||
}
|
||||
|
||||
probeSSHAgentForwarding = func(timeouts sshAgentTimeouts) error {
|
||||
return nil
|
||||
}
|
||||
routeSSHAgentForwarding = func(client *ssh.Client, timeouts sshAgentTimeouts) (io.Closer, error) {
|
||||
return &testCloser{}, nil
|
||||
}
|
||||
|
||||
var requestCalls atomic.Int32
|
||||
requestSSHAgentForwarding = func(session *ssh.Session) error {
|
||||
requestCalls.Add(1)
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, err := star.NewPTYSession(nil); err != nil {
|
||||
t.Fatalf("new pty session: %v", err)
|
||||
}
|
||||
if ptyCalls.Load() != 1 {
|
||||
t.Fatalf("expected one PTY request, got %d", ptyCalls.Load())
|
||||
}
|
||||
if requestCalls.Load() != 1 {
|
||||
t.Fatalf("expected one agent forwarding request, got %d", requestCalls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewExecSessionSkipsAgentForwardingWhenDisabled(t *testing.T) {
|
||||
oldNewSSHSession := newSSHSession
|
||||
oldProbeSSHAgentForwarding := probeSSHAgentForwarding
|
||||
oldRequestSSHAgentForwarding := requestSSHAgentForwarding
|
||||
t.Cleanup(func() {
|
||||
newSSHSession = oldNewSSHSession
|
||||
probeSSHAgentForwarding = oldProbeSSHAgentForwarding
|
||||
requestSSHAgentForwarding = oldRequestSSHAgentForwarding
|
||||
})
|
||||
|
||||
star := &StarSSH{}
|
||||
star.setTransport(&ssh.Client{}, nil)
|
||||
|
||||
newSSHSession = func(client *ssh.Client) (*ssh.Session, error) {
|
||||
return &ssh.Session{}, nil
|
||||
}
|
||||
probeSSHAgentForwarding = func(timeouts sshAgentTimeouts) error {
|
||||
t.Fatal("agent forwarding probe should not run when disabled")
|
||||
return nil
|
||||
}
|
||||
requestSSHAgentForwarding = func(session *ssh.Session) error {
|
||||
t.Fatal("agent forwarding should not be requested when disabled")
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, err := star.NewExecSession(); err != nil {
|
||||
t.Fatalf("new exec session without forwarding: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestAgentForwardingReturnsUnavailableError(t *testing.T) {
|
||||
oldProbeSSHAgentForwarding := probeSSHAgentForwarding
|
||||
oldRequestSSHAgentForwarding := requestSSHAgentForwarding
|
||||
t.Cleanup(func() {
|
||||
probeSSHAgentForwarding = oldProbeSSHAgentForwarding
|
||||
requestSSHAgentForwarding = oldRequestSSHAgentForwarding
|
||||
})
|
||||
|
||||
star := &StarSSH{}
|
||||
star.setTransport(&ssh.Client{}, nil)
|
||||
|
||||
probeSSHAgentForwarding = func(timeouts sshAgentTimeouts) error {
|
||||
return errors.New("ssh-agent forwarding unavailable: ssh-agent unavailable")
|
||||
}
|
||||
requestSSHAgentForwarding = func(session *ssh.Session) error {
|
||||
t.Fatal("session request should not run when agent forwarder init fails")
|
||||
return nil
|
||||
}
|
||||
|
||||
err := star.RequestAgentForwarding(&ssh.Session{})
|
||||
if err == nil {
|
||||
t.Fatal("expected agent forwarding init error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestAgentForwardingWrapsSetupErrorAsUnavailable(t *testing.T) {
|
||||
oldProbeSSHAgentForwarding := probeSSHAgentForwarding
|
||||
t.Cleanup(func() {
|
||||
probeSSHAgentForwarding = oldProbeSSHAgentForwarding
|
||||
})
|
||||
|
||||
star := &StarSSH{}
|
||||
star.setTransport(&ssh.Client{}, nil)
|
||||
|
||||
probeSSHAgentForwarding = func(timeouts sshAgentTimeouts) error {
|
||||
return errors.New("dial unix /tmp/ssh-broken.sock: connect: permission denied")
|
||||
}
|
||||
|
||||
err := star.RequestAgentForwarding(&ssh.Session{})
|
||||
if !isSSHAgentForwardingUnavailableError(err) {
|
||||
t.Fatalf("expected unavailable error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestAgentForwardingReturnsDeniedError(t *testing.T) {
|
||||
oldProbeSSHAgentForwarding := probeSSHAgentForwarding
|
||||
oldRouteSSHAgentForwarding := routeSSHAgentForwarding
|
||||
oldRequestSSHAgentForwarding := requestSSHAgentForwarding
|
||||
t.Cleanup(func() {
|
||||
probeSSHAgentForwarding = oldProbeSSHAgentForwarding
|
||||
routeSSHAgentForwarding = oldRouteSSHAgentForwarding
|
||||
requestSSHAgentForwarding = oldRequestSSHAgentForwarding
|
||||
})
|
||||
|
||||
star := &StarSSH{}
|
||||
star.setTransport(&ssh.Client{}, nil)
|
||||
|
||||
probeSSHAgentForwarding = func(timeouts sshAgentTimeouts) error {
|
||||
return nil
|
||||
}
|
||||
routeSSHAgentForwarding = func(client *ssh.Client, timeouts sshAgentTimeouts) (io.Closer, error) {
|
||||
return &testCloser{}, nil
|
||||
}
|
||||
requestSSHAgentForwarding = func(session *ssh.Session) error {
|
||||
return errors.New("forwarding request denied")
|
||||
}
|
||||
|
||||
err := star.RequestAgentForwarding(&ssh.Session{})
|
||||
if !isSSHAgentForwardingDeniedError(err) {
|
||||
t.Fatalf("expected forwarding denied error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewExecSessionIgnoresAgentForwardingDenied(t *testing.T) {
|
||||
oldNewSSHSession := newSSHSession
|
||||
oldProbeSSHAgentForwarding := probeSSHAgentForwarding
|
||||
oldRouteSSHAgentForwarding := routeSSHAgentForwarding
|
||||
oldRequestSSHAgentForwarding := requestSSHAgentForwarding
|
||||
t.Cleanup(func() {
|
||||
newSSHSession = oldNewSSHSession
|
||||
probeSSHAgentForwarding = oldProbeSSHAgentForwarding
|
||||
routeSSHAgentForwarding = oldRouteSSHAgentForwarding
|
||||
requestSSHAgentForwarding = oldRequestSSHAgentForwarding
|
||||
})
|
||||
|
||||
star := &StarSSH{
|
||||
LoginInfo: LoginInput{
|
||||
ForwardSSHAgent: true,
|
||||
},
|
||||
}
|
||||
star.setTransport(&ssh.Client{}, nil)
|
||||
|
||||
newSSHSession = func(client *ssh.Client) (*ssh.Session, error) {
|
||||
return &ssh.Session{}, nil
|
||||
}
|
||||
probeSSHAgentForwarding = func(timeouts sshAgentTimeouts) error {
|
||||
return nil
|
||||
}
|
||||
routeSSHAgentForwarding = func(client *ssh.Client, timeouts sshAgentTimeouts) (io.Closer, error) {
|
||||
return &testCloser{}, nil
|
||||
}
|
||||
requestSSHAgentForwarding = func(session *ssh.Session) error {
|
||||
return errors.New("forwarding request denied")
|
||||
}
|
||||
|
||||
if _, err := star.NewExecSession(); err != nil {
|
||||
t.Fatalf("new exec session should ignore denied agent forwarding: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewExecSessionIgnoresAgentForwardingUnavailable(t *testing.T) {
|
||||
oldNewSSHSession := newSSHSession
|
||||
oldProbeSSHAgentForwarding := probeSSHAgentForwarding
|
||||
t.Cleanup(func() {
|
||||
newSSHSession = oldNewSSHSession
|
||||
probeSSHAgentForwarding = oldProbeSSHAgentForwarding
|
||||
})
|
||||
|
||||
star := &StarSSH{
|
||||
LoginInfo: LoginInput{
|
||||
ForwardSSHAgent: true,
|
||||
},
|
||||
}
|
||||
star.setTransport(&ssh.Client{}, nil)
|
||||
|
||||
newSSHSession = func(client *ssh.Client) (*ssh.Session, error) {
|
||||
return &ssh.Session{}, nil
|
||||
}
|
||||
probeSSHAgentForwarding = func(timeouts sshAgentTimeouts) error {
|
||||
return errors.New("ssh-agent forwarding unavailable: ssh-agent unavailable")
|
||||
}
|
||||
|
||||
if _, err := star.NewExecSession(); err != nil {
|
||||
t.Fatalf("new exec session should ignore unavailable agent forwarding: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewExecSessionIgnoresAgentForwardingSetupError(t *testing.T) {
|
||||
oldNewSSHSession := newSSHSession
|
||||
oldProbeSSHAgentForwarding := probeSSHAgentForwarding
|
||||
t.Cleanup(func() {
|
||||
newSSHSession = oldNewSSHSession
|
||||
probeSSHAgentForwarding = oldProbeSSHAgentForwarding
|
||||
})
|
||||
|
||||
star := &StarSSH{
|
||||
LoginInfo: LoginInput{
|
||||
ForwardSSHAgent: true,
|
||||
},
|
||||
}
|
||||
star.setTransport(&ssh.Client{}, nil)
|
||||
|
||||
newSSHSession = func(client *ssh.Client) (*ssh.Session, error) {
|
||||
return &ssh.Session{}, nil
|
||||
}
|
||||
probeSSHAgentForwarding = func(timeouts sshAgentTimeouts) error {
|
||||
return errors.New("dial unix /tmp/ssh-broken.sock: connect: connection refused")
|
||||
}
|
||||
|
||||
if _, err := star.NewExecSession(); err != nil {
|
||||
t.Fatalf("new exec session should ignore agent setup error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureAgentForwardingClosesNewForwarderWhenCloseStarts(t *testing.T) {
|
||||
oldProbeSSHAgentForwarding := probeSSHAgentForwarding
|
||||
oldRouteSSHAgentForwarding := routeSSHAgentForwarding
|
||||
oldCloseSSHClient := closeSSHClient
|
||||
t.Cleanup(func() {
|
||||
probeSSHAgentForwarding = oldProbeSSHAgentForwarding
|
||||
routeSSHAgentForwarding = oldRouteSSHAgentForwarding
|
||||
closeSSHClient = oldCloseSSHClient
|
||||
})
|
||||
|
||||
star := &StarSSH{
|
||||
LoginInfo: LoginInput{
|
||||
ForwardSSHAgent: true,
|
||||
},
|
||||
}
|
||||
star.setTransport(&ssh.Client{}, nil)
|
||||
|
||||
started := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
closer := &testCloser{}
|
||||
probeSSHAgentForwarding = func(timeouts sshAgentTimeouts) error {
|
||||
return nil
|
||||
}
|
||||
routeSSHAgentForwarding = func(client *ssh.Client, timeouts sshAgentTimeouts) (io.Closer, error) {
|
||||
close(started)
|
||||
<-release
|
||||
return closer, nil
|
||||
}
|
||||
closeSSHClient = func(client sshClientRequester) error { return nil }
|
||||
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
errCh <- star.ensureAgentForwarding()
|
||||
}()
|
||||
|
||||
<-started
|
||||
closeDone := make(chan struct{})
|
||||
go func() {
|
||||
_ = star.Close()
|
||||
close(closeDone)
|
||||
}()
|
||||
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for !star.closing.Load() {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("close did not enter closing state in time")
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
|
||||
close(release)
|
||||
|
||||
err := <-errCh
|
||||
if !errors.Is(err, errSSHClientClosing) {
|
||||
t.Fatalf("expected closing error, got %v", err)
|
||||
}
|
||||
<-closeDone
|
||||
|
||||
if closer.closed.Load() != 1 {
|
||||
t.Fatalf("expected new forwarder closer to be closed once, got %d", closer.closed.Load())
|
||||
}
|
||||
if got := star.takeAgentForwarder(); got != nil {
|
||||
t.Fatal("expected no leaked agent forwarder after close race")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxySSHAgentChannelClosesBlockedAgentConnWhenRemoteChannelEnds(t *testing.T) {
|
||||
agentConn, peerConn := net.Pipe()
|
||||
defer peerConn.Close()
|
||||
|
||||
tracked := &trackedConn{Conn: agentConn}
|
||||
channel := newTestSSHChannel(func(p []byte) (int, error) {
|
||||
return 0, io.EOF
|
||||
})
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
proxySSHAgentChannel(channel, tracked)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("proxySSHAgentChannel did not exit after remote EOF")
|
||||
}
|
||||
|
||||
if tracked.closed.Load() == 0 {
|
||||
t.Fatal("expected local agent connection to be closed")
|
||||
}
|
||||
if channel.closed.Load() == 0 {
|
||||
t.Fatal("expected ssh channel to be closed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHAgentForwardProxyCloseClosesActiveBridges(t *testing.T) {
|
||||
agentConn, peerConn := net.Pipe()
|
||||
defer peerConn.Close()
|
||||
|
||||
tracked := &trackedConn{Conn: agentConn}
|
||||
channel := newBlockingTestSSHChannel()
|
||||
proxy := &sshAgentForwardProxy{
|
||||
stopCh: make(chan struct{}),
|
||||
active: make(map[*sshAgentForwardBridge]struct{}),
|
||||
}
|
||||
bridge := &sshAgentForwardBridge{
|
||||
proxy: proxy,
|
||||
channel: channel,
|
||||
conn: tracked,
|
||||
}
|
||||
if !proxy.registerBridge(bridge) {
|
||||
t.Fatal("expected bridge registration to succeed")
|
||||
}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
bridge.run()
|
||||
close(done)
|
||||
}()
|
||||
|
||||
if err := proxy.Close(); err != nil {
|
||||
t.Fatalf("close proxy: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("bridge did not exit after proxy close")
|
||||
}
|
||||
|
||||
if tracked.closed.Load() == 0 {
|
||||
t.Fatal("expected proxy close to close local agent connection")
|
||||
}
|
||||
if channel.closed.Load() == 0 {
|
||||
t.Fatal("expected proxy close to close ssh channel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleSSHAgentForwardChannelUsesForwardTimeout(t *testing.T) {
|
||||
oldDialResolvedSSHAgent := dialResolvedSSHAgentFunc
|
||||
t.Cleanup(func() {
|
||||
dialResolvedSSHAgentFunc = oldDialResolvedSSHAgent
|
||||
})
|
||||
|
||||
agentConn, peerConn := net.Pipe()
|
||||
defer peerConn.Close()
|
||||
tracked := &trackedConn{Conn: agentConn}
|
||||
dialResolvedSSHAgentFunc = func(resolved resolvedSSHAgentEndpoint, timeout time.Duration) (net.Conn, error) {
|
||||
return tracked, nil
|
||||
}
|
||||
|
||||
channel := newBlockingTestSSHChannel()
|
||||
newChannel := &testNewChannel{
|
||||
channel: channel,
|
||||
}
|
||||
proxy := &sshAgentForwardProxy{
|
||||
stopCh: make(chan struct{}),
|
||||
active: make(map[*sshAgentForwardBridge]struct{}),
|
||||
}
|
||||
handleSSHAgentForwardChannel(proxy, newChannel, sshAgentTimeouts{
|
||||
Endpoint: "/tmp/agent.sock",
|
||||
Forward: 20 * time.Millisecond,
|
||||
})
|
||||
|
||||
if !newChannel.accepted.Load() {
|
||||
t.Fatal("expected channel to be accepted")
|
||||
}
|
||||
|
||||
waitUntil(t, time.Second, func() bool {
|
||||
return tracked.closed.Load() > 0 && channel.closed.Load() > 0
|
||||
}, "forwarded agent bridge did not close both sides after idle timeout")
|
||||
|
||||
waitUntil(t, time.Second, func() bool {
|
||||
proxy.activeMu.Lock()
|
||||
defer proxy.activeMu.Unlock()
|
||||
return len(proxy.active) == 0
|
||||
}, "forwarded agent bridge did not unregister after idle timeout")
|
||||
}
|
||||
|
||||
func waitUntil(t *testing.T, timeout time.Duration, condition func() bool, message string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
if condition() {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
t.Fatal(message)
|
||||
}
|
||||
+282
-24
@@ -3,21 +3,39 @@ package starssh
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type ForwardRequest struct {
|
||||
// Keep the exported shape compatible with older positional literals:
|
||||
// ForwardRequest{listenAddr, targetAddr, dialContext}.
|
||||
//
|
||||
// Non-default networks can be encoded with an explicit scheme-like prefix:
|
||||
// "tcp4://127.0.0.1:22", "tcp6://[::1]:22", "unix:///tmp/socket".
|
||||
// Bare values default to the "tcp" network.
|
||||
ListenAddr string
|
||||
TargetAddr string
|
||||
DialContext DialContextFunc
|
||||
}
|
||||
|
||||
type normalizedForwardRequest struct {
|
||||
ListenNetwork string
|
||||
ListenAddr string
|
||||
TargetNetwork string
|
||||
TargetAddr string
|
||||
DialContext DialContextFunc
|
||||
}
|
||||
|
||||
type DynamicForwardRequest struct {
|
||||
ListenAddr string
|
||||
}
|
||||
@@ -41,10 +59,16 @@ type PortForwarder struct {
|
||||
cleanupFns []func() error
|
||||
}
|
||||
|
||||
const unixForwardProbeTimeout = 200 * time.Millisecond
|
||||
|
||||
var dialSSHClient = func(ctx context.Context, client *ssh.Client, network, address string) (net.Conn, error) {
|
||||
return client.Dial(network, address)
|
||||
}
|
||||
|
||||
var listenSSHClient = func(client *ssh.Client, network, address string) (net.Listener, error) {
|
||||
return client.Listen(network, address)
|
||||
}
|
||||
|
||||
var newDetachedForwardClient = func(ctx context.Context, input LoginInput) (*StarSSH, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
@@ -64,6 +88,90 @@ func (s *StarSSH) DialTCPContextCloseOnCancel(ctx context.Context, network strin
|
||||
return s.dialTCPContext(ctx, network, address, s.Close)
|
||||
}
|
||||
|
||||
func (s *StarSSH) StartLocalTCPForward(listenAddr string, targetAddr string) (*PortForwarder, error) {
|
||||
return s.StartLocalForward(ForwardRequest{
|
||||
ListenAddr: listenAddr,
|
||||
TargetAddr: targetAddr,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *StarSSH) StartLocalTCPForwardDetached(listenAddr string, targetAddr string) (*PortForwarder, error) {
|
||||
return s.StartLocalForwardDetached(ForwardRequest{
|
||||
ListenAddr: listenAddr,
|
||||
TargetAddr: targetAddr,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *StarSSH) StartLocalTCPToUnixForward(listenAddr string, targetPath string) (*PortForwarder, error) {
|
||||
return s.StartLocalForward(ForwardRequest{
|
||||
ListenAddr: listenAddr,
|
||||
TargetAddr: forwardEndpoint("unix", targetPath),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *StarSSH) StartLocalTCPToUnixForwardDetached(listenAddr string, targetPath string) (*PortForwarder, error) {
|
||||
return s.StartLocalForwardDetached(ForwardRequest{
|
||||
ListenAddr: listenAddr,
|
||||
TargetAddr: forwardEndpoint("unix", targetPath),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *StarSSH) StartLocalUnixForward(listenPath string, targetAddr string) (*PortForwarder, error) {
|
||||
return s.StartLocalForward(ForwardRequest{
|
||||
ListenAddr: forwardEndpoint("unix", listenPath),
|
||||
TargetAddr: targetAddr,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *StarSSH) StartLocalUnixForwardDetached(listenPath string, targetAddr string) (*PortForwarder, error) {
|
||||
return s.StartLocalForwardDetached(ForwardRequest{
|
||||
ListenAddr: forwardEndpoint("unix", listenPath),
|
||||
TargetAddr: targetAddr,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *StarSSH) StartLocalUnixToUnixForward(listenPath string, targetPath string) (*PortForwarder, error) {
|
||||
return s.StartLocalForward(ForwardRequest{
|
||||
ListenAddr: forwardEndpoint("unix", listenPath),
|
||||
TargetAddr: forwardEndpoint("unix", targetPath),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *StarSSH) StartLocalUnixToUnixForwardDetached(listenPath string, targetPath string) (*PortForwarder, error) {
|
||||
return s.StartLocalForwardDetached(ForwardRequest{
|
||||
ListenAddr: forwardEndpoint("unix", listenPath),
|
||||
TargetAddr: forwardEndpoint("unix", targetPath),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *StarSSH) StartRemoteTCPForward(listenAddr string, targetAddr string) (*PortForwarder, error) {
|
||||
return s.StartRemoteForward(ForwardRequest{
|
||||
ListenAddr: listenAddr,
|
||||
TargetAddr: targetAddr,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *StarSSH) StartRemoteTCPToUnixForward(listenAddr string, targetPath string) (*PortForwarder, error) {
|
||||
return s.StartRemoteForward(ForwardRequest{
|
||||
ListenAddr: listenAddr,
|
||||
TargetAddr: forwardEndpoint("unix", targetPath),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *StarSSH) StartRemoteUnixForward(listenPath string, targetAddr string) (*PortForwarder, error) {
|
||||
return s.StartRemoteForward(ForwardRequest{
|
||||
ListenAddr: forwardEndpoint("unix", listenPath),
|
||||
TargetAddr: targetAddr,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *StarSSH) StartRemoteUnixToUnixForward(listenPath string, targetPath string) (*PortForwarder, error) {
|
||||
return s.StartRemoteForward(ForwardRequest{
|
||||
ListenAddr: forwardEndpoint("unix", listenPath),
|
||||
TargetAddr: forwardEndpoint("unix", targetPath),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *StarSSH) dialTCPContext(ctx context.Context, network string, address string, onCancel func() error) (net.Conn, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
@@ -136,21 +244,22 @@ func (s *StarSSH) StartLocalForward(req ForwardRequest) (*PortForwarder, error)
|
||||
if _, err := s.requireSSHClient(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(req.ListenAddr) == "" {
|
||||
normalizedReq, err := normalizeForwardRequest(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(normalizedReq.ListenAddr) == "" {
|
||||
return nil, errors.New("local forward listen address is empty")
|
||||
}
|
||||
if strings.TrimSpace(req.TargetAddr) == "" {
|
||||
return nil, errors.New("local forward target address is empty")
|
||||
}
|
||||
|
||||
listener, err := net.Listen("tcp", req.ListenAddr)
|
||||
listener, cleanup, err := prepareLocalForwardListener(normalizedReq.ListenNetwork, normalizedReq.ListenAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
forwarder := newPortForwarder(listener)
|
||||
forwarder.addCleanup(cleanup)
|
||||
forwarder.serve(func(ctx context.Context) (net.Conn, error) {
|
||||
return s.DialTCPContext(ctx, "tcp", req.TargetAddr)
|
||||
return s.DialTCPContext(ctx, normalizedReq.TargetNetwork, normalizedReq.TargetAddr)
|
||||
})
|
||||
return forwarder, nil
|
||||
}
|
||||
@@ -159,14 +268,12 @@ func (s *StarSSH) StartLocalForwardDetached(req ForwardRequest) (*PortForwarder,
|
||||
if _, err := s.requireSSHClient(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(req.ListenAddr) == "" {
|
||||
return nil, errors.New("local forward listen address is empty")
|
||||
}
|
||||
if strings.TrimSpace(req.TargetAddr) == "" {
|
||||
return nil, errors.New("local forward target address is empty")
|
||||
normalizedReq, err := normalizeForwardRequest(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
listener, err := net.Listen("tcp", req.ListenAddr)
|
||||
listener, cleanup, err := prepareLocalForwardListener(normalizedReq.ListenNetwork, normalizedReq.ListenAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -174,15 +281,19 @@ func (s *StarSSH) StartLocalForwardDetached(req ForwardRequest) (*PortForwarder,
|
||||
forwardClient, err := s.newForwardDialClient(context.Background())
|
||||
if err != nil {
|
||||
_ = listener.Close()
|
||||
if cleanup != nil {
|
||||
_ = cleanup()
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
forwarder := newPortForwarder(listener)
|
||||
forwarder.addCleanup(cleanup)
|
||||
forwarder.addCleanup(func() error {
|
||||
return normalizeAlreadyClosedError(forwardClient.Close())
|
||||
})
|
||||
forwarder.serve(func(ctx context.Context) (net.Conn, error) {
|
||||
return forwardClient.DialTCPContext(ctx, "tcp", req.TargetAddr)
|
||||
return forwardClient.DialTCPContext(ctx, normalizedReq.TargetNetwork, normalizedReq.TargetAddr)
|
||||
})
|
||||
return forwarder, nil
|
||||
}
|
||||
@@ -192,19 +303,17 @@ func (s *StarSSH) StartRemoteForward(req ForwardRequest) (*PortForwarder, error)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(req.ListenAddr) == "" {
|
||||
return nil, errors.New("remote forward listen address is empty")
|
||||
}
|
||||
if strings.TrimSpace(req.TargetAddr) == "" {
|
||||
return nil, errors.New("remote forward target address is empty")
|
||||
}
|
||||
|
||||
listener, err := client.Listen("tcp", req.ListenAddr)
|
||||
normalizedReq, err := normalizeForwardRequest(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dialContext := req.DialContext
|
||||
listener, err := listenSSHClient(client, normalizedReq.ListenNetwork, normalizedReq.ListenAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dialContext := normalizedReq.DialContext
|
||||
if dialContext == nil {
|
||||
dialer := &net.Dialer{
|
||||
Timeout: defaultLoginTimeout,
|
||||
@@ -214,7 +323,7 @@ func (s *StarSSH) StartRemoteForward(req ForwardRequest) (*PortForwarder, error)
|
||||
|
||||
forwarder := newPortForwarder(listener)
|
||||
forwarder.serve(func(ctx context.Context) (net.Conn, error) {
|
||||
return dialContext(ctx, "tcp", req.TargetAddr)
|
||||
return dialContext(ctx, normalizedReq.TargetNetwork, normalizedReq.TargetAddr)
|
||||
})
|
||||
return forwarder, nil
|
||||
}
|
||||
@@ -239,6 +348,74 @@ func (s *StarSSH) StartDynamicForward(req DynamicForwardRequest) (*PortForwarder
|
||||
return forwarder, nil
|
||||
}
|
||||
|
||||
func normalizeForwardRequest(req ForwardRequest) (normalizedForwardRequest, error) {
|
||||
normalized := normalizedForwardRequest{
|
||||
DialContext: req.DialContext,
|
||||
}
|
||||
|
||||
var err error
|
||||
normalized.ListenNetwork, normalized.ListenAddr, err = parseForwardEndpoint(req.ListenAddr)
|
||||
if err != nil {
|
||||
return normalized, fmt.Errorf("normalize listen address: %w", err)
|
||||
}
|
||||
normalized.TargetNetwork, normalized.TargetAddr, err = parseForwardEndpoint(req.TargetAddr)
|
||||
if err != nil {
|
||||
return normalized, fmt.Errorf("normalize target address: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(normalized.ListenAddr) == "" {
|
||||
return normalized, errors.New("forward listen address is empty")
|
||||
}
|
||||
if strings.TrimSpace(normalized.TargetAddr) == "" {
|
||||
return normalized, errors.New("forward target address is empty")
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func normalizeForwardNetwork(network string) string {
|
||||
network = strings.ToLower(strings.TrimSpace(network))
|
||||
if network == "" {
|
||||
return "tcp"
|
||||
}
|
||||
return network
|
||||
}
|
||||
|
||||
func isSupportedForwardNetwork(network string) bool {
|
||||
switch network {
|
||||
case "tcp", "tcp4", "tcp6", "unix":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func parseForwardEndpoint(value string) (network string, address string, err error) {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return "tcp", "", nil
|
||||
}
|
||||
|
||||
lowerValue := strings.ToLower(value)
|
||||
for _, prefix := range []string{"tcp4://", "tcp6://", "tcp://", "unix://"} {
|
||||
if strings.HasPrefix(lowerValue, prefix) {
|
||||
network = normalizeForwardNetwork(strings.TrimSuffix(prefix, "://"))
|
||||
address = value[len(prefix):]
|
||||
if !isSupportedForwardNetwork(network) {
|
||||
return "", "", fmt.Errorf("unsupported forward network %q", network)
|
||||
}
|
||||
return network, address, nil
|
||||
}
|
||||
}
|
||||
return "tcp", value, nil
|
||||
}
|
||||
|
||||
func forwardEndpoint(network string, address string) string {
|
||||
network = normalizeForwardNetwork(network)
|
||||
if network == "tcp" {
|
||||
return address
|
||||
}
|
||||
return network + "://" + address
|
||||
}
|
||||
|
||||
func (s *StarSSH) StartDynamicForwardDetached(req DynamicForwardRequest) (*PortForwarder, error) {
|
||||
if _, err := s.requireSSHClient(); err != nil {
|
||||
return nil, err
|
||||
@@ -344,6 +521,87 @@ func (f *PortForwarder) addCleanup(fn func() error) {
|
||||
f.cleanupFns = append(f.cleanupFns, fn)
|
||||
}
|
||||
|
||||
func prepareLocalForwardListener(network string, address string) (net.Listener, func() error, error) {
|
||||
network = normalizeForwardNetwork(network)
|
||||
if network != "unix" {
|
||||
listener, err := net.Listen(network, address)
|
||||
return listener, nil, err
|
||||
}
|
||||
|
||||
if err := removeStaleUnixSocket(address); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
listener, err := net.Listen(network, address)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
cleanup, err := makeUnixSocketCleanup(address)
|
||||
if err != nil {
|
||||
_ = listener.Close()
|
||||
_ = removeUnixSocketPath(address)
|
||||
return nil, nil, err
|
||||
}
|
||||
return listener, cleanup, nil
|
||||
}
|
||||
|
||||
func removeStaleUnixSocket(path string) error {
|
||||
info, err := os.Lstat(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.Mode()&os.ModeSocket == 0 {
|
||||
return fmt.Errorf("local unix forward path %q already exists and is not a socket", path)
|
||||
}
|
||||
|
||||
conn, err := net.DialTimeout("unix", path, unixForwardProbeTimeout)
|
||||
if err == nil {
|
||||
_ = conn.Close()
|
||||
return fmt.Errorf("local unix forward path %q is already in use", path)
|
||||
}
|
||||
if !isStaleUnixSocketDialError(err) {
|
||||
return fmt.Errorf("probe existing unix socket %q: %w", path, err)
|
||||
}
|
||||
return removeUnixSocketPath(path)
|
||||
}
|
||||
|
||||
func isStaleUnixSocketDialError(err error) bool {
|
||||
return errors.Is(err, syscall.ECONNREFUSED) || errors.Is(err, syscall.ENOENT)
|
||||
}
|
||||
|
||||
func makeUnixSocketCleanup(path string) (func() error, error) {
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return func() error {
|
||||
current, err := os.Lstat(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current.Mode()&os.ModeSocket == 0 || !os.SameFile(info, current) {
|
||||
return nil
|
||||
}
|
||||
return removeUnixSocketPath(path)
|
||||
}, nil
|
||||
}
|
||||
|
||||
func removeUnixSocketPath(path string) error {
|
||||
err := os.Remove(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *PortForwarder) runCleanup() {
|
||||
if f == nil {
|
||||
return
|
||||
|
||||
+534
@@ -2,8 +2,13 @@ package starssh
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -11,6 +16,59 @@ import (
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
type stubListener struct {
|
||||
addr net.Addr
|
||||
acceptCh chan net.Conn
|
||||
closeCh chan struct{}
|
||||
closeOnce sync.Once
|
||||
}
|
||||
|
||||
type dialRecord struct {
|
||||
network string
|
||||
addr string
|
||||
}
|
||||
|
||||
func newStubListener(addr net.Addr) *stubListener {
|
||||
return &stubListener{
|
||||
addr: addr,
|
||||
acceptCh: make(chan net.Conn, 1),
|
||||
closeCh: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func (l *stubListener) Accept() (net.Conn, error) {
|
||||
select {
|
||||
case conn, ok := <-l.acceptCh:
|
||||
if !ok {
|
||||
return nil, io.EOF
|
||||
}
|
||||
return conn, nil
|
||||
case <-l.closeCh:
|
||||
return nil, net.ErrClosed
|
||||
}
|
||||
}
|
||||
|
||||
func (l *stubListener) Close() error {
|
||||
l.closeOnce.Do(func() {
|
||||
close(l.closeCh)
|
||||
close(l.acceptCh)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *stubListener) Addr() net.Addr {
|
||||
return l.addr
|
||||
}
|
||||
|
||||
func (l *stubListener) Push(conn net.Conn) error {
|
||||
select {
|
||||
case <-l.closeCh:
|
||||
return net.ErrClosed
|
||||
case l.acceptCh <- conn:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartLocalForwardUsesExistingConnectionByDefault(t *testing.T) {
|
||||
oldDialSSHClient := dialSSHClient
|
||||
oldNewDetachedForwardClient := newDetachedForwardClient
|
||||
@@ -63,6 +121,64 @@ func TestStartLocalForwardUsesExistingConnectionByDefault(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestForwardRequestLegacyPositionalLiteralDefaultsToTCP(t *testing.T) {
|
||||
dialer := func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
req, err := normalizeForwardRequest(ForwardRequest{
|
||||
"127.0.0.1:10022",
|
||||
"example.internal:22",
|
||||
dialer,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("normalizeForwardRequest: %v", err)
|
||||
}
|
||||
if req.ListenNetwork != "tcp" {
|
||||
t.Fatalf("ListenNetwork=%q want tcp", req.ListenNetwork)
|
||||
}
|
||||
if req.TargetNetwork != "tcp" {
|
||||
t.Fatalf("TargetNetwork=%q want tcp", req.TargetNetwork)
|
||||
}
|
||||
if req.ListenAddr != "127.0.0.1:10022" || req.TargetAddr != "example.internal:22" {
|
||||
t.Fatalf("unexpected normalized request: %+v", req)
|
||||
}
|
||||
if req.DialContext == nil {
|
||||
t.Fatal("expected DialContext to be preserved")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseForwardEndpointTreatsTCPPrefixLikePlainAddress(t *testing.T) {
|
||||
network, address, err := parseForwardEndpoint("tcp:22")
|
||||
if err != nil {
|
||||
t.Fatalf("parseForwardEndpoint: %v", err)
|
||||
}
|
||||
if network != "tcp" {
|
||||
t.Fatalf("network=%q want tcp", network)
|
||||
}
|
||||
if address != "tcp:22" {
|
||||
t.Fatalf("address=%q want tcp:22", address)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseForwardEndpointSupportsExplicitSchemes(t *testing.T) {
|
||||
network, address, err := parseForwardEndpoint("unix:///tmp/test-forward.sock")
|
||||
if err != nil {
|
||||
t.Fatalf("parseForwardEndpoint unix: %v", err)
|
||||
}
|
||||
if network != "unix" || address != "/tmp/test-forward.sock" {
|
||||
t.Fatalf("unexpected unix endpoint parse: network=%q address=%q", network, address)
|
||||
}
|
||||
|
||||
network, address, err = parseForwardEndpoint("tcp6://[::1]:2222")
|
||||
if err != nil {
|
||||
t.Fatalf("parseForwardEndpoint tcp6: %v", err)
|
||||
}
|
||||
if network != "tcp6" || address != "[::1]:2222" {
|
||||
t.Fatalf("unexpected tcp6 endpoint parse: network=%q address=%q", network, address)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartLocalForwardDetachedUsesSeparateConnection(t *testing.T) {
|
||||
oldDialSSHClient := dialSSHClient
|
||||
oldNewDetachedForwardClient := newDetachedForwardClient
|
||||
@@ -132,6 +248,424 @@ func TestStartLocalForwardDetachedUsesSeparateConnection(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartRemoteForwardSupportsUnixListenAndTCPTarget(t *testing.T) {
|
||||
oldListenSSHClient := listenSSHClient
|
||||
t.Cleanup(func() {
|
||||
listenSSHClient = oldListenSSHClient
|
||||
})
|
||||
|
||||
baseClient := &ssh.Client{}
|
||||
star := &StarSSH{}
|
||||
star.setTransport(baseClient, nil)
|
||||
|
||||
listener := newStubListener(&net.UnixAddr{
|
||||
Name: "/run/user/0/gnupg/S.gpg-agent",
|
||||
Net: "unix",
|
||||
})
|
||||
|
||||
var listenedNetwork string
|
||||
var listenedAddr string
|
||||
listenSSHClient = func(client *ssh.Client, network, address string) (net.Listener, error) {
|
||||
if client != baseClient {
|
||||
t.Fatalf("unexpected ssh client %p", client)
|
||||
}
|
||||
listenedNetwork = network
|
||||
listenedAddr = address
|
||||
return listener, nil
|
||||
}
|
||||
|
||||
var targetNetwork string
|
||||
var targetAddr string
|
||||
forwarder, err := star.StartRemoteForward(ForwardRequest{
|
||||
ListenAddr: forwardEndpoint("unix", "/run/user/0/gnupg/S.gpg-agent"),
|
||||
TargetAddr: "127.0.0.1:4321",
|
||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
targetNetwork = network
|
||||
targetAddr = address
|
||||
serverConn, clientConn := net.Pipe()
|
||||
go echoForwardPipe(serverConn)
|
||||
return clientConn, nil
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("start remote unix forward: %v", err)
|
||||
}
|
||||
defer forwarder.Close()
|
||||
|
||||
srcPeer, forwardedConn := net.Pipe()
|
||||
defer srcPeer.Close()
|
||||
if err := listener.Push(forwardedConn); err != nil {
|
||||
t.Fatalf("push forwarded connection: %v", err)
|
||||
}
|
||||
|
||||
payload := []byte("unix-forward")
|
||||
done := make(chan []byte, 1)
|
||||
go func() {
|
||||
reply := make([]byte, len(payload))
|
||||
_, _ = io.ReadFull(srcPeer, reply)
|
||||
done <- reply
|
||||
}()
|
||||
|
||||
if _, err := srcPeer.Write(payload); err != nil {
|
||||
t.Fatalf("write source payload: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case reply := <-done:
|
||||
if string(reply) != string(payload) {
|
||||
t.Fatalf("unexpected remote unix forward reply: %q", string(reply))
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("remote unix forward did not relay payload")
|
||||
}
|
||||
|
||||
if listenedNetwork != "unix" || listenedAddr != "/run/user/0/gnupg/S.gpg-agent" {
|
||||
t.Fatalf("unexpected remote listen request: network=%q addr=%q", listenedNetwork, listenedAddr)
|
||||
}
|
||||
if targetNetwork != "tcp" || targetAddr != "127.0.0.1:4321" {
|
||||
t.Fatalf("unexpected local dial target: network=%q addr=%q", targetNetwork, targetAddr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartLocalUnixForwardUsesUnixListenerAndTCPTarget(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("unix socket smoke test is exercised in WSL/Linux CI path")
|
||||
}
|
||||
|
||||
oldDialSSHClient := dialSSHClient
|
||||
t.Cleanup(func() {
|
||||
dialSSHClient = oldDialSSHClient
|
||||
})
|
||||
|
||||
baseClient := &ssh.Client{}
|
||||
star := &StarSSH{}
|
||||
star.setTransport(baseClient, nil)
|
||||
|
||||
var targetNetwork string
|
||||
var targetAddr string
|
||||
dialSSHClient = func(ctx context.Context, client *ssh.Client, network, address string) (net.Conn, error) {
|
||||
if client != baseClient {
|
||||
t.Fatalf("unexpected ssh client %p", client)
|
||||
}
|
||||
targetNetwork = network
|
||||
targetAddr = address
|
||||
serverConn, clientConn := net.Pipe()
|
||||
go echoForwardPipe(serverConn)
|
||||
return clientConn, nil
|
||||
}
|
||||
|
||||
socketPath := filepath.Join(t.TempDir(), "forward.sock")
|
||||
forwarder, err := star.StartLocalUnixForward(socketPath, "127.0.0.1:4321")
|
||||
if err != nil {
|
||||
t.Fatalf("start local unix forward: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
closeErr := forwarder.Close()
|
||||
if closeErr != nil && !errors.Is(closeErr, net.ErrClosed) {
|
||||
t.Fatalf("close local unix forward: %v", closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
conn, err := net.DialTimeout("unix", socketPath, time.Second)
|
||||
if err != nil {
|
||||
t.Fatalf("dial unix forward listener: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
_ = conn.SetDeadline(time.Now().Add(2 * time.Second))
|
||||
|
||||
payload := []byte("unix-local-forward")
|
||||
if _, err := conn.Write(payload); err != nil {
|
||||
t.Fatalf("write unix forward payload: %v", err)
|
||||
}
|
||||
reply := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(conn, reply); err != nil {
|
||||
t.Fatalf("read unix forward reply: %v", err)
|
||||
}
|
||||
if string(reply) != string(payload) {
|
||||
t.Fatalf("unexpected unix forward reply: %q", string(reply))
|
||||
}
|
||||
if targetNetwork != "tcp" || targetAddr != "127.0.0.1:4321" {
|
||||
t.Fatalf("unexpected remote dial target: network=%q addr=%q", targetNetwork, targetAddr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartLocalUnixForwardRemovesSocketOnClose(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("unix socket smoke test is exercised in WSL/Linux CI path")
|
||||
}
|
||||
|
||||
oldDialSSHClient := dialSSHClient
|
||||
t.Cleanup(func() {
|
||||
dialSSHClient = oldDialSSHClient
|
||||
})
|
||||
|
||||
baseClient := &ssh.Client{}
|
||||
star := &StarSSH{}
|
||||
star.setTransport(baseClient, nil)
|
||||
|
||||
dialSSHClient = func(ctx context.Context, client *ssh.Client, network, address string) (net.Conn, error) {
|
||||
serverConn, clientConn := net.Pipe()
|
||||
go echoForwardPipe(serverConn)
|
||||
return clientConn, nil
|
||||
}
|
||||
|
||||
socketPath := filepath.Join(t.TempDir(), "cleanup.sock")
|
||||
forwarder, err := star.StartLocalUnixForward(socketPath, "127.0.0.1:4321")
|
||||
if err != nil {
|
||||
t.Fatalf("start local unix forward: %v", err)
|
||||
}
|
||||
|
||||
if _, err := os.Lstat(socketPath); err != nil {
|
||||
t.Fatalf("socket should exist while forward is running: %v", err)
|
||||
}
|
||||
if err := forwarder.Close(); err != nil && !errors.Is(err, net.ErrClosed) {
|
||||
t.Fatalf("close local unix forward: %v", err)
|
||||
}
|
||||
if _, err := os.Lstat(socketPath); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("socket path should be removed on close, got err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartLocalUnixForwardReusesStaleSocketPath(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("unix socket smoke test is exercised in WSL/Linux CI path")
|
||||
}
|
||||
|
||||
oldDialSSHClient := dialSSHClient
|
||||
t.Cleanup(func() {
|
||||
dialSSHClient = oldDialSSHClient
|
||||
})
|
||||
|
||||
baseClient := &ssh.Client{}
|
||||
star := &StarSSH{}
|
||||
star.setTransport(baseClient, nil)
|
||||
|
||||
dialSSHClient = func(ctx context.Context, client *ssh.Client, network, address string) (net.Conn, error) {
|
||||
serverConn, clientConn := net.Pipe()
|
||||
go echoForwardPipe(serverConn)
|
||||
return clientConn, nil
|
||||
}
|
||||
|
||||
socketPath := filepath.Join(t.TempDir(), "stale.sock")
|
||||
staleListener, err := net.ListenUnix("unix", &net.UnixAddr{
|
||||
Name: socketPath,
|
||||
Net: "unix",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create stale unix socket: %v", err)
|
||||
}
|
||||
staleListener.SetUnlinkOnClose(false)
|
||||
if err := staleListener.Close(); err != nil {
|
||||
t.Fatalf("close stale unix socket listener: %v", err)
|
||||
}
|
||||
if _, err := os.Lstat(socketPath); err != nil {
|
||||
t.Fatalf("expected stale unix socket path to remain after close: %v", err)
|
||||
}
|
||||
|
||||
forwarder, err := star.StartLocalUnixForward(socketPath, "127.0.0.1:4321")
|
||||
if err != nil {
|
||||
t.Fatalf("start local unix forward on stale socket path: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
closeErr := forwarder.Close()
|
||||
if closeErr != nil && !errors.Is(closeErr, net.ErrClosed) {
|
||||
t.Fatalf("close local unix forward: %v", closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
reply := make([]byte, len("stale-reuse"))
|
||||
conn, err := net.DialTimeout("unix", socketPath, time.Second)
|
||||
if err != nil {
|
||||
t.Fatalf("dial reused unix forward listener: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
_ = conn.SetDeadline(time.Now().Add(2 * time.Second))
|
||||
if _, err := conn.Write([]byte("stale-reuse")); err != nil {
|
||||
t.Fatalf("write reused unix forward payload: %v", err)
|
||||
}
|
||||
if _, err := io.ReadFull(conn, reply); err != nil {
|
||||
t.Fatalf("read reused unix forward reply: %v", err)
|
||||
}
|
||||
if string(reply) != "stale-reuse" {
|
||||
t.Fatalf("unexpected reply on reused unix forward: %q", string(reply))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartLocalUnixToUnixForwardUsesUnixTarget(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("unix socket smoke test is exercised in WSL/Linux CI path")
|
||||
}
|
||||
|
||||
oldDialSSHClient := dialSSHClient
|
||||
t.Cleanup(func() {
|
||||
dialSSHClient = oldDialSSHClient
|
||||
})
|
||||
|
||||
baseClient := &ssh.Client{}
|
||||
star := &StarSSH{}
|
||||
star.setTransport(baseClient, nil)
|
||||
|
||||
targetSocketPath := filepath.Join(t.TempDir(), "target.sock")
|
||||
targetListener, err := net.Listen("unix", targetSocketPath)
|
||||
if err != nil {
|
||||
t.Fatalf("listen target unix socket: %v", err)
|
||||
}
|
||||
defer targetListener.Close()
|
||||
|
||||
done := make(chan []byte, 1)
|
||||
go func() {
|
||||
conn, acceptErr := targetListener.Accept()
|
||||
if acceptErr != nil {
|
||||
done <- nil
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
buf := make([]byte, 64)
|
||||
n, _ := conn.Read(buf)
|
||||
_, _ = conn.Write(buf[:n])
|
||||
done <- buf[:n]
|
||||
}()
|
||||
|
||||
dialRecordCh := make(chan dialRecord, 1)
|
||||
dialSSHClient = func(ctx context.Context, client *ssh.Client, network, address string) (net.Conn, error) {
|
||||
if client != baseClient {
|
||||
t.Fatalf("unexpected ssh client %p", client)
|
||||
}
|
||||
dialRecordCh <- dialRecord{network: network, addr: address}
|
||||
var dialer net.Dialer
|
||||
return dialer.DialContext(ctx, network, address)
|
||||
}
|
||||
|
||||
listenSocketPath := filepath.Join(t.TempDir(), "listen.sock")
|
||||
forwarder, err := star.StartLocalUnixToUnixForward(listenSocketPath, targetSocketPath)
|
||||
if err != nil {
|
||||
t.Fatalf("start local unix-to-unix forward: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
closeErr := forwarder.Close()
|
||||
if closeErr != nil && !errors.Is(closeErr, net.ErrClosed) {
|
||||
t.Fatalf("close local unix-to-unix forward: %v", closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
conn, err := net.DialTimeout("unix", listenSocketPath, time.Second)
|
||||
if err != nil {
|
||||
t.Fatalf("dial unix-to-unix listener: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
_ = conn.SetDeadline(time.Now().Add(2 * time.Second))
|
||||
|
||||
payload := []byte("unix-to-unix")
|
||||
if _, err := conn.Write(payload); err != nil {
|
||||
t.Fatalf("write unix-to-unix payload: %v", err)
|
||||
}
|
||||
reply := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(conn, reply); err != nil {
|
||||
t.Fatalf("read unix-to-unix reply: %v", err)
|
||||
}
|
||||
if string(reply) != string(payload) {
|
||||
t.Fatalf("unexpected unix-to-unix reply: %q", string(reply))
|
||||
}
|
||||
|
||||
select {
|
||||
case got := <-done:
|
||||
if string(got) != string(payload) {
|
||||
t.Fatalf("unexpected payload seen by target unix socket: %q", string(got))
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("target unix socket did not receive forwarded payload")
|
||||
}
|
||||
|
||||
select {
|
||||
case got := <-dialRecordCh:
|
||||
if got.network != "unix" || got.addr != targetSocketPath {
|
||||
t.Fatalf("unexpected unix target dial: network=%q addr=%q", got.network, got.addr)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("did not observe unix target dial")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartLocalTCPToUnixForwardUsesUnixTarget(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("unix socket smoke test is exercised in WSL/Linux CI path")
|
||||
}
|
||||
|
||||
oldDialSSHClient := dialSSHClient
|
||||
t.Cleanup(func() {
|
||||
dialSSHClient = oldDialSSHClient
|
||||
})
|
||||
|
||||
baseClient := &ssh.Client{}
|
||||
star := &StarSSH{}
|
||||
star.setTransport(baseClient, nil)
|
||||
|
||||
targetSocketPath := filepath.Join(t.TempDir(), "target-tcp-to-unix.sock")
|
||||
targetListener, err := net.Listen("unix", targetSocketPath)
|
||||
if err != nil {
|
||||
t.Fatalf("listen target unix socket: %v", err)
|
||||
}
|
||||
defer targetListener.Close()
|
||||
|
||||
done := make(chan []byte, 1)
|
||||
go func() {
|
||||
conn, acceptErr := targetListener.Accept()
|
||||
if acceptErr != nil {
|
||||
done <- nil
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
buf := make([]byte, 64)
|
||||
n, _ := conn.Read(buf)
|
||||
_, _ = conn.Write(buf[:n])
|
||||
done <- buf[:n]
|
||||
}()
|
||||
|
||||
dialRecordCh := make(chan dialRecord, 1)
|
||||
dialSSHClient = func(ctx context.Context, client *ssh.Client, network, address string) (net.Conn, error) {
|
||||
if client != baseClient {
|
||||
t.Fatalf("unexpected ssh client %p", client)
|
||||
}
|
||||
dialRecordCh <- dialRecord{network: network, addr: address}
|
||||
var dialer net.Dialer
|
||||
return dialer.DialContext(ctx, network, address)
|
||||
}
|
||||
|
||||
forwarder, err := star.StartLocalTCPToUnixForward("127.0.0.1:0", targetSocketPath)
|
||||
if err != nil {
|
||||
t.Fatalf("start local tcp-to-unix forward: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
closeErr := forwarder.Close()
|
||||
if closeErr != nil && !errors.Is(closeErr, net.ErrClosed) {
|
||||
t.Fatalf("close local tcp-to-unix forward: %v", closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
reply := exerciseForwarder(t, forwarder.Addr().String(), []byte("tcp-to-unix"))
|
||||
if string(reply) != "tcp-to-unix" {
|
||||
t.Fatalf("unexpected tcp-to-unix reply: %q", string(reply))
|
||||
}
|
||||
|
||||
select {
|
||||
case got := <-done:
|
||||
if string(got) != "tcp-to-unix" {
|
||||
t.Fatalf("unexpected payload seen by unix target: %q", string(got))
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("unix target did not receive forwarded tcp payload")
|
||||
}
|
||||
|
||||
select {
|
||||
case got := <-dialRecordCh:
|
||||
if got.network != "unix" || got.addr != targetSocketPath {
|
||||
t.Fatalf("unexpected unix target dial: network=%q addr=%q", got.network, got.addr)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("did not observe unix target dial")
|
||||
}
|
||||
}
|
||||
|
||||
func echoForwardPipe(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
buf := make([]byte, 4096)
|
||||
|
||||
@@ -4,25 +4,14 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
"golang.org/x/crypto/ssh/agent"
|
||||
)
|
||||
|
||||
var ErrHostKeyCallbackRequired = errors.New("host key callback is required; use DefaultAllowHostKeyCallback to explicitly allow any host key")
|
||||
var errSSHAgentUnavailable = errors.New("ssh-agent unavailable")
|
||||
|
||||
var defaultAuthOrder = []AuthMethodKind{
|
||||
AuthMethodSSHAgent,
|
||||
AuthMethodPrivateKey,
|
||||
AuthMethodPassword,
|
||||
AuthMethodKeyboardInteractive,
|
||||
}
|
||||
|
||||
func DefaultAllowHostKeyCallback(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
||||
return nil
|
||||
@@ -42,14 +31,39 @@ func loginWithContext(ctx context.Context, info LoginInput) (*StarSSH, error) {
|
||||
return nil, ErrHostKeyCallbackRequired
|
||||
}
|
||||
|
||||
loginCtx, cancel := contextWithLoginTimeout(ctx, info.Timeout)
|
||||
authTimeout := effectiveLoginTimeout(info)
|
||||
loginCtx, cancel := contextWithLoginTimeout(ctx, authTimeout)
|
||||
defer cancel()
|
||||
|
||||
order, err := normalizeAuthOrder(info.AuthOrder)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if shouldRetrySSHAgentAuth(info, order) {
|
||||
agentAttempt := newSSHAgentAuthAttempt()
|
||||
for {
|
||||
agentAttempt.begin()
|
||||
sshInfo, err := loginOnceWithContext(loginCtx, info, authTimeout, agentAttempt)
|
||||
if err == nil {
|
||||
return sshInfo, nil
|
||||
}
|
||||
if errors.Is(err, errRetrySSHAgentAuth) && loginCtx.Err() == nil {
|
||||
continue
|
||||
}
|
||||
return sshInfo, err
|
||||
}
|
||||
}
|
||||
|
||||
return loginOnceWithContext(loginCtx, info, authTimeout, nil)
|
||||
}
|
||||
|
||||
func loginOnceWithContext(ctx context.Context, info LoginInput, authTimeout time.Duration, agentAttempt *sshAgentAuthAttempt) (*StarSSH, error) {
|
||||
sshInfo := &StarSSH{
|
||||
LoginInfo: info,
|
||||
}
|
||||
|
||||
auth, authCleanup, err := buildAuthMethods(info)
|
||||
auth, authCleanup, err := buildAuthMethodsWithAgentAttempt(info, agentAttempt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -76,7 +90,7 @@ func loginWithContext(ctx context.Context, info LoginInput) (*StarSSH, error) {
|
||||
clientConfig := &ssh.ClientConfig{
|
||||
User: info.User,
|
||||
Auth: auth,
|
||||
Timeout: info.Timeout,
|
||||
Timeout: authTimeout,
|
||||
HostKeyCallback: hostKeyCallback,
|
||||
BannerCallback: bannerCallback,
|
||||
}
|
||||
@@ -89,11 +103,11 @@ func loginWithContext(ctx context.Context, info LoginInput) (*StarSSH, error) {
|
||||
}
|
||||
|
||||
targetAddr := joinHostPort(info.Addr, info.Port)
|
||||
rawConn, upstream, err := dialTargetConn(loginCtx, info)
|
||||
rawConn, upstream, err := dialTargetConn(ctx, info)
|
||||
if err != nil {
|
||||
return sshInfo, err
|
||||
}
|
||||
restoreDeadline := applyConnDeadline(rawConn, loginCtx, info.Timeout)
|
||||
restoreDeadline := applyConnDeadline(rawConn, ctx, authTimeout)
|
||||
defer restoreDeadline()
|
||||
|
||||
clientConn, chans, reqs, err := ssh.NewClientConn(rawConn, targetAddr, clientConfig)
|
||||
@@ -130,6 +144,7 @@ func LoginSimple(host string, user string, passwd string, prikeyPath string, por
|
||||
Addr: host,
|
||||
Port: port,
|
||||
Timeout: timeout,
|
||||
DialTimeout: timeout,
|
||||
User: user,
|
||||
HostKeyCallback: DefaultAllowHostKeyCallback,
|
||||
}
|
||||
@@ -154,209 +169,25 @@ func normalizeLoginInput(info LoginInput) LoginInput {
|
||||
if info.Port <= 0 {
|
||||
info.Port = defaultSSHPort
|
||||
}
|
||||
if info.Timeout <= 0 {
|
||||
info.Timeout = defaultLoginTimeout
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
func buildAuthMethods(info LoginInput) ([]ssh.AuthMethod, func(), error) {
|
||||
order, err := normalizeAuthOrder(info.AuthOrder)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
func effectiveLoginTimeout(info LoginInput) time.Duration {
|
||||
if info.Timeout <= 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
auth := make([]ssh.AuthMethod, 0, len(order))
|
||||
var agentErr error
|
||||
var cleanupFuncs []func()
|
||||
|
||||
for _, methodKind := range order {
|
||||
switch methodKind {
|
||||
case AuthMethodPrivateKey:
|
||||
method, err := buildPrivateKeyAuthMethod(info)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if method != nil {
|
||||
auth = append(auth, method)
|
||||
}
|
||||
case AuthMethodPassword:
|
||||
method := buildPasswordAuthMethod(info.Password, info.PasswordCallback)
|
||||
if method != nil {
|
||||
auth = append(auth, method)
|
||||
}
|
||||
case AuthMethodKeyboardInteractive:
|
||||
method := buildKeyboardInteractiveAuthMethod(info.Password, info.PasswordCallback, info.KeyboardInteractiveCallback)
|
||||
if method != nil {
|
||||
auth = append(auth, method)
|
||||
}
|
||||
case AuthMethodSSHAgent:
|
||||
if info.DisableSSHAgent {
|
||||
continue
|
||||
}
|
||||
agentMethod, cleanup, err := buildSSHAgentAuthMethod(info.Timeout)
|
||||
if err != nil {
|
||||
agentErr = err
|
||||
continue
|
||||
}
|
||||
if agentMethod != nil {
|
||||
auth = append(auth, agentMethod)
|
||||
}
|
||||
if cleanup != nil {
|
||||
cleanupFuncs = append(cleanupFuncs, cleanup)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(auth) == 0 {
|
||||
if agentErr != nil {
|
||||
return nil, nil, fmt.Errorf("no authentication method provided; ssh-agent unavailable: %w", agentErr)
|
||||
}
|
||||
return nil, nil, errors.New("no authentication method provided: password, private key, or ssh-agent is required")
|
||||
}
|
||||
|
||||
return auth, composeCleanup(cleanupFuncs...), nil
|
||||
return info.Timeout
|
||||
}
|
||||
|
||||
func normalizeAuthOrder(order []AuthMethodKind) ([]AuthMethodKind, error) {
|
||||
if len(order) == 0 {
|
||||
return append([]AuthMethodKind(nil), defaultAuthOrder...), nil
|
||||
}
|
||||
|
||||
normalized := make([]AuthMethodKind, 0, len(order))
|
||||
seen := make(map[AuthMethodKind]struct{}, len(order))
|
||||
for _, raw := range order {
|
||||
kind := AuthMethodKind(strings.ToLower(strings.TrimSpace(string(raw))))
|
||||
if kind == "" {
|
||||
return nil, errors.New("auth order contains an empty auth method")
|
||||
}
|
||||
if !isSupportedAuthMethodKind(kind) {
|
||||
return nil, fmt.Errorf("unsupported auth method %q", raw)
|
||||
}
|
||||
if _, exists := seen[kind]; exists {
|
||||
continue
|
||||
}
|
||||
seen[kind] = struct{}{}
|
||||
normalized = append(normalized, kind)
|
||||
}
|
||||
|
||||
if len(normalized) == 0 {
|
||||
return nil, errors.New("auth order is empty")
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func isSupportedAuthMethodKind(kind AuthMethodKind) bool {
|
||||
switch kind {
|
||||
case AuthMethodPrivateKey, AuthMethodPassword, AuthMethodKeyboardInteractive, AuthMethodSSHAgent:
|
||||
return true
|
||||
func effectiveDialTimeout(info LoginInput) time.Duration {
|
||||
switch {
|
||||
case info.DialTimeout < 0:
|
||||
return 0
|
||||
case info.DialTimeout > 0:
|
||||
return info.DialTimeout
|
||||
case info.Timeout > 0:
|
||||
return info.Timeout
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func buildPrivateKeyAuthMethod(info LoginInput) (ssh.AuthMethod, error) {
|
||||
if strings.TrimSpace(info.Prikey) == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
pemBytes := []byte(info.Prikey)
|
||||
if info.PrikeyPwd == "" {
|
||||
signer, err := ssh.ParsePrivateKey(pemBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ssh.PublicKeys(signer), nil
|
||||
}
|
||||
|
||||
signer, err := ssh.ParsePrivateKeyWithPassphrase(pemBytes, []byte(info.PrikeyPwd))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ssh.PublicKeys(signer), nil
|
||||
}
|
||||
|
||||
func buildPasswordAuthMethod(password string, callback func() (string, error)) ssh.AuthMethod {
|
||||
if password != "" {
|
||||
return ssh.Password(password)
|
||||
}
|
||||
if callback != nil {
|
||||
return ssh.PasswordCallback(callback)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func buildKeyboardInteractiveAuthMethod(
|
||||
password string,
|
||||
passwordCallback func() (string, error),
|
||||
challenge ssh.KeyboardInteractiveChallenge,
|
||||
) ssh.AuthMethod {
|
||||
if challenge != nil {
|
||||
return ssh.KeyboardInteractive(challenge)
|
||||
}
|
||||
if password == "" && passwordCallback == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
keyboardInteractiveChallenge := func(user, instruction string, questions []string, echos []bool) ([]string, error) {
|
||||
if len(questions) == 0 {
|
||||
return []string{}, nil
|
||||
}
|
||||
|
||||
answer := password
|
||||
if answer == "" {
|
||||
var err error
|
||||
answer, err = passwordCallback()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
answers := make([]string, len(questions))
|
||||
for i := range questions {
|
||||
answers[i] = answer
|
||||
}
|
||||
return answers, nil
|
||||
}
|
||||
return ssh.KeyboardInteractive(keyboardInteractiveChallenge)
|
||||
}
|
||||
|
||||
func buildSSHAgentAuthMethod(timeout time.Duration) (ssh.AuthMethod, func(), error) {
|
||||
conn, err := dialSSHAgent(timeout)
|
||||
if err != nil {
|
||||
if errors.Is(err, errSSHAgentUnavailable) {
|
||||
return nil, nil, nil
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
if conn == nil {
|
||||
return nil, nil, nil
|
||||
}
|
||||
|
||||
signers, err := agent.NewClient(conn).Signers()
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(signers) == 0 {
|
||||
_ = conn.Close()
|
||||
return nil, nil, errors.New("ssh-agent has no loaded keys")
|
||||
}
|
||||
|
||||
return ssh.PublicKeys(signers...), func() {
|
||||
_ = conn.Close()
|
||||
}, nil
|
||||
}
|
||||
|
||||
func composeCleanup(funcs ...func()) func() {
|
||||
if len(funcs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return func() {
|
||||
for i := len(funcs) - 1; i >= 0; i-- {
|
||||
if funcs[i] != nil {
|
||||
funcs[i]()
|
||||
}
|
||||
}
|
||||
return defaultLoginTimeout
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,763 @@
|
||||
package starssh
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
sshagent "golang.org/x/crypto/ssh/agent"
|
||||
)
|
||||
|
||||
func TestNormalizeLoginInputKeepsZeroAuthTimeout(t *testing.T) {
|
||||
info := normalizeLoginInput(LoginInput{})
|
||||
if info.Port != defaultSSHPort {
|
||||
t.Fatalf("Port=%d want %d", info.Port, defaultSSHPort)
|
||||
}
|
||||
if info.Timeout != 0 {
|
||||
t.Fatalf("Timeout=%v want 0", info.Timeout)
|
||||
}
|
||||
if info.DialTimeout != 0 {
|
||||
t.Fatalf("DialTimeout=%v want 0", info.DialTimeout)
|
||||
}
|
||||
if info.SSHAgentTimeout != 0 {
|
||||
t.Fatalf("SSHAgentTimeout=%v want 0", info.SSHAgentTimeout)
|
||||
}
|
||||
if info.SSHAgentForwardTimeout != 0 {
|
||||
t.Fatalf("SSHAgentForwardTimeout=%v want 0", info.SSHAgentForwardTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEffectiveLoginTimeout(t *testing.T) {
|
||||
if got := effectiveLoginTimeout(LoginInput{}); got != 0 {
|
||||
t.Fatalf("zero login timeout should stay zero, got %v", got)
|
||||
}
|
||||
if got := effectiveLoginTimeout(LoginInput{Timeout: 7 * time.Second}); got != 7*time.Second {
|
||||
t.Fatalf("expected explicit login timeout, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEffectiveDialTimeout(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
info LoginInput
|
||||
want time.Duration
|
||||
}{
|
||||
{
|
||||
name: "default fallback",
|
||||
info: LoginInput{},
|
||||
want: defaultLoginTimeout,
|
||||
},
|
||||
{
|
||||
name: "reuse timeout when dial timeout omitted",
|
||||
info: LoginInput{Timeout: 9 * time.Second},
|
||||
want: 9 * time.Second,
|
||||
},
|
||||
{
|
||||
name: "explicit dial timeout wins",
|
||||
info: LoginInput{Timeout: 9 * time.Second, DialTimeout: 3 * time.Second},
|
||||
want: 3 * time.Second,
|
||||
},
|
||||
{
|
||||
name: "negative dial timeout disables default dial deadline",
|
||||
info: LoginInput{Timeout: 9 * time.Second, DialTimeout: -1},
|
||||
want: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := effectiveDialTimeout(tc.info); got != tc.want {
|
||||
t.Fatalf("effectiveDialTimeout(%+v)=%v want %v", tc.info, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEffectiveSSHAgentTimeout(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
info LoginInput
|
||||
want time.Duration
|
||||
}{
|
||||
{
|
||||
name: "default fallback without auth timeout",
|
||||
info: LoginInput{},
|
||||
want: defaultSSHAgentTimeout,
|
||||
},
|
||||
{
|
||||
name: "auth timeout does not cap default",
|
||||
info: LoginInput{Timeout: 9 * time.Second},
|
||||
want: defaultSSHAgentTimeout,
|
||||
},
|
||||
{
|
||||
name: "explicit agent timeout wins",
|
||||
info: LoginInput{Timeout: 9 * time.Second, DialTimeout: 3 * time.Second, SSHAgentTimeout: 90 * time.Second},
|
||||
want: 90 * time.Second,
|
||||
},
|
||||
{
|
||||
name: "negative agent timeout disables operation deadline",
|
||||
info: LoginInput{SSHAgentTimeout: -1},
|
||||
want: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := effectiveSSHAgentTimeout(tc.info); got != tc.want {
|
||||
t.Fatalf("effectiveSSHAgentTimeout(%+v)=%v want %v", tc.info, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEffectiveSSHAgentForwardTimeout(t *testing.T) {
|
||||
if got := effectiveSSHAgentForwardTimeout(LoginInput{}); got != 0 {
|
||||
t.Fatalf("zero forward timeout should stay zero, got %v", got)
|
||||
}
|
||||
if got := effectiveSSHAgentForwardTimeout(LoginInput{SSHAgentForwardTimeout: 4 * time.Second}); got != 4*time.Second {
|
||||
t.Fatalf("expected explicit forward timeout, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildAuthMethodsUsesSeparateSSHAgentTimeouts(t *testing.T) {
|
||||
oldBuilder := buildSSHAgentAuthMethodFunc
|
||||
t.Cleanup(func() {
|
||||
buildSSHAgentAuthMethodFunc = oldBuilder
|
||||
})
|
||||
|
||||
captured := sshAgentTimeouts{Dial: -2, Operation: -2, Forward: -2}
|
||||
buildSSHAgentAuthMethodFunc = func(timeouts sshAgentTimeouts) (ssh.AuthMethod, func(), error) {
|
||||
captured = timeouts
|
||||
return ssh.Password("agent"), nil, nil
|
||||
}
|
||||
|
||||
info := LoginInput{
|
||||
Timeout: 0,
|
||||
DialTimeout: 11 * time.Second,
|
||||
SSHAgentTimeout: 90 * time.Second,
|
||||
SSHAgentForwardTimeout: 4 * time.Second,
|
||||
IdentityAgent: "/tmp/custom-agent.sock",
|
||||
AuthOrder: []AuthMethodKind{AuthMethodSSHAgent},
|
||||
}
|
||||
auth, cleanup, err := buildAuthMethods(info)
|
||||
if err != nil {
|
||||
t.Fatalf("buildAuthMethods: %v", err)
|
||||
}
|
||||
if cleanup != nil {
|
||||
cleanup()
|
||||
}
|
||||
if len(auth) != 1 {
|
||||
t.Fatalf("expected one auth method, got %d", len(auth))
|
||||
}
|
||||
if captured.Dial != 11*time.Second {
|
||||
t.Fatalf("agent auth builder dial timeout=%v want %v", captured.Dial, 11*time.Second)
|
||||
}
|
||||
if captured.Operation != 90*time.Second {
|
||||
t.Fatalf("agent auth builder operation timeout=%v want %v", captured.Operation, 90*time.Second)
|
||||
}
|
||||
if captured.Forward != 4*time.Second {
|
||||
t.Fatalf("agent auth builder forward timeout=%v want %v", captured.Forward, 4*time.Second)
|
||||
}
|
||||
if captured.Endpoint != "/tmp/custom-agent.sock" {
|
||||
t.Fatalf("agent auth builder endpoint=%q want custom endpoint", captured.Endpoint)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildAuthMethodsUsesSingleAgentAuthMethod(t *testing.T) {
|
||||
oldBuilder := buildSSHAgentAuthMethodFunc
|
||||
t.Cleanup(func() {
|
||||
buildSSHAgentAuthMethodFunc = oldBuilder
|
||||
})
|
||||
|
||||
buildSSHAgentAuthMethodFunc = func(timeouts sshAgentTimeouts) (ssh.AuthMethod, func(), error) {
|
||||
return ssh.Password("agent"), nil, nil
|
||||
}
|
||||
|
||||
auth, cleanup, err := buildAuthMethods(LoginInput{
|
||||
AuthOrder: []AuthMethodKind{AuthMethodSSHAgent},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("buildAuthMethods: %v", err)
|
||||
}
|
||||
if cleanup != nil {
|
||||
cleanup()
|
||||
}
|
||||
if len(auth) != 1 {
|
||||
t.Fatalf("auth methods=%d, want 1", len(auth))
|
||||
}
|
||||
}
|
||||
|
||||
func TestShouldRetrySSHAgentAuthWhenAgentIsNotFirst(t *testing.T) {
|
||||
order := []AuthMethodKind{AuthMethodPassword, AuthMethodSSHAgent}
|
||||
if !shouldRetrySSHAgentAuth(LoginInput{}, order) {
|
||||
t.Fatal("expected ssh-agent retry when ssh-agent is present after password")
|
||||
}
|
||||
if shouldRetrySSHAgentAuth(LoginInput{DisableSSHAgent: true}, order) {
|
||||
t.Fatal("expected ssh-agent retry disabled when DisableSSHAgent is true")
|
||||
}
|
||||
if shouldRetrySSHAgentAuth(LoginInput{}, []AuthMethodKind{AuthMethodPassword}) {
|
||||
t.Fatal("expected no ssh-agent retry when ssh-agent auth is absent")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildAuthMethodsWithAgentAttemptMarksNonFirstAgentForRetry(t *testing.T) {
|
||||
oldBuilder := buildSSHAgentAuthMethodFunc
|
||||
t.Cleanup(func() {
|
||||
buildSSHAgentAuthMethodFunc = oldBuilder
|
||||
})
|
||||
|
||||
buildSSHAgentAuthMethodFunc = func(timeouts sshAgentTimeouts) (ssh.AuthMethod, func(), error) {
|
||||
if timeouts.SignFailure == nil {
|
||||
t.Fatal("expected SignFailure callback for non-first ssh-agent auth")
|
||||
}
|
||||
if timeouts.SkipFingerprints != nil {
|
||||
t.Fatalf("unexpected initial skip fingerprints: %#v", timeouts.SkipFingerprints)
|
||||
}
|
||||
return ssh.Password("agent"), nil, nil
|
||||
}
|
||||
|
||||
auth, cleanup, err := buildAuthMethodsWithAgentAttempt(LoginInput{
|
||||
Password: "secret",
|
||||
AuthOrder: []AuthMethodKind{AuthMethodPassword, AuthMethodSSHAgent},
|
||||
}, newSSHAgentAuthAttempt())
|
||||
if err != nil {
|
||||
t.Fatalf("buildAuthMethodsWithAgentAttempt: %v", err)
|
||||
}
|
||||
if cleanup != nil {
|
||||
cleanup()
|
||||
}
|
||||
if len(auth) != 2 {
|
||||
t.Fatalf("auth methods=%d want 2", len(auth))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentRetryPendingBlocksFallbackAuthThenResets(t *testing.T) {
|
||||
attempt := newSSHAgentAuthAttempt()
|
||||
attempt.skipFingerprint("SHA256:test")
|
||||
if err := checkSSHAgentRetryPending(attempt); !errors.Is(err, errRetrySSHAgentAuth) {
|
||||
t.Fatalf("retry pending err=%v want errRetrySSHAgentAuth", err)
|
||||
}
|
||||
attempt.begin()
|
||||
if err := checkSSHAgentRetryPending(attempt); err != nil {
|
||||
t.Fatalf("retry should reset on next attempt: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentRetryPendingBlocksPrivateKeyAuth(t *testing.T) {
|
||||
signer := mustGenerateTestSigner(t)
|
||||
attempt := newSSHAgentAuthAttempt()
|
||||
callback := privateKeySignersCallback(signer, attempt)
|
||||
|
||||
signers, err := callback()
|
||||
if err != nil {
|
||||
t.Fatalf("private key callback before retry: %v", err)
|
||||
}
|
||||
if len(signers) != 1 || signers[0] != signer {
|
||||
t.Fatalf("private key callback returned %#v, want original signer", signers)
|
||||
}
|
||||
|
||||
attempt.skipFingerprint("SHA256:test")
|
||||
signers, err = callback()
|
||||
if !errors.Is(err, errRetrySSHAgentAuth) {
|
||||
t.Fatalf("private key callback err=%v want errRetrySSHAgentAuth", err)
|
||||
}
|
||||
if signers != nil {
|
||||
t.Fatalf("private key callback signers=%#v want nil while retry pending", signers)
|
||||
}
|
||||
|
||||
attempt.begin()
|
||||
signers, err = callback()
|
||||
if err != nil {
|
||||
t.Fatalf("private key callback after retry reset: %v", err)
|
||||
}
|
||||
if len(signers) != 1 || signers[0] != signer {
|
||||
t.Fatalf("private key callback after retry returned %#v, want original signer", signers)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterSSHAgentSignersSkipsSignerAfterSignFailure(t *testing.T) {
|
||||
firstSigner := mustGenerateTestSigner(t)
|
||||
secondSigner := mustGenerateTestSigner(t)
|
||||
failingFirstSigner := &testFailingSigner{Signer: firstSigner, err: errors.New("first agent key cannot sign")}
|
||||
|
||||
attempt := newSSHAgentAuthAttempt()
|
||||
firstMethods := filterSSHAgentSignersForRetry([]ssh.Signer{failingFirstSigner, secondSigner}, sshAgentTimeouts{
|
||||
SignFailure: attempt.recordSignFailure,
|
||||
SkipFingerprints: attempt.skipSnapshot(),
|
||||
})
|
||||
if len(firstMethods) != 2 {
|
||||
t.Fatalf("first auth method signers=%d want 2", len(firstMethods))
|
||||
}
|
||||
if _, err := firstMethods[0].Sign(nil, []byte("challenge")); !errors.Is(err, errRetrySSHAgentAuth) {
|
||||
t.Fatalf("first signer err=%v want errRetrySSHAgentAuth", err)
|
||||
}
|
||||
secondMethods := filterSSHAgentSignersForRetry([]ssh.Signer{failingFirstSigner, secondSigner}, sshAgentTimeouts{
|
||||
SignFailure: attempt.recordSignFailure,
|
||||
SkipFingerprints: attempt.skipSnapshot(),
|
||||
})
|
||||
if len(secondMethods) != 1 {
|
||||
t.Fatalf("second auth method signers=%d want 1", len(secondMethods))
|
||||
}
|
||||
if string(secondMethods[0].PublicKey().Marshal()) != string(secondSigner.PublicKey().Marshal()) {
|
||||
t.Fatalf("second auth method did not skip failed first key")
|
||||
}
|
||||
signature, err := secondMethods[0].Sign(nil, []byte("challenge"))
|
||||
if err != nil {
|
||||
t.Fatalf("second signer Sign: %v", err)
|
||||
}
|
||||
if signature == nil {
|
||||
t.Fatal("second signer returned nil signature")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildAuthMethodsSkipsFailedAgentSignerOnRetry(t *testing.T) {
|
||||
firstSigner := mustGenerateTestSigner(t)
|
||||
secondSigner := mustGenerateTestSigner(t)
|
||||
wantErr := errors.New("first agent key cannot sign")
|
||||
failingFirstSigner := &testFailingSigner{Signer: firstSigner, err: wantErr}
|
||||
|
||||
oldBuilder := buildSSHAgentAuthMethodFunc
|
||||
t.Cleanup(func() {
|
||||
buildSSHAgentAuthMethodFunc = oldBuilder
|
||||
})
|
||||
|
||||
var buildCalls int
|
||||
buildSSHAgentAuthMethodFunc = func(timeouts sshAgentTimeouts) (ssh.AuthMethod, func(), error) {
|
||||
buildCalls++
|
||||
filteredSigners := filterSSHAgentSignersForRetry([]ssh.Signer{failingFirstSigner, secondSigner}, timeouts)
|
||||
if buildCalls == 1 {
|
||||
if len(filteredSigners) != 2 {
|
||||
t.Fatalf("first build signers=%d want 2", len(filteredSigners))
|
||||
}
|
||||
return ssh.PublicKeys(filteredSigners...), nil, nil
|
||||
}
|
||||
if len(filteredSigners) != 1 {
|
||||
t.Fatalf("retry build signers=%d want 1", len(filteredSigners))
|
||||
}
|
||||
if string(filteredSigners[0].PublicKey().Marshal()) != string(secondSigner.PublicKey().Marshal()) {
|
||||
t.Fatal("retry build did not skip failed signer")
|
||||
}
|
||||
return ssh.PublicKeys(filteredSigners...), nil, nil
|
||||
}
|
||||
|
||||
attempt := newSSHAgentAuthAttempt()
|
||||
attempt.begin()
|
||||
auth, cleanup, err := buildAuthMethodsWithAgentAttempt(LoginInput{
|
||||
AuthOrder: []AuthMethodKind{AuthMethodSSHAgent},
|
||||
}, attempt)
|
||||
if err != nil {
|
||||
t.Fatalf("first buildAuthMethodsWithAgentAttempt: %v", err)
|
||||
}
|
||||
if cleanup != nil {
|
||||
cleanup()
|
||||
}
|
||||
if len(auth) != 1 {
|
||||
t.Fatalf("first auth methods=%d want 1", len(auth))
|
||||
}
|
||||
if _, err := failingFirstSigner.Sign(rand.Reader, []byte("challenge")); !errors.Is(err, wantErr) {
|
||||
t.Fatalf("raw failing signer err=%v", err)
|
||||
}
|
||||
firstWrapped := filterSSHAgentSignersForRetry([]ssh.Signer{failingFirstSigner}, sshAgentTimeouts{
|
||||
SignFailure: attempt.recordSignFailure,
|
||||
})[0]
|
||||
if _, err := firstWrapped.Sign(rand.Reader, []byte("challenge")); !errors.Is(err, errRetrySSHAgentAuth) {
|
||||
t.Fatalf("wrapped failing signer err=%v want errRetrySSHAgentAuth", err)
|
||||
}
|
||||
|
||||
attempt.begin()
|
||||
auth, cleanup, err = buildAuthMethodsWithAgentAttempt(LoginInput{
|
||||
AuthOrder: []AuthMethodKind{AuthMethodSSHAgent},
|
||||
}, attempt)
|
||||
if err != nil {
|
||||
t.Fatalf("retry buildAuthMethodsWithAgentAttempt: %v", err)
|
||||
}
|
||||
if cleanup != nil {
|
||||
cleanup()
|
||||
}
|
||||
if len(auth) != 1 {
|
||||
t.Fatalf("retry auth methods=%d want 1", len(auth))
|
||||
}
|
||||
if buildCalls != 2 {
|
||||
t.Fatalf("build calls=%d want 2", buildCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrderSSHAgentSignersPrefersPriorityComment(t *testing.T) {
|
||||
plainSigner := mustGenerateTestSigner(t)
|
||||
prioritySigner := mustGenerateCommentedTestSigner(t, "priority=40")
|
||||
|
||||
ordered := orderSSHAgentSigners([]ssh.Signer{plainSigner, prioritySigner})
|
||||
if len(ordered) != 2 {
|
||||
t.Fatalf("ordered signers=%d want 2", len(ordered))
|
||||
}
|
||||
if string(ordered[0].PublicKey().Marshal()) != string(prioritySigner.PublicKey().Marshal()) {
|
||||
t.Fatalf("priority signer should be first, got %s", sshAgentSignerComment(ordered[0]))
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrderSSHAgentSignersPrefersCardKeys(t *testing.T) {
|
||||
plainSigner := mustGenerateTestSigner(t)
|
||||
cardSigner := mustGenerateCommentedTestSigner(t, "cardno:26_865_673")
|
||||
|
||||
ordered := orderSSHAgentSigners([]ssh.Signer{plainSigner, cardSigner})
|
||||
if len(ordered) != 2 {
|
||||
t.Fatalf("ordered signers=%d want 2", len(ordered))
|
||||
}
|
||||
if string(ordered[0].PublicKey().Marshal()) != string(cardSigner.PublicKey().Marshal()) {
|
||||
t.Fatalf("card signer should be first, got %s", sshAgentSignerComment(ordered[0]))
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrderSSHAgentSignersKeepsStableOrderWithoutHints(t *testing.T) {
|
||||
firstSigner := mustGenerateTestSigner(t)
|
||||
secondSigner := mustGenerateTestSigner(t)
|
||||
|
||||
ordered := orderSSHAgentSigners([]ssh.Signer{firstSigner, secondSigner})
|
||||
if len(ordered) != 2 {
|
||||
t.Fatalf("ordered signers=%d want 2", len(ordered))
|
||||
}
|
||||
if string(ordered[0].PublicKey().Marshal()) != string(firstSigner.PublicKey().Marshal()) {
|
||||
t.Fatalf("first signer changed order without hints")
|
||||
}
|
||||
if string(ordered[1].PublicKey().Marshal()) != string(secondSigner.PublicKey().Marshal()) {
|
||||
t.Fatalf("second signer changed order without hints")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHAgentSignerEmitsSignDebugWithoutChangingError(t *testing.T) {
|
||||
signer := mustGenerateTestSigner(t)
|
||||
wantErr := errors.New("agent refused operation")
|
||||
var debugCalls int
|
||||
wrapped := wrapSSHAgentSigner(&testFailingSigner{Signer: signer, err: wantErr}, sshAgentSignerOptions{
|
||||
Resolved: resolvedSSHAgentEndpoint{
|
||||
Endpoint: "/tmp/debug-agent.sock",
|
||||
Source: "identity-agent",
|
||||
Network: "unix",
|
||||
},
|
||||
Debug: func(event SSHAgentDebugEvent) {
|
||||
debugCalls++
|
||||
if event.Step != "auth" || event.Phase != "sign" {
|
||||
t.Fatalf("unexpected debug event: %+v", event)
|
||||
}
|
||||
if event.Endpoint != "/tmp/debug-agent.sock" || event.Source != "identity-agent" || event.Network != "unix" {
|
||||
t.Fatalf("unexpected endpoint details: %+v", event)
|
||||
}
|
||||
if event.Status != "error" || !errors.Is(event.Err, wantErr) {
|
||||
t.Fatalf("unexpected sign status: %+v", event)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
_, err := wrapped.Sign(rand.Reader, []byte("challenge"))
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Fatalf("Sign err=%v want original signer error", err)
|
||||
}
|
||||
if debugCalls != 1 {
|
||||
t.Fatalf("debug calls=%d want 1", debugCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHAgentRetrySignerPrefersRSASHA2(t *testing.T) {
|
||||
signer := mustGenerateRSATestSigner(t)
|
||||
spy := &testAlgorithmSpySigner{Signer: signer}
|
||||
wrapped, ok := wrapSSHAgentSignerForRetry(spy, func(ssh.PublicKey, error) {}).(ssh.AlgorithmSigner)
|
||||
if !ok {
|
||||
t.Fatal("wrapped signer does not implement AlgorithmSigner")
|
||||
}
|
||||
|
||||
signature, err := wrapped.SignWithAlgorithm(rand.Reader, []byte("challenge"), ssh.KeyAlgoRSA)
|
||||
if err != nil {
|
||||
t.Fatalf("SignWithAlgorithm: %v", err)
|
||||
}
|
||||
if spy.lastAlgorithm != ssh.KeyAlgoRSASHA256 {
|
||||
t.Fatalf("last algorithm=%q want %q", spy.lastAlgorithm, ssh.KeyAlgoRSASHA256)
|
||||
}
|
||||
if signature.Format != ssh.KeyAlgoRSASHA256 {
|
||||
t.Fatalf("signature format=%q want %q", signature.Format, ssh.KeyAlgoRSASHA256)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHAgentRetrySignerKeepsRestrictedRSA(t *testing.T) {
|
||||
signer := mustGenerateRSATestSigner(t)
|
||||
restricted, err := ssh.NewSignerWithAlgorithms(signer.(ssh.AlgorithmSigner), []string{ssh.KeyAlgoRSA})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSignerWithAlgorithms: %v", err)
|
||||
}
|
||||
spy := &testMultiAlgorithmSpySigner{
|
||||
testAlgorithmSpySigner: &testAlgorithmSpySigner{Signer: restricted},
|
||||
}
|
||||
wrapped, ok := wrapSSHAgentSignerForRetry(spy, func(ssh.PublicKey, error) {}).(ssh.AlgorithmSigner)
|
||||
if !ok {
|
||||
t.Fatal("wrapped signer does not implement AlgorithmSigner")
|
||||
}
|
||||
|
||||
signature, err := wrapped.SignWithAlgorithm(rand.Reader, []byte("challenge"), ssh.KeyAlgoRSA)
|
||||
if err != nil {
|
||||
t.Fatalf("SignWithAlgorithm: %v", err)
|
||||
}
|
||||
if spy.lastAlgorithm != ssh.KeyAlgoRSA {
|
||||
t.Fatalf("last algorithm=%q want %q", spy.lastAlgorithm, ssh.KeyAlgoRSA)
|
||||
}
|
||||
if signature.Format != ssh.KeyAlgoRSA {
|
||||
t.Fatalf("signature format=%q want %q", signature.Format, ssh.KeyAlgoRSA)
|
||||
}
|
||||
}
|
||||
|
||||
type deadlineSpyConn struct {
|
||||
net.Conn
|
||||
mu sync.Mutex
|
||||
deadlines []time.Time
|
||||
readErr error
|
||||
writeErr error
|
||||
}
|
||||
|
||||
type testFailingSigner struct {
|
||||
ssh.Signer
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *testFailingSigner) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) {
|
||||
return nil, s.err
|
||||
}
|
||||
|
||||
func (s *testFailingSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*ssh.Signature, error) {
|
||||
return nil, s.err
|
||||
}
|
||||
|
||||
type testAlgorithmSpySigner struct {
|
||||
ssh.Signer
|
||||
lastAlgorithm string
|
||||
}
|
||||
|
||||
func (s *testAlgorithmSpySigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*ssh.Signature, error) {
|
||||
s.lastAlgorithm = algorithm
|
||||
return s.Signer.(ssh.AlgorithmSigner).SignWithAlgorithm(rand, data, algorithm)
|
||||
}
|
||||
|
||||
type testMultiAlgorithmSpySigner struct {
|
||||
*testAlgorithmSpySigner
|
||||
}
|
||||
|
||||
func (s *testMultiAlgorithmSpySigner) Algorithms() []string {
|
||||
if multiAlgorithmSigner, ok := s.Signer.(ssh.MultiAlgorithmSigner); ok {
|
||||
return multiAlgorithmSigner.Algorithms()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func mustGenerateTestSigner(t *testing.T) ssh.Signer {
|
||||
t.Helper()
|
||||
_, key, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("generate test private key: %v", err)
|
||||
}
|
||||
signer, err := ssh.NewSignerFromKey(key)
|
||||
if err != nil {
|
||||
t.Fatalf("new test signer: %v", err)
|
||||
}
|
||||
return signer
|
||||
}
|
||||
|
||||
func mustGenerateCommentedTestSigner(t *testing.T, comment string) ssh.Signer {
|
||||
t.Helper()
|
||||
baseSigner := mustGenerateTestSigner(t)
|
||||
publicKey := baseSigner.PublicKey()
|
||||
return &commentedTestSigner{
|
||||
Signer: baseSigner,
|
||||
publicKey: &sshagent.Key{
|
||||
Format: publicKey.Type(),
|
||||
Blob: publicKey.Marshal(),
|
||||
Comment: comment,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type commentedTestSigner struct {
|
||||
ssh.Signer
|
||||
publicKey ssh.PublicKey
|
||||
}
|
||||
|
||||
func (s *commentedTestSigner) PublicKey() ssh.PublicKey {
|
||||
return s.publicKey
|
||||
}
|
||||
|
||||
func mustGenerateRSATestSigner(t *testing.T) ssh.Signer {
|
||||
t.Helper()
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatalf("generate rsa test private key: %v", err)
|
||||
}
|
||||
signer, err := ssh.NewSignerFromKey(key)
|
||||
if err != nil {
|
||||
t.Fatalf("new rsa test signer: %v", err)
|
||||
}
|
||||
return signer
|
||||
}
|
||||
|
||||
func (c *deadlineSpyConn) SetDeadline(deadline time.Time) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.deadlines = append(c.deadlines, deadline)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *deadlineSpyConn) deadlineCount() int {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return len(c.deadlines)
|
||||
}
|
||||
|
||||
func (c *deadlineSpyConn) firstDeadline() time.Time {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.deadlines[0]
|
||||
}
|
||||
|
||||
func (c *deadlineSpyConn) Read(p []byte) (int, error) {
|
||||
if c.readErr != nil {
|
||||
return 0, c.readErr
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (c *deadlineSpyConn) Write(p []byte) (int, error) {
|
||||
if c.writeErr != nil {
|
||||
return 0, c.writeErr
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func TestWrapSSHAgentConnWithDeadlineSetsReadDeadline(t *testing.T) {
|
||||
spy := &deadlineSpyConn{readErr: io.EOF}
|
||||
conn := wrapSSHAgentConnWithDeadline(spy, 2*time.Second)
|
||||
buf := make([]byte, 1)
|
||||
if _, err := conn.Read(buf); !errors.Is(err, io.EOF) {
|
||||
t.Fatalf("Read err=%v", err)
|
||||
}
|
||||
if spy.deadlineCount() != 1 {
|
||||
t.Fatalf("deadlines=%d want 1", spy.deadlineCount())
|
||||
}
|
||||
if firstDeadline := spy.firstDeadline(); time.Until(firstDeadline) <= 0 {
|
||||
t.Fatalf("deadline=%v should be in the future", firstDeadline)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrapSSHAgentConnWithDeadlineSetsWriteDeadline(t *testing.T) {
|
||||
spy := &deadlineSpyConn{}
|
||||
conn := wrapSSHAgentConnWithDeadline(spy, 2*time.Second)
|
||||
if _, err := conn.Write([]byte("x")); err != nil {
|
||||
t.Fatalf("Write err=%v", err)
|
||||
}
|
||||
if spy.deadlineCount() != 1 {
|
||||
t.Fatalf("deadlines=%d want 1", spy.deadlineCount())
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveSSHAgentEndpointUsesIdentityAgent(t *testing.T) {
|
||||
t.Setenv("SSH_AUTH_SOCK", "/tmp/env-agent.sock")
|
||||
resolved, err := resolveSSHAgentEndpoint(sshAgentDialOptions{Endpoint: " /tmp/identity-agent.sock "})
|
||||
if err != nil {
|
||||
t.Fatalf("resolveSSHAgentEndpoint: %v", err)
|
||||
}
|
||||
if resolved.Endpoint != "/tmp/identity-agent.sock" {
|
||||
t.Fatalf("endpoint=%q", resolved.Endpoint)
|
||||
}
|
||||
if resolved.Source != "identity-agent" {
|
||||
t.Fatalf("source=%q", resolved.Source)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveSSHAgentEndpointUsesSSHAuthSock(t *testing.T) {
|
||||
t.Setenv("SSH_AUTH_SOCK", "/tmp/env-agent.sock")
|
||||
resolved, err := resolveSSHAgentEndpoint(sshAgentDialOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("resolveSSHAgentEndpoint: %v", err)
|
||||
}
|
||||
if resolved.Endpoint != "/tmp/env-agent.sock" {
|
||||
t.Fatalf("endpoint=%q", resolved.Endpoint)
|
||||
}
|
||||
if resolved.Source != "SSH_AUTH_SOCK" {
|
||||
t.Fatalf("source=%q", resolved.Source)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSSHAgentAuthMethodTimesOutWhenAgentDoesNotRespond(t *testing.T) {
|
||||
server, client := net.Pipe()
|
||||
defer server.Close()
|
||||
|
||||
oldDialResolvedSSHAgent := dialResolvedSSHAgentFunc
|
||||
t.Cleanup(func() {
|
||||
dialResolvedSSHAgentFunc = oldDialResolvedSSHAgent
|
||||
})
|
||||
dialResolvedSSHAgentFunc = func(resolved resolvedSSHAgentEndpoint, timeout time.Duration) (net.Conn, error) {
|
||||
return client, nil
|
||||
}
|
||||
|
||||
_, cleanup, err := buildSSHAgentAuthMethod(sshAgentTimeouts{
|
||||
Operation: 20 * time.Millisecond,
|
||||
Endpoint: "/tmp/hung-agent.sock",
|
||||
})
|
||||
if cleanup != nil {
|
||||
cleanup()
|
||||
}
|
||||
if !errors.Is(err, ErrSSHAgentTimeout) {
|
||||
t.Fatalf("err=%v want ErrSSHAgentTimeout", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSSHAgentAuthMethodEmitsDebugEvents(t *testing.T) {
|
||||
socketPath := tempUnixSocketPath(t)
|
||||
listener, err := net.Listen("unix", socketPath)
|
||||
if err != nil {
|
||||
t.Fatalf("listen unix: %v", err)
|
||||
}
|
||||
defer listener.Close()
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = conn.Close()
|
||||
}()
|
||||
|
||||
var events []SSHAgentDebugEvent
|
||||
_, _, _ = buildSSHAgentAuthMethod(sshAgentTimeouts{
|
||||
Dial: time.Second,
|
||||
Operation: time.Second,
|
||||
Endpoint: socketPath,
|
||||
Debug: func(event SSHAgentDebugEvent) {
|
||||
events = append(events, event)
|
||||
},
|
||||
})
|
||||
<-done
|
||||
|
||||
if len(events) == 0 {
|
||||
t.Fatal("expected debug events")
|
||||
}
|
||||
if events[0].Step != "auth" || events[0].Phase != "dial" {
|
||||
t.Fatalf("unexpected first event: %+v", events[0])
|
||||
}
|
||||
if events[0].Endpoint != socketPath || events[0].Source != "identity-agent" {
|
||||
t.Fatalf("unexpected endpoint event: %+v", events[0])
|
||||
}
|
||||
}
|
||||
|
||||
func tempUnixSocketPath(t *testing.T) string {
|
||||
t.Helper()
|
||||
path := t.TempDir() + "/agent.sock"
|
||||
t.Cleanup(func() {
|
||||
_ = os.Remove(path)
|
||||
})
|
||||
return path
|
||||
}
|
||||
+29
-5
@@ -9,6 +9,14 @@ import (
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
var newSSHSession = func(client *ssh.Client) (*ssh.Session, error) {
|
||||
return client.NewSession()
|
||||
}
|
||||
|
||||
var requestSessionPTY = func(session *ssh.Session, config TerminalConfig) error {
|
||||
return session.RequestPty(config.Term, config.Rows, config.Columns, config.Modes)
|
||||
}
|
||||
|
||||
func (s *StarSSH) Close() error {
|
||||
return s.closeTransport(true)
|
||||
}
|
||||
@@ -22,7 +30,15 @@ func (s *StarSSH) NewExecSession() (*ssh.Session, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewExecSession(client)
|
||||
session, err := NewExecSession(client)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.maybeRequestAgentForwarding(session); err != nil {
|
||||
_ = session.Close()
|
||||
return nil, err
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (s *StarSSH) NewPTYSession(config *TerminalConfig) (*ssh.Session, error) {
|
||||
@@ -30,7 +46,15 @@ func (s *StarSSH) NewPTYSession(config *TerminalConfig) (*ssh.Session, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewPTYSession(client, config)
|
||||
session, err := NewPTYSession(client, config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.maybeRequestAgentForwarding(session); err != nil {
|
||||
_ = session.Close()
|
||||
return nil, err
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func NewTransferSession(client *ssh.Client) (*ssh.Session, error) {
|
||||
@@ -41,7 +65,7 @@ func NewExecSession(client *ssh.Client) (*ssh.Session, error) {
|
||||
if client == nil {
|
||||
return nil, errors.New("ssh client is nil")
|
||||
}
|
||||
return client.NewSession()
|
||||
return newSSHSession(client)
|
||||
}
|
||||
|
||||
func NewSession(client *ssh.Client) (*ssh.Session, error) {
|
||||
@@ -53,13 +77,13 @@ func NewPTYSession(client *ssh.Client, config *TerminalConfig) (*ssh.Session, er
|
||||
return nil, errors.New("ssh client is nil")
|
||||
}
|
||||
|
||||
session, err := client.NewSession()
|
||||
session, err := newSSHSession(client)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cfg := normalizeTerminalConfig(config)
|
||||
if err := session.RequestPty(cfg.Term, cfg.Rows, cfg.Columns, cfg.Modes); err != nil {
|
||||
if err := requestSessionPTY(session, cfg); err != nil {
|
||||
_ = session.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,668 @@
|
||||
package starssh
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
sshagent "golang.org/x/crypto/ssh/agent"
|
||||
)
|
||||
|
||||
var errSSHAgentUnavailable = errors.New("ssh-agent unavailable")
|
||||
var errRetrySSHAgentAuth = errors.New("retry ssh-agent auth")
|
||||
var buildSSHAgentAuthMethodFunc = buildSSHAgentAuthMethod
|
||||
|
||||
type sshAgentTimeouts struct {
|
||||
Dial time.Duration
|
||||
Operation time.Duration
|
||||
Forward time.Duration
|
||||
Endpoint string
|
||||
Resolved resolvedSSHAgentEndpoint
|
||||
Debug SSHAgentDebugFunc
|
||||
SkipFingerprints map[string]struct{}
|
||||
SignFailure func(ssh.PublicKey, error)
|
||||
}
|
||||
|
||||
type sshAgentAuthAttempt struct {
|
||||
mu sync.Mutex
|
||||
skipFingerprints map[string]struct{}
|
||||
retryRequested bool
|
||||
}
|
||||
|
||||
var defaultAuthOrder = []AuthMethodKind{
|
||||
AuthMethodSSHAgent,
|
||||
AuthMethodPrivateKey,
|
||||
AuthMethodPassword,
|
||||
AuthMethodKeyboardInteractive,
|
||||
}
|
||||
|
||||
func effectiveSSHAgentTimeout(info LoginInput) time.Duration {
|
||||
switch {
|
||||
case info.SSHAgentTimeout < 0:
|
||||
return 0
|
||||
case info.SSHAgentTimeout > 0:
|
||||
return info.SSHAgentTimeout
|
||||
default:
|
||||
return defaultSSHAgentTimeout
|
||||
}
|
||||
}
|
||||
|
||||
func effectiveSSHAgentTimeouts(info LoginInput) sshAgentTimeouts {
|
||||
return sshAgentTimeouts{
|
||||
Dial: effectiveDialTimeout(info),
|
||||
Operation: effectiveSSHAgentTimeout(info),
|
||||
Forward: effectiveSSHAgentForwardTimeout(info),
|
||||
Endpoint: info.IdentityAgent,
|
||||
Debug: info.SSHAgentDebug,
|
||||
}
|
||||
}
|
||||
|
||||
func effectiveSSHAgentForwardTimeout(info LoginInput) time.Duration {
|
||||
if info.SSHAgentForwardTimeout > 0 {
|
||||
return info.SSHAgentForwardTimeout
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func buildAuthMethods(info LoginInput) ([]ssh.AuthMethod, func(), error) {
|
||||
return buildAuthMethodsWithAgentAttempt(info, nil)
|
||||
}
|
||||
|
||||
func buildAuthMethodsWithAgentAttempt(info LoginInput, agentAttempt *sshAgentAuthAttempt) ([]ssh.AuthMethod, func(), error) {
|
||||
order, err := normalizeAuthOrder(info.AuthOrder)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
auth := make([]ssh.AuthMethod, 0, len(order))
|
||||
var agentErr error
|
||||
var cleanupFuncs []func()
|
||||
|
||||
for _, methodKind := range order {
|
||||
switch methodKind {
|
||||
case AuthMethodPrivateKey:
|
||||
method, err := buildPrivateKeyAuthMethod(info, agentAttempt)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if method != nil {
|
||||
auth = append(auth, method)
|
||||
}
|
||||
case AuthMethodPassword:
|
||||
method := buildPasswordAuthMethod(info.Password, info.PasswordCallback, agentAttempt)
|
||||
if method != nil {
|
||||
auth = append(auth, method)
|
||||
}
|
||||
case AuthMethodKeyboardInteractive:
|
||||
method := buildKeyboardInteractiveAuthMethod(info.Password, info.PasswordCallback, info.KeyboardInteractiveCallback, agentAttempt)
|
||||
if method != nil {
|
||||
auth = append(auth, method)
|
||||
}
|
||||
case AuthMethodSSHAgent:
|
||||
if info.DisableSSHAgent {
|
||||
continue
|
||||
}
|
||||
timeouts := effectiveSSHAgentTimeouts(info)
|
||||
if agentAttempt != nil {
|
||||
timeouts.SkipFingerprints = agentAttempt.skipSnapshot()
|
||||
timeouts.SignFailure = agentAttempt.recordSignFailure
|
||||
}
|
||||
agentMethod, cleanup, err := buildSSHAgentAuthMethodFunc(timeouts)
|
||||
if err != nil {
|
||||
agentErr = err
|
||||
continue
|
||||
}
|
||||
if agentMethod != nil {
|
||||
auth = append(auth, agentMethod)
|
||||
}
|
||||
if cleanup != nil {
|
||||
cleanupFuncs = append(cleanupFuncs, cleanup)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(auth) == 0 {
|
||||
if agentErr != nil {
|
||||
return nil, nil, fmt.Errorf("no authentication method provided; ssh-agent unavailable: %w", agentErr)
|
||||
}
|
||||
return nil, nil, errors.New("no authentication method provided: password, private key, or ssh-agent is required")
|
||||
}
|
||||
|
||||
return auth, composeCleanup(cleanupFuncs...), nil
|
||||
}
|
||||
|
||||
func normalizeAuthOrder(order []AuthMethodKind) ([]AuthMethodKind, error) {
|
||||
if len(order) == 0 {
|
||||
return append([]AuthMethodKind(nil), defaultAuthOrder...), nil
|
||||
}
|
||||
|
||||
normalized := make([]AuthMethodKind, 0, len(order))
|
||||
seen := make(map[AuthMethodKind]struct{}, len(order))
|
||||
for _, raw := range order {
|
||||
kind := AuthMethodKind(strings.ToLower(strings.TrimSpace(string(raw))))
|
||||
if kind == "" {
|
||||
return nil, errors.New("auth order contains an empty auth method")
|
||||
}
|
||||
if !isSupportedAuthMethodKind(kind) {
|
||||
return nil, fmt.Errorf("unsupported auth method %q", raw)
|
||||
}
|
||||
if _, exists := seen[kind]; exists {
|
||||
continue
|
||||
}
|
||||
seen[kind] = struct{}{}
|
||||
normalized = append(normalized, kind)
|
||||
}
|
||||
|
||||
if len(normalized) == 0 {
|
||||
return nil, errors.New("auth order is empty")
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func isSupportedAuthMethodKind(kind AuthMethodKind) bool {
|
||||
switch kind {
|
||||
case AuthMethodPrivateKey, AuthMethodPassword, AuthMethodKeyboardInteractive, AuthMethodSSHAgent:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func shouldRetrySSHAgentAuth(info LoginInput, order []AuthMethodKind) bool {
|
||||
if info.DisableSSHAgent {
|
||||
return false
|
||||
}
|
||||
for _, methodKind := range order {
|
||||
if methodKind == AuthMethodSSHAgent {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func buildPrivateKeyAuthMethod(info LoginInput, agentAttempt *sshAgentAuthAttempt) (ssh.AuthMethod, error) {
|
||||
if strings.TrimSpace(info.Prikey) == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
pemBytes := []byte(info.Prikey)
|
||||
if info.PrikeyPwd == "" {
|
||||
signer, err := ssh.ParsePrivateKey(pemBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ssh.PublicKeysCallback(privateKeySignersCallback(signer, agentAttempt)), nil
|
||||
}
|
||||
|
||||
signer, err := ssh.ParsePrivateKeyWithPassphrase(pemBytes, []byte(info.PrikeyPwd))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ssh.PublicKeysCallback(privateKeySignersCallback(signer, agentAttempt)), nil
|
||||
}
|
||||
|
||||
func privateKeySignersCallback(signer ssh.Signer, agentAttempt *sshAgentAuthAttempt) func() ([]ssh.Signer, error) {
|
||||
return func() ([]ssh.Signer, error) {
|
||||
if err := checkSSHAgentRetryPending(agentAttempt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []ssh.Signer{signer}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func buildPasswordAuthMethod(password string, callback func() (string, error), agentAttempt *sshAgentAuthAttempt) ssh.AuthMethod {
|
||||
if password == "" && callback == nil {
|
||||
return nil
|
||||
}
|
||||
return ssh.PasswordCallback(func() (string, error) {
|
||||
if err := checkSSHAgentRetryPending(agentAttempt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if password != "" {
|
||||
return password, nil
|
||||
}
|
||||
return callback()
|
||||
})
|
||||
}
|
||||
|
||||
func buildKeyboardInteractiveAuthMethod(
|
||||
password string,
|
||||
passwordCallback func() (string, error),
|
||||
challenge ssh.KeyboardInteractiveChallenge,
|
||||
agentAttempt *sshAgentAuthAttempt,
|
||||
) ssh.AuthMethod {
|
||||
if challenge != nil {
|
||||
return ssh.KeyboardInteractive(func(user, instruction string, questions []string, echos []bool) ([]string, error) {
|
||||
if err := checkSSHAgentRetryPending(agentAttempt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return challenge(user, instruction, questions, echos)
|
||||
})
|
||||
}
|
||||
if password == "" && passwordCallback == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
keyboardInteractiveChallenge := func(user, instruction string, questions []string, echos []bool) ([]string, error) {
|
||||
if err := checkSSHAgentRetryPending(agentAttempt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(questions) == 0 {
|
||||
return []string{}, nil
|
||||
}
|
||||
|
||||
answer := password
|
||||
if answer == "" {
|
||||
var err error
|
||||
answer, err = passwordCallback()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
answers := make([]string, len(questions))
|
||||
for i := range questions {
|
||||
answers[i] = answer
|
||||
}
|
||||
return answers, nil
|
||||
}
|
||||
return ssh.KeyboardInteractive(keyboardInteractiveChallenge)
|
||||
}
|
||||
|
||||
func buildSSHAgentAuthMethod(timeouts sshAgentTimeouts) (ssh.AuthMethod, func(), error) {
|
||||
conn, resolved, err := dialSSHAgentWithDebug("auth", timeouts)
|
||||
if err != nil {
|
||||
if errors.Is(err, errSSHAgentUnavailable) {
|
||||
return nil, nil, nil
|
||||
}
|
||||
return nil, nil, err
|
||||
}
|
||||
if conn == nil {
|
||||
return nil, nil, nil
|
||||
}
|
||||
conn = wrapSSHAgentConnWithDeadline(conn, timeouts.Operation)
|
||||
|
||||
started := time.Now()
|
||||
signers, err := sshagent.NewClient(conn).Signers()
|
||||
err = normalizeSSHAgentError(err)
|
||||
logSSHAgentDebug(timeouts.Debug, SSHAgentDebugEvent{
|
||||
Step: "auth",
|
||||
Source: resolved.Source,
|
||||
Endpoint: resolved.Endpoint,
|
||||
Network: resolved.Network,
|
||||
Phase: "list",
|
||||
Status: debugStatus(err),
|
||||
Duration: time.Since(started),
|
||||
KeyCount: len(signers),
|
||||
Err: err,
|
||||
})
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
if len(signers) == 0 {
|
||||
_ = conn.Close()
|
||||
return nil, nil, errors.New("ssh-agent has no loaded keys")
|
||||
}
|
||||
|
||||
timeouts.Resolved = resolved
|
||||
orderedSigners := orderSSHAgentSigners(signers)
|
||||
filteredSigners := filterSSHAgentSignersForRetry(orderedSigners, timeouts)
|
||||
if len(filteredSigners) == 0 {
|
||||
_ = conn.Close()
|
||||
return nil, nil, errors.New("ssh-agent has no usable keys")
|
||||
}
|
||||
|
||||
return ssh.PublicKeys(filteredSigners...), func() {
|
||||
_ = conn.Close()
|
||||
}, nil
|
||||
}
|
||||
|
||||
func orderSSHAgentSigners(signers []ssh.Signer) []ssh.Signer {
|
||||
type orderedSigner struct {
|
||||
signer ssh.Signer
|
||||
index int
|
||||
score int
|
||||
comment string
|
||||
}
|
||||
|
||||
ordered := make([]orderedSigner, 0, len(signers))
|
||||
for index, signer := range signers {
|
||||
if signer == nil || signer.PublicKey() == nil {
|
||||
continue
|
||||
}
|
||||
ordered = append(ordered, orderedSigner{
|
||||
signer: signer,
|
||||
index: index,
|
||||
score: sshAgentSignerPriority(signer),
|
||||
comment: sshAgentSignerComment(signer),
|
||||
})
|
||||
}
|
||||
|
||||
sort.SliceStable(ordered, func(i, j int) bool {
|
||||
if ordered[i].score != ordered[j].score {
|
||||
return ordered[i].score > ordered[j].score
|
||||
}
|
||||
return ordered[i].index < ordered[j].index
|
||||
})
|
||||
|
||||
result := make([]ssh.Signer, 0, len(ordered))
|
||||
for _, item := range ordered {
|
||||
result = append(result, item.signer)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func sshAgentSignerComment(signer ssh.Signer) string {
|
||||
if signer == nil {
|
||||
return ""
|
||||
}
|
||||
if key, ok := signer.PublicKey().(*sshagent.Key); ok {
|
||||
return key.Comment
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func sshAgentSignerPriority(signer ssh.Signer) int {
|
||||
comment := strings.TrimSpace(sshAgentSignerComment(signer))
|
||||
if comment == "" {
|
||||
return 0
|
||||
}
|
||||
|
||||
score := 0
|
||||
if priority, ok := parseSSHAgentSignerPriority(comment); ok {
|
||||
score += 100000 + priority*1000
|
||||
}
|
||||
|
||||
lower := strings.ToLower(comment)
|
||||
if strings.Contains(lower, "current") {
|
||||
score += 400
|
||||
}
|
||||
if strings.Contains(lower, "cardno:") {
|
||||
score += 300
|
||||
}
|
||||
if strings.Contains(lower, "card ") || strings.Contains(lower, " card") || strings.Contains(lower, "card:") {
|
||||
score += 100
|
||||
}
|
||||
if strings.Contains(lower, "openpgp") || strings.Contains(lower, "gpg") {
|
||||
score += 50
|
||||
}
|
||||
return score
|
||||
}
|
||||
|
||||
func parseSSHAgentSignerPriority(comment string) (int, bool) {
|
||||
lower := strings.ToLower(comment)
|
||||
index := strings.Index(lower, "priority=")
|
||||
if index < 0 {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
value := strings.TrimSpace(comment[index+len("priority="):])
|
||||
if value == "" {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
end := 0
|
||||
for end < len(value) {
|
||||
ch := value[end]
|
||||
if ch == '+' || ch == '-' || (ch >= '0' && ch <= '9') {
|
||||
end++
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
if end == 0 {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
priority, err := strconv.Atoi(value[:end])
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
return priority, true
|
||||
}
|
||||
|
||||
func filterSSHAgentSignersForRetry(signers []ssh.Signer, timeouts sshAgentTimeouts) []ssh.Signer {
|
||||
filteredSigners := make([]ssh.Signer, 0, len(signers))
|
||||
for _, signer := range signers {
|
||||
if signer == nil {
|
||||
continue
|
||||
}
|
||||
publicKey := signer.PublicKey()
|
||||
if publicKey == nil {
|
||||
continue
|
||||
}
|
||||
if _, skip := timeouts.SkipFingerprints[ssh.FingerprintSHA256(publicKey)]; skip {
|
||||
continue
|
||||
}
|
||||
if timeouts.SignFailure == nil && timeouts.Debug == nil {
|
||||
filteredSigners = append(filteredSigners, signer)
|
||||
continue
|
||||
}
|
||||
filteredSigners = append(filteredSigners, wrapSSHAgentSigner(signer, sshAgentSignerOptions{
|
||||
Resolved: timeouts.Resolved,
|
||||
Debug: timeouts.Debug,
|
||||
SignFailure: timeouts.SignFailure,
|
||||
}))
|
||||
}
|
||||
return filteredSigners
|
||||
}
|
||||
|
||||
func newSSHAgentAuthAttempt() *sshAgentAuthAttempt {
|
||||
return &sshAgentAuthAttempt{
|
||||
skipFingerprints: make(map[string]struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func (a *sshAgentAuthAttempt) begin() {
|
||||
if a == nil {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.retryRequested = false
|
||||
}
|
||||
|
||||
func (a *sshAgentAuthAttempt) skipSnapshot() map[string]struct{} {
|
||||
if a == nil {
|
||||
return nil
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if len(a.skipFingerprints) == 0 {
|
||||
return nil
|
||||
}
|
||||
snapshot := make(map[string]struct{}, len(a.skipFingerprints))
|
||||
for fingerprint := range a.skipFingerprints {
|
||||
snapshot[fingerprint] = struct{}{}
|
||||
}
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func (a *sshAgentAuthAttempt) recordSignFailure(publicKey ssh.PublicKey, err error) {
|
||||
_ = err
|
||||
if a == nil || publicKey == nil {
|
||||
return
|
||||
}
|
||||
a.skipFingerprint(ssh.FingerprintSHA256(publicKey))
|
||||
}
|
||||
|
||||
func (a *sshAgentAuthAttempt) skipFingerprint(fingerprint string) {
|
||||
if a == nil {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.retryRequested = true
|
||||
if fingerprint != "" {
|
||||
a.skipFingerprints[fingerprint] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *sshAgentAuthAttempt) shouldRetry() bool {
|
||||
if a == nil {
|
||||
return false
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.retryRequested
|
||||
}
|
||||
|
||||
func checkSSHAgentRetryPending(agentAttempt *sshAgentAuthAttempt) error {
|
||||
if agentAttempt != nil && agentAttempt.shouldRetry() {
|
||||
return errRetrySSHAgentAuth
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type sshAgentRetrySigner struct {
|
||||
signer ssh.Signer
|
||||
publicKey ssh.PublicKey
|
||||
options sshAgentSignerOptions
|
||||
}
|
||||
|
||||
type sshAgentRetryAlgorithmSigner struct {
|
||||
sshAgentRetrySigner
|
||||
algorithmSigner ssh.AlgorithmSigner
|
||||
}
|
||||
|
||||
type sshAgentRetryMultiAlgorithmSigner struct {
|
||||
sshAgentRetryAlgorithmSigner
|
||||
multiAlgorithmSigner ssh.MultiAlgorithmSigner
|
||||
}
|
||||
|
||||
type sshAgentSignerOptions struct {
|
||||
Resolved resolvedSSHAgentEndpoint
|
||||
Debug SSHAgentDebugFunc
|
||||
SignFailure func(ssh.PublicKey, error)
|
||||
}
|
||||
|
||||
func wrapSSHAgentSignerForRetry(signer ssh.Signer, onFailure func(ssh.PublicKey, error)) ssh.Signer {
|
||||
return wrapSSHAgentSigner(signer, sshAgentSignerOptions{SignFailure: onFailure})
|
||||
}
|
||||
|
||||
func wrapSSHAgentSigner(signer ssh.Signer, options sshAgentSignerOptions) ssh.Signer {
|
||||
publicKey := signer.PublicKey()
|
||||
base := sshAgentRetrySigner{
|
||||
signer: signer,
|
||||
publicKey: publicKey,
|
||||
options: options,
|
||||
}
|
||||
if multiAlgorithmSigner, ok := signer.(ssh.MultiAlgorithmSigner); ok {
|
||||
return &sshAgentRetryMultiAlgorithmSigner{
|
||||
sshAgentRetryAlgorithmSigner: sshAgentRetryAlgorithmSigner{
|
||||
sshAgentRetrySigner: base,
|
||||
algorithmSigner: multiAlgorithmSigner,
|
||||
},
|
||||
multiAlgorithmSigner: multiAlgorithmSigner,
|
||||
}
|
||||
}
|
||||
if algorithmSigner, ok := signer.(ssh.AlgorithmSigner); ok {
|
||||
return &sshAgentRetryAlgorithmSigner{
|
||||
sshAgentRetrySigner: base,
|
||||
algorithmSigner: algorithmSigner,
|
||||
}
|
||||
}
|
||||
return &base
|
||||
}
|
||||
|
||||
func (s *sshAgentRetrySigner) PublicKey() ssh.PublicKey {
|
||||
return s.publicKey
|
||||
}
|
||||
|
||||
func (s *sshAgentRetrySigner) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) {
|
||||
started := time.Now()
|
||||
signature, err := s.signer.Sign(rand, data)
|
||||
return signature, s.finishSign(started, err)
|
||||
}
|
||||
|
||||
func (s *sshAgentRetrySigner) finishSign(started time.Time, err error) error {
|
||||
err = normalizeSSHAgentError(err)
|
||||
s.logSignDebug(started, err)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if s.options.SignFailure != nil {
|
||||
s.options.SignFailure(s.publicKey, err)
|
||||
return wrapSSHAgentSignError(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *sshAgentRetrySigner) logSignDebug(started time.Time, err error) {
|
||||
if s == nil || s.options.Debug == nil {
|
||||
return
|
||||
}
|
||||
logSSHAgentDebug(s.options.Debug, SSHAgentDebugEvent{
|
||||
Step: "auth",
|
||||
Source: s.options.Resolved.Source,
|
||||
Endpoint: s.options.Resolved.Endpoint,
|
||||
Network: s.options.Resolved.Network,
|
||||
Phase: "sign",
|
||||
Status: debugStatus(err),
|
||||
Duration: time.Since(started),
|
||||
Err: err,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *sshAgentRetryAlgorithmSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*ssh.Signature, error) {
|
||||
algorithm = preferredSSHAgentSignAlgorithm(s.publicKey, algorithm, nil)
|
||||
started := time.Now()
|
||||
signature, err := s.algorithmSigner.SignWithAlgorithm(rand, data, algorithm)
|
||||
return signature, s.finishSign(started, err)
|
||||
}
|
||||
|
||||
func (s *sshAgentRetryMultiAlgorithmSigner) Algorithms() []string {
|
||||
return s.multiAlgorithmSigner.Algorithms()
|
||||
}
|
||||
|
||||
func (s *sshAgentRetryMultiAlgorithmSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*ssh.Signature, error) {
|
||||
algorithm = preferredSSHAgentSignAlgorithm(s.publicKey, algorithm, s.multiAlgorithmSigner.Algorithms())
|
||||
started := time.Now()
|
||||
signature, err := s.multiAlgorithmSigner.SignWithAlgorithm(rand, data, algorithm)
|
||||
return signature, s.finishSign(started, err)
|
||||
}
|
||||
|
||||
func preferredSSHAgentSignAlgorithm(publicKey ssh.PublicKey, requested string, algorithms []string) string {
|
||||
if publicKey == nil || publicKey.Type() != ssh.KeyAlgoRSA || requested != ssh.KeyAlgoRSA {
|
||||
return requested
|
||||
}
|
||||
if len(algorithms) == 0 {
|
||||
return ssh.KeyAlgoRSASHA256
|
||||
}
|
||||
for _, algorithm := range algorithms {
|
||||
if algorithm == ssh.KeyAlgoRSA {
|
||||
break
|
||||
}
|
||||
if algorithm == ssh.KeyAlgoRSASHA256 || algorithm == ssh.KeyAlgoRSASHA512 {
|
||||
return algorithm
|
||||
}
|
||||
}
|
||||
return requested
|
||||
}
|
||||
|
||||
func wrapSSHAgentSignError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%w: %v", errRetrySSHAgentAuth, normalizeSSHAgentError(err))
|
||||
}
|
||||
|
||||
func composeCleanup(funcs ...func()) func() {
|
||||
if len(funcs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return func() {
|
||||
for i := len(funcs) - 1; i >= 0; i-- {
|
||||
if funcs[i] != nil {
|
||||
funcs[i]()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package starssh
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrSSHAgentTimeout = errors.New("ssh-agent timeout")
|
||||
var dialResolvedSSHAgentFunc = dialResolvedSSHAgent
|
||||
|
||||
type sshAgentDialOptions struct {
|
||||
Endpoint string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
type resolvedSSHAgentEndpoint struct {
|
||||
Endpoint string
|
||||
Source string
|
||||
Network string
|
||||
}
|
||||
|
||||
type deadlineAgentConn struct {
|
||||
net.Conn
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func resolveSSHAgentEndpoint(options sshAgentDialOptions) (resolvedSSHAgentEndpoint, error) {
|
||||
endpoint := strings.TrimSpace(options.Endpoint)
|
||||
if endpoint != "" {
|
||||
return resolvedSSHAgentEndpoint{
|
||||
Endpoint: endpoint,
|
||||
Source: "identity-agent",
|
||||
Network: defaultSSHAgentNetwork(endpoint),
|
||||
}, nil
|
||||
}
|
||||
|
||||
endpoint = strings.TrimSpace(os.Getenv("SSH_AUTH_SOCK"))
|
||||
if endpoint != "" {
|
||||
return resolvedSSHAgentEndpoint{
|
||||
Endpoint: endpoint,
|
||||
Source: "SSH_AUTH_SOCK",
|
||||
Network: defaultSSHAgentNetwork(endpoint),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return defaultSSHAgentEndpoint()
|
||||
}
|
||||
|
||||
func dialSSHAgent(options sshAgentDialOptions) (net.Conn, resolvedSSHAgentEndpoint, error) {
|
||||
resolved, err := resolveSSHAgentEndpoint(options)
|
||||
if err != nil {
|
||||
return nil, resolvedSSHAgentEndpoint{}, err
|
||||
}
|
||||
|
||||
conn, err := dialResolvedSSHAgentFunc(resolved, options.Timeout)
|
||||
if isTimeoutError(err) {
|
||||
err = fmt.Errorf("%w: %v", ErrSSHAgentTimeout, err)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, resolved, err
|
||||
}
|
||||
return conn, resolved, nil
|
||||
}
|
||||
|
||||
func dialSSHAgentWithDebug(step string, timeouts sshAgentTimeouts) (net.Conn, resolvedSSHAgentEndpoint, error) {
|
||||
options := sshAgentDialOptions{
|
||||
Endpoint: timeouts.Endpoint,
|
||||
Timeout: timeouts.Dial,
|
||||
}
|
||||
started := time.Now()
|
||||
conn, resolved, err := dialSSHAgent(options)
|
||||
logSSHAgentDebug(timeouts.Debug, SSHAgentDebugEvent{
|
||||
Step: step,
|
||||
Source: resolved.Source,
|
||||
Endpoint: resolved.Endpoint,
|
||||
Network: resolved.Network,
|
||||
Phase: "dial",
|
||||
Status: debugStatus(err),
|
||||
Duration: time.Since(started),
|
||||
Err: err,
|
||||
})
|
||||
return conn, resolved, err
|
||||
}
|
||||
|
||||
func logSSHAgentDebug(debug SSHAgentDebugFunc, event SSHAgentDebugEvent) {
|
||||
if debug == nil {
|
||||
return
|
||||
}
|
||||
debug(event)
|
||||
}
|
||||
|
||||
func debugStatus(err error) string {
|
||||
if err != nil {
|
||||
return "error"
|
||||
}
|
||||
return "ok"
|
||||
}
|
||||
|
||||
func wrapSSHAgentConnWithDeadline(conn net.Conn, timeout time.Duration) net.Conn {
|
||||
if conn == nil || timeout <= 0 {
|
||||
return conn
|
||||
}
|
||||
return &deadlineAgentConn{Conn: conn, timeout: timeout}
|
||||
}
|
||||
|
||||
func (c *deadlineAgentConn) Read(p []byte) (int, error) {
|
||||
c.setDeadline()
|
||||
n, err := c.Conn.Read(p)
|
||||
return n, wrapSSHAgentConnError(err)
|
||||
}
|
||||
|
||||
func (c *deadlineAgentConn) Write(p []byte) (int, error) {
|
||||
c.setDeadline()
|
||||
n, err := c.Conn.Write(p)
|
||||
return n, wrapSSHAgentConnError(err)
|
||||
}
|
||||
|
||||
func (c *deadlineAgentConn) setDeadline() {
|
||||
if c == nil || c.timeout <= 0 || c.Conn == nil {
|
||||
return
|
||||
}
|
||||
_ = c.Conn.SetDeadline(time.Now().Add(c.timeout))
|
||||
}
|
||||
|
||||
func isTimeoutError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, os.ErrDeadlineExceeded) {
|
||||
return true
|
||||
}
|
||||
var netErr net.Error
|
||||
return errors.As(err, &netErr) && netErr.Timeout()
|
||||
}
|
||||
|
||||
func wrapSSHAgentConnError(err error) error {
|
||||
if isTimeoutError(err) {
|
||||
return fmt.Errorf("%w: %v", ErrSSHAgentTimeout, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func normalizeSSHAgentError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, ErrSSHAgentTimeout) {
|
||||
return err
|
||||
}
|
||||
if strings.Contains(err.Error(), ErrSSHAgentTimeout.Error()) {
|
||||
return fmt.Errorf("%w: %v", ErrSSHAgentTimeout, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
+10
-7
@@ -4,16 +4,19 @@ package starssh
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func dialSSHAgent(timeout time.Duration) (net.Conn, error) {
|
||||
agentSock := strings.TrimSpace(os.Getenv("SSH_AUTH_SOCK"))
|
||||
if agentSock == "" {
|
||||
return nil, errSSHAgentUnavailable
|
||||
}
|
||||
func defaultSSHAgentEndpoint() (resolvedSSHAgentEndpoint, error) {
|
||||
return resolvedSSHAgentEndpoint{}, errSSHAgentUnavailable
|
||||
}
|
||||
|
||||
func defaultSSHAgentNetwork(endpoint string) string {
|
||||
return "unix"
|
||||
}
|
||||
|
||||
func dialResolvedSSHAgent(resolved resolvedSSHAgentEndpoint, timeout time.Duration) (net.Conn, error) {
|
||||
agentSock := resolved.Endpoint
|
||||
if timeout > 0 {
|
||||
return net.DialTimeout("unix", agentSock, timeout)
|
||||
}
|
||||
|
||||
+218
-17
@@ -3,10 +3,16 @@
|
||||
package starssh
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -16,22 +22,40 @@ import (
|
||||
|
||||
const defaultWindowsSSHAgentPipe = `\\.\pipe\openssh-ssh-agent`
|
||||
|
||||
func dialSSHAgent(timeout time.Duration) (net.Conn, error) {
|
||||
agentSock := strings.TrimSpace(os.Getenv("SSH_AUTH_SOCK"))
|
||||
if agentSock != "" {
|
||||
return dialWindowsSSHAgentEndpoint(agentSock, timeout)
|
||||
}
|
||||
return dialWindowsNamedPipe(defaultWindowsSSHAgentPipe, timeout, true)
|
||||
var errInvalidGPGSocketInfo = errors.New("invalid gpg agent socket file")
|
||||
|
||||
type gpgSocketInfo struct {
|
||||
port uint16
|
||||
nonce []byte
|
||||
cygwin bool
|
||||
}
|
||||
|
||||
func dialWindowsSSHAgentEndpoint(endpoint string, timeout time.Duration) (net.Conn, error) {
|
||||
if pipePath, ok := normalizeWindowsSSHAgentPipe(endpoint); ok {
|
||||
return dialWindowsNamedPipe(pipePath, timeout, false)
|
||||
func defaultSSHAgentEndpoint() (resolvedSSHAgentEndpoint, error) {
|
||||
return resolvedSSHAgentEndpoint{
|
||||
Endpoint: defaultWindowsSSHAgentPipe,
|
||||
Source: "platform-default",
|
||||
Network: "windows-pipe",
|
||||
}, nil
|
||||
}
|
||||
|
||||
func defaultSSHAgentNetwork(endpoint string) string {
|
||||
if _, ok := normalizeWindowsSSHAgentPipe(endpoint); ok {
|
||||
return "windows-pipe"
|
||||
}
|
||||
if timeout > 0 {
|
||||
return net.DialTimeout("unix", endpoint, timeout)
|
||||
if isAgentSSHSocketPath(endpoint) {
|
||||
return "gpg-socket"
|
||||
}
|
||||
return net.Dial("unix", endpoint)
|
||||
return "unix"
|
||||
}
|
||||
|
||||
func dialResolvedSSHAgent(resolved resolvedSSHAgentEndpoint, timeout time.Duration) (net.Conn, error) {
|
||||
if pipePath, ok := normalizeWindowsSSHAgentPipe(resolved.Endpoint); ok {
|
||||
return dialWindowsNamedPipe(pipePath, timeout, resolved.Source == "platform-default")
|
||||
}
|
||||
if isAgentSSHSocketPath(resolved.Endpoint) {
|
||||
return dialWindowsGPGSocketFile(resolved.Endpoint, timeout)
|
||||
}
|
||||
return dialWindowsUnixAgent(resolved.Endpoint, timeout)
|
||||
}
|
||||
|
||||
func dialWindowsNamedPipe(path string, timeout time.Duration, unavailableOnNotFound bool) (net.Conn, error) {
|
||||
@@ -42,11 +66,7 @@ func dialWindowsNamedPipe(path string, timeout time.Duration, unavailableOnNotFo
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
conn, err := winio.DialPipeContext(ctx, path)
|
||||
if err != nil && unavailableOnNotFound && isWindowsPipeUnavailable(err) {
|
||||
return nil, errSSHAgentUnavailable
|
||||
}
|
||||
return conn, err
|
||||
return dialWindowsNamedPipeContext(ctx, path, unavailableOnNotFound)
|
||||
}
|
||||
|
||||
func normalizeWindowsSSHAgentPipe(endpoint string) (string, bool) {
|
||||
@@ -68,3 +88,184 @@ func normalizeWindowsSSHAgentPipe(endpoint string) (string, bool) {
|
||||
func isWindowsPipeUnavailable(err error) bool {
|
||||
return errors.Is(err, windows.ERROR_FILE_NOT_FOUND) || errors.Is(err, windows.ERROR_PATH_NOT_FOUND)
|
||||
}
|
||||
|
||||
func dialWindowsUnixAgent(endpoint string, timeout time.Duration) (net.Conn, error) {
|
||||
if timeout > 0 {
|
||||
return net.DialTimeout("unix", endpoint, timeout)
|
||||
}
|
||||
return net.Dial("unix", endpoint)
|
||||
}
|
||||
|
||||
func dialWindowsGPGSocketFile(path string, timeout time.Duration) (net.Conn, error) {
|
||||
ctx := context.Background()
|
||||
cancel := func() {}
|
||||
if timeout > 0 {
|
||||
ctx, cancel = context.WithTimeout(ctx, timeout)
|
||||
}
|
||||
defer cancel()
|
||||
return dialWindowsGPGSocketFileDepth(ctx, strings.TrimSpace(path), 0)
|
||||
}
|
||||
|
||||
func dialWindowsGPGSocketFileDepth(ctx context.Context, path string, depth int) (net.Conn, error) {
|
||||
if path == "" {
|
||||
return nil, fmt.Errorf("gpg agent endpoint is empty")
|
||||
}
|
||||
if depth > 8 {
|
||||
return nil, fmt.Errorf("gpg agent socket redirect loop at %s", path)
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if target, ok := parseGPGAssuanSocketRedirect(data); ok {
|
||||
target = resolveGPGSocketRedirectTarget(path, target)
|
||||
if pipePath, ok := normalizeWindowsSSHAgentPipe(target); ok {
|
||||
return dialWindowsNamedPipeContext(ctx, pipePath, false)
|
||||
}
|
||||
return dialWindowsGPGSocketFileDepth(ctx, target, depth+1)
|
||||
}
|
||||
|
||||
info, err := parseGPGSocketInfo(path, data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dialWindowsGPGSocketInfo(ctx, info)
|
||||
}
|
||||
|
||||
func dialWindowsGPGSocketInfo(ctx context.Context, info gpgSocketInfo) (net.Conn, error) {
|
||||
var dialer net.Dialer
|
||||
conn, err := dialer.DialContext(ctx, "tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(int(info.port))))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if deadline, ok := ctx.Deadline(); ok {
|
||||
if err := conn.SetDeadline(deadline); err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if _, err := conn.Write(info.nonce); err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
if info.cygwin {
|
||||
var nonce [16]byte
|
||||
if _, err := io.ReadFull(conn, nonce[:]); err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
var credential [8]byte
|
||||
binary.LittleEndian.PutUint32(credential[:4], uint32(os.Getpid()))
|
||||
if _, err := conn.Write(credential[:]); err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
if _, err := io.ReadFull(conn, credential[:]); err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
_ = conn.SetDeadline(time.Time{})
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func resolveGPGSocketRedirectTarget(source string, target string) string {
|
||||
target = strings.TrimSpace(target)
|
||||
if target == "" || filepath.IsAbs(target) {
|
||||
return target
|
||||
}
|
||||
if _, ok := normalizeWindowsSSHAgentPipe(target); ok {
|
||||
return target
|
||||
}
|
||||
return filepath.Join(filepath.Dir(source), target)
|
||||
}
|
||||
|
||||
func parseGPGSocketInfo(path string, data []byte) (gpgSocketInfo, error) {
|
||||
if info, ok := parseGPGAssuanSocketInfo(data); ok {
|
||||
return info, nil
|
||||
}
|
||||
if info, ok := parseGPGCygwinSocketInfo(data); ok {
|
||||
return info, nil
|
||||
}
|
||||
return gpgSocketInfo{}, fmt.Errorf("%w %s: expected GnuPG port/nonce socket file; if SSH_AUTH_SOCK was set to this file, restart gpg-agent to recreate it", errInvalidGPGSocketInfo, path)
|
||||
}
|
||||
|
||||
func parseGPGAssuanSocketRedirect(data []byte) (string, bool) {
|
||||
text := strings.ReplaceAll(string(data), "\r\n", "\n")
|
||||
text = strings.TrimSuffix(text, "\n")
|
||||
lines := strings.Split(text, "\n")
|
||||
if len(lines) != 2 || lines[0] != "%Assuan%" {
|
||||
return "", false
|
||||
}
|
||||
target, ok := strings.CutPrefix(lines[1], "socket=")
|
||||
if !ok || strings.TrimSpace(target) == "" {
|
||||
return "", false
|
||||
}
|
||||
return os.ExpandEnv(target), true
|
||||
}
|
||||
|
||||
func parseGPGAssuanSocketInfo(data []byte) (gpgSocketInfo, bool) {
|
||||
newline := bytes.IndexByte(data, '\n')
|
||||
if newline <= 0 || len(data)-newline-1 != 16 {
|
||||
return gpgSocketInfo{}, false
|
||||
}
|
||||
port64, err := strconv.ParseUint(strings.TrimSpace(string(data[:newline])), 10, 16)
|
||||
if err != nil || port64 == 0 {
|
||||
return gpgSocketInfo{}, false
|
||||
}
|
||||
nonce := make([]byte, 16)
|
||||
copy(nonce, data[newline+1:])
|
||||
return gpgSocketInfo{port: uint16(port64), nonce: nonce}, true
|
||||
}
|
||||
|
||||
func parseGPGCygwinSocketInfo(data []byte) (gpgSocketInfo, bool) {
|
||||
if !bytes.HasPrefix(data, []byte("!<socket >")) {
|
||||
return gpgSocketInfo{}, false
|
||||
}
|
||||
fields := strings.Fields(strings.TrimRight(string(data[10:]), "\x00"))
|
||||
if len(fields) != 3 || fields[1] != "s" {
|
||||
return gpgSocketInfo{}, false
|
||||
}
|
||||
port64, err := strconv.ParseUint(fields[0], 10, 16)
|
||||
if err != nil || port64 == 0 {
|
||||
return gpgSocketInfo{}, false
|
||||
}
|
||||
hexParts := strings.Split(fields[2], "-")
|
||||
if len(hexParts) != 4 {
|
||||
return gpgSocketInfo{}, false
|
||||
}
|
||||
nonce := make([]byte, 0, 16)
|
||||
for _, part := range hexParts {
|
||||
if len(part) != 8 {
|
||||
return gpgSocketInfo{}, false
|
||||
}
|
||||
value, err := strconv.ParseUint(part, 16, 32)
|
||||
if err != nil {
|
||||
return gpgSocketInfo{}, false
|
||||
}
|
||||
var chunk [4]byte
|
||||
binary.LittleEndian.PutUint32(chunk[:], uint32(value))
|
||||
nonce = append(nonce, chunk[:]...)
|
||||
}
|
||||
return gpgSocketInfo{port: uint16(port64), nonce: nonce, cygwin: true}, true
|
||||
}
|
||||
|
||||
func isAgentSSHSocketPath(endpoint string) bool {
|
||||
normalized := strings.ToLower(strings.TrimSpace(endpoint))
|
||||
return strings.HasSuffix(normalized, "s.gpg-agent.ssh")
|
||||
}
|
||||
|
||||
func dialWindowsNamedPipeContext(ctx context.Context, path string, unavailableOnNotFound bool) (net.Conn, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
conn, err := winio.DialPipeContext(ctx, path)
|
||||
if err != nil && unavailableOnNotFound && isWindowsPipeUnavailable(err) {
|
||||
return nil, errSSHAgentUnavailable
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
//go:build windows
|
||||
|
||||
package starssh
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestParseGPGAssuanSocketInfo(t *testing.T) {
|
||||
info, ok := parseGPGAssuanSocketInfo([]byte("7247\n0123456789abcdef"))
|
||||
if !ok {
|
||||
t.Fatal("expected Assuan socket info to parse")
|
||||
}
|
||||
if info.port != 7247 || string(info.nonce) != "0123456789abcdef" || info.cygwin {
|
||||
t.Fatalf("info=%+v nonce=%x", info, info.nonce)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseGPGCygwinSocketInfo(t *testing.T) {
|
||||
info, ok := parseGPGCygwinSocketInfo([]byte("!<socket >7247 s 00000001-02030405-06070809-0a0b0c0d\x00"))
|
||||
if !ok {
|
||||
t.Fatal("expected Cygwin socket info to parse")
|
||||
}
|
||||
want := []byte{1, 0, 0, 0, 5, 4, 3, 2, 9, 8, 7, 6, 13, 12, 11, 10}
|
||||
if info.port != 7247 || string(info.nonce) != string(want) || !info.cygwin {
|
||||
t.Fatalf("info=%+v nonce=%x", info, info.nonce)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseGPGAssuanSocketRedirect(t *testing.T) {
|
||||
t.Setenv("STARSSH_TEST_PIPE", `\\.\pipe\openssh-ssh-agent`)
|
||||
target, ok := parseGPGAssuanSocketRedirect([]byte("%Assuan%\r\nsocket=${STARSSH_TEST_PIPE}\r\n"))
|
||||
if !ok {
|
||||
t.Fatal("expected Assuan redirect to parse")
|
||||
}
|
||||
if target != `\\.\pipe\openssh-ssh-agent` {
|
||||
t.Fatalf("target=%q", target)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadInvalidAgentSSHSocketReturnsGPGSocketError(t *testing.T) {
|
||||
path := t.TempDir() + "/S.gpg-agent.ssh"
|
||||
if err := os.WriteFile(path, []byte("not a socket info file"), 0o600); err != nil {
|
||||
t.Fatalf("write socket file: %v", err)
|
||||
}
|
||||
|
||||
_, err := dialResolvedSSHAgent(resolvedSSHAgentEndpoint{
|
||||
Endpoint: path,
|
||||
Source: "SSH_AUTH_SOCK",
|
||||
Network: defaultSSHAgentNetwork(path),
|
||||
}, 0)
|
||||
if !errors.Is(err, errInvalidGPGSocketInfo) {
|
||||
t.Fatalf("err=%v want errInvalidGPGSocketInfo", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingAgentSSHSocketReturnsReadError(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "S.gpg-agent.ssh")
|
||||
|
||||
_, err := dialResolvedSSHAgent(resolvedSSHAgentEndpoint{
|
||||
Endpoint: path,
|
||||
Source: "identity-agent",
|
||||
Network: defaultSSHAgentNetwork(path),
|
||||
}, 0)
|
||||
if err == nil {
|
||||
t.Fatal("expected missing GPG socket file error")
|
||||
}
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("err=%v want os.ErrNotExist", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnreadableAgentSSHSocketReturnsReadError(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "S.gpg-agent.ssh")
|
||||
if err := os.Mkdir(path, 0o700); err != nil {
|
||||
t.Fatalf("mkdir socket path: %v", err)
|
||||
}
|
||||
|
||||
_, err := dialResolvedSSHAgent(resolvedSSHAgentEndpoint{
|
||||
Endpoint: path,
|
||||
Source: "identity-agent",
|
||||
Network: defaultSSHAgentNetwork(path),
|
||||
}, 0)
|
||||
if err == nil {
|
||||
t.Fatal("expected unreadable GPG socket file error")
|
||||
}
|
||||
if errors.Is(err, errInvalidGPGSocketInfo) {
|
||||
t.Fatalf("err=%v should expose read failure before parse", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDialWindowsGPGSocketFilePerformsNonceHandshake(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen tcp: %v", err)
|
||||
}
|
||||
defer listener.Close()
|
||||
|
||||
type handshakeResult struct {
|
||||
nonce []byte
|
||||
err error
|
||||
}
|
||||
resultCh := make(chan handshakeResult, 1)
|
||||
go func() {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
resultCh <- handshakeResult{err: err}
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
nonce := make([]byte, 16)
|
||||
if _, err := io.ReadFull(conn, nonce); err != nil {
|
||||
resultCh <- handshakeResult{err: err}
|
||||
return
|
||||
}
|
||||
resultCh <- handshakeResult{nonce: append([]byte(nil), nonce...)}
|
||||
}()
|
||||
|
||||
socketPath := filepath.Join(t.TempDir(), "S.gpg-agent.ssh")
|
||||
if err := os.WriteFile(socketPath, []byte(strconv.Itoa(listener.Addr().(*net.TCPAddr).Port)+"\n0123456789abcdef"), 0o600); err != nil {
|
||||
t.Fatalf("write socket file: %v", err)
|
||||
}
|
||||
|
||||
conn, err := dialWindowsGPGSocketFile(socketPath, time.Second)
|
||||
if err != nil {
|
||||
t.Fatalf("dialWindowsGPGSocketFile: %v", err)
|
||||
}
|
||||
_ = conn.Close()
|
||||
|
||||
var result handshakeResult
|
||||
select {
|
||||
case result = <-resultCh:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("listener did not accept GPG socket connection")
|
||||
}
|
||||
if result.err != nil {
|
||||
t.Fatalf("listener handshake error: %v", result.err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(result.nonce, []byte("0123456789abcdef")) {
|
||||
t.Fatalf("nonce=%q", result.nonce)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
var errSSHClientClosing = errors.New("ssh client is closing")
|
||||
|
||||
type sshClientRequester interface {
|
||||
SendRequest(name string, wantReply bool, payload []byte) (bool, []byte, error)
|
||||
Close() error
|
||||
@@ -29,10 +31,19 @@ func (s *StarSSH) snapshotSSHClient() *ssh.Client {
|
||||
}
|
||||
|
||||
func (s *StarSSH) requireSSHClient() (*ssh.Client, error) {
|
||||
if s == nil {
|
||||
return nil, errors.New("ssh client is nil")
|
||||
}
|
||||
if s.closing.Load() {
|
||||
return nil, errSSHClientClosing
|
||||
}
|
||||
client := s.snapshotSSHClient()
|
||||
if client == nil {
|
||||
return nil, errors.New("ssh client is nil")
|
||||
}
|
||||
if s.closing.Load() {
|
||||
return nil, errSSHClientClosing
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
@@ -46,6 +57,7 @@ func (s *StarSSH) setTransport(client *ssh.Client, upstream *StarSSH) {
|
||||
s.Client = client
|
||||
s.upstream = upstream
|
||||
s.online = client != nil
|
||||
s.closing.Store(false)
|
||||
}
|
||||
|
||||
func (s *StarSSH) detachTransport() (*ssh.Client, *StarSSH) {
|
||||
@@ -84,7 +96,9 @@ func (s *StarSSH) closeTransport(waitKeepalive bool) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
s.closing.Store(true)
|
||||
_ = s.closeReusableSFTPClient()
|
||||
agentForwarder := s.takeAgentForwarder()
|
||||
|
||||
client, upstream := s.detachTransport()
|
||||
stop, done := s.takeKeepaliveHandles()
|
||||
@@ -93,8 +107,13 @@ func (s *StarSSH) closeTransport(waitKeepalive bool) error {
|
||||
}
|
||||
|
||||
var closeErr error
|
||||
if agentForwarder != nil {
|
||||
closeErr = normalizeAlreadyClosedError(agentForwarder.Close())
|
||||
}
|
||||
if client != nil {
|
||||
closeErr = normalizeAlreadyClosedError(closeSSHClient(client))
|
||||
if err := normalizeAlreadyClosedError(closeSSHClient(client)); closeErr == nil {
|
||||
closeErr = err
|
||||
}
|
||||
}
|
||||
if waitKeepalive && done != nil {
|
||||
<-done
|
||||
@@ -104,3 +123,13 @@ func (s *StarSSH) closeTransport(waitKeepalive bool) error {
|
||||
}
|
||||
return closeErr
|
||||
}
|
||||
|
||||
func (s *StarSSH) canAttachAgentForwarder(client *ssh.Client) bool {
|
||||
if s == nil || client == nil || s.closing.Load() {
|
||||
return false
|
||||
}
|
||||
|
||||
s.stateMu.RLock()
|
||||
defer s.stateMu.RUnlock()
|
||||
return !s.closing.Load() && s.Client == client
|
||||
}
|
||||
|
||||
+2
-2
@@ -32,7 +32,7 @@ func resolveDialContext(info LoginInput) DialContextFunc {
|
||||
}
|
||||
|
||||
dialer := &net.Dialer{
|
||||
Timeout: info.Timeout,
|
||||
Timeout: effectiveDialTimeout(info),
|
||||
}
|
||||
return dialer.DialContext
|
||||
}
|
||||
@@ -44,7 +44,7 @@ func dialTargetConn(ctx context.Context, info LoginInput) (net.Conn, *StarSSH, e
|
||||
}
|
||||
|
||||
dialContext := resolveDialContext(info)
|
||||
proxyConfig := normalizeProxyConfig(info.Proxy, info.Timeout)
|
||||
proxyConfig := normalizeProxyConfig(info.Proxy, effectiveDialTimeout(info))
|
||||
if proxyConfig != nil {
|
||||
return dialViaProxy(ctx, dialContext, *proxyConfig, targetAddr)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/sftp"
|
||||
@@ -15,6 +16,7 @@ import (
|
||||
const (
|
||||
defaultSSHPort = 22
|
||||
defaultLoginTimeout = 5 * time.Second
|
||||
defaultSSHAgentTimeout = 2 * time.Minute
|
||||
defaultKeepAliveTimeout = 3 * time.Second
|
||||
defaultShellPollInterval = 120 * time.Millisecond
|
||||
defaultShellSetupDelay = 200 * time.Millisecond
|
||||
@@ -57,22 +59,39 @@ const (
|
||||
AuthMethodSSHAgent AuthMethodKind = "ssh_agent"
|
||||
)
|
||||
|
||||
type SSHAgentDebugFunc func(SSHAgentDebugEvent)
|
||||
|
||||
type SSHAgentDebugEvent struct {
|
||||
Step string
|
||||
Source string
|
||||
Endpoint string
|
||||
Network string
|
||||
Phase string
|
||||
Status string
|
||||
Duration time.Duration
|
||||
KeyCount int
|
||||
Err error
|
||||
}
|
||||
|
||||
type StarSSH struct {
|
||||
stateMu sync.RWMutex
|
||||
Client *ssh.Client
|
||||
PublicKey ssh.PublicKey
|
||||
PubkeyBase64 string
|
||||
Hostname string
|
||||
RemoteAddr net.Addr
|
||||
Banner string
|
||||
LoginInfo LoginInput
|
||||
online bool
|
||||
upstream *StarSSH
|
||||
sftpClient *sftp.Client
|
||||
sftpMu sync.Mutex
|
||||
keepaliveMu sync.Mutex
|
||||
keepaliveStop chan struct{}
|
||||
keepaliveDone chan struct{}
|
||||
stateMu sync.RWMutex
|
||||
Client *ssh.Client
|
||||
PublicKey ssh.PublicKey
|
||||
PubkeyBase64 string
|
||||
Hostname string
|
||||
RemoteAddr net.Addr
|
||||
Banner string
|
||||
LoginInfo LoginInput
|
||||
online bool
|
||||
upstream *StarSSH
|
||||
sftpClient *sftp.Client
|
||||
sftpMu sync.Mutex
|
||||
agentForwardMu sync.Mutex
|
||||
agentForwarder io.Closer
|
||||
keepaliveMu sync.Mutex
|
||||
keepaliveStop chan struct{}
|
||||
keepaliveDone chan struct{}
|
||||
closing atomic.Bool
|
||||
}
|
||||
|
||||
type LoginInput struct {
|
||||
@@ -86,17 +105,39 @@ type LoginInput struct {
|
||||
Prikey string
|
||||
PrikeyPwd string
|
||||
DisableSSHAgent bool
|
||||
ForwardSSHAgent bool
|
||||
AuthOrder []AuthMethodKind
|
||||
Addr string
|
||||
Port int
|
||||
Timeout time.Duration
|
||||
DialContext DialContextFunc
|
||||
Proxy *ProxyConfig
|
||||
Jump *LoginInput
|
||||
KeepAliveInterval time.Duration
|
||||
KeepAliveTimeout time.Duration
|
||||
HostKeyCallback func(string, net.Addr, ssh.PublicKey) error
|
||||
BannerCallback func(string) error
|
||||
// IdentityAgent overrides the local ssh-agent endpoint used for authentication
|
||||
// and agent forwarding. Empty uses SSH_AUTH_SOCK, or the platform default where
|
||||
// one exists.
|
||||
IdentityAgent string
|
||||
Addr string
|
||||
Port int
|
||||
// Timeout limits the SSH handshake/authentication phase after a TCP connection has
|
||||
// already been established. Zero means no authentication timeout.
|
||||
Timeout time.Duration
|
||||
// DialTimeout limits outbound dial steps such as TCP connect, proxy connect, and
|
||||
// local ssh-agent socket connect. Zero falls back to Timeout when set, otherwise
|
||||
// uses the package default dial timeout. Negative disables the default dial timeout.
|
||||
DialTimeout time.Duration
|
||||
// SSHAgentTimeout limits ssh-agent protocol operations such as listing keys and
|
||||
// signing challenges. Zero uses the package default, and negative disables the
|
||||
// per-operation deadline. This is intentionally separate from Timeout and
|
||||
// DialTimeout because hardware-backed agents may require a PIN or touch confirmation.
|
||||
SSHAgentTimeout time.Duration
|
||||
// SSHAgentForwardTimeout limits idle reads and writes on forwarded agent
|
||||
// channels. Zero or negative leaves forwarded channels without an idle deadline.
|
||||
SSHAgentForwardTimeout time.Duration
|
||||
// SSHAgentDebug receives structured ssh-agent dial/protocol events. It is nil by
|
||||
// default and must not log private key material.
|
||||
SSHAgentDebug SSHAgentDebugFunc
|
||||
DialContext DialContextFunc
|
||||
Proxy *ProxyConfig
|
||||
Jump *LoginInput
|
||||
KeepAliveInterval time.Duration
|
||||
KeepAliveTimeout time.Duration
|
||||
HostKeyCallback func(string, net.Addr, ssh.PublicKey) error
|
||||
BannerCallback func(string) error
|
||||
}
|
||||
|
||||
// StarShell keeps the legacy prompt-driven helper for POSIX-style scripted shell interactions.
|
||||
|
||||
Reference in New Issue
Block a user