-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathpca.go
242 lines (201 loc) · 7.39 KB
/
pca.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/*
Copyright 2021 The Kubernetes Authors.
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 aws
import (
"bytes"
"context"
"crypto/md5"
"encoding/pem"
"fmt"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/service/acmpca"
acmpcatypes "github.com/aws/aws-sdk-go-v2/service/acmpca/types"
injections "github.com/cert-manager/aws-privateca-issuer/pkg/api/injections"
"github.com/go-logr/logr"
cmapi "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1"
"k8s.io/apimachinery/pkg/types"
)
const DEFAULT_DURATION = 30 * 24 * 3600
var collection = new(sync.Map)
// GenericProvisioner abstracts over the Provisioner type for mocking purposes
type GenericProvisioner interface {
Sign(ctx context.Context, cr *cmapi.CertificateRequest, log logr.Logger) ([]byte, []byte, error)
}
// acmPCAClient abstracts over the methods used from acmpca.Client
type acmPCAClient interface {
acmpca.GetCertificateAPIClient
DescribeCertificateAuthority(ctx context.Context, params *acmpca.DescribeCertificateAuthorityInput, optFns ...func(*acmpca.Options)) (*acmpca.DescribeCertificateAuthorityOutput, error)
IssueCertificate(ctx context.Context, params *acmpca.IssueCertificateInput, optFns ...func(*acmpca.Options)) (*acmpca.IssueCertificateOutput, error)
}
// PCAProvisioner contains logic for issuing PCA certificates
type PCAProvisioner struct {
pcaClient acmPCAClient
arn string
signingAlgorithm *acmpcatypes.SigningAlgorithm
clock func() time.Time
}
// GetProvisioner gets a provisioner that has previously been stored
func GetProvisioner(name types.NamespacedName) (GenericProvisioner, bool) {
value, exists := collection.Load(name)
if !exists {
return nil, exists
}
p, exists := value.(GenericProvisioner)
return p, exists
}
// StoreProvisioner stores a provisioner in the cache
func StoreProvisioner(name types.NamespacedName, provisioner GenericProvisioner) {
collection.Store(name, provisioner)
}
// NewProvisioner returns a new PCAProvisioner
func NewProvisioner(config aws.Config, arn string) (p *PCAProvisioner) {
return &PCAProvisioner{
pcaClient: acmpca.NewFromConfig(config, acmpca.WithAPIOptions(
middleware.AddUserAgentKeyValue("aws-privateca-issuer", injections.PlugInVersion),
)),
arn: arn,
}
}
// idempotencyToken is limited to 64 ASCII characters, so make a fixed length hash.
// @see: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html
func idempotencyToken(cr *cmapi.CertificateRequest) string {
token := []byte(cr.ObjectMeta.Namespace + "/" + cr.ObjectMeta.Name)
return fmt.Sprintf("%x", md5.Sum(token))
}
// Sign takes a certificate request and signs it using PCA
func (p *PCAProvisioner) Sign(ctx context.Context, cr *cmapi.CertificateRequest, log logr.Logger) ([]byte, []byte, error) {
block, _ := pem.Decode(cr.Spec.Request)
if block == nil {
return nil, nil, fmt.Errorf("failed to decode CSR")
}
validityExpiration := int64(p.now().Unix()) + DEFAULT_DURATION
if cr.Spec.Duration != nil {
validityExpiration = int64(p.now().Unix()) + int64(cr.Spec.Duration.Seconds())
}
tempArn := templateArn(p.arn, cr.Spec)
// Consider it a "retry" if we try to re-create a cert with the same name in the same namespace
token := idempotencyToken(cr)
err := getSigningAlgorithm(ctx, p)
if err != nil {
return nil, nil, err
}
issueParams := acmpca.IssueCertificateInput{
CertificateAuthorityArn: aws.String(p.arn),
SigningAlgorithm: *p.signingAlgorithm,
TemplateArn: aws.String(tempArn),
Csr: cr.Spec.Request,
Validity: &acmpcatypes.Validity{
Type: acmpcatypes.ValidityPeriodTypeAbsolute,
Value: &validityExpiration,
},
IdempotencyToken: aws.String(token),
}
issueOutput, err := p.pcaClient.IssueCertificate(ctx, &issueParams)
if err != nil {
return nil, nil, err
}
getParams := acmpca.GetCertificateInput{
CertificateArn: aws.String(*issueOutput.CertificateArn),
CertificateAuthorityArn: aws.String(p.arn),
}
log.Info("Created certificate with arn: " + *issueOutput.CertificateArn)
waiter := acmpca.NewCertificateIssuedWaiter(p.pcaClient)
err = waiter.Wait(ctx, &getParams, 5*time.Minute)
if err != nil {
return nil, nil, err
}
getOutput, err := p.pcaClient.GetCertificate(ctx, &getParams)
if err != nil {
return nil, nil, err
}
certPem := []byte(*getOutput.Certificate + "\n")
chainPem := []byte(*getOutput.CertificateChain)
chainIntCAs, rootCA, err := splitRootCACertificate(chainPem)
if err != nil {
return nil, nil, err
}
certPem = append(certPem, chainIntCAs...)
return certPem, rootCA, nil
}
func getSigningAlgorithm(ctx context.Context, p *PCAProvisioner) error {
if p.signingAlgorithm != nil {
return nil
}
describeParams := acmpca.DescribeCertificateAuthorityInput{
CertificateAuthorityArn: aws.String(p.arn),
}
describeOutput, err := p.pcaClient.DescribeCertificateAuthority(ctx, &describeParams)
if err != nil {
return err
}
p.signingAlgorithm = &describeOutput.CertificateAuthority.CertificateAuthorityConfiguration.SigningAlgorithm
return nil
}
func (p *PCAProvisioner) now() time.Time {
if p.clock != nil {
return p.clock()
}
return time.Now()
}
func templateArn(caArn string, spec cmapi.CertificateRequestSpec) string {
arn := strings.SplitAfterN(caArn, ":", 3)
prefix := arn[0] + arn[1]
if spec.IsCA {
return prefix + "acm-pca:::template/SubordinateCACertificate_PathLen0/V1"
}
if len(spec.Usages) == 1 {
switch spec.Usages[0] {
case cmapi.UsageCodeSigning:
return prefix + "acm-pca:::template/CodeSigningCertificate/V1"
case cmapi.UsageClientAuth:
return prefix + "acm-pca:::template/EndEntityClientAuthCertificate/V1"
case cmapi.UsageServerAuth:
return prefix + "acm-pca:::template/EndEntityServerAuthCertificate/V1"
case cmapi.UsageOCSPSigning:
return prefix + "acm-pca:::template/OCSPSigningCertificate/V1"
}
} else if len(spec.Usages) == 2 {
clientServer := (spec.Usages[0] == cmapi.UsageClientAuth && spec.Usages[1] == cmapi.UsageServerAuth)
serverClient := (spec.Usages[0] == cmapi.UsageServerAuth && spec.Usages[1] == cmapi.UsageClientAuth)
if clientServer || serverClient {
return prefix + "acm-pca:::template/EndEntityCertificate/V1"
}
}
return prefix + "acm-pca:::template/BlankEndEntityCertificate_APICSRPassthrough/V1"
}
func splitRootCACertificate(caCertChainPem []byte) ([]byte, []byte, error) {
var caChainCerts []byte
var rootCACert []byte
for {
block, rest := pem.Decode(caCertChainPem)
if block == nil || block.Type != "CERTIFICATE" {
return nil, nil, fmt.Errorf("failed to read certificate")
}
var encBuf bytes.Buffer
if err := pem.Encode(&encBuf, block); err != nil {
return nil, nil, err
}
if len(rest) > 0 {
caChainCerts = append(caChainCerts, encBuf.Bytes()...)
caCertChainPem = rest
} else {
rootCACert = append(rootCACert, encBuf.Bytes()...)
break
}
}
return caChainCerts, rootCACert, nil
}