Debian Codegraph @

x509/ekcert_test.go

raw
1 package x509ext
2
3 import (
4 "crypto"
5 "crypto/rand"
6 "crypto/rsa"
7 "crypto/x509"
8 "crypto/x509/pkix"
9 "encoding/asn1"
10 "errors"
11 "math/big"
12 "testing"
13 "time"
14
15 "github.com/google/go-attestation/oid"
16 "github.com/google/go-cmp/cmp"
17 "github.com/google/go-cmp/cmp/cmpopts"
18 )
19
20 var (
21 SAN = &SubjectAltName{
22 DirectoryNames: []pkix.Name{
23 {
24 ExtraNames: []pkix.AttributeTypeAndValue{
25 {Type: oid.TPMManufacturer, Value: "id:12345"},
26 {Type: oid.TPMModel, Value: "vTPM"},
27 {Type: oid.TPMVersion, Value: "id:246810"},
28 },
29 },
30 },
31 }
32 tpmSpec = TpmSpecification{
33 Family: "2.0",
34 Level: 1,
35 Revision: 48,
36 }
37
38 keySize = 2048
39 )
40
41 func generateRSAPrivateKey(t *testing.T) crypto.Signer {
42 privateKey, err := rsa.GenerateKey(rand.Reader, keySize)
43 if err != nil {
44 t.Fatalf("failed to generate RSA private key: %v", err)
45 }
46
47 return privateKey
48 }
49
50 // selfSignedCert creates a self-signed certificate.
51 func selfSignedCert(t *testing.T, signer crypto.Signer) *x509.Certificate {
52 template := &x509.Certificate{
53 SerialNumber: big.NewInt(1),
54 IsCA: true,
55 NotBefore: time.Date(2024, 01, 01, 0, 0, 0, 0, time.UTC),
56 NotAfter: time.Date(2034, 01, 01, 0, 0, 0, 0, time.UTC),
57 Subject: pkix.Name{CommonName: "Test Signer"},
58 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
59 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
60 BasicConstraintsValid: true,
61 }
62
63 certBytes, err := x509.CreateCertificate(nil, template, template, signer.Public(), signer)
64 if err != nil {
65 t.Fatalf("x509.CreateCertificate() failed: %v", err)
66 }
67 cert, err := x509.ParseCertificate(certBytes)
68 if err != nil {
69 t.Fatalf("x509.ParseCertificate() failed: %v", err)
70 }
71 return cert
72 }
73
74 // setupTestCert creates a new x509.Certificate for each test.
75 func setupTestCert(t *testing.T, modifyCertTemplate func(*testing.T, *x509.Certificate)) *x509.Certificate {
76 t.Helper()
77 privateKey := generateRSAPrivateKey(t)
78 parentCert := selfSignedCert(t, privateKey)
79 template := &x509.Certificate{
80 SerialNumber: big.NewInt(1234),
81 Version: 3,
82 Issuer: pkix.Name{
83 CommonName: "Test CA",
84 },
85 Subject: pkix.Name{
86 CommonName: "test-common-name",
87 },
88 KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement,
89 BasicConstraintsValid: true,
90 IsCA: false,
91 ExtraExtensions: []pkix.Extension{
92 createSubjectAltNameExtension(t, SAN, false),
93 createSubjectDirectoryAttributesExtension(t, tpmSpec, false),
94 },
95 AuthorityKeyId: []byte("test-authority-key-id"),
96 UnknownExtKeyUsage: []asn1.ObjectIdentifier{oid.EKCertificate},
97 }
98
99 if modifyCertTemplate != nil {
100 modifyCertTemplate(t, template)
101 }
102 certBytes, err := x509.CreateCertificate(rand.Reader, template, parentCert, generateRSAPrivateKey(t).Public(), privateKey)
103 if err != nil {
104 t.Fatalf("Failed to create certificate: %v", err)
105 }
106
107 cert, err := x509.ParseCertificate(certBytes)
108 if err != nil {
109 t.Fatalf("Failed to parse created certificate: %v", err)
110 }
111
112 return cert
113 }
114
115 // createSubjectAltNameExtension creates a new pkix.Extension for the SubjectAltName extension.
116 func createSubjectAltNameExtension(t *testing.T, san *SubjectAltName, critical bool) pkix.Extension {
117 t.Helper()
118 marshalledSAN, err := MarshalSubjectAltName(san, critical)
119 if err != nil {
120 t.Fatalf("Failed to marshal SubjectAltName: %v", err)
121 }
122 return pkix.Extension{
123 Id: oid.SubjectAltName,
124 Critical: critical,
125 Value: marshalledSAN.Value,
126 }
127 }
128
129 // createSubjectDirectoryAttributesExtension creates a new pkix.Extension for the SubjectDirectoryAttributes extension.
130 func createSubjectDirectoryAttributesExtension(t *testing.T, tpmSpec TpmSpecification, critical bool) pkix.Extension {
131 t.Helper()
132 tpmSpecBytes, err := asn1.Marshal(tpmSpec)
133 if err != nil {
134 t.Fatalf("Failed to marshal TpmSpecification: %v", err)
135 }
136 subjectDirectoryAttributes := []attribute{
137 {
138 Type: oid.TPMSpecification,
139 Values: []asn1.RawValue{
140 {FullBytes: tpmSpecBytes},
141 },
142 },
143 }
144 subjectDirectoryAttributesBytes, err := asn1.Marshal(subjectDirectoryAttributes)
145 if err != nil {
146 t.Fatalf("Failed to marshal subjectDirectoryAttributes: %v", err)
147 }
148 return pkix.Extension{
149 Id: oid.SubjectDirectoryAttributes,
150 Critical: critical,
151 Value: subjectDirectoryAttributesBytes,
152 }
153 }
154
155 // modifyExtension ensures that an extension with the given OID is present with the specified criticality. If not, it is added.
156 func modifyExtension(t *testing.T, cert *x509.Certificate, oid asn1.ObjectIdentifier, value []byte, critical bool) {
157 t.Helper()
158 for i, ext := range cert.Extensions {
159 if ext.Id.Equal(oid) {
160 cert.Extensions[i].Critical = critical
161 cert.Extensions[i].Value = value
162 return
163 }
164 }
165
166 // Extension not found, so add it.
167 ext := pkix.Extension{
168 Id: oid,
169 Critical: critical,
170 Value: value,
171 }
172 cert.Extensions = append(cert.Extensions, ext)
173 }
174
175 func TestToEKCertificate_Success(t *testing.T) {
176 tests := []struct {
177 name string
178 modifyCertTemplate func(*testing.T, *x509.Certificate)
179 wantHasEkcExtendedKeyUsage bool
180 wantUnhandledCriticalExtensionsOIDs []asn1.ObjectIdentifier
181 }{
182 {
183 name: "HasEkcExtendedKeyUsage is true",
184 modifyCertTemplate: func(t *testing.T, cert *x509.Certificate) {
185 cert.UnknownExtKeyUsage = []asn1.ObjectIdentifier{oid.EKCertificate}
186 },
187 wantHasEkcExtendedKeyUsage: true,
188 },
189 {
190 name: "HasEkcExtendedKeyUsage is false",
191 modifyCertTemplate: func(t *testing.T, cert *x509.Certificate) {
192 cert.UnknownExtKeyUsage = []asn1.ObjectIdentifier{}
193 },
194 wantHasEkcExtendedKeyUsage: false,
195 },
196 {
197 name: "Unhandled critical extension",
198 modifyCertTemplate: func(t *testing.T, cert *x509.Certificate) {
199 // Use empty subject, make the SubjectAltName extension critical, and
200 // add an unhandled critical extension.
201 cert.Subject = pkix.Name{}
202 for i, ext := range cert.ExtraExtensions {
203 if ext.Id.Equal(oid.SubjectAltName) {
204 cert.ExtraExtensions[i].Critical = true
205 }
206 }
207 cert.ExtraExtensions = append(cert.ExtraExtensions, pkix.Extension{
208 Id: asn1.ObjectIdentifier{1, 2, 3, 4, 5},
209 Critical: true,
210 Value: []byte("test"),
211 })
212 },
213 wantHasEkcExtendedKeyUsage: true,
214 wantUnhandledCriticalExtensionsOIDs: []asn1.ObjectIdentifier{{1, 2, 3, 4, 5}},
215 },
216 }
217 for _, test := range tests {
218 t.Run(test.name, func(t *testing.T) {
219 cert := setupTestCert(t, test.modifyCertTemplate)
220 ekCert, err := ToEKCertificate(cert)
221 if err != nil {
222 t.Fatalf("ToEKCertificate() returned an unexpected error: %v", err)
223 }
224
225 if ekCert.Certificate != cert {
226 t.Errorf("ToEKCertificate() Certificate = %v, want: %v", ekCert.Certificate, cert)
227 }
228
229 if ekCert.TpmManufacturer != SAN.DirectoryNames[0].ExtraNames[0].Value {
230 t.Errorf("ToEKCertificate() TPMManufacturer = %v, want: %v", ekCert.TpmManufacturer, SAN.DirectoryNames[0].ExtraNames[0].Value)
231 }
232
233 if ekCert.TpmModel != SAN.DirectoryNames[0].ExtraNames[1].Value {
234 t.Errorf("ToEKCertificate() TPMModel = %v, want: %v", ekCert.TpmModel, SAN.DirectoryNames[0].ExtraNames[1].Value)
235 }
236
237 if ekCert.TpmVersion != SAN.DirectoryNames[0].ExtraNames[2].Value {
238 t.Errorf("ToEKCertificate() TPMVersion = %v, want: %v", ekCert.TpmVersion, SAN.DirectoryNames[0].ExtraNames[2].Value)
239 }
240
241 if ekCert.TpmSpecification != (tpmSpec) {
242 t.Errorf("ToEKCertificate() TpmSpecification is %v, want %v", ekCert.TpmSpecification, tpmSpec)
243 }
244
245 if test.wantHasEkcExtendedKeyUsage != ekCert.HasEkcExtendedKeyUsage {
246 t.Errorf("ToEKCertificate() HasEkcExtendedKeyUsage = %v, want: %v", ekCert.HasEkcExtendedKeyUsage, test.wantHasEkcExtendedKeyUsage)
247 }
248
249 sortOIDs := cmpopts.SortSlices(func(a, b asn1.ObjectIdentifier) bool { return a.String() < b.String() })
250 if diff := cmp.Diff(test.wantUnhandledCriticalExtensionsOIDs, ekCert.UnhandledCriticalExtensions, cmpopts.EquateEmpty(), sortOIDs); diff != "" {
251 t.Errorf("ToEKCertificate() UnhandledCriticalExtensions differs (-want +got):\n%s", diff)
252 }
253 })
254 }
255 }
256
257 func TestToEKCertificate_Failures(t *testing.T) {
258 tests := []struct {
259 name string
260 modifyCert func(*testing.T, *x509.Certificate)
261 wantErr error
262 }{
263 {
264 name: "Version is 2",
265 modifyCert: func(t *testing.T, cert *x509.Certificate) {
266 cert.Version = 2
267 },
268 wantErr: errors.New("invalid version of EK certificate: 2"),
269 },
270 {
271 name: "SerialNumber is zero",
272 modifyCert: func(t *testing.T, cert *x509.Certificate) {
273 cert.SerialNumber = big.NewInt(0)
274 },
275 wantErr: errors.New("SerialNumber is not a positive integer"),
276 },
277 {
278 name: "SerialNumber negative",
279 modifyCert: func(t *testing.T, cert *x509.Certificate) {
280 cert.SerialNumber = big.NewInt(-1)
281 },
282 wantErr: errors.New("SerialNumber is not a positive integer"),
283 },
284 {
285 name: "SerialNumber nil",
286 modifyCert: func(t *testing.T, cert *x509.Certificate) {
287 cert.SerialNumber = nil
288 },
289 wantErr: errors.New("SerialNumber is nil, expected a positive integer"),
290 },
291 {
292 name: "Issuer is empty",
293 modifyCert: func(t *testing.T, cert *x509.Certificate) {
294 cert.RawIssuer = []byte{0x30, 0x00}
295 },
296 wantErr: errors.New("issuer is empty"),
297 },
298 {
299 name: "BasicConstraints not set",
300 modifyCert: func(t *testing.T, cert *x509.Certificate) {
301 cert.BasicConstraintsValid = false
302 cert.IsCA = false
303 },
304 wantErr: errors.New("BasicConstraints are not valid or it is a CA certificate"),
305 },
306 {
307 name: "BasicConstraints is set but cert is a CA",
308 modifyCert: func(t *testing.T, cert *x509.Certificate) {
309 cert.BasicConstraintsValid = true
310 cert.IsCA = true
311 },
312 wantErr: errors.New("BasicConstraints are not valid or it is a CA certificate"),
313 },
314 {
315 name: "BasicConstraints is not critical",
316 modifyCert: func(t *testing.T, cert *x509.Certificate) {
317 for i, ext := range cert.Extensions {
318 if ext.Id.Equal(oidBasicConstraints) {
319 cert.Extensions[i].Critical = false
320 }
321 }
322 },
323 wantErr: errors.New("extension \"Basic Constraints\" is not critical, supposed to be critical"),
324 },
325 {
326 name: "SAN is not critical when Subject is empty",
327 modifyCert: func(t *testing.T, cert *x509.Certificate) {
328 cert.RawSubject = []byte{0x30, 0x00}
329 for i, ext := range cert.Extensions {
330 if ext.Id.Equal(oid.SubjectAltName) {
331 cert.Extensions[i].Critical = false
332 }
333 }
334 },
335 wantErr: errors.New("SubjectAltName extension must be critical when Subject is not present"),
336 },
337 {
338 name: "MUST extension is missing",
339 modifyCert: func(t *testing.T, cert *x509.Certificate) {
340 cert.Extensions = []pkix.Extension{}
341 },
342 wantErr: errors.New("extension SubjectAltName is missing"),
343 },
344 {
345 name: "AuthorityKeyId empty",
346 modifyCert: func(t *testing.T, cert *x509.Certificate) {
347 cert.AuthorityKeyId = []byte{}
348 },
349 wantErr: errors.New("missing Authority Key ID"),
350 },
351 {
352 name: "Authority Key Identifier is critical",
353 modifyCert: func(t *testing.T, cert *x509.Certificate) {
354 modifyExtension(t, cert, oidAuthorityKeyID, []byte{0x30, 0x00}, true)
355 },
356 wantErr: errors.New("extension \"Authority Key Identifier\" is critical, supposed to be non-critical"),
357 },
358 {
359 name: "KeyUsage not set",
360 modifyCert: func(t *testing.T, cert *x509.Certificate) {
361 cert.PublicKeyAlgorithm = x509.RSA
362 cert.KeyUsage = 0
363 },
364 wantErr: errors.New("KeyUsage field is not set"),
365 },
366 {
367 name: "KeyUsageKeyEncipherment not set for RSA",
368 modifyCert: func(t *testing.T, cert *x509.Certificate) {
369 cert.PublicKeyAlgorithm = x509.RSA
370 cert.KeyUsage = x509.KeyUsageKeyAgreement
371 },
372 wantErr: errors.New("KeyUsageKeyEncipherment is not set for RSA public key type"),
373 },
374 {
375 name: "KeyUsageKeyAgreement not set for ECDSA",
376 modifyCert: func(t *testing.T, cert *x509.Certificate) {
377 cert.PublicKeyAlgorithm = x509.ECDSA
378 cert.KeyUsage = x509.KeyUsageKeyEncipherment
379 },
380 wantErr: errors.New("KeyUsageKeyAgreement is not set for ECDSA public key type"),
381 },
382 {
383 name: "Key Usage is not critical",
384 modifyCert: func(t *testing.T, cert *x509.Certificate) {
385 for i, ext := range cert.Extensions {
386 if ext.Id.Equal(oidKeyUsage) {
387 cert.Extensions[i].Critical = false
388 }
389 }
390 },
391 wantErr: errors.New("extension \"Key Usage\" is not critical, supposed to be critical"),
392 },
393 {
394 name: "CertificatePolicies present but empty PolicyIdentifiers",
395 modifyCert: func(t *testing.T, cert *x509.Certificate) {
396 modifyExtension(t, cert, oid.CertificatePolicies, []byte{0x30, 0x00}, true)
397 cert.PolicyIdentifiers = []asn1.ObjectIdentifier{}
398 },
399 wantErr: errors.New("extension \"Certificate Policies\" should contain at least 1 policy identifier if the extension is present"),
400 },
401 {
402 name: "AuthorityInfoAccess is critical",
403 modifyCert: func(t *testing.T, cert *x509.Certificate) {
404 modifyExtension(t, cert, oidAuthorityInfoAccess, []byte{0x30, 0x00}, true)
405 },
406 wantErr: errors.New("extension \"Authority Info Access\" is critical, supposed to be non-critical"),
407 },
408 {
409 name: "CRLDistributionPoints is critical",
410 modifyCert: func(t *testing.T, cert *x509.Certificate) {
411 modifyExtension(t, cert, oidCRLDistributionPoints, []byte{0x30, 0x00}, true)
412 },
413 wantErr: errors.New("extension \"CRL Distribution Points\" is critical, supposed to be non-critical"),
414 },
415 {
416 name: "ExtendedKeyUsage is critical",
417 modifyCert: func(t *testing.T, cert *x509.Certificate) {
418 modifyExtension(t, cert, oidExtendedKeyUsage, []byte{0x30, 0x00}, true)
419 },
420 wantErr: errors.New("extension \"Extended Key Usage\" is critical, supposed to be non-critical"),
421 },
422 {
423 name: "SubjectKeyIdentifier is critical",
424 modifyCert: func(t *testing.T, cert *x509.Certificate) {
425 modifyExtension(t, cert, oidSubjectKeyIdentifier, []byte{0x30, 0x00}, true)
426 },
427 wantErr: errors.New("extension \"Subject Key Identifier\" is critical, supposed to be non-critical"),
428 },
429 }
430
431 for _, test := range tests {
432 t.Run(test.name, func(t *testing.T) {
433 cert := setupTestCert(t, nil)
434 test.modifyCert(t, cert)
435 _, err := ToEKCertificate(cert)
436
437 if err == nil {
438 t.Fatalf("ToEKCertificate() succeeded unexpectedly, want error: %v", test.wantErr)
439 }
440
441 if err.Error() != test.wantErr.Error() {
442 t.Fatalf("ToEKCertificate() error = %v, want error: %v", err, test.wantErr)
443 }
444 })
445 }
446 }