summaryrefslogtreecommitdiffhomepage
path: root/prober/tls_test.go
blob: a32693762f291ee517a67e4398440922e5f5542e (plain)
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
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause

package prober

import (
	"bytes"
	"context"
	"crypto/ecdsa"
	"crypto/rand"
	"crypto/rsa"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"math/big"
	"net"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

var leafCert = x509.Certificate{
	SerialNumber:       big.NewInt(10001),
	Subject:            pkix.Name{CommonName: "tlsprobe.test"},
	SignatureAlgorithm: x509.SHA256WithRSA,
	PublicKeyAlgorithm: x509.RSA,
	Version:            3,
	IPAddresses:        []net.IP{net.IPv4(127, 0, 0, 1), net.IPv6loopback},
	NotBefore:          time.Now().Add(-5 * time.Minute),
	NotAfter:           time.Now().Add(60 * 24 * time.Hour),
	SubjectKeyId:       []byte{1, 2, 3},
	AuthorityKeyId:     []byte{1, 2, 3, 4, 5}, // issuerCert below
	ExtKeyUsage:        []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
	KeyUsage:           x509.KeyUsageDigitalSignature,
}

var issuerCertTpl = x509.Certificate{
	SerialNumber:       big.NewInt(10002),
	Subject:            pkix.Name{CommonName: "tlsprobe.ca.test"},
	SignatureAlgorithm: x509.SHA256WithRSA,
	PublicKeyAlgorithm: x509.RSA,
	Version:            3,
	IPAddresses:        []net.IP{net.IPv4(127, 0, 0, 1), net.IPv6loopback},
	NotBefore:          time.Now().Add(-5 * time.Minute),
	NotAfter:           time.Now().Add(60 * 24 * time.Hour),
	SubjectKeyId:       []byte{1, 2, 3, 4, 5},
	ExtKeyUsage:        []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
	KeyUsage:           x509.KeyUsageDigitalSignature,
}

func simpleCert() (tls.Certificate, error) {
	certPrivKey, err := rsa.GenerateKey(rand.Reader, 4096)
	if err != nil {
		return tls.Certificate{}, err
	}
	certPrivKeyPEM := new(bytes.Buffer)
	pem.Encode(certPrivKeyPEM, &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(certPrivKey),
	})
	certBytes, err := x509.CreateCertificate(rand.Reader, &leafCert, &leafCert, &certPrivKey.PublicKey, certPrivKey)
	if err != nil {
		return tls.Certificate{}, err
	}
	certPEM := new(bytes.Buffer)
	pem.Encode(certPEM, &pem.Block{
		Type:  "CERTIFICATE",
		Bytes: certBytes,
	})
	return tls.X509KeyPair(certPEM.Bytes(), certPrivKeyPEM.Bytes())
}

func TestTLSConnection(t *testing.T) {
	crt, err := simpleCert()
	if err != nil {
		t.Fatal(err)
	}
	srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	srv.TLS = &tls.Config{Certificates: []tls.Certificate{crt}}
	srv.StartTLS()
	defer srv.Close()

	err = probeTLS(context.Background(), &tls.Config{ServerName: "fail.example.com"}, srv.Listener.Addr().String())
	// The specific error message here is platform-specific ("certificate is not trusted"
	// on macOS and "certificate signed by unknown authority" on Linux), so only check
	// that it contains the word 'certificate'.
	if err == nil || !strings.Contains(err.Error(), "certificate") {
		t.Errorf("unexpected error: %q", err)
	}
}

func TestCertExpiration(t *testing.T) {
	for _, tt := range []struct {
		name    string
		cert    func() *x509.Certificate
		wantErr string
	}{
		{
			"cert not valid yet",
			func() *x509.Certificate {
				c := leafCert
				c.NotBefore = time.Now().Add(time.Hour)
				return &c
			},
			"one of the certs has NotBefore in the future",
		},
		{
			"cert expiring soon",
			func() *x509.Certificate {
				c := leafCert
				c.NotAfter = time.Now().Add(time.Hour)
				return &c
			},
			"one of the certs expires in",
		},
	} {
		t.Run(tt.name, func(t *testing.T) {
			cs := &tls.ConnectionState{PeerCertificates: []*x509.Certificate{tt.cert()}}
			err := validateConnState(context.Background(), cs)
			if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
				t.Errorf("unexpected error %q; want %q", err, tt.wantErr)
			}
		})
	}
}

