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 1 commit
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
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.
`
*/
59 changes: 58 additions & 1 deletion website/source/api/secret/pki/index.html.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -1073,7 +1074,6 @@ verbatim.
{
"csr": "...",
"common_name": "example.com"

}
```

Expand Down Expand Up @@ -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: <required>)` – 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

Expand Down