-
-
Notifications
You must be signed in to change notification settings - Fork 351
Expand file tree
/
Copy pathocsp_test.go
More file actions
402 lines (365 loc) · 12.5 KB
/
Copy pathocsp_test.go
File metadata and controls
402 lines (365 loc) · 12.5 KB
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
package certmagic
import (
"bytes"
"context"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"io"
"math/big"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"golang.org/x/crypto/ocsp"
)
const certWithOCSPServer = `-----BEGIN CERTIFICATE-----
MIIBgjCCASegAwIBAgICIAAwCgYIKoZIzj0EAwIwEjEQMA4GA1UEAxMHVGVzdCBD
QTAeFw0yMzAxMDExMjAwMDBaFw0yMzAyMDExMjAwMDBaMCAxHjAcBgNVBAMTFU9D
U1AgVGVzdCBDZXJ0aWZpY2F0ZTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABIoe
I/bjo34qony8LdRJD+Jhuk8/S8YHXRHl6rH9t5VFCFtX8lIPN/Ll1zCrQ2KB3Wlb
fxSgiQyLrCpZyrdhVPSjXzBdMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAU+Eo3
5sST4LRrwS4dueIdGBZ5d7IwLAYIKwYBBQUHAQEEIDAeMBwGCCsGAQUFBzABhhBv
Y3NwLmV4YW1wbGUuY29tMAoGCCqGSM49BAMCA0kAMEYCIQDg94xY/+/VepESdvTT
ykCwiWOS2aCpjyryrKpwMKkR0AIhAPc/+ZEz4W10OENxC1t+NUTvS8JbEGOwulkZ
z9yfaLuD
-----END CERTIFICATE-----`
const certWithoutOCSPServer = `-----BEGIN CERTIFICATE-----
MIIBUzCB+aADAgECAgIgADAKBggqhkjOPQQDAjASMRAwDgYDVQQDEwdUZXN0IENB
MB4XDTIzMDEwMTEyMDAwMFoXDTIzMDIwMTEyMDAwMFowIDEeMBwGA1UEAxMVT0NT
UCBUZXN0IENlcnRpZmljYXRlMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEih4j
9uOjfiqifLwt1EkP4mG6Tz9LxgddEeXqsf23lUUIW1fyUg838uXXMKtDYoHdaVt/
FKCJDIusKlnKt2FU9KMxMC8wDAYDVR0TAQH/BAIwADAfBgNVHSMEGDAWgBT4Sjfm
xJPgtGvBLh254h0YFnl3sjAKBggqhkjOPQQDAgNJADBGAiEA3rWetLGblfSuNZKf
5CpZxhj3A0BjEocEh+2P+nAgIdUCIQDIgptabR1qTLQaF2u0hJsEX2IKuIUvYWH3
6Lb92+zIHg==
-----END CERTIFICATE-----`
// certKey is the private key for both certWithOCSPServer and
// certWithoutOCSPServer.
const certKey = `-----BEGIN EC PRIVATE KEY-----
MHcCAQEEINnVcgrSNh4HlThWlZpegq14M8G/p9NVDtdVjZrseUGLoAoGCCqGSM49
AwEHoUQDQgAEih4j9uOjfiqifLwt1EkP4mG6Tz9LxgddEeXqsf23lUUIW1fyUg83
8uXXMKtDYoHdaVt/FKCJDIusKlnKt2FU9A==
-----END EC PRIVATE KEY-----`
// caCert is the issuing certificate for certWithOCSPServer and
// certWithoutOCSPServer.
const caCert = `-----BEGIN CERTIFICATE-----
MIIBazCCARGgAwIBAgICEAAwCgYIKoZIzj0EAwIwEjEQMA4GA1UEAxMHVGVzdCBD
QTAeFw0yMzAxMDExMjAwMDBaFw0yMzAyMDExMjAwMDBaMBIxEDAOBgNVBAMTB1Rl
c3QgQ0EwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASdKexSor/aeazDM57UHhAX
rCkJxUeF2BWf0lZYCRxc3f0GdrEsVvjJW8+/E06eAzDCGSdM/08Nvun1nb6AmAlt
o1cwVTAOBgNVHQ8BAf8EBAMCAQYwEwYDVR0lBAwwCgYIKwYBBQUHAwkwDwYDVR0T
AQH/BAUwAwEB/zAdBgNVHQ4EFgQU+Eo35sST4LRrwS4dueIdGBZ5d7IwCgYIKoZI
zj0EAwIDSAAwRQIgGbA39+kETTB/YMLBFoC2fpZe1cDWfFB7TUdfINUqdH4CIQCR
ByUFC8A+hRNkK5YNH78bgjnKk/88zUQF5ONy4oPGdQ==
-----END CERTIFICATE-----`
const caKey = `-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIDJ59ptjq3MzILH4zn5IKoH1sYn+zrUeq2kD8+DD2x+OoAoGCCqGSM49
AwEHoUQDQgAEnSnsUqK/2nmswzOe1B4QF6wpCcVHhdgVn9JWWAkcXN39BnaxLFb4
yVvPvxNOngMwwhknTP9PDb7p9Z2+gJgJbQ==
-----END EC PRIVATE KEY-----`
func TestStapleOCSP(t *testing.T) {
ctx := context.Background()
storage := &FileStorage{Path: t.TempDir()}
t.Run("disabled", func(t *testing.T) {
cert := mustMakeCertificate(t, certWithOCSPServer, certKey)
config := OCSPConfig{DisableStapling: true}
err := stapleOCSP(ctx, config, storage, &cert, nil)
if err != nil {
t.Error("unexpected error:", err)
} else if cert.Certificate.OCSPStaple != nil {
t.Error("unexpected OCSP staple")
}
})
t.Run("no OCSP server", func(t *testing.T) {
cert := mustMakeCertificate(t, certWithoutOCSPServer, certKey)
err := stapleOCSP(ctx, OCSPConfig{}, storage, &cert, nil)
if !errors.Is(err, ErrNoOCSPServerSpecified) {
t.Error("expected ErrNoOCSPServerSpecified in error", err)
}
})
// Start an OCSP responder test server.
responses := make(map[string][]byte)
responder := startOCSPResponder(t, responses)
t.Cleanup(responder.Close)
ca := mustMakeCertificate(t, caCert, caKey)
// The certWithOCSPServer certificate has a bogus ocsp.example.com endpoint.
// Use the ResponderOverrides option to point to the test server instead.
config := OCSPConfig{
ResponderOverrides: map[string]string{
"ocsp.example.com": responder.URL,
},
}
t.Run("ok", func(t *testing.T) {
cert := mustMakeCertificate(t, certWithOCSPServer, certKey)
tpl := ocsp.Response{
Status: ocsp.Good,
SerialNumber: cert.Leaf.SerialNumber,
}
r, err := ocsp.CreateResponse(
ca.Leaf, ca.Leaf, tpl, ca.PrivateKey.(crypto.Signer))
if err != nil {
t.Fatal("couldn't create OCSP response", err)
}
responses[cert.Leaf.SerialNumber.String()] = r
bundle := []byte(certWithOCSPServer + "\n" + caCert)
err = stapleOCSP(ctx, config, storage, &cert, bundle)
if err != nil {
t.Error("unexpected error:", err)
} else if !bytes.Equal(cert.Certificate.OCSPStaple, r) {
t.Error("expected OCSP response to be stapled to certificate")
}
})
t.Run("revoked", func(t *testing.T) {
cert := mustMakeCertificate(t, certWithOCSPServer, certKey)
tpl := ocsp.Response{
Status: ocsp.Revoked,
SerialNumber: cert.Leaf.SerialNumber,
}
r, err := ocsp.CreateResponse(
ca.Leaf, ca.Leaf, tpl, ca.PrivateKey.(crypto.Signer))
if err != nil {
t.Fatal("couldn't create OCSP response", err)
}
responses[cert.Leaf.SerialNumber.String()] = r
bundle := []byte(certWithOCSPServer + "\n" + caCert)
err = stapleOCSP(ctx, config, storage, &cert, bundle)
if err != nil {
t.Error("unexpected error:", err)
} else if cert.Certificate.OCSPStaple != nil {
t.Error("revoked OCSP response should not be stapled")
}
})
t.Run("no issuing cert", func(t *testing.T) {
cert := mustMakeCertificate(t, certWithOCSPServer, certKey)
err := stapleOCSP(ctx, config, storage, &cert, nil)
expected := "no OCSP stapling for [ocsp test certificate]: " +
"no URL to issuing certificate"
if err == nil || err.Error() != expected {
t.Errorf("expected error %q but got %q", expected, err)
}
})
}
func TestValidateOCSPResponder(t *testing.T) {
issuer := mustMakeCertificate(t, caCert, caKey).Leaf
tests := []struct {
name string
resp *ocsp.Response
wantErr string
}{
{
name: "issuer signed response with no embedded cert",
resp: &ocsp.Response{Certificate: nil},
},
{
name: "embedded responder cert is issuer cert",
resp: &ocsp.Response{Certificate: issuer},
},
{
name: "delegated responder with OCSP signing eku",
resp: &ocsp.Response{Certificate: &x509.Certificate{
Subject: pkix.Name{CommonName: "Delegated OCSP Responder"},
ExtKeyUsage: []x509.ExtKeyUsage{
x509.ExtKeyUsageServerAuth,
x509.ExtKeyUsageOCSPSigning,
},
}},
},
{
name: "delegated responder without OCSP signing eku",
resp: &ocsp.Response{Certificate: &x509.Certificate{
Subject: pkix.Name{CommonName: "Not Authorized"},
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}},
wantErr: "does not carry id-kp-OCSPSigning",
},
{
name: "delegated responder with empty eku",
resp: &ocsp.Response{Certificate: &x509.Certificate{
Subject: pkix.Name{CommonName: "No EKU"},
}},
wantErr: "does not carry id-kp-OCSPSigning",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
err := validateOCSPResponder(tc.resp, issuer)
if tc.wantErr == "" {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
return
}
if err == nil {
t.Fatalf("expected error containing %q, got nil", tc.wantErr)
}
if !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("expected error containing %q, got %q", tc.wantErr, err.Error())
}
})
}
}
func TestStapleOCSPDelegatedResponderAuthorization(t *testing.T) {
now := time.Now().Add(-1 * time.Hour)
issuerCert, issuerKey, issuerPEM := mustIssueTestCertificate(t, &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: "test issuer"},
NotBefore: now,
NotAfter: now.Add(48 * time.Hour),
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
BasicConstraintsValid: true,
IsCA: true,
}, nil, nil)
issuedCert, issuedKey, issuedPEM := mustIssueTestCertificate(t, &x509.Certificate{
SerialNumber: big.NewInt(2),
Subject: pkix.Name{CommonName: "victim.example"},
DNSNames: []string{"victim.example"},
NotBefore: now,
NotAfter: now.Add(30 * 24 * time.Hour),
OCSPServer: []string{"http://ocsp.example.test"},
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}, issuerCert, issuerKey)
issuedKeyPEM, err := PEMEncodePrivateKey(issuedKey)
if err != nil {
t.Fatalf("encoding issued certificate key: %v", err)
}
bundle := append(append([]byte{}, issuedPEM...), issuerPEM...)
tests := []struct {
name string
responderSerial int64
responderCommonName string
responderExtKeyUsage []x509.ExtKeyUsage
wantErr string
wantStaple bool
}{
{
name: "authorized OCSP responder is stapled",
responderSerial: 3,
responderCommonName: "authorized-responder.example",
responderExtKeyUsage: []x509.ExtKeyUsage{
x509.ExtKeyUsageOCSPSigning,
},
wantStaple: true,
},
{
name: "same issuer server auth responder is rejected",
responderSerial: 4,
responderCommonName: "server-auth-responder.example",
responderExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
wantErr: "does not carry id-kp-OCSPSigning",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
responderCert, responderKey, _ := mustIssueTestCertificate(t, &x509.Certificate{
SerialNumber: big.NewInt(tc.responderSerial),
Subject: pkix.Name{CommonName: tc.responderCommonName},
DNSNames: []string{tc.responderCommonName},
NotBefore: now,
NotAfter: now.Add(30 * 24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: tc.responderExtKeyUsage,
}, issuerCert, issuerKey)
responseBytes, err := ocsp.CreateResponse(issuerCert, responderCert, ocsp.Response{
Status: ocsp.Good,
SerialNumber: issuedCert.SerialNumber,
ThisUpdate: time.Now().Add(-5 * time.Minute).UTC(),
NextUpdate: time.Now().Add(2 * time.Hour).UTC(),
Certificate: responderCert,
}, responderKey)
if err != nil {
t.Fatalf("creating OCSP response: %v", err)
}
responder := startOCSPResponder(t, map[string][]byte{
issuedCert.SerialNumber.String(): responseBytes,
})
defer responder.Close()
cert, err := makeCertificate(issuedPEM, issuedKeyPEM)
if err != nil {
t.Fatalf("making issued certificate: %v", err)
}
config := OCSPConfig{
ResponderOverrides: map[string]string{
"http://ocsp.example.test": responder.URL,
},
}
storage := &FileStorage{Path: t.TempDir()}
err = stapleOCSP(context.Background(), config, storage, &cert, bundle)
if tc.wantErr != "" {
if err == nil {
t.Fatalf("expected error containing %q, got nil", tc.wantErr)
}
if !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("expected error containing %q, got %q", tc.wantErr, err.Error())
}
if cert.Certificate.OCSPStaple != nil {
t.Fatal("unexpected OCSP staple for unauthorized responder")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if tc.wantStaple && !bytes.Equal(cert.Certificate.OCSPStaple, responseBytes) {
t.Fatal("expected OCSP response to be stapled")
}
})
}
}
func mustMakeCertificate(t *testing.T, cert, key string) Certificate {
t.Helper()
c, err := makeCertificate([]byte(cert), []byte(key))
if err != nil {
t.Fatal("couldn't make certificate:", err)
}
return c
}
func startOCSPResponder(
t *testing.T, responses map[string][]byte,
) *httptest.Server {
h := func(w http.ResponseWriter, r *http.Request) {
ct := r.Header.Get("Content-Type")
if ct != "application/ocsp-request" {
t.Errorf("unexpected request Content-Type %q", ct)
}
b, _ := io.ReadAll(r.Body)
request, err := ocsp.ParseRequest(b)
if err != nil {
t.Fatal(err)
}
w.Header().Set("Content-Type", "application/ocsp-response")
w.Write(responses[request.SerialNumber.String()])
}
return httptest.NewServer(http.HandlerFunc(h))
}
func mustIssueTestCertificate(
t *testing.T,
tmpl, parent *x509.Certificate,
parentKey crypto.Signer,
) (*x509.Certificate, crypto.Signer, []byte) {
t.Helper()
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatalf("generating private key: %v", err)
}
if parent == nil {
parent = tmpl
parentKey = priv
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, parent, priv.Public(), parentKey)
if err != nil {
t.Fatalf("creating certificate: %v", err)
}
cert, err := x509.ParseCertificate(der)
if err != nil {
t.Fatalf("parsing certificate: %v", err)
}
return cert, priv, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
}