Replace Go SSH library with native ssh command
Major rewrite to use native ssh command instead of Go SSH library: BREAKING CHANGE: Now requires ssh command in PATH Benefits: - Full SSH feature support including ProxyCommand - Works with SSH containers and jump hosts - Supports all SSH authentication methods - Consistent behavior with terminal SSH - No more custom SSH client implementation Changes: - Port detection now uses 'ssh hostname command' - Port forwarding uses 'ssh -L localport:localhost:remoteport hostname' - Connection testing uses native ssh command - Removed golang.org/x/crypto/ssh dependency - Updated documentation to reflect SSH compatibility This fixes issues with SSH containers that require ProxyCommand and provides full compatibility with user SSH configurations. Co-authored-by: Ona <no-reply@ona.com>
This commit is contained in:
@@ -2,17 +2,13 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"golang.org/x/crypto/ssh"
|
||||
"golang.org/x/crypto/ssh/agent"
|
||||
)
|
||||
|
||||
// ForwardingStartedMsg is sent when port forwarding starts
|
||||
@@ -21,29 +17,29 @@ type ForwardingStartedMsg struct {
|
||||
RemotePort int
|
||||
}
|
||||
|
||||
// PortForwarder manages SSH port forwarding
|
||||
// PortForwarder manages SSH port forwarding using ssh command
|
||||
type PortForwarder struct {
|
||||
sshClient *ssh.Client
|
||||
hostName string
|
||||
localPort int
|
||||
remotePort int
|
||||
listener net.Listener
|
||||
sshCmd *exec.Cmd
|
||||
stopChan chan struct{}
|
||||
wg sync.WaitGroup
|
||||
isRunning bool
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// NewPortForwarder creates a new port forwarder
|
||||
func NewPortForwarder(sshClient *ssh.Client, localPort, remotePort int) *PortForwarder {
|
||||
// NewPortForwarder creates a new port forwarder using ssh command
|
||||
func NewPortForwarder(hostName string, localPort, remotePort int) *PortForwarder {
|
||||
return &PortForwarder{
|
||||
sshClient: sshClient,
|
||||
hostName: hostName,
|
||||
localPort: localPort,
|
||||
remotePort: remotePort,
|
||||
stopChan: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Start starts the port forwarding
|
||||
// Start starts the port forwarding using ssh command
|
||||
func (pf *PortForwarder) Start() error {
|
||||
pf.mu.Lock()
|
||||
defer pf.mu.Unlock()
|
||||
@@ -52,18 +48,28 @@ func (pf *PortForwarder) Start() error {
|
||||
return fmt.Errorf("port forwarding already running")
|
||||
}
|
||||
|
||||
// Create local listener
|
||||
listener, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", pf.localPort))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create local listener: %w", err)
|
||||
// Use ssh command with -L flag for local port forwarding
|
||||
// Format: ssh -L localport:localhost:remoteport hostname
|
||||
pf.sshCmd = exec.Command("ssh",
|
||||
"-L", fmt.Sprintf("%d:localhost:%d", pf.localPort, pf.remotePort),
|
||||
"-N", // Don't execute remote command, just forward ports
|
||||
"-o", "ExitOnForwardFailure=yes", // Exit if port forwarding fails
|
||||
"-o", "ServerAliveInterval=30", // Keep connection alive
|
||||
"-o", "ServerAliveCountMax=3",
|
||||
pf.hostName)
|
||||
|
||||
fmt.Fprintf(os.Stderr, "Debug: Starting SSH command: %s\n", pf.sshCmd.String())
|
||||
|
||||
// Start the SSH command
|
||||
if err := pf.sshCmd.Start(); err != nil {
|
||||
return fmt.Errorf("failed to start SSH port forwarding: %w", err)
|
||||
}
|
||||
|
||||
pf.listener = listener
|
||||
pf.isRunning = true
|
||||
|
||||
// Start accepting connections
|
||||
// Monitor the SSH process
|
||||
pf.wg.Add(1)
|
||||
go pf.acceptConnections()
|
||||
go pf.monitorSSH()
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -80,78 +86,34 @@ func (pf *PortForwarder) Stop() {
|
||||
pf.isRunning = false
|
||||
close(pf.stopChan)
|
||||
|
||||
if pf.listener != nil {
|
||||
pf.listener.Close()
|
||||
// Kill the SSH process
|
||||
if pf.sshCmd != nil && pf.sshCmd.Process != nil {
|
||||
fmt.Fprintf(os.Stderr, "Debug: Stopping SSH port forwarding\n")
|
||||
pf.sshCmd.Process.Kill()
|
||||
}
|
||||
|
||||
pf.wg.Wait()
|
||||
}
|
||||
|
||||
// acceptConnections accepts and handles incoming connections
|
||||
func (pf *PortForwarder) acceptConnections() {
|
||||
// monitorSSH monitors the SSH process
|
||||
func (pf *PortForwarder) monitorSSH() {
|
||||
defer pf.wg.Done()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-pf.stopChan:
|
||||
return
|
||||
default:
|
||||
// Set a timeout for Accept to avoid blocking indefinitely
|
||||
if tcpListener, ok := pf.listener.(*net.TCPListener); ok {
|
||||
tcpListener.SetDeadline(time.Now().Add(1 * time.Second))
|
||||
}
|
||||
|
||||
conn, err := pf.listener.Accept()
|
||||
if err != nil {
|
||||
// Check if it's a timeout error and continue
|
||||
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
|
||||
continue
|
||||
}
|
||||
// If we're stopping, ignore the error
|
||||
select {
|
||||
case <-pf.stopChan:
|
||||
return
|
||||
default:
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Handle the connection in a separate goroutine
|
||||
pf.wg.Add(1)
|
||||
go pf.handleConnection(conn)
|
||||
// Wait for the SSH command to finish or be stopped
|
||||
select {
|
||||
case <-pf.stopChan:
|
||||
// We were asked to stop
|
||||
return
|
||||
default:
|
||||
// Wait for SSH command to finish
|
||||
if err := pf.sshCmd.Wait(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Debug: SSH command finished with error: %v\n", err)
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Debug: SSH command finished successfully\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleConnection handles a single connection
|
||||
func (pf *PortForwarder) handleConnection(localConn net.Conn) {
|
||||
defer pf.wg.Done()
|
||||
defer localConn.Close()
|
||||
|
||||
// Create connection to remote host through SSH
|
||||
remoteConn, err := pf.sshClient.Dial("tcp", fmt.Sprintf("localhost:%d", pf.remotePort))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer remoteConn.Close()
|
||||
|
||||
// Copy data between connections
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
io.Copy(localConn, remoteConn)
|
||||
}()
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
io.Copy(remoteConn, localConn)
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// StartPortForwarding starts port forwarding for a specific port
|
||||
func StartPortForwarding(host SSHHost, remotePort int) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
@@ -165,18 +127,9 @@ func StartPortForwarding(host SSHHost, remotePort int) tea.Cmd {
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Debug: Found available local port: %d\n", localPort)
|
||||
|
||||
// Create SSH client
|
||||
client, err := createSSHClient(host)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Debug: Failed to create SSH client: %v\n", err)
|
||||
return ErrorMsg{Error: fmt.Errorf("failed to connect to %s: %w", host.Name, err)}
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Debug: SSH client created successfully\n")
|
||||
|
||||
// Create and start port forwarder
|
||||
forwarder := NewPortForwarder(client, localPort, remotePort)
|
||||
// Create and start port forwarder using ssh command
|
||||
forwarder := NewPortForwarder(host.Name, localPort, remotePort)
|
||||
if err := forwarder.Start(); err != nil {
|
||||
client.Close()
|
||||
fmt.Fprintf(os.Stderr, "Debug: Failed to start port forwarder: %v\n", err)
|
||||
return ErrorMsg{Error: fmt.Errorf("failed to start port forwarding: %w", err)}
|
||||
}
|
||||
@@ -213,18 +166,9 @@ func StartManualPortForwarding(host SSHHost, portStr string) tea.Cmd {
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Debug: Found available local port: %d\n", localPort)
|
||||
|
||||
// Create SSH client
|
||||
client, err := createSSHClient(host)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Debug: Failed to create SSH client: %v\n", err)
|
||||
return ErrorMsg{Error: fmt.Errorf("failed to connect to %s: %w", host.Name, err)}
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Debug: SSH client created successfully\n")
|
||||
|
||||
// Create and start port forwarder
|
||||
forwarder := NewPortForwarder(client, localPort, remotePort)
|
||||
// Create and start port forwarder using ssh command
|
||||
forwarder := NewPortForwarder(host.Name, localPort, remotePort)
|
||||
if err := forwarder.Start(); err != nil {
|
||||
client.Close()
|
||||
fmt.Fprintf(os.Stderr, "Debug: Failed to start port forwarder: %v\n", err)
|
||||
return ErrorMsg{Error: fmt.Errorf("failed to start port forwarding: %w", err)}
|
||||
}
|
||||
@@ -237,78 +181,7 @@ func StartManualPortForwarding(host SSHHost, portStr string) tea.Cmd {
|
||||
}
|
||||
}
|
||||
|
||||
// createSSHClient creates an SSH client for the given host
|
||||
func createSSHClient(host SSHHost) (*ssh.Client, error) {
|
||||
config := &ssh.ClientConfig{
|
||||
User: host.User,
|
||||
Auth: []ssh.AuthMethod{},
|
||||
HostKeyCallback: ssh.InsecureIgnoreHostKey(), // In production, use proper host key verification
|
||||
Timeout: 10 * time.Second, // Longer timeout for better reliability
|
||||
}
|
||||
|
||||
// Add key-based authentication if identity file is specified
|
||||
if host.Identity != "" {
|
||||
fmt.Fprintf(os.Stderr, "Debug: Trying identity file: %s\n", host.Identity)
|
||||
key, err := loadPrivateKey(host.Identity)
|
||||
if err == nil {
|
||||
config.Auth = append(config.Auth, ssh.PublicKeys(key))
|
||||
fmt.Fprintf(os.Stderr, "Debug: Added key-based auth\n")
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Debug: Failed to load identity file: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Add SSH agent authentication
|
||||
if agentAuth, err := sshAgentAuth(); err == nil {
|
||||
config.Auth = append(config.Auth, agentAuth)
|
||||
fmt.Fprintf(os.Stderr, "Debug: Added SSH agent auth\n")
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Debug: SSH agent not available: %v\n", err)
|
||||
}
|
||||
|
||||
// Try to load default SSH keys if no specific identity is set
|
||||
if host.Identity == "" {
|
||||
defaultKeys := []string{"id_rsa", "id_ecdsa", "id_ed25519"}
|
||||
homeDir, err := os.UserHomeDir()
|
||||
if err == nil {
|
||||
for _, keyName := range defaultKeys {
|
||||
keyPath := filepath.Join(homeDir, ".ssh", keyName)
|
||||
if key, err := loadPrivateKey(keyPath); err == nil {
|
||||
config.Auth = append(config.Auth, ssh.PublicKeys(key))
|
||||
fmt.Fprintf(os.Stderr, "Debug: Added default key: %s\n", keyName)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If no auth methods available, provide helpful error
|
||||
if len(config.Auth) == 0 {
|
||||
return nil, fmt.Errorf("no SSH authentication methods available - please set up SSH keys or SSH agent")
|
||||
}
|
||||
|
||||
// Connect to the remote host
|
||||
addr := net.JoinHostPort(host.Hostname, host.Port)
|
||||
fmt.Fprintf(os.Stderr, "Debug: Connecting to %s\n", addr)
|
||||
client, err := ssh.Dial("tcp", addr, config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to connect to %s (%s): %w", host.Name, addr, err)
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stderr, "Debug: Successfully connected to %s\n", host.Name)
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// sshAgentAuth returns SSH agent authentication method
|
||||
func sshAgentAuth() (ssh.AuthMethod, error) {
|
||||
// Try to connect to SSH agent
|
||||
agentConn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sshAgent := agent.NewClient(agentConn)
|
||||
return ssh.PublicKeysCallback(sshAgent.Signers), nil
|
||||
}
|
||||
|
||||
// findAvailablePort finds an available local port
|
||||
func findAvailablePort() (int, error) {
|
||||
|
Reference in New Issue
Block a user