-
Notifications
You must be signed in to change notification settings - Fork 2k
/
match.go
269 lines (230 loc) · 9.2 KB
/
match.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/*
Copyright 2020 The cert-manager 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 pki
import (
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"net"
"fmt"
"reflect"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/sets"
cmapi "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1"
"github.com/cert-manager/cert-manager/pkg/util"
)
// PrivateKeyMatchesSpec returns an error if the private key bit size
// doesn't match the provided spec. RSA, Ed25519 and ECDSA are supported.
// If any error is returned, a list of violations will also be returned.
func PrivateKeyMatchesSpec(pk crypto.PrivateKey, spec cmapi.CertificateSpec) ([]string, error) {
spec = *spec.DeepCopy()
if spec.PrivateKey == nil {
spec.PrivateKey = &cmapi.CertificatePrivateKey{}
}
switch spec.PrivateKey.Algorithm {
case "", cmapi.RSAKeyAlgorithm:
return rsaPrivateKeyMatchesSpec(pk, spec)
case cmapi.Ed25519KeyAlgorithm:
return ed25519PrivateKeyMatchesSpec(pk, spec)
case cmapi.ECDSAKeyAlgorithm:
return ecdsaPrivateKeyMatchesSpec(pk, spec)
default:
return nil, fmt.Errorf("unrecognised key algorithm type %q", spec.PrivateKey.Algorithm)
}
}
func rsaPrivateKeyMatchesSpec(pk crypto.PrivateKey, spec cmapi.CertificateSpec) ([]string, error) {
rsaPk, ok := pk.(*rsa.PrivateKey)
if !ok {
return []string{"spec.privateKey.algorithm"}, nil
}
var violations []string
// TODO: we should not use implicit defaulting here, and instead rely on
// defaulting performed within the Kubernetes apiserver here.
// This requires careful handling in order to not interrupt users upgrading
// from older versions.
// The default RSA keySize is set to 2048.
keySize := MinRSAKeySize
if spec.PrivateKey.Size > 0 {
keySize = spec.PrivateKey.Size
}
if rsaPk.N.BitLen() != keySize {
violations = append(violations, "spec.privateKey.size")
}
return violations, nil
}
func ecdsaPrivateKeyMatchesSpec(pk crypto.PrivateKey, spec cmapi.CertificateSpec) ([]string, error) {
ecdsaPk, ok := pk.(*ecdsa.PrivateKey)
if !ok {
return []string{"spec.privateKey.algorithm"}, nil
}
var violations []string
// TODO: we should not use implicit defaulting here, and instead rely on
// defaulting performed within the Kubernetes apiserver here.
// This requires careful handling in order to not interrupt users upgrading
// from older versions.
// The default EC curve type is EC256
expectedKeySize := ECCurve256
if spec.PrivateKey.Size > 0 {
expectedKeySize = spec.PrivateKey.Size
}
if expectedKeySize != ecdsaPk.Curve.Params().BitSize {
violations = append(violations, "spec.privateKey.size")
}
return violations, nil
}
func ed25519PrivateKeyMatchesSpec(pk crypto.PrivateKey, spec cmapi.CertificateSpec) ([]string, error) {
_, ok := pk.(ed25519.PrivateKey)
if !ok {
return []string{"spec.privateKey.algorithm"}, nil
}
return nil, nil
}
func ipSlicesMatch(parsedIPs []net.IP, stringIPs []string) bool {
parsedStringIPs := make([]net.IP, len(stringIPs))
for i, s := range stringIPs {
parsedStringIPs[i] = net.ParseIP(s)
}
return util.EqualIPsUnsorted(parsedStringIPs, parsedIPs)
}
// RequestMatchesSpec compares a CertificateRequest with a CertificateSpec
// and returns a list of field names on the Certificate that do not match their
// counterpart fields on the CertificateRequest.
// If decoding the x509 certificate request fails, an error will be returned.
func RequestMatchesSpec(req *cmapi.CertificateRequest, spec cmapi.CertificateSpec) ([]string, error) {
x509req, err := DecodeX509CertificateRequestBytes(req.Spec.Request)
if err != nil {
return nil, err
}
// It is safe to mutate top-level fields in `spec` as it is not a pointer
// meaning changes will not effect the caller.
if spec.Subject == nil {
spec.Subject = &cmapi.X509Subject{}
}
var violations []string
if !ipSlicesMatch(x509req.IPAddresses, spec.IPAddresses) {
violations = append(violations, "spec.ipAddresses")
}
if !util.EqualUnsorted(URLsToString(x509req.URIs), spec.URIs) {
violations = append(violations, "spec.uris")
}
if !util.EqualUnsorted(x509req.EmailAddresses, spec.EmailAddresses) {
violations = append(violations, "spec.emailAddresses")
}
if !util.EqualUnsorted(x509req.DNSNames, spec.DNSNames) {
violations = append(violations, "spec.dnsNames")
}
if spec.LiteralSubject == "" {
// Comparing Subject fields
if x509req.Subject.CommonName != spec.CommonName {
violations = append(violations, "spec.commonName")
}
if x509req.Subject.SerialNumber != spec.Subject.SerialNumber {
violations = append(violations, "spec.subject.serialNumber")
}
if !util.EqualUnsorted(x509req.Subject.Organization, spec.Subject.Organizations) {
violations = append(violations, "spec.subject.organizations")
}
if !util.EqualUnsorted(x509req.Subject.Country, spec.Subject.Countries) {
violations = append(violations, "spec.subject.countries")
}
if !util.EqualUnsorted(x509req.Subject.Locality, spec.Subject.Localities) {
violations = append(violations, "spec.subject.localities")
}
if !util.EqualUnsorted(x509req.Subject.OrganizationalUnit, spec.Subject.OrganizationalUnits) {
violations = append(violations, "spec.subject.organizationalUnits")
}
if !util.EqualUnsorted(x509req.Subject.PostalCode, spec.Subject.PostalCodes) {
violations = append(violations, "spec.subject.postCodes")
}
if !util.EqualUnsorted(x509req.Subject.Province, spec.Subject.Provinces) {
violations = append(violations, "spec.subject.postCodes")
}
if !util.EqualUnsorted(x509req.Subject.StreetAddress, spec.Subject.StreetAddresses) {
violations = append(violations, "spec.subject.streetAddresses")
}
} else {
// we have a LiteralSubject
// parse the subject of the csr in the same way as we parse LiteralSubject and see whether the RDN Sequences match
rdnSequenceFromCertificateRequest, err := UnmarshalRawDerBytesToRDNSequence(x509req.RawSubject)
if err != nil {
return nil, err
}
rdnSequenceFromCertificate, err := UnmarshalSubjectStringToRDNSequence(spec.LiteralSubject)
if err != nil {
return nil, err
}
if !reflect.DeepEqual(rdnSequenceFromCertificate, rdnSequenceFromCertificateRequest) {
violations = append(violations, "spec.literalSubject")
}
}
if req.Spec.IsCA != spec.IsCA {
violations = append(violations, "spec.isCA")
}
if !util.EqualKeyUsagesUnsorted(req.Spec.Usages, spec.Usages) {
violations = append(violations, "spec.usages")
}
if req.Spec.Duration != nil && spec.Duration != nil &&
req.Spec.Duration.Duration != spec.Duration.Duration {
violations = append(violations, "spec.duration")
}
if !reflect.DeepEqual(req.Spec.IssuerRef, spec.IssuerRef) {
violations = append(violations, "spec.issuerRef")
}
// TODO: check spec.EncodeBasicConstraintsInRequest and spec.EncodeUsagesInRequest
return violations, nil
}
// SecretDataAltNamesMatchSpec will compare a Secret resource containing certificate
// data to a CertificateSpec and return a list of 'violations' for any fields that
// do not match their counterparts.
// This is a purposely less comprehensive check than RequestMatchesSpec as some
// issuers override/force certain fields.
func SecretDataAltNamesMatchSpec(secret *corev1.Secret, spec cmapi.CertificateSpec) ([]string, error) {
x509cert, err := DecodeX509CertificateBytes(secret.Data[corev1.TLSCertKey])
if err != nil {
return nil, err
}
var violations []string
// Perform a 'loose' check on the x509 certificate to determine if the
// commonName and dnsNames fields are up to date.
// This check allows names to move between the DNSNames and CommonName
// field freely in order to account for CAs behaviour of promoting DNSNames
// to be CommonNames or vice-versa.
expectedDNSNames := sets.NewString(spec.DNSNames...)
if spec.CommonName != "" {
expectedDNSNames.Insert(spec.CommonName)
}
allDNSNames := sets.NewString(x509cert.DNSNames...)
if x509cert.Subject.CommonName != "" {
allDNSNames.Insert(x509cert.Subject.CommonName)
}
if !allDNSNames.Equal(expectedDNSNames) {
// We know a mismatch occurred, so now determine which fields mismatched.
if (spec.CommonName != "" && !allDNSNames.Has(spec.CommonName)) || (x509cert.Subject.CommonName != "" && !expectedDNSNames.Has(x509cert.Subject.CommonName)) {
violations = append(violations, "spec.commonName")
}
if !allDNSNames.HasAll(spec.DNSNames...) || !expectedDNSNames.HasAll(x509cert.DNSNames...) {
violations = append(violations, "spec.dnsNames")
}
}
if !ipSlicesMatch(x509cert.IPAddresses, spec.IPAddresses) {
violations = append(violations, "spec.ipAddresses")
}
if !util.EqualUnsorted(URLsToString(x509cert.URIs), spec.URIs) {
violations = append(violations, "spec.uris")
}
if !util.EqualUnsorted(x509cert.EmailAddresses, spec.EmailAddresses) {
violations = append(violations, "spec.emailAddresses")
}
return violations, nil
}