Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pki/root/sign-self-issued. #3274

Merged
merged 2 commits into from
Sep 1, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions builtin/logical/pki/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ func Backend() *backend {

Root: []string{
"root",
"root/sign-self-issued",
},
},

Expand All @@ -50,6 +51,7 @@ func Backend() *backend {
pathRoles(&b),
pathGenerateRoot(&b),
pathSignIntermediate(&b),
pathSignSelfIssued(&b),
pathDeleteRoot(&b),
pathGenerateIntermediate(&b),
pathSetSignedIntermediate(&b),
Expand Down
156 changes: 156 additions & 0 deletions builtin/logical/pki/backend_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package pki

import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
Expand All @@ -12,6 +13,7 @@ import (
"encoding/pem"
"fmt"
"math"
"math/big"
mathrand "math/rand"
"net"
"os"
Expand Down Expand Up @@ -2459,6 +2461,160 @@ func TestBackend_Permitted_DNS_Domains(t *testing.T) {
checkIssue(true, "common_name", "host.xyz.com")
}

func TestBackend_SignSelfIssued(t *testing.T) {
// create the backend
config := logical.TestBackendConfig()
storage := &logical.InmemStorage{}
config.StorageView = storage

b := Backend()
err := b.Setup(config)
if err != nil {
t.Fatal(err)
}

// generate root
rootData := map[string]interface{}{
"common_name": "test.com",
"ttl": "172800",
}

resp, err := b.HandleRequest(&logical.Request{
Operation: logical.UpdateOperation,
Path: "root/generate/internal",
Storage: storage,
Data: rootData,
})
if resp != nil && resp.IsError() {
t.Fatalf("failed to generate root, %#v", *resp)
}
if err != nil {
t.Fatal(err)
}

key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}

getSelfSigned := func(subject, issuer *x509.Certificate) (string, *x509.Certificate) {
selfSigned, err := x509.CreateCertificate(rand.Reader, subject, issuer, key.Public(), key)
if err != nil {
t.Fatal(err)
}
cert, err := x509.ParseCertificate(selfSigned)
if err != nil {
t.Fatal(err)
}
pemSS := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: selfSigned,
})
return string(pemSS), cert
}

template := &x509.Certificate{
Subject: pkix.Name{
CommonName: "foo.bar.com",
},
SerialNumber: big.NewInt(1234),
IsCA: false,
BasicConstraintsValid: true,
}

ss, _ := getSelfSigned(template, template)
resp, err = b.HandleRequest(&logical.Request{
Operation: logical.UpdateOperation,
Path: "root/sign-self-issued",
Storage: storage,
Data: map[string]interface{}{
"certificate": ss,
},
})
if err != nil {
t.Fatal(err)
}
if resp == nil {
t.Fatal("got nil response")
}
if !resp.IsError() {
t.Fatalf("expected error due to non-CA; got: %#v", *resp)
}

// Set CA to true, but leave issuer alone
template.IsCA = true

issuer := &x509.Certificate{
Subject: pkix.Name{
CommonName: "bar.foo.com",
},
SerialNumber: big.NewInt(2345),
IsCA: true,
BasicConstraintsValid: true,
}
ss, ssCert := getSelfSigned(template, issuer)
resp, err = b.HandleRequest(&logical.Request{
Operation: logical.UpdateOperation,
Path: "root/sign-self-issued",
Storage: storage,
Data: map[string]interface{}{
"certificate": ss,
},
})
if err != nil {
t.Fatal(err)
}
if resp == nil {
t.Fatal("got nil response")
}
if !resp.IsError() {
t.Fatalf("expected error due to different issuer; cert info is\nIssuer\n%#v\nSubject\n%#v\n", ssCert.Issuer, ssCert.Subject)
}

ss, ssCert = getSelfSigned(template, template)
resp, err = b.HandleRequest(&logical.Request{
Operation: logical.UpdateOperation,
Path: "root/sign-self-issued",
Storage: storage,
Data: map[string]interface{}{
"certificate": ss,
},
})
if err != nil {
t.Fatal(err)
}
if resp == nil {
t.Fatal("got nil response")
}
if resp.IsError() {
t.Fatalf("error in response: %s", resp.Error().Error())
}

