Debian Codegraph @

crypto/x509util/profile_test.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 package x509util
2
3 import (
4 "crypto"
5 "crypto/ecdsa"
6 "crypto/ed25519"
7 "crypto/elliptic"
8 "crypto/rand"
9 "crypto/rsa"
10 "crypto/x509"
11 "crypto/x509/pkix"
12 "encoding/asn1"
13 "encoding/pem"
14 "io/ioutil"
15 "net"
16 "net/url"
17 "reflect"
18 "testing"
19
20 "github.com/pkg/errors"
21 "github.com/smallstep/assert"
22 )
23
24 func mustParseRSAKey(t *testing.T, filename string) *rsa.PrivateKey {
25 t.Helper()
26
•27 b, err := ioutil.ReadFile("testdata/noPasscodeCa.key")
28 if err != nil {
29 t.Fatal(err)
30 }
31 block, _ := pem.Decode(b)
32 if block == nil {
33 t.Fatalf("error decoding %s", filename)
34 }
35 key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
36 if err != nil {
37 t.Fatal(err)
38 }
39 return key
40 }
41
42 func decodeCertificateFile(t *testing.T, filename string) *x509.Certificate {
43 t.Helper()
44 b, err := ioutil.ReadFile(filename)
45 if err != nil {
46 t.Fatal(err)
47 }
48 block, _ := pem.Decode(b)
49 if block == nil {
50 t.Fatal("error decoding pem")
51 }
52 crt, err := x509.ParseCertificate(block.Bytes)
53 if err != nil {
54 t.Fatal(err)
55 }
56 return crt
57 }
58
59 type basicConstraints struct {
60 IsCA bool `asn1:"optional"`
61 MaxPathLen int `asn1:"optional,default:-1"`
62 }
63
64 // asn1BitLength returns the bit-length of bitString by considering the
65 // most-significant bit in a byte to be the "first" bit. This convention
66 // matches ASN.1, but differs from almost everything else.
67 func asn1BitLength(bitString []byte) int {
68 bitLen := len(bitString) * 8
69 for i := range bitString {
70 b := bitString[len(bitString)-i-1]
71 for bit := uint(0); bit < 8; bit++ {
72 if (b>>bit)&1 == 1 {
73 return bitLen
74 }
75 bitLen--
76 }
77 }
78 return 0
79 }
80
81 func reverseBitsInAByte(in byte) byte {
82 b1 := in>>4 | in<<4
83 b2 := b1>>2&0x33 | b1<<2&0xcc
84 b3 := b2>>1&0x55 | b2<<1&0xaa
85 return b3
86 }
87
88 // RFC 5280, 4.2.1.12 Extended Key Usage
89 //
90 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
91 //
92 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
93 //
94 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
95 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
96 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
97 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
98 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
99 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
100 var (
101 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
102 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
103 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
104 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
105 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
106 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
107 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
108 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
109 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
110 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
111 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
112 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
113 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
114 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
115 )
116
117 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
118 var extKeyUsageOIDs = []struct {
119 extKeyUsage x509.ExtKeyUsage
120 oid asn1.ObjectIdentifier
121 }{
122 {x509.ExtKeyUsageAny, oidExtKeyUsageAny},
123 {x509.ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
124 {x509.ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
125 {x509.ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
126 {x509.ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
127 {x509.ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
128 {x509.ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
129 {x509.ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
130 {x509.ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
131 {x509.ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
132 {x509.ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
133 {x509.ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
134 {x509.ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
135 {x509.ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
136 }
137
138 func oidFromExtKeyUsage(eku x509.ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
139 for _, pair := range extKeyUsageOIDs {
140 if eku == pair.extKeyUsage {
141 return pair.oid, true
142 }
143 }
144 return
145 }
146
147 // RFC 5280, 4.2.1.10
148 type nameConstraints struct {
149 Permitted []generalSubtree `asn1:"optional,tag:0"`
150 Excluded []generalSubtree `asn1:"optional,tag:1"`
151 }
152
153 type generalSubtree struct {
154 Name string `asn1:"tag:2,optional,ia5"`
155 }
156
157 type userExt struct {
158 FName string `asn1:"tag:0,optional,ia5"`
159 LName string `asn1:"tag:1,optional,ia5"`
160 }
161
162 const (
163 nameTypeEmail = 1
164 nameTypeDNS = 2
165 nameTypeURI = 6
166 nameTypeIP = 7
167 )
168
169 // marshalSANs marshals a list of addresses into a the contents of an X.509
170 // SubjectAlternativeName extension.
171 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
172 var rawValues []asn1.RawValue
173 for _, name := range dnsNames {
174 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
175 }
176 for _, email := range emailAddresses {
177 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
178 }
179 for _, rawIP := range ipAddresses {
180 // If possible, we always want to encode IPv4 addresses in 4 bytes.
181 ip := rawIP.To4()
182 if ip == nil {
183 ip = rawIP
184 }
185 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
186 }
187 for _, uri := range uris {
188 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uri.String())})
189 }
190 return asn1.Marshal(rawValues)
191 }
192
193 func Test_base_CreateCertificate(t *testing.T) {
•194 issCert := mustParseCertificate(t, "testdata/noPasscodeCa.crt")
195 issKey := mustParseRSAKey(t, "testdata/noPasscodeCa.key")
196 ecdsaKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
197 assert.FatalError(t, err)
198
199 type test struct {
200 p Profile
201 err error
202 }
203 tests := map[string]func(*testing.T) test{
204 "fail/no-subject-pub-key": func(t *testing.T) test {
205 p, err := NewLeafProfile("test.smallstep.com", issCert, issKey)
206 assert.FatalError(t, err)
207 lp, ok := p.(*Leaf)
208 assert.Fatal(t, ok)
209 lp.base.subPub = nil
210 return test{
211 p: lp,
212 err: errors.New("Profile does not have subject public key. Need to call 'profile.GenerateKeyPair(...)' or use setters to populate keys"),
213 }
214 },
215 "fail/no-issuer-priv-key": func(t *testing.T) test {
216 p, err := NewLeafProfile("test.smallstep.com", issCert, issKey)
217 assert.FatalError(t, err)
218 lp, ok := p.(*Leaf)
219 assert.Fatal(t, ok)
220 lp.base.issPriv = nil
221 return test{
222 p: lp,
223 err: errors.New("Profile does not have issuer private key. Use setters to populate this field"),
224 }
225 },
226 "ok": func(t *testing.T) test {
227 p, err := NewLeafProfile("test.smallstep.com", issCert, issKey, WithPublicKey(ecdsaKey.Public()))
228 assert.FatalError(t, err)
229 lp, ok := p.(*Leaf)
230 assert.Fatal(t, ok)
231
232 // KeyUsage Extension
233 keyUsageExt := pkix.Extension{}
234 keyUsageExt.Id = asn1.ObjectIdentifier{2, 5, 29, 15}
235 keyUsageExt.Critical = true
236 ku := x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageCertSign
237 var a [2]byte
238 a[0] = reverseBitsInAByte(byte(ku))
239 a[1] = reverseBitsInAByte(byte(ku >> 8))
240 l := 1
241 if a[1] != 0 {
242 l = 2
243 }
244 bitString := a[:l]
245 keyUsageExt.Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
246 assert.FatalError(t, err)
247
248 // BasicConstraints Extension
249 bcExt := pkix.Extension{}
250 bcExt.Id = asn1.ObjectIdentifier{2, 5, 29, 19}
251 bcExt.Critical = false
252 bcExt.Value, err = asn1.Marshal(basicConstraints{IsCA: true, MaxPathLen: 1})
253 assert.FatalError(t, err)
254
255 // ExtendedKeyUSage Extension
256 extKeyUsageExt := pkix.Extension{}
257 extKeyUsageExt.Id = asn1.ObjectIdentifier{2, 5, 29, 37}
258 extKeyUsageExt.Critical = false
259 var oids []asn1.ObjectIdentifier
260 var eku []x509.ExtKeyUsage = []x509.ExtKeyUsage{
261 x509.ExtKeyUsageServerAuth,
262 x509.ExtKeyUsageClientAuth,
263 x509.ExtKeyUsageMicrosoftKernelCodeSigning,
264 }
265 for _, u := range eku {
266 oid, ok := oidFromExtKeyUsage(u)
267 assert.Fatal(t, ok)
268 oids = append(oids, oid)
269 }
270 // Add unknown extkeyusage
271 oids = append(oids, asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4})
272 extKeyUsageExt.Value, err = asn1.Marshal(oids)
273 assert.FatalError(t, err)
274
275 // Add SubjectAltName extension
276 sanExt := pkix.Extension{}
277 sanExt.Id = oidExtSubjectAltName
278 sanExt.Value, err = marshalSANs([]string{"foo.internal"}, nil, []net.IP{net.ParseIP("127.0.0.1")}, []*url.URL{{Scheme: "https", Host: "google.com"}})
279 assert.FatalError(t, err)
280
281 // NameConstraints Extension
282 ncExt := pkix.Extension{}
283 ncExt.Id = asn1.ObjectIdentifier{2, 5, 29, 30}
284 ncExt.Critical = true
285 var out nameConstraints
286 permittedDNSDomains := []string{"foo", "bar", "baz"}
287 out.Permitted = make([]generalSubtree, len(permittedDNSDomains))
288 for i, permitted := range permittedDNSDomains {
289 out.Permitted[i] = generalSubtree{Name: permitted}
290 }
291 ncExt.Value, err = asn1.Marshal(out)
292 assert.FatalError(t, err)
293
294 // Unknown Extension
295 uExt := pkix.Extension{}
296 uExt.Id = asn1.ObjectIdentifier{1, 2, 3, 4, 5}
297 uExt.Critical = false
298 uExt.Value = []byte("foo")
299
300 u2Ext := pkix.Extension{}
301 u2Ext.Id = asn1.ObjectIdentifier{1, 1, 13, 1, 2, 4, 15, 17, 1, 3, 1, 2, 4, 1}
302 u2Ext.Critical = true
303 u2Ext.Value, err = asn1.Marshal(userExt{FName: "max", LName: "furman"})
304 assert.FatalError(t, err)
305
306 lp.base.ext = []pkix.Extension{keyUsageExt, bcExt, extKeyUsageExt, sanExt, ncExt, uExt, u2Ext}
307 return test{
308 p: lp,
309 }
310 },
311 }
312 for name, tt := range tests {
313 t.Run(name, func(t *testing.T) {
314 tc := tt(t)
315 if certBytes, err := tc.p.CreateCertificate(); err != nil {
316 if assert.NotNil(t, tc.err, "expected no error but got '%s'", err) {
317 assert.HasPrefix(t, err.Error(), tc.err.Error())
318 }
319 } else {
320 if assert.Nil(t, tc.err) {
321 cert, err := x509.ParseCertificate(certBytes)
322 assert.FatalError(t, err)
323 assert.Equals(t, cert.Subject.CommonName, "test.smallstep.com")
324 assert.Equals(t, cert.KeyUsage, x509.KeyUsageDigitalSignature)
325
326 assert.Len(t, 2, cert.ExtKeyUsage)
327 assert.Equals(t, cert.ExtKeyUsage[0], x509.ExtKeyUsageServerAuth)
328 assert.Equals(t, cert.ExtKeyUsage[1], x509.ExtKeyUsageClientAuth)
329
330 assert.False(t, cert.BasicConstraintsValid)
331 assert.False(t, cert.IsCA)
332 assert.False(t, cert.MaxPathLenZero)
333 assert.Equals(t, cert.MaxPathLen, 0)
334
335 assert.Len(t, 0, cert.PermittedDNSDomains)
336
337 assert.Len(t, 0, cert.DNSNames)
338 assert.Len(t, 0, cert.EmailAddresses)
339 assert.Len(t, 0, cert.IPAddresses)
340 assert.Len(t, 0, cert.URIs)
341
342 nonStdExts := 0
343 for _, ext := range cert.Extensions {
344 if _, ok := oidStdExtHashMap[ext.Id.String()]; !ok {
345 nonStdExts++
346 }
347 }
348 assert.Equals(t, nonStdExts, 2)
349 }
350 }
351 })
352 }
353 }
354
355 func Test_base_CreateCertificate_KeyEncipherment(t *testing.T) {
356 // Issuer
•357 iss := mustParseCertificate(t, "testdata/noPasscodeCa.crt")
358 issPriv := mustParseRSAKey(t, "testdata/noPasscodeCa.key")
359
360 mustCreateLeaf := func(key interface{}) Profile {
361 p, err := NewLeafProfile("test.smallstep.com", iss, issPriv, WithPublicKey(key))
362 if err != nil {
363 t.Fatal(err)
364 }
365 return p
366 }
367
368 // Keys and certs
369 ecdsaKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
370 if err != nil {
371 t.Fatal(err)
372 }
373 ecdsaProfile := mustCreateLeaf(ecdsaKey.Public())
374
375 rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
376 if err != nil {
377 t.Fatal(err)
378 }
379 rsaProfile := mustCreateLeaf(rsaKey.Public())
380
381 ed25519PubKey, _, err := ed25519.GenerateKey(rand.Reader)
382 if err != nil {
383 t.Fatal(err)
384 }
385 ed25519Profile := mustCreateLeaf(ed25519PubKey)
386
387 tests := []struct {
388 name string
389 profile Profile
390 wantKeyEncipherment bool
391 }{
392 {"ecdsa", ecdsaProfile, false},
393 {"rsa", rsaProfile, true},
394 {"ed25519", ed25519Profile, false},
395 }
396 for _, tt := range tests {
397 t.Run(tt.name, func(t *testing.T) {
398 got, err := tt.profile.CreateCertificate()
399 if err != nil {
400 t.Errorf("base.CreateCertificate() error = %v", err)
401 return
402 }
403 cert, err := x509.ParseCertificate(got)
404 if err != nil {
405 t.Errorf("error parsing certificate: %v", err)
406 } else {
407 ku := cert.KeyUsage & x509.KeyUsageKeyEncipherment
408 switch {
409 case tt.wantKeyEncipherment && ku == 0:
410 t.Errorf("base.CreateCertificate() keyUsage = %x, want %x", cert.KeyUsage, x509.KeyUsageDigitalSignature|x509.KeyUsageKeyEncipherment)
411 case !tt.wantKeyEncipherment && ku != 0:
412 t.Errorf("base.CreateCertificate() keyUsage = %x, want %x", cert.KeyUsage, x509.KeyUsageDigitalSignature)
413 }
414 }
415 })
416 }
417 }
418
419 func Test_generateSubjectKeyID(t *testing.T) {
•420 ecdsaCrt := decodeCertificateFile(t, "testdata/google.crt")
421 rsaCrt := decodeCertificateFile(t, "testdata/smallstep.crt")
422 ed25519Crt := decodeCertificateFile(t, "testdata/ed25519.crt")
423
424 type args struct {
425 pub crypto.PublicKey
426 }
427 tests := []struct {
428 name string
429 args args
430 want []byte
431 wantErr bool
432 }{
433 {"ecdsa", args{ecdsaCrt.PublicKey}, ecdsaCrt.SubjectKeyId, false},
434 {"rsa", args{rsaCrt.PublicKey}, rsaCrt.SubjectKeyId, false},
435 {"ed25519", args{ed25519Crt.PublicKey}, ed25519Crt.SubjectKeyId, false},
436 {"fail", args{[]byte("fail")}, nil, true},
437 }
438 for _, tt := range tests {
439 t.Run(tt.name, func(t *testing.T) {
440 got, err := generateSubjectKeyID(tt.args.pub)
441 if (err != nil) != tt.wantErr {
442 t.Errorf("generateSubjectKeyID() error = %v, wantErr %v", err, tt.wantErr)
443 return
444 }
445 if !reflect.DeepEqual(got, tt.want) {
446 t.Errorf("generateSubjectKeyID() = %v, want %v", got, tt.want)
447 }
448 })
449 }
450 }