File: csr_test.go

package info (click to toggle)
golang-github-cloudflare-cfssl 1.2.0%2Bgit20160825.89.7fb22c8-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 4,916 kB
  • ctags: 2,827
  • sloc: sh: 146; sql: 62; python: 11; makefile: 8
file content (744 lines) | stat: -rw-r--r-- 16,663 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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
package csr

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rsa"
	"crypto/x509"
	"encoding/asn1"
	"encoding/pem"
	"io/ioutil"
	"testing"

	"github.com/cloudflare/cfssl/errors"
	"github.com/cloudflare/cfssl/helpers"
)

//TestNew validate the CertificateRequest created to return with a BasicKeyRequest
//in KeyRequest field

func TestNew(t *testing.T) {

	if cr := New(); cr.KeyRequest == nil {
		t.Fatalf("Should create a new, empty certificate request with BasicKeyRequest")
	}
}

// TestBasicKeyRequest ensures that key generation returns the same type of
// key specified in the BasicKeyRequest.
func TestBasicKeyRequest(t *testing.T) {
	kr := NewBasicKeyRequest()
	priv, err := kr.Generate()
	if err != nil {
		t.Fatalf("%v", err)
	}

	switch priv.(type) {
	case *rsa.PrivateKey:
		if kr.Algo() != "rsa" {
			t.Fatal("RSA key generated, but expected", kr.Algo())
		}
	case *ecdsa.PrivateKey:
		if kr.Algo() != "ecdsa" {
			t.Fatal("ECDSA key generated, but expected", kr.Algo())
		}
	}
}

// TestPKIXName validates building a pkix.Name structure from a
// CertificateRequest.
func TestPKIXName(t *testing.T) {
	var cr = &CertificateRequest{
		CN: "Test Common Name",
		Names: []Name{
			{
				C:  "US",
				ST: "California",
				L:  "San Francisco",
				O:  "CloudFlare, Inc.",
				OU: "Systems Engineering",
			},
			{
				C:  "GB",
				ST: "London",
				L:  "London",
				O:  "CloudFlare, Inc",
				OU: "Systems Engineering",
			},
		},
		Hosts:      []string{"cloudflare.com", "www.cloudflare.com"},
		KeyRequest: NewBasicKeyRequest(),
	}

	name := cr.Name()
	if len(name.Country) != 2 {
		t.Fatal("Expected two countries in SubjInfo.")
	} else if len(name.Province) != 2 {
		t.Fatal("Expected two states in SubjInfo.")
	} else if len(name.Locality) != 2 {
		t.Fatal("Expected two localities in SubjInfo.")
	} else if len(name.Country) != 2 {
		t.Fatal("Expected two countries in SubjInfo.")
	} else if len(name.Organization) != 2 {
		t.Fatal("Expected two organization in SubjInfo.")
	} else if len(name.OrganizationalUnit) != 2 {
		t.Fatal("Expected two organizational units in SubjInfo.")
	}
}

// TestParseRequest ensures that a valid certificate request does not
// error.
func TestParseRequest(t *testing.T) {
	var cr = &CertificateRequest{
		CN: "Test Common Name",
		Names: []Name{
			{
				C:  "US",
				ST: "California",
				L:  "San Francisco",
				O:  "CloudFlare, Inc.",
				OU: "Systems Engineering",
			},
			{
				C:  "GB",
				ST: "London",
				L:  "London",
				O:  "CloudFlare, Inc",
				OU: "Systems Engineering",
			},
		},
		Hosts:      []string{"cloudflare.com", "www.cloudflare.com", "192.168.0.1", "jdoe@example.com"},
		KeyRequest: NewBasicKeyRequest(),
	}

	_, _, err := ParseRequest(cr)
	if err != nil {
		t.Fatalf("%v", err)
	}
}

