github.com/rothwerx/packer@v0.9.0/builder/amazon/common/step_get_password.go (about)

     1  package common
     2  
     3  import (
     4  	"crypto/rsa"
     5  	"crypto/x509"
     6  	"encoding/base64"
     7  	"encoding/pem"
     8  	"errors"
     9  	"fmt"
    10  	"log"
    11  	"time"
    12  
    13  	"github.com/aws/aws-sdk-go/service/ec2"
    14  	"github.com/mitchellh/multistep"
    15  	"github.com/mitchellh/packer/helper/communicator"
    16  	"github.com/mitchellh/packer/packer"
    17  )
    18  
    19  // StepGetPassword reads the password from a Windows server and sets it
    20  // on the WinRM config.
    21  type StepGetPassword struct {
    22  	Debug   bool
    23  	Comm    *communicator.Config
    24  	Timeout time.Duration
    25  }
    26  
    27  func (s *StepGetPassword) Run(state multistep.StateBag) multistep.StepAction {
    28  	ui := state.Get("ui").(packer.Ui)
    29  
    30  	// Skip if we're not using winrm
    31  	if s.Comm.Type != "winrm" {
    32  		log.Printf("[INFO] Not using winrm communicator, skipping get password...")
    33  		return multistep.ActionContinue
    34  	}
    35  
    36  	// If we already have a password, skip it
    37  	if s.Comm.WinRMPassword != "" {
    38  		ui.Say("Skipping waiting for password since WinRM password set...")
    39  		return multistep.ActionContinue
    40  	}
    41  
    42  	// Get the password
    43  	var password string
    44  	var err error
    45  	cancel := make(chan struct{})
    46  	waitDone := make(chan bool, 1)
    47  	go func() {
    48  		ui.Say("Waiting for auto-generated password for instance...")
    49  		ui.Message(
    50  			"It is normal for this process to take up to 15 minutes,\n" +
    51  				"but it usually takes around 5. Please wait.")
    52  		password, err = s.waitForPassword(state, cancel)
    53  		waitDone <- true
    54  	}()
    55  
    56  	timeout := time.After(s.Timeout)
    57  WaitLoop:
    58  	for {
    59  		// Wait for either SSH to become available, a timeout to occur,
    60  		// or an interrupt to come through.
    61  		select {
    62  		case <-waitDone:
    63  			if err != nil {
    64  				ui.Error(fmt.Sprintf("Error waiting for password: %s", err))
    65  				state.Put("error", err)
    66  				return multistep.ActionHalt
    67  			}
    68  
    69  			ui.Message(fmt.Sprintf(" \nPassword retrieved!"))
    70  			s.Comm.WinRMPassword = password
    71  			break WaitLoop
    72  		case <-timeout:
    73  			err := fmt.Errorf("Timeout waiting for password.")
    74  			state.Put("error", err)
    75  			ui.Error(err.Error())
    76  			close(cancel)
    77  			return multistep.ActionHalt
    78  		case <-time.After(1 * time.Second):
    79  			if _, ok := state.GetOk(multistep.StateCancelled); ok {
    80  				// The step sequence was cancelled, so cancel waiting for password
    81  				// and just start the halting process.
    82  				close(cancel)
    83  				log.Println("[WARN] Interrupt detected, quitting waiting for password.")
    84  				return multistep.ActionHalt
    85  			}
    86  		}
    87  	}
    88  
    89  	// In debug-mode, we output the password
    90  	if s.Debug {
    91  		ui.Message(fmt.Sprintf(
    92  			"Password (since debug is enabled): %s", s.Comm.WinRMPassword))
    93  	}
    94  
    95  	return multistep.ActionContinue
    96  }
    97  
    98  func (s *StepGetPassword) Cleanup(multistep.StateBag) {}
    99  
   100  func (s *StepGetPassword) waitForPassword(state multistep.StateBag, cancel <-chan struct{}) (string, error) {
   101  	ec2conn := state.Get("ec2").(*ec2.EC2)
   102  	instance := state.Get("instance").(*ec2.Instance)
   103  	privateKey := state.Get("privateKey").(string)
   104  
   105  	for {
   106  		select {
   107  		case <-cancel:
   108  			log.Println("[INFO] Retrieve password wait cancelled. Exiting loop.")
   109  			return "", errors.New("Retrieve password wait cancelled")
   110  		case <-time.After(5 * time.Second):
   111  		}
   112  
   113  		resp, err := ec2conn.GetPasswordData(&ec2.GetPasswordDataInput{
   114  			InstanceId: instance.InstanceId,
   115  		})
   116  		if err != nil {
   117  			err := fmt.Errorf("Error retrieving auto-generated instance password: %s", err)
   118  			return "", err
   119  		}
   120  
   121  		if resp.PasswordData != nil && *resp.PasswordData != "" {
   122  			decryptedPassword, err := decryptPasswordDataWithPrivateKey(
   123  				*resp.PasswordData, []byte(privateKey))
   124  			if err != nil {
   125  				err := fmt.Errorf("Error decrypting auto-generated instance password: %s", err)
   126  				return "", err
   127  			}
   128  
   129  			return decryptedPassword, nil
   130  		}
   131  
   132  		log.Printf("[DEBUG] Password is blank, will retry...")
   133  	}
   134  }
   135  
   136  func decryptPasswordDataWithPrivateKey(passwordData string, pemBytes []byte) (string, error) {
   137  	encryptedPasswd, err := base64.StdEncoding.DecodeString(passwordData)
   138  	if err != nil {
   139  		return "", err
   140  	}
   141  
   142  	block, _ := pem.Decode(pemBytes)
   143  	var asn1Bytes []byte
   144  	if _, ok := block.Headers["DEK-Info"]; ok {
   145  		return "", errors.New("encrypted private key isn't yet supported")
   146  		/*
   147  			asn1Bytes, err = x509.DecryptPEMBlock(block, password)
   148  			if err != nil {
   149  				return "", err
   150  			}
   151  		*/
   152  	} else {
   153  		asn1Bytes = block.Bytes
   154  	}
   155  
   156  	key, err := x509.ParsePKCS1PrivateKey(asn1Bytes)
   157  	if err != nil {
   158  		return "", err
   159  	}
   160  
   161  	out, err := rsa.DecryptPKCS1v15(nil, key, encryptedPasswd)
   162  	if err != nil {
   163  		return "", err
   164  	}
   165  
   166  	return string(out), nil
   167  }