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