newCertString := resp.Data["certificate"].(string)
block, _ := pem.Decode([]byte(newCertString))
newCert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
t.Fatal(err)
}

signingBundle, err := fetchCAInfo(&logical.Request{Storage: storage})
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(newCert.Subject, newCert.Issuer) {
t.Fatal("expected same subject/issuer")
}
if bytes.Equal(newCert.AuthorityKeyId, newCert.SubjectKeyId) {
t.Fatal("expected different authority/subject")
}
if !bytes.Equal(newCert.AuthorityKeyId, signingBundle.Certificate.SubjectKeyId) {
t.Fatal("expected authority on new cert to be same as signing subject")
}
if newCert.Subject.CommonName != "foo.bar.com" {
t.Fatalf("unexpected common name on new cert: %s", newCert.Subject.CommonName)
}
}

const (
rsaCAKey string = `-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAmPQlK7xD5p+E8iLQ8XlVmll5uU2NKMxKY3UF5tbh+0vkc+Fy
Expand Down
16 changes: 10 additions & 6 deletions builtin/logical/pki/cert_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -929,6 +929,7 @@ func createCertificate(creationInfo *creationBundle) (*certutil.ParsedCertBundle
}

caCert := creationInfo.SigningBundle.Certificate
certTemplate.AuthorityKeyId = caCert.SubjectKeyId

err = checkPermittedDNSDomains(certTemplate, caCert)
if err != nil {
Expand All @@ -952,6 +953,7 @@ func createCertificate(creationInfo *creationBundle) (*certutil.ParsedCertBundle
certTemplate.SignatureAlgorithm = x509.ECDSAWithSHA256
}

certTemplate.AuthorityKeyId = subjKeyID
certTemplate.BasicConstraintsValid = true
certBytes, err = x509.CreateCertificate(rand.Reader, certTemplate, certTemplate, result.PrivateKey.Public(), result.PrivateKey)
}
Expand Down Expand Up @@ -1059,18 +1061,21 @@ func signCertificate(creationInfo *creationBundle,
}
subjKeyID := sha1.Sum(marshaledKey)

caCert := creationInfo.SigningBundle.Certificate

subject := pkix.Name{
CommonName: creationInfo.CommonName,
OrganizationalUnit: creationInfo.OU,
Organization: creationInfo.Organization,
}

certTemplate := &x509.Certificate{
SerialNumber: serialNumber,
Subject: subject,
NotBefore: time.Now().Add(-30 * time.Second),
NotAfter: creationInfo.NotAfter,
SubjectKeyId: subjKeyID[:],
SerialNumber: serialNumber,
Subject: subject,
NotBefore: time.Now().Add(-30 * time.Second),
NotAfter: creationInfo.NotAfter,
SubjectKeyId: subjKeyID[:],
AuthorityKeyId: caCert.SubjectKeyId,
}

switch creationInfo.SigningBundle.PrivateKeyType {
Expand All @@ -1097,7 +1102,6 @@ func signCertificate(creationInfo *creationBundle,
addKeyUsages(creationInfo, certTemplate)

var certBytes []byte
caCert := creationInfo.SigningBundle.Certificate

certTemplate.IssuingCertificateURL = creationInfo.URLs.IssuingCertificates
certTemplate.CRLDistributionPoints = creationInfo.URLs.CRLDistributionPoints
Expand Down
101 changes: 84 additions & 17 deletions builtin/logical/pki/path_root.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
package pki

import (
"crypto/rand"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"reflect"
"time"

"github.com/hashicorp/errwrap"
"github.com/hashicorp/vault/helper/errutil"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
Expand Down Expand Up @@ -82,33 +87,27 @@ the non-repudiation flag.`,
return ret
}