// TestParseRequestCA ensures that a valid CA certificate request does not
// error and the resulting CSR includes the BasicConstraint extension
func TestParseRequestCA(t *testing.T) {
	var cr = &CertificateRequest{
		CN: "Test Common Name",
		Names: []Name{
			{
				C:  "US",
				ST: "California",
				L:  "San Francisco",
				O:  "CloudFlare, Inc.",
				OU: "Systems Engineering",
			},
			{
				C:  "GB",
				ST: "London",
				L:  "London",
				O:  "CloudFlare, Inc",
				OU: "Systems Engineering",
			},
		},
		CA: &CAConfig{
			PathLength:  0,
			PathLenZero: true,
		},
		KeyRequest: NewBasicKeyRequest(),
	}

	csrBytes, _, err := ParseRequest(cr)
	if err != nil {
		t.Fatalf("%v", err)
	}

	block, _ := pem.Decode(csrBytes)
	if block == nil {
		t.Fatalf("%v", err)
	}

	if block.Type != "CERTIFICATE REQUEST" {
		t.Fatalf("Incorrect block type: %s", block.Type)
	}

	csr, err := x509.ParseCertificateRequest(block.Bytes)
	if err != nil {
		t.Fatalf("%v", err)
	}

	found := false
	for _, ext := range csr.Extensions {
		if ext.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 19}) {
			found = true
			break
		}
	}

	if !found {
		t.Fatalf("CSR did not include BasicConstraint Extension")
	}
}

// TestParseRequestCANoPathlen ensures that a valid CA certificate request
// with an unspecified pathlen does not error and the resulting CSR includes
// the BasicConstraint extension
func TestParseRequestCANoPathlen(t *testing.T) {
	var cr = &CertificateRequest{
		CN: "Test Common Name",
		Names: []Name{
			{
				C:  "US",
				ST: "California",
				L:  "San Francisco",
				O:  "CloudFlare, Inc.",
				OU: "Systems Engineering",
			},
			{
				C:  "GB",
				ST: "London",
				L:  "London",
				O:  "CloudFlare, Inc",
				OU: "Systems Engineering",
			},
		},
		CA: &CAConfig{
			PathLength:  0,
			PathLenZero: false,
		},
		KeyRequest: NewBasicKeyRequest(),
	}

	csrBytes, _, err := ParseRequest(cr)
	if err != nil {
		t.Fatalf("%v", err)
	}

	block, _ := pem.Decode(csrBytes)
	if block == nil {
		t.Fatalf("%v", err)
	}

	if block.Type != "CERTIFICATE REQUEST" {
		t.Fatalf("Incorrect block type: %s", block.Type)
	}

	csr, err := x509.ParseCertificateRequest(block.Bytes)
	if err != nil {
		t.Fatalf("%v", err)
	}

	found := false
	for _, ext := range csr.Extensions {
		if ext.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 19}) {
			bc := &BasicConstraints{}
			asn1.Unmarshal(ext.Value, bc)
			if bc.IsCA == true && bc.MaxPathLen == -1 {
				found = true
				break
			}
		}
	}

	if !found {
		t.Fatalf("CSR did not include BasicConstraint Extension")
	}
}

func whichCurve(sz int) elliptic.Curve {
	switch sz {
	case 256:
		return elliptic.P256()
	case 384:
		return elliptic.P384()
	case 521:
		return elliptic.P521()
	}
	return nil
}

// TestECGeneration ensures that the proper curve is used depending on
// the bit size specified in a key request and that an appropriate
// signature algorithm is returned.
func TestECGeneration(t *testing.T) {
	var eckey *ecdsa.PrivateKey

	for _, sz := range []int{256, 384, 521} {
		kr := &BasicKeyRequest{"ecdsa", sz}
		priv, err := kr.Generate()
		if err != nil {
			t.Fatalf("%v", err)
		}
		eckey = priv.(*ecdsa.PrivateKey)
		if eckey.Curve != whichCurve(sz) {
			t.Fatal("Generated key has wrong curve.")
		}
		if sa := kr.SigAlgo(); sa == x509.UnknownSignatureAlgorithm {
			t.Fatal("Invalid signature algorithm!")
		}
	}
}

func TestRSAKeyGeneration(t *testing.T) {
	var rsakey *rsa.PrivateKey

	for _, sz := range []int{2048, 3072, 4096} {
		kr := &BasicKeyRequest{"rsa", sz}
		priv, err := kr.Generate()
		if err != nil {
			t.Fatalf("%v", err)
		}
		rsakey = priv.(*rsa.PrivateKey)
		if rsakey.PublicKey.N.BitLen() != kr.Size() {
			t.Fatal("Generated key has wrong size.")
		}
		if sa := kr.SigAlgo(); sa == x509.UnknownSignatureAlgorithm {
			t.Fatal("Invalid signature algorithm!")
		}
	}
}

