Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[communicator] add proxy_command support to connection block #36643

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changes/v1.12/ENHANCEMENTS-20250301-165740.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
kind: ENHANCEMENTS
body: You can now utilize an SSH proxy command with the `proxy_command` argument in `connection` blocks of resources.
time: 2025-03-01T16:57:40.050317317Z
custom:
Issue: "394"
4 changes: 4 additions & 0 deletions internal/communicator/shared/shared.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ var ConnectionBlockSupersetSchema = &configschema.Block{
Type: cty.String,
Optional: true,
},
"proxy_command": {
Type: cty.String,
Optional: true,
},
"bastion_host": {
Type: cty.String,
Optional: true,
Expand Down
188 changes: 185 additions & 3 deletions internal/communicator/ssh/communicator.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@ import (
"math/rand"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"

"github.com/apparentlymart/go-shquot/shquot"
Expand All @@ -31,6 +33,9 @@ import (
_ "github.com/hashicorp/terraform/internal/logging"
)

// execCommand is a variable for testing that allows us to mock exec.Command
var execCommand = exec.Command

const (
// DefaultShebang is added at the top of a SSH script file
DefaultShebang = "#!/bin/sh\n"
Expand Down Expand Up @@ -174,7 +179,12 @@ func (c *Communicator) Connect(o provisioners.UIOutput) (err error) {
))
}

if c.connInfo.ProxyHost != "" {
if c.connInfo.ProxyCommand != "" {
o.Output(fmt.Sprintf(
"Using configured proxy command: %s",
c.connInfo.ProxyCommand,
))
} else if c.connInfo.ProxyHost != "" {
o.Output(fmt.Sprintf(
"Using configured proxy host...\n"+
" ProxyHost: %s\n"+
Expand Down Expand Up @@ -329,7 +339,18 @@ func (c *Communicator) Disconnect() error {
if c.conn != nil {
conn := c.conn
c.conn = nil
return conn.Close()

// Close the connection
err := conn.Close()
if err != nil {
log.Printf("[ERROR] Error closing connection: %s", err)
return err
}

// Ensure the proxy command is terminated if this is a proxy command connection
if proxyConn, ok := conn.(*proxyCommandConn); ok {
proxyConn.Close()
}
}

return nil
Expand Down Expand Up @@ -603,7 +624,7 @@ func (c *Communicator) scpSession(scpCommand string, f func(io.Writer, *bufio.Re

if err != nil {
if exitErr, ok := err.(*ssh.ExitError); ok {
// Otherwise, we have an ExitErorr, meaning we can just read
// Otherwise, we have an ExitError, meaning we can just read
// the exit status
log.Printf("[ERROR] %s", exitErr)

Expand Down Expand Up @@ -897,3 +918,164 @@ func quoteShell(args []string, targetPlatform string) (string, error) {
return "", fmt.Errorf("Cannot quote shell command, target platform unknown: %s", targetPlatform)

}

// ProxyCommandConnectFunc is a convenience method for returning a function
// that connects to a host using a proxy command.
func ProxyCommandConnectFunc(proxyCommand, addr string) func() (net.Conn, error) {
return func() (net.Conn, error) {
log.Printf("[DEBUG] Connecting to %s using proxy command: %s", addr, proxyCommand)

// Replace %h and %p in the proxy command with the host and port
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("Error parsing address: %s", err)
}

command := strings.Replace(proxyCommand, "%h", host, -1)
command = strings.Replace(command, "%p", port, -1)

// Split the command into command and args
cmdParts := strings.Fields(command)
if len(cmdParts) == 0 {
return nil, fmt.Errorf("Invalid proxy command: %s", proxyCommand)
}

// Create a buffer to capture stderr
stderrBuf := new(bytes.Buffer)

// Create proxy command
cmd := execCommand(cmdParts[0], cmdParts[1:]...)
cmd.Stderr = stderrBuf

// Set up the command to run in its own process group
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true, // Create a new process group
}

// Start the command with pipes
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, fmt.Errorf("Error creating stdin pipe for proxy command: %s", err)
}

stdout, err := cmd.StdoutPipe()
if err != nil {
stdin.Close()
return nil, fmt.Errorf("Error creating stdout pipe for proxy command: %s", err)
}

if err := cmd.Start(); err != nil {
stdin.Close()
stdout.Close()
return nil, fmt.Errorf("Error starting proxy command: %s", err)
}

// Create a wrapper that manages the command and pipes
conn := &proxyCommandConn{
cmd: cmd,
stderr: stderrBuf,
stdinPipe: stdin,
stdoutPipe: stdout,
}

return conn, nil
}
}

type proxyCommandConn struct {
cmd *exec.Cmd
stderr *bytes.Buffer
stdinPipe io.WriteCloser
stdoutPipe io.ReadCloser
closed bool
mutex sync.Mutex
}

// Read reads data from the connection (the command's stdout)
func (c *proxyCommandConn) Read(b []byte) (int, error) {
if c.closed {
return 0, io.EOF
}
return c.stdoutPipe.Read(b)
}

// Write writes data to the connection (the command's stdin)
func (c *proxyCommandConn) Write(b []byte) (int, error) {
if c.closed {
return 0, io.ErrClosedPipe
}
return c.stdinPipe.Write(b)
}

func (c *proxyCommandConn) Close() error {
c.mutex.Lock()
defer c.mutex.Unlock()

if c.closed {
return nil
}
c.closed = true

log.Print("[DEBUG] Closing proxy command connection")

// Close pipes and hangup
if err := c.stdinPipe.Close(); err != nil {
log.Printf("[ERROR] Error closing stdin pipe: %s", err)
}
if err := c.stdoutPipe.Close(); err != nil {
log.Printf("[ERROR] Error closing stdout pipe: %s", err)
}

// Send hangup the proxy command and any child processes
if c.cmd.Process != nil {
pgid, err := syscall.Getpgid(c.cmd.Process.Pid)
if err != nil {
log.Printf("[ERROR] Error getting process group ID: %s", err)
// Fall back to killing just the process if we can't get the process group
if err := c.cmd.Process.Signal(syscall.SIGHUP); err != nil {
log.Printf("[ERROR] Error sending SIGHUP to proxy command: %s", err)
}
} else {
// Kill the entire process group
if err := syscall.Kill(-pgid, syscall.SIGHUP); err != nil {
log.Printf("[ERROR] Error sending SIGHUP to process group: %s", err)
}
}

// Wait for the process to finish to avoid zombie processes
go func() {
if err := c.cmd.Wait(); err != nil {
// This is expected since we're killing the process
log.Printf("[DEBUG] Proxy command exited: %s", err)
}
}()
}

// If the command failed, log the stderr output
if c.stderr.Len() > 0 {
log.Printf("[ERROR] Proxy command stderr: %s", c.stderr.String())
}

return nil
}

// Required methods to implement net.Conn interface
func (c *proxyCommandConn) LocalAddr() net.Addr {
return &net.UnixAddr{Name: "local", Net: "unix"}
}

func (c *proxyCommandConn) RemoteAddr() net.Addr {
return &net.UnixAddr{Name: "remote", Net: "unix"}
}

func (c *proxyCommandConn) SetDeadline(t time.Time) error {
return nil // Not implemented
}

func (c *proxyCommandConn) SetReadDeadline(t time.Time) error {
return nil // Not implemented
}

func (c *proxyCommandConn) SetWriteDeadline(t time.Time) error {
return nil // Not implemented
}
50 changes: 50 additions & 0 deletions internal/communicator/ssh/communicator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"math/rand"
"net"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
Expand Down Expand Up @@ -735,6 +736,55 @@ func TestScriptPath_randSeed(t *testing.T) {
}
}

func TestProxyCommandPlaceholders(t *testing.T) {
// Instead of using a real command, we'll mock the exec.Command function
// to verify the command string has the placeholders replaced correctly

// Save the original command function and restore it after the test
origCommand := execCommand
defer func() { execCommand = origCommand }()

// Create a variable to capture the command and arguments
var capturedCommand string
var capturedArgs []string

// Mock the exec.Command function
execCommand = func(command string, args ...string) *exec.Cmd {
capturedCommand = command
capturedArgs = args

// Return a command that will succeed but not do anything
cmd := exec.Command("echo", "test")
return cmd
}

// Call the function with a proxy command that has placeholders
proxyCommand := "ssh -W %h:%p bastion-host.example.com"
addr := "example.com:2222"

// Create and call the connect function
connectFunc := ProxyCommandConnectFunc(proxyCommand, addr)
connectFunc()

// Verify the placeholders were replaced correctly
expectedCommand := "ssh"
expectedArgs := []string{"-W", "example.com:2222", "bastion-host.example.com"}

if capturedCommand != expectedCommand {
t.Fatalf("Command mismatch. Expected: %q, Got: %q", expectedCommand, capturedCommand)
}

if len(capturedArgs) != len(expectedArgs) {
t.Fatalf("Argument count mismatch. Expected: %d, Got: %d", len(expectedArgs), len(capturedArgs))
}

for i, arg := range expectedArgs {
if capturedArgs[i] != arg {
t.Fatalf("Argument mismatch at index %d. Expected: %q, Got: %q", i, arg, capturedArgs[i])
}
}
}

var testClientPublicKey = `ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDE6A1c4n+OtEPEFlNKTZf2i03L3NylSYmvmJ8OLmzLuPZmJBJt4G3VZ/60s1aKzwLKrTq20S+ONG4zvnK5zIPoauoNNdUJKbg944hB4OE+HDbrBhk7SH+YWCsCILBoSXwAVdUEic6FWf/SeqBSmTBySHvpuNOw16J+SK6Ardx8k64F2tRkZuC6AmOZijgKa/sQKjWAIVPk34ECM6OLfPc3kKUEfkdpYLvuMfuRMfSTlxn5lFC0b0SovK9aWfNMBH9iXLQkieQ5rXoyzUC7mwgnASgl8cqw1UrToiUuhvneduXBhbQfmC/Upv+tL6dSSk+0DlgVKEHuJmc8s8+/qpdL`

func acceptUserPass(goodUser, goodPass string) func(ssh.ConnMetadata, []byte) (*ssh.Permissions, error) {
Expand Down
Loading
Loading