github.com/StackPointCloud/packer@v0.10.2-0.20180716202532-b28098e0f79b/builder/null/ssh.go (about)

     1  package null
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"net"
     7  	"os"
     8  
     9  	"github.com/hashicorp/packer/communicator/ssh"
    10  	"github.com/hashicorp/packer/helper/multistep"
    11  	gossh "golang.org/x/crypto/ssh"
    12  	"golang.org/x/crypto/ssh/agent"
    13  )
    14  
    15  func CommHost(host string) func(multistep.StateBag) (string, error) {
    16  	return func(state multistep.StateBag) (string, error) {
    17  		return host, nil
    18  	}
    19  }
    20  
    21  // SSHConfig returns a function that can be used for the SSH communicator
    22  // config for connecting to the specified host via SSH
    23  // private_key_file has precedence over password!
    24  func SSHConfig(useAgent bool, username string, password string, privateKeyFile string) func(multistep.StateBag) (*gossh.ClientConfig, error) {
    25  	return func(state multistep.StateBag) (*gossh.ClientConfig, error) {
    26  		if useAgent {
    27  			authSock := os.Getenv("SSH_AUTH_SOCK")
    28  			if authSock == "" {
    29  				return nil, fmt.Errorf("SSH_AUTH_SOCK is not set")
    30  			}
    31  
    32  			sshAgent, err := net.Dial("unix", authSock)
    33  			if err != nil {
    34  				return nil, fmt.Errorf("Cannot connect to SSH Agent socket %q: %s", authSock, err)
    35  			}
    36  
    37  			return &gossh.ClientConfig{
    38  				User: username,
    39  				Auth: []gossh.AuthMethod{
    40  					gossh.PublicKeysCallback(agent.NewClient(sshAgent).Signers),
    41  				},
    42  				HostKeyCallback: gossh.InsecureIgnoreHostKey(),
    43  			}, nil
    44  		}
    45  
    46  		if privateKeyFile != "" {
    47  			// key based auth
    48  
    49  			bytes, err := ioutil.ReadFile(privateKeyFile)
    50  			if err != nil {
    51  				return nil, fmt.Errorf("Error setting up SSH config: %s", err)
    52  			}
    53  			privateKey := string(bytes)
    54  
    55  			signer, err := gossh.ParsePrivateKey([]byte(privateKey))
    56  			if err != nil {
    57  				return nil, fmt.Errorf("Error setting up SSH config: %s", err)
    58  			}
    59  
    60  			return &gossh.ClientConfig{
    61  				User: username,
    62  				Auth: []gossh.AuthMethod{
    63  					gossh.PublicKeys(signer),
    64  				},
    65  				HostKeyCallback: gossh.InsecureIgnoreHostKey(),
    66  			}, nil
    67  		} else {
    68  			// password based auth
    69  
    70  			return &gossh.ClientConfig{
    71  				User: username,
    72  				Auth: []gossh.AuthMethod{
    73  					gossh.Password(password),
    74  					gossh.KeyboardInteractive(
    75  						ssh.PasswordKeyboardInteractive(password)),
    76  				},
    77  				HostKeyCallback: gossh.InsecureIgnoreHostKey(),
    78  			}, nil
    79  		}
    80  	}
    81  }