// TestBadBasicKeyRequest ensures that generating a key from a BasicKeyRequest
// fails with an invalid algorithm, or an invalid RSA or ECDSA key
// size. An invalid ECDSA key size is any size other than 256, 384, or
// 521; an invalid RSA key size is any size less than 2048 bits.
func TestBadBasicKeyRequest(t *testing.T) {
	kr := &BasicKeyRequest{"yolocrypto", 1024}

	if _, err := kr.Generate(); err == nil {
		t.Fatal("Key generation should fail with invalid algorithm")
	} else if sa := kr.SigAlgo(); sa != x509.UnknownSignatureAlgorithm {
		t.Fatal("The wrong signature algorithm was returned from SigAlgo!")
	}

	kr.A = "ecdsa"
	if _, err := kr.Generate(); err == nil {
		t.Fatal("Key generation should fail with invalid key size")
	} else if sa := kr.SigAlgo(); sa != x509.ECDSAWithSHA1 {
		t.Fatal("The wrong signature algorithm was returned from SigAlgo!")
	}

	kr.A = "rsa"
	if _, err := kr.Generate(); err == nil {
		t.Fatal("Key generation should fail with invalid key size")
	} else if sa := kr.SigAlgo(); sa != x509.SHA1WithRSA {
		t.Fatal("The wrong signature algorithm was returned from SigAlgo!")
	}

	kr = &BasicKeyRequest{"tobig", 9216}

	kr.A = "rsa"
	if _, err := kr.Generate(); err == nil {
		t.Fatal("Key generation should fail with invalid key size")
	} else if sa := kr.SigAlgo(); sa != x509.SHA512WithRSA {
		t.Fatal("The wrong signature algorithm was returned from SigAlgo!")
	}
}

// TestDefaultBasicKeyRequest makes sure that certificate requests without
// explicit key requests fall back to the default key request.
func TestDefaultBasicKeyRequest(t *testing.T) {
	var req = &CertificateRequest{
		Names: []Name{
			{
				C:  "US",
				ST: "California",
				L:  "San Francisco",
				O:  "CloudFlare",
				OU: "Systems Engineering",
			},
		},
		CN:    "cloudflare.com",
		Hosts: []string{"cloudflare.com", "www.cloudflare.com", "jdoe@example.com"},
	}
	_, priv, err := ParseRequest(req)
	if err != nil {
		t.Fatalf("%v", err)
	}

	// If the default key type changes, this will need to be changed.
	block, _ := pem.Decode(priv)
	if block == nil {
		t.Fatal("Bad private key was generated!")
	}

	DefaultKeyRequest := NewBasicKeyRequest()
	switch block.Type {
	case "RSA PRIVATE KEY":
		if DefaultKeyRequest.Algo() != "rsa" {
			t.Fatal("Invalid default key request.")
		}
	case "EC PRIVATE KEY":
		if DefaultKeyRequest.Algo() != "ecdsa" {
			t.Fatal("Invalid default key request.")
		}
	}
}

// TestRSACertRequest validates parsing a certificate request with an
// RSA key.
func TestRSACertRequest(t *testing.T) {
	var req = &CertificateRequest{
		Names: []Name{
			{
				C:  "US",
				ST: "California",
				L:  "San Francisco",
				O:  "CloudFlare",
				OU: "Systems Engineering",
			},
		},
		CN:         "cloudflare.com",
		Hosts:      []string{"cloudflare.com", "www.cloudflare.com", "jdoe@example.com"},
		KeyRequest: &BasicKeyRequest{"rsa", 2048},
	}
	_, _, err := ParseRequest(req)
	if err != nil {
		t.Fatalf("%v", err)
	}
}

// TestBadCertRequest checks for failure conditions of ParseRequest.
func TestBadCertRequest(t *testing.T) {
	var req = &CertificateRequest{
		Names: []Name{
			{
				C:  "US",
				ST: "California",
				L:  "San Francisco",
				O:  "CloudFlare",
				OU: "Systems Engineering",
			},
		},
		CN:         "cloudflare.com",
		Hosts:      []string{"cloudflare.com", "www.cloudflare.com"},
		KeyRequest: &BasicKeyRequest{"yolo-crypto", 2048},
	}
	_, _, err := ParseRequest(req)
	if err == nil {
		t.Fatal("ParseRequest should fail with a bad key algorithm.")
	}
}

