VMware vSphere Integrated Containers provider (#206)
* Add Virtual Kubelet provider for VIC Initial virtual kubelet provider for VMware VIC. This provider currently handles creating and starting of a pod VM via the VIC portlayer and persona server. Image store handling via the VIC persona server. This provider currently requires the feature/wolfpack branch of VIC. * Added pod stop and delete. Also added node capacity. Added the ability to stop and delete pod VMs via VIC. Also retrieve node capacity information from the VCH. * Cleanup and readme file Some file clean up and added a Readme.md markdown file for the VIC provider. * Cleaned up errors, added function comments, moved operation code 1. Cleaned up error handling. Set standard for creating errors. 2. Added method prototype comments for all interface functions. 3. Moved PodCreator, PodStarter, PodStopper, and PodDeleter to a new folder. * Add mocking code and unit tests for podcache, podcreator, and podstarter Used the unit test framework used in VIC to handle assertions in the provider's unit test. Mocking code generated using OSS project mockery, which is compatible with the testify assertion framework. * Vendored packages for the VIC provider Requires feature/wolfpack branch of VIC and a few specific commit sha of projects used within VIC. * Implementation of POD Stopper and Deleter unit tests (#4) * Updated files for initial PR
This commit is contained in:
359
vendor/github.com/vmware/vic/pkg/certificate/certificate.go
generated
vendored
Normal file
359
vendor/github.com/vmware/vic/pkg/certificate/certificate.go
generated
vendored
Normal file
@@ -0,0 +1,359 @@
|
||||
// Copyright 2016-2017 VMware, Inc. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package certificate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha1"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"math/big"
|
||||
"net"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/vmware/vic/pkg/errors"
|
||||
"github.com/vmware/vic/pkg/trace"
|
||||
)
|
||||
|
||||
// Default certificate file names
|
||||
const (
|
||||
ClientCert = "cert.pem"
|
||||
ClientKey = "key.pem"
|
||||
ServerCert = "server-cert.pem"
|
||||
ServerKey = "server-key.pem"
|
||||
CACert = "ca.pem"
|
||||
CAKey = "ca-key.pem"
|
||||
)
|
||||
|
||||
func hashPublicKey(key *rsa.PublicKey) ([]byte, error) {
|
||||
b, err := x509.MarshalPKIXPublicKey(key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Unable to hash key: %s", err)
|
||||
}
|
||||
|
||||
h := sha1.New()
|
||||
h.Write(b)
|
||||
return h.Sum(nil), nil
|
||||
}
|
||||
|
||||
func template(org []string) *x509.Certificate {
|
||||
now := time.Now().UTC()
|
||||
// help address issues with clock drift
|
||||
notBefore := now.AddDate(0, 0, -1)
|
||||
notAfter := now.AddDate(1, 0, 0) // 1 year
|
||||
|
||||
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
|
||||
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
|
||||
if err != nil {
|
||||
err = errors.Errorf("Failed to generate random number: %s", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensure that org is set to something
|
||||
if len(org) == 0 {
|
||||
org = []string{"default"}
|
||||
}
|
||||
|
||||
template := x509.Certificate{
|
||||
SerialNumber: serialNumber,
|
||||
Subject: pkix.Name{
|
||||
Organization: org,
|
||||
},
|
||||
NotBefore: notBefore,
|
||||
NotAfter: notAfter,
|
||||
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageKeyAgreement,
|
||||
BasicConstraintsValid: true,
|
||||
}
|
||||
|
||||
return &template
|
||||
}
|
||||
|
||||
func templateWithKey(template *x509.Certificate, size int) (*x509.Certificate, *rsa.PrivateKey, error) {
|
||||
priv, err := rsa.GenerateKey(rand.Reader, size)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
keyID, err := hashPublicKey(&priv.PublicKey)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
template.SubjectKeyId = keyID
|
||||
template.PublicKey = priv.Public()
|
||||
|
||||
return template, priv, nil
|
||||
}
|
||||
|
||||
func templateWithCA(template *x509.Certificate) *x509.Certificate {
|
||||
template.IsCA = true
|
||||
template.KeyUsage |= x509.KeyUsageCertSign
|
||||
template.KeyUsage |= x509.KeyUsageKeyEncipherment
|
||||
template.KeyUsage |= x509.KeyUsageKeyAgreement
|
||||
template.ExtKeyUsage = nil
|
||||
|
||||
return template
|
||||
}
|
||||
|
||||
// templateAsClientOnly restricts the capabilities of the certificate to be only used for client auth
|
||||
func templateAsClientOnly(template *x509.Certificate) *x509.Certificate {
|
||||
template.KeyUsage = x509.KeyUsageDigitalSignature
|
||||
template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
|
||||
|
||||
return template
|
||||
}
|
||||
|
||||
// templateWithServer adds the capabilities of the certificate to be only used for server auth
|
||||
func templateWithServer(template *x509.Certificate, domain string) *x509.Certificate {
|
||||
template.ExtKeyUsage = append(template.ExtKeyUsage, x509.ExtKeyUsageServerAuth)
|
||||
|
||||
template.Subject.CommonName = domain
|
||||
|
||||
// abide by the spec - if CN is an IP, put it in the subjectAltName as well
|
||||
ip := net.ParseIP(domain)
|
||||
if ip == nil {
|
||||
// see if CIDR works
|
||||
// #nosec: Errors unhandled.
|
||||
ip, _, _ = net.ParseCIDR(domain)
|
||||
}
|
||||
|
||||
if ip != nil {
|
||||
// use the normalized address
|
||||
template.Subject.CommonName = ip.String()
|
||||
template.IPAddresses = []net.IP{ip}
|
||||
|
||||
// try best guess at DNSNames entries
|
||||
names, err := net.LookupAddr(domain)
|
||||
if err == nil && len(names) > 0 {
|
||||
template.DNSNames = names
|
||||
}
|
||||
|
||||
return template
|
||||
}
|
||||
|
||||
if domain != "" {
|
||||
template.DNSNames = []string{domain}
|
||||
|
||||
// try best guess at IPAddresses entries
|
||||
ips, err := net.LookupIP(domain)
|
||||
if err == nil && len(ips) > 0 {
|
||||
template.IPAddresses = ips
|
||||
}
|
||||
}
|
||||
|
||||
return template
|
||||
}
|
||||
|
||||
// createCertificate creates a certificate from the supplied template:
|
||||
// template: an x509 template describing the certificate to generate.
|
||||
// parent: either a CA certificate, or template (for self-signed). If nil, will use template.
|
||||
// templateKey: the private key for the certificate supplied as template
|
||||
// parentKey: the private key for the certificate supplied as parent (whether CA or self-signed). If nil will use templateKey
|
||||
//
|
||||
// return PEM encoded certificate and key
|
||||
func createCertificate(template, parent *x509.Certificate, templateKey, parentKey *rsa.PrivateKey) (cert bytes.Buffer, key bytes.Buffer, err error) {
|
||||
defer trace.End(trace.Begin(""))
|
||||
|
||||
if parent == nil {
|
||||
parent = template
|
||||
}
|
||||
|
||||
if parentKey == nil {
|
||||
parentKey = templateKey
|
||||
}
|
||||
|
||||
derBytes, err := x509.CreateCertificate(rand.Reader, template, parent, &templateKey.PublicKey, parentKey)
|
||||
if err != nil {
|
||||
err = errors.Errorf("Failed to generate x509 certificate: %s", err)
|
||||
return cert, key, err
|
||||
}
|
||||
|
||||
err = pem.Encode(&cert, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
|
||||
if err != nil {
|
||||
err = errors.Errorf("Failed to encode x509 certificate: %s", err)
|
||||
return cert, key, err
|
||||
}
|
||||
|
||||
err = pem.Encode(&key, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(templateKey)})
|
||||
if err != nil {
|
||||
err = errors.Errorf("Failed to encode tls key pairs: %s", err)
|
||||
return cert, key, err
|
||||
}
|
||||
|
||||
return cert, key, nil
|
||||
}
|
||||
|
||||
// saveCertificate saves the certificate and key to files of the form basename-cert.pem and basename-key.pem
|
||||
// cf and kf are the certificate file and key file respectively
|
||||
func saveCertificate(cf, kf string, cert, key *bytes.Buffer) error {
|
||||
defer trace.End(trace.Begin(""))
|
||||
|
||||
// #nosec: Expect file permissions to be 0600 or less
|
||||
certFile, err := os.OpenFile(cf, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
err = errors.Errorf("Failed to create certificate file %s: %s", cf, err)
|
||||
return err
|
||||
}
|
||||
defer certFile.Close()
|
||||
|
||||
_, err = certFile.Write(cert.Bytes())
|
||||
if err != nil {
|
||||
err = errors.Errorf("Failed to write certificate: %s", err)
|
||||
return err
|
||||
}
|
||||
|
||||
keyFile, err := os.OpenFile(kf, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
|
||||
if err != nil {
|
||||
err = errors.Errorf("Failed to create key file %s: %s", kf, err)
|
||||
return err
|
||||
}
|
||||
defer keyFile.Close()
|
||||
|
||||
_, err = keyFile.Write(key.Bytes())
|
||||
if err != nil {
|
||||
err = errors.Errorf("Failed to write key: %s", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadCertificate(cf, kf string) (*x509.Certificate, *rsa.PrivateKey, error) {
|
||||
defer trace.End(trace.Begin(""))
|
||||
|
||||
cb, err := ioutil.ReadFile(cf)
|
||||
if err != nil {
|
||||
err = errors.Errorf("Failed to read certificate file %s: %s", cf, err)
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
kb, err := ioutil.ReadFile(kf)
|
||||
if err != nil {
|
||||
err = errors.Errorf("Failed to read key file %s: %s", kf, err)
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return ParseCertificate(cb, kb)
|
||||
}
|
||||
|
||||
func ParseCertificate(cb, kb []byte) (*x509.Certificate, *rsa.PrivateKey, error) {
|
||||
defer trace.End(trace.Begin(""))
|
||||
|
||||
block, _ := pem.Decode(cb)
|
||||
cert, err := x509.ParseCertificate(block.Bytes)
|
||||
if err != nil {
|
||||
err = errors.Errorf("Failed to parse certificate data: %s", err)
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var key *rsa.PrivateKey
|
||||
block, _ = pem.Decode(kb)
|
||||
if block != nil {
|
||||
key, err = x509.ParsePKCS1PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
err = errors.Errorf("Failed to parse key data: %s", err)
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return cert, key, nil
|
||||
}
|
||||
|
||||
func CreateSelfSigned(domain string, org []string, size int) (cert bytes.Buffer, key bytes.Buffer, err error) {
|
||||
defer trace.End(trace.Begin(""))
|
||||
|
||||
template, pkey, err := templateWithKey(templateWithServer(template(org), domain), size)
|
||||
if err != nil {
|
||||
return cert, key, err
|
||||
}
|
||||
|
||||
return createCertificate(template, nil, pkey, nil)
|
||||
}
|
||||
|
||||
func CreateRootCA(domain string, org []string, size int) (cert bytes.Buffer, key bytes.Buffer, err error) {
|
||||
defer trace.End(trace.Begin(""))
|
||||
|
||||
template, pkey, err := templateWithKey(templateWithCA(template(org)), size)
|
||||
if err != nil {
|
||||
return cert, key, err
|
||||
}
|
||||
|
||||
return createCertificate(template, nil, pkey, nil)
|
||||
}
|
||||
|
||||
func CreateServerCertificate(domain string, org []string, size int, cb, kb []byte) (cert bytes.Buffer, key bytes.Buffer, err error) {
|
||||
defer trace.End(trace.Begin(""))
|
||||
|
||||
// Load up the CA
|
||||
cacert, cakey, err := ParseCertificate(cb, kb)
|
||||
if err != nil {
|
||||
return cert, key, err
|
||||
}
|
||||
|
||||
// Generate the new cert
|
||||
template, pkey, err := templateWithKey(templateWithServer(template(org), domain), size)
|
||||
if err != nil {
|
||||
return cert, key, err
|
||||
}
|
||||
|
||||
return createCertificate(template, cacert, pkey, cakey)
|
||||
}
|
||||
|
||||
func CreateClientCertificate(domain string, org []string, size int, cb, kb []byte) (cert bytes.Buffer, key bytes.Buffer, err error) {
|
||||
defer trace.End(trace.Begin(""))
|
||||
|
||||
// Load up the CA
|
||||
cacert, cakey, err := ParseCertificate(cb, kb)
|
||||
|
||||
// Generate the new cert
|
||||
template, pkey, err := templateWithKey(templateAsClientOnly(template(org)), size)
|
||||
if err != nil {
|
||||
return cert, key, err
|
||||
}
|
||||
|
||||
return createCertificate(template, cacert, pkey, cakey)
|
||||
}
|
||||
|
||||
// VerifyClientCert verifies the loaded client cert keypair against the input CA and
|
||||
// returns the certificate on success.
|
||||
func VerifyClientCert(ca []byte, ckp *KeyPair) (*tls.Certificate, error) {
|
||||
var err error
|
||||
|
||||
cert, err := ckp.Certificate()
|
||||
if err != nil || cert.Leaf == nil {
|
||||
return nil, CertParseError{msg: err.Error()}
|
||||
}
|
||||
|
||||
pool := x509.NewCertPool()
|
||||
if !pool.AppendCertsFromPEM(ca) {
|
||||
return nil, CreateCAPoolError{}
|
||||
}
|
||||
|
||||
opts := x509.VerifyOptions{
|
||||
Roots: pool,
|
||||
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
|
||||
}
|
||||
if _, err = cert.Leaf.Verify(opts); err != nil {
|
||||
return nil, CertVerifyError{}
|
||||
}
|
||||
|
||||
return cert, nil
|
||||
}
|
||||
122
vendor/github.com/vmware/vic/pkg/certificate/certificate_test.go
generated
vendored
Normal file
122
vendor/github.com/vmware/vic/pkg/certificate/certificate_test.go
generated
vendored
Normal file
@@ -0,0 +1,122 @@
|
||||
// Copyright 2016-2017 VMware, Inc. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package certificate
|
||||
|
||||
import (
|
||||
"crypto/x509"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
log "github.com/Sirupsen/logrus"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestCreateCA(t *testing.T) {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
|
||||
cacert, cakey, err := CreateRootCA("somewhere.com", []string{"MyOrg"}, 2048)
|
||||
assert.NoError(t, err, "Failed generating CA certificate")
|
||||
|
||||
_, _, err = ParseCertificate(cacert.Bytes(), cakey.Bytes())
|
||||
assert.NoError(t, err, "Failed reparsing CA certificate")
|
||||
|
||||
}
|
||||
|
||||
func TestSignedCertificate(t *testing.T) {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
|
||||
cacert, cakey, err := CreateRootCA("somewhere.com", []string{"MyOrg"}, 2048)
|
||||
assert.NoError(t, err, "Failed generating ca certificate")
|
||||
|
||||
cert, key, err := CreateServerCertificate("somewere.com", []string{"MyOrg"}, 2048, cacert.Bytes(), cakey.Bytes())
|
||||
assert.NoError(t, err, "Failed generating signed certificate")
|
||||
|
||||
// validate
|
||||
roots := x509.NewCertPool()
|
||||
ok := roots.AppendCertsFromPEM(cacert.Bytes())
|
||||
assert.Equal(t, true, ok, "Failed to append CA to roots")
|
||||
|
||||
opts := x509.VerifyOptions{
|
||||
Roots: roots,
|
||||
}
|
||||
|
||||
tlsCert, _, err := ParseCertificate(cert.Bytes(), key.Bytes())
|
||||
assert.NoError(t, err, "Failed loading signed certificate")
|
||||
|
||||
_, err = tlsCert.Verify(opts)
|
||||
assert.NoError(t, err, "Failed loading signed certificate")
|
||||
}
|
||||
|
||||
func TestFailedValidation(t *testing.T) {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
|
||||
cacert, cakey, err := CreateRootCA("somewhere.com", []string{"MyOrg"}, 2048)
|
||||
assert.NoError(t, err, "Failed generating ca certificate")
|
||||
|
||||
cert, key, err := CreateServerCertificate("somewere.com", []string{"MyOrg"}, 2048, cacert.Bytes(), cakey.Bytes())
|
||||
assert.NoError(t, err, "Failed generating signed certificate")
|
||||
|
||||
// validate
|
||||
roots := x509.NewCertPool()
|
||||
ok := roots.AppendCertsFromPEM(cacert.Bytes())
|
||||
assert.Equal(t, true, ok, "Failed to append CA to roots")
|
||||
|
||||
tlsCert, _, err := ParseCertificate(cert.Bytes(), key.Bytes())
|
||||
assert.NoError(t, err, "Failed loading signed certificate")
|
||||
|
||||
opts := x509.VerifyOptions{
|
||||
Roots: roots,
|
||||
DNSName: "somewhereELSE.com",
|
||||
}
|
||||
|
||||
_, err = tlsCert.Verify(opts)
|
||||
assert.Error(t, err, "Expected to fail initial verify")
|
||||
|
||||
opts = x509.VerifyOptions{
|
||||
Roots: roots,
|
||||
DNSName: "somewhere.com",
|
||||
}
|
||||
|
||||
_, err = tlsCert.Verify(opts)
|
||||
assert.Error(t, err, "Expected to pass second verify")
|
||||
|
||||
}
|
||||
|
||||
func TestVerifyClientCert(t *testing.T) {
|
||||
cacert, cakey, err := CreateRootCA("foo.com", []string{"FooOrg"}, 2048)
|
||||
assert.NoError(t, err)
|
||||
|
||||
cert, key, err := CreateClientCertificate("foo.com", []string{"FooOrg"}, 2048, cacert.Bytes(), cakey.Bytes())
|
||||
assert.NoError(t, err)
|
||||
|
||||
kp := NewKeyPair(ClientCert, ClientKey, cert.Bytes(), key.Bytes())
|
||||
err = kp.SaveCertificate()
|
||||
assert.NoError(t, err)
|
||||
defer func() {
|
||||
os.Remove(ClientCert)
|
||||
os.Remove(ClientKey)
|
||||
}()
|
||||
|
||||
// Validate client certificate keypair created with the right CA
|
||||
_, err = VerifyClientCert(cacert.Bytes(), kp)
|
||||
assert.NoError(t, err)
|
||||
|
||||
cacert, cakey, err = CreateRootCA("bar.com", []string{"BarOrg"}, 2048)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Attempt to validate client certificate keypair created with a different CA
|
||||
_, err = VerifyClientCert(cacert.Bytes(), kp)
|
||||
assert.NotNil(t, err)
|
||||
}
|
||||
40
vendor/github.com/vmware/vic/pkg/certificate/errors.go
generated
vendored
Normal file
40
vendor/github.com/vmware/vic/pkg/certificate/errors.go
generated
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
// Copyright 2017 VMware, Inc. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package certificate
|
||||
|
||||
import "fmt"
|
||||
|
||||
// CertParseError is returned when there's an error parsing a cert.
|
||||
type CertParseError struct {
|
||||
msg string
|
||||
}
|
||||
|
||||
func (e CertParseError) Error() string {
|
||||
return fmt.Sprintf("Unable to parse client certificate: %s", e.msg)
|
||||
}
|
||||
|
||||
// CreateCAPoolError is returned when there's an error creating a CA cert pool.
|
||||
type CreateCAPoolError struct{}
|
||||
|
||||
func (e CreateCAPoolError) Error() string {
|
||||
return "Unable to create CA pool to check client certificate"
|
||||
}
|
||||
|
||||
// CertVerifyError is returned when the client cert cannot be validated against the CA.
|
||||
type CertVerifyError struct{}
|
||||
|
||||
func (e CertVerifyError) Error() string {
|
||||
return "Client certificate in certificate path does not validate with provided CA"
|
||||
}
|
||||
127
vendor/github.com/vmware/vic/pkg/certificate/keypair.go
generated
vendored
Normal file
127
vendor/github.com/vmware/vic/pkg/certificate/keypair.go
generated
vendored
Normal file
@@ -0,0 +1,127 @@
|
||||
// Copyright 2016 VMware, Inc. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package certificate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"io/ioutil"
|
||||
|
||||
"github.com/vmware/vic/pkg/errors"
|
||||
)
|
||||
|
||||
type KeyPair struct {
|
||||
KeyPEM []byte
|
||||
CertPEM []byte
|
||||
|
||||
KeyFile string
|
||||
CertFile string
|
||||
}
|
||||
|
||||
func NewKeyPair(certFile, keyFile string, certPEM, keyPEM []byte) *KeyPair {
|
||||
return &KeyPair{
|
||||
KeyPEM: keyPEM,
|
||||
CertPEM: certPEM,
|
||||
KeyFile: keyFile,
|
||||
CertFile: certFile,
|
||||
}
|
||||
}
|
||||
|
||||
func (kp *KeyPair) LoadCertificate() error {
|
||||
c, err := ioutil.ReadFile(kp.CertFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
k, err := ioutil.ReadFile(kp.KeyFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
kp.CertPEM = c
|
||||
kp.KeyPEM = k
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (kp *KeyPair) SaveCertificate() error {
|
||||
return saveCertificate(kp.CertFile, kp.KeyFile, bytes.NewBuffer(kp.CertPEM), bytes.NewBuffer(kp.KeyPEM))
|
||||
}
|
||||
|
||||
func (kp *KeyPair) CreateSelfSigned(domain string, org []string, size int) error {
|
||||
c, k, err := CreateSelfSigned(domain, org, size)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
kp.CertPEM = c.Bytes()
|
||||
kp.KeyPEM = k.Bytes()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (kp *KeyPair) CreateRootCA(domain string, org []string, size int) error {
|
||||
c, k, err := CreateRootCA(domain, org, size)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
kp.CertPEM = c.Bytes()
|
||||
kp.KeyPEM = k.Bytes()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (kp *KeyPair) CreateServerCertificate(domain string, org []string, size int, ca *KeyPair) error {
|
||||
c, k, err := CreateServerCertificate(domain, org, size, ca.CertPEM, ca.KeyPEM)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
kp.CertPEM = c.Bytes()
|
||||
kp.KeyPEM = k.Bytes()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (kp *KeyPair) CreateClientCertificate(domain string, org []string, size int, ca *KeyPair) error {
|
||||
c, k, err := CreateClientCertificate(domain, org, size, ca.CertPEM, ca.KeyPEM)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
kp.CertPEM = c.Bytes()
|
||||
kp.KeyPEM = k.Bytes()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Certificate turns the KeyPair back into useful TLS constructs
|
||||
// This attempts to populate the certificate.Leaf field with the x509 certificate for convenience
|
||||
func (kp *KeyPair) Certificate() (*tls.Certificate, error) {
|
||||
if kp.CertPEM == nil || kp.KeyPEM == nil {
|
||||
return nil, errors.New("KeyPair has no data")
|
||||
}
|
||||
|
||||
cert, err := tls.X509KeyPair(kp.CertPEM, kp.KeyPEM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// #nosec: Errors unhandled.
|
||||
cert.Leaf, _, _ = ParseCertificate(kp.CertPEM, kp.KeyPEM)
|
||||
|
||||
return &cert, nil
|
||||
}
|
||||
122
vendor/github.com/vmware/vic/pkg/certificate/keypair_test.go
generated
vendored
Normal file
122
vendor/github.com/vmware/vic/pkg/certificate/keypair_test.go
generated
vendored
Normal file
@@ -0,0 +1,122 @@
|
||||
// Copyright 2016 VMware, Inc. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package certificate
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"crypto/tls"
|
||||
|
||||
log "github.com/Sirupsen/logrus"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/vmware/vic/pkg/trace"
|
||||
)
|
||||
|
||||
const (
|
||||
keyFile = "./key.pem"
|
||||
certFile = "./cert.pem"
|
||||
)
|
||||
|
||||
func TestMain(t *testing.T) {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
trace.Logger.Level = log.DebugLevel
|
||||
}
|
||||
|
||||
func TestCreateSelfSigned(t *testing.T) {
|
||||
cert, key, err := CreateSelfSigned("somewhere.com", []string{"MyOrg"}, 2048)
|
||||
if err != nil {
|
||||
t.Errorf("CreateSelfSigned failed with error %s", err)
|
||||
}
|
||||
|
||||
certString := cert.String()
|
||||
keyString := key.String()
|
||||
|
||||
log.Infof("cert: %s", certString)
|
||||
log.Infof("key: %s", keyString)
|
||||
|
||||
if !strings.HasPrefix(certString, "-----BEGIN CERTIFICATE-----") {
|
||||
t.Errorf("Certificate lacks proper prefix; must not have been generated properly.")
|
||||
}
|
||||
|
||||
if !strings.HasSuffix(certString, "-----END CERTIFICATE-----\n") {
|
||||
t.Errorf("Certificate lacks proper suffix; must not have been generated properly.")
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(keyString, "-----BEGIN RSA PRIVATE KEY-----") {
|
||||
t.Errorf("Private key lacks proper prefix; must not have been generated properly.")
|
||||
}
|
||||
|
||||
if !strings.HasSuffix(keyString, "-----END RSA PRIVATE KEY-----\n") {
|
||||
t.Errorf("Private key lacks proper suffix; must not have been generated properly.")
|
||||
}
|
||||
|
||||
_, err = tls.X509KeyPair([]byte(certString), []byte(keyString))
|
||||
if err != nil {
|
||||
t.Errorf("Unable to load X509 key pair(%s,%s): %s", certString, keyString, err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestGenerate(t *testing.T) {
|
||||
log.SetLevel(log.InfoLevel)
|
||||
if _, err := os.Stat(keyFile); err == nil {
|
||||
os.Remove(keyFile)
|
||||
}
|
||||
|
||||
pair := NewKeyPair(keyFile, certFile, nil, nil)
|
||||
|
||||
err := pair.CreateSelfSigned("somewhere.com", []string{"MyOrg"}, 2048)
|
||||
assert.NoError(t, err, "Failed generating self-signed certificate")
|
||||
|
||||
err = pair.SaveCertificate()
|
||||
assert.NoError(t, err, "Failed saving generated certificate")
|
||||
defer os.Remove(keyFile)
|
||||
defer os.Remove(certFile)
|
||||
|
||||
assert.NotEmpty(t, pair.KeyPEM, "Expected contents in key PEM data")
|
||||
assert.NotEmpty(t, pair.CertPEM, "Expected contents in cert PEM data")
|
||||
|
||||
_, err = os.Stat(keyFile)
|
||||
assert.NoError(t, err, "Key file was not created")
|
||||
|
||||
assert.Contains(t, string(pair.KeyPEM), "RSA PRIVATE KEY", "Key is not correctly generated")
|
||||
}
|
||||
|
||||
func TestGetCertificate(t *testing.T) {
|
||||
log.SetLevel(log.InfoLevel)
|
||||
if _, err := os.Stat(keyFile); err == nil {
|
||||
os.Remove(keyFile)
|
||||
}
|
||||
|
||||
pair := NewKeyPair(keyFile, certFile, nil, nil)
|
||||
|
||||
err := pair.CreateSelfSigned("somewhere.com", []string{"MyOrg"}, 2048)
|
||||
assert.NoError(t, err, "Failed generating self-signed certificate")
|
||||
|
||||
err = pair.SaveCertificate()
|
||||
assert.NoError(t, err, "Failed saving generated certificate")
|
||||
defer os.Remove(keyFile)
|
||||
defer os.Remove(certFile)
|
||||
|
||||
pair2 := NewKeyPair(keyFile, certFile, nil, nil)
|
||||
|
||||
err = pair2.LoadCertificate()
|
||||
assert.NoError(t, err, "Failed loading self-signed certificate")
|
||||
|
||||
assert.Equal(t, pair, pair2, "Expected loads to be consistent")
|
||||
}
|
||||
Reference in New Issue
Block a user