/*
func pathSignSelfIssued(b *backend) *framework.Path {
ret := &framework.Path{
Pattern: "root/sign-self-issued",

Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathCASignIntermediate,
logical.UpdateOperation: b.pathCASignSelfIssued,
},

Fields: map[string]*framework.FieldSchema{
"certificate": &framework.FieldSchema{
Type: framework.TypeString,
Description: `PEM-format self-issued certificate to be signed.`,
},
},

HelpSynopsis: pathSignSelfIssuedHelpSyn,
HelpDescription: pathSignSelfIssuedHelpDesc,
}

ret.Fields["certificate"] = &framework.FieldSchema{
Type: framework.TypeString,
Default: "",
Description: `PEM-format self-issued certificate to be signed.`,
}

ret.Fields["ttl"] = &framework.FieldSchema{
Type: framework.TypeDurationSecond,
Description: `Time-to-live for the signed certificate. This is not bounded by the lifetime of this root CA.`,
}

return ret
}
*/

func (b *backend) pathCADeleteRoot(
req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
Expand Down Expand Up @@ -348,6 +347,76 @@ func (b *backend) pathCASignIntermediate(
return resp, nil
}

func (b *backend) pathCASignSelfIssued(
req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
var err error

certPem := data.Get("certificate").(string)
block, _ := pem.Decode([]byte(certPem))
if block == nil || len(block.Bytes) == 0 {
return logical.ErrorResponse("certificate could not be PEM-decoded"), nil
}
certs, err := x509.ParseCertificates(block.Bytes)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("error parsing certificate: %s", err)), nil
}
if len(certs) != 1 {
return logical.ErrorResponse(fmt.Sprintf("%d certificates found in PEM file, expected 1", len(certs))), nil
}

cert := certs[0]
if !cert.IsCA {
return logical.ErrorResponse("given certificate is not a CA certificate"), nil
}
if !reflect.DeepEqual(cert.Issuer, cert.Subject) {
return logical.ErrorResponse("given certificate is not self-issued"), nil
}

var caErr error
signingBundle, caErr := fetchCAInfo(req)
switch caErr.(type) {
case errutil.UserError:
return nil, errutil.UserError{Err: fmt.Sprintf(
"could not fetch the CA certificate (was one set?): %s", caErr)}
case errutil.InternalError:
return nil, errutil.InternalError{Err: fmt.Sprintf(
"error fetching CA certificate: %s", caErr)}
}

signingCB, err := signingBundle.ToCertBundle()
if err != nil {
return nil, fmt.Errorf("Error converting raw signing bundle to cert bundle: %s", err)
}

cert.AuthorityKeyId = signingBundle.Certificate.SubjectKeyId
urls := &urlEntries{}
if signingBundle.URLs != nil {
urls = signingBundle.URLs
}
cert.IssuingCertificateURL = urls.IssuingCertificates
cert.CRLDistributionPoints = urls.CRLDistributionPoints
cert.OCSPServer = urls.OCSPServers

newCert, err := x509.CreateCertificate(rand.Reader, cert, cert, signingBundle.PrivateKey.Public(), signingBundle.PrivateKey)
if err != nil {
return nil, errwrap.Wrapf("error signing self-issued certificate: {{err}}", err)
}
if len(newCert) == 0 {
return nil, fmt.Errorf("nil cert was created when signing self-issued certificate")
}
pemCert := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: newCert,
})

return &logical.Response{
Data: map[string]interface{}{
"certificate": string(pemCert),
"issuing_ca": signingCB.Certificate,
},
}, nil
}

const pathGenerateRootHelpSyn = `
Generate a new CA certificate and private key used for signing.
`
Expand All @@ -372,14 +441,12 @@ const pathSignIntermediateHelpDesc = `
see the API documentation for more information.
`

/*
const pathSignSelfIssuedHelpSyn = `
Signs another CA's self-issued certificate.
`

const pathSignSelfIssuedHelpDesc = `
Signs another CA's self-issued certificate. This is most often used for rolling roots; unless you know you need this you probably want to use sign-intermediate instead.

Note that this is a very "god-mode" operation and should be extremely restricted in terms of who is allowed to use it. All values will be taken directly from the incoming certificate and no verification of host names, path lengths, or any other values will be performed.
Note that this is a very privileged operation and should be extremely restricted in terms of who is allowed to use it. All values will be taken directly from the incoming certificate and no verification of host names, path lengths, or any other values will be performed.
`
*/
Loading