// testValidator is a stripped-down validator that checks to make sure
// the request has a common name. It should mimic some of the
// functionality expected in an actual validator.
func testValidator(req *CertificateRequest) error {
	if req.CN == "" {
		return errors.NewBadRequestMissingParameter("CN")
	}

	return nil
}

// TestGenerator ensures that a valid request is processed properly
// and returns a certificate request and key.
func TestGenerator(t *testing.T) {
	g := &Generator{testValidator}
	var req = &CertificateRequest{
		Names: []Name{
			{
				C:  "US",
				ST: "California",
				L:  "San Francisco",
				O:  "CloudFlare",
				OU: "Systems Engineering",
			},
		},
		CN:         "cloudflare.com",
		Hosts:      []string{"cloudflare.com", "www.cloudflare.com", "192.168.0.1", "jdoe@example.com"},
		KeyRequest: &BasicKeyRequest{"rsa", 2048},
	}

	csrBytes, _, err := g.ProcessRequest(req)
	if err != nil {
		t.Fatal(err)
	}

	block, _ := pem.Decode([]byte(csrBytes))
	if block == nil {
		t.Fatalf("bad CSR in PEM")
	}

	if block.Type != "CERTIFICATE REQUEST" {
		t.Fatalf("bad CSR in PEM")
	}

	csr, err := x509.ParseCertificateRequest(block.Bytes)
	if err != nil {
		t.Fatal(err)
	}

	if len(csr.DNSNames) != 2 {
		t.Fatal("SAN parsing error")
	}

	if len(csr.IPAddresses) != 1 {
		t.Fatal("SAN parsing error")
	}

	if len(csr.EmailAddresses) != 1 {
		t.Fatal("SAN parsing error")
	}

}

// TestBadGenerator ensures that a request that fails the validator is
// not processed.
func TestBadGenerator(t *testing.T) {
	g := &Generator{testValidator}
	missingCN := &CertificateRequest{
		Names: []Name{
			{
				C:  "US",
				ST: "California",
				L:  "San Francisco",
				O:  "CloudFlare",
				OU: "Systems Engineering",
			},
		},
		// Missing CN
		Hosts:      []string{"cloudflare.com", "www.cloudflare.com"},
		KeyRequest: &BasicKeyRequest{"rsa", 2048},
	}

	_, _, err := g.ProcessRequest(missingCN)
	if err == nil {
		t.Fatalf("Request should have failed.")
	}
}

func TestWeakCSR(t *testing.T) {
	weakKey := &CertificateRequest{
		Names: []Name{
			{
				C:  "US",
				ST: "California",
				L:  "San Francisco",
				O:  "CloudFlare",
				OU: "Systems Engineering",
			},
		},
		CN:         "cloudflare.com",
		Hosts:      []string{"cloudflare.com", "www.cloudflare.com", "jdoe@example.com"},
		KeyRequest: &BasicKeyRequest{"rsa", 1024},
	}
	g := &Generator{testValidator}

	_, _, err := g.ProcessRequest(weakKey)
	if err == nil {
		t.Fatalf("Request should have failed.")
	}
}

var testEmpty = []struct {
	name Name
	ok   bool
}{
	{
		Name{},
		true,
	},
	{
		Name{C: "OK"},
		false,
	},
	{
		Name{ST: "OK"},
		false,
	},
	{
		Name{L: "OK"},
		false,
	},
	{
		Name{O: "OK"},
		false,
	},
	{
		Name{OU: "OK"},
		false,
	},
}

func TestIsNameEmpty(t *testing.T) {
	for i, c := range testEmpty {
		if IsNameEmpty(c.name) != c.ok {
			t.Fatalf("%d: expected IsNameEmpty to return %v, but have %v", i, c.ok, !c.ok)
		}
	}
}

