| 1 |
// Copyright 2012 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package tls |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"context" |
| 10 |
"crypto" |
| 11 |
"crypto/x509" |
| 12 |
"encoding/json" |
| 13 |
"errors" |
| 14 |
"fmt" |
| 15 |
"internal/testenv" |
| 16 |
"io" |
| 17 |
"math" |
| 18 |
"net" |
| 19 |
"os" |
| 20 |
"reflect" |
| 21 |
"sort" |
| 22 |
"strings" |
| 23 |
"testing" |
| 24 |
"time" |
| 25 |
) |
| 26 |
|
| 27 |
var rsaCertPEM = `-----BEGIN CERTIFICATE----- |
| 28 |
MIIB0zCCAX2gAwIBAgIJAI/M7BYjwB+uMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV |
| 29 |
BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX |
| 30 |
aWRnaXRzIFB0eSBMdGQwHhcNMTIwOTEyMjE1MjAyWhcNMTUwOTEyMjE1MjAyWjBF |
| 31 |
MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 |
| 32 |
ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANLJ |
| 33 |
hPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wok/4xIA+ui35/MmNa |
| 34 |
rtNuC+BdZ1tMuVCPFZcCAwEAAaNQME4wHQYDVR0OBBYEFJvKs8RfJaXTH08W+SGv |
| 35 |
zQyKn0H8MB8GA1UdIwQYMBaAFJvKs8RfJaXTH08W+SGvzQyKn0H8MAwGA1UdEwQF |
| 36 |
MAMBAf8wDQYJKoZIhvcNAQEFBQADQQBJlffJHybjDGxRMqaRmDhX0+6v02TUKZsW |
| 37 |
r5QuVbpQhH6u+0UgcW0jp9QwpxoPTLTWGXEWBBBurxFwiCBhkQ+V |
| 38 |
-----END CERTIFICATE----- |
| 39 |
` |
| 40 |
|
| 41 |
var rsaKeyPEM = testingKey(`-----BEGIN RSA TESTING KEY----- |
| 42 |
MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo |
| 43 |
k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G |
| 44 |
6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N |
| 45 |
MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW |
| 46 |
SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T |
| 47 |
xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi |
| 48 |
D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g== |
| 49 |
-----END RSA TESTING KEY----- |
| 50 |
`) |
| 51 |
|
| 52 |
// keyPEM is the same as rsaKeyPEM, but declares itself as just |
| 53 |
// "PRIVATE KEY", not "RSA PRIVATE KEY". https://golang.org/issue/4477 |
| 54 |
var keyPEM = testingKey(`-----BEGIN TESTING KEY----- |
| 55 |
MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo |
| 56 |
k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G |
| 57 |
6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N |
| 58 |
MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW |
| 59 |
SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T |
| 60 |
xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi |
| 61 |
D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g== |
| 62 |
-----END TESTING KEY----- |
| 63 |
`) |
| 64 |
|
| 65 |
var ecdsaCertPEM = `-----BEGIN CERTIFICATE----- |
| 66 |
MIIB/jCCAWICCQDscdUxw16XFDAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw |
| 67 |
EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0 |
| 68 |
eSBMdGQwHhcNMTIxMTE0MTI0MDQ4WhcNMTUxMTE0MTI0MDQ4WjBFMQswCQYDVQQG |
| 69 |
EwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lk |
| 70 |
Z2l0cyBQdHkgTHRkMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBY9+my9OoeSUR |
| 71 |
lDQdV/x8LsOuLilthhiS1Tz4aGDHIPwC1mlvnf7fg5lecYpMCrLLhauAc1UJXcgl |
| 72 |
01xoLuzgtAEAgv2P/jgytzRSpUYvgLBt1UA0leLYBy6mQQbrNEuqT3INapKIcUv8 |
| 73 |
XxYP0xMEUksLPq6Ca+CRSqTtrd/23uTnapkwCQYHKoZIzj0EAQOBigAwgYYCQXJo |
| 74 |
A7Sl2nLVf+4Iu/tAX/IF4MavARKC4PPHK3zfuGfPR3oCCcsAoz3kAzOeijvd0iXb |
| 75 |
H5jBImIxPL4WxQNiBTexAkF8D1EtpYuWdlVQ80/h/f4pBcGiXPqX5h2PQSQY7hP1 |
| 76 |
+jwM1FGS4fREIOvlBYr/SzzQRtwrvrzGYxDEDbsC0ZGRnA== |
| 77 |
-----END CERTIFICATE----- |
| 78 |
` |
| 79 |
|
| 80 |
var ecdsaKeyPEM = testingKey(`-----BEGIN EC PARAMETERS----- |
| 81 |
BgUrgQQAIw== |
| 82 |
-----END EC PARAMETERS----- |
| 83 |
-----BEGIN EC TESTING KEY----- |
| 84 |
MIHcAgEBBEIBrsoKp0oqcv6/JovJJDoDVSGWdirrkgCWxrprGlzB9o0X8fV675X0 |
| 85 |
NwuBenXFfeZvVcwluO7/Q9wkYoPd/t3jGImgBwYFK4EEACOhgYkDgYYABAFj36bL |
| 86 |
06h5JRGUNB1X/Hwuw64uKW2GGJLVPPhoYMcg/ALWaW+d/t+DmV5xikwKssuFq4Bz |
| 87 |
VQldyCXTXGgu7OC0AQCC/Y/+ODK3NFKlRi+AsG3VQDSV4tgHLqZBBus0S6pPcg1q |
| 88 |
kohxS/xfFg/TEwRSSws+roJr4JFKpO2t3/be5OdqmQ== |
| 89 |
-----END EC TESTING KEY----- |
| 90 |
`) |
| 91 |
|
| 92 |
var keyPairTests = []struct { |
| 93 |
algo string |
| 94 |
cert string |
| 95 |
key string |
| 96 |
}{ |
| 97 |
{"ECDSA", ecdsaCertPEM, ecdsaKeyPEM}, |
| 98 |
{"RSA", rsaCertPEM, rsaKeyPEM}, |
| 99 |
{"RSA-untyped", rsaCertPEM, keyPEM}, // golang.org/issue/4477 |
| 100 |
} |
| 101 |
|
| 102 |
func TestX509KeyPair(t *testing.T) { |
| 103 |
t.Parallel() |
| 104 |
var pem []byte |
| 105 |
for _, test := range keyPairTests { |
| 106 |
pem = []byte(test.cert + test.key) |
| 107 |
if _, err := X509KeyPair(pem, pem); err != nil { |
| 108 |
t.Errorf("Failed to load %s cert followed by %s key: %s", test.algo, test.algo, err) |
| 109 |
} |
| 110 |
pem = []byte(test.key + test.cert) |
| 111 |
if _, err := X509KeyPair(pem, pem); err != nil { |
| 112 |
t.Errorf("Failed to load %s key followed by %s cert: %s", test.algo, test.algo, err) |
| 113 |
} |
| 114 |
} |
| 115 |
} |
| 116 |
|
| 117 |
func TestX509KeyPairErrors(t *testing.T) { |
| 118 |
_, err := X509KeyPair([]byte(rsaKeyPEM), []byte(rsaCertPEM)) |
| 119 |
if err == nil { |
| 120 |
t.Fatalf("X509KeyPair didn't return an error when arguments were switched") |
| 121 |
} |
| 122 |
if subStr := "been switched"; !strings.Contains(err.Error(), subStr) { |
| 123 |
t.Fatalf("Expected %q in the error when switching arguments to X509KeyPair, but the error was %q", subStr, err) |
| 124 |
} |
| 125 |
|
| 126 |
_, err = X509KeyPair([]byte(rsaCertPEM), []byte(rsaCertPEM)) |
| 127 |
if err == nil { |
| 128 |
t.Fatalf("X509KeyPair didn't return an error when both arguments were certificates") |
| 129 |
} |
| 130 |
if subStr := "certificate"; !strings.Contains(err.Error(), subStr) { |
| 131 |
t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were certificates, but the error was %q", subStr, err) |
| 132 |
} |
| 133 |
|
| 134 |
const nonsensePEM = ` |
| 135 |
-----BEGIN NONSENSE----- |
| 136 |
Zm9vZm9vZm9v |
| 137 |
-----END NONSENSE----- |
| 138 |
` |
| 139 |
|
| 140 |
_, err = X509KeyPair([]byte(nonsensePEM), []byte(nonsensePEM)) |
| 141 |
if err == nil { |
| 142 |
t.Fatalf("X509KeyPair didn't return an error when both arguments were nonsense") |
| 143 |
} |
| 144 |
if subStr := "NONSENSE"; !strings.Contains(err.Error(), subStr) { |
| 145 |
t.Fatalf("Expected %q in the error when both arguments to X509KeyPair were nonsense, but the error was %q", subStr, err) |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
func TestX509MixedKeyPair(t *testing.T) { |
| 150 |
if _, err := X509KeyPair([]byte(rsaCertPEM), []byte(ecdsaKeyPEM)); err == nil { |
| 151 |
t.Error("Load of RSA certificate succeeded with ECDSA private key") |
| 152 |
} |
| 153 |
if _, err := X509KeyPair([]byte(ecdsaCertPEM), []byte(rsaKeyPEM)); err == nil { |
| 154 |
t.Error("Load of ECDSA certificate succeeded with RSA private key") |
| 155 |
} |
| 156 |
} |
| 157 |
|
| 158 |
func newLocalListener(t testing.TB) net.Listener { |
| 159 |
ln, err := net.Listen("tcp", "127.0.0.1:0") |
| 160 |
if err != nil { |
| 161 |
ln, err = net.Listen("tcp6", "[::1]:0") |
| 162 |
} |
| 163 |
if err != nil { |
| 164 |
t.Fatal(err) |
| 165 |
} |
| 166 |
return ln |
| 167 |
} |
| 168 |
|
| 169 |
func TestDialTimeout(t *testing.T) { |
| 170 |
if testing.Short() { |
| 171 |
t.Skip("skipping in short mode") |
| 172 |
} |
| 173 |
listener := newLocalListener(t) |
| 174 |
|
| 175 |
addr := listener.Addr().String() |
| 176 |
defer listener.Close() |
| 177 |
|
| 178 |
complete := make(chan bool) |
| 179 |
defer close(complete) |
| 180 |
|
| 181 |
go func() { |
| 182 |
conn, err := listener.Accept() |
| 183 |
if err != nil { |
| 184 |
t.Error(err) |
| 185 |
return |
| 186 |
} |
| 187 |
<-complete |
| 188 |
conn.Close() |
| 189 |
}() |
| 190 |
|
| 191 |
dialer := &net.Dialer{ |
| 192 |
Timeout: 10 * time.Millisecond, |
| 193 |
} |
| 194 |
|
| 195 |
var err error |
| 196 |
if _, err = DialWithDialer(dialer, "tcp", addr, nil); err == nil { |
| 197 |
t.Fatal("DialWithTimeout completed successfully") |
| 198 |
} |
| 199 |
|
| 200 |
if !isTimeoutError(err) { |
| 201 |
t.Errorf("resulting error not a timeout: %v\nType %T: %#v", err, err, err) |
| 202 |
} |
| 203 |
} |
| 204 |
|
| 205 |
func TestDeadlineOnWrite(t *testing.T) { |
| 206 |
if testing.Short() { |
| 207 |
t.Skip("skipping in short mode") |
| 208 |
} |
| 209 |
|
| 210 |
ln := newLocalListener(t) |
| 211 |
defer ln.Close() |
| 212 |
|
| 213 |
srvCh := make(chan *Conn, 1) |
| 214 |
|
| 215 |
go func() { |
| 216 |
sconn, err := ln.Accept() |
| 217 |
if err != nil { |
| 218 |
srvCh <- nil |
| 219 |
return |
| 220 |
} |
| 221 |
srv := Server(sconn, testConfig.Clone()) |
| 222 |
if err := srv.Handshake(); err != nil { |
| 223 |
srvCh <- nil |
| 224 |
return |
| 225 |
} |
| 226 |
srvCh <- srv |
| 227 |
}() |
| 228 |
|
| 229 |
clientConfig := testConfig.Clone() |
| 230 |
clientConfig.MaxVersion = VersionTLS12 |
| 231 |
conn, err := Dial("tcp", ln.Addr().String(), clientConfig) |
| 232 |
if err != nil { |
| 233 |
t.Fatal(err) |
| 234 |
} |
| 235 |
defer conn.Close() |
| 236 |
|
| 237 |
srv := <-srvCh |
| 238 |
if srv == nil { |
| 239 |
t.Error(err) |
| 240 |
} |
| 241 |
|
| 242 |
// Make sure the client/server is setup correctly and is able to do a typical Write/Read |
| 243 |
buf := make([]byte, 6) |
| 244 |
if _, err := srv.Write([]byte("foobar")); err != nil { |
| 245 |
t.Errorf("Write err: %v", err) |
| 246 |
} |
| 247 |
if n, err := conn.Read(buf); n != 6 || err != nil || string(buf) != "foobar" { |
| 248 |
t.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf) |
| 249 |
} |
| 250 |
|
| 251 |
// Set a deadline which should cause Write to timeout |
| 252 |
if err = srv.SetDeadline(time.Now()); err != nil { |
| 253 |
t.Fatalf("SetDeadline(time.Now()) err: %v", err) |
| 254 |
} |
| 255 |
if _, err = srv.Write([]byte("should fail")); err == nil { |
| 256 |
t.Fatal("Write should have timed out") |
| 257 |
} |
| 258 |
|
| 259 |
// Clear deadline and make sure it still times out |
| 260 |
if err = srv.SetDeadline(time.Time{}); err != nil { |
| 261 |
t.Fatalf("SetDeadline(time.Time{}) err: %v", err) |
| 262 |
} |
| 263 |
if _, err = srv.Write([]byte("This connection is permanently broken")); err == nil { |
| 264 |
t.Fatal("Write which previously failed should still time out") |
| 265 |
} |
| 266 |
|
| 267 |
// Verify the error |
| 268 |
if ne := err.(net.Error); ne.Temporary() != false { |
| 269 |
t.Error("Write timed out but incorrectly classified the error as Temporary") |
| 270 |
} |
| 271 |
if !isTimeoutError(err) { |
| 272 |
t.Error("Write timed out but did not classify the error as a Timeout") |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
type readerFunc func([]byte) (int, error) |
| 277 |
|
| 278 |
func (f readerFunc) Read(b []byte) (int, error) { return f(b) } |
| 279 |
|
| 280 |
// TestDialer tests that tls.Dialer.DialContext can abort in the middle of a handshake. |
| 281 |
// (The other cases are all handled by the existing dial tests in this package, which |
| 282 |
// all also flow through the same code shared code paths) |
| 283 |
func TestDialer(t *testing.T) { |
| 284 |
ln := newLocalListener(t) |
| 285 |
defer ln.Close() |
| 286 |
|
| 287 |
unblockServer := make(chan struct{}) // close-only |
| 288 |
defer close(unblockServer) |
| 289 |
go func() { |
| 290 |
conn, err := ln.Accept() |
| 291 |
if err != nil { |
| 292 |
return |
| 293 |
} |
| 294 |
defer conn.Close() |
| 295 |
<-unblockServer |
| 296 |
}() |
| 297 |
|
| 298 |
ctx, cancel := context.WithCancel(context.Background()) |
| 299 |
d := Dialer{Config: &Config{ |
| 300 |
Rand: readerFunc(func(b []byte) (n int, err error) { |
| 301 |
// By the time crypto/tls wants randomness, that means it has a TCP |
| 302 |
// connection, so we're past the Dialer's dial and now blocked |
| 303 |
// in a handshake. Cancel our context and see if we get unstuck. |
| 304 |
// (Our TCP listener above never reads or writes, so the Handshake |
| 305 |
// would otherwise be stuck forever) |
| 306 |
cancel() |
| 307 |
return len(b), nil |
| 308 |
}), |
| 309 |
ServerName: "foo", |
| 310 |
}} |
| 311 |
_, err := d.DialContext(ctx, "tcp", ln.Addr().String()) |
| 312 |
if err != context.Canceled { |
| 313 |
t.Errorf("err = %v; want context.Canceled", err) |
| 314 |
} |
| 315 |
} |
| 316 |
|
| 317 |
func isTimeoutError(err error) bool { |
| 318 |
if ne, ok := err.(net.Error); ok { |
| 319 |
return ne.Timeout() |
| 320 |
} |
| 321 |
return false |
| 322 |
} |
| 323 |
|
| 324 |
// tests that Conn.Read returns (non-zero, io.EOF) instead of |
| 325 |
// (non-zero, nil) when a Close (alertCloseNotify) is sitting right |
| 326 |
// behind the application data in the buffer. |
| 327 |
func TestConnReadNonzeroAndEOF(t *testing.T) { |
| 328 |
// This test is racy: it assumes that after a write to a |
| 329 |
// localhost TCP connection, the peer TCP connection can |
| 330 |
// immediately read it. Because it's racy, we skip this test |
| 331 |
// in short mode, and then retry it several times with an |
| 332 |
// increasing sleep in between our final write (via srv.Close |
| 333 |
// below) and the following read. |
| 334 |
if testing.Short() { |
| 335 |
t.Skip("skipping in short mode") |
| 336 |
} |
| 337 |
var err error |
| 338 |
for delay := time.Millisecond; delay <= 64*time.Millisecond; delay *= 2 { |
| 339 |
if err = testConnReadNonzeroAndEOF(t, delay); err == nil { |
| 340 |
return |
| 341 |
} |
| 342 |
} |
| 343 |
t.Error(err) |
| 344 |
} |
| 345 |
|
| 346 |
func testConnReadNonzeroAndEOF(t *testing.T, delay time.Duration) error { |
| 347 |
ln := newLocalListener(t) |
| 348 |
defer ln.Close() |
| 349 |
|
| 350 |
srvCh := make(chan *Conn, 1) |
| 351 |
var serr error |
| 352 |
go func() { |
| 353 |
sconn, err := ln.Accept() |
| 354 |
if err != nil { |
| 355 |
serr = err |
| 356 |
srvCh <- nil |
| 357 |
return |
| 358 |
} |
| 359 |
serverConfig := testConfig.Clone() |
| 360 |
srv := Server(sconn, serverConfig) |
| 361 |
if err := srv.Handshake(); err != nil { |
| 362 |
serr = fmt.Errorf("handshake: %v", err) |
| 363 |
srvCh <- nil |
| 364 |
return |
| 365 |
} |
| 366 |
srvCh <- srv |
| 367 |
}() |
| 368 |
|
| 369 |
clientConfig := testConfig.Clone() |
| 370 |
// In TLS 1.3, alerts are encrypted and disguised as application data, so |
| 371 |
// the opportunistic peek won't work. |
| 372 |
clientConfig.MaxVersion = VersionTLS12 |
| 373 |
conn, err := Dial("tcp", ln.Addr().String(), clientConfig) |
| 374 |
if err != nil { |
| 375 |
t.Fatal(err) |
| 376 |
} |
| 377 |
defer conn.Close() |
| 378 |
|
| 379 |
srv := <-srvCh |
| 380 |
if srv == nil { |
| 381 |
return serr |
| 382 |
} |
| 383 |
|
| 384 |
buf := make([]byte, 6) |
| 385 |
|
| 386 |
srv.Write([]byte("foobar")) |
| 387 |
n, err := conn.Read(buf) |
| 388 |
if n != 6 || err != nil || string(buf) != "foobar" { |
| 389 |
return fmt.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf) |
| 390 |
} |
| 391 |
|
| 392 |
srv.Write([]byte("abcdef")) |
| 393 |
srv.Close() |
| 394 |
time.Sleep(delay) |
| 395 |
n, err = conn.Read(buf) |
| 396 |
if n != 6 || string(buf) != "abcdef" { |
| 397 |
return fmt.Errorf("Read = %d, buf= %q; want 6, abcdef", n, buf) |
| 398 |
} |
| 399 |
if err != io.EOF { |
| 400 |
return fmt.Errorf("Second Read error = %v; want io.EOF", err) |
| 401 |
} |
| 402 |
return nil |
| 403 |
} |
| 404 |
|
| 405 |
func TestTLSUniqueMatches(t *testing.T) { |
| 406 |
ln := newLocalListener(t) |
| 407 |
defer ln.Close() |
| 408 |
|
| 409 |
serverTLSUniques := make(chan []byte) |
| 410 |
parentDone := make(chan struct{}) |
| 411 |
childDone := make(chan struct{}) |
| 412 |
defer close(parentDone) |
| 413 |
go func() { |
| 414 |
defer close(childDone) |
| 415 |
for i := 0; i < 2; i++ { |
| 416 |
sconn, err := ln.Accept() |
| 417 |
if err != nil { |
| 418 |
t.Error(err) |
| 419 |
return |
| 420 |
} |
| 421 |
serverConfig := testConfig.Clone() |
| 422 |
serverConfig.MaxVersion = VersionTLS12 // TLSUnique is not defined in TLS 1.3 |
| 423 |
srv := Server(sconn, serverConfig) |
| 424 |
if err := srv.Handshake(); err != nil { |
| 425 |
t.Error(err) |
| 426 |
return |
| 427 |
} |
| 428 |
select { |
| 429 |
case <-parentDone: |
| 430 |
return |
| 431 |
case serverTLSUniques <- srv.ConnectionState().TLSUnique: |
| 432 |
} |
| 433 |
} |
| 434 |
}() |
| 435 |
|
| 436 |
clientConfig := testConfig.Clone() |
| 437 |
clientConfig.ClientSessionCache = NewLRUClientSessionCache(1) |
| 438 |
conn, err := Dial("tcp", ln.Addr().String(), clientConfig) |
| 439 |
if err != nil { |
| 440 |
t.Fatal(err) |
| 441 |
} |
| 442 |
|
| 443 |
var serverTLSUniquesValue []byte |
| 444 |
select { |
| 445 |
case <-childDone: |
| 446 |
return |
| 447 |
case serverTLSUniquesValue = <-serverTLSUniques: |
| 448 |
} |
| 449 |
|
| 450 |
if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) { |
| 451 |
t.Error("client and server channel bindings differ") |
| 452 |
} |
| 453 |
conn.Close() |
| 454 |
|
| 455 |
conn, err = Dial("tcp", ln.Addr().String(), clientConfig) |
| 456 |
if err != nil { |
| 457 |
t.Fatal(err) |
| 458 |
} |
| 459 |
defer conn.Close() |
| 460 |
if !conn.ConnectionState().DidResume { |
| 461 |
t.Error("second session did not use resumption") |
| 462 |
} |
| 463 |
|
| 464 |
select { |
| 465 |
case <-childDone: |
| 466 |
return |
| 467 |
case serverTLSUniquesValue = <-serverTLSUniques: |
| 468 |
} |
| 469 |
|
| 470 |
if !bytes.Equal(conn.ConnectionState().TLSUnique, serverTLSUniquesValue) { |
| 471 |
t.Error("client and server channel bindings differ when session resumption is used") |
| 472 |
} |
| 473 |
} |
| 474 |
|
| 475 |
func TestVerifyHostname(t *testing.T) { |
| 476 |
testenv.MustHaveExternalNetwork(t) |
| 477 |
|
| 478 |
c, err := Dial("tcp", "www.google.com:https", nil) |
| 479 |
if err != nil { |
| 480 |
t.Fatal(err) |
| 481 |
} |
| 482 |
if err := c.VerifyHostname("www.google.com"); err != nil { |
| 483 |
t.Fatalf("verify www.google.com: %v", err) |
| 484 |
} |
| 485 |
if err := c.VerifyHostname("www.yahoo.com"); err == nil { |
| 486 |
t.Fatalf("verify www.yahoo.com succeeded") |
| 487 |
} |
| 488 |
|
| 489 |
c, err = Dial("tcp", "www.google.com:https", &Config{InsecureSkipVerify: true}) |
| 490 |
if err != nil { |
| 491 |
t.Fatal(err) |
| 492 |
} |
| 493 |
if err := c.VerifyHostname("www.google.com"); err == nil { |
| 494 |
t.Fatalf("verify www.google.com succeeded with InsecureSkipVerify=true") |
| 495 |
} |
| 496 |
} |
| 497 |
|
| 498 |
func TestConnCloseBreakingWrite(t *testing.T) { |
| 499 |
ln := newLocalListener(t) |
| 500 |
defer ln.Close() |
| 501 |
|
| 502 |
srvCh := make(chan *Conn, 1) |
| 503 |
var serr error |
| 504 |
var sconn net.Conn |
| 505 |
go func() { |
| 506 |
var err error |
| 507 |
sconn, err = ln.Accept() |
| 508 |
if err != nil { |
| 509 |
serr = err |
| 510 |
srvCh <- nil |
| 511 |
return |
| 512 |
} |
| 513 |
serverConfig := testConfig.Clone() |
| 514 |
srv := Server(sconn, serverConfig) |
| 515 |
if err := srv.Handshake(); err != nil { |
| 516 |
serr = fmt.Errorf("handshake: %v", err) |
| 517 |
srvCh <- nil |
| 518 |
return |
| 519 |
} |
| 520 |
srvCh <- srv |
| 521 |
}() |
| 522 |
|
| 523 |
cconn, err := net.Dial("tcp", ln.Addr().String()) |
| 524 |
if err != nil { |
| 525 |
t.Fatal(err) |
| 526 |
} |
| 527 |
defer cconn.Close() |
| 528 |
|
| 529 |
conn := &changeImplConn{ |
| 530 |
Conn: cconn, |
| 531 |
} |
| 532 |
|
| 533 |
clientConfig := testConfig.Clone() |
| 534 |
tconn := Client(conn, clientConfig) |
| 535 |
if err := tconn.Handshake(); err != nil { |
| 536 |
t.Fatal(err) |
| 537 |
} |
| 538 |
|
| 539 |
srv := <-srvCh |
| 540 |
if srv == nil { |
| 541 |
t.Fatal(serr) |
| 542 |
} |
| 543 |
defer sconn.Close() |
| 544 |
|
| 545 |
connClosed := make(chan struct{}) |
| 546 |
conn.closeFunc = func() error { |
| 547 |
close(connClosed) |
| 548 |
return nil |
| 549 |
} |
| 550 |
|
| 551 |
inWrite := make(chan bool, 1) |
| 552 |
var errConnClosed = errors.New("conn closed for test") |
| 553 |
conn.writeFunc = func(p []byte) (n int, err error) { |
| 554 |
inWrite <- true |
| 555 |
<-connClosed |
| 556 |
return 0, errConnClosed |
| 557 |
} |
| 558 |
|
| 559 |
closeReturned := make(chan bool, 1) |
| 560 |
go func() { |
| 561 |
<-inWrite |
| 562 |
tconn.Close() // test that this doesn't block forever. |
| 563 |
closeReturned <- true |
| 564 |
}() |
| 565 |
|
| 566 |
_, err = tconn.Write([]byte("foo")) |
| 567 |
if err != errConnClosed { |
| 568 |
t.Errorf("Write error = %v; want errConnClosed", err) |
| 569 |
} |
| 570 |
|
| 571 |
<-closeReturned |
| 572 |
if err := tconn.Close(); err != net.ErrClosed { |
| 573 |
t.Errorf("Close error = %v; want net.ErrClosed", err) |
| 574 |
} |
| 575 |
} |
| 576 |
|
| 577 |
func TestConnCloseWrite(t *testing.T) { |
| 578 |
ln := newLocalListener(t) |
| 579 |
defer ln.Close() |
| 580 |
|
| 581 |
clientDoneChan := make(chan struct{}) |
| 582 |
|
| 583 |
serverCloseWrite := func() error { |
| 584 |
sconn, err := ln.Accept() |
| 585 |
if err != nil { |
| 586 |
return fmt.Errorf("accept: %v", err) |
| 587 |
} |
| 588 |
defer sconn.Close() |
| 589 |
|
| 590 |
serverConfig := testConfig.Clone() |
| 591 |
srv := Server(sconn, serverConfig) |
| 592 |
if err := srv.Handshake(); err != nil { |
| 593 |
return fmt.Errorf("handshake: %v", err) |
| 594 |
} |
| 595 |
defer srv.Close() |
| 596 |
|
| 597 |
data, err := io.ReadAll(srv) |
| 598 |
if err != nil { |
| 599 |
return err |
| 600 |
} |
| 601 |
if len(data) > 0 { |
| 602 |
return fmt.Errorf("Read data = %q; want nothing", data) |
| 603 |
} |
| 604 |
|
| 605 |
if err := srv.CloseWrite(); err != nil { |
| 606 |
return fmt.Errorf("server CloseWrite: %v", err) |
| 607 |
} |
| 608 |
|
| 609 |
// Wait for clientCloseWrite to finish, so we know we |
| 610 |
// tested the CloseWrite before we defer the |
| 611 |
// sconn.Close above, which would also cause the |
| 612 |
// client to unblock like CloseWrite. |
| 613 |
<-clientDoneChan |
| 614 |
return nil |
| 615 |
} |
| 616 |
|
| 617 |
clientCloseWrite := func() error { |
| 618 |
defer close(clientDoneChan) |
| 619 |
|
| 620 |
clientConfig := testConfig.Clone() |
| 621 |
conn, err := Dial("tcp", ln.Addr().String(), clientConfig) |
| 622 |
if err != nil { |
| 623 |
return err |
| 624 |
} |
| 625 |
if err := conn.Handshake(); err != nil { |
| 626 |
return err |
| 627 |
} |
| 628 |
defer conn.Close() |
| 629 |
|
| 630 |
if err := conn.CloseWrite(); err != nil { |
| 631 |
return fmt.Errorf("client CloseWrite: %v", err) |
| 632 |
} |
| 633 |
|
| 634 |
if _, err := conn.Write([]byte{0}); err != errShutdown { |
| 635 |
return fmt.Errorf("CloseWrite error = %v; want errShutdown", err) |
| 636 |
} |
| 637 |
|
| 638 |
data, err := io.ReadAll(conn) |
| 639 |
if err != nil { |
| 640 |
return err |
| 641 |
} |
| 642 |
if len(data) > 0 { |
| 643 |
return fmt.Errorf("Read data = %q; want nothing", data) |
| 644 |
} |
| 645 |
return nil |
| 646 |
} |
| 647 |
|
| 648 |
errChan := make(chan error, 2) |
| 649 |
|
| 650 |
go func() { errChan <- serverCloseWrite() }() |
| 651 |
go func() { errChan <- clientCloseWrite() }() |
| 652 |
|
| 653 |
for i := 0; i < 2; i++ { |
| 654 |
select { |
| 655 |
case err := <-errChan: |
| 656 |
if err != nil { |
| 657 |
t.Fatal(err) |
| 658 |
} |
| 659 |
case <-time.After(10 * time.Second): |
| 660 |
t.Fatal("deadlock") |
| 661 |
} |
| 662 |
} |
| 663 |
|
| 664 |
// Also test CloseWrite being called before the handshake is |
| 665 |
// finished: |
| 666 |
{ |
| 667 |
ln2 := newLocalListener(t) |
| 668 |
defer ln2.Close() |
| 669 |
|
| 670 |
netConn, err := net.Dial("tcp", ln2.Addr().String()) |
| 671 |
if err != nil { |
| 672 |
t.Fatal(err) |
| 673 |
} |
| 674 |
defer netConn.Close() |
| 675 |
conn := Client(netConn, testConfig.Clone()) |
| 676 |
|
| 677 |
if err := conn.CloseWrite(); err != errEarlyCloseWrite { |
| 678 |
t.Errorf("CloseWrite error = %v; want errEarlyCloseWrite", err) |
| 679 |
} |
| 680 |
} |
| 681 |
} |
| 682 |
|
| 683 |
func TestWarningAlertFlood(t *testing.T) { |
| 684 |
ln := newLocalListener(t) |
| 685 |
defer ln.Close() |
| 686 |
|
| 687 |
server := func() error { |
| 688 |
sconn, err := ln.Accept() |
| 689 |
if err != nil { |
| 690 |
return fmt.Errorf("accept: %v", err) |
| 691 |
} |
| 692 |
defer sconn.Close() |
| 693 |
|
| 694 |
serverConfig := testConfig.Clone() |
| 695 |
srv := Server(sconn, serverConfig) |
| 696 |
if err := srv.Handshake(); err != nil { |
| 697 |
return fmt.Errorf("handshake: %v", err) |
| 698 |
} |
| 699 |
defer srv.Close() |
| 700 |
|
| 701 |
_, err = io.ReadAll(srv) |
| 702 |
if err == nil { |
| 703 |
return errors.New("unexpected lack of error from server") |
| 704 |
} |
| 705 |
const expected = "too many ignored" |
| 706 |
if str := err.Error(); !strings.Contains(str, expected) { |
| 707 |
return fmt.Errorf("expected error containing %q, but saw: %s", expected, str) |
| 708 |
} |
| 709 |
|
| 710 |
return nil |
| 711 |
} |
| 712 |
|
| 713 |
errChan := make(chan error, 1) |
| 714 |
go func() { errChan <- server() }() |
| 715 |
|
| 716 |
clientConfig := testConfig.Clone() |
| 717 |
clientConfig.MaxVersion = VersionTLS12 // there are no warning alerts in TLS 1.3 |
| 718 |
conn, err := Dial("tcp", ln.Addr().String(), clientConfig) |
| 719 |
if err != nil { |
| 720 |
t.Fatal(err) |
| 721 |
} |
| 722 |
defer conn.Close() |
| 723 |
if err := conn.Handshake(); err != nil { |
| 724 |
t.Fatal(err) |
| 725 |
} |
| 726 |
|
| 727 |
for i := 0; i < maxUselessRecords+1; i++ { |
| 728 |
conn.sendAlert(alertNoRenegotiation) |
| 729 |
} |
| 730 |
|
| 731 |
if err := <-errChan; err != nil { |
| 732 |
t.Fatal(err) |
| 733 |
} |
| 734 |
} |
| 735 |
|
| 736 |
func TestCloneFuncFields(t *testing.T) { |
| 737 |
const expectedCount = 6 |
| 738 |
called := 0 |
| 739 |
|
| 740 |
c1 := Config{ |
| 741 |
Time: func() time.Time { |
| 742 |
called |= 1 << 0 |
| 743 |
return time.Time{} |
| 744 |
}, |
| 745 |
GetCertificate: func(*ClientHelloInfo) (*Certificate, error) { |
| 746 |
called |= 1 << 1 |
| 747 |
return nil, nil |
| 748 |
}, |
| 749 |
GetClientCertificate: func(*CertificateRequestInfo) (*Certificate, error) { |
| 750 |
called |= 1 << 2 |
| 751 |
return nil, nil |
| 752 |
}, |
| 753 |
GetConfigForClient: func(*ClientHelloInfo) (*Config, error) { |
| 754 |
called |= 1 << 3 |
| 755 |
return nil, nil |
| 756 |
}, |
| 757 |
VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { |
| 758 |
called |= 1 << 4 |
| 759 |
return nil |
| 760 |
}, |
| 761 |
VerifyConnection: func(ConnectionState) error { |
| 762 |
called |= 1 << 5 |
| 763 |
return nil |
| 764 |
}, |
| 765 |
} |
| 766 |
|
| 767 |
c2 := c1.Clone() |
| 768 |
|
| 769 |
c2.Time() |
| 770 |
c2.GetCertificate(nil) |
| 771 |
c2.GetClientCertificate(nil) |
| 772 |
c2.GetConfigForClient(nil) |
| 773 |
c2.VerifyPeerCertificate(nil, nil) |
| 774 |
c2.VerifyConnection(ConnectionState{}) |
| 775 |
|
| 776 |
if called != (1<<expectedCount)-1 { |
| 777 |
t.Fatalf("expected %d calls but saw calls %b", expectedCount, called) |
| 778 |
} |
| 779 |
} |
| 780 |
|
| 781 |
func TestCloneNonFuncFields(t *testing.T) { |
| 782 |
var c1 Config |
| 783 |
v := reflect.ValueOf(&c1).Elem() |
| 784 |
|
| 785 |
typ := v.Type() |
| 786 |
for i := 0; i < typ.NumField(); i++ { |
| 787 |
f := v.Field(i) |
| 788 |
// testing/quick can't handle functions or interfaces and so |
| 789 |
// isn't used here. |
| 790 |
switch fn := typ.Field(i).Name; fn { |
| 791 |
case "Rand": |
| 792 |
f.Set(reflect.ValueOf(io.Reader(os.Stdin))) |
| 793 |
case "Time", "GetCertificate", "GetConfigForClient", "VerifyPeerCertificate", "VerifyConnection", "GetClientCertificate": |
| 794 |
// DeepEqual can't compare functions. If you add a |
| 795 |
// function field to this list, you must also change |
| 796 |
// TestCloneFuncFields to ensure that the func field is |
| 797 |
// cloned. |
| 798 |
case "Certificates": |
| 799 |
f.Set(reflect.ValueOf([]Certificate{ |
| 800 |
{Certificate: [][]byte{{'b'}}}, |
| 801 |
})) |
| 802 |
case "NameToCertificate": |
| 803 |
f.Set(reflect.ValueOf(map[string]*Certificate{"a": nil})) |
| 804 |
case "RootCAs", "ClientCAs": |
| 805 |
f.Set(reflect.ValueOf(x509.NewCertPool())) |
| 806 |
case "ClientSessionCache": |
| 807 |
f.Set(reflect.ValueOf(NewLRUClientSessionCache(10))) |
| 808 |
case "KeyLogWriter": |
| 809 |
f.Set(reflect.ValueOf(io.Writer(os.Stdout))) |
| 810 |
case "NextProtos": |
| 811 |
f.Set(reflect.ValueOf([]string{"a", "b"})) |
| 812 |
case "ServerName": |
| 813 |
f.Set(reflect.ValueOf("b")) |
| 814 |
case "ClientAuth": |
| 815 |
f.Set(reflect.ValueOf(VerifyClientCertIfGiven)) |
| 816 |
case "InsecureSkipVerify", "SessionTicketsDisabled", "DynamicRecordSizingDisabled", "PreferServerCipherSuites": |
| 817 |
f.Set(reflect.ValueOf(true)) |
| 818 |
case "MinVersion", "MaxVersion": |
| 819 |
f.Set(reflect.ValueOf(uint16(VersionTLS12))) |
| 820 |
case "SessionTicketKey": |
| 821 |
f.Set(reflect.ValueOf([32]byte{})) |
| 822 |
case "CipherSuites": |
| 823 |
f.Set(reflect.ValueOf([]uint16{1, 2})) |
| 824 |
case "CurvePreferences": |
| 825 |
f.Set(reflect.ValueOf([]CurveID{CurveP256})) |
| 826 |
case "Renegotiation": |
| 827 |
f.Set(reflect.ValueOf(RenegotiateOnceAsClient)) |
| 828 |
case "mutex", "autoSessionTicketKeys", "sessionTicketKeys": |
| 829 |
continue // these are unexported fields that are handled separately |
| 830 |
default: |
| 831 |
t.Errorf("all fields must be accounted for, but saw unknown field %q", fn) |
| 832 |
} |
| 833 |
} |
| 834 |
// Set the unexported fields related to session ticket keys, which are copied with Clone(). |
| 835 |
c1.autoSessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)} |
| 836 |
c1.sessionTicketKeys = []ticketKey{c1.ticketKeyFromBytes(c1.SessionTicketKey)} |
| 837 |
|
| 838 |
c2 := c1.Clone() |
| 839 |
if !reflect.DeepEqual(&c1, c2) { |
| 840 |
t.Errorf("clone failed to copy a field") |
| 841 |
} |
| 842 |
} |
| 843 |
|
| 844 |
func TestCloneNilConfig(t *testing.T) { |
| 845 |
var config *Config |
| 846 |
if cc := config.Clone(); cc != nil { |
| 847 |
t.Fatalf("Clone with nil should return nil, got: %+v", cc) |
| 848 |
} |
| 849 |
} |
| 850 |
|
| 851 |
// changeImplConn is a net.Conn which can change its Write and Close |
| 852 |
// methods. |
| 853 |
type changeImplConn struct { |
| 854 |
net.Conn |
| 855 |
writeFunc func([]byte) (int, error) |
| 856 |
closeFunc func() error |
| 857 |
} |
| 858 |
|
| 859 |
func (w *changeImplConn) Write(p []byte) (n int, err error) { |
| 860 |
if w.writeFunc != nil { |
| 861 |
return w.writeFunc(p) |
| 862 |
} |
| 863 |
return w.Conn.Write(p) |
| 864 |
} |
| 865 |
|
| 866 |
func (w *changeImplConn) Close() error { |
| 867 |
if w.closeFunc != nil { |
| 868 |
return w.closeFunc() |
| 869 |
} |
| 870 |
return w.Conn.Close() |
| 871 |
} |
| 872 |
|
| 873 |
func throughput(b *testing.B, version uint16, totalBytes int64, dynamicRecordSizingDisabled bool) { |
| 874 |
ln := newLocalListener(b) |
| 875 |
defer ln.Close() |
| 876 |
|
| 877 |
N := b.N |
| 878 |
|
| 879 |
// Less than 64KB because Windows appears to use a TCP rwin < 64KB. |
| 880 |
// See Issue #15899. |
| 881 |
const bufsize = 32 << 10 |
| 882 |
|
| 883 |
go func() { |
| 884 |
buf := make([]byte, bufsize) |
| 885 |
for i := 0; i < N; i++ { |
| 886 |
sconn, err := ln.Accept() |
| 887 |
if err != nil { |
| 888 |
// panic rather than synchronize to avoid benchmark overhead |
| 889 |
// (cannot call b.Fatal in goroutine) |
| 890 |
panic(fmt.Errorf("accept: %v", err)) |
| 891 |
} |
| 892 |
serverConfig := testConfig.Clone() |
| 893 |
serverConfig.CipherSuites = nil // the defaults may prefer faster ciphers |
| 894 |
serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled |
| 895 |
srv := Server(sconn, serverConfig) |
| 896 |
if err := srv.Handshake(); err != nil { |
| 897 |
panic(fmt.Errorf("handshake: %v", err)) |
| 898 |
} |
| 899 |
if _, err := io.CopyBuffer(srv, srv, buf); err != nil { |
| 900 |
panic(fmt.Errorf("copy buffer: %v", err)) |
| 901 |
} |
| 902 |
} |
| 903 |
}() |
| 904 |
|
| 905 |
b.SetBytes(totalBytes) |
| 906 |
clientConfig := testConfig.Clone() |
| 907 |
clientConfig.CipherSuites = nil // the defaults may prefer faster ciphers |
| 908 |
clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled |
| 909 |
clientConfig.MaxVersion = version |
| 910 |
|
| 911 |
buf := make([]byte, bufsize) |
| 912 |
chunks := int(math.Ceil(float64(totalBytes) / float64(len(buf)))) |
| 913 |
for i := 0; i < N; i++ { |
| 914 |
conn, err := Dial("tcp", ln.Addr().String(), clientConfig) |
| 915 |
if err != nil { |
| 916 |
b.Fatal(err) |
| 917 |
} |
| 918 |
for j := 0; j < chunks; j++ { |
| 919 |
_, err := conn.Write(buf) |
| 920 |
if err != nil { |
| 921 |
b.Fatal(err) |
| 922 |
} |
| 923 |
_, err = io.ReadFull(conn, buf) |
| 924 |
if err != nil { |
| 925 |
b.Fatal(err) |
| 926 |
} |
| 927 |
} |
| 928 |
conn.Close() |
| 929 |
} |
| 930 |
} |
| 931 |
|
| 932 |
func BenchmarkThroughput(b *testing.B) { |
| 933 |
for _, mode := range []string{"Max", "Dynamic"} { |
| 934 |
for size := 1; size <= 64; size <<= 1 { |
| 935 |
name := fmt.Sprintf("%sPacket/%dMB", mode, size) |
| 936 |
b.Run(name, func(b *testing.B) { |
| 937 |
b.Run("TLSv12", func(b *testing.B) { |
| 938 |
throughput(b, VersionTLS12, int64(size<<20), mode == "Max") |
| 939 |
}) |
| 940 |
b.Run("TLSv13", func(b *testing.B) { |
| 941 |
throughput(b, VersionTLS13, int64(size<<20), mode == "Max") |
| 942 |
}) |
| 943 |
}) |
| 944 |
} |
| 945 |
} |
| 946 |
} |
| 947 |
|
| 948 |
type slowConn struct { |
| 949 |
net.Conn |
| 950 |
bps int |
| 951 |
} |
| 952 |
|
| 953 |
func (c *slowConn) Write(p []byte) (int, error) { |
| 954 |
if c.bps == 0 { |
| 955 |
panic("too slow") |
| 956 |
} |
| 957 |
t0 := time.Now() |
| 958 |
wrote := 0 |
| 959 |
for wrote < len(p) { |
| 960 |
time.Sleep(100 * time.Microsecond) |
| 961 |
allowed := int(time.Since(t0).Seconds()*float64(c.bps)) / 8 |
| 962 |
if allowed > len(p) { |
| 963 |
allowed = len(p) |
| 964 |
} |
| 965 |
if wrote < allowed { |
| 966 |
n, err := c.Conn.Write(p[wrote:allowed]) |
| 967 |
wrote += n |
| 968 |
if err != nil { |
| 969 |
return wrote, err |
| 970 |
} |
| 971 |
} |
| 972 |
} |
| 973 |
return len(p), nil |
| 974 |
} |
| 975 |
|
| 976 |
func latency(b *testing.B, version uint16, bps int, dynamicRecordSizingDisabled bool) { |
| 977 |
ln := newLocalListener(b) |
| 978 |
defer ln.Close() |
| 979 |
|
| 980 |
N := b.N |
| 981 |
|
| 982 |
go func() { |
| 983 |
for i := 0; i < N; i++ { |
| 984 |
sconn, err := ln.Accept() |
| 985 |
if err != nil { |
| 986 |
// panic rather than synchronize to avoid benchmark overhead |
| 987 |
// (cannot call b.Fatal in goroutine) |
| 988 |
panic(fmt.Errorf("accept: %v", err)) |
| 989 |
} |
| 990 |
serverConfig := testConfig.Clone() |
| 991 |
serverConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled |
| 992 |
srv := Server(&slowConn{sconn, bps}, serverConfig) |
| 993 |
if err := srv.Handshake(); err != nil { |
| 994 |
panic(fmt.Errorf("handshake: %v", err)) |
| 995 |
} |
| 996 |
io.Copy(srv, srv) |
| 997 |
} |
| 998 |
}() |
| 999 |
|
| 1000 |
clientConfig := testConfig.Clone() |
| 1001 |
clientConfig.DynamicRecordSizingDisabled = dynamicRecordSizingDisabled |
| 1002 |
clientConfig.MaxVersion = version |
| 1003 |
|
| 1004 |
buf := make([]byte, 16384) |
| 1005 |
peek := make([]byte, 1) |
| 1006 |
|
| 1007 |
for i := 0; i < N; i++ { |
| 1008 |
conn, err := Dial("tcp", ln.Addr().String(), clientConfig) |
| 1009 |
if err != nil { |
| 1010 |
b.Fatal(err) |
| 1011 |
} |
| 1012 |
// make sure we're connected and previous connection has stopped |
| 1013 |
if _, err := conn.Write(buf[:1]); err != nil { |
| 1014 |
b.Fatal(err) |
| 1015 |
} |
| 1016 |
if _, err := io.ReadFull(conn, peek); err != nil { |
| 1017 |
b.Fatal(err) |
| 1018 |
} |
| 1019 |
if _, err := conn.Write(buf); err != nil { |
| 1020 |
b.Fatal(err) |
| 1021 |
} |
| 1022 |
if _, err = io.ReadFull(conn, peek); err != nil { |
| 1023 |
b.Fatal(err) |
| 1024 |
} |
| 1025 |
conn.Close() |
| 1026 |
} |
| 1027 |
} |
| 1028 |
|
| 1029 |
func BenchmarkLatency(b *testing.B) { |
| 1030 |
for _, mode := range []string{"Max", "Dynamic"} { |
| 1031 |
for _, kbps := range []int{200, 500, 1000, 2000, 5000} { |
| 1032 |
name := fmt.Sprintf("%sPacket/%dkbps", mode, kbps) |
| 1033 |
b.Run(name, func(b *testing.B) { |
| 1034 |
b.Run("TLSv12", func(b *testing.B) { |
| 1035 |
latency(b, VersionTLS12, kbps*1000, mode == "Max") |
| 1036 |
}) |
| 1037 |
b.Run("TLSv13", func(b *testing.B) { |
| 1038 |
latency(b, VersionTLS13, kbps*1000, mode == "Max") |
| 1039 |
}) |
| 1040 |
}) |
| 1041 |
} |
| 1042 |
} |
| 1043 |
} |
| 1044 |
|
| 1045 |
func TestConnectionStateMarshal(t *testing.T) { |
| 1046 |
cs := &ConnectionState{} |
| 1047 |
_, err := json.Marshal(cs) |
| 1048 |
if err != nil { |
| 1049 |
t.Errorf("json.Marshal failed on ConnectionState: %v", err) |
| 1050 |
} |
| 1051 |
} |
| 1052 |
|
| 1053 |
func TestConnectionState(t *testing.T) { |
| 1054 |
issuer, err := x509.ParseCertificate(testRSACertificateIssuer) |
| 1055 |
if err != nil { |
| 1056 |
panic(err) |
| 1057 |
} |
| 1058 |
rootCAs := x509.NewCertPool() |
| 1059 |
rootCAs.AddCert(issuer) |
| 1060 |
|
| 1061 |
const alpnProtocol = "golang" |
| 1062 |
const serverName = "example.golang" |
| 1063 |
var scts = [][]byte{[]byte("dummy sct 1"), []byte("dummy sct 2")} |
| 1064 |
var ocsp = []byte("dummy ocsp") |
| 1065 |
|
| 1066 |
for _, v := range []uint16{VersionTLS12, VersionTLS13} { |
| 1067 |
var name string |
| 1068 |
switch v { |
| 1069 |
case VersionTLS12: |
| 1070 |
name = "TLSv12" |
| 1071 |
case VersionTLS13: |
| 1072 |
name = "TLSv13" |
| 1073 |
} |
| 1074 |
t.Run(name, func(t *testing.T) { |
| 1075 |
config := &Config{ |
| 1076 |
Time: testTime, |
| 1077 |
Rand: zeroSource{}, |
| 1078 |
Certificates: make([]Certificate, 1), |
| 1079 |
MaxVersion: v, |
| 1080 |
RootCAs: rootCAs, |
| 1081 |
ClientCAs: rootCAs, |
| 1082 |
ClientAuth: RequireAndVerifyClientCert, |
| 1083 |
NextProtos: []string{alpnProtocol}, |
| 1084 |
ServerName: serverName, |
| 1085 |
} |
| 1086 |
config.Certificates[0].Certificate = [][]byte{testRSACertificate} |
| 1087 |
config.Certificates[0].PrivateKey = testRSAPrivateKey |
| 1088 |
config.Certificates[0].SignedCertificateTimestamps = scts |
| 1089 |
config.Certificates[0].OCSPStaple = ocsp |
| 1090 |
|
| 1091 |
ss, cs, err := testHandshake(t, config, config) |
| 1092 |
if err != nil { |
| 1093 |
t.Fatalf("Handshake failed: %v", err) |
| 1094 |
} |
| 1095 |
|
| 1096 |
if ss.Version != v || cs.Version != v { |
| 1097 |
t.Errorf("Got versions %x (server) and %x (client), expected %x", ss.Version, cs.Version, v) |
| 1098 |
} |
| 1099 |
|
| 1100 |
if !ss.HandshakeComplete || !cs.HandshakeComplete { |
| 1101 |
t.Errorf("Got HandshakeComplete %v (server) and %v (client), expected true", ss.HandshakeComplete, cs.HandshakeComplete) |
| 1102 |
} |
| 1103 |
|
| 1104 |
if ss.DidResume || cs.DidResume { |
| 1105 |
t.Errorf("Got DidResume %v (server) and %v (client), expected false", ss.DidResume, cs.DidResume) |
| 1106 |
} |
| 1107 |
|
| 1108 |
if ss.CipherSuite == 0 || cs.CipherSuite == 0 { |
| 1109 |
t.Errorf("Got invalid cipher suite: %v (server) and %v (client)", ss.CipherSuite, cs.CipherSuite) |
| 1110 |
} |
| 1111 |
|
| 1112 |
if ss.NegotiatedProtocol != alpnProtocol || cs.NegotiatedProtocol != alpnProtocol { |
| 1113 |
t.Errorf("Got negotiated protocol %q (server) and %q (client), expected %q", ss.NegotiatedProtocol, cs.NegotiatedProtocol, alpnProtocol) |
| 1114 |
} |
| 1115 |
|
| 1116 |
if !cs.NegotiatedProtocolIsMutual { |
| 1117 |
t.Errorf("Got false NegotiatedProtocolIsMutual on the client side") |
| 1118 |
} |
| 1119 |
// NegotiatedProtocolIsMutual on the server side is unspecified. |
| 1120 |
|
| 1121 |
if ss.ServerName != serverName { |
| 1122 |
t.Errorf("Got server name %q, expected %q", ss.ServerName, serverName) |
| 1123 |
} |
| 1124 |
if cs.ServerName != serverName { |
| 1125 |
t.Errorf("Got server name on client connection %q, expected %q", cs.ServerName, serverName) |
| 1126 |
} |
| 1127 |
|
| 1128 |
if len(ss.PeerCertificates) != 1 || len(cs.PeerCertificates) != 1 { |
| 1129 |
t.Errorf("Got %d (server) and %d (client) peer certificates, expected %d", len(ss.PeerCertificates), len(cs.PeerCertificates), 1) |
| 1130 |
} |
| 1131 |
|
| 1132 |
if len(ss.VerifiedChains) != 1 || len(cs.VerifiedChains) != 1 { |
| 1133 |
t.Errorf("Got %d (server) and %d (client) verified chains, expected %d", len(ss.VerifiedChains), len(cs.VerifiedChains), 1) |
| 1134 |
} else if len(ss.VerifiedChains[0]) != 2 || len(cs.VerifiedChains[0]) != 2 { |
| 1135 |
t.Errorf("Got %d (server) and %d (client) long verified chain, expected %d", len(ss.VerifiedChains[0]), len(cs.VerifiedChains[0]), 2) |
| 1136 |
} |
| 1137 |
|
| 1138 |
if len(cs.SignedCertificateTimestamps) != 2 { |
| 1139 |
t.Errorf("Got %d SCTs, expected %d", len(cs.SignedCertificateTimestamps), 2) |
| 1140 |
} |
| 1141 |
if !bytes.Equal(cs.OCSPResponse, ocsp) { |
| 1142 |
t.Errorf("Got OCSPs %x, expected %x", cs.OCSPResponse, ocsp) |
| 1143 |
} |
| 1144 |
// Only TLS 1.3 supports OCSP and SCTs on client certs. |
| 1145 |
if v == VersionTLS13 { |
| 1146 |
if len(ss.SignedCertificateTimestamps) != 2 { |
| 1147 |
t.Errorf("Got %d client SCTs, expected %d", len(ss.SignedCertificateTimestamps), 2) |
| 1148 |
} |
| 1149 |
if !bytes.Equal(ss.OCSPResponse, ocsp) { |
| 1150 |
t.Errorf("Got client OCSPs %x, expected %x", ss.OCSPResponse, ocsp) |
| 1151 |
} |
| 1152 |
} |
| 1153 |
|
| 1154 |
if v == VersionTLS13 { |
| 1155 |
if ss.TLSUnique != nil || cs.TLSUnique != nil { |
| 1156 |
t.Errorf("Got TLSUnique %x (server) and %x (client), expected nil in TLS 1.3", ss.TLSUnique, cs.TLSUnique) |
| 1157 |
} |
| 1158 |
} else { |
| 1159 |
if ss.TLSUnique == nil || cs.TLSUnique == nil { |
| 1160 |
t.Errorf("Got TLSUnique %x (server) and %x (client), expected non-nil", ss.TLSUnique, cs.TLSUnique) |
| 1161 |
} |
| 1162 |
} |
| 1163 |
}) |
| 1164 |
} |
| 1165 |
} |
| 1166 |
|
| 1167 |
// Issue 28744: Ensure that we don't modify memory |
| 1168 |
// that Config doesn't own such as Certificates. |
| 1169 |
func TestBuildNameToCertificate_doesntModifyCertificates(t *testing.T) { |
| 1170 |
c0 := Certificate{ |
| 1171 |
Certificate: [][]byte{testRSACertificate}, |
| 1172 |
PrivateKey: testRSAPrivateKey, |
| 1173 |
} |
| 1174 |
c1 := Certificate{ |
| 1175 |
Certificate: [][]byte{testSNICertificate}, |
| 1176 |
PrivateKey: testRSAPrivateKey, |
| 1177 |
} |
| 1178 |
config := testConfig.Clone() |
| 1179 |
config.Certificates = []Certificate{c0, c1} |
| 1180 |
|
| 1181 |
config.BuildNameToCertificate() |
| 1182 |
got := config.Certificates |
| 1183 |
want := []Certificate{c0, c1} |
| 1184 |
if !reflect.DeepEqual(got, want) { |
| 1185 |
t.Fatalf("Certificates were mutated by BuildNameToCertificate\nGot: %#v\nWant: %#v\n", got, want) |
| 1186 |
} |
| 1187 |
} |
| 1188 |
|
| 1189 |
func testingKey(s string) string { return strings.ReplaceAll(s, "TESTING KEY", "PRIVATE KEY") } |
| 1190 |
|
| 1191 |
func TestClientHelloInfo_SupportsCertificate(t *testing.T) { |
| 1192 |
rsaCert := &Certificate{ |
| 1193 |
Certificate: [][]byte{testRSACertificate}, |
| 1194 |
PrivateKey: testRSAPrivateKey, |
| 1195 |
} |
| 1196 |
pkcs1Cert := &Certificate{ |
| 1197 |
Certificate: [][]byte{testRSACertificate}, |
| 1198 |
PrivateKey: testRSAPrivateKey, |
| 1199 |
SupportedSignatureAlgorithms: []SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256}, |
| 1200 |
} |
| 1201 |
ecdsaCert := &Certificate{ |
| 1202 |
// ECDSA P-256 certificate |
| 1203 |
Certificate: [][]byte{testP256Certificate}, |
| 1204 |
PrivateKey: testP256PrivateKey, |
| 1205 |
} |
| 1206 |
ed25519Cert := &Certificate{ |
| 1207 |
Certificate: [][]byte{testEd25519Certificate}, |
| 1208 |
PrivateKey: testEd25519PrivateKey, |
| 1209 |
} |
| 1210 |
|
| 1211 |
tests := []struct { |
| 1212 |
c *Certificate |
| 1213 |
chi *ClientHelloInfo |
| 1214 |
wantErr string |
| 1215 |
}{ |
| 1216 |
{rsaCert, &ClientHelloInfo{ |
| 1217 |
ServerName: "example.golang", |
| 1218 |
SignatureSchemes: []SignatureScheme{PSSWithSHA256}, |
| 1219 |
SupportedVersions: []uint16{VersionTLS13}, |
| 1220 |
}, ""}, |
| 1221 |
{ecdsaCert, &ClientHelloInfo{ |
| 1222 |
SignatureSchemes: []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256}, |
| 1223 |
SupportedVersions: []uint16{VersionTLS13, VersionTLS12}, |
| 1224 |
}, ""}, |
| 1225 |
{rsaCert, &ClientHelloInfo{ |
| 1226 |
ServerName: "example.com", |
| 1227 |
SignatureSchemes: []SignatureScheme{PSSWithSHA256}, |
| 1228 |
SupportedVersions: []uint16{VersionTLS13}, |
| 1229 |
}, "not valid for requested server name"}, |
| 1230 |
{ecdsaCert, &ClientHelloInfo{ |
| 1231 |
SignatureSchemes: []SignatureScheme{ECDSAWithP384AndSHA384}, |
| 1232 |
SupportedVersions: []uint16{VersionTLS13}, |
| 1233 |
}, "signature algorithms"}, |
| 1234 |
{pkcs1Cert, &ClientHelloInfo{ |
| 1235 |
SignatureSchemes: []SignatureScheme{PSSWithSHA256, ECDSAWithP256AndSHA256}, |
| 1236 |
SupportedVersions: []uint16{VersionTLS13}, |
| 1237 |
}, "signature algorithms"}, |
| 1238 |
|
| 1239 |
{rsaCert, &ClientHelloInfo{ |
| 1240 |
CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, |
| 1241 |
SignatureSchemes: []SignatureScheme{PKCS1WithSHA1}, |
| 1242 |
SupportedVersions: []uint16{VersionTLS13, VersionTLS12}, |
| 1243 |
}, "signature algorithms"}, |
| 1244 |
{rsaCert, &ClientHelloInfo{ |
| 1245 |
CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, |
| 1246 |
SignatureSchemes: []SignatureScheme{PKCS1WithSHA1}, |
| 1247 |
SupportedVersions: []uint16{VersionTLS13, VersionTLS12}, |
| 1248 |
config: &Config{ |
| 1249 |
MaxVersion: VersionTLS12, |
| 1250 |
}, |
| 1251 |
}, ""}, // Check that mutual version selection works. |
| 1252 |
|
| 1253 |
{ecdsaCert, &ClientHelloInfo{ |
| 1254 |
CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, |
| 1255 |
SupportedCurves: []CurveID{CurveP256}, |
| 1256 |
SupportedPoints: []uint8{pointFormatUncompressed}, |
| 1257 |
SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256}, |
| 1258 |
SupportedVersions: []uint16{VersionTLS12}, |
| 1259 |
}, ""}, |
| 1260 |
{ecdsaCert, &ClientHelloInfo{ |
| 1261 |
CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, |
| 1262 |
SupportedCurves: []CurveID{CurveP256}, |
| 1263 |
SupportedPoints: []uint8{pointFormatUncompressed}, |
| 1264 |
SignatureSchemes: []SignatureScheme{ECDSAWithP384AndSHA384}, |
| 1265 |
SupportedVersions: []uint16{VersionTLS12}, |
| 1266 |
}, ""}, // TLS 1.2 does not restrict curves based on the SignatureScheme. |
| 1267 |
{ecdsaCert, &ClientHelloInfo{ |
| 1268 |
CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, |
| 1269 |
SupportedCurves: []CurveID{CurveP256}, |
| 1270 |
SupportedPoints: []uint8{pointFormatUncompressed}, |
| 1271 |
SignatureSchemes: nil, |
| 1272 |
SupportedVersions: []uint16{VersionTLS12}, |
| 1273 |
}, ""}, // TLS 1.2 comes with default signature schemes. |
| 1274 |
{ecdsaCert, &ClientHelloInfo{ |
| 1275 |
CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, |
| 1276 |
SupportedCurves: []CurveID{CurveP256}, |
| 1277 |
SupportedPoints: []uint8{pointFormatUncompressed}, |
| 1278 |
SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256}, |
| 1279 |
SupportedVersions: []uint16{VersionTLS12}, |
| 1280 |
}, "cipher suite"}, |
| 1281 |
{ecdsaCert, &ClientHelloInfo{ |
| 1282 |
CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, |
| 1283 |
SupportedCurves: []CurveID{CurveP256}, |
| 1284 |
SupportedPoints: []uint8{pointFormatUncompressed}, |
| 1285 |
SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256}, |
| 1286 |
SupportedVersions: []uint16{VersionTLS12}, |
| 1287 |
config: &Config{ |
| 1288 |
CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, |
| 1289 |
}, |
| 1290 |
}, "cipher suite"}, |
| 1291 |
{ecdsaCert, &ClientHelloInfo{ |
| 1292 |
CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, |
| 1293 |
SupportedCurves: []CurveID{CurveP384}, |
| 1294 |
SupportedPoints: []uint8{pointFormatUncompressed}, |
| 1295 |
SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256}, |
| 1296 |
SupportedVersions: []uint16{VersionTLS12}, |
| 1297 |
}, "certificate curve"}, |
| 1298 |
{ecdsaCert, &ClientHelloInfo{ |
| 1299 |
CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, |
| 1300 |
SupportedCurves: []CurveID{CurveP256}, |
| 1301 |
SupportedPoints: []uint8{1}, |
| 1302 |
SignatureSchemes: []SignatureScheme{ECDSAWithP256AndSHA256}, |
| 1303 |
SupportedVersions: []uint16{VersionTLS12}, |
| 1304 |
}, "doesn't support ECDHE"}, |
| 1305 |
{ecdsaCert, &ClientHelloInfo{ |
| 1306 |
CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, |
| 1307 |
SupportedCurves: []CurveID{CurveP256}, |
| 1308 |
SupportedPoints: []uint8{pointFormatUncompressed}, |
| 1309 |
SignatureSchemes: []SignatureScheme{PSSWithSHA256}, |
| 1310 |
SupportedVersions: []uint16{VersionTLS12}, |
| 1311 |
}, "signature algorithms"}, |
| 1312 |
|
| 1313 |
{ed25519Cert, &ClientHelloInfo{ |
| 1314 |
CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, |
| 1315 |
SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support |
| 1316 |
SupportedPoints: []uint8{pointFormatUncompressed}, |
| 1317 |
SignatureSchemes: []SignatureScheme{Ed25519}, |
| 1318 |
SupportedVersions: []uint16{VersionTLS12}, |
| 1319 |
}, ""}, |
| 1320 |
{ed25519Cert, &ClientHelloInfo{ |
| 1321 |
CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, |
| 1322 |
SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support |
| 1323 |
SupportedPoints: []uint8{pointFormatUncompressed}, |
| 1324 |
SignatureSchemes: []SignatureScheme{Ed25519}, |
| 1325 |
SupportedVersions: []uint16{VersionTLS10}, |
| 1326 |
}, "doesn't support Ed25519"}, |
| 1327 |
{ed25519Cert, &ClientHelloInfo{ |
| 1328 |
CipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, |
| 1329 |
SupportedCurves: []CurveID{}, |
| 1330 |
SupportedPoints: []uint8{pointFormatUncompressed}, |
| 1331 |
SignatureSchemes: []SignatureScheme{Ed25519}, |
| 1332 |
SupportedVersions: []uint16{VersionTLS12}, |
| 1333 |
}, "doesn't support ECDHE"}, |
| 1334 |
|
| 1335 |
{rsaCert, &ClientHelloInfo{ |
| 1336 |
CipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA}, |
| 1337 |
SupportedCurves: []CurveID{CurveP256}, // only relevant for ECDHE support |
| 1338 |
SupportedPoints: []uint8{pointFormatUncompressed}, |
| 1339 |
SupportedVersions: []uint16{VersionTLS10}, |
| 1340 |
}, ""}, |
| 1341 |
{rsaCert, &ClientHelloInfo{ |
| 1342 |
CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256}, |
| 1343 |
SupportedVersions: []uint16{VersionTLS12}, |
| 1344 |
}, ""}, // static RSA fallback |
| 1345 |
} |
| 1346 |
for i, tt := range tests { |
| 1347 |
err := tt.chi.SupportsCertificate(tt.c) |
| 1348 |
switch { |
| 1349 |
case tt.wantErr == "" && err != nil: |
| 1350 |
t.Errorf("%d: unexpected error: %v", i, err) |
| 1351 |
case tt.wantErr != "" && err == nil: |
| 1352 |
t.Errorf("%d: unexpected success", i) |
| 1353 |
case tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr): |
| 1354 |
t.Errorf("%d: got error %q, expected %q", i, err, tt.wantErr) |
| 1355 |
} |
| 1356 |
} |
| 1357 |
} |
| 1358 |
|
| 1359 |
func TestCipherSuites(t *testing.T) { |
| 1360 |
var lastID uint16 |
| 1361 |
for _, c := range CipherSuites() { |
| 1362 |
if lastID > c.ID { |
| 1363 |
t.Errorf("CipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID) |
| 1364 |
} else { |
| 1365 |
lastID = c.ID |
| 1366 |
} |
| 1367 |
|
| 1368 |
if c.Insecure { |
| 1369 |
t.Errorf("%#04x: Insecure CipherSuite returned by CipherSuites()", c.ID) |
| 1370 |
} |
| 1371 |
} |
| 1372 |
lastID = 0 |
| 1373 |
for _, c := range InsecureCipherSuites() { |
| 1374 |
if lastID > c.ID { |
| 1375 |
t.Errorf("InsecureCipherSuites are not ordered by ID: got %#04x after %#04x", c.ID, lastID) |
| 1376 |
} else { |
| 1377 |
lastID = c.ID |
| 1378 |
} |
| 1379 |
|
| 1380 |
if !c.Insecure { |
| 1381 |
t.Errorf("%#04x: not Insecure CipherSuite returned by InsecureCipherSuites()", c.ID) |
| 1382 |
} |
| 1383 |
} |
| 1384 |
|
| 1385 |
CipherSuiteByID := func(id uint16) *CipherSuite { |
| 1386 |
for _, c := range CipherSuites() { |
| 1387 |
if c.ID == id { |
| 1388 |
return c |
| 1389 |
} |
| 1390 |
} |
| 1391 |
for _, c := range InsecureCipherSuites() { |
| 1392 |
if c.ID == id { |
| 1393 |
return c |
| 1394 |
} |
| 1395 |
} |
| 1396 |
return nil |
| 1397 |
} |
| 1398 |
|
| 1399 |
for _, c := range cipherSuites { |
| 1400 |
cc := CipherSuiteByID(c.id) |
| 1401 |
if cc == nil { |
| 1402 |
t.Errorf("%#04x: no CipherSuite entry", c.id) |
| 1403 |
continue |
| 1404 |
} |
| 1405 |
|
| 1406 |
if tls12Only := c.flags&suiteTLS12 != 0; tls12Only && len(cc.SupportedVersions) != 1 { |
| 1407 |
t.Errorf("%#04x: suite is TLS 1.2 only, but SupportedVersions is %v", c.id, cc.SupportedVersions) |
| 1408 |
} else if !tls12Only && len(cc.SupportedVersions) != 3 { |
| 1409 |
t.Errorf("%#04x: suite TLS 1.0-1.2, but SupportedVersions is %v", c.id, cc.SupportedVersions) |
| 1410 |
} |
| 1411 |
|
| 1412 |
if got := CipherSuiteName(c.id); got != cc.Name { |
| 1413 |
t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name) |
| 1414 |
} |
| 1415 |
} |
| 1416 |
for _, c := range cipherSuitesTLS13 { |
| 1417 |
cc := CipherSuiteByID(c.id) |
| 1418 |
if cc == nil { |
| 1419 |
t.Errorf("%#04x: no CipherSuite entry", c.id) |
| 1420 |
continue |
| 1421 |
} |
| 1422 |
|
| 1423 |
if cc.Insecure { |
| 1424 |
t.Errorf("%#04x: Insecure %v, expected false", c.id, cc.Insecure) |
| 1425 |
} |
| 1426 |
if len(cc.SupportedVersions) != 1 || cc.SupportedVersions[0] != VersionTLS13 { |
| 1427 |
t.Errorf("%#04x: suite is TLS 1.3 only, but SupportedVersions is %v", c.id, cc.SupportedVersions) |
| 1428 |
} |
| 1429 |
|
| 1430 |
if got := CipherSuiteName(c.id); got != cc.Name { |
| 1431 |
t.Errorf("%#04x: unexpected CipherSuiteName: got %q, expected %q", c.id, got, cc.Name) |
| 1432 |
} |
| 1433 |
} |
| 1434 |
|
| 1435 |
if got := CipherSuiteName(0xabc); got != "0x0ABC" { |
| 1436 |
t.Errorf("unexpected fallback CipherSuiteName: got %q, expected 0x0ABC", got) |
| 1437 |
} |
| 1438 |
|
| 1439 |
if len(cipherSuitesPreferenceOrder) != len(cipherSuites) { |
| 1440 |
t.Errorf("cipherSuitesPreferenceOrder is not the same size as cipherSuites") |
| 1441 |
} |
| 1442 |
if len(cipherSuitesPreferenceOrderNoAES) != len(cipherSuitesPreferenceOrder) { |
| 1443 |
t.Errorf("cipherSuitesPreferenceOrderNoAES is not the same size as cipherSuitesPreferenceOrder") |
| 1444 |
} |
| 1445 |
|
| 1446 |
// Check that disabled suites are at the end of the preference lists, and |
| 1447 |
// that they are marked insecure. |
| 1448 |
for i, id := range disabledCipherSuites { |
| 1449 |
offset := len(cipherSuitesPreferenceOrder) - len(disabledCipherSuites) |
| 1450 |
if cipherSuitesPreferenceOrder[offset+i] != id { |
| 1451 |
t.Errorf("disabledCipherSuites[%d]: not at the end of cipherSuitesPreferenceOrder", i) |
| 1452 |
} |
| 1453 |
if cipherSuitesPreferenceOrderNoAES[offset+i] != id { |
| 1454 |
t.Errorf("disabledCipherSuites[%d]: not at the end of cipherSuitesPreferenceOrderNoAES", i) |
| 1455 |
} |
| 1456 |
c := CipherSuiteByID(id) |
| 1457 |
if c == nil { |
| 1458 |
t.Errorf("%#04x: no CipherSuite entry", id) |
| 1459 |
continue |
| 1460 |
} |
| 1461 |
if !c.Insecure { |
| 1462 |
t.Errorf("%#04x: disabled by default but not marked insecure", id) |
| 1463 |
} |
| 1464 |
} |
| 1465 |
|
| 1466 |
for i, prefOrder := range [][]uint16{cipherSuitesPreferenceOrder, cipherSuitesPreferenceOrderNoAES} { |
| 1467 |
// Check that insecure and HTTP/2 bad cipher suites are at the end of |
| 1468 |
// the preference lists. |
| 1469 |
var sawInsecure, sawBad bool |
| 1470 |
for _, id := range prefOrder { |
| 1471 |
c := CipherSuiteByID(id) |
| 1472 |
if c == nil { |
| 1473 |
t.Errorf("%#04x: no CipherSuite entry", id) |
| 1474 |
continue |
| 1475 |
} |
| 1476 |
|
| 1477 |
if c.Insecure { |
| 1478 |
sawInsecure = true |
| 1479 |
} else if sawInsecure { |
| 1480 |
t.Errorf("%#04x: secure suite after insecure one(s)", id) |
| 1481 |
} |
| 1482 |
|
| 1483 |
if http2isBadCipher(id) { |
| 1484 |
sawBad = true |
| 1485 |
} else if sawBad { |
| 1486 |
t.Errorf("%#04x: non-bad suite after bad HTTP/2 one(s)", id) |
| 1487 |
} |
| 1488 |
} |
| 1489 |
|
| 1490 |
// Check that the list is sorted according to the documented criteria. |
| 1491 |
isBetter := func(a, b int) bool { |
| 1492 |
aSuite, bSuite := cipherSuiteByID(prefOrder[a]), cipherSuiteByID(prefOrder[b]) |
| 1493 |
aName, bName := CipherSuiteName(prefOrder[a]), CipherSuiteName(prefOrder[b]) |
| 1494 |
// * < RC4 |
| 1495 |
if !strings.Contains(aName, "RC4") && strings.Contains(bName, "RC4") { |
| 1496 |
return true |
| 1497 |
} else if strings.Contains(aName, "RC4") && !strings.Contains(bName, "RC4") { |
| 1498 |
return false |
| 1499 |
} |
| 1500 |
// * < CBC_SHA256 |
| 1501 |
if !strings.Contains(aName, "CBC_SHA256") && strings.Contains(bName, "CBC_SHA256") { |
| 1502 |
return true |
| 1503 |
} else if strings.Contains(aName, "CBC_SHA256") && !strings.Contains(bName, "CBC_SHA256") { |
| 1504 |
return false |
| 1505 |
} |
| 1506 |
// * < 3DES |
| 1507 |
if !strings.Contains(aName, "3DES") && strings.Contains(bName, "3DES") { |
| 1508 |
return true |
| 1509 |
} else if strings.Contains(aName, "3DES") && !strings.Contains(bName, "3DES") { |
| 1510 |
return false |
| 1511 |
} |
| 1512 |
// ECDHE < * |
| 1513 |
if aSuite.flags&suiteECDHE != 0 && bSuite.flags&suiteECDHE == 0 { |
| 1514 |
return true |
| 1515 |
} else if aSuite.flags&suiteECDHE == 0 && bSuite.flags&suiteECDHE != 0 { |
| 1516 |
return false |
| 1517 |
} |
| 1518 |
// AEAD < CBC |
| 1519 |
if aSuite.aead != nil && bSuite.aead == nil { |
| 1520 |
return true |
| 1521 |
} else if aSuite.aead == nil && bSuite.aead != nil { |
| 1522 |
return false |
| 1523 |
} |
| 1524 |
// AES < ChaCha20 |
| 1525 |
if strings.Contains(aName, "AES") && strings.Contains(bName, "CHACHA20") { |
| 1526 |
return i == 0 // true for cipherSuitesPreferenceOrder |
| 1527 |
} else if strings.Contains(aName, "CHACHA20") && strings.Contains(bName, "AES") { |
| 1528 |
return i != 0 // true for cipherSuitesPreferenceOrderNoAES |
| 1529 |
} |
| 1530 |
// AES-128 < AES-256 |
| 1531 |
if strings.Contains(aName, "AES_128") && strings.Contains(bName, "AES_256") { |
| 1532 |
return true |
| 1533 |
} else if strings.Contains(aName, "AES_256") && strings.Contains(bName, "AES_128") { |
| 1534 |
return false |
| 1535 |
} |
| 1536 |
// ECDSA < RSA |
| 1537 |
if aSuite.flags&suiteECSign != 0 && bSuite.flags&suiteECSign == 0 { |
| 1538 |
return true |
| 1539 |
} else if aSuite.flags&suiteECSign == 0 && bSuite.flags&suiteECSign != 0 { |
| 1540 |
return false |
| 1541 |
} |
| 1542 |
t.Fatalf("two ciphersuites are equal by all criteria: %v and %v", aName, bName) |
| 1543 |
panic("unreachable") |
| 1544 |
} |
| 1545 |
if !sort.SliceIsSorted(prefOrder, isBetter) { |
| 1546 |
t.Error("preference order is not sorted according to the rules") |
| 1547 |
} |
| 1548 |
} |
| 1549 |
} |
| 1550 |
|
| 1551 |
// http2isBadCipher is copied from net/http. |
| 1552 |
// TODO: if it ends up exposed somewhere, use that instead. |
| 1553 |
func http2isBadCipher(cipher uint16) bool { |
| 1554 |
switch cipher { |
| 1555 |
case TLS_RSA_WITH_RC4_128_SHA, |
| 1556 |
TLS_RSA_WITH_3DES_EDE_CBC_SHA, |
| 1557 |
TLS_RSA_WITH_AES_128_CBC_SHA, |
| 1558 |
TLS_RSA_WITH_AES_256_CBC_SHA, |
| 1559 |
TLS_RSA_WITH_AES_128_CBC_SHA256, |
| 1560 |
TLS_RSA_WITH_AES_128_GCM_SHA256, |
| 1561 |
TLS_RSA_WITH_AES_256_GCM_SHA384, |
| 1562 |
TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, |
| 1563 |
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, |
| 1564 |
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, |
| 1565 |
TLS_ECDHE_RSA_WITH_RC4_128_SHA, |
| 1566 |
TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, |
| 1567 |
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, |
| 1568 |
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, |
| 1569 |
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, |
| 1570 |
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: |
| 1571 |
return true |
| 1572 |
default: |
| 1573 |
return false |
| 1574 |
} |
| 1575 |
} |
| 1576 |
|
| 1577 |
type brokenSigner struct{ crypto.Signer } |
| 1578 |
|
| 1579 |
func (s brokenSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) { |
| 1580 |
// Replace opts with opts.HashFunc(), so rsa.PSSOptions are discarded. |
| 1581 |
return s.Signer.Sign(rand, digest, opts.HashFunc()) |
| 1582 |
} |
| 1583 |
|
| 1584 |
// TestPKCS1OnlyCert uses a client certificate with a broken crypto.Signer that |
| 1585 |
// always makes PKCS #1 v1.5 signatures, so can't be used with RSA-PSS. |
| 1586 |
func TestPKCS1OnlyCert(t *testing.T) { |
| 1587 |
clientConfig := testConfig.Clone() |
| 1588 |
clientConfig.Certificates = []Certificate{{ |
| 1589 |
Certificate: [][]byte{testRSACertificate}, |
| 1590 |
PrivateKey: brokenSigner{testRSAPrivateKey}, |
| 1591 |
}} |
| 1592 |
serverConfig := testConfig.Clone() |
| 1593 |
serverConfig.MaxVersion = VersionTLS12 // TLS 1.3 doesn't support PKCS #1 v1.5 |
| 1594 |
serverConfig.ClientAuth = RequireAnyClientCert |
| 1595 |
|
| 1596 |
// If RSA-PSS is selected, the handshake should fail. |
| 1597 |
if _, _, err := testHandshake(t, clientConfig, serverConfig); err == nil { |
| 1598 |
t.Fatal("expected broken certificate to cause connection to fail") |
| 1599 |
} |
| 1600 |
|
| 1601 |
clientConfig.Certificates[0].SupportedSignatureAlgorithms = |
| 1602 |
[]SignatureScheme{PKCS1WithSHA1, PKCS1WithSHA256} |
| 1603 |
|
| 1604 |
// But if the certificate restricts supported algorithms, RSA-PSS should not |
| 1605 |
// be selected, and the handshake should succeed. |
| 1606 |
if _, _, err := testHandshake(t, clientConfig, serverConfig); err != nil { |
| 1607 |
t.Error(err) |
| 1608 |
} |
| 1609 |
} |