github.com/marksheahan/packer@v0.10.2-0.20160613200515-1acb2d6645a0/helper/communicator/ssh.go (about)

     1  package communicator
     2  
     3  import (
     4  	"encoding/pem"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"os"
     8  
     9  	"golang.org/x/crypto/ssh"
    10  )
    11  
    12  // SSHFileSigner returns an ssh.Signer for a key file.
    13  func SSHFileSigner(path string) (ssh.Signer, error) {
    14  	f, err := os.Open(path)
    15  	if err != nil {
    16  		return nil, err
    17  	}
    18  	defer f.Close()
    19  
    20  	keyBytes, err := ioutil.ReadAll(f)
    21  	if err != nil {
    22  		return nil, err
    23  	}
    24  
    25  	// We parse the private key on our own first so that we can
    26  	// show a nicer error if the private key has a password.
    27  	block, _ := pem.Decode(keyBytes)
    28  	if block == nil {
    29  		return nil, fmt.Errorf(
    30  			"Failed to read key '%s': no key found", path)
    31  	}
    32  	if block.Headers["Proc-Type"] == "4,ENCRYPTED" {
    33  		return nil, fmt.Errorf(
    34  			"Failed to read key '%s': password protected keys are\n"+
    35  				"not supported. Please decrypt the key prior to use.", path)
    36  	}
    37  
    38  	signer, err := ssh.ParsePrivateKey(keyBytes)
    39  	if err != nil {
    40  		return nil, fmt.Errorf("Error setting up SSH config: %s", err)
    41  	}
    42  
    43  	return signer, nil
    44  }