type CRLServer struct {
	crlBytes []byte
}

func (s *CRLServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if s.crlBytes == nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/pkix-crl")
	w.WriteHeader(http.StatusOK)
	w.Write(s.crlBytes)
}

// someECDSAKey{1,2,3} are different EC private keys in PEM format
// as generated by:
//
//	openssl ecparam -name prime256v1 -genkey -noout -out -
//
// They're used in tests to avoid burning CPU at test time to just
// to make some arbitrary test keys.
const (
	someECDSAKey1 = `
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIDKggO47Si0/JgqF0q9m0HfQ92lbERWsBaKS5YihtuheoAoGCCqGSM49
AwEHoUQDQgAE/JtNZkfFmAGQJHW5Xgz0Eoyi9MKVxl77sXjIFDMX233QDIWPEM/B
vmNMvdFkuYBjwbq6H+SNf1NXRNladEGU/Q==
-----END EC PRIVATE KEY-----
`
	someECDSAKey2 = `
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIPIJhRf4MpzLil1ZKcRqMx+jPeJXw96KtYYzV2AcgBzgoAoGCCqGSM49
AwEHoUQDQgAEhA9CSWFmUvdvXMzyt+as+6f+0luydHU1x/gEksVByYIgYxahaGts
xbSKj6F2WgAN/ok1gFLqhH3UWMNVthM1wA==
-----END EC PRIVATE KEY-----
`
	someECDSAKey3 = `
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIKgZ1OJjK2St9O0i52N1K+IgSiu2/NSMk9Yt2+kDMHd7oAoGCCqGSM49
AwEHoUQDQgAExFp80etkjy/AEUtSgJjXRA39jTU7eiEmCGRREewFQhwcEscBEfrg
6NN31r9YlEs+hZ8gXE1L3Deu6jn5jW3pig==
-----END EC PRIVATE KEY-----
`
)

// parseECKey parses an EC private key from a PEM-encoded string.
func parseECKey(t *testing.T, pemPriv string) *ecdsa.PrivateKey {
	t.Helper()
	block, _ := pem.Decode([]byte(pemPriv))
	if block == nil {
		t.Fatal("failed to decode PEM")
	}
	key, err := x509.ParseECPrivateKey(block.Bytes)
	if err != nil {
		t.Fatalf("failed to parse EC key: %v", err)
	}
	return key
}

