-
Notifications
You must be signed in to change notification settings - Fork 156
/
x509_test.go
211 lines (188 loc) · 4.63 KB
/
x509_test.go
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
// Copyright (c) 2020-2024 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/tls"
"crypto/x509"
"io"
logpkg "log"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/decred/dcrd/crypto/rand"
)
type keygen func(t *testing.T) (pub, priv any, name string)
func ed25519Keygen() keygen {
return func(t *testing.T) (pub, priv any, name string) {
seed := make([]byte, ed25519.SeedSize)
rand.Read(seed)
key := ed25519.NewKeyFromSeed(seed)
return key.Public(), key, "ed25519"
}
}
func ecKeygen(curve elliptic.Curve) keygen {
return func(t *testing.T) (pub, priv any, name string) {
var key *ecdsa.PrivateKey
key, err := ecdsa.GenerateKey(curve, rand.Reader())
if err != nil {
t.Fatal(err)
}
return key.Public(), key, curve.Params().Name
}
}
func TestClientCert(t *testing.T) {
algos := []keygen{
ed25519Keygen(),
ecKeygen(elliptic.P256()),
ecKeygen(elliptic.P384()),
ecKeygen(elliptic.P521()),
}
for _, algo := range algos {
pub, priv, name := algo(t)
testClientCert(t, pub, priv, name)
}
}
func echo(w http.ResponseWriter, r *http.Request) {
io.Copy(w, r.Body)
}
func testClientCert(t *testing.T, pub, priv any, name string) {
ca, err := generateAuthority(pub, priv)
if err != nil {
t.Error(err)
return
}
keyBlock, err := marshalPrivateKey(ca.PrivateKey)
if err != nil {
t.Error(err)
return
}
certBlock, err := createSignedClientCert(pub, ca.PrivateKey, ca.Cert)
if err != nil {
t.Error(err)
return
}
keypair, err := tls.X509KeyPair(certBlock, keyBlock)
if err != nil {
t.Error(err)
return
}
s := httptest.NewUnstartedServer(http.HandlerFunc(echo))
s.TLS = &tls.Config{
MinVersion: tls.VersionTLS12,
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: x509.NewCertPool(),
}
s.TLS.ClientCAs.AddCert(ca.Cert)
defer s.Close()
s.StartTLS()
client := s.Client()
tr := client.Transport.(*http.Transport)
tr.TLSClientConfig.Certificates = []tls.Certificate{keypair}
req, err := http.NewRequest(http.MethodPut, s.URL, strings.NewReader("balls"))
if err != nil {
t.Error(err)
return
}
resp, err := s.Client().Do(req)
if err != nil {
t.Errorf("algorithm %s: %v", name, err)
return
}
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
t.Error(err)
return
}
if !bytes.Equal(body, []byte("balls")) {
t.Errorf("echo handler did not return expected result")
}
}
func TestUntrustedClientCert(t *testing.T) {
algo := ed25519Keygen()
pub1, priv1, _ := algo(t) // trusted by server
pub2, priv2, _ := algo(t) // presented by client
ca1, err := generateAuthority(pub1, priv1)
if err != nil {
t.Error(err)
return
}
ca2, err := generateAuthority(pub2, priv2)
if err != nil {
t.Error(err)
return
}
keyBlock2, err := marshalPrivateKey(ca2.PrivateKey)
if err != nil {
t.Error(err)
return
}
certBlock2, err := createSignedClientCert(pub2, ca2.PrivateKey, ca2.Cert)
if err != nil {
t.Error(err)
return
}
keypair2, err := tls.X509KeyPair(certBlock2, keyBlock2)
if err != nil {
t.Error(err)
return
}
s := httptest.NewUnstartedServer(http.HandlerFunc(echo))
s.Config = &http.Server{
// Don't log remote cert errors for this negative test
ErrorLog: logpkg.New(io.Discard, "", 0),
}
s.TLS = &tls.Config{
MinVersion: tls.VersionTLS12,
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: x509.NewCertPool(),
}
s.TLS.ClientCAs.AddCert(ca1.Cert)
defer s.Close()
s.StartTLS()
client := s.Client()
tr := client.Transport.(*http.Transport)
tr.TLSClientConfig.Certificates = []tls.Certificate{keypair2}
ctx := context.Background()
errChan := make(chan error, 2)
timeout := time.After(time.Second * 5)
for {
go func() {
req, err := http.NewRequestWithContext(ctx, http.MethodPut, s.URL, strings.NewReader("test"))
if err != nil {
errChan <- err
return
}
_, err = s.Client().Do(req)
errChan <- err
}()
select {
case err := <-errChan:
if err == nil {
t.Fatalf("request with bad client cert did not error")
}
if strings.HasSuffix(err.Error(), "reset by peer") ||
strings.Contains(err.Error(), "connection was forcibly closed") {
// Retry.
continue
}
if !(strings.HasSuffix(err.Error(), "tls: bad certificate") ||
strings.HasSuffix(err.Error(), "tls: unknown certificate authority")) {
t.Fatalf("server did not report bad certificate error; "+
"instead errored with: %v (%T)", err, err)
}
// Success.
return
case <-timeout:
t.Fatal("Did not receive response before timeout")
}
}
}