2014-07-10 23:52:43 +02:00
|
|
|
package ssh
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"bytes"
|
2019-02-22 19:58:07 +01:00
|
|
|
"context"
|
2014-07-10 23:52:43 +02:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"log"
|
2015-04-30 18:02:33 +02:00
|
|
|
"math/rand"
|
2014-07-10 23:52:43 +02:00
|
|
|
"net"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2015-04-30 18:02:33 +02:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
2016-12-06 09:11:32 +01:00
|
|
|
"sync"
|
2014-07-15 02:23:33 +02:00
|
|
|
"time"
|
2014-10-13 21:47:55 +02:00
|
|
|
|
2021-06-15 19:04:01 +02:00
|
|
|
"github.com/apparentlymart/go-shquot/shquot"
|
2019-07-16 23:07:53 +02:00
|
|
|
"github.com/hashicorp/errwrap"
|
2021-05-17 19:00:12 +02:00
|
|
|
"github.com/hashicorp/terraform/internal/communicator/remote"
|
2021-05-17 19:51:48 +02:00
|
|
|
"github.com/hashicorp/terraform/internal/provisioners"
|
2020-11-25 18:40:42 +01:00
|
|
|
"github.com/zclconf/go-cty/cty"
|
2015-03-11 21:48:47 +01:00
|
|
|
"golang.org/x/crypto/ssh"
|
2015-06-22 18:34:02 +02:00
|
|
|
"golang.org/x/crypto/ssh/agent"
|
2020-11-25 18:40:42 +01:00
|
|
|
|
|
|
|
_ "github.com/hashicorp/terraform/internal/logging"
|
2014-07-10 23:52:43 +02:00
|
|
|
)
|
|
|
|
|
2015-04-09 21:58:00 +02:00
|
|
|
const (
|
|
|
|
// DefaultShebang is added at the top of a SSH script file
|
|
|
|
DefaultShebang = "#!/bin/sh\n"
|
2019-07-11 03:28:58 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
// randShared is a global random generator object that is shared. This must be
|
|
|
|
// shared since it is seeded by the current time and creating multiple can
|
|
|
|
// result in the same values. By using a shared RNG we assure different numbers
|
|
|
|
// per call.
|
|
|
|
randLock sync.Mutex
|
|
|
|
randShared *rand.Rand
|
2019-02-22 19:58:07 +01:00
|
|
|
|
|
|
|
// enable ssh keeplive probes by default
|
|
|
|
keepAliveInterval = 2 * time.Second
|
2014-07-10 23:52:43 +02:00
|
|
|
|
2019-07-11 03:28:58 +02:00
|
|
|
// max time to wait for for a KeepAlive response before considering the
|
|
|
|
// connection to be dead.
|
|
|
|
maxKeepAliveDelay = 120 * time.Second
|
|
|
|
)
|
2016-12-06 09:11:32 +01:00
|
|
|
|
2015-04-10 20:34:46 +02:00
|
|
|
// Communicator represents the SSH communicator
|
|
|
|
type Communicator struct {
|
2019-02-22 19:58:07 +01:00
|
|
|
connInfo *connectionInfo
|
|
|
|
client *ssh.Client
|
|
|
|
config *sshConfig
|
|
|
|
conn net.Conn
|
|
|
|
cancelKeepAlive context.CancelFunc
|
2016-12-27 01:29:32 +01:00
|
|
|
|
|
|
|
lock sync.Mutex
|
2014-07-10 23:52:43 +02:00
|
|
|
}
|
|
|
|
|
2015-04-10 20:34:46 +02:00
|
|
|
type sshConfig struct {
|
2014-07-10 23:52:43 +02:00
|
|
|
// The configuration of the Go SSH connection
|
2015-04-10 20:34:46 +02:00
|
|
|
config *ssh.ClientConfig
|
2014-07-10 23:52:43 +02:00
|
|
|
|
2015-04-10 20:34:46 +02:00
|
|
|
// connection returns a new connection. The current connection
|
2014-07-10 23:52:43 +02:00
|
|
|
// in use will be closed as part of the Close method, or in the
|
|
|
|
// case an error occurs.
|
2015-04-10 20:34:46 +02:00
|
|
|
connection func() (net.Conn, error)
|
2014-07-10 23:52:43 +02:00
|
|
|
|
2015-04-10 20:34:46 +02:00
|
|
|
// noPty, if true, will not request a pty from the remote end.
|
|
|
|
noPty bool
|
2015-03-21 02:18:35 +01:00
|
|
|
|
2015-06-22 18:34:02 +02:00
|
|
|
// sshAgent is a struct surrounding the agent.Agent client and the net.Conn
|
|
|
|
// to the SSH Agent. It is nil if no SSH agent is configured
|
|
|
|
sshAgent *sshAgent
|
2014-07-10 23:52:43 +02:00
|
|
|
}
|
|
|
|
|
2018-02-15 20:16:37 +01:00
|
|
|
type fatalError struct {
|
|
|
|
error
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e fatalError) FatalError() error {
|
|
|
|
return e.error
|
|
|
|
}
|
|
|
|
|
2015-04-10 20:34:46 +02:00
|
|
|
// New creates a new communicator implementation over SSH.
|
2020-11-25 18:40:42 +01:00
|
|
|
func New(v cty.Value) (*Communicator, error) {
|
|
|
|
connInfo, err := parseConnectionInfo(v)
|
2015-04-09 21:58:00 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2015-04-10 20:34:46 +02:00
|
|
|
config, err := prepareSSHConfig(connInfo)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-01-26 20:39:11 +01:00
|
|
|
// Set up the random number generator once. The seed value is the
|
2016-12-06 09:11:32 +01:00
|
|
|
// time multiplied by the PID. This can overflow the int64 but that
|
|
|
|
// is okay. We multiply by the PID in case we have multiple processes
|
|
|
|
// grabbing this at the same time. This is possible with Terraform and
|
|
|
|
// if we communicate to the same host at the same instance, we could
|
|
|
|
// overwrite the same files. Multiplying by the PID prevents this.
|
|
|
|
randLock.Lock()
|
|
|
|
defer randLock.Unlock()
|
|
|
|
if randShared == nil {
|
|
|
|
randShared = rand.New(rand.NewSource(
|
|
|
|
time.Now().UnixNano() * int64(os.Getpid())))
|
|
|
|
}
|
|
|
|
|
2015-04-10 20:34:46 +02:00
|
|
|
comm := &Communicator{
|
|
|
|
connInfo: connInfo,
|
|
|
|
config: config,
|
|
|
|
}
|
2015-04-09 21:58:00 +02:00
|
|
|
|
|
|
|
return comm, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Connect implementation of communicator.Communicator interface
|
2020-11-25 18:40:42 +01:00
|
|
|
func (c *Communicator) Connect(o provisioners.UIOutput) (err error) {
|
2016-12-27 01:29:32 +01:00
|
|
|
// Grab a lock so we can modify our internal attributes
|
|
|
|
c.lock.Lock()
|
|
|
|
defer c.lock.Unlock()
|
|
|
|
|
2015-04-09 21:58:00 +02:00
|
|
|
if c.conn != nil {
|
|
|
|
c.conn.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set the conn and client to nil since we'll recreate it
|
|
|
|
c.conn = nil
|
|
|
|
c.client = nil
|
|
|
|
|
|
|
|
if o != nil {
|
|
|
|
o.Output(fmt.Sprintf(
|
|
|
|
"Connecting to remote host via SSH...\n"+
|
|
|
|
" Host: %s\n"+
|
|
|
|
" User: %s\n"+
|
2015-04-10 20:34:46 +02:00
|
|
|
" Password: %t\n"+
|
|
|
|
" Private key: %t\n"+
|
2018-09-19 02:36:39 +02:00
|
|
|
" Certificate: %t\n"+
|
2018-02-14 01:27:56 +01:00
|
|
|
" SSH Agent: %t\n"+
|
2020-11-12 16:00:48 +01:00
|
|
|
" Checking Host Key: %t\n"+
|
|
|
|
" Target Platform: %s\n",
|
2015-04-09 21:58:00 +02:00
|
|
|
c.connInfo.Host, c.connInfo.User,
|
|
|
|
c.connInfo.Password != "",
|
2015-11-12 21:39:41 +01:00
|
|
|
c.connInfo.PrivateKey != "",
|
2018-09-19 02:36:39 +02:00
|
|
|
c.connInfo.Certificate != "",
|
2015-04-09 21:58:00 +02:00
|
|
|
c.connInfo.Agent,
|
2018-02-14 01:27:56 +01:00
|
|
|
c.connInfo.HostKey != "",
|
2020-11-12 16:00:48 +01:00
|
|
|
c.connInfo.TargetPlatform,
|
2015-04-09 21:58:00 +02:00
|
|
|
))
|
2015-07-10 20:53:06 +02:00
|
|
|
|
|
|
|
if c.connInfo.BastionHost != "" {
|
|
|
|
o.Output(fmt.Sprintf(
|
2015-07-16 19:16:39 +02:00
|
|
|
"Using configured bastion host...\n"+
|
2015-07-10 20:53:06 +02:00
|
|
|
" Host: %s\n"+
|
|
|
|
" User: %s\n"+
|
|
|
|
" Password: %t\n"+
|
|
|
|
" Private key: %t\n"+
|
2019-07-21 08:32:48 +02:00
|
|
|
" Certificate: %t\n"+
|
2018-02-14 01:27:56 +01:00
|
|
|
" SSH Agent: %t\n"+
|
|
|
|
" Checking Host Key: %t",
|
2015-07-10 20:53:06 +02:00
|
|
|
c.connInfo.BastionHost, c.connInfo.BastionUser,
|
|
|
|
c.connInfo.BastionPassword != "",
|
2015-11-12 21:39:41 +01:00
|
|
|
c.connInfo.BastionPrivateKey != "",
|
2019-07-21 08:32:48 +02:00
|
|
|
c.connInfo.BastionCertificate != "",
|
2015-07-10 20:53:06 +02:00
|
|
|
c.connInfo.Agent,
|
2018-02-14 01:27:56 +01:00
|
|
|
c.connInfo.BastionHostKey != "",
|
2015-07-10 20:53:06 +02:00
|
|
|
))
|
|
|
|
}
|
2014-07-10 23:52:43 +02:00
|
|
|
}
|
|
|
|
|
2019-07-16 23:07:53 +02:00
|
|
|
hostAndPort := fmt.Sprintf("%s:%d", c.connInfo.Host, c.connInfo.Port)
|
|
|
|
log.Printf("[DEBUG] Connecting to %s for SSH", hostAndPort)
|
2015-04-10 20:34:46 +02:00
|
|
|
c.conn, err = c.config.connection()
|
2015-04-09 21:58:00 +02:00
|
|
|
if err != nil {
|
|
|
|
// Explicitly set this to the REAL nil. Connection() can return
|
|
|
|
// a nil implementation of net.Conn which will make the
|
|
|
|
// "if c.conn == nil" check fail above. Read here for more information
|
|
|
|
// on this psychotic language feature:
|
|
|
|
//
|
|
|
|
// http://golang.org/doc/faq#nil_error
|
|
|
|
c.conn = nil
|
|
|
|
|
2018-04-05 16:22:30 +02:00
|
|
|
log.Printf("[ERROR] connection error: %s", err)
|
2015-04-09 21:58:00 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-07-16 23:07:53 +02:00
|
|
|
log.Printf("[DEBUG] Connection established. Handshaking for user %v", c.connInfo.User)
|
|
|
|
sshConn, sshChan, req, err := ssh.NewClientConn(c.conn, hostAndPort, c.config.config)
|
2015-04-09 21:58:00 +02:00
|
|
|
if err != nil {
|
2019-07-16 23:07:53 +02:00
|
|
|
err = errwrap.Wrapf(fmt.Sprintf("SSH authentication failed (%s@%s): {{err}}", c.connInfo.User, hostAndPort), err)
|
|
|
|
|
2018-03-30 21:23:24 +02:00
|
|
|
// While in theory this should be a fatal error, some hosts may start
|
|
|
|
// the ssh service before it is properly configured, or before user
|
|
|
|
// authentication data is available.
|
|
|
|
// Log the error, and allow the provisioner to retry.
|
|
|
|
log.Printf("[WARN] %s", err)
|
|
|
|
return err
|
2015-04-09 21:58:00 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
c.client = ssh.NewClient(sshConn, sshChan, req)
|
|
|
|
|
2015-06-22 18:34:02 +02:00
|
|
|
if c.config.sshAgent != nil {
|
2015-09-11 20:56:20 +02:00
|
|
|
log.Printf("[DEBUG] Telling SSH config to forward to agent")
|
2015-06-22 18:34:02 +02:00
|
|
|
if err := c.config.sshAgent.ForwardToAgent(c.client); err != nil {
|
2018-02-15 20:16:37 +01:00
|
|
|
return fatalError{err}
|
2015-06-22 18:34:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("[DEBUG] Setting up a session to request agent forwarding")
|
2019-12-12 18:16:17 +01:00
|
|
|
session, err := c.client.NewSession()
|
2015-06-22 18:34:02 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer session.Close()
|
|
|
|
|
2015-07-10 20:51:45 +02:00
|
|
|
err = agent.RequestAgentForwarding(session)
|
2015-06-22 18:34:02 +02:00
|
|
|
|
2015-07-10 20:51:45 +02:00
|
|
|
if err == nil {
|
|
|
|
log.Printf("[INFO] agent forwarding enabled")
|
|
|
|
} else {
|
|
|
|
log.Printf("[WARN] error forwarding agent: %s", err)
|
|
|
|
}
|
2015-06-22 18:34:02 +02:00
|
|
|
}
|
|
|
|
|
2019-02-22 19:58:07 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-04-09 21:58:00 +02:00
|
|
|
if o != nil {
|
|
|
|
o.Output("Connected!")
|
|
|
|
}
|
|
|
|
|
2019-02-22 19:58:07 +01:00
|
|
|
ctx, cancelKeepAlive := context.WithCancel(context.TODO())
|
|
|
|
c.cancelKeepAlive = cancelKeepAlive
|
|
|
|
|
|
|
|
// Start a keepalive goroutine to help maintain the connection for
|
|
|
|
// long-running commands.
|
|
|
|
log.Printf("[DEBUG] starting ssh KeepAlives")
|
2019-10-02 19:42:22 +02:00
|
|
|
|
2019-10-02 21:03:18 +02:00
|
|
|
// We want a local copy of the ssh client pointer, so that a reconnect
|
2019-10-02 19:42:22 +02:00
|
|
|
// doesn't race with the running keep-alive loop.
|
|
|
|
sshClient := c.client
|
2019-02-22 19:58:07 +01:00
|
|
|
go func() {
|
2019-07-11 03:28:58 +02:00
|
|
|
defer cancelKeepAlive()
|
|
|
|
// Along with the KeepAlives generating packets to keep the tcp
|
|
|
|
// connection open, we will use the replies to verify liveness of the
|
|
|
|
// connection. This will prevent dead connections from blocking the
|
|
|
|
// provisioner indefinitely.
|
|
|
|
respCh := make(chan error, 1)
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
t := time.NewTicker(keepAliveInterval)
|
|
|
|
defer t.Stop()
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-t.C:
|
2019-10-02 19:42:22 +02:00
|
|
|
_, _, err := sshClient.SendRequest("keepalive@terraform.io", true, nil)
|
2019-07-11 03:28:58 +02:00
|
|
|
respCh <- err
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
after := time.NewTimer(maxKeepAliveDelay)
|
|
|
|
defer after.Stop()
|
|
|
|
|
2019-02-22 19:58:07 +01:00
|
|
|
for {
|
|
|
|
select {
|
2019-07-11 03:28:58 +02:00
|
|
|
case err := <-respCh:
|
2019-02-22 19:58:07 +01:00
|
|
|
if err != nil {
|
2019-07-11 03:28:58 +02:00
|
|
|
log.Printf("[ERROR] ssh keepalive: %s", err)
|
|
|
|
sshConn.Close()
|
2019-02-22 19:58:07 +01:00
|
|
|
return
|
|
|
|
}
|
2019-07-11 03:28:58 +02:00
|
|
|
case <-after.C:
|
|
|
|
// abort after too many missed keepalives
|
|
|
|
log.Println("[ERROR] no reply from ssh server")
|
|
|
|
sshConn.Close()
|
|
|
|
return
|
2019-02-22 19:58:07 +01:00
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
}
|
2019-07-11 03:28:58 +02:00
|
|
|
if !after.Stop() {
|
|
|
|
<-after.C
|
|
|
|
}
|
|
|
|
after.Reset(maxKeepAliveDelay)
|
2019-02-22 19:58:07 +01:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return nil
|
2014-07-10 23:52:43 +02:00
|
|
|
}
|
|
|
|
|
2015-04-09 21:58:00 +02:00
|
|
|
// Disconnect implementation of communicator.Communicator interface
|
2015-04-10 20:34:46 +02:00
|
|
|
func (c *Communicator) Disconnect() error {
|
2016-12-27 01:29:32 +01:00
|
|
|
c.lock.Lock()
|
|
|
|
defer c.lock.Unlock()
|
|
|
|
|
2019-02-22 19:58:07 +01:00
|
|
|
if c.cancelKeepAlive != nil {
|
|
|
|
c.cancelKeepAlive()
|
|
|
|
}
|
|
|
|
|
2015-06-22 18:34:02 +02:00
|
|
|
if c.config.sshAgent != nil {
|
2016-12-27 01:29:32 +01:00
|
|
|
if err := c.config.sshAgent.Close(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if c.conn != nil {
|
|
|
|
conn := c.conn
|
|
|
|
c.conn = nil
|
|
|
|
return conn.Close()
|
2015-04-09 21:58:00 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Timeout implementation of communicator.Communicator interface
|
2015-04-10 20:34:46 +02:00
|
|
|
func (c *Communicator) Timeout() time.Duration {
|
2015-04-09 21:58:00 +02:00
|
|
|
return c.connInfo.TimeoutVal
|
|
|
|
}
|
|
|
|
|
2015-04-10 20:34:46 +02:00
|
|
|
// ScriptPath implementation of communicator.Communicator interface
|
|
|
|
func (c *Communicator) ScriptPath() string {
|
2016-12-06 09:11:32 +01:00
|
|
|
randLock.Lock()
|
|
|
|
defer randLock.Unlock()
|
|
|
|
|
2015-04-30 18:02:33 +02:00
|
|
|
return strings.Replace(
|
|
|
|
c.connInfo.ScriptPath, "%RAND%",
|
2016-12-06 09:11:32 +01:00
|
|
|
strconv.FormatInt(int64(randShared.Int31()), 10), -1)
|
2015-04-09 21:58:00 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Start implementation of communicator.Communicator interface
|
2015-04-10 20:34:46 +02:00
|
|
|
func (c *Communicator) Start(cmd *remote.Cmd) error {
|
2018-03-15 15:50:17 +01:00
|
|
|
cmd.Init()
|
|
|
|
|
2014-07-10 23:52:43 +02:00
|
|
|
session, err := c.newSession()
|
|
|
|
if err != nil {
|
2015-04-09 21:58:00 +02:00
|
|
|
return err
|
2014-07-10 23:52:43 +02:00
|
|
|
}
|
|
|
|
|
2021-01-26 20:39:11 +01:00
|
|
|
// Set up our session
|
2014-07-10 23:52:43 +02:00
|
|
|
session.Stdin = cmd.Stdin
|
|
|
|
session.Stdout = cmd.Stdout
|
|
|
|
session.Stderr = cmd.Stderr
|
|
|
|
|
2020-11-12 16:00:48 +01:00
|
|
|
if !c.config.noPty && c.connInfo.TargetPlatform != TargetPlatformWindows {
|
2014-07-10 23:52:43 +02:00
|
|
|
// Request a PTY
|
|
|
|
termModes := ssh.TerminalModes{
|
|
|
|
ssh.ECHO: 0, // do not echo
|
|
|
|
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
|
|
|
|
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
|
|
|
|
}
|
|
|
|
|
2015-04-09 21:58:00 +02:00
|
|
|
if err := session.RequestPty("xterm", 80, 40, termModes); err != nil {
|
|
|
|
return err
|
2014-07-10 23:52:43 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-05 16:22:30 +02:00
|
|
|
log.Printf("[DEBUG] starting remote command: %s", cmd.Command)
|
2018-03-15 15:50:17 +01:00
|
|
|
err = session.Start(strings.TrimSpace(cmd.Command) + "\n")
|
2014-07-10 23:52:43 +02:00
|
|
|
if err != nil {
|
2015-04-09 21:58:00 +02:00
|
|
|
return err
|
2014-07-10 23:52:43 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Start a goroutine to wait for the session to end and set the
|
|
|
|
// exit boolean and status.
|
|
|
|
go func() {
|
|
|
|
defer session.Close()
|
|
|
|
|
|
|
|
err := session.Wait()
|
|
|
|
exitStatus := 0
|
|
|
|
if err != nil {
|
|
|
|
exitErr, ok := err.(*ssh.ExitError)
|
|
|
|
if ok {
|
|
|
|
exitStatus = exitErr.ExitStatus()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-15 15:50:17 +01:00
|
|
|
cmd.SetExitStatus(exitStatus, err)
|
2018-04-05 16:22:30 +02:00
|
|
|
log.Printf("[DEBUG] remote command exited with '%d': %s", exitStatus, cmd.Command)
|
2014-07-10 23:52:43 +02:00
|
|
|
}()
|
|
|
|
|
2015-04-09 21:58:00 +02:00
|
|
|
return nil
|
2014-07-10 23:52:43 +02:00
|
|
|
}
|
|
|
|
|
2015-04-09 21:58:00 +02:00
|
|
|
// Upload implementation of communicator.Communicator interface
|
2015-04-10 20:34:46 +02:00
|
|
|
func (c *Communicator) Upload(path string, input io.Reader) error {
|
2014-07-10 23:52:43 +02:00
|
|
|
// The target directory and file for talking the SCP protocol
|
2014-08-07 20:19:08 +02:00
|
|
|
targetDir := filepath.Dir(path)
|
2014-08-07 19:53:18 +02:00
|
|
|
targetFile := filepath.Base(path)
|
2014-07-10 23:52:43 +02:00
|
|
|
|
2014-08-07 09:19:56 +02:00
|
|
|
// On windows, filepath.Dir uses backslash separators (ie. "\tmp").
|
2014-07-10 23:52:43 +02:00
|
|
|
// This does not work when the target host is unix. Switch to forward slash
|
|
|
|
// which works for unix and windows
|
2014-08-07 20:19:08 +02:00
|
|
|
targetDir = filepath.ToSlash(targetDir)
|
2014-07-10 23:52:43 +02:00
|
|
|
|
2017-02-09 22:41:07 +01:00
|
|
|
// Skip copying if we can get the file size directly from common io.Readers
|
|
|
|
size := int64(0)
|
|
|
|
|
|
|
|
switch src := input.(type) {
|
|
|
|
case *os.File:
|
|
|
|
fi, err := src.Stat()
|
|
|
|
if err != nil {
|
|
|
|
size = fi.Size()
|
|
|
|
}
|
|
|
|
case *bytes.Buffer:
|
|
|
|
size = int64(src.Len())
|
|
|
|
case *bytes.Reader:
|
|
|
|
size = int64(src.Len())
|
|
|
|
case *strings.Reader:
|
|
|
|
size = int64(src.Len())
|
|
|
|
}
|
|
|
|
|
2014-07-10 23:52:43 +02:00
|
|
|
scpFunc := func(w io.Writer, stdoutR *bufio.Reader) error {
|
2017-02-09 22:41:07 +01:00
|
|
|
return scpUploadFile(targetFile, input, w, stdoutR, size)
|
2014-07-10 23:52:43 +02:00
|
|
|
}
|
|
|
|
|
2021-06-15 19:04:01 +02:00
|
|
|
cmd, err := quoteShell([]string{"scp", "-vt", targetDir}, c.connInfo.TargetPlatform)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return c.scpSession(cmd, scpFunc)
|
2014-07-10 23:52:43 +02:00
|
|
|
}
|
|
|
|
|
2015-04-09 21:58:00 +02:00
|
|
|
// UploadScript implementation of communicator.Communicator interface
|
2015-04-10 20:34:46 +02:00
|
|
|
func (c *Communicator) UploadScript(path string, input io.Reader) error {
|
2015-05-21 23:36:54 +02:00
|
|
|
reader := bufio.NewReader(input)
|
|
|
|
prefix, err := reader.Peek(2)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Error reading script: %s", err)
|
|
|
|
}
|
|
|
|
var script bytes.Buffer
|
2020-11-12 16:00:48 +01:00
|
|
|
|
|
|
|
if string(prefix) != "#!" && c.connInfo.TargetPlatform != TargetPlatformWindows {
|
2015-05-21 23:36:54 +02:00
|
|
|
script.WriteString(DefaultShebang)
|
|
|
|
}
|
|
|
|
script.ReadFrom(reader)
|
2020-11-12 16:00:48 +01:00
|
|
|
|
2015-05-21 23:36:54 +02:00
|
|
|
if err := c.Upload(path, &script); err != nil {
|
2015-04-09 21:58:00 +02:00
|
|
|
return err
|
|
|
|
}
|
2020-11-12 16:00:48 +01:00
|
|
|
if c.connInfo.TargetPlatform != TargetPlatformWindows {
|
|
|
|
var stdout, stderr bytes.Buffer
|
|
|
|
cmd := &remote.Cmd{
|
|
|
|
Command: fmt.Sprintf("chmod 0777 %s", path),
|
|
|
|
Stdout: &stdout,
|
|
|
|
Stderr: &stderr,
|
|
|
|
}
|
|
|
|
if err := c.Start(cmd); err != nil {
|
|
|
|
return fmt.Errorf(
|
|
|
|
"Error chmodding script file to 0777 in remote "+
|
|
|
|
"machine: %s", err)
|
|
|
|
}
|
2015-04-09 21:58:00 +02:00
|
|
|
|
2020-11-12 16:00:48 +01:00
|
|
|
if err := cmd.Wait(); err != nil {
|
|
|
|
return fmt.Errorf(
|
|
|
|
"Error chmodding script file to 0777 in remote "+
|
|
|
|
"machine %v: %s %s", err, stdout.String(), stderr.String())
|
|
|
|
}
|
2015-05-04 22:43:38 +02:00
|
|
|
}
|
2015-04-09 21:58:00 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// UploadDir implementation of communicator.Communicator interface
|
2015-04-10 20:34:46 +02:00
|
|
|
func (c *Communicator) UploadDir(dst string, src string) error {
|
2018-04-05 16:22:30 +02:00
|
|
|
log.Printf("[DEBUG] Uploading dir '%s' to '%s'", src, dst)
|
2014-07-10 23:52:43 +02:00
|
|
|
scpFunc := func(w io.Writer, r *bufio.Reader) error {
|
|
|
|
uploadEntries := func() error {
|
|
|
|
f, err := os.Open(src)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
|
|
|
entries, err := f.Readdir(-1)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return scpUploadDir(src, entries, w, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
if src[len(src)-1] != '/' {
|
2018-04-05 16:22:30 +02:00
|
|
|
log.Printf("[DEBUG] No trailing slash, creating the source directory name")
|
2014-07-10 23:52:43 +02:00
|
|
|
return scpUploadDirProtocol(filepath.Base(src), w, r, uploadEntries)
|
2014-08-21 07:24:35 +02:00
|
|
|
}
|
2014-08-07 20:29:02 +02:00
|
|
|
// Trailing slash, so only upload the contents
|
|
|
|
return uploadEntries()
|
2014-07-10 23:52:43 +02:00
|
|
|
}
|
|
|
|
|
2021-06-15 19:04:01 +02:00
|
|
|
cmd, err := quoteShell([]string{"scp", "-rvt", dst}, c.connInfo.TargetPlatform)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return c.scpSession(cmd, scpFunc)
|
2014-07-10 23:52:43 +02:00
|
|
|
}
|
|
|
|
|
2015-04-10 20:34:46 +02:00
|
|
|
func (c *Communicator) newSession() (session *ssh.Session, err error) {
|
2018-04-05 16:22:30 +02:00
|
|
|
log.Println("[DEBUG] opening new ssh session")
|
2014-07-10 23:52:43 +02:00
|
|
|
if c.client == nil {
|
2018-04-05 16:54:59 +02:00
|
|
|
err = errors.New("ssh client is not connected")
|
2014-07-10 23:52:43 +02:00
|
|
|
} else {
|
|
|
|
session, err = c.client.NewSession()
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
2018-04-05 16:22:30 +02:00
|
|
|
log.Printf("[WARN] ssh session open error: '%s', attempting reconnect", err)
|
2015-04-09 21:58:00 +02:00
|
|
|
if err := c.Connect(nil); err != nil {
|
2014-07-10 23:52:43 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return c.client.NewSession()
|
|
|
|
}
|
|
|
|
|
|
|
|
return session, nil
|
|
|
|
}
|
|
|
|
|
2015-04-10 20:34:46 +02:00
|
|
|
func (c *Communicator) scpSession(scpCommand string, f func(io.Writer, *bufio.Reader) error) error {
|
2014-07-10 23:52:43 +02:00
|
|
|
session, err := c.newSession()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer session.Close()
|
|
|
|
|
|
|
|
// Get a pipe to stdin so that we can send data down
|
|
|
|
stdinW, err := session.StdinPipe()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// We only want to close once, so we nil w after we close it,
|
|
|
|
// and only close in the defer if it hasn't been closed already.
|
|
|
|
defer func() {
|
|
|
|
if stdinW != nil {
|
|
|
|
stdinW.Close()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Get a pipe to stdout so that we can get responses back
|
|
|
|
stdoutPipe, err := session.StdoutPipe()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
stdoutR := bufio.NewReader(stdoutPipe)
|
|
|
|
|
|
|
|
// Set stderr to a bytes buffer
|
|
|
|
stderr := new(bytes.Buffer)
|
|
|
|
session.Stderr = stderr
|
|
|
|
|
|
|
|
// Start the sink mode on the other side
|
|
|
|
// TODO(mitchellh): There are probably issues with shell escaping the path
|
2018-04-05 16:22:30 +02:00
|
|
|
log.Println("[DEBUG] Starting remote scp process: ", scpCommand)
|
2014-07-10 23:52:43 +02:00
|
|
|
if err := session.Start(scpCommand); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Call our callback that executes in the context of SCP. We ignore
|
|
|
|
// EOF errors if they occur because it usually means that SCP prematurely
|
|
|
|
// ended on the other side.
|
2018-04-05 16:22:30 +02:00
|
|
|
log.Println("[DEBUG] Started SCP session, beginning transfers...")
|
2014-07-10 23:52:43 +02:00
|
|
|
if err := f(stdinW, stdoutR); err != nil && err != io.EOF {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close the stdin, which sends an EOF, and then set w to nil so that
|
|
|
|
// our defer func doesn't close it again since that is unsafe with
|
|
|
|
// the Go SSH package.
|
2018-04-05 16:22:30 +02:00
|
|
|
log.Println("[DEBUG] SCP session complete, closing stdin pipe.")
|
2014-07-10 23:52:43 +02:00
|
|
|
stdinW.Close()
|
|
|
|
stdinW = nil
|
|
|
|
|
|
|
|
// Wait for the SCP connection to close, meaning it has consumed all
|
|
|
|
// our data and has completed. Or has errored.
|
2018-04-05 16:22:30 +02:00
|
|
|
log.Println("[DEBUG] Waiting for SSH session to complete.")
|
2014-07-10 23:52:43 +02:00
|
|
|
err = session.Wait()
|
2019-02-21 19:42:46 +01:00
|
|
|
|
|
|
|
// log any stderr before exiting on an error
|
|
|
|
scpErr := stderr.String()
|
|
|
|
if len(scpErr) > 0 {
|
|
|
|
log.Printf("[ERROR] scp stderr: %q", stderr)
|
|
|
|
}
|
|
|
|
|
2014-07-10 23:52:43 +02:00
|
|
|
if err != nil {
|
|
|
|
if exitErr, ok := err.(*ssh.ExitError); ok {
|
|
|
|
// Otherwise, we have an ExitErorr, meaning we can just read
|
|
|
|
// the exit status
|
2018-04-05 16:22:30 +02:00
|
|
|
log.Printf("[ERROR] %s", exitErr)
|
2014-07-10 23:52:43 +02:00
|
|
|
|
|
|
|
// If we exited with status 127, it means SCP isn't available.
|
|
|
|
// Return a more descriptive error for that.
|
|
|
|
if exitErr.ExitStatus() == 127 {
|
|
|
|
return errors.New(
|
|
|
|
"SCP failed to start. This usually means that SCP is not\n" +
|
|
|
|
"properly installed on the remote system.")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// checkSCPStatus checks that a prior command sent to SCP completed
|
|
|
|
// successfully. If it did not complete successfully, an error will
|
|
|
|
// be returned.
|
|
|
|
func checkSCPStatus(r *bufio.Reader) error {
|
|
|
|
code, err := r.ReadByte()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if code != 0 {
|
|
|
|
// Treat any non-zero (really 1 and 2) as fatal errors
|
|
|
|
message, _, err := r.ReadLine()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Error reading error message: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return errors.New(string(message))
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-02-09 22:41:07 +01:00
|
|
|
func scpUploadFile(dst string, src io.Reader, w io.Writer, r *bufio.Reader, size int64) error {
|
|
|
|
if size == 0 {
|
|
|
|
// Create a temporary file where we can copy the contents of the src
|
|
|
|
// so that we can determine the length, since SCP is length-prefixed.
|
|
|
|
tf, err := ioutil.TempFile("", "terraform-upload")
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Error creating temporary file for upload: %s", err)
|
|
|
|
}
|
|
|
|
defer os.Remove(tf.Name())
|
|
|
|
defer tf.Close()
|
2014-07-10 23:52:43 +02:00
|
|
|
|
2018-04-05 16:22:30 +02:00
|
|
|
log.Println("[DEBUG] Copying input data into temporary file so we can read the length")
|
2017-02-09 22:41:07 +01:00
|
|
|
if _, err := io.Copy(tf, src); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2014-07-10 23:52:43 +02:00
|
|
|
|
2017-02-09 22:41:07 +01:00
|
|
|
// Sync the file so that the contents are definitely on disk, then
|
|
|
|
// read the length of it.
|
|
|
|
if err := tf.Sync(); err != nil {
|
|
|
|
return fmt.Errorf("Error creating temporary file for upload: %s", err)
|
|
|
|
}
|
2014-07-10 23:52:43 +02:00
|
|
|
|
2017-02-09 22:41:07 +01:00
|
|
|
// Seek the file to the beginning so we can re-read all of it
|
|
|
|
if _, err := tf.Seek(0, 0); err != nil {
|
|
|
|
return fmt.Errorf("Error creating temporary file for upload: %s", err)
|
|
|
|
}
|
2014-07-10 23:52:43 +02:00
|
|
|
|
2017-02-09 22:41:07 +01:00
|
|
|
fi, err := tf.Stat()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Error creating temporary file for upload: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
src = tf
|
|
|
|
size = fi.Size()
|
2014-07-10 23:52:43 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Start the protocol
|
2018-04-05 16:22:30 +02:00
|
|
|
log.Println("[DEBUG] Beginning file upload...")
|
2017-02-09 22:41:07 +01:00
|
|
|
fmt.Fprintln(w, "C0644", size, dst)
|
2014-07-10 23:52:43 +02:00
|
|
|
if err := checkSCPStatus(r); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2017-02-09 22:41:07 +01:00
|
|
|
if _, err := io.Copy(w, src); err != nil {
|
2014-07-10 23:52:43 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Fprint(w, "\x00")
|
|
|
|
if err := checkSCPStatus(r); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func scpUploadDirProtocol(name string, w io.Writer, r *bufio.Reader, f func() error) error {
|
2018-04-05 16:22:30 +02:00
|
|
|
log.Printf("[DEBUG] SCP: starting directory upload: %s", name)
|
2014-07-10 23:52:43 +02:00
|
|
|
fmt.Fprintln(w, "D0755 0", name)
|
|
|
|
err := checkSCPStatus(r)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := f(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Fprintln(w, "E")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func scpUploadDir(root string, fs []os.FileInfo, w io.Writer, r *bufio.Reader) error {
|
|
|
|
for _, fi := range fs {
|
|
|
|
realPath := filepath.Join(root, fi.Name())
|
|
|
|
|
|
|
|
// Track if this is actually a symlink to a directory. If it is
|
|
|
|
// a symlink to a file we don't do any special behavior because uploading
|
|
|
|
// a file just works. If it is a directory, we need to know so we
|
|
|
|
// treat it as such.
|
|
|
|
isSymlinkToDir := false
|
|
|
|
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
|
|
|
|
symPath, err := filepath.EvalSymlinks(realPath)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
symFi, err := os.Lstat(symPath)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
isSymlinkToDir = symFi.IsDir()
|
|
|
|
}
|
|
|
|
|
|
|
|
if !fi.IsDir() && !isSymlinkToDir {
|
|
|
|
// It is a regular file (or symlink to a file), just upload it
|
|
|
|
f, err := os.Open(realPath)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
err = func() error {
|
|
|
|
defer f.Close()
|
2017-02-09 22:41:07 +01:00
|
|
|
return scpUploadFile(fi.Name(), f, w, r, fi.Size())
|
2014-07-10 23:52:43 +02:00
|
|
|
}()
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// It is a directory, recursively upload
|
|
|
|
err := scpUploadDirProtocol(fi.Name(), w, r, func() error {
|
|
|
|
f, err := os.Open(realPath)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
|
|
|
entries, err := f.Readdir(-1)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return scpUploadDir(realPath, entries, w, r)
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2014-07-15 02:23:33 +02:00
|
|
|
|
|
|
|
// ConnectFunc is a convenience method for returning a function
|
|
|
|
// that just uses net.Dial to communicate with the remote end that
|
|
|
|
// is suitable for use with the SSH communicator configuration.
|
|
|
|
func ConnectFunc(network, addr string) func() (net.Conn, error) {
|
|
|
|
return func() (net.Conn, error) {
|
|
|
|
c, err := net.DialTimeout(network, addr, 15*time.Second)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if tcpConn, ok := c.(*net.TCPConn); ok {
|
|
|
|
tcpConn.SetKeepAlive(true)
|
|
|
|
}
|
|
|
|
|
|
|
|
return c, nil
|
|
|
|
}
|
|
|
|
}
|
2015-06-22 18:34:02 +02:00
|
|
|
|
|
|
|
// BastionConnectFunc is a convenience method for returning a function
|
|
|
|
// that connects to a host over a bastion connection.
|
|
|
|
func BastionConnectFunc(
|
|
|
|
bProto string,
|
|
|
|
bAddr string,
|
|
|
|
bConf *ssh.ClientConfig,
|
|
|
|
proto string,
|
|
|
|
addr string) func() (net.Conn, error) {
|
|
|
|
return func() (net.Conn, error) {
|
|
|
|
log.Printf("[DEBUG] Connecting to bastion: %s", bAddr)
|
|
|
|
bastion, err := ssh.Dial(bProto, bAddr, bConf)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Error connecting to bastion: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("[DEBUG] Connecting via bastion (%s) to host: %s", bAddr, addr)
|
|
|
|
conn, err := bastion.Dial(proto, addr)
|
|
|
|
if err != nil {
|
|
|
|
bastion.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wrap it up so we close both things properly
|
|
|
|
return &bastionConn{
|
|
|
|
Conn: conn,
|
|
|
|
Bastion: bastion,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type bastionConn struct {
|
|
|
|
net.Conn
|
|
|
|
Bastion *ssh.Client
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *bastionConn) Close() error {
|
|
|
|
c.Conn.Close()
|
|
|
|
return c.Bastion.Close()
|
|
|
|
}
|
2021-06-15 19:04:01 +02:00
|
|
|
|
|
|
|
func quoteShell(args []string, targetPlatform string) (string, error) {
|
|
|
|
if targetPlatform == TargetPlatformUnix {
|
|
|
|
return shquot.POSIXShell(args), nil
|
|
|
|
}
|
|
|
|
if targetPlatform == TargetPlatformWindows {
|
|
|
|
return shquot.WindowsArgv(args), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return "", fmt.Errorf("Cannot quote shell command, target platform unknown: %s", targetPlatform)
|
|
|
|
|
|
|
|
}
|