From 6e223206aaa3ee38efd16537514284aaa0fd0095 Mon Sep 17 00:00:00 2001 From: Jeff Mitchell Date: Thu, 31 Aug 2017 18:20:41 -0400 Subject: [PATCH 1/2] Add pki/root/sign-self-issued. This is useful for root CA rolling, and is also suitably dangerous. Along the way I noticed we weren't setting the authority key IDs anywhere, so I addressed that. --- builtin/logical/pki/backend.go | 2 + builtin/logical/pki/cert_util.go | 16 ++-- builtin/logical/pki/path_root.go | 101 ++++++++++++++++---- website/source/api/secret/pki/index.html.md | 59 +++++++++++- 4 files changed, 154 insertions(+), 24 deletions(-) diff --git a/builtin/logical/pki/backend.go b/builtin/logical/pki/backend.go index 9d06b5129897..bf5168d44e28 100644 --- a/builtin/logical/pki/backend.go +++ b/builtin/logical/pki/backend.go @@ -42,6 +42,7 @@ func Backend() *backend { Root: []string{ "root", + "root/sign-self-issued", }, }, @@ -50,6 +51,7 @@ func Backend() *backend { pathRoles(&b), pathGenerateRoot(&b), pathSignIntermediate(&b), + pathSignSelfIssued(&b), pathDeleteRoot(&b), pathGenerateIntermediate(&b), pathSetSignedIntermediate(&b), diff --git a/builtin/logical/pki/cert_util.go b/builtin/logical/pki/cert_util.go index 02f232ecc610..29b60e618850 100644 --- a/builtin/logical/pki/cert_util.go +++ b/builtin/logical/pki/cert_util.go @@ -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 { @@ -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) } @@ -1059,6 +1061,8 @@ func signCertificate(creationInfo *creationBundle, } subjKeyID := sha1.Sum(marshaledKey) + caCert := creationInfo.SigningBundle.Certificate + subject := pkix.Name{ CommonName: creationInfo.CommonName, OrganizationalUnit: creationInfo.OU, @@ -1066,11 +1070,12 @@ func signCertificate(creationInfo *creationBundle, } 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 { @@ -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 diff --git a/builtin/logical/pki/path_root.go b/builtin/logical/pki/path_root.go index c96e99e4c04c..46f0dc1b11a5 100644 --- a/builtin/logical/pki/path_root.go +++ b/builtin/logical/pki/path_root.go @@ -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" @@ -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) { @@ -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. ` @@ -372,7 +441,6 @@ const pathSignIntermediateHelpDesc = ` see the API documentation for more information. ` -/* const pathSignSelfIssuedHelpSyn = ` Signs another CA's self-issued certificate. ` @@ -380,6 +448,5 @@ 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. ` -*/ diff --git a/website/source/api/secret/pki/index.html.md b/website/source/api/secret/pki/index.html.md index ba0b7f66607a..4f6a350b6d81 100644 --- a/website/source/api/secret/pki/index.html.md +++ b/website/source/api/secret/pki/index.html.md @@ -41,6 +41,7 @@ update your API calls accordingly. * [Generate Root](#generate-root) * [Delete Root](#delete-root) * [Sign Intermediate](#sign-intermediate) +* [Sign Self-Issued](#sign-self-issued) * [Sign Certificate](#sign-certificate) * [Sign Verbatim](#sign-verbatim) * [Tidy](#tidy) @@ -1073,7 +1074,6 @@ verbatim. { "csr": "...", "common_name": "example.com" - } ``` @@ -1103,6 +1103,63 @@ $ curl \ "auth": null } ``` +## Sign Self-Issued + +This endpoint uses the configured CA certificate to sign a self-issued +certificate (which will usually be a self-signed certificate as well). + +**_This is an extremely privileged endpoint_**. The given certificate will be +signed as-is with only minimal validation performed (is it a CA cert, and is it +actually self-issued). The only values that will be changed will be the +authority key ID and, if set, any distribution points. + +This is generally only needed for root certificate rolling. If you don't know +whether you need this endpoint, you most likely should be using a different +endpoint (such as `sign-intermediate`). + +This endpoint requires `sudo` capability. + +| Method | Path | Produces | +| :------- | :--------------------------- | :--------------------- | +| `POST` | `/pki/root/sign-self-issued` | `200 application/json` | + +### Parameters + +- `certificate` `(string: )` – Specifies the PEM-encoded self-issued certificate. + +### Sample Payload + +```json +{ + "certificate": "..." +} +``` + +### Sample Request + +``` +$ curl \ + --header "X-Vault-Token: ..." \ + --request POST \ + --data @payload.json \ + https://vault.rocks/v1/pki/root/sign-self-issued +``` + +### Sample Response + +```json +{ + "lease_id": "", + "renewable": false, + "lease_duration": 0, + "data": { + "certificate": "-----BEGIN CERTIFICATE-----\nMIIDzDCCAragAwIBAgIUOd0ukLcjH43TfTHFG9qE0FtlMVgwCwYJKoZIhvcNAQEL\n...\numkqeYeO30g1uYvDuWLXVA==\n-----END CERTIFICATE-----\n", + "issuing_ca": "-----BEGIN CERTIFICATE-----\nMIIDUTCCAjmgAwIBAgIJAKM+z4MSfw2mMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV\n...\nG/7g4koczXLoUM3OQXd5Aq2cs4SS1vODrYmgbioFsQ3eDHd1fg==\n-----END CERTIFICATE-----\n", + }, + "auth": null +} +``` + ## Sign Certificate From 7d42eec2a1f91994b42183feaac7e182b605719a Mon Sep 17 00:00:00 2001 From: Jeff Mitchell Date: Thu, 31 Aug 2017 23:06:42 -0400 Subject: [PATCH 2/2] Add tests --- builtin/logical/pki/backend_test.go | 156 ++++++++++++++++++++++++++++ 1 file changed, 156 insertions(+) diff --git a/builtin/logical/pki/backend_test.go b/builtin/logical/pki/backend_test.go index 35aed2a48a25..9aef6a5a3994 100644 --- a/builtin/logical/pki/backend_test.go +++ b/builtin/logical/pki/backend_test.go @@ -1,6 +1,7 @@ package pki import ( + "bytes" "crypto" "crypto/ecdsa" "crypto/elliptic" @@ -12,6 +13,7 @@ import ( "encoding/pem" "fmt" "math" + "math/big" mathrand "math/rand" "net" "os" @@ -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