Skip to content
Open
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
43 changes: 43 additions & 0 deletions pkg/aws/pca.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
"bytes"
"context"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
Expand Down Expand Up @@ -181,6 +183,21 @@ func idempotencyToken(cr *cmapi.CertificateRequest) string {
return fullHash[:36] // Truncate to 36 characters
}

// extractNameConstraints finds the Name Constraints extension in the request and
// returns its raw ASN.1 bytes. Returns (nil, nil) if the extension is not present.
func extractNameConstraints(req *x509.CertificateRequest) ([]byte, error) {
var nc []byte
oidNameConstraints := []int{2, 5, 29, 30} // OID for Name Constraints
for _, ext := range req.Extensions {
if ext.Id.Equal(oidNameConstraints) {
nc = ext.Value
break
}
}

return nc, nil
}

// Sign takes a certificate request and signs it using PCA
func (p *PCAProvisioner) Sign(ctx context.Context, cr *cmapi.CertificateRequest, log logr.Logger) error {
block, _ := pem.Decode(cr.Spec.Request)
Expand All @@ -203,11 +220,37 @@ func (p *PCAProvisioner) Sign(ctx context.Context, cr *cmapi.CertificateRequest,
return err
}

crX509, err := x509.ParseCertificateRequest(block.Bytes)
if err != nil {
return err
}

nameConstraints, err := extractNameConstraints(crX509)
if err != nil {
return err
}

var apiPassthrough *acmpcatypes.ApiPassthrough
if nameConstraints != nil {
apiPassthrough = &acmpcatypes.ApiPassthrough{
Extensions: &acmpcatypes.Extensions{
CustomExtensions: []acmpcatypes.CustomExtension{
{
ObjectIdentifier: aws.String("2.5.29.30"), // OID for Name Constraints
Value: aws.String(base64.StdEncoding.EncodeToString(nameConstraints)),
Critical: aws.Bool(true),
},
},
},
Comment on lines +236 to +244
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we create a function to generate the extensions blob? This way in the future someone just has to add to that function instead of changing all this logic around (and by extensions the tests).

We can say something like "if list empty return nil", which will make the api passthrough blob look like {subject: nil, extensions:nil}, which acts as if the object is not present.

Picturing something like

if nameConstraints {
    add custom extension for name constraints to list
}

if otherExtension {
    addCustomExtensions
}

return list.empty() ? nil : extensions { list }

}
}

issueParams := acmpca.IssueCertificateInput{
CertificateAuthorityArn: aws.String(p.arn),
SigningAlgorithm: *p.signingAlgorithm,
TemplateArn: aws.String(tempArn),
Csr: cr.Spec.Request,
ApiPassthrough: apiPassthrough,
Validity: &acmpcatypes.Validity{
Type: acmpcatypes.ValidityPeriodTypeAbsolute,
Value: &validityExpiration,
Expand Down
101 changes: 101 additions & 0 deletions pkg/aws/pca_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
Expand Down Expand Up @@ -818,6 +820,105 @@ func TestPCASign(t *testing.T) {
}
}

// --- ApiPassthrough tests ---

// ASN.1 structure for GeneralSubtree (RFC 5280)
type GeneralSubtree struct {
Base asn1.RawValue
Minimum int `asn1:"optional,default:0"`
Maximum int `asn1:"optional"`
}

// ASN.1 structure for NameConstraints (RFC 5280)
type NameConstraints struct {
Permitted []GeneralSubtree `asn1:"tag:0,optional"`
Excluded []GeneralSubtree `asn1:"tag:1,optional"`
}

func createCSRWithNameConstraints() ([]byte, error) {

nc := NameConstraints{
Permitted: []GeneralSubtree{{Base: asn1.RawValue{Tag: 2, Class: asn1.ClassContextSpecific, Bytes: []byte("permitted.com")}}},
Excluded: []GeneralSubtree{{Base: asn1.RawValue{Tag: 2, Class: asn1.ClassContextSpecific, Bytes: []byte("excluded.com")}}},
}
ncBytes, err := asn1.Marshal(nc)
if err != nil {
return nil, err
}

ext := pkix.Extension{
Id: asn1.ObjectIdentifier{2, 5, 29, 30},
Value: ncBytes,
Critical: true,
}
tpl := x509.CertificateRequest{
Subject: pkix.Name{CommonName: "with-nc"},
ExtraExtensions: []pkix.Extension{ext},
}
key, _ := rsa.GenerateKey(rand.Reader, 2048)
csrBytes, err := x509.CreateCertificateRequest(rand.Reader, &tpl, key)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrBytes}), nil
}

func createCSRWithoutNameConstraints() ([]byte, error) {
tpl := x509.CertificateRequest{
Subject: pkix.Name{CommonName: "no-nc"},
}
key, _ := rsa.GenerateKey(rand.Reader, 2048)
csrBytes, err := x509.CreateCertificateRequest(rand.Reader, &tpl, key)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrBytes}), nil
}

func TestPCASign_ApiPassthrough(t *testing.T) {
client := &workingACMPCAClient{}
provisioner := PCAProvisioner{arn: arn, pcaClient: client}

// With Name Constraints
csrWithNC, err := createCSRWithNameConstraints()
require.NoError(t, err)
crWithNC := &cmapi.CertificateRequest{
Spec: cmapi.CertificateRequestSpec{Request: csrWithNC},
}
_ = provisioner.Sign(context.TODO(), crWithNC, logr.Discard())
got := client.issueCertInput
if assert.NotNil(t, got, "Expected IssueCertificateInput with Name Constraints") {
assert.NotNil(t, got.ApiPassthrough, "ApiPassthrough should be set when Name Constraints present")
if assert.NotNil(t, got.ApiPassthrough.Extensions) {
// This assumes only one custom extension is present. If support
// for additional extensions via apiPassthrough is added, this
// test will need to be updated.
Comment on lines +893 to +895
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we future proof this test?

assert.Len(t, got.ApiPassthrough.Extensions.CustomExtensions, 1)
ext := got.ApiPassthrough.Extensions.CustomExtensions[0]
assert.Equal(t, "2.5.29.30", *ext.ObjectIdentifier)
assert.True(t, *ext.Critical)
// Decode and check permitted/excluded DNS names
ncBytes, err := base64.StdEncoding.DecodeString(*ext.Value)
require.NoError(t, err)
// Look for 'permitted.com' and 'excluded.com' in the raw bytes
assert.Contains(t, string(ncBytes), "permitted.com", "Permitted DNS name should be present")
assert.Contains(t, string(ncBytes), "excluded.com", "Excluded DNS name should be present")
}
}

// Without Name Constraints
csrNoNC, err := createCSRWithoutNameConstraints()
require.NoError(t, err)
crNoNC := &cmapi.CertificateRequest{
Spec: cmapi.CertificateRequestSpec{Request: csrNoNC},
}
_ = provisioner.Sign(context.TODO(), crNoNC, logr.Discard())
got = client.issueCertInput
if assert.NotNil(t, got, "Expected IssueCertificateInput without Name Constraints") {
assert.Nil(t, got.ApiPassthrough, "ApiPassthrough should be nil when Name Constraints absent")
}
}

func TestPCASignValidity(t *testing.T) {
now := time.Now()
client := &workingACMPCAClient{}
Expand Down