github.com/rahart/packer@v0.12.2-0.20161229105310-282bb6ad370f/builder/azure/common/lin/step_create_cert.go (about)

     1  // Copyright (c) Microsoft Corporation. All rights reserved.
     2  // Licensed under the MIT License. See the LICENSE file in builder/azure for license information.
     3  
     4  package lin
     5  
     6  import (
     7  	"crypto/rand"
     8  	"crypto/rsa"
     9  	"crypto/sha1"
    10  	"crypto/x509"
    11  	"crypto/x509/pkix"
    12  	"encoding/pem"
    13  	"fmt"
    14  	"log"
    15  	"math/big"
    16  	"time"
    17  
    18  	"github.com/mitchellh/packer/builder/azure/common/constants"
    19  
    20  	"github.com/mitchellh/multistep"
    21  	"github.com/mitchellh/packer/packer"
    22  )
    23  
    24  type StepCreateCert struct {
    25  	TmpServiceName string
    26  }
    27  
    28  func (s *StepCreateCert) Run(state multistep.StateBag) multistep.StepAction {
    29  	ui := state.Get("ui").(packer.Ui)
    30  
    31  	ui.Say("Creating temporary certificate...")
    32  
    33  	err := s.createCert(state)
    34  	if err != nil {
    35  		err = fmt.Errorf("Error creating temporary certificate: %s", err)
    36  		state.Put("error", err)
    37  		ui.Error(err.Error())
    38  		return multistep.ActionHalt
    39  	}
    40  
    41  	return multistep.ActionContinue
    42  }
    43  
    44  func (s *StepCreateCert) Cleanup(state multistep.StateBag) {}
    45  
    46  func (s *StepCreateCert) createCert(state multistep.StateBag) error {
    47  
    48  	log.Println("createCert: Generating RSA key pair...")
    49  
    50  	priv, err := rsa.GenerateKey(rand.Reader, 2048)
    51  	if err != nil {
    52  		err = fmt.Errorf("Failed to Generate Private Key: %s", err)
    53  		return err
    54  	}
    55  
    56  	// ASN.1 DER encoded form
    57  	privkey := string(pem.EncodeToMemory(&pem.Block{
    58  		Type:  "RSA PRIVATE KEY",
    59  		Bytes: x509.MarshalPKCS1PrivateKey(priv),
    60  	}))
    61  
    62  	// Set the private key in the state bag for later
    63  	state.Put(constants.PrivateKey, privkey)
    64  	log.Printf("createCert: Private key:\n%s", privkey)
    65  
    66  	log.Println("createCert: Creating certificate...")
    67  
    68  	host := fmt.Sprintf("%s.cloudapp.net", s.TmpServiceName)
    69  	notBefore := time.Now()
    70  	notAfter := notBefore.Add(365 * 24 * time.Hour)
    71  
    72  	serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
    73  	if err != nil {
    74  		err = fmt.Errorf("Failed to Generate Serial Number: %v", err)
    75  		return err
    76  	}
    77  
    78  	template := x509.Certificate{
    79  		SerialNumber: serialNumber,
    80  		Issuer: pkix.Name{
    81  			CommonName: host,
    82  		},
    83  		Subject: pkix.Name{
    84  			CommonName: host,
    85  		},
    86  		NotBefore: notBefore,
    87  		NotAfter:  notAfter,
    88  
    89  		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
    90  		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
    91  		BasicConstraintsValid: true,
    92  	}
    93  
    94  	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
    95  	if err != nil {
    96  		err = fmt.Errorf("Failed to Create Certificate: %s", err)
    97  		return err
    98  	}
    99  
   100  	cert := string(pem.EncodeToMemory(&pem.Block{
   101  		Type:  "RSA PRIVATE KEY",
   102  		Bytes: derBytes,
   103  	}))
   104  	state.Put(constants.Certificate, cert)
   105  	log.Printf("createCert: Certificate:\n%s", cert)
   106  
   107  	h := sha1.New()
   108  	h.Write(derBytes)
   109  	thumbprint := fmt.Sprintf("%X", h.Sum(nil))
   110  	state.Put(constants.Thumbprint, thumbprint)
   111  	log.Printf("createCert: Thumbprint:\n%s", thumbprint)
   112  
   113  	return nil
   114  }