File: testing_helpers_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 (479 lines) | stat: -rw-r--r-- 13,773 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
package testsuite

import (
	"crypto/x509"
	"encoding/json"
	"io/ioutil"
	"math"
	"math/rand"
	"os"
	"os/exec"
	"reflect"
	"strconv"
	"strings"
	"testing"
	"time"

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

const (
	testDataDirectory = "testdata"
	initCADirectory   = testDataDirectory + string(os.PathSeparator) + "initCA"
	preMadeOutput     = initCADirectory + string(os.PathSeparator) + "cfssl_output.pem"
	csrFile           = testDataDirectory + string(os.PathSeparator) + "cert_csr.json"
)

var (
	keyRequest = csr.BasicKeyRequest{
		A: "rsa",
		S: 2048,
	}
	CAConfig = csr.CAConfig{
		PathLength: 1,
		Expiry:     "1h", // issue a CA certificate only valid for 1 hour
	}
	baseRequest = csr.CertificateRequest{
		CN: "example.com",
		Names: []csr.Name{
			{
				C:  "US",
				ST: "California",
				L:  "San Francisco",
				O:  "Internet Widgets, LLC",
				OU: "Certificate Authority",
			},
		},
		Hosts:      []string{"ca.example.com"},
		KeyRequest: &keyRequest,
	}
	CARequest = csr.CertificateRequest{
		CN: "example.com",
		Names: []csr.Name{
			{
				C:  "US",
				ST: "California",
				L:  "San Francisco",
				O:  "Internet Widgets, LLC",
				OU: "Certificate Authority",
			},
		},
		Hosts:      []string{"ca.example.com"},
		KeyRequest: &keyRequest,
		CA:         &CAConfig,
	}
)

func TestStartCFSSLServer(t *testing.T) {
	// We will test on this address and port. Be sure that these are free or
	// the test will fail.
	addressToTest := "127.0.0.1"
	portToTest := 9775

	CACert, CAKey, err := CreateSelfSignedCert(CARequest)
	if err != nil {
		t.Fatal(err.Error())
	}

	// Set up a test server using our CA certificate and key.
	serverData := CFSSLServerData{CA: CACert, CAKey: CAKey}
	server, err := StartCFSSLServer(addressToTest, portToTest, serverData)
	if err != nil {
		t.Fatal(err.Error())
	}

	// Try to start up a second server at the same address and port number. We
	// should get an 'address in use' error.
	_, err = StartCFSSLServer(addressToTest, portToTest, serverData)
	if err == nil || !strings.Contains(err.Error(), "Error occurred on server: address") {
		t.Fatal("Two servers allowed on same address and port.")
	}

	// Now make a request of our server and check that no error occurred.

	// First we need a request to send to our server. We marshall the request
	// into JSON format and write it to a temporary file.
	jsonBytes, err := json.Marshal(baseRequest)
	if err != nil {
		t.Fatal(err.Error())
	}
	tempFile, err := createTempFile(jsonBytes)
	if err != nil {
		os.Remove(tempFile)
		panic(err)
	}

	// Now we make the request and check the output.
	remoteServerString := "-remote=" + addressToTest + ":" + strconv.Itoa(portToTest)
	command := exec.Command(
		"cfssl", "gencert", remoteServerString, "-hostname="+baseRequest.CN, tempFile)
	CLIOutput, err := command.CombinedOutput()
	os.Remove(tempFile)
	if err != nil {
		t.Fatalf("%v: %s", err.Error(), string(CLIOutput))
	}
	err = checkCLIOutput(CLIOutput)
	if err != nil {
		t.Fatal(err.Error())
	}
	// The output should contain the certificate, request, and private key.
	_, err = cleanCLIOutput(CLIOutput, "cert")
	if err != nil {
		t.Fatal(err.Error())
	}
	_, err = cleanCLIOutput(CLIOutput, "csr")
	if err != nil {
		t.Fatal(err.Error())
	}
	_, err = cleanCLIOutput(CLIOutput, "key")
	if err != nil {
		t.Fatal(err.Error())
	}

	// Finally, kill the server.
	err = server.Kill()
	if err != nil {
		t.Fatal(err.Error())
	}
}

func TestCreateCertificateChain(t *testing.T) {

	// N is the number of certificates that will be chained together.
	N := 10

	// --- TEST: Create a chain of one certificate. --- //

	encodedChainFromCode, _, err := CreateCertificateChain([]csr.CertificateRequest{CARequest})
	if err != nil {
		t.Fatal(err.Error())
	}

	// Now compare to a pre-made certificate chain using a JSON file containing
	// the same request data.

	CLIOutputFile := preMadeOutput
	CLIOutput, err := ioutil.ReadFile(CLIOutputFile)
	if err != nil {
		t.Fatal(err.Error())
	}
	encodedChainFromCLI, err := cleanCLIOutput(CLIOutput, "cert")
	if err != nil {
		t.Fatal(err.Error())
	}

	chainFromCode, err := helpers.ParseCertificatesPEM(encodedChainFromCode)
	if err != nil {
		t.Fatal(err.Error())
	}
	chainFromCLI, err := helpers.ParseCertificatesPEM(encodedChainFromCLI)
	if err != nil {
		t.Fatal(err.Error())
	}

	if !chainsEqual(chainFromCode, chainFromCLI) {
		unequalFieldSlices := checkFieldsOfChains(chainFromCode, chainFromCLI)
		for i, unequalFields := range unequalFieldSlices {
			if len(unequalFields) > 0 {
				t.Log("The certificate chains held unequal fields for chain " + strconv.Itoa(i))
				t.Log("The following fields were unequal:")
				for _, field := range unequalFields {
					t.Log("\t" + field)
				}
			}
		}
		t.Fatal("Certificate chains unequal.")
	}

	// --- TEST: Create a chain of N certificates. --- //

	// First we make a slice of N requests. We make each slightly different.

	cnGrabBag := []string{"example", "invalid", "test"}
	topLevelDomains := []string{".com", ".net", ".org"}
	subDomains := []string{"www.", "secure.", "ca.", ""}
	countryGrabBag := []string{"USA", "China", "England", "Vanuatu"}
	stateGrabBag := []string{"California", "Texas", "Alaska", "London"}
	localityGrabBag := []string{"San Francisco", "Houston", "London", "Oslo"}
	orgGrabBag := []string{"Internet Widgets, LLC", "CloudFlare, Inc."}
	orgUnitGrabBag := []string{"Certificate Authority", "Systems Engineering"}

	requests := make([]csr.CertificateRequest, N)
	requests[0] = CARequest
	for i := 1; i < N; i++ {
		requests[i] = baseRequest

		cn := randomElement(cnGrabBag)
		tld := randomElement(topLevelDomains)
		subDomain1 := randomElement(subDomains)
		subDomain2 := randomElement(subDomains)
		country := randomElement(countryGrabBag)
		state := randomElement(stateGrabBag)
		locality := randomElement(localityGrabBag)
		org := randomElement(orgGrabBag)
		orgUnit := randomElement(orgUnitGrabBag)

		requests[i].CN = cn + "." + tld
		requests[i].Names = []csr.Name{
			{C: country,
				ST: state,
				L:  locality,
				O:  org,
				OU: orgUnit,
			},
		}
		hosts := []string{subDomain1 + requests[i].CN}
		if subDomain2 != subDomain1 {
			hosts = append(hosts, subDomain2+requests[i].CN)
		}
		requests[i].Hosts = hosts
	}

	// Now we make a certificate chain out of these requests.
	encodedCertChain, _, err := CreateCertificateChain(requests)
	if err != nil {
		t.Fatal(err.Error())
	}

	// To test this chain, we compare the data encoded in each certificate to
	// each request we used to generate the chain.
	chain, err := helpers.ParseCertificatesPEM(encodedCertChain)
	if err != nil {
		t.Fatal(err.Error())
	}

	if len(chain) != len(requests) {
		t.Log("Length of chain: " + strconv.Itoa(len(chain)))
		t.Log("Length of requests: " + strconv.Itoa(len(requests)))
		t.Fatal("Length of chain not equal to length of requests.")
	}

	mismatchOccurred := false
	for i := 0; i < len(chain); i++ {
		certEqualsRequest, unequalFields := certEqualsRequest(chain[i], requests[i])
		if !certEqualsRequest {
			mismatchOccurred = true
			t.Log(
				"Certificate " + strconv.Itoa(i) + " and request " +
					strconv.Itoa(i) + " unequal.",
			)
			t.Log("Unequal fields for index " + strconv.Itoa(i) + ":")
			for _, field := range unequalFields {
				t.Log("\t" + field)
			}
		}
	}

	// TODO: check that each certificate is actually signed by the previous one

	if mismatchOccurred {
		t.Fatal("Unequal certificate(s) and request(s) found.")
	}

	// --- TEST: Create a chain of certificates with invalid path lengths. --- //

	// Other invalid chains?
}

func TestCreateSelfSignedCert(t *testing.T) {

	// --- TEST: Create a self-signed certificate from a CSR. --- //

	// Generate a self-signed certificate from the request.
	encodedCertFromCode, _, err := CreateSelfSignedCert(CARequest)
	if err != nil {
		t.Fatal(err.Error())
	}

	// Now compare to a pre-made certificate made using a JSON file with the
	// same request information. This JSON file is located in testdata/initCA
	// and is called ca_csr.json.

	CLIOutputFile := preMadeOutput
	CLIOutput, err := ioutil.ReadFile(CLIOutputFile)
	if err != nil {
		t.Fatal(err.Error())
	}
	encodedCertFromCLI, err := cleanCLIOutput(CLIOutput, "cert")
	if err != nil {
		t.Fatal(err.Error())
	}

	certFromCode, err := helpers.ParseSelfSignedCertificatePEM(encodedCertFromCode)
	if err != nil {
		t.Fatal(err.Error())
	}
	certFromCLI, err := helpers.ParseSelfSignedCertificatePEM(encodedCertFromCLI)
	if err != nil {
		t.Fatal(err.Error())
	}

	// Nullify any fields of the certificates which are dependent upon the time
	// of the certificate's creation.
	nullifyTimeDependency(certFromCode)
	nullifyTimeDependency(certFromCLI)

	if !reflect.DeepEqual(certFromCode, certFromCLI) {
		unequalFields := checkFields(
			*certFromCode, *certFromCLI, reflect.TypeOf(*certFromCode))
		t.Log("The following fields were unequal:")
		for _, field := range unequalFields {
			t.Log(field)
		}
		t.Fatal("Certificates unequal.")
	}

}

// Compare two x509 certificate chains. We only compare relevant data to
// determine equality.
func chainsEqual(chain1, chain2 []*x509.Certificate) bool {
	if len(chain1) != len(chain2) {
		return false
	}

	for i := 0; i < len(chain1); i++ {
		cert1 := nullifyTimeDependency(chain1[i])
		cert2 := nullifyTimeDependency(chain2[i])
		if !reflect.DeepEqual(cert1, cert2) {
			return false
		}
	}
	return true
}

// When comparing certificates created at different times for equality, we do
// not want to worry about fields which are dependent on the time of creation.
// Thus we nullify these fields before comparing the certificates.
func nullifyTimeDependency(cert *x509.Certificate) *x509.Certificate {
	cert.Raw = nil
	cert.RawTBSCertificate = nil
	cert.RawSubject = nil
	cert.RawIssuer = nil
	cert.RawSubjectPublicKeyInfo = nil
	cert.Signature = nil
	cert.PublicKey = nil
	cert.SerialNumber = nil
	cert.NotBefore = time.Time{}
	cert.NotAfter = time.Time{}
	cert.Extensions = nil
	cert.SubjectKeyId = nil
	cert.AuthorityKeyId = nil

	cert.Subject.Names = nil
	cert.Subject.ExtraNames = nil
	cert.Issuer.Names = nil
	cert.Issuer.ExtraNames = nil

	return cert
}

// Compares two structs and returns a list containing the names of all fields
// for which the two structs hold different values.
func checkFields(struct1, struct2 interface{}, typeOfStructs reflect.Type) []string {
	v1 := reflect.ValueOf(struct1)
	v2 := reflect.ValueOf(struct2)

	var unequalFields []string
	for i := 0; i < v1.NumField(); i++ {
		if !reflect.DeepEqual(v1.Field(i).Interface(), v2.Field(i).Interface()) {
			unequalFields = append(unequalFields, typeOfStructs.Field(i).Name)
		}
	}

	return unequalFields
}

// Runs checkFields on the corresponding elements of chain1 and chain2. Element
// i of the returned slice contains a slice of the fields for which certificate
// i in chain1 had different values than certificate i of chain2.
func checkFieldsOfChains(chain1, chain2 []*x509.Certificate) [][]string {
	minLen := math.Min(float64(len(chain1)), float64(len(chain2)))
	typeOfCert := reflect.TypeOf(*chain1[0])

	var unequalFields [][]string
	for i := 0; i < int(minLen); i++ {
		unequalFields = append(unequalFields, checkFields(
			*chain1[i], *chain2[i], typeOfCert))
	}

	return unequalFields
}

// Compares a certificate to a request. Returns (true, []) if both items
// contain matching data (for the things that can match). Otherwise, returns
// (false, unequalFields) where unequalFields contains the names of all fields
// which did not match.
func certEqualsRequest(cert *x509.Certificate, request csr.CertificateRequest) (bool, []string) {
	equal := true
	var unequalFields []string

	if cert.Subject.CommonName != request.CN {
		equal = false
		unequalFields = append(unequalFields, "Common Name")
	}

	nameData := make(map[string]map[string]bool)
	nameData["Country"] = make(map[string]bool)
	nameData["Organization"] = make(map[string]bool)
	nameData["OrganizationalUnit"] = make(map[string]bool)
	nameData["Locality"] = make(map[string]bool)
	nameData["Province"] = make(map[string]bool)
	for _, name := range request.Names {
		nameData["Country"][name.C] = true
		nameData["Organization"][name.O] = true
		nameData["OrganizationalUnit"][name.OU] = true
		nameData["Locality"][name.L] = true
		nameData["Province"][name.ST] = true
	}
	for _, country := range cert.Subject.Country {
		if _, exists := nameData["Country"][country]; !exists {
			equal = false
			unequalFields = append(unequalFields, "Country")
		}
	}
	for _, organization := range cert.Subject.Organization {
		if _, exists := nameData["Organization"][organization]; !exists {
			equal = false
			unequalFields = append(unequalFields, "Organization")
		}
	}
	for _, organizationalUnit := range cert.Subject.OrganizationalUnit {
		if _, exists := nameData["OrganizationalUnit"][organizationalUnit]; !exists {
			equal = false
			unequalFields = append(unequalFields, "OrganizationalUnit")
		}
	}
	for _, locality := range cert.Subject.Locality {
		if _, exists := nameData["Locality"][locality]; !exists {
			equal = false
			unequalFields = append(unequalFields, "Locality")
		}
	}
	for _, province := range cert.Subject.Province {
		if _, exists := nameData["Province"][province]; !exists {
			equal = false
			unequalFields = append(unequalFields, "Province")
		}
	}

	// TODO: check hosts

	if cert.BasicConstraintsValid && request.CA != nil {
		if cert.MaxPathLen != request.CA.PathLength {
			equal = false
			unequalFields = append(unequalFields, "Max Path Length")
		}
		// TODO: check expiry
	}

	// TODO: check isCA

	return equal, unequalFields
}

// Returns a random element of the input slice.
func randomElement(set []string) string {
	return set[rand.Intn(len(set))]
}