| 1 |
// Copyright 2024 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 |
"crypto/internal/cryptotest" |
| 10 |
"crypto/x509" |
| 11 |
"encoding/base64" |
| 12 |
"encoding/json" |
| 13 |
"encoding/pem" |
| 14 |
"errors" |
| 15 |
"flag" |
| 16 |
"fmt" |
| 17 |
"html/template" |
| 18 |
"internal/byteorder" |
| 19 |
"internal/testenv" |
| 20 |
"io" |
| 21 |
"log" |
| 22 |
"net" |
| 23 |
"os" |
| 24 |
"path/filepath" |
| 25 |
"runtime" |
| 26 |
"slices" |
| 27 |
"strconv" |
| 28 |
"strings" |
| 29 |
"testing" |
| 30 |
"time" |
| 31 |
|
| 32 |
"golang.org/x/crypto/cryptobyte" |
| 33 |
) |
| 34 |
|
| 35 |
const boringsslModVer = "v0.0.0-20250620172916-f51d8b099832" |
| 36 |
|
| 37 |
var ( |
| 38 |
port = flag.String("port", "", "") |
| 39 |
server = flag.Bool("server", false, "") |
| 40 |
|
| 41 |
isHandshakerSupported = flag.Bool("is-handshaker-supported", false, "") |
| 42 |
|
| 43 |
keyfile = flag.String("key-file", "", "") |
| 44 |
certfile = flag.String("cert-file", "", "") |
| 45 |
ocspResponse = flagBase64("ocsp-response", "") |
| 46 |
signingPrefs = flagIntSlice("signing-prefs", "") |
| 47 |
|
| 48 |
trustCert = flag.String("trust-cert", "", "") |
| 49 |
|
| 50 |
minVersion = flag.Int("min-version", VersionSSL30, "") |
| 51 |
maxVersion = flag.Int("max-version", VersionTLS13, "") |
| 52 |
expectVersion = flag.Int("expect-version", 0, "") |
| 53 |
|
| 54 |
noTLS1 = flag.Bool("no-tls1", false, "") |
| 55 |
noTLS11 = flag.Bool("no-tls11", false, "") |
| 56 |
noTLS12 = flag.Bool("no-tls12", false, "") |
| 57 |
noTLS13 = flag.Bool("no-tls13", false, "") |
| 58 |
|
| 59 |
requireAnyClientCertificate = flag.Bool("require-any-client-certificate", false, "") |
| 60 |
|
| 61 |
shimWritesFirst = flag.Bool("shim-writes-first", false, "") |
| 62 |
|
| 63 |
resumeCount = flag.Int("resume-count", 0, "") |
| 64 |
|
| 65 |
curves = flagIntSlice("curves", "") |
| 66 |
expectedCurve = flag.String("expect-curve-id", "", "") |
| 67 |
|
| 68 |
verifyPrefs = flagIntSlice("verify-prefs", "") |
| 69 |
expectedSigAlg = flag.String("expect-peer-signature-algorithm", "", "") |
| 70 |
expectedPeerSigAlg = flagIntSlice("expect-peer-verify-pref", "") |
| 71 |
|
| 72 |
shimID = flag.Uint64("shim-id", 0, "") |
| 73 |
_ = flag.Bool("ipv6", false, "") |
| 74 |
|
| 75 |
echConfigList = flagBase64("ech-config-list", "") |
| 76 |
expectECHAccepted = flag.Bool("expect-ech-accept", false, "") |
| 77 |
expectHRR = flag.Bool("expect-hrr", false, "") |
| 78 |
expectNoHRR = flag.Bool("expect-no-hrr", false, "") |
| 79 |
expectedECHRetryConfigs = flag.String("expect-ech-retry-configs", "", "") |
| 80 |
expectNoECHRetryConfigs = flag.Bool("expect-no-ech-retry-configs", false, "") |
| 81 |
onInitialExpectECHAccepted = flag.Bool("on-initial-expect-ech-accept", false, "") |
| 82 |
_ = flag.Bool("expect-no-ech-name-override", false, "") |
| 83 |
_ = flag.String("expect-ech-name-override", "", "") |
| 84 |
_ = flag.Bool("reverify-on-resume", false, "") |
| 85 |
onResumeECHConfigList = flagBase64("on-resume-ech-config-list", "") |
| 86 |
_ = flag.Bool("on-resume-expect-reject-early-data", false, "") |
| 87 |
onResumeExpectECHAccepted = flag.Bool("on-resume-expect-ech-accept", false, "") |
| 88 |
_ = flag.Bool("on-resume-expect-no-ech-name-override", false, "") |
| 89 |
expectedServerName = flag.String("expect-server-name", "", "") |
| 90 |
echServerConfig = flagStringSlice("ech-server-config", "") |
| 91 |
echServerKey = flagStringSlice("ech-server-key", "") |
| 92 |
echServerRetryConfig = flagStringSlice("ech-is-retry-config", "") |
| 93 |
|
| 94 |
expectSessionMiss = flag.Bool("expect-session-miss", false, "") |
| 95 |
|
| 96 |
_ = flag.Bool("enable-early-data", false, "") |
| 97 |
_ = flag.Bool("on-resume-expect-accept-early-data", false, "") |
| 98 |
_ = flag.Bool("expect-ticket-supports-early-data", false, "") |
| 99 |
_ = flag.Bool("on-resume-shim-writes-first", false, "") |
| 100 |
|
| 101 |
advertiseALPN = flag.String("advertise-alpn", "", "") |
| 102 |
expectALPN = flag.String("expect-alpn", "", "") |
| 103 |
rejectALPN = flag.Bool("reject-alpn", false, "") |
| 104 |
declineALPN = flag.Bool("decline-alpn", false, "") |
| 105 |
expectAdvertisedALPN = flag.String("expect-advertised-alpn", "", "") |
| 106 |
selectALPN = flag.String("select-alpn", "", "") |
| 107 |
|
| 108 |
hostName = flag.String("host-name", "", "") |
| 109 |
|
| 110 |
verifyPeer = flag.Bool("verify-peer", false, "") |
| 111 |
_ = flag.Bool("use-custom-verify-callback", false, "") |
| 112 |
|
| 113 |
waitForDebugger = flag.Bool("wait-for-debugger", false, "") |
| 114 |
) |
| 115 |
|
| 116 |
type stringSlice []string |
| 117 |
|
| 118 |
func flagStringSlice(name, usage string) *stringSlice { |
| 119 |
f := new(stringSlice) |
| 120 |
flag.Var(f, name, usage) |
| 121 |
return f |
| 122 |
} |
| 123 |
|
| 124 |
func (saf *stringSlice) String() string { |
| 125 |
return strings.Join(*saf, ",") |
| 126 |
} |
| 127 |
|
| 128 |
func (saf *stringSlice) Set(s string) error { |
| 129 |
*saf = append(*saf, s) |
| 130 |
return nil |
| 131 |
} |
| 132 |
|
| 133 |
type intSlice []int64 |
| 134 |
|
| 135 |
func flagIntSlice(name, usage string) *intSlice { |
| 136 |
f := new(intSlice) |
| 137 |
flag.Var(f, name, usage) |
| 138 |
return f |
| 139 |
} |
| 140 |
|
| 141 |
func (sf *intSlice) String() string { |
| 142 |
return strings.Join(strings.Split(fmt.Sprint(*sf), " "), ",") |
| 143 |
} |
| 144 |
|
| 145 |
func (sf *intSlice) Set(s string) error { |
| 146 |
i, err := strconv.ParseInt(s, 10, 64) |
| 147 |
if err != nil { |
| 148 |
return err |
| 149 |
} |
| 150 |
*sf = append(*sf, i) |
| 151 |
return nil |
| 152 |
} |
| 153 |
|
| 154 |
type base64Flag []byte |
| 155 |
|
| 156 |
func flagBase64(name, usage string) *base64Flag { |
| 157 |
f := new(base64Flag) |
| 158 |
flag.Var(f, name, usage) |
| 159 |
return f |
| 160 |
} |
| 161 |
|
| 162 |
func (f *base64Flag) String() string { |
| 163 |
return base64.StdEncoding.EncodeToString(*f) |
| 164 |
} |
| 165 |
|
| 166 |
func (f *base64Flag) Set(s string) error { |
| 167 |
if *f != nil { |
| 168 |
return fmt.Errorf("multiple base64 values not supported") |
| 169 |
} |
| 170 |
b, err := base64.StdEncoding.DecodeString(s) |
| 171 |
if err != nil { |
| 172 |
return err |
| 173 |
} |
| 174 |
*f = b |
| 175 |
return nil |
| 176 |
} |
| 177 |
|
| 178 |
func bogoShim() { |
| 179 |
if *isHandshakerSupported { |
| 180 |
fmt.Println("No") |
| 181 |
return |
| 182 |
} |
| 183 |
|
| 184 |
fmt.Printf("BoGo shim flags: %q", os.Args[1:]) |
| 185 |
|
| 186 |
// Test with both the default and insecure cipher suites. |
| 187 |
var ciphersuites []uint16 |
| 188 |
for _, s := range append(CipherSuites(), InsecureCipherSuites()...) { |
| 189 |
ciphersuites = append(ciphersuites, s.ID) |
| 190 |
} |
| 191 |
|
| 192 |
cfg := &Config{ |
| 193 |
ServerName: "test", |
| 194 |
|
| 195 |
MinVersion: uint16(*minVersion), |
| 196 |
MaxVersion: uint16(*maxVersion), |
| 197 |
|
| 198 |
ClientSessionCache: NewLRUClientSessionCache(0), |
| 199 |
|
| 200 |
CipherSuites: ciphersuites, |
| 201 |
|
| 202 |
GetConfigForClient: func(chi *ClientHelloInfo) (*Config, error) { |
| 203 |
|
| 204 |
if *expectAdvertisedALPN != "" { |
| 205 |
|
| 206 |
s := cryptobyte.String(*expectAdvertisedALPN) |
| 207 |
|
| 208 |
var expectedALPNs []string |
| 209 |
|
| 210 |
for !s.Empty() { |
| 211 |
var alpn cryptobyte.String |
| 212 |
if !s.ReadUint8LengthPrefixed(&alpn) { |
| 213 |
return nil, fmt.Errorf("unexpected error while parsing arguments for -expect-advertised-alpn") |
| 214 |
} |
| 215 |
expectedALPNs = append(expectedALPNs, string(alpn)) |
| 216 |
} |
| 217 |
|
| 218 |
if !slices.Equal(chi.SupportedProtos, expectedALPNs) { |
| 219 |
return nil, fmt.Errorf("unexpected ALPN: got %q, want %q", chi.SupportedProtos, expectedALPNs) |
| 220 |
} |
| 221 |
} |
| 222 |
return nil, nil |
| 223 |
}, |
| 224 |
} |
| 225 |
|
| 226 |
if *noTLS1 { |
| 227 |
cfg.MinVersion = VersionTLS11 |
| 228 |
if *noTLS11 { |
| 229 |
cfg.MinVersion = VersionTLS12 |
| 230 |
if *noTLS12 { |
| 231 |
cfg.MinVersion = VersionTLS13 |
| 232 |
if *noTLS13 { |
| 233 |
log.Fatalf("no supported versions enabled") |
| 234 |
} |
| 235 |
} |
| 236 |
} |
| 237 |
} else if *noTLS13 { |
| 238 |
cfg.MaxVersion = VersionTLS12 |
| 239 |
if *noTLS12 { |
| 240 |
cfg.MaxVersion = VersionTLS11 |
| 241 |
if *noTLS11 { |
| 242 |
cfg.MaxVersion = VersionTLS10 |
| 243 |
if *noTLS1 { |
| 244 |
log.Fatalf("no supported versions enabled") |
| 245 |
} |
| 246 |
} |
| 247 |
} |
| 248 |
} |
| 249 |
|
| 250 |
if *advertiseALPN != "" { |
| 251 |
alpns := *advertiseALPN |
| 252 |
for len(alpns) > 0 { |
| 253 |
alpnLen := int(alpns[0]) |
| 254 |
cfg.NextProtos = append(cfg.NextProtos, alpns[1:1+alpnLen]) |
| 255 |
alpns = alpns[alpnLen+1:] |
| 256 |
} |
| 257 |
} |
| 258 |
|
| 259 |
if *rejectALPN { |
| 260 |
cfg.NextProtos = []string{"unnegotiableprotocol"} |
| 261 |
} |
| 262 |
|
| 263 |
if *declineALPN { |
| 264 |
cfg.NextProtos = []string{} |
| 265 |
} |
| 266 |
if *selectALPN != "" { |
| 267 |
cfg.NextProtos = []string{*selectALPN} |
| 268 |
} |
| 269 |
|
| 270 |
if *hostName != "" { |
| 271 |
cfg.ServerName = *hostName |
| 272 |
} |
| 273 |
|
| 274 |
if *keyfile != "" || *certfile != "" { |
| 275 |
pair, err := LoadX509KeyPair(*certfile, *keyfile) |
| 276 |
if err != nil { |
| 277 |
log.Fatalf("load key-file err: %s", err) |
| 278 |
} |
| 279 |
for _, id := range *signingPrefs { |
| 280 |
pair.SupportedSignatureAlgorithms = append(pair.SupportedSignatureAlgorithms, SignatureScheme(id)) |
| 281 |
} |
| 282 |
pair.OCSPStaple = *ocspResponse |
| 283 |
// Use Get[Client]Certificate to force the use of the certificate, which |
| 284 |
// more closely matches the BoGo expectations (e.g. handshake failure if |
| 285 |
// no client certificates are compatible). |
| 286 |
cfg.GetCertificate = func(chi *ClientHelloInfo) (*Certificate, error) { |
| 287 |
if *expectedPeerSigAlg != nil { |
| 288 |
if len(chi.SignatureSchemes) != len(*expectedPeerSigAlg) { |
| 289 |
return nil, fmt.Errorf("unexpected signature algorithms: got %s, want %v", chi.SignatureSchemes, *expectedPeerSigAlg) |
| 290 |
} |
| 291 |
for i := range *expectedPeerSigAlg { |
| 292 |
if chi.SignatureSchemes[i] != SignatureScheme((*expectedPeerSigAlg)[i]) { |
| 293 |
return nil, fmt.Errorf("unexpected signature algorithms: got %s, want %v", chi.SignatureSchemes, *expectedPeerSigAlg) |
| 294 |
} |
| 295 |
} |
| 296 |
} |
| 297 |
return &pair, nil |
| 298 |
} |
| 299 |
cfg.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) { |
| 300 |
if *expectedPeerSigAlg != nil { |
| 301 |
if len(cri.SignatureSchemes) != len(*expectedPeerSigAlg) { |
| 302 |
return nil, fmt.Errorf("unexpected signature algorithms: got %s, want %v", cri.SignatureSchemes, *expectedPeerSigAlg) |
| 303 |
} |
| 304 |
for i := range *expectedPeerSigAlg { |
| 305 |
if cri.SignatureSchemes[i] != SignatureScheme((*expectedPeerSigAlg)[i]) { |
| 306 |
return nil, fmt.Errorf("unexpected signature algorithms: got %s, want %v", cri.SignatureSchemes, *expectedPeerSigAlg) |
| 307 |
} |
| 308 |
} |
| 309 |
} |
| 310 |
return &pair, nil |
| 311 |
} |
| 312 |
} |
| 313 |
if *trustCert != "" { |
| 314 |
pool := x509.NewCertPool() |
| 315 |
certFile, err := os.ReadFile(*trustCert) |
| 316 |
if err != nil { |
| 317 |
log.Fatalf("load trust-cert err: %s", err) |
| 318 |
} |
| 319 |
block, _ := pem.Decode(certFile) |
| 320 |
cert, err := x509.ParseCertificate(block.Bytes) |
| 321 |
if err != nil { |
| 322 |
log.Fatalf("parse trust-cert err: %s", err) |
| 323 |
} |
| 324 |
pool.AddCert(cert) |
| 325 |
cfg.RootCAs = pool |
| 326 |
} |
| 327 |
|
| 328 |
if *requireAnyClientCertificate { |
| 329 |
cfg.ClientAuth = RequireAnyClientCert |
| 330 |
} |
| 331 |
if *verifyPeer { |
| 332 |
cfg.ClientAuth = VerifyClientCertIfGiven |
| 333 |
} |
| 334 |
|
| 335 |
if *echConfigList != nil { |
| 336 |
cfg.EncryptedClientHelloConfigList = *echConfigList |
| 337 |
cfg.MinVersion = VersionTLS13 |
| 338 |
} |
| 339 |
|
| 340 |
if *curves != nil { |
| 341 |
for _, id := range *curves { |
| 342 |
cfg.CurvePreferences = append(cfg.CurvePreferences, CurveID(id)) |
| 343 |
} |
| 344 |
} |
| 345 |
|
| 346 |
if *verifyPrefs != nil { |
| 347 |
for _, id := range *verifyPrefs { |
| 348 |
testingOnlySupportedSignatureAlgorithms = append(testingOnlySupportedSignatureAlgorithms, SignatureScheme(id)) |
| 349 |
} |
| 350 |
} |
| 351 |
|
| 352 |
if *echServerConfig != nil { |
| 353 |
if len(*echServerConfig) != len(*echServerKey) || len(*echServerConfig) != len(*echServerRetryConfig) { |
| 354 |
log.Fatal("-ech-server-config, -ech-server-key, and -ech-is-retry-config mismatch") |
| 355 |
} |
| 356 |
|
| 357 |
for i, c := range *echServerConfig { |
| 358 |
configBytes, err := base64.StdEncoding.DecodeString(c) |
| 359 |
if err != nil { |
| 360 |
log.Fatalf("parse ech-server-config err: %s", err) |
| 361 |
} |
| 362 |
privBytes, err := base64.StdEncoding.DecodeString((*echServerKey)[i]) |
| 363 |
if err != nil { |
| 364 |
log.Fatalf("parse ech-server-key err: %s", err) |
| 365 |
} |
| 366 |
|
| 367 |
cfg.EncryptedClientHelloKeys = append(cfg.EncryptedClientHelloKeys, EncryptedClientHelloKey{ |
| 368 |
Config: configBytes, |
| 369 |
PrivateKey: privBytes, |
| 370 |
SendAsRetry: (*echServerRetryConfig)[i] == "1", |
| 371 |
}) |
| 372 |
} |
| 373 |
} |
| 374 |
|
| 375 |
for i := 0; i < *resumeCount+1; i++ { |
| 376 |
if i > 0 && *onResumeECHConfigList != nil { |
| 377 |
cfg.EncryptedClientHelloConfigList = *onResumeECHConfigList |
| 378 |
} |
| 379 |
|
| 380 |
conn, err := net.Dial("tcp", net.JoinHostPort("localhost", *port)) |
| 381 |
if err != nil { |
| 382 |
log.Fatalf("dial err: %s", err) |
| 383 |
} |
| 384 |
defer conn.Close() |
| 385 |
|
| 386 |
// Write the shim ID we were passed as a little endian uint64 |
| 387 |
shimIDBytes := make([]byte, 8) |
| 388 |
byteorder.LEPutUint64(shimIDBytes, *shimID) |
| 389 |
if _, err := conn.Write(shimIDBytes); err != nil { |
| 390 |
log.Fatalf("failed to write shim id: %s", err) |
| 391 |
} |
| 392 |
|
| 393 |
var tlsConn *Conn |
| 394 |
if *server { |
| 395 |
tlsConn = Server(conn, cfg) |
| 396 |
} else { |
| 397 |
tlsConn = Client(conn, cfg) |
| 398 |
} |
| 399 |
|
| 400 |
if i == 0 && *shimWritesFirst { |
| 401 |
if _, err := tlsConn.Write([]byte("hello")); err != nil { |
| 402 |
log.Fatalf("write err: %s", err) |
| 403 |
} |
| 404 |
} |
| 405 |
|
| 406 |
// If we were instructed to wait for a debugger, then send SIGSTOP to ourselves. |
| 407 |
// When the debugger attaches it will continue the process. |
| 408 |
if *waitForDebugger { |
| 409 |
pauseProcess() |
| 410 |
} |
| 411 |
|
| 412 |
for { |
| 413 |
buf := make([]byte, 500) |
| 414 |
var n int |
| 415 |
n, err = tlsConn.Read(buf) |
| 416 |
if err != nil { |
| 417 |
break |
| 418 |
} |
| 419 |
buf = buf[:n] |
| 420 |
for i := range buf { |
| 421 |
buf[i] ^= 0xff |
| 422 |
} |
| 423 |
if _, err = tlsConn.Write(buf); err != nil { |
| 424 |
break |
| 425 |
} |
| 426 |
} |
| 427 |
if err != io.EOF { |
| 428 |
// Flush the TLS conn and then perform a graceful shutdown of the |
| 429 |
// TCP connection to avoid the runner side hitting an unexpected |
| 430 |
// write error before it has processed the alert we may have |
| 431 |
// generated for the error condition. |
| 432 |
orderlyShutdown(tlsConn) |
| 433 |
|
| 434 |
retryErr, ok := err.(*ECHRejectionError) |
| 435 |
if !ok { |
| 436 |
log.Fatal(err) |
| 437 |
} |
| 438 |
if *expectNoECHRetryConfigs && len(retryErr.RetryConfigList) > 0 { |
| 439 |
log.Fatalf("expected no ECH retry configs, got some") |
| 440 |
} |
| 441 |
if *expectedECHRetryConfigs != "" { |
| 442 |
expectedRetryConfigs, err := base64.StdEncoding.DecodeString(*expectedECHRetryConfigs) |
| 443 |
if err != nil { |
| 444 |
log.Fatalf("failed to decode expected retry configs: %s", err) |
| 445 |
} |
| 446 |
if !bytes.Equal(retryErr.RetryConfigList, expectedRetryConfigs) { |
| 447 |
log.Fatalf("unexpected retry list returned: got %x, want %x", retryErr.RetryConfigList, expectedRetryConfigs) |
| 448 |
} |
| 449 |
} |
| 450 |
log.Fatalf("conn error: %s", err) |
| 451 |
} |
| 452 |
|
| 453 |
cs := tlsConn.ConnectionState() |
| 454 |
if cs.HandshakeComplete { |
| 455 |
if *expectALPN != "" && cs.NegotiatedProtocol != *expectALPN { |
| 456 |
log.Fatalf("unexpected protocol negotiated: want %q, got %q", *expectALPN, cs.NegotiatedProtocol) |
| 457 |
} |
| 458 |
|
| 459 |
if *selectALPN != "" && cs.NegotiatedProtocol != *selectALPN { |
| 460 |
log.Fatalf("unexpected protocol negotiated: want %q, got %q", *selectALPN, cs.NegotiatedProtocol) |
| 461 |
} |
| 462 |
|
| 463 |
if *expectVersion != 0 && cs.Version != uint16(*expectVersion) { |
| 464 |
log.Fatalf("expected ssl version %d, got %d", *expectVersion, cs.Version) |
| 465 |
} |
| 466 |
if *declineALPN && cs.NegotiatedProtocol != "" { |
| 467 |
log.Fatal("unexpected ALPN protocol") |
| 468 |
} |
| 469 |
if *expectECHAccepted && !cs.ECHAccepted { |
| 470 |
log.Fatal("expected ECH to be accepted, but connection state shows it was not") |
| 471 |
} else if i == 0 && *onInitialExpectECHAccepted && !cs.ECHAccepted { |
| 472 |
log.Fatal("expected ECH to be accepted, but connection state shows it was not") |
| 473 |
} else if i > 0 && *onResumeExpectECHAccepted && !cs.ECHAccepted { |
| 474 |
log.Fatal("expected ECH to be accepted on resumption, but connection state shows it was not") |
| 475 |
} else if i == 0 && !*expectECHAccepted && cs.ECHAccepted { |
| 476 |
log.Fatal("did not expect ECH, but it was accepted") |
| 477 |
} |
| 478 |
|
| 479 |
if *expectHRR && !cs.HelloRetryRequest { |
| 480 |
log.Fatal("expected HRR but did not do it") |
| 481 |
} |
| 482 |
|
| 483 |
if *expectNoHRR && cs.HelloRetryRequest { |
| 484 |
log.Fatal("expected no HRR but did do it") |
| 485 |
} |
| 486 |
|
| 487 |
if *expectSessionMiss && cs.DidResume { |
| 488 |
log.Fatal("unexpected session resumption") |
| 489 |
} |
| 490 |
|
| 491 |
if *expectedServerName != "" && cs.ServerName != *expectedServerName { |
| 492 |
log.Fatalf("unexpected server name: got %q, want %q", cs.ServerName, *expectedServerName) |
| 493 |
} |
| 494 |
} |
| 495 |
|
| 496 |
if *expectedCurve != "" { |
| 497 |
expectedCurveID, err := strconv.Atoi(*expectedCurve) |
| 498 |
if err != nil { |
| 499 |
log.Fatalf("failed to parse -expect-curve-id: %s", err) |
| 500 |
} |
| 501 |
if cs.CurveID != CurveID(expectedCurveID) { |
| 502 |
log.Fatalf("unexpected curve id: want %d, got %d", expectedCurveID, tlsConn.curveID) |
| 503 |
} |
| 504 |
} |
| 505 |
|
| 506 |
// TODO: implement testingOnlyPeerSignatureAlgorithm on resumption. |
| 507 |
if *expectedSigAlg != "" && !cs.DidResume { |
| 508 |
expectedSigAlgID, err := strconv.Atoi(*expectedSigAlg) |
| 509 |
if err != nil { |
| 510 |
log.Fatalf("failed to parse -expect-peer-signature-algorithm: %s", err) |
| 511 |
} |
| 512 |
if cs.testingOnlyPeerSignatureAlgorithm != SignatureScheme(expectedSigAlgID) { |
| 513 |
log.Fatalf("unexpected peer signature algorithm: want %s, got %s", SignatureScheme(expectedSigAlgID), cs.testingOnlyPeerSignatureAlgorithm) |
| 514 |
} |
| 515 |
} |
| 516 |
} |
| 517 |
} |
| 518 |
|
| 519 |
// If the test case produces an error, we don't want to immediately close the |
| 520 |
// TCP connection after generating an alert. The runner side may try to write |
| 521 |
// additional data to the connection before it reads the alert. If the conn |
| 522 |
// has already been torn down, then these writes will produce an unexpected |
| 523 |
// broken pipe err and fail the test. |
| 524 |
func orderlyShutdown(tlsConn *Conn) { |
| 525 |
// Flush any pending alert data |
| 526 |
tlsConn.flush() |
| 527 |
|
| 528 |
netConn := tlsConn.NetConn() |
| 529 |
tcpConn := netConn.(*net.TCPConn) |
| 530 |
tcpConn.CloseWrite() |
| 531 |
|
| 532 |
// Read and discard any data that was sent by the peer. |
| 533 |
buf := make([]byte, maxPlaintext) |
| 534 |
for { |
| 535 |
n, err := tcpConn.Read(buf) |
| 536 |
if n == 0 || err != nil { |
| 537 |
break |
| 538 |
} |
| 539 |
} |
| 540 |
|
| 541 |
tcpConn.CloseRead() |
| 542 |
} |
| 543 |
|
| 544 |
func TestBogoSuite(t *testing.T) { |
| 545 |
if testing.Short() { |
| 546 |
t.Skip("skipping in short mode") |
| 547 |
} |
| 548 |
if testenv.Builder() != "" && runtime.GOOS == "windows" { |
| 549 |
t.Skip("#66913: windows network connections are flakey on builders") |
| 550 |
} |
| 551 |
skipFIPS(t) |
| 552 |
|
| 553 |
// In order to make Go test caching work as expected, we stat the |
| 554 |
// bogo_config.json file, so that the Go testing hooks know that it is |
| 555 |
// important for this test and will invalidate a cached test result if the |
| 556 |
// file changes. |
| 557 |
if _, err := os.Stat("bogo_config.json"); err != nil { |
| 558 |
t.Fatal(err) |
| 559 |
} |
| 560 |
|
| 561 |
var bogoDir string |
| 562 |
if *bogoLocalDir != "" { |
| 563 |
ensureLocalBogo(t, *bogoLocalDir) |
| 564 |
bogoDir = *bogoLocalDir |
| 565 |
} else { |
| 566 |
bogoDir = cryptotest.FetchModule(t, "boringssl.googlesource.com/boringssl.git", boringsslModVer) |
| 567 |
} |
| 568 |
|
| 569 |
cwd, err := os.Getwd() |
| 570 |
if err != nil { |
| 571 |
t.Fatal(err) |
| 572 |
} |
| 573 |
|
| 574 |
resultsFile := filepath.Join(t.TempDir(), "results.json") |
| 575 |
|
| 576 |
args := []string{ |
| 577 |
"test", |
| 578 |
".", |
| 579 |
fmt.Sprintf("-shim-config=%s", filepath.Join(cwd, "bogo_config.json")), |
| 580 |
fmt.Sprintf("-shim-path=%s", testenv.Executable(t)), |
| 581 |
"-shim-extra-flags=-bogo-mode", |
| 582 |
"-allow-unimplemented", |
| 583 |
"-loose-errors", // TODO(roland): this should be removed eventually |
| 584 |
fmt.Sprintf("-json-output=%s", resultsFile), |
| 585 |
} |
| 586 |
if *bogoFilter != "" { |
| 587 |
args = append(args, fmt.Sprintf("-test=%s", *bogoFilter)) |
| 588 |
} |
| 589 |
|
| 590 |
cmd := testenv.Command(t, testenv.GoToolPath(t), args...) |
| 591 |
cmd.Dir = filepath.Join(bogoDir, "ssl/test/runner") |
| 592 |
out, err := cmd.CombinedOutput() |
| 593 |
// NOTE: we don't immediately check the error, because the failure could be either because |
| 594 |
// the runner failed for some unexpected reason, or because a test case failed, and we |
| 595 |
// cannot easily differentiate these cases. We check if the JSON results file was written, |
| 596 |
// which should only happen if the failure was because of a test failure, and use that |
| 597 |
// to determine the failure mode. |
| 598 |
|
| 599 |
resultsJSON, jsonErr := os.ReadFile(resultsFile) |
| 600 |
if jsonErr != nil { |
| 601 |
if err != nil { |
| 602 |
t.Fatalf("bogo failed: %s\n%s", err, out) |
| 603 |
} |
| 604 |
t.Fatalf("failed to read results JSON file: %s", jsonErr) |
| 605 |
} |
| 606 |
|
| 607 |
var results bogoResults |
| 608 |
if err := json.Unmarshal(resultsJSON, &results); err != nil { |
| 609 |
t.Fatalf("failed to parse results JSON: %s", err) |
| 610 |
} |
| 611 |
|
| 612 |
if *bogoReport != "" { |
| 613 |
if err := generateReport(results, *bogoReport); err != nil { |
| 614 |
t.Fatalf("failed to generate report: %v", err) |
| 615 |
} |
| 616 |
} |
| 617 |
|
| 618 |
// assertResults contains test results we want to make sure |
| 619 |
// are present in the output. They are only checked if -bogo-filter |
| 620 |
// was not passed. |
| 621 |
assertResults := map[string]string{ |
| 622 |
"CurveTest-Client-MLKEM-TLS13": "PASS", |
| 623 |
"CurveTest-Server-MLKEM-TLS13": "PASS", |
| 624 |
|
| 625 |
// Various signature algorithm tests checking that we enforce our |
| 626 |
// preferences on the peer. |
| 627 |
"ClientAuth-Enforced": "PASS", |
| 628 |
"ServerAuth-Enforced": "PASS", |
| 629 |
"ClientAuth-Enforced-TLS13": "PASS", |
| 630 |
"ServerAuth-Enforced-TLS13": "PASS", |
| 631 |
"VerifyPreferences-Advertised": "PASS", |
| 632 |
"VerifyPreferences-Enforced": "PASS", |
| 633 |
"Client-TLS12-NoSign-RSA_PKCS1_MD5_SHA1": "PASS", |
| 634 |
"Server-TLS12-NoSign-RSA_PKCS1_MD5_SHA1": "PASS", |
| 635 |
"Client-TLS13-NoSign-RSA_PKCS1_MD5_SHA1": "PASS", |
| 636 |
"Server-TLS13-NoSign-RSA_PKCS1_MD5_SHA1": "PASS", |
| 637 |
} |
| 638 |
|
| 639 |
for name, result := range results.Tests { |
| 640 |
// This is not really the intended way to do this... but... it works? |
| 641 |
t.Run(name, func(t *testing.T) { |
| 642 |
if result.Actual == "FAIL" && result.IsUnexpected { |
| 643 |
t.Fail() |
| 644 |
} |
| 645 |
if result.Error != "" { |
| 646 |
t.Log(result.Error) |
| 647 |
} |
| 648 |
if exp, ok := assertResults[name]; ok && exp != result.Actual { |
| 649 |
t.Errorf("unexpected result: got %s, want %s", result.Actual, exp) |
| 650 |
} |
| 651 |
delete(assertResults, name) |
| 652 |
if result.Actual == "SKIP" { |
| 653 |
t.SkipNow() |
| 654 |
} |
| 655 |
}) |
| 656 |
} |
| 657 |
if *bogoFilter == "" { |
| 658 |
// Anything still in assertResults did not show up in the results, so we should fail |
| 659 |
for name, expectedResult := range assertResults { |
| 660 |
t.Run(name, func(t *testing.T) { |
| 661 |
t.Fatalf("expected test to run with result %s, but it was not present in the test results", expectedResult) |
| 662 |
}) |
| 663 |
} |
| 664 |
} |
| 665 |
} |
| 666 |
|
| 667 |
// ensureLocalBogo fetches BoringSSL to localBogoDir at the correct revision |
| 668 |
// (from boringsslModVer) if localBogoDir doesn't already exist. |
| 669 |
// |
| 670 |
// If localBogoDir does exist, ensureLocalBogo fails the test if it isn't |
| 671 |
// a directory. |
| 672 |
func ensureLocalBogo(t *testing.T, localBogoDir string) { |
| 673 |
t.Helper() |
| 674 |
|
| 675 |
if stat, err := os.Stat(localBogoDir); err == nil { |
| 676 |
if !stat.IsDir() { |
| 677 |
t.Fatalf("local bogo dir (%q) exists but is not a directory", localBogoDir) |
| 678 |
} |
| 679 |
|
| 680 |
t.Logf("using local bogo checkout from %q", localBogoDir) |
| 681 |
return |
| 682 |
} else if !errors.Is(err, os.ErrNotExist) { |
| 683 |
t.Fatalf("failed to stat local bogo dir (%q): %v", localBogoDir, err) |
| 684 |
} |
| 685 |
|
| 686 |
testenv.MustHaveExecPath(t, "git") |
| 687 |
|
| 688 |
idx := strings.LastIndex(boringsslModVer, "-") |
| 689 |
if idx == -1 || idx == len(boringsslModVer)-1 { |
| 690 |
t.Fatalf("invalid boringsslModVer format: %q", boringsslModVer) |
| 691 |
} |
| 692 |
commitSHA := boringsslModVer[idx+1:] |
| 693 |
|
| 694 |
t.Logf("cloning boringssl@%s to %q", commitSHA, localBogoDir) |
| 695 |
cloneCmd := testenv.Command(t, "git", "clone", "--no-checkout", "https://boringssl.googlesource.com/boringssl", localBogoDir) |
| 696 |
if err := cloneCmd.Run(); err != nil { |
| 697 |
t.Fatalf("git clone failed: %v", err) |
| 698 |
} |
| 699 |
|
| 700 |
checkoutCmd := testenv.Command(t, "git", "checkout", commitSHA) |
| 701 |
checkoutCmd.Dir = localBogoDir |
| 702 |
if err := checkoutCmd.Run(); err != nil { |
| 703 |
t.Fatalf("git checkout failed: %v", err) |
| 704 |
} |
| 705 |
|
| 706 |
t.Logf("using fresh local bogo checkout from %q", localBogoDir) |
| 707 |
} |
| 708 |
|
| 709 |
func generateReport(results bogoResults, outPath string) error { |
| 710 |
data := reportData{ |
| 711 |
Results: results, |
| 712 |
Timestamp: time.Unix(int64(results.SecondsSinceEpoch), 0).Format("2006-01-02 15:04:05"), |
| 713 |
Revision: boringsslModVer, |
| 714 |
} |
| 715 |
|
| 716 |
tmpl := template.Must(template.New("report").Parse(reportTemplate)) |
| 717 |
file, err := os.Create(outPath) |
| 718 |
if err != nil { |
| 719 |
return err |
| 720 |
} |
| 721 |
defer file.Close() |
| 722 |
|
| 723 |
return tmpl.Execute(file, data) |
| 724 |
} |
| 725 |
|
| 726 |
// bogoResults is a copy of boringssl.googlesource.com/boringssl/testresults.Results |
| 727 |
type bogoResults struct { |
| 728 |
Version int `json:"version"` |
| 729 |
Interrupted bool `json:"interrupted"` |
| 730 |
PathDelimiter string `json:"path_delimiter"` |
| 731 |
SecondsSinceEpoch float64 `json:"seconds_since_epoch"` |
| 732 |
NumFailuresByType map[string]int `json:"num_failures_by_type"` |
| 733 |
Tests map[string]struct { |
| 734 |
Actual string `json:"actual"` |
| 735 |
Expected string `json:"expected"` |
| 736 |
IsUnexpected bool `json:"is_unexpected"` |
| 737 |
Error string `json:"error,omitempty"` |
| 738 |
} `json:"tests"` |
| 739 |
} |
| 740 |
|
| 741 |
type reportData struct { |
| 742 |
Results bogoResults |
| 743 |
SkipReasons map[string]string |
| 744 |
Timestamp string |
| 745 |
Revision string |
| 746 |
} |
| 747 |
|
| 748 |
const reportTemplate = ` |
| 749 |
<!DOCTYPE html> |
| 750 |
<html> |
| 751 |
<head> |
| 752 |
<title>BoGo Results Report</title> |
| 753 |
<style> |
| 754 |
body { font-family: monospace; margin: 20px; } |
| 755 |
.summary { background: #f5f5f5; padding: 10px; margin-bottom: 20px; } |
| 756 |
.controls { margin-bottom: 10px; } |
| 757 |
.controls input, select { margin-right: 10px; } |
| 758 |
table { width: 100%; border-collapse: collapse; table-layout: fixed; } |
| 759 |
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; vertical-align: top; } |
| 760 |
th { background-color: #f2f2f2; cursor: pointer; } |
| 761 |
.name-col { width: 30%; } |
| 762 |
.status-col { width: 8%; } |
| 763 |
.actual-col { width: 8%; } |
| 764 |
.expected-col { width: 8%; } |
| 765 |
.error-col { width: 26%; } |
| 766 |
.PASS { background-color: #d4edda; } |
| 767 |
.FAIL { background-color: #f8d7da; } |
| 768 |
.SKIP { background-color: #fff3cd; } |
| 769 |
.error { |
| 770 |
font-family: monospace; |
| 771 |
font-size: 0.9em; |
| 772 |
color: #721c24; |
| 773 |
white-space: pre-wrap; |
| 774 |
word-break: break-word; |
| 775 |
} |
| 776 |
</style> |
| 777 |
</head> |
| 778 |
<body> |
| 779 |
<h1>BoGo Results Report</h1> |
| 780 |
|
| 781 |
<div class="summary"> |
| 782 |
<strong>Generated:</strong> {{.Timestamp}} | <strong>BoGo Revision:</strong> {{.Revision}}<br> |
| 783 |
{{range $status, $count := .Results.NumFailuresByType}} |
| 784 |
<strong>{{$status}}:</strong> {{$count}} | |
| 785 |
{{end}} |
| 786 |
</div> |
| 787 |
|
| 788 |
<div class="controls"> |
| 789 |
<input type="text" id="search" placeholder="Search tests..." onkeyup="filterTests()"> |
| 790 |
<select id="statusFilter" onchange="filterTests()"> |
| 791 |
<option value="">All</option> |
| 792 |
<option value="FAIL">Failed</option> |
| 793 |
<option value="PASS">Passed</option> |
| 794 |
<option value="SKIP">Skipped</option> |
| 795 |
</select> |
| 796 |
</div> |
| 797 |
|
| 798 |
<table id="resultsTable"> |
| 799 |
<thead> |
| 800 |
<tr> |
| 801 |
<th class="name-col" onclick="sortBy('name')">Test Name</th> |
| 802 |
<th class="status-col" onclick="sortBy('status')">Status</th> |
| 803 |
<th class="actual-col" onclick="sortBy('actual')">Actual</th> |
| 804 |
<th class="expected-col" onclick="sortBy('expected')">Expected</th> |
| 805 |
<th class="error-col">Error</th> |
| 806 |
</tr> |
| 807 |
</thead> |
| 808 |
<tbody> |
| 809 |
{{range $name, $test := .Results.Tests}} |
| 810 |
<tr class="{{$test.Actual}}" data-name="{{$name}}" data-status="{{$test.Actual}}"> |
| 811 |
<td>{{$name}}</td> |
| 812 |
<td>{{$test.Actual}}</td> |
| 813 |
<td>{{$test.Actual}}</td> |
| 814 |
<td>{{$test.Expected}}</td> |
| 815 |
<td class="error">{{$test.Error}}</td> |
| 816 |
</tr> |
| 817 |
{{end}} |
| 818 |
</tbody> |
| 819 |
</table> |
| 820 |
|
| 821 |
<script> |
| 822 |
function filterTests() { |
| 823 |
const search = document.getElementById('search').value.toLowerCase(); |
| 824 |
const status = document.getElementById('statusFilter').value; |
| 825 |
const rows = document.querySelectorAll('#resultsTable tbody tr'); |
| 826 |
|
| 827 |
rows.forEach(row => { |
| 828 |
const name = row.dataset.name.toLowerCase(); |
| 829 |
const rowStatus = row.dataset.status; |
| 830 |
const matchesSearch = name.includes(search); |
| 831 |
const matchesStatus = !status || rowStatus === status; |
| 832 |
|
| 833 |
row.style.display = matchesSearch && matchesStatus ? '' : 'none'; |
| 834 |
}); |
| 835 |
} |
| 836 |
|
| 837 |
function sortBy(column) { |
| 838 |
const tbody = document.querySelector('#resultsTable tbody'); |
| 839 |
const rows = Array.from(tbody.querySelectorAll('tr')); |
| 840 |
|
| 841 |
rows.sort((a, b) => { |
| 842 |
if (column === 'status') { |
| 843 |
const statusOrder = {'FAIL': 0, 'PASS': 1, 'SKIP': 2}; |
| 844 |
const aStatus = a.dataset.status; |
| 845 |
const bStatus = b.dataset.status; |
| 846 |
if (aStatus !== bStatus) { |
| 847 |
return statusOrder[aStatus] - statusOrder[bStatus]; |
| 848 |
} |
| 849 |
return a.dataset.name.localeCompare(b.dataset.name); |
| 850 |
} else { |
| 851 |
return a.dataset.name.localeCompare(b.dataset.name); |
| 852 |
} |
| 853 |
}); |
| 854 |
|
| 855 |
rows.forEach(row => tbody.appendChild(row)); |
| 856 |
filterTests(); |
| 857 |
} |
| 858 |
|
| 859 |
sortBy("status"); |
| 860 |
</script> |
| 861 |
</body> |
| 862 |
</html> |
| 863 |
` |