func TestGenerate(t *testing.T) {
	var req = &CertificateRequest{
		Names: []Name{
			{
				C:  "US",
				ST: "California",
				L:  "San Francisco",
				O:  "CloudFlare",
				OU: "Systems Engineering",
			},
		},
		CN:         "cloudflare.com",
		Hosts:      []string{"cloudflare.com", "www.cloudflare.com", "192.168.0.1", "jdoe@example.com"},
		KeyRequest: &BasicKeyRequest{"ecdsa", 256},
	}

	key, err := req.KeyRequest.Generate()
	if err != nil {
		t.Fatalf("%v", err)
	}

	priv, ok := key.(crypto.Signer)
	if !ok {
		t.Fatal("Private key is not a signer.")
	}

	csrPEM, err := Generate(priv, req)
	if err != nil {
		t.Fatalf("%v", err)
	}

	csr, _, err := helpers.ParseCSR(csrPEM)
	if err != nil {
		t.Fatalf("%v", err)
	}

	if len(csr.DNSNames) != 2 {
		t.Fatal("SAN parsing error")
	}

	if len(csr.IPAddresses) != 1 {
		t.Fatal("SAN parsing error")
	}

	if len(csr.EmailAddresses) != 1 {
		t.Fatal("SAN parsing error")
	}
}

// TestReGenerate ensures Regenerate() is abel to use the provided CSR as a template for signing a new
// CSR using priv.
func TestReGenerate(t *testing.T) {
	var req = &CertificateRequest{
		Names: []Name{
			{
				C:  "US",
				ST: "California",
				L:  "San Francisco",
				O:  "CloudFlare",
				OU: "Systems Engineering",
			},
		},
		CN:         "cloudflare.com",
		Hosts:      []string{"cloudflare.com", "www.cloudflare.com", "192.168.0.1"},
		KeyRequest: &BasicKeyRequest{"ecdsa", 256},
	}

	csr, key, err := ParseRequest(req)
	if err != nil {
		t.Fatalf("%v", err)
	}

	priv, err := helpers.ParsePrivateKeyPEM(key)
	if err != nil {
		t.Fatalf("%v", err)
	}

	csr, err = Generate(priv, req)
	if err != nil {
		t.Fatalf("%v", err)
	}

	if _, _, err = helpers.ParseCSR(csr); err != nil {
		t.Fatalf("%v", err)
	}

	_, err = Regenerate(priv, csr)
	if err != nil {
		t.Fatalf("%v", err)
	}
}

// TestBadReGenerator ensures that a request that fails the ParseCSR is
// not processed.
func TestBadReGenerate(t *testing.T) {
	var req = &CertificateRequest{
		Names: []Name{
			{
				C:  "US",
				ST: "California",
				L:  "San Francisco",
				O:  "CloudFlare",
				OU: "Systems Engineering",
			},
		},
		CN:         "cloudflare.com",
		Hosts:      []string{"cloudflare.com", "www.cloudflare.com", "192.168.0.1"},
		KeyRequest: &BasicKeyRequest{"ecdsa", 256},
	}

	csr, key, err := ParseRequest(req)
	if err != nil {
		t.Fatalf("%v", err)
	}

	priv, err := helpers.ParsePrivateKeyPEM(key)
	if err != nil {
		t.Fatalf("%v", err)
	}

	csr, err = Generate(priv, req)
	if err != nil {
		t.Fatalf("%v", err)
	}

	block := pem.Block{
		Type: "CERTIFICATE REQUEST",
		Headers: map[string]string{
			"Location": "UCSD",
		},
		Bytes: csr,
	}

	csr = pem.EncodeToMemory(&block)

	_, err = Regenerate(priv, csr)
	if err == nil {
		t.Fatalf("%v", err)
	}
}

var testECDSACertificateFile = "testdata/test-ecdsa-ca.pem"

func TestExtractCertificateRequest(t *testing.T) {
	certPEM, err := ioutil.ReadFile(testECDSACertificateFile)
	if err != nil {
		t.Fatal(err)
	}

	// must parse ok
	cert, err := helpers.ParseCertificatePEM(certPEM)
	if err != nil {
		t.Fatal(err)
	}

	req := ExtractCertificateRequest(cert)

	if req.CN != "" {
		t.Fatal("Bad Certificate Request!")
	}

	if len(req.Names) != 1 {
		t.Fatal("Bad Certificate Request!")
	}

	name := req.Names[0]
	if name.C != "US" || name.ST != "California" || name.O != "CloudFlare, Inc." ||
		name.OU != "Test Certificate Authority" || name.L != "San Francisco" {
		t.Fatal("Bad Certificate Request!")
	}

	if req.CA == nil || req.CA.PathLength != 2 {
		t.Fatal("Bad Certificate Request!")
	}
}