func TestCRL(t *testing.T) {
	// Generate CA key and self-signed CA cert
	caKey := parseECKey(t, someECDSAKey1)

	caTpl := issuerCertTpl
	caTpl.BasicConstraintsValid = true
	caTpl.IsCA = true
	caTpl.KeyUsage = x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature
	caTpl.SignatureAlgorithm = x509.ECDSAWithSHA256
	caBytes, err := x509.CreateCertificate(rand.Reader, &caTpl, &caTpl, &caKey.PublicKey, caKey)
	if err != nil {
		t.Fatal(err)
	}
	caCert, err := x509.ParseCertificate(caBytes)
	if err != nil {
		t.Fatal(err)
	}

	// Issue a leaf cert signed by the CA
	leaf := leafCert
	leaf.SerialNumber = big.NewInt(20001)
	leaf.SignatureAlgorithm = x509.ECDSAWithSHA256
	leaf.Issuer = caCert.Subject
	leafKey := parseECKey(t, someECDSAKey2)
	leafBytes, err := x509.CreateCertificate(rand.Reader, &leaf, caCert, &leafKey.PublicKey, caKey)
	if err != nil {
		t.Fatal(err)
	}
	leafCertParsed, err := x509.ParseCertificate(leafBytes)
	if err != nil {
		t.Fatal(err)
	}

	// Catch no CRL set by Let's Encrypt date.
	noCRLCert := leafCert
	noCRLCert.SerialNumber = big.NewInt(20002)
	noCRLCert.CRLDistributionPoints = []string{}
	noCRLCert.NotBefore = time.Unix(letsEncryptStartedStaplingCRL, 0).Add(-48 * time.Hour)
	noCRLCert.Issuer = caCert.Subject
	noCRLCert.SignatureAlgorithm = x509.ECDSAWithSHA256
	noCRLCertKey := parseECKey(t, someECDSAKey3)
	noCRLStapledBytes, err := x509.CreateCertificate(rand.Reader, &noCRLCert, caCert, &noCRLCertKey.PublicKey, caKey)
	if err != nil {
		t.Fatal(err)
	}
	noCRLStapledParsed, err := x509.ParseCertificate(noCRLStapledBytes)
	if err != nil {
		t.Fatal(err)
	}

	crlServer := &CRLServer{crlBytes: nil}
	srv := httptest.NewServer(crlServer)
	defer srv.Close()

	// Create a CRL that revokes the leaf cert using x509.CreateRevocationList
	now := time.Now()
	revoked := []x509.RevocationListEntry{{
		SerialNumber:   leaf.SerialNumber,
		RevocationTime: now,
		ReasonCode:     1, // Key compromise
	}}
	rl := x509.RevocationList{
		SignatureAlgorithm:        caCert.SignatureAlgorithm,
		Issuer:                    caCert.Subject,
		ThisUpdate:                now,
		NextUpdate:                now.Add(24 * time.Hour),
		RevokedCertificateEntries: revoked,
		Number:                    big.NewInt(1),
	}
	rlBytes, err := x509.CreateRevocationList(rand.Reader, &rl, caCert, caKey)
	if err != nil {
		t.Fatal(err)
	}

	emptyRlBytes, err := x509.CreateRevocationList(rand.Reader, &x509.RevocationList{Number: big.NewInt(2)}, caCert, caKey)
	if err != nil {
		t.Fatal(err)
	}

	for _, tt := range []struct {
		name     string
		cert     *x509.Certificate
		crlBytes []byte
		issuer   pkix.Name
		wantErr  string
	}{
		{
			"ValidCert",
			leafCertParsed,
			emptyRlBytes,
			caCert.Issuer,
			"",
		},
		{
			"RevokedCert",
			leafCertParsed,
			rlBytes,
			caCert.Issuer,
			"has been revoked on",
		},
		{
			"EmptyCRL",
			leafCertParsed,
			emptyRlBytes,
			caCert.Issuer,
			"",
		},
		{
			"NoCRLLetsEncrypt",
			leafCertParsed,
			nil,
			pkix.Name{CommonName: "tlsprobe.test", Organization: []string{"Let's Encrypt"}},
			"no CRL server presented in leaf cert for",
		},
		{
			"NoCRLOtherCA",
			leafCertParsed,
			nil,
			caCert.Issuer,
			"",
		},
		{
			"NotBeforeCRLStaplingDate",
			noCRLStapledParsed,
			nil,
			caCert.Issuer,
			"",
		},
	} {
		t.Run(tt.name, func(t *testing.T) {
			tt.cert.Issuer = tt.issuer
			cs := &tls.ConnectionState{PeerCertificates: []*x509.Certificate{tt.cert, caCert}}
			if tt.crlBytes != nil {
				crlServer.crlBytes = tt.crlBytes
				tt.cert.CRLDistributionPoints = []string{srv.URL}
			} else {
				crlServer.crlBytes = nil
				tt.cert.CRLDistributionPoints = []string{}
			}
			err := validateConnState(context.Background(), cs)

			if err == nil && tt.wantErr == "" {
				return
			}

			if err == nil || tt.wantErr == "" || !strings.Contains(err.Error(), tt.wantErr) {
				t.Errorf("unexpected error %q; want %q", err, tt.wantErr)
			}
		})
	}
}