File: profile_test.go

package info (click to toggle)
golang-github-smallstep-cli 0.15.16%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,404 kB
  • sloc: sh: 512; makefile: 99
file content (450 lines) | stat: -rw-r--r-- 14,590 bytes parent folder | download | duplicates (2)
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
package x509util

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/ed25519"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"encoding/pem"
	"io/ioutil"
	"net"
	"net/url"
	"reflect"
	"testing"

	"github.com/pkg/errors"
	"github.com/smallstep/assert"
)

func mustParseRSAKey(t *testing.T, filename string) *rsa.PrivateKey {
	t.Helper()

	b, err := ioutil.ReadFile("test_files/noPasscodeCa.key")
	if err != nil {
		t.Fatal(err)
	}
	block, _ := pem.Decode(b)
	if block == nil {
		t.Fatalf("error decoding %s", filename)
	}
	key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		t.Fatal(err)
	}
	return key
}

func decodeCertificateFile(t *testing.T, filename string) *x509.Certificate {
	t.Helper()
	b, err := ioutil.ReadFile(filename)
	if err != nil {
		t.Fatal(err)
	}
	block, _ := pem.Decode(b)
	if block == nil {
		t.Fatal("error decoding pem")
	}
	crt, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		t.Fatal(err)
	}
	return crt
}

type basicConstraints struct {
	IsCA       bool `asn1:"optional"`
	MaxPathLen int  `asn1:"optional,default:-1"`
}

// asn1BitLength returns the bit-length of bitString by considering the
// most-significant bit in a byte to be the "first" bit. This convention
// matches ASN.1, but differs from almost everything else.
func asn1BitLength(bitString []byte) int {
	bitLen := len(bitString) * 8
	for i := range bitString {
		b := bitString[len(bitString)-i-1]
		for bit := uint(0); bit < 8; bit++ {
			if (b>>bit)&1 == 1 {
				return bitLen
			}
			bitLen--
		}
	}
	return 0
}

func reverseBitsInAByte(in byte) byte {
	b1 := in>>4 | in<<4
	b2 := b1>>2&0x33 | b1<<2&0xcc
	b3 := b2>>1&0x55 | b2<<1&0xaa
	return b3
}

// RFC 5280, 4.2.1.12  Extended Key Usage
//
// anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
//
// id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
//
// id-kp-serverAuth             OBJECT IDENTIFIER ::= { id-kp 1 }
// id-kp-clientAuth             OBJECT IDENTIFIER ::= { id-kp 2 }
// id-kp-codeSigning            OBJECT IDENTIFIER ::= { id-kp 3 }
// id-kp-emailProtection        OBJECT IDENTIFIER ::= { id-kp 4 }
// id-kp-timeStamping           OBJECT IDENTIFIER ::= { id-kp 8 }
// id-kp-OCSPSigning            OBJECT IDENTIFIER ::= { id-kp 9 }
var (
	oidExtKeyUsageAny                            = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
	oidExtKeyUsageServerAuth                     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
	oidExtKeyUsageClientAuth                     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
	oidExtKeyUsageCodeSigning                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
	oidExtKeyUsageEmailProtection                = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
	oidExtKeyUsageIPSECEndSystem                 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
	oidExtKeyUsageIPSECTunnel                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
	oidExtKeyUsageIPSECUser                      = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
	oidExtKeyUsageTimeStamping                   = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
	oidExtKeyUsageOCSPSigning                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
	oidExtKeyUsageMicrosoftServerGatedCrypto     = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
	oidExtKeyUsageNetscapeServerGatedCrypto      = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
	oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
	oidExtKeyUsageMicrosoftKernelCodeSigning     = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
)

// extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
var extKeyUsageOIDs = []struct {
	extKeyUsage x509.ExtKeyUsage
	oid         asn1.ObjectIdentifier
}{
	{x509.ExtKeyUsageAny, oidExtKeyUsageAny},
	{x509.ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
	{x509.ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
	{x509.ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
	{x509.ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
	{x509.ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
	{x509.ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
	{x509.ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
	{x509.ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
	{x509.ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
	{x509.ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
	{x509.ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
	{x509.ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
	{x509.ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
}

func oidFromExtKeyUsage(eku x509.ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
	for _, pair := range extKeyUsageOIDs {
		if eku == pair.extKeyUsage {
			return pair.oid, true
		}
	}
	return
}

// RFC 5280, 4.2.1.10
type nameConstraints struct {
	Permitted []generalSubtree `asn1:"optional,tag:0"`
	Excluded  []generalSubtree `asn1:"optional,tag:1"`
}

type generalSubtree struct {
	Name string `asn1:"tag:2,optional,ia5"`
}

type userExt struct {
	FName string `asn1:"tag:0,optional,ia5"`
	LName string `asn1:"tag:1,optional,ia5"`
}

const (
	nameTypeEmail = 1
	nameTypeDNS   = 2
	nameTypeURI   = 6
	nameTypeIP    = 7
)

// marshalSANs marshals a list of addresses into a the contents of an X.509
// SubjectAlternativeName extension.
func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
	var rawValues []asn1.RawValue
	for _, name := range dnsNames {
		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
	}
	for _, email := range emailAddresses {
		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
	}
	for _, rawIP := range ipAddresses {
		// If possible, we always want to encode IPv4 addresses in 4 bytes.
		ip := rawIP.To4()
		if ip == nil {
			ip = rawIP
		}
		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
	}
	for _, uri := range uris {
		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uri.String())})
	}
	return asn1.Marshal(rawValues)
}

func Test_base_CreateCertificate(t *testing.T) {
	issCert := mustParseCertificate(t, "test_files/noPasscodeCa.crt")
	issKey := mustParseRSAKey(t, "test_files/noPasscodeCa.key")
	ecdsaKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	assert.FatalError(t, err)

	type test struct {
		p   Profile
		err error
	}
	tests := map[string]func(*testing.T) test{
		"fail/no-subject-pub-key": func(t *testing.T) test {
			p, err := NewLeafProfile("test.smallstep.com", issCert, issKey)
			assert.FatalError(t, err)
			lp, ok := p.(*Leaf)
			assert.Fatal(t, ok)
			lp.base.subPub = nil
			return test{
				p:   lp,
				err: errors.New("Profile does not have subject public key. Need to call 'profile.GenerateKeyPair(...)' or use setters to populate keys"),
			}
		},
		"fail/no-issuer-priv-key": func(t *testing.T) test {
			p, err := NewLeafProfile("test.smallstep.com", issCert, issKey)
			assert.FatalError(t, err)
			lp, ok := p.(*Leaf)
			assert.Fatal(t, ok)
			lp.base.issPriv = nil
			return test{
				p:   lp,
				err: errors.New("Profile does not have issuer private key. Use setters to populate this field"),
			}
		},
		"ok": func(t *testing.T) test {
			p, err := NewLeafProfile("test.smallstep.com", issCert, issKey, WithPublicKey(ecdsaKey.Public()))
			assert.FatalError(t, err)
			lp, ok := p.(*Leaf)
			assert.Fatal(t, ok)

			// KeyUsage Extension
			keyUsageExt := pkix.Extension{}
			keyUsageExt.Id = asn1.ObjectIdentifier{2, 5, 29, 15}
			keyUsageExt.Critical = true
			ku := x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageCertSign
			var a [2]byte
			a[0] = reverseBitsInAByte(byte(ku))
			a[1] = reverseBitsInAByte(byte(ku >> 8))
			l := 1
			if a[1] != 0 {
				l = 2
			}
			bitString := a[:l]
			keyUsageExt.Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
			assert.FatalError(t, err)

			// BasicConstraints Extension
			bcExt := pkix.Extension{}
			bcExt.Id = asn1.ObjectIdentifier{2, 5, 29, 19}
			bcExt.Critical = false
			bcExt.Value, err = asn1.Marshal(basicConstraints{IsCA: true, MaxPathLen: 1})
			assert.FatalError(t, err)

			// ExtendedKeyUSage Extension
			extKeyUsageExt := pkix.Extension{}
			extKeyUsageExt.Id = asn1.ObjectIdentifier{2, 5, 29, 37}
			extKeyUsageExt.Critical = false
			var oids []asn1.ObjectIdentifier
			var eku []x509.ExtKeyUsage = []x509.ExtKeyUsage{
				x509.ExtKeyUsageServerAuth,
				x509.ExtKeyUsageClientAuth,
				x509.ExtKeyUsageMicrosoftKernelCodeSigning,
			}
			for _, u := range eku {
				oid, ok := oidFromExtKeyUsage(u)
				assert.Fatal(t, ok)
				oids = append(oids, oid)
			}
			// Add unknown extkeyusage
			oids = append(oids, asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4})
			extKeyUsageExt.Value, err = asn1.Marshal(oids)
			assert.FatalError(t, err)

			// Add SubjectAltName extension
			sanExt := pkix.Extension{}
			sanExt.Id = oidExtSubjectAltName
			sanExt.Value, err = marshalSANs([]string{"foo.internal"}, nil, []net.IP{net.ParseIP("127.0.0.1")}, []*url.URL{{Scheme: "https", Host: "google.com"}})
			assert.FatalError(t, err)

			// NameConstraints Extension
			ncExt := pkix.Extension{}
			ncExt.Id = asn1.ObjectIdentifier{2, 5, 29, 30}
			ncExt.Critical = true
			var out nameConstraints
			permittedDNSDomains := []string{"foo", "bar", "baz"}
			out.Permitted = make([]generalSubtree, len(permittedDNSDomains))
			for i, permitted := range permittedDNSDomains {
				out.Permitted[i] = generalSubtree{Name: permitted}
			}
			ncExt.Value, err = asn1.Marshal(out)
			assert.FatalError(t, err)

			// Unknown Extension
			uExt := pkix.Extension{}
			uExt.Id = asn1.ObjectIdentifier{1, 2, 3, 4, 5}
			uExt.Critical = false
			uExt.Value = []byte("foo")

			u2Ext := pkix.Extension{}
			u2Ext.Id = asn1.ObjectIdentifier{1, 1, 13, 1, 2, 4, 15, 17, 1, 3, 1, 2, 4, 1}
			u2Ext.Critical = true
			u2Ext.Value, err = asn1.Marshal(userExt{FName: "max", LName: "furman"})
			assert.FatalError(t, err)

			lp.base.ext = []pkix.Extension{keyUsageExt, bcExt, extKeyUsageExt, sanExt, ncExt, uExt, u2Ext}
			return test{
				p: lp,
			}
		},
	}
	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			tc := tt(t)
			if certBytes, err := tc.p.CreateCertificate(); err != nil {
				if assert.NotNil(t, tc.err, "expected no error but got '%s'", err) {
					assert.HasPrefix(t, err.Error(), tc.err.Error())
				}
			} else {
				if assert.Nil(t, tc.err) {
					cert, err := x509.ParseCertificate(certBytes)
					assert.FatalError(t, err)
					assert.Equals(t, cert.Subject.CommonName, "test.smallstep.com")
					assert.Equals(t, cert.KeyUsage, x509.KeyUsageDigitalSignature)

					assert.Len(t, 2, cert.ExtKeyUsage)
					assert.Equals(t, cert.ExtKeyUsage[0], x509.ExtKeyUsageServerAuth)
					assert.Equals(t, cert.ExtKeyUsage[1], x509.ExtKeyUsageClientAuth)

					assert.False(t, cert.BasicConstraintsValid)
					assert.False(t, cert.IsCA)
					assert.False(t, cert.MaxPathLenZero)
					assert.Equals(t, cert.MaxPathLen, 0)

					assert.Len(t, 0, cert.PermittedDNSDomains)

					assert.Len(t, 0, cert.DNSNames)
					assert.Len(t, 0, cert.EmailAddresses)
					assert.Len(t, 0, cert.IPAddresses)
					assert.Len(t, 0, cert.URIs)

					nonStdExts := 0
					for _, ext := range cert.Extensions {
						if _, ok := oidStdExtHashMap[ext.Id.String()]; !ok {
							nonStdExts++
						}
					}
					assert.Equals(t, nonStdExts, 2)
				}
			}
		})
	}
}

func Test_base_CreateCertificate_KeyEncipherment(t *testing.T) {
	// Issuer
	iss := mustParseCertificate(t, "test_files/noPasscodeCa.crt")
	issPriv := mustParseRSAKey(t, "test_files/noPasscodeCa.key")

	mustCreateLeaf := func(key interface{}) Profile {
		p, err := NewLeafProfile("test.smallstep.com", iss, issPriv, WithPublicKey(key))
		if err != nil {
			t.Fatal(err)
		}
		return p
	}

	// Keys and certs
	ecdsaKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatal(err)
	}
	ecdsaProfile := mustCreateLeaf(ecdsaKey.Public())

	rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal(err)
	}
	rsaProfile := mustCreateLeaf(rsaKey.Public())

	ed25519PubKey, _, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatal(err)
	}
	ed25519Profile := mustCreateLeaf(ed25519PubKey)

	tests := []struct {
		name                string
		profile             Profile
		wantKeyEncipherment bool
	}{
		{"ecdsa", ecdsaProfile, false},
		{"rsa", rsaProfile, true},
		{"ed25519", ed25519Profile, false},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := tt.profile.CreateCertificate()
			if err != nil {
				t.Errorf("base.CreateCertificate() error = %v", err)
				return
			}
			cert, err := x509.ParseCertificate(got)
			if err != nil {
				t.Errorf("error parsing certificate: %v", err)
			} else {
				ku := cert.KeyUsage & x509.KeyUsageKeyEncipherment
				switch {
				case tt.wantKeyEncipherment && ku == 0:
					t.Errorf("base.CreateCertificate() keyUsage = %x, want %x", cert.KeyUsage, x509.KeyUsageDigitalSignature|x509.KeyUsageKeyEncipherment)
				case !tt.wantKeyEncipherment && ku != 0:
					t.Errorf("base.CreateCertificate() keyUsage = %x, want %x", cert.KeyUsage, x509.KeyUsageDigitalSignature)
				}
			}
		})
	}
}

func Test_generateSubjectKeyID(t *testing.T) {
	ecdsaCrt := decodeCertificateFile(t, "test_files/google.crt")
	rsaCrt := decodeCertificateFile(t, "test_files/smallstep.crt")
	ed25519Crt := decodeCertificateFile(t, "test_files/ed25519.crt")

	type args struct {
		pub crypto.PublicKey
	}
	tests := []struct {
		name    string
		args    args
		want    []byte
		wantErr bool
	}{
		{"ecdsa", args{ecdsaCrt.PublicKey}, ecdsaCrt.SubjectKeyId, false},
		{"rsa", args{rsaCrt.PublicKey}, rsaCrt.SubjectKeyId, false},
		{"ed25519", args{ed25519Crt.PublicKey}, ed25519Crt.SubjectKeyId, false},
		{"fail", args{[]byte("fail")}, nil, true},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := generateSubjectKeyID(tt.args.pub)
			if (err != nil) != tt.wantErr {
				t.Errorf("generateSubjectKeyID() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("generateSubjectKeyID() = %v, want %v", got, tt.want)
			}
		})
	}
}