| 6 | // |
| 7 | // https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | package runner |
| 16 |
| 17 | import ( |
| 18 | "bytes" |
| 19 | "crypto" |
| 20 | "crypto/ecdsa" |
| 21 | "crypto/ed25519" |
| 22 | "crypto/rsa" |
| 23 | "crypto/x509" |
| 24 | _ "embed" |
| 25 | "encoding/base64" |
| 26 | "encoding/binary" |
| 27 | "encoding/hex" |
| 28 | "encoding/json" |
| 29 | "encoding/pem" |
| 30 | "errors" |
| 31 | "flag" |
| 32 | "fmt" |
| 33 | "io" |
| 34 | "net" |
| 35 | "os" |
| 36 | "os/exec" |
| 37 | "path/filepath" |
| 38 | "runtime" |
| 39 | "slices" |
| 40 | "strconv" |
| 41 | "strings" |
| 42 | "sync" |
| 43 | "syscall" |
| 44 | "time" |
| 45 |
| 46 | "boringssl.googlesource.com/boringssl.git/util/testresult" |
| 47 | "golang.org/x/crypto/cryptobyte" |
| 48 | ) |
| 49 |
| 50 | var ( |
| 51 | useValgrind = flag.Bool("valgrind", false, "If true, run code under valgrind") |
| 52 | useGDB = flag.Bool("gdb", false, "If true, run BoringSSL code under gdb") |
| 53 | useLLDB = flag.Bool("lldb", false, "If true, run BoringSSL code under lldb") |
| 54 | useRR = flag.Bool("rr-record", false, "If true, run BoringSSL code under `rr record`.") |
| 55 | waitForDebugger = flag.Bool("wait-for-debugger", false, "If true, jobs will run one at a time and pause for a debugger to attach") |
| 56 | flagDebug = flag.Bool("debug", false, "Hexdump the contents of the connection") |
| 57 | mallocTest = flag.Int64("malloc-test", -1, "If non-negative, run each test with each malloc in turn failing from the given number onwards.") |
| 58 | mallocTestDebug = flag.Bool("malloc-test-debug", false, "If true, ask bssl_shim to abort rather than fail a malloc. This can be used with a specific value for --malloc-test to identity the malloc failing that is causing problems.") |
| 59 | jsonOutput = flag.String("json-output", "", "The file to output JSON results to.") |
| 60 | pipe = flag.Bool("pipe", false, "If true, print status output suitable for piping into another program.") |
| 61 | testToRun = flag.String("test", "", "Semicolon-separated patterns of tests to run, or empty to run all tests") |
| 62 | skipTest = flag.String("skip", "", "Semicolon-separated patterns of tests to skip") |
| 63 | allowHintMismatch = flag.String("allow-hint-mismatch", "", "Semicolon-separated patterns of tests where hints may mismatch") |
| 64 | numWorkersFlag = flag.Int("num-workers", runtime.NumCPU(), "The number of workers to run in parallel.") |
| 65 | shimPath = flag.String("shim-path", "../../../build/ssl/test/bssl_shim", "The location of the shim binary.") |
| 66 | shimExtraFlags = flag.String("shim-extra-flags", "", "Semicolon-separated extra flags to pass to the shim binary on each invocation.") |
| 67 | handshakerPath = flag.String("handshaker-path", "../../../build/ssl/test/handshaker", "The location of the handshaker binary.") |
| 68 | fuzzer = flag.Bool("fuzzer", false, "If true, tests against a BoringSSL built in fuzzer mode.") |
| 69 | transcriptDir = flag.String("transcript-dir", "", "The directory in which to write transcripts.") |
| 70 | idleTimeout = flag.Duration("idle-timeout", 15*time.Second, "The number of seconds to wait for a read or write to bssl_shim.") |
| 71 | deterministic = flag.Bool("deterministic", false, "If true, uses a deterministic PRNG in the runner.") |
| 72 | allowUnimplemented = flag.Bool("allow-unimplemented", false, "If true, report pass even if some tests are unimplemented.") |
| 73 | looseErrors = flag.Bool("loose-errors", false, "If true, allow shims to report an untranslated error code.") |
| 74 | shimConfigFile = flag.String("shim-config", "", "A config file to use to configure the tests for this shim.") |
| 75 | includeDisabled = flag.Bool("include-disabled", false, "If true, also runs disabled tests.") |
| 76 | repeatUntilFailure = flag.Bool("repeat-until-failure", false, "If true, the first selected test will be run repeatedly until failure.") |
| 77 | ) |
| 78 |
| 79 | // ShimConfigurations is used with the “json” package and represents a shim |
| 80 | // config file. |
| 81 | type ShimConfiguration struct { |
| 82 | // DisabledTests maps from a glob-based pattern to a freeform string. |
| 83 | // The glob pattern is used to exclude tests from being run and the |
| 84 | // freeform string is unparsed but expected to explain why the test is |
| 85 | // disabled. |
| 86 | DisabledTests map[string]string |
| 87 |
| 88 | // ErrorMap maps from expected error strings to the correct error |
| 89 | // string for the shim in question. For example, it might map |
| 90 | // “:NO_SHARED_CIPHER:” (a BoringSSL error string) to something |
| 91 | // like “SSL_ERROR_NO_CYPHER_OVERLAP”. |
| 92 | ErrorMap map[string][]string |
| 93 |
| 94 | // HalfRTTTickets is the number of half-RTT tickets the client should |
| 95 | // expect before half-RTT data when testing 0-RTT. |
| 96 | HalfRTTTickets int |
| 97 |
| 98 | // AllCurves is the list of all curve code points supported by the shim. |
| 99 | // This is currently used to control tests that enable all curves but may |
| 100 | // automatically disable tests in the future. |
| 101 | AllCurves []int |
| 102 |
| 103 | // MaxACKBuffer is the maximum number of received records the shim is |
| 104 | // expected to retain when ACKing. |
| 105 | MaxACKBuffer int |
| 106 | } |
| 107 |
| 108 | // Setup shimConfig defaults aligning with BoringSSL. |
| 109 | var shimConfig ShimConfiguration = ShimConfiguration{ |
| 110 | HalfRTTTickets: 2, |
| 111 | MaxACKBuffer: 32, |
| 112 | } |
| 113 |
| 114 | //go:embed rsa_2048_key.pem |
| 115 | var rsa2048KeyPEM []byte |
| 116 |
| 117 | //go:embed rsa_1024_key.pem |
| 118 | var rsa1024KeyPEM []byte |
| 119 |
| 120 | //go:embed ecdsa_p224_key.pem |
| 121 | var ecdsaP224KeyPEM []byte |
| 122 |
| 123 | //go:embed ecdsa_p256_key.pem |
| 124 | var ecdsaP256KeyPEM []byte |
| 125 |
| 126 | //go:embed ecdsa_p384_key.pem |
| 127 | var ecdsaP384KeyPEM []byte |
| 128 |
| 129 | //go:embed ecdsa_p521_key.pem |
| 130 | var ecdsaP521KeyPEM []byte |
| 131 |
| 132 | //go:embed ed25519_key.pem |
| 133 | var ed25519KeyPEM []byte |
| 134 |
| 135 | //go:embed channel_id_key.pem |
| 136 | var channelIDKeyPEM []byte |
| 137 |
| 138 | var ( |
| 139 | rsa1024Key rsa.PrivateKey |
| 140 | rsa2048Key rsa.PrivateKey |
| 141 |
| 142 | ecdsaP224Key ecdsa.PrivateKey |
| 143 | ecdsaP256Key ecdsa.PrivateKey |
| 144 | ecdsaP384Key ecdsa.PrivateKey |
| 145 | ecdsaP521Key ecdsa.PrivateKey |
| 146 |
| 147 | ed25519Key ed25519.PrivateKey |
| 148 |
| 149 | channelIDKey ecdsa.PrivateKey |
| 150 | ) |
| 151 |
| 152 | var channelIDKeyPath string |
| 153 |
| 154 | func initKeys() { |
| 155 | // Since key generation is not particularly cheap (especially RSA), and the |
| 156 | // runner is intended to run on systems which may be resouece constrained, |
| 157 | // we load keys from disk instead of dynamically generating them. We treat |
| 158 | // key files the same as dynamically generated certificates, writing them |
| 159 | // out to temporary files before passing them to the shim. |
| 160 |
| 161 | for _, k := range []struct { |
| 162 | pemBytes []byte |
| 163 | key *rsa.PrivateKey |
| 164 | }{ |
| 165 | {rsa1024KeyPEM, &rsa1024Key}, |
| 166 | {rsa2048KeyPEM, &rsa2048Key}, |
| 167 | } { |
| 168 | key, err := loadPEMKey(k.pemBytes) |
| 169 | if err != nil { |
| 170 | panic(fmt.Sprintf("failed to load RSA test key: %s", err)) |
| 171 | } |
| 172 | *k.key = *(key.(*rsa.PrivateKey)) |
| 173 | } |
| 174 |
| 175 | for _, k := range []struct { |
| 176 | pemBytes []byte |
| 177 | key *ecdsa.PrivateKey |
| 178 | }{ |
| 179 | {ecdsaP224KeyPEM, &ecdsaP224Key}, |
| 180 | {ecdsaP256KeyPEM, &ecdsaP256Key}, |
| 181 | {ecdsaP384KeyPEM, &ecdsaP384Key}, |
| 182 | {ecdsaP521KeyPEM, &ecdsaP521Key}, |
| 183 | {channelIDKeyPEM, &channelIDKey}, |
| 184 | } { |
| 185 | key, err := loadPEMKey(k.pemBytes) |
| 186 | if err != nil { |
| 187 | panic(fmt.Sprintf("failed to load ECDSA test key: %s", err)) |
| 188 | } |
| 189 | *k.key = *(key.(*ecdsa.PrivateKey)) |
| 190 | } |
| 191 |
| 192 | k, err := loadPEMKey(ed25519KeyPEM) |
| 193 | if err != nil { |
| 194 | panic(fmt.Sprintf("failed to load Ed25519 test key: %s", err)) |
| 195 | } |
| 196 | ed25519Key = k.(ed25519.PrivateKey) |
| 197 |
| 198 | channelIDKeyPath = writeTempKeyFile(&channelIDKey) |
| 199 | } |
| 200 |
| 201 | var channelIDBytes []byte |
| 202 |
| 203 | var ( |
| 204 | testOCSPResponse = []byte{1, 2, 3, 4} |
| 205 | testOCSPResponse2 = []byte{5, 6, 7, 8} |
| 206 | testSCTList = []byte{0, 6, 0, 4, 5, 6, 7, 8} |
| 207 | testSCTList2 = []byte{0, 6, 0, 4, 1, 2, 3, 4} |
| 208 | ) |
| 209 |
| 210 | var ( |
| 211 | testOCSPExtension = append([]byte{byte(extensionStatusRequest) >> 8, byte(extensionStatusRequest), 0, 8, statusTypeOCSP, 0, 0, 4}, testOCSPResponse...) |
| 212 | testSCTExtension = append([]byte{byte(extensionSignedCertificateTimestamp) >> 8, byte(extensionSignedCertificateTimestamp), 0, byte(len(testSCTList))}, testSCTList...) |
| 213 | ) |
| 214 |
| 215 | var ( |
| 216 | rsaCertificate Credential |
| 217 | rsaChainCertificate Credential |
| 218 | rsa1024Certificate Credential |
| 219 | ecdsaP224Certificate Credential |
| 220 | ecdsaP256Certificate Credential |
| 221 | ecdsaP384Certificate Credential |
| 222 | ecdsaP521Certificate Credential |
| 223 | ed25519Certificate Credential |
| 224 | garbageCertificate Credential |
| 225 | ) |
| 226 |
| 227 | func initCertificates() { |
| 228 | for _, def := range []struct { |
| 229 | name string |
| 230 | key crypto.Signer |
| 231 | out *Credential |
| 232 | }{ |
| 233 | {"Test RSA-1024 Cert", &rsa1024Key, &rsa1024Certificate}, |
| 234 | {"Test RSA-2048 Cert", &rsa2048Key, &rsaCertificate}, |
| 235 | {"Test ECDSA P-224 Cert", &ecdsaP224Key, &ecdsaP224Certificate}, |
| 236 | {"Test ECDSA P-256 Cert", &ecdsaP256Key, &ecdsaP256Certificate}, |
| 237 | {"Test ECDSA P-384 Cert", &ecdsaP384Key, &ecdsaP384Certificate}, |
| 238 | {"Test ECDSA P-521 Cert", &ecdsaP521Key, &ecdsaP521Certificate}, |
| 239 | {"Test Ed25519 Cert", ed25519Key, &ed25519Certificate}, |
| 240 | } { |
| 241 | template := *baseCertTemplate |
| 242 | template.Subject.CommonName = def.name |
| 243 | *def.out = generateSingleCertChain(&template, def.key) |
| 244 | } |
| 245 |
| 246 | channelIDBytes = make([]byte, 64) |
| 247 | writeIntPadded(channelIDBytes[:32], channelIDKey.X) |
| 248 | writeIntPadded(channelIDBytes[32:], channelIDKey.Y) |
| 249 |
| 250 | garbageCertificate.Certificate = [][]byte{[]byte("GARBAGE")} |
| 251 | garbageCertificate.PrivateKey = rsaCertificate.PrivateKey |
| 252 |
| 253 | // Build a basic three cert chain for testing chain specific things. |
| 254 | rootTmpl := *baseCertTemplate |
| 255 | rootTmpl.Subject.CommonName = "test root" |
| 256 | rootCert := generateTestCert(&rootTmpl, nil, &rsa2048Key) |
| 257 | intermediateTmpl := *baseCertTemplate |
| 258 | intermediateTmpl.Subject.CommonName = "test inter" |
| 259 | intermediateCert := generateTestCert(&intermediateTmpl, rootCert, &rsa2048Key) |
| 260 | leafTmpl := *baseCertTemplate |
| 261 | leafTmpl.IsCA, leafTmpl.BasicConstraintsValid = false, false |
| 262 | leafCert := generateTestCert(nil, intermediateCert, &rsa2048Key) |
| 263 |
| 264 | keyPath := writeTempKeyFile(&rsa2048Key) |
| 265 | rootCertPath, chainPath := writeTempCertFile([]*x509.Certificate{rootCert}), writeTempCertFile([]*x509.Certificate{leafCert, intermediateCert}) |
| 266 |
| 267 | rsaChainCertificate = Credential{ |
| 268 | Certificate: [][]byte{leafCert.Raw, intermediateCert.Raw}, |
| 269 | RootCertificate: rootCert.Raw, |
| 270 | PrivateKey: &rsa2048Key, |
| 271 | Leaf: leafCert, |
| 272 | ChainPath: chainPath, |
| 273 | KeyPath: keyPath, |
| 274 | RootPath: rootCertPath, |
| 275 | } |
| 276 | } |
| 277 |
| 278 | func flagInts(flagName string, vals []int) []string { |
| 279 | ret := make([]string, 0, 2*len(vals)) |
| 280 | for _, val := range vals { |
| 281 | ret = append(ret, flagName, strconv.Itoa(val)) |
| 282 | } |
| 283 | return ret |
| 284 | } |
| 285 |
| 286 | func base64FlagValue(in []byte) string { |
| 287 | return base64.StdEncoding.EncodeToString(in) |
| 288 | } |
| 289 |
| 290 | func useDebugger() bool { |
| 291 | return *useGDB || *useLLDB || *useRR || *waitForDebugger |
| 292 | } |
| 293 |
| 294 | func loadPEMKey(pemBytes []byte) (crypto.PrivateKey, error) { |
| 295 | block, _ := pem.Decode(pemBytes) |
| 296 | if block == nil { |
| 297 | return nil, fmt.Errorf("no PEM block found") |
| 298 | } |
| 299 |
| 300 | if block.Type != "PRIVATE KEY" { |
| 301 | return nil, fmt.Errorf("unexpected PEM type (expected \"PRIVATE KEY\"): %s", block.Type) |
| 302 | } |
| 303 |
| 304 | k, err := x509.ParsePKCS8PrivateKey(block.Bytes) |
| 305 | if err != nil { |
| 306 | return nil, fmt.Errorf("failed to parse PKCS#8 key: %s", err) |
| 307 | } |
| 308 |
| 309 | return k, nil |
| 310 | } |
| 311 |
| 312 | // recordVersionToWire maps a record-layer protocol version to its wire |
| 313 | // representation. |
| 314 | func recordVersionToWire(vers uint16, protocol protocol) uint16 { |
| 315 | if protocol == dtls { |
| 316 | switch vers { |
| 317 | case VersionTLS12: |
| 318 | return VersionDTLS12 |
| 319 | case VersionTLS10: |
| 320 | return VersionDTLS10 |
| 321 | } |
| 322 | } else { |
| 323 | switch vers { |
| 324 | case VersionSSL30, VersionTLS10, VersionTLS11, VersionTLS12: |
| 325 | return vers |
| 326 | } |
| 327 | } |
| 328 |
| 329 | panic("unknown version") |
| 330 | } |
| 331 |
| 332 | // encodeDERValues encodes a series of bytestrings in comma-separated-hex form. |
| 333 | func encodeDERValues(values [][]byte) string { |
| 334 | var ret string |
| 335 | for i, v := range values { |
| 336 | if i > 0 { |
| 337 | ret += "," |
| 338 | } |
| 339 | ret += hex.EncodeToString(v) |
| 340 | } |
| 341 |
| 342 | return ret |
| 343 | } |
| 344 |
| 345 | func decodeHexOrPanic(in string) []byte { |
| 346 | ret, err := hex.DecodeString(in) |
| 347 | if err != nil { |
| 348 | panic(err) |
| 349 | } |
| 350 | return ret |
| 351 | } |
| 352 |
| 353 | type testType int |
| 354 |
| 355 | const ( |
| 356 | clientTest testType = iota |
| 357 | serverTest |
| 358 | ) |
| 359 |
| 360 | func (t testType) String() string { |
| 361 | switch t { |
| 362 | case clientTest: |
| 363 | return "Client" |
| 364 | case serverTest: |
| 365 | return "Server" |
| 366 | } |
| 367 | panic(fmt.Sprintf("bad test type %d", t)) |
| 368 | } |
| 369 |
| 370 | type protocol int |
| 371 |
| 372 | const ( |
| 373 | tls protocol = iota |
| 374 | dtls |
| 375 | quic |
| 376 | ) |
| 377 |
| 378 | func (p protocol) String() string { |
| 379 | switch p { |
| 380 | case tls: |
| 381 | return "TLS" |
| 382 | case dtls: |
| 383 | return "DTLS" |
| 384 | case quic: |
| 385 | return "QUIC" |
| 386 | } |
| 387 | return "unknown protocol" |
| 388 | } |
| 389 |
| 390 | const ( |
| 391 | alpn = 1 |
| 392 | npn = 2 |
| 393 | ) |
| 394 |
| 395 | // connectionExpectations contains connection-level test expectations to check |
| 396 | // on the runner side. |
| 397 | type connectionExpectations struct { |
| 398 | // version, if non-zero, specifies the TLS version that must be negotiated. |
| 399 | version uint16 |
| 400 | // cipher, if non-zero, specifies the TLS cipher suite that should be |
| 401 | // negotiated. |
| 402 | cipher uint16 |
| 403 | // channelID controls whether the connection should have negotiated a |
| 404 | // Channel ID with channelIDKey. |
| 405 | channelID bool |
| 406 | // nextProto controls whether the connection should negotiate a next |
| 407 | // protocol via NPN or ALPN. |
| 408 | nextProto string |
| 409 | // noNextProto, if true, means that no next protocol should be negotiated. |
| 410 | noNextProto bool |
| 411 | // nextProtoType, if non-zero, is the next protocol negotiation mechanism. |
| 412 | nextProtoType int |
| 413 | // srtpProtectionProfile is the DTLS-SRTP profile that should be negotiated. |
| 414 | // If zero, none should be negotiated. |
| 415 | srtpProtectionProfile uint16 |
| 416 | // peerSignatureAlgorithm, if not zero, is the signature algorithm that the |
| 417 | // peer should have used in the handshake. |
| 418 | peerSignatureAlgorithm signatureAlgorithm |
| 419 | // curveID, if not zero, is the curve that the handshake should have used. |
| 420 | curveID CurveID |
| 421 | // peerCertificate, if not nil, is the credential the peer is expected to |
| 422 | // send. |
| 423 | peerCertificate *Credential |
| 424 | // quicTransportParams contains the QUIC transport parameters that are to be |
| 425 | // sent by the peer using codepoint 57. |
| 426 | quicTransportParams []byte |
| 427 | // quicTransportParamsLegacy contains the QUIC transport parameters that are |
| 428 | // to be sent by the peer using legacy codepoint 0xffa5. |
| 429 | quicTransportParamsLegacy []byte |
| 430 | // peerApplicationSettings are the expected application settings for the |
| 431 | // connection. If nil, no application settings are expected. |
| 432 | peerApplicationSettings []byte |
| 433 | // peerApplicationSettingsOld are the expected application settings for |
| 434 | // the connection that are to be sent by the peer using old codepoint. |
| 435 | // If nil, no application settings are expected. |
| 436 | peerApplicationSettingsOld []byte |
| 437 | // echAccepted is whether ECH should have been accepted on this connection. |
| 438 | echAccepted bool |
| 439 | } |
| 440 |
| 441 | type testCase struct { |
| 442 | testType testType |
| 443 | protocol protocol |
| 444 | name string |
| 445 | config Config |
| 446 | shouldFail bool |
| 447 | expectedError string |
| 448 | // expectedLocalError, if not empty, contains a substring that must be |
| 449 | // found in the local error. |
| 450 | expectedLocalError string |
| 451 | // expectations contains test expectations for the initial |
| 452 | // connection. |
| 453 | expectations connectionExpectations |
| 454 | // resumeExpectations, if non-nil, contains test expectations for the |
| 455 | // resumption connection. If nil, |expectations| is used. |
| 456 | resumeExpectations *connectionExpectations |
| 457 | // messageLen is the length, in bytes, of the test message that will be |
| 458 | // sent. |
| 459 | messageLen int |
| 460 | // messageCount is the number of test messages that will be sent. |
| 461 | messageCount int |
| 462 | // resumeSession controls whether a second connection should be tested |
| 463 | // which attempts to resume the first session. |
| 464 | resumeSession bool |
| 465 | // resumeRenewedSession controls whether a third connection should be |
| 466 | // tested which attempts to resume the second connection's session. |
| 467 | resumeRenewedSession bool |
| 468 | // expectResumeRejected, if true, specifies that the attempted |
| 469 | // resumption must be rejected by the client. This is only valid for a |
| 470 | // serverTest. |
| 471 | expectResumeRejected bool |
| 472 | // resumeConfig, if not nil, points to a Config to be used on |
| 473 | // resumption. Unless newSessionsOnResume is set, |
| 474 | // SessionTicketKey, ServerSessionCache, and |
| 475 | // ClientSessionCache are copied from the initial connection's |
| 476 | // config. If nil, the initial connection's config is used. |
| 477 | resumeConfig *Config |
| 478 | // newSessionsOnResume, if true, will cause resumeConfig to |
| 479 | // use a different session resumption context. |
| 480 | newSessionsOnResume bool |
| 481 | // noSessionCache, if true, will cause the server to run without a |
| 482 | // session cache. |
| 483 | noSessionCache bool |
| 484 | // sendPrefix sends a prefix on the socket before actually performing a |
| 485 | // handshake. |
| 486 | sendPrefix string |
| 487 | // shimWritesFirst controls whether the shim sends an initial "hello" |
| 488 | // message before doing a roundtrip with the runner. |
| 489 | shimWritesFirst bool |
| 490 | // readWithUnfinishedWrite behaves like shimWritesFirst, but the shim |
| 491 | // does not complete the write until responding to the first runner |
| 492 | // message. |
| 493 | readWithUnfinishedWrite bool |
| 494 | // shimShutsDown, if true, runs a test where the shim shuts down the |
| 495 | // connection immediately after the handshake rather than echoing |
| 496 | // messages from the runner. The runner will default to not sending |
| 497 | // application data. |
| 498 | shimShutsDown bool |
| 499 | // renegotiate indicates the number of times the connection should be |
| 500 | // renegotiated during the exchange. |
| 501 | renegotiate int |
| 502 | // sendHalfHelloRequest, if true, causes the server to send half a |
| 503 | // HelloRequest when the handshake completes. |
| 504 | sendHalfHelloRequest bool |
| 505 | // renegotiateCiphers is a list of ciphersuite ids that will be |
| 506 | // switched in just before renegotiation. |
| 507 | renegotiateCiphers []uint16 |
| 508 | // replayWrites, if true, configures the underlying transport |
| 509 | // to replay every write it makes in DTLS tests. |
| 510 | replayWrites bool |
| 511 | // damageFirstWrite, if true, configures the underlying transport to |
| 512 | // damage the final byte of the first application data write. |
| 513 | damageFirstWrite bool |
| 514 | // exportKeyingMaterial, if non-zero, configures the test to exchange |
| 515 | // keying material and verify they match. |
| 516 | exportKeyingMaterial int |
| 517 | exportLabel string |
| 518 | exportContext string |
| 519 | useExportContext bool |
| 520 | // flags, if not empty, contains a list of command-line flags that will |
| 521 | // be passed to the shim program. |
| 522 | flags []string |
| 523 | // testTLSUnique, if true, causes the shim to send the tls-unique value |
| 524 | // which will be compared against the expected value. |
| 525 | testTLSUnique bool |
| 526 | // sendEmptyRecords is the number of consecutive empty records to send |
| 527 | // before each test message. |
| 528 | sendEmptyRecords int |
| 529 | // sendWarningAlerts is the number of consecutive warning alerts to send |
| 530 | // before each test message. |
| 531 | sendWarningAlerts int |
| 532 | // sendUserCanceledAlerts is the number of consecutive user_canceled alerts to |
| 533 | // send before each test message. |
| 534 | sendUserCanceledAlerts int |
| 535 | // sendBogusAlertType, if true, causes a bogus alert of invalid type to |
| 536 | // be sent before each test message. |
| 537 | sendBogusAlertType bool |
| 538 | // sendKeyUpdates is the number of consecutive key updates to send |
| 539 | // before and after the test message. |
| 540 | sendKeyUpdates int |
| 541 | // keyUpdateRequest is the KeyUpdateRequest value to send in KeyUpdate messages. |
| 542 | keyUpdateRequest byte |
| 543 | // shimSendsKeyUpdateBeforeRead indicates the shim should send a KeyUpdate |
| 544 | // message before each read. |
| 545 | shimSendsKeyUpdateBeforeRead bool |
| 546 | // expectUnsolicitedKeyUpdate makes the test expect a one or more KeyUpdate |
| 547 | // messages while reading data from the shim. Don't use this in combination |
| 548 | // with any of the fields that send a KeyUpdate otherwise any received |
| 549 | // KeyUpdate might not be as unsolicited as expected. |
| 550 | expectUnsolicitedKeyUpdate bool |
| 551 | // expectMessageDropped, if true, means the test message is expected to |
| 552 | // be dropped by the client rather than echoed back. |
| 553 | expectMessageDropped bool |
| 554 | // shimPrefix is the prefix that the shim will send to the server. |
| 555 | shimPrefix string |
| 556 | // resumeShimPrefix is the prefix that the shim will send to the server on a |
| 557 | // resumption. |
| 558 | resumeShimPrefix string |
| 559 | // exportTrafficSecrets, if true, configures the test to export the TLS 1.3 |
| 560 | // traffic secrets and confirms that they match. |
| 561 | exportTrafficSecrets bool |
| 562 | // skipTransportParamsConfig, if true, will skip automatic configuration of |
| 563 | // sending QUIC transport parameters when protocol == quic. |
| 564 | skipTransportParamsConfig bool |
| 565 | // skipQUICALPNConfig, if true, will skip automatic configuration of |
| 566 | // sending a fake ALPN when protocol == quic. |
| 567 | skipQUICALPNConfig bool |
| 568 | // earlyData, if true, configures default settings for an early data test. |
| 569 | // expectEarlyDataRejected controls whether the test is for early data |
| 570 | // accept or reject. In a client test, the shim will be configured to send |
| 571 | // an initial write in early data which, on accept, the runner will enforce. |
| 572 | // In a server test, the runner will send some default message in early |
| 573 | // data, which the shim is expected to echo in half-RTT. |
| 574 | earlyData bool |
| 575 | // expectEarlyDataRejected, if earlyData is true, is whether early data is |
| 576 | // expected to be rejected. In a client test, this controls whether the shim |
| 577 | // should retry for early rejection. In a server test, this is whether the |
| 578 | // test expects the shim to reject early data. |
| 579 | expectEarlyDataRejected bool |
| 580 | // skipSplitHandshake, if true, will skip the generation of a split |
| 581 | // handshake copy of the test. |
| 582 | skipSplitHandshake bool |
| 583 | // skipHints, if true, will skip the generation of a handshake hints copy of |
| 584 | // the test. |
| 585 | skipHints bool |
| 586 | // skipVersionNameCheck, if true, will skip the consistency check between |
| 587 | // test name and the versions. |
| 588 | skipVersionNameCheck bool |
| 589 | // shimCertificate, if not nil, is the default credential which should be |
| 590 | // configured at the shim. If set, it must be an X.509 credential. |
| 591 | shimCertificate *Credential |
| 592 | // handshakerCertificate, if not nil, overrides the default credential which |
| 593 | // on the handshaker. |
| 594 | handshakerCertificate *Credential |
| 595 | // shimCredentials is a list of credentials which should be configured at |
| 596 | // the shim. It differs from shimCertificate only in whether the old or |
| 597 | // new APIs are used. |
| 598 | shimCredentials []*Credential |
| 599 | resumeShimCredentials []*Credential |
| 600 | } |
| 601 |
| 602 | var testCases []testCase |
| 603 |
| 604 | func appendTranscript(path string, data []byte) error { |
| 605 | if len(data) == 0 { |
| 606 | return nil |
| 607 | } |
| 608 |
| 609 | settings, err := os.ReadFile(path) |
| 610 | if err != nil { |
| 611 | if !os.IsNotExist(err) { |
| 612 | return err |
| 613 | } |
| 614 | // If the shim aborted before writing a file, use a default |
| 615 | // settings block, so the transcript is still somewhat valid. |
| 616 | settings = []byte{0, 0} // kDataTag |
| 617 | } |
| 618 |
| 619 | settings = append(settings, data...) |
| 620 | return os.WriteFile(path, settings, 0644) |
| 621 | } |
| 622 |
| 623 | // A timeoutConn implements an idle timeout on each Read and Write operation. |
| 624 | type timeoutConn struct { |
| 625 | net.Conn |
| 626 | timeout time.Duration |
| 627 | } |
| 628 |
| 629 | func (t *timeoutConn) Read(b []byte) (int, error) { |
| 630 | if !*useGDB { |
| 631 | if err := t.SetReadDeadline(time.Now().Add(t.timeout)); err != nil { |
| 632 | return 0, err |
| 633 | } |
| 634 | } |
| 635 | return t.Conn.Read(b) |
| 636 | } |
| 637 |
| 638 | func (t *timeoutConn) Write(b []byte) (int, error) { |
| 639 | if !*useGDB { |
| 640 | if err := t.SetWriteDeadline(time.Now().Add(t.timeout)); err != nil { |
| 641 | return 0, err |
| 642 | } |
| 643 | } |
| 644 | return t.Conn.Write(b) |
| 645 | } |
| 646 |
| 647 | func makeTestMessage(msgIdx int, messageLen int) []byte { |
| 648 | testMessage := make([]byte, messageLen) |
| 649 | for i := range testMessage { |
| 650 | testMessage[i] = 0x42 ^ byte(msgIdx) |
| 651 | } |
| 652 | return testMessage |
| 653 | } |
| 654 |
| 655 | func expectedReply(b []byte) []byte { |
| 656 | ret := make([]byte, len(b)) |
| 657 | for i, v := range b { |
| 658 | ret[i] = v ^ 0xff |
| 659 | } |
| 660 | return ret |
| 661 | } |
| 662 |
| 663 | func doExchange(test *testCase, config *Config, conn net.Conn, isResume bool, transcripts *[][]byte, num int) error { |
| 664 | if !test.noSessionCache { |
| 665 | if config.ClientSessionCache == nil { |
| 666 | config.ClientSessionCache = NewLRUClientSessionCache(1) |
| 667 | } |
| 668 | if config.ServerSessionCache == nil { |
| 669 | config.ServerSessionCache = NewLRUServerSessionCache(1) |
| 670 | } |
| 671 | } |
| 672 | if test.testType != clientTest { |
| 673 | // Supply a ServerName to ensure a constant session cache key, |
| 674 | // rather than falling back to net.Conn.RemoteAddr. |
| 675 | if len(config.ServerName) == 0 { |
| 676 | config.ServerName = "test" |
| 677 | } |
| 678 | } |
| 679 |
| 680 | if *fuzzer { |
| 681 | config.Bugs.NullAllCiphers = true |
| 682 | } |
| 683 | if *deterministic { |
| 684 | config.Time = func() time.Time { return time.Unix(1234, 1234) } |
| 685 | } |
| 686 |
| 687 | if !useDebugger() { |
| 688 | conn = &timeoutConn{conn, *idleTimeout} |
| 689 | } |
| 690 |
| 691 | if test.protocol == dtls { |
| 692 | config.Bugs.PacketAdaptor = newPacketAdaptor(conn) |
| 693 | conn = config.Bugs.PacketAdaptor |
| 694 | } |
| 695 |
| 696 | if *flagDebug || len(*transcriptDir) != 0 { |
| 697 | local, peer := "client", "server" |
| 698 | if test.testType == clientTest { |
| 699 | local, peer = peer, local |
| 700 | } |
| 701 | connDebug := &recordingConn{ |
| 702 | Conn: conn, |
| 703 | isDatagram: test.protocol == dtls, |
| 704 | local: local, |
| 705 | peer: peer, |
| 706 | } |
| 707 | conn = connDebug |
| 708 | if *flagDebug { |
| 709 | defer connDebug.WriteTo(os.Stdout) |
| 710 | } |
| 711 | if len(*transcriptDir) != 0 { |
| 712 | defer func() { |
| 713 | if num == len(*transcripts) { |
| 714 | *transcripts = append(*transcripts, connDebug.Transcript()) |
| 715 | } else { |
| 716 | panic("transcripts are out of sync") |
| 717 | } |
| 718 | }() |
| 719 |
| 720 | // Record ClientHellos for the decode_client_hello_inner fuzzer. |
| 721 | var clientHelloCount int |
| 722 | config.Bugs.RecordClientHelloInner = func(encodedInner, outer []byte) error { |
| 723 | name := fmt.Sprintf("%s-%d-%d", test.name, num, clientHelloCount) |
| 724 | clientHelloCount++ |
| 725 | dir := filepath.Join(*transcriptDir, "decode_client_hello_inner") |
| 726 | if err := os.MkdirAll(dir, 0755); err != nil { |
| 727 | return err |
| 728 | } |
| 729 | bb := cryptobyte.NewBuilder(nil) |
| 730 | addUint24LengthPrefixedBytes(bb, encodedInner) |
| 731 | bb.AddBytes(outer) |
| 732 | return os.WriteFile(filepath.Join(dir, name), bb.BytesOrPanic(), 0644) |
| 733 | } |
| 734 | } |
| 735 |
| 736 | if config.Bugs.PacketAdaptor != nil { |
| 737 | config.Bugs.PacketAdaptor.debug = connDebug |
| 738 | } |
| 739 | } |
| 740 | if test.protocol == quic { |
| 741 | config.Bugs.MockQUICTransport = newMockQUICTransport(conn) |
| 742 | // The MockQUICTransport will panic if Read or Write is |
| 743 | // called. When a MockQUICTransport is set, separate |
| 744 | // methods should be used to actually read and write |
| 745 | // records. By setting the conn to it here, it ensures |
| 746 | // Read or Write aren't accidentally used instead of the |
| 747 | // methods provided by MockQUICTransport. |
| 748 | conn = config.Bugs.MockQUICTransport |
| 749 | } |
| 750 |
| 751 | if test.replayWrites { |
| 752 | conn = newReplayAdaptor(conn) |
| 753 | } |
| 754 |
| 755 | var connDamage *damageAdaptor |
| 756 | if test.damageFirstWrite { |
| 757 | connDamage = newDamageAdaptor(conn) |
| 758 | conn = connDamage |
| 759 | } |
| 760 |
| 761 | if test.sendPrefix != "" { |
| 762 | if _, err := conn.Write([]byte(test.sendPrefix)); err != nil { |
| 763 | return err |
| 764 | } |
| 765 | } |
| 766 |
| 767 | var tlsConn *Conn |
| 768 | if test.testType == clientTest { |
| 769 | if test.protocol == dtls { |
| 770 | tlsConn = DTLSServer(conn, config) |
| 771 | } else { |
| 772 | tlsConn = Server(conn, config) |
| 773 | } |
| 774 | } else { |
| 775 | config.InsecureSkipVerify = true |
| 776 | if test.protocol == dtls { |
| 777 | tlsConn = DTLSClient(conn, config) |
| 778 | } else { |
| 779 | tlsConn = Client(conn, config) |
| 780 | } |
| 781 | } |
| 782 | defer tlsConn.Close() |
| 783 |
| 784 | if err := tlsConn.Handshake(); err != nil { |
| 785 | return err |
| 786 | } |
| 787 |
| 788 | expectations := &test.expectations |
| 789 | if isResume && test.resumeExpectations != nil { |
| 790 | expectations = test.resumeExpectations |
| 791 | } |
| 792 | connState := tlsConn.ConnectionState() |
| 793 | if vers := connState.Version; expectations.version != 0 && vers != expectations.version { |
| 794 | return fmt.Errorf("got version %x, expected %x", vers, expectations.version) |
| 795 | } |
| 796 |
| 797 | if cipher := connState.CipherSuite; expectations.cipher != 0 && cipher != expectations.cipher { |
| 798 | return fmt.Errorf("got cipher %x, expected %x", cipher, expectations.cipher) |
| 799 | } |
| 800 | if didResume := connState.DidResume; isResume && didResume == test.expectResumeRejected { |
| 801 | return fmt.Errorf("didResume is %t, but we expected the opposite", didResume) |
| 802 | } |
| 803 |
| 804 | if expectations.channelID { |
| 805 | channelID := connState.ChannelID |
| 806 | if channelID == nil { |
| 807 | return fmt.Errorf("no channel ID negotiated") |
| 808 | } |
| 809 | if channelID.Curve != channelIDKey.Curve || |
| 810 | channelIDKey.X.Cmp(channelIDKey.X) != 0 || |
| 811 | channelIDKey.Y.Cmp(channelIDKey.Y) != 0 { |
| 812 | return fmt.Errorf("incorrect channel ID") |
| 813 | } |
| 814 | } else if connState.ChannelID != nil { |
| 815 | return fmt.Errorf("channel ID unexpectedly negotiated") |
| 816 | } |
| 817 |
| 818 | if expected := expectations.nextProto; expected != "" { |
| 819 | if actual := connState.NegotiatedProtocol; actual != expected { |
| 820 | return fmt.Errorf("next proto mismatch: got %s, wanted %s", actual, expected) |
| 821 | } |
| 822 | } |
| 823 |
| 824 | if expectations.noNextProto { |
| 825 | if actual := connState.NegotiatedProtocol; actual != "" { |
| 826 | return fmt.Errorf("got unexpected next proto %s", actual) |
| 827 | } |
| 828 | } |
| 829 |
| 830 | if expectations.nextProtoType != 0 { |
| 831 | if (expectations.nextProtoType == alpn) != connState.NegotiatedProtocolFromALPN { |
| 832 | return fmt.Errorf("next proto type mismatch") |
| 833 | } |
| 834 | } |
| 835 |
| 836 | if expectations.peerApplicationSettings != nil { |
| 837 | if !connState.HasApplicationSettings { |
| 838 | return errors.New("application settings should have been negotiated") |
| 839 | } |
| 840 | if !bytes.Equal(connState.PeerApplicationSettings, expectations.peerApplicationSettings) { |
| 841 | return fmt.Errorf("peer application settings mismatch: got %q, wanted %q", connState.PeerApplicationSettings, expectations.peerApplicationSettings) |
| 842 | } |
| 843 | } else if connState.HasApplicationSettings { |
| 844 | return errors.New("application settings unexpectedly negotiated") |
| 845 | } |
| 846 |
| 847 | if expectations.peerApplicationSettingsOld != nil { |
| 848 | if !connState.HasApplicationSettingsOld { |
| 849 | return errors.New("old application settings should have been negotiated") |
| 850 | } |
| 851 | if !bytes.Equal(connState.PeerApplicationSettingsOld, expectations.peerApplicationSettingsOld) { |
| 852 | return fmt.Errorf("old peer application settings mismatch: got %q, wanted %q", connState.PeerApplicationSettingsOld, expectations.peerApplicationSettingsOld) |
| 853 | } |
| 854 | } else if connState.HasApplicationSettingsOld { |
| 855 | return errors.New("old application settings unexpectedly negotiated") |
| 856 | } |
| 857 |
| 858 | if p := connState.SRTPProtectionProfile; p != expectations.srtpProtectionProfile { |
| 859 | return fmt.Errorf("SRTP profile mismatch: got %d, wanted %d", p, expectations.srtpProtectionProfile) |
| 860 | } |
| 861 |
| 862 | if expected := expectations.peerSignatureAlgorithm; expected != 0 && expected != connState.PeerSignatureAlgorithm { |
| 863 | return fmt.Errorf("expected peer to use signature algorithm %04x, but got %04x", expected, connState.PeerSignatureAlgorithm) |
| 864 | } |
| 865 |
| 866 | if expected := expectations.curveID; expected != 0 && expected != connState.CurveID { |
| 867 | return fmt.Errorf("expected peer to use curve %04x, but got %04x", expected, connState.CurveID) |
| 868 | } |
| 869 |
| 870 | if expected := expectations.peerCertificate; expected != nil { |
| 871 | if len(connState.PeerCertificates) != len(expected.Certificate) { |
| 872 | return fmt.Errorf("expected peer to send %d certificates, but got %d", len(connState.PeerCertificates), len(expected.Certificate)) |
| 873 | } |
| 874 | for i, cert := range connState.PeerCertificates { |
| 875 | if !bytes.Equal(cert.Raw, expected.Certificate[i]) { |
| 876 | return fmt.Errorf("peer certificate %d did not match", i+1) |
| 877 | } |
| 878 | } |
| 879 |
| 880 | if !bytes.Equal(connState.OCSPResponse, expected.OCSPStaple) { |
| 881 | return fmt.Errorf("peer OCSP response did not match") |
| 882 | } |
| 883 |
| 884 | if !bytes.Equal(connState.SCTList, expected.SignedCertificateTimestampList) { |
| 885 | return fmt.Errorf("peer SCT list did not match") |
| 886 | } |
| 887 |
| 888 | if expected.Type == CredentialTypeDelegated { |
| 889 | if connState.PeerDelegatedCredential == nil { |
| 890 | return fmt.Errorf("peer unexpectedly did not use delegated credentials") |
| 891 | } |
| 892 | if !bytes.Equal(expected.DelegatedCredential, connState.PeerDelegatedCredential) { |
| 893 | return fmt.Errorf("peer delegated credential did not match") |
| 894 | } |
| 895 | } else if connState.PeerDelegatedCredential != nil { |
| 896 | return fmt.Errorf("peer unexpectedly used delegated credentials") |
| 897 | } |
| 898 | } |
| 899 |
| 900 | if len(expectations.quicTransportParams) > 0 { |
| 901 | if !bytes.Equal(expectations.quicTransportParams, connState.QUICTransportParams) { |
| 902 | return errors.New("Peer did not send expected QUIC transport params") |
| 903 | } |
| 904 | } |
| 905 |
| 906 | if len(expectations.quicTransportParamsLegacy) > 0 { |
| 907 | if !bytes.Equal(expectations.quicTransportParamsLegacy, connState.QUICTransportParamsLegacy) { |
| 908 | return errors.New("Peer did not send expected legacy QUIC transport params") |
| 909 | } |
| 910 | } |
| 911 |
| 912 | if expectations.echAccepted { |
| 913 | if !connState.ECHAccepted { |
| 914 | return errors.New("tls: server did not accept ECH") |
| 915 | } |
| 916 | } else { |
| 917 | if connState.ECHAccepted { |
| 918 | return errors.New("tls: server unexpectedly accepted ECH") |
| 919 | } |
| 920 | } |
| 921 |
| 922 | if test.exportKeyingMaterial > 0 { |
| 923 | actual := make([]byte, test.exportKeyingMaterial) |
| 924 | if _, err := io.ReadFull(tlsConn, actual); err != nil { |
| 925 | return err |
| 926 | } |
| 927 | expected, err := tlsConn.ExportKeyingMaterial(test.exportKeyingMaterial, []byte(test.exportLabel), []byte(test.exportContext), test.useExportContext) |
| 928 | if err != nil { |
| 929 | return err |
| 930 | } |
| 931 | if !bytes.Equal(actual, expected) { |
| 932 | return fmt.Errorf("keying material mismatch; got %x, wanted %x", actual, expected) |
| 933 | } |
| 934 | } |
| 935 |
| 936 | if test.exportTrafficSecrets { |
| 937 | secretLenBytes := make([]byte, 2) |
| 938 | if _, err := io.ReadFull(tlsConn, secretLenBytes); err != nil { |
| 939 | return err |
| 940 | } |
| 941 | secretLen := binary.LittleEndian.Uint16(secretLenBytes) |
| 942 |
| 943 | theirReadSecret := make([]byte, secretLen) |
| 944 | theirWriteSecret := make([]byte, secretLen) |
| 945 | if _, err := io.ReadFull(tlsConn, theirReadSecret); err != nil { |
| 946 | return err |
| 947 | } |
| 948 | if _, err := io.ReadFull(tlsConn, theirWriteSecret); err != nil { |
| 949 | return err |
| 950 | } |
| 951 |
| 952 | myReadSecret := tlsConn.in.trafficSecret |
| 953 | myWriteSecret := tlsConn.out.trafficSecret |
| 954 | if !bytes.Equal(myWriteSecret, theirReadSecret) { |
| 955 | return fmt.Errorf("read traffic-secret mismatch; got %x, wanted %x", theirReadSecret, myWriteSecret) |
| 956 | } |
| 957 | if !bytes.Equal(myReadSecret, theirWriteSecret) { |
| 958 | return fmt.Errorf("write traffic-secret mismatch; got %x, wanted %x", theirWriteSecret, myReadSecret) |
| 959 | } |
| 960 | } |
| 961 |
| 962 | if test.testTLSUnique { |
| 963 | var peersValue [12]byte |
| 964 | if _, err := io.ReadFull(tlsConn, peersValue[:]); err != nil { |
| 965 | return err |
| 966 | } |
| 967 | expected := tlsConn.ConnectionState().TLSUnique |
| 968 | if !bytes.Equal(peersValue[:], expected) { |
| 969 | return fmt.Errorf("tls-unique mismatch: peer sent %x, but %x was expected", peersValue[:], expected) |
| 970 | } |
| 971 | } |
| 972 |
| 973 | if test.sendHalfHelloRequest { |
| 974 | tlsConn.SendHalfHelloRequest() |
| 975 | } |
| 976 |
| 977 | shimPrefix := test.shimPrefix |
| 978 | if isResume { |
| 979 | shimPrefix = test.resumeShimPrefix |
| 980 | } |
| 981 | if test.shimWritesFirst || test.readWithUnfinishedWrite { |
| 982 | shimPrefix = shimInitialWrite |
| 983 | } |
| 984 | if test.renegotiate > 0 { |
| 985 | // If readWithUnfinishedWrite is set, the shim prefix will be |
| 986 | // available later. |
| 987 | if shimPrefix != "" && !test.readWithUnfinishedWrite { |
| 988 | buf := make([]byte, len(shimPrefix)) |
| 989 | _, err := io.ReadFull(tlsConn, buf) |
| 990 | if err != nil { |
| 991 | return err |
| 992 | } |
| 993 | if string(buf) != shimPrefix { |
| 994 | return fmt.Errorf("bad initial message %v vs %v", string(buf), shimPrefix) |
| 995 | } |
| 996 | shimPrefix = "" |
| 997 | } |
| 998 |
| 999 | if test.renegotiateCiphers != nil { |
| 1000 | config.CipherSuites = test.renegotiateCiphers |
| 1001 | } |
| 1002 | for i := 0; i < test.renegotiate; i++ { |
| 1003 | if err := tlsConn.Renegotiate(); err != nil { |
| 1004 | return err |
| 1005 | } |
| 1006 | } |
| 1007 | } else if test.renegotiateCiphers != nil { |
| 1008 | panic("renegotiateCiphers without renegotiate") |
| 1009 | } |
| 1010 |
| 1011 | if test.damageFirstWrite { |
| 1012 | connDamage.setDamage(true) |
| 1013 | if _, err := tlsConn.Write([]byte("DAMAGED WRITE")); err != nil { |
| 1014 | return err |
| 1015 | } |
| 1016 | connDamage.setDamage(false) |
| 1017 | } |
| 1018 |
| 1019 | messageLen := test.messageLen |
| 1020 | if messageLen < 0 { |
| 1021 | if test.protocol == dtls { |
| 1022 | return fmt.Errorf("messageLen < 0 not supported for DTLS tests") |
| 1023 | } |
| 1024 | // Read until EOF. |
| 1025 | _, err := io.Copy(io.Discard, tlsConn) |
| 1026 | return err |
| 1027 | } |
| 1028 | if messageLen == 0 { |
| 1029 | messageLen = 32 |
| 1030 | } |
| 1031 |
| 1032 | messageCount := test.messageCount |
| 1033 | // shimShutsDown sets the default message count to zero. |
| 1034 | if messageCount == 0 && !test.shimShutsDown { |
| 1035 | messageCount = 1 |
| 1036 | } |
| 1037 |
| 1038 | for j := 0; j < messageCount; j++ { |
| 1039 | for i := 0; i < test.sendKeyUpdates; i++ { |
| 1040 | if err := tlsConn.SendKeyUpdate(test.keyUpdateRequest); err != nil { |
| 1041 | return err |
| 1042 | } |
| 1043 | } |
| 1044 |
| 1045 | for i := 0; i < test.sendEmptyRecords; i++ { |
| 1046 | if _, err := tlsConn.Write(nil); err != nil { |
| 1047 | return err |
| 1048 | } |
| 1049 | } |
| 1050 |
| 1051 | for i := 0; i < test.sendWarningAlerts; i++ { |
| 1052 | if err := tlsConn.SendAlert(alertLevelWarning, alertUnexpectedMessage); err != nil { |
| 1053 | return err |
| 1054 | } |
| 1055 | } |
| 1056 |
| 1057 | for i := 0; i < test.sendUserCanceledAlerts; i++ { |
| 1058 | if err := tlsConn.SendAlert(alertLevelWarning, alertUserCanceled); err != nil { |
| 1059 | return err |
| 1060 | } |
| 1061 | } |
| 1062 |
| 1063 | if test.sendBogusAlertType { |
| 1064 | if err := tlsConn.SendAlert(0x42, alertUnexpectedMessage); err != nil { |
| 1065 | return err |
| 1066 | } |
| 1067 | } |
| 1068 |
| 1069 | if test.shimSendsKeyUpdateBeforeRead { |
| 1070 | if err := tlsConn.ReadKeyUpdate(); err != nil { |
| 1071 | return err |
| 1072 | } |
| 1073 | } |
| 1074 |
| 1075 | testMessage := makeTestMessage(j, messageLen) |
| 1076 | if _, err := tlsConn.Write(testMessage); err != nil { |
| 1077 | return err |
| 1078 | } |
| 1079 |
| 1080 | // Consume the shim prefix if needed. |
| 1081 | if shimPrefix != "" { |
| 1082 | buf := make([]byte, len(shimPrefix)) |
| 1083 | _, err := io.ReadFull(tlsConn, buf) |
| 1084 | if err != nil { |
| 1085 | return err |
| 1086 | } |
| 1087 | if string(buf) != shimPrefix { |
| 1088 | return fmt.Errorf("bad initial message %v vs %v", string(buf), shimPrefix) |
| 1089 | } |
| 1090 | shimPrefix = "" |
| 1091 | } |
| 1092 |
| 1093 | if test.shimShutsDown || test.expectMessageDropped { |
| 1094 | // The shim will not respond. |
| 1095 | continue |
| 1096 | } |
| 1097 |
| 1098 | // Process the KeyUpdate reply. However many KeyUpdates the runner |
| 1099 | // sends, the shim should respond only once. |
| 1100 | if test.sendKeyUpdates > 0 && test.keyUpdateRequest == keyUpdateRequested { |
| 1101 | if err := tlsConn.ReadKeyUpdate(); err != nil { |
| 1102 | return err |
| 1103 | } |
| 1104 | } |
| 1105 |
| 1106 | buf := make([]byte, len(testMessage)) |
| 1107 | if test.protocol == dtls { |
| 1108 | bufTmp := make([]byte, len(buf)+1) |
| 1109 | n, err := tlsConn.Read(bufTmp) |
| 1110 | if err != nil { |
| 1111 | return err |
| 1112 | } |
| 1113 | if config.Bugs.SplitAndPackAppData { |
| 1114 | m, err := tlsConn.Read(bufTmp[n:]) |
| 1115 | if err != nil { |
| 1116 | return err |
| 1117 | } |
| 1118 | n += m |
| 1119 | } |
| 1120 | if n != len(buf) { |
| 1121 | return fmt.Errorf("bad reply; length mismatch (%d vs %d)", n, len(buf)) |
| 1122 | } |
| 1123 | copy(buf, bufTmp) |
| 1124 | } else { |
| 1125 | _, err := io.ReadFull(tlsConn, buf) |
| 1126 | if err != nil { |
| 1127 | return err |
| 1128 | } |
| 1129 | } |
| 1130 |
| 1131 | if expected := expectedReply(testMessage); !bytes.Equal(buf, expected) { |
| 1132 | return fmt.Errorf("bad reply contents; got %x and wanted %x", buf, expected) |
| 1133 | } |
| 1134 |
| 1135 | if seen := tlsConn.keyUpdateSeen; seen != test.expectUnsolicitedKeyUpdate { |
| 1136 | return fmt.Errorf("keyUpdateSeen (%t) != expectUnsolicitedKeyUpdate", seen) |
| 1137 | } |
| 1138 | } |
| 1139 |
| 1140 | // The shim will end attempting to read, sending one last KeyUpdate. Consume |
| 1141 | // the KeyUpdate before closing the connection. |
| 1142 | if test.shimSendsKeyUpdateBeforeRead { |
| 1143 | if err := tlsConn.ReadKeyUpdate(); err != nil { |
| 1144 | return err |
| 1145 | } |
| 1146 | } |
| 1147 |
| 1148 | return nil |
| 1149 | } |
| 1150 |
| 1151 | const xtermSize = "140x50" |
| 1152 |
| 1153 | func valgrindOf(dbAttach bool, path string, args ...string) *exec.Cmd { |
| 1154 | valgrindArgs := []string{"--error-exitcode=99", "--track-origins=yes", "--leak-check=full", "--quiet"} |
| 1155 | if dbAttach { |
| 1156 | valgrindArgs = append(valgrindArgs, "--db-attach=yes", "--db-command=xterm -geometry "+xtermSize+" -e gdb -nw %f %p") |
| 1157 | } |
| 1158 | valgrindArgs = append(valgrindArgs, path) |
| 1159 | valgrindArgs = append(valgrindArgs, args...) |
| 1160 |
| 1161 | return exec.Command("valgrind", valgrindArgs...) |
| 1162 | } |
| 1163 |
| 1164 | func gdbOf(path string, args ...string) *exec.Cmd { |
| 1165 | xtermArgs := []string{"-geometry", xtermSize, "-e", "gdb", "--args"} |
| 1166 | xtermArgs = append(xtermArgs, path) |
| 1167 | xtermArgs = append(xtermArgs, args...) |
| 1168 |
| 1169 | return exec.Command("xterm", xtermArgs...) |
| 1170 | } |
| 1171 |
| 1172 | func lldbOf(path string, args ...string) *exec.Cmd { |
| 1173 | xtermArgs := []string{"-geometry", xtermSize, "-e", "lldb", "--"} |
| 1174 | xtermArgs = append(xtermArgs, path) |
| 1175 | xtermArgs = append(xtermArgs, args...) |
| 1176 |
| 1177 | return exec.Command("xterm", xtermArgs...) |
| 1178 | } |
| 1179 |
| 1180 | func rrOf(path string, args ...string) *exec.Cmd { |
| 1181 | rrArgs := []string{"record", path} |
| 1182 | rrArgs = append(rrArgs, args...) |
| 1183 | return exec.Command("rr", rrArgs...) |
| 1184 | } |
| 1185 |
| 1186 | func removeFirstLineIfSuffix(s, suffix string) string { |
| 1187 | idx := strings.IndexByte(s, '\n') |
| 1188 | if idx < 0 { |
| 1189 | return s |
| 1190 | } |
| 1191 | if strings.HasSuffix(s[:idx], suffix) { |
| 1192 | return s[idx+1:] |
| 1193 | } |
| 1194 | return s |
| 1195 | } |
| 1196 |
| 1197 | var ( |
| 1198 | errMoreMallocs = errors.New("child process did not exhaust all allocation calls") |
| 1199 | errUnimplemented = errors.New("child process does not implement needed flags") |
| 1200 | ) |
| 1201 |
| 1202 | type shimProcess struct { |
| 1203 | cmd *exec.Cmd |
| 1204 | // done is closed when the process has exited. At that point, childErr may be |
| 1205 | // read for the result. |
| 1206 | done chan struct{} |
| 1207 | childErr error |
| 1208 | listener *shimListener |
| 1209 | stdout, stderr bytes.Buffer |
| 1210 | } |
| 1211 |
| 1212 | // newShimProcess starts a new shim with the specified executable, flags, and |
| 1213 | // environment. It internally creates a TCP listener and adds the the -port |
| 1214 | // flag. |
| 1215 | func newShimProcess(dispatcher *shimDispatcher, shimPath string, flags []string, env []string) (*shimProcess, error) { |
| 1216 | listener, err := dispatcher.NewShim() |
| 1217 | if err != nil { |
| 1218 | return nil, err |
| 1219 | } |
| 1220 |
| 1221 | shim := &shimProcess{listener: listener} |
| 1222 | cmdFlags := []string{ |
| 1223 | "-port", strconv.Itoa(listener.Port()), |
| 1224 | "-shim-id", strconv.FormatUint(listener.ShimID(), 10), |
| 1225 | } |
| 1226 | if listener.IsIPv6() { |
| 1227 | cmdFlags = append(cmdFlags, "-ipv6") |
| 1228 | } |
| 1229 | cmdFlags = append(cmdFlags, flags...) |
| 1230 |
| 1231 | if *useValgrind { |
| 1232 | shim.cmd = valgrindOf(false, shimPath, cmdFlags...) |
| 1233 | } else if *useGDB { |
| 1234 | shim.cmd = gdbOf(shimPath, cmdFlags...) |
| 1235 | } else if *useLLDB { |
| 1236 | shim.cmd = lldbOf(shimPath, cmdFlags...) |
| 1237 | } else if *useRR { |
| 1238 | shim.cmd = rrOf(shimPath, cmdFlags...) |
| 1239 | } else { |
| 1240 | shim.cmd = exec.Command(shimPath, cmdFlags...) |
| 1241 | } |
| 1242 | shim.cmd.Stdin = os.Stdin |
| 1243 | shim.cmd.Stdout = &shim.stdout |
| 1244 | shim.cmd.Stderr = &shim.stderr |
| 1245 | shim.cmd.Env = env |
| 1246 |
| 1247 | if err := shim.cmd.Start(); err != nil { |
| 1248 | shim.listener.Close() |
| 1249 | return nil, err |
| 1250 | } |
| 1251 |
| 1252 | shim.done = make(chan struct{}) |
| 1253 | go func() { |
| 1254 | shim.childErr = shim.cmd.Wait() |
| 1255 | shim.listener.Close() |
| 1256 | close(shim.done) |
| 1257 | }() |
| 1258 | return shim, nil |
| 1259 | } |
| 1260 |
| 1261 | // accept returns a new TCP connection with the shim process, or returns an |
| 1262 | // error on timeout or shim exit. |
| 1263 | func (s *shimProcess) accept() (net.Conn, error) { |
| 1264 | var deadline time.Time |
| 1265 | if !useDebugger() { |
| 1266 | deadline = time.Now().Add(*idleTimeout) |
| 1267 | } |
| 1268 | return s.listener.Accept(deadline) |
| 1269 | } |
| 1270 |
| 1271 | // wait finishes the test and waits for the shim process to exit. |
| 1272 | func (s *shimProcess) wait() error { |
| 1273 | // Close the listener now. This is to avoid hangs if the shim tries to open |
| 1274 | // more connections than expected. |
| 1275 | s.listener.Close() |
| 1276 |
| 1277 | if !useDebugger() { |
| 1278 | waitTimeout := time.AfterFunc(*idleTimeout, func() { |
| 1279 | s.cmd.Process.Kill() |
| 1280 | }) |
| 1281 | defer waitTimeout.Stop() |
| 1282 | } |
| 1283 |
| 1284 | <-s.done |
| 1285 | return s.childErr |
| 1286 | } |
| 1287 |
| 1288 | // close releases resources associated with the shimProcess. This is safe to |
| 1289 | // call before or after |wait|. |
| 1290 | func (s *shimProcess) close() { |
| 1291 | s.listener.Close() |
| 1292 | s.cmd.Process.Kill() |
| 1293 | } |
| 1294 |
| 1295 | func doExchanges(test *testCase, shim *shimProcess, resumeCount int, transcripts *[][]byte) error { |
| 1296 | config := test.config |
| 1297 | if *deterministic { |
| 1298 | config.Rand = &deterministicRand{} |
| 1299 | } |
| 1300 |
| 1301 | conn, err := shim.accept() |
| 1302 | if err != nil { |
| 1303 | return err |
| 1304 | } |
| 1305 | err = doExchange(test, &config, conn, false /* not a resumption */, transcripts, 0) |
| 1306 | conn.Close() |
| 1307 | if err != nil { |
| 1308 | return err |
| 1309 | } |
| 1310 |
| 1311 | nextTicketKey := config.SessionTicketKey |
| 1312 | for i := 0; i < resumeCount; i++ { |
| 1313 | var resumeConfig Config |
| 1314 | if test.resumeConfig != nil { |
| 1315 | resumeConfig = *test.resumeConfig |
| 1316 | resumeConfig.Rand = config.Rand |
| 1317 | if resumeConfig.Credential == nil { |
| 1318 | resumeConfig.Credential = config.Credential |
| 1319 | } |
| 1320 | } else { |
| 1321 | resumeConfig = config |
| 1322 | } |
| 1323 |
| 1324 | if test.newSessionsOnResume { |
| 1325 | resumeConfig.ClientSessionCache = nil |
| 1326 | resumeConfig.ServerSessionCache = nil |
| 1327 | if _, err := resumeConfig.rand().Read(resumeConfig.SessionTicketKey[:]); err != nil { |
| 1328 | return err |
| 1329 | } |
| 1330 | } else { |
| 1331 | resumeConfig.ClientSessionCache = config.ClientSessionCache |
| 1332 | resumeConfig.ServerSessionCache = config.ServerSessionCache |
| 1333 | // Rotate the ticket keys between each connection, with each connection |
| 1334 | // encrypting with next connection's keys. This ensures that we test |
| 1335 | // the renewed sessions. |
| 1336 | resumeConfig.SessionTicketKey = nextTicketKey |
| 1337 | if _, err := resumeConfig.rand().Read(nextTicketKey[:]); err != nil { |
| 1338 | return err |
| 1339 | } |
| 1340 | resumeConfig.Bugs.EncryptSessionTicketKey = &nextTicketKey |
| 1341 | } |
| 1342 |
| 1343 | var connResume net.Conn |
| 1344 | connResume, err = shim.accept() |
| 1345 | if err != nil { |
| 1346 | return err |
| 1347 | } |
| 1348 | err = doExchange(test, &resumeConfig, connResume, true /* resumption */, transcripts, i+1) |
| 1349 | connResume.Close() |
| 1350 | if err != nil { |
| 1351 | return err |
| 1352 | } |
| 1353 | } |
| 1354 |
| 1355 | return nil |
| 1356 | } |
| 1357 |
| 1358 | // translateExpectedError uses a canonical BoringSSL error to produce |
| 1359 | // a slice of expected canonical errors in bogo_shim_config.json. |
| 1360 | func translateExpectedError(canonical string) []string { |
| 1361 | if translated, found := shimConfig.ErrorMap[canonical]; found { |
| 1362 | return translated |
| 1363 | } |
| 1364 |
| 1365 | // not specifying a canonical error will have the same effect as -loose-errors being true |
| 1366 | // since the emptry string with match all error substrings. |
| 1367 | return []string{canonical} |
| 1368 | } |
| 1369 |
| 1370 | // formatErrors takes the semantic mapping from translateExpectedError |
| 1371 | // and outputs human-readable digest of BoGo error state. |
| 1372 | func formatErrors(expectedErrors []string, stderr, local, child, stdout, expectedLocal, expectedCanonical string) (string, string) { |
| 1373 | got := fmt.Sprintf("\tstderr:\n\t\t%s\n\tlocal: %q\n\tchild: %q\n\tstdout: %s", stderr, local, child, stdout) |
| 1374 | want := fmt.Sprintf("\tlocal: %q\n\tremote: %q", expectedLocal, expectedCanonical) |
| 1375 | if slices.Equal(expectedErrors, []string{expectedCanonical}) { |
| 1376 | return got, want |
| 1377 | } |
| 1378 | if len(expectedErrors) == 0 || expectedErrors == nil { |
| 1379 | return got, want + " (no specified mapping)" |
| 1380 | } |
| 1381 | return got, want + " mapped to one of:\n\t\t" + strings.Join(expectedErrors, "\n\t\t") |
| 1382 | } |
| 1383 |
| 1384 | // matchError plucks the relevant canonical error from the provided |
| 1385 | // slice if found; if the slice is empty/nil, strict error checking |
| 1386 | // is presumed to be disabled. |
| 1387 | func matchError(expectedErrors []string, stderr string) bool { |
| 1388 | for _, expectedError := range expectedErrors { |
| 1389 | if strings.Contains(stderr, expectedError) { |
| 1390 | return true |
| 1391 | } |
| 1392 | } |
| 1393 | return false |
| 1394 | } |
| 1395 |
| 1396 | // shimInitialWrite is the data we expect from the shim when the |
| 1397 | // -shim-writes-first flag is used. |
| 1398 | const shimInitialWrite = "hello" |
| 1399 |
| 1400 | func appendCredentialFlags(flags []string, cred *Credential, prefix string, newCredential bool) []string { |
| 1401 | if newCredential { |
| 1402 | switch cred.Type { |
| 1403 | case CredentialTypeX509: |
| 1404 | flags = append(flags, prefix+"-new-x509-credential") |
| 1405 | case CredentialTypeDelegated: |
| 1406 | flags = append(flags, prefix+"-new-delegated-credential") |
| 1407 | case CredentialTypeSPAKE2PlusV1: |
| 1408 | flags = append(flags, prefix+"-new-spake2plusv1-credential") |
| 1409 | default: |
| 1410 | panic(fmt.Errorf("unknown credential type %d", cred.Type)) |
| 1411 | } |
| 1412 | } else if cred.Type != CredentialTypeX509 { |
| 1413 | panic("default credential must be X.509") |
| 1414 | } |
| 1415 |
| 1416 | handleBase64Field := func(flag string, value []byte) { |
| 1417 | if len(value) != 0 { |
| 1418 | flags = append(flags, fmt.Sprintf("%s-%s", prefix, flag), base64FlagValue(value)) |
| 1419 | } |
| 1420 | } |
| 1421 |
| 1422 | if len(cred.ChainPath) != 0 { |
| 1423 | flags = append(flags, prefix+"-cert-file", cred.ChainPath) |
| 1424 | } |
| 1425 | if len(cred.KeyPath) != 0 { |
| 1426 | flags = append(flags, prefix+"-key-file", cred.KeyPath) |
| 1427 | } |
| 1428 | handleBase64Field("ocsp-response", cred.OCSPStaple) |
| 1429 | handleBase64Field("signed-cert-timestamps", cred.SignedCertificateTimestampList) |
| 1430 | for _, sigAlg := range cred.SignatureAlgorithms { |
| 1431 | flags = append(flags, prefix+"-signing-prefs", strconv.Itoa(int(sigAlg))) |
| 1432 | } |
| 1433 | handleBase64Field("delegated-credential", cred.DelegatedCredential) |
| 1434 | if cred.MustMatchIssuer { |
| 1435 | flags = append(flags, prefix+"-must-match-issuer") |
| 1436 | } |
| 1437 | handleBase64Field("pake-context", cred.PAKEContext) |
| 1438 | handleBase64Field("pake-client-id", cred.PAKEClientID) |
| 1439 | handleBase64Field("pake-server-id", cred.PAKEServerID) |
| 1440 | handleBase64Field("pake-password", cred.PAKEPassword) |
| 1441 | if cred.WrongPAKERole { |
| 1442 | flags = append(flags, prefix+"-wrong-pake-role") |
| 1443 | } |
| 1444 | handleBase64Field("trust-anchor-id", cred.TrustAnchorID) |
| 1445 | return flags |
| 1446 | } |
| 1447 |
| 1448 | func runTest(dispatcher *shimDispatcher, statusChan chan statusMsg, test *testCase, shimPath string, mallocNumToFail int64) error { |
| 1449 | // Help debugging panics on the Go side. |
| 1450 | defer func() { |
| 1451 | if r := recover(); r != nil { |
| 1452 | fmt.Fprintf(os.Stderr, "Test '%s' panicked.\n", test.name) |
| 1453 | panic(r) |
| 1454 | } |
| 1455 | }() |
| 1456 |
| 1457 | var flags []string |
| 1458 | if len(*shimExtraFlags) > 0 { |
| 1459 | flags = strings.Split(*shimExtraFlags, ";") |
| 1460 | } |
| 1461 | if *fuzzer { |
| 1462 | flags = append(flags, "-fuzzer-mode") |
| 1463 | } |
| 1464 | if test.testType == serverTest { |
| 1465 | flags = append(flags, "-server") |
| 1466 | } |
| 1467 |
| 1468 | // Configure the default credential. |
| 1469 | shimCertificate := test.shimCertificate |
| 1470 | if shimCertificate == nil && len(test.shimCredentials) == 0 && len(test.resumeShimCredentials) == 0 && test.testType == serverTest && len(test.config.PreSharedKey) == 0 { |
| 1471 | shimCertificate = &rsaCertificate |
| 1472 | } |
| 1473 | if shimCertificate != nil { |
| 1474 | var shimPrefix string |
| 1475 | if test.handshakerCertificate != nil { |
| 1476 | shimPrefix = "-on-shim" |
| 1477 | } |
| 1478 | flags = appendCredentialFlags(flags, shimCertificate, shimPrefix, false) |
| 1479 | } |
| 1480 | if test.handshakerCertificate != nil { |
| 1481 | flags = appendCredentialFlags(flags, test.handshakerCertificate, "-on-handshaker", false) |
| 1482 | } |
| 1483 |
| 1484 | // Configure any additional credentials. |
| 1485 | for _, cred := range test.shimCredentials { |
| 1486 | flags = appendCredentialFlags(flags, cred, "", true) |
| 1487 | } |
| 1488 | for _, cred := range test.resumeShimCredentials { |
| 1489 | flags = appendCredentialFlags(flags, cred, "-on-resume", true) |
| 1490 | } |
| 1491 |
| 1492 | if test.protocol == dtls { |
| 1493 | flags = append(flags, "-dtls") |
| 1494 | } else if test.protocol == quic { |
| 1495 | flags = append(flags, "-quic") |
| 1496 | if !test.skipTransportParamsConfig { |
| 1497 | test.config.QUICTransportParams = []byte{1, 2} |
| 1498 | test.config.QUICTransportParamsUseLegacyCodepoint = QUICUseCodepointStandard |
| 1499 | if test.resumeConfig != nil { |
| 1500 | test.resumeConfig.QUICTransportParams = []byte{1, 2} |
| 1501 | test.resumeConfig.QUICTransportParamsUseLegacyCodepoint = QUICUseCodepointStandard |
| 1502 | } |
| 1503 | test.expectations.quicTransportParams = []byte{3, 4} |
| 1504 | if test.resumeExpectations != nil { |
| 1505 | test.resumeExpectations.quicTransportParams = []byte{3, 4} |
| 1506 | } |
| 1507 | useCodepointFlag := "0" |
| 1508 | if test.config.QUICTransportParamsUseLegacyCodepoint == QUICUseCodepointLegacy { |
| 1509 | useCodepointFlag = "1" |
| 1510 | } |
| 1511 | flags = append(flags, |
| 1512 | "-quic-transport-params", |
| 1513 | base64FlagValue([]byte{3, 4}), |
| 1514 | "-expect-quic-transport-params", |
| 1515 | base64FlagValue([]byte{1, 2}), |
| 1516 | "-quic-use-legacy-codepoint", useCodepointFlag) |
| 1517 | } |
| 1518 | if !test.skipQUICALPNConfig { |
| 1519 | flags = append(flags, |
| 1520 | []string{ |
| 1521 | "-advertise-alpn", "\x03foo", |
| 1522 | "-select-alpn", "foo", |
| 1523 | "-expect-alpn", "foo", |
| 1524 | }...) |
| 1525 | test.config.NextProtos = []string{"foo"} |
| 1526 | if test.resumeConfig != nil { |
| 1527 | test.resumeConfig.NextProtos = []string{"foo"} |
| 1528 | } |
| 1529 | test.expectations.nextProto = "foo" |
| 1530 | test.expectations.nextProtoType = alpn |
| 1531 | if test.resumeExpectations != nil { |
| 1532 | test.resumeExpectations.nextProto = "foo" |
| 1533 | test.resumeExpectations.nextProtoType = alpn |
| 1534 | } |
| 1535 | } |
| 1536 | } |
| 1537 |
| 1538 | if test.earlyData { |
| 1539 | if !test.resumeSession { |
| 1540 | panic("earlyData set without resumeSession in " + test.name) |
| 1541 | } |
| 1542 |
| 1543 | resumeConfig := test.resumeConfig |
| 1544 | if resumeConfig == nil { |
| 1545 | resumeConfig = &test.config |
| 1546 | } |
| 1547 | if test.expectEarlyDataRejected { |
| 1548 | flags = append(flags, "-on-resume-expect-reject-early-data") |
| 1549 | } else { |
| 1550 | flags = append(flags, "-on-resume-expect-accept-early-data") |
| 1551 | } |
| 1552 |
| 1553 | if test.protocol == quic { |
| 1554 | // QUIC requires an early data context string. |
| 1555 | flags = append(flags, "-quic-early-data-context", "context") |
| 1556 | } |
| 1557 |
| 1558 | flags = append(flags, "-enable-early-data") |
| 1559 | if test.testType == clientTest { |
| 1560 | // Configure the runner with default maximum early data. |
| 1561 | flags = append(flags, "-expect-ticket-supports-early-data") |
| 1562 | if test.config.MaxEarlyDataSize == 0 { |
| 1563 | test.config.MaxEarlyDataSize = 16384 |
| 1564 | } |
| 1565 | if resumeConfig.MaxEarlyDataSize == 0 { |
| 1566 | resumeConfig.MaxEarlyDataSize = 16384 |
| 1567 | } |
| 1568 |
| 1569 | // In DTLS 1.3, we're setting flags to configure the client to attempt |
| 1570 | // sending early data, but we expect it to realize that it's incapable |
| 1571 | // of supporting early data and not send any. |
| 1572 | if test.protocol != dtls { |
| 1573 | // Configure the shim to send some data in early data. |
| 1574 | flags = append(flags, "-on-resume-shim-writes-first") |
| 1575 | if resumeConfig.Bugs.ExpectEarlyData == nil { |
| 1576 | resumeConfig.Bugs.ExpectEarlyData = [][]byte{[]byte(shimInitialWrite)} |
| 1577 | } |
| 1578 | } |
| 1579 | } else { |
| 1580 | // By default, send some early data and expect half-RTT data response. |
| 1581 | if resumeConfig.Bugs.SendEarlyData == nil { |
| 1582 | resumeConfig.Bugs.SendEarlyData = [][]byte{{1, 2, 3, 4}} |
| 1583 | } |
| 1584 | if resumeConfig.Bugs.ExpectHalfRTTData == nil { |
| 1585 | resumeConfig.Bugs.ExpectHalfRTTData = [][]byte{{254, 253, 252, 251}} |
| 1586 | } |
| 1587 | resumeConfig.Bugs.ExpectEarlyDataAccepted = !test.expectEarlyDataRejected |
| 1588 | } |
| 1589 | } |
| 1590 |
| 1591 | var resumeCount int |
| 1592 | if test.resumeSession { |
| 1593 | resumeCount++ |
| 1594 | if test.resumeRenewedSession { |
| 1595 | resumeCount++ |
| 1596 | } |
| 1597 | } |
| 1598 |
| 1599 | if resumeCount > 0 { |
| 1600 | flags = append(flags, "-resume-count", strconv.Itoa(resumeCount)) |
| 1601 | } |
| 1602 |
| 1603 | if test.shimWritesFirst { |
| 1604 | flags = append(flags, "-shim-writes-first") |
| 1605 | } |
| 1606 |
| 1607 | if test.readWithUnfinishedWrite { |
| 1608 | flags = append(flags, "-read-with-unfinished-write") |
| 1609 | } |
| 1610 |
| 1611 | if test.shimShutsDown { |
| 1612 | flags = append(flags, "-shim-shuts-down") |
| 1613 | } |
| 1614 |
| 1615 | if test.exportKeyingMaterial > 0 { |
| 1616 | flags = append(flags, "-export-keying-material", strconv.Itoa(test.exportKeyingMaterial)) |
| 1617 | if test.useExportContext { |
| 1618 | flags = append(flags, "-use-export-context") |
| 1619 | } |
| 1620 | } |
| 1621 | if test.exportKeyingMaterial > 0 { |
| 1622 | flags = append(flags, "-export-label", test.exportLabel) |
| 1623 | flags = append(flags, "-export-context", test.exportContext) |
| 1624 | } |
| 1625 |
| 1626 | if test.exportTrafficSecrets { |
| 1627 | flags = append(flags, "-export-traffic-secrets") |
| 1628 | } |
| 1629 |
| 1630 | if test.expectResumeRejected { |
| 1631 | flags = append(flags, "-expect-session-miss") |
| 1632 | } |
| 1633 |
| 1634 | if test.testTLSUnique { |
| 1635 | flags = append(flags, "-tls-unique") |
| 1636 | } |
| 1637 |
| 1638 | if test.shimSendsKeyUpdateBeforeRead { |
| 1639 | flags = append(flags, "-key-update-before-read") |
| 1640 | } |
| 1641 |
| 1642 | if *waitForDebugger { |
| 1643 | flags = append(flags, "-wait-for-debugger") |
| 1644 | } |
| 1645 |
| 1646 | var transcriptPrefix string |
| 1647 | var transcripts [][]byte |
| 1648 | if len(*transcriptDir) != 0 { |
| 1649 | protocol := "tls" |
| 1650 | if test.protocol == dtls { |
| 1651 | protocol = "dtls" |
| 1652 | } else if test.protocol == quic { |
| 1653 | protocol = "quic" |
| 1654 | } |
| 1655 |
| 1656 | side := "client" |
| 1657 | if test.testType == serverTest { |
| 1658 | side = "server" |
| 1659 | } |
| 1660 |
| 1661 | dir := filepath.Join(*transcriptDir, protocol, side) |
| 1662 | if err := os.MkdirAll(dir, 0755); err != nil { |
| 1663 | return err |
| 1664 | } |
| 1665 | transcriptPrefix = filepath.Join(dir, test.name+"-") |
| 1666 | flags = append(flags, "-write-settings", transcriptPrefix) |
| 1667 | } |
| 1668 |
| 1669 | if test.testType == clientTest && test.config.Credential == nil { |
| 1670 | test.config.Credential = &rsaCertificate |
| 1671 | } |
| 1672 | if test.config.Credential != nil { |
| 1673 | flags = append(flags, "-trust-cert", test.config.Credential.RootPath) |
| 1674 | } |
| 1675 |
| 1676 | flags = append(flags, test.flags...) |
| 1677 |
| 1678 | var env []string |
| 1679 | if mallocNumToFail >= 0 { |
| 1680 | env = os.Environ() |
| 1681 | env = append(env, "MALLOC_NUMBER_TO_FAIL="+strconv.FormatInt(mallocNumToFail, 10)) |
| 1682 | if *mallocTestDebug { |
| 1683 | env = append(env, "MALLOC_BREAK_ON_FAIL=1") |
| 1684 | } |
| 1685 | env = append(env, "_MALLOC_CHECK=1") |
| 1686 | } |
| 1687 |
| 1688 | shim, err := newShimProcess(dispatcher, shimPath, flags, env) |
| 1689 | if err != nil { |
| 1690 | return err |
| 1691 | } |
| 1692 | statusChan <- statusMsg{test: test, statusType: statusShimStarted, pid: shim.cmd.Process.Pid} |
| 1693 | defer shim.close() |
| 1694 |
| 1695 | localErr := doExchanges(test, shim, resumeCount, &transcripts) |
| 1696 | childErr := shim.wait() |
| 1697 |
| 1698 | // Now that the shim has exited, all the settings files have been |
| 1699 | // written. Append the saved transcripts. |
| 1700 | for i, transcript := range transcripts { |
| 1701 | if err := appendTranscript(transcriptPrefix+strconv.Itoa(i), transcript); err != nil { |
| 1702 | return err |
| 1703 | } |
| 1704 | } |
| 1705 |
| 1706 | var isValgrindError, mustFail bool |
| 1707 | if exitError, ok := childErr.(*exec.ExitError); ok { |
| 1708 | switch exitError.Sys().(syscall.WaitStatus).ExitStatus() { |
| 1709 | case 88: |
| 1710 | return errMoreMallocs |
| 1711 | case 89: |
| 1712 | return errUnimplemented |
| 1713 | case 90: |
| 1714 | mustFail = true |
| 1715 | case 99: |
| 1716 | isValgrindError = true |
| 1717 | } |
| 1718 | } |
| 1719 |
| 1720 | // Account for Windows line endings. |
| 1721 | stdout := strings.Replace(shim.stdout.String(), "\r\n", "\n", -1) |
| 1722 | stderr := strings.Replace(shim.stderr.String(), "\r\n", "\n", -1) |
| 1723 |
| 1724 | // Work around an NDK / Android bug. The NDK r16 sometimes generates |
| 1725 | // binaries with the DF_1_PIE, which the runtime linker on Android N |
| 1726 | // complains about. The next NDK revision should work around this but, |
| 1727 | // in the meantime, strip its error out. |
| 1728 | // |
| 1729 | // https://github.com/android-ndk/ndk/issues/602 |
| 1730 | // https://android-review.googlesource.com/c/platform/bionic/+/259790 |
| 1731 | // https://android-review.googlesource.com/c/toolchain/binutils/+/571550 |
| 1732 | // |
| 1733 | // Remove this after switching to the r17 NDK. |
| 1734 | stderr = removeFirstLineIfSuffix(stderr, ": unsupported flags DT_FLAGS_1=0x8000001") |
| 1735 |
| 1736 | // Separate the errors from the shim and those from tools like |
| 1737 | // AddressSanitizer. |
| 1738 | var extraStderr string |
| 1739 | if stderrParts := strings.SplitN(stderr, "--- DONE ---\n", 2); len(stderrParts) == 2 { |
| 1740 | stderr = stderrParts[0] |
| 1741 | extraStderr = stderrParts[1] |
| 1742 | } |
| 1743 |
| 1744 | failed := localErr != nil || childErr != nil |
| 1745 | expectedErrors := translateExpectedError(test.expectedError) |
| 1746 | correctFailure := *looseErrors || matchError(expectedErrors, stderr) |
| 1747 |
| 1748 | localErrString := "none" |
| 1749 | if localErr != nil { |
| 1750 | localErrString = localErr.Error() |
| 1751 | } |
| 1752 | if len(test.expectedLocalError) != 0 { |
| 1753 | correctFailure = correctFailure && strings.Contains(localErrString, test.expectedLocalError) |
| 1754 | } |
| 1755 |
| 1756 | if failed != test.shouldFail || failed && !correctFailure || mustFail { |
| 1757 | childErrString := "none" |
| 1758 | if childErr != nil { |
| 1759 | childErrString = childErr.Error() |
| 1760 | } |
| 1761 |
| 1762 | got, want := formatErrors(expectedErrors, |
| 1763 | stderr, localErrString, childErrString, stdout, |
| 1764 | test.expectedLocalError, test.expectedError) |
| 1765 |
| 1766 | var msg string |
| 1767 | switch { |
| 1768 | case failed && !test.shouldFail: |
| 1769 | msg = fmt.Sprintf("unexpected failure\ngot:\n%s\n", got) |
| 1770 | case !failed && test.shouldFail: |
| 1771 | msg = fmt.Sprintf("unexpected success\nwant:\n%s\n", want) |
| 1772 | case failed && !correctFailure: |
| 1773 | msg = fmt.Sprintf("unexpected error\ngot:\n%s\n\nwant:\n%s\n", got, want) |
| 1774 | case mustFail: |
| 1775 | msg = "test failure" |
| 1776 | default: |
| 1777 | panic("internal error") |
| 1778 | } |
| 1779 |
| 1780 | return fmt.Errorf("%s\nextra stderr:\n%s", msg, extraStderr) |
| 1781 | } |
| 1782 |
| 1783 | if len(extraStderr) > 0 || (!failed && len(stderr) > 0) { |
| 1784 | return fmt.Errorf("unexpected error output:\n%s\n%s", stderr, extraStderr) |
| 1785 | } |
| 1786 |
| 1787 | if *useValgrind && isValgrindError { |
| 1788 | return fmt.Errorf("valgrind error:\n%s\n%s", stderr, extraStderr) |
| 1789 | } |
| 1790 |
| 1791 | return nil |
| 1792 | } |
| 1793 |
| 1794 | type tlsVersion struct { |
| 1795 | name string |
| 1796 | // version is the protocol version. |
| 1797 | version uint16 |
| 1798 | // excludeFlag is the legacy shim flag to disable the version. |
| 1799 | excludeFlag string |
| 1800 | hasDTLS bool |
| 1801 | hasQUIC bool |
| 1802 | // versionDTLS, if non-zero, is the DTLS-specific representation of the version. |
| 1803 | versionDTLS uint16 |
| 1804 | // versionWire, if non-zero, is the wire representation of the |
| 1805 | // version. Otherwise the wire version is the protocol version or |
| 1806 | // versionDTLS. |
| 1807 | versionWire uint16 |
| 1808 | } |
| 1809 |
| 1810 | func (vers tlsVersion) String() string { |
| 1811 | return vers.name |
| 1812 | } |
| 1813 |
| 1814 | func (vers tlsVersion) shimFlag(protocol protocol) string { |
| 1815 | // The shim uses the protocol version in its public API, but uses the |
| 1816 | // DTLS-specific version if it exists. |
| 1817 | if protocol == dtls && vers.versionDTLS != 0 { |
| 1818 | return strconv.Itoa(int(vers.versionDTLS)) |
| 1819 | } |
| 1820 | return strconv.Itoa(int(vers.version)) |
| 1821 | } |
| 1822 |
| 1823 | func (vers tlsVersion) wire(protocol protocol) uint16 { |
| 1824 | if protocol == dtls && vers.versionDTLS != 0 { |
| 1825 | return vers.versionDTLS |
| 1826 | } |
| 1827 | if vers.versionWire != 0 { |
| 1828 | return vers.versionWire |
| 1829 | } |
| 1830 | return vers.version |
| 1831 | } |
| 1832 |
| 1833 | func (vers tlsVersion) supportsProtocol(protocol protocol) bool { |
| 1834 | if protocol == dtls { |
| 1835 | return vers.hasDTLS |
| 1836 | } |
| 1837 | if protocol == quic { |
| 1838 | return vers.hasQUIC |
| 1839 | } |
| 1840 | return true |
| 1841 | } |
| 1842 |
| 1843 | var tlsVersions = []tlsVersion{ |
| 1844 | { |
| 1845 | name: "TLS1", |
| 1846 | version: VersionTLS10, |
| 1847 | excludeFlag: "-no-tls1", |
| 1848 | hasDTLS: true, |
| 1849 | versionDTLS: VersionDTLS10, |
| 1850 | }, |
| 1851 | { |
| 1852 | name: "TLS11", |
| 1853 | version: VersionTLS11, |
| 1854 | excludeFlag: "-no-tls11", |
| 1855 | }, |
| 1856 | { |
| 1857 | name: "TLS12", |
| 1858 | version: VersionTLS12, |
| 1859 | excludeFlag: "-no-tls12", |
| 1860 | hasDTLS: true, |
| 1861 | versionDTLS: VersionDTLS12, |
| 1862 | }, |
| 1863 | { |
| 1864 | name: "TLS13", |
| 1865 | version: VersionTLS13, |
| 1866 | excludeFlag: "-no-tls13", |
| 1867 | hasQUIC: true, |
| 1868 | hasDTLS: true, |
| 1869 | versionDTLS: VersionDTLS13, |
| 1870 | versionWire: VersionTLS13, |
| 1871 | }, |
| 1872 | } |
| 1873 |
| 1874 | func allVersions(protocol protocol) []tlsVersion { |
| 1875 | if protocol == tls { |
| 1876 | return tlsVersions |
| 1877 | } |
| 1878 |
| 1879 | var ret []tlsVersion |
| 1880 | for _, vers := range tlsVersions { |
| 1881 | if vers.supportsProtocol(protocol) { |
| 1882 | ret = append(ret, vers) |
| 1883 | } |
| 1884 | } |
| 1885 | return ret |
| 1886 | } |
| 1887 |
| 1888 | func convertToSplitHandshakeTests(tests []testCase) (splitHandshakeTests []testCase, err error) { |
| 1889 | var stdout bytes.Buffer |
| 1890 | var flags []string |
| 1891 | if len(*shimExtraFlags) > 0 { |
| 1892 | flags = strings.Split(*shimExtraFlags, ";") |
| 1893 | } |
| 1894 | flags = append(flags, "-is-handshaker-supported") |
| 1895 | shim := exec.Command(*shimPath, flags...) |
| 1896 | shim.Stdout = &stdout |
| 1897 | if err := shim.Run(); err != nil { |
| 1898 | return nil, err |
| 1899 | } |
| 1900 |
| 1901 | switch strings.TrimSpace(string(stdout.Bytes())) { |
| 1902 | case "No": |
| 1903 | return |
| 1904 | case "Yes": |
| 1905 | break |
| 1906 | default: |
| 1907 | return nil, fmt.Errorf("unknown output from shim: %q", stdout.Bytes()) |
| 1908 | } |
| 1909 |
| 1910 | var allowHintMismatchPattern []string |
| 1911 | if len(*allowHintMismatch) > 0 { |
| 1912 | allowHintMismatchPattern = strings.Split(*allowHintMismatch, ";") |
| 1913 | } |
| 1914 |
| 1915 | NextTest: |
| 1916 | for _, test := range tests { |
| 1917 | if test.protocol != tls || |
| 1918 | test.testType != serverTest || |
| 1919 | len(test.shimCredentials) != 0 || |
| 1920 | len(test.resumeShimCredentials) != 0 || |
| 1921 | strings.Contains(test.name, "ECH-Server") || |
| 1922 | test.skipSplitHandshake { |
| 1923 | continue |
| 1924 | } |
| 1925 |
| 1926 | for _, flag := range test.flags { |
| 1927 | if flag == "-implicit-handshake" { |
| 1928 | continue NextTest |
| 1929 | } |
| 1930 | } |
| 1931 |
| 1932 | shTest := test |
| 1933 | shTest.name += "-Split" |
| 1934 | shTest.flags = make([]string, len(test.flags), len(test.flags)+3) |
| 1935 | copy(shTest.flags, test.flags) |
| 1936 | shTest.flags = append(shTest.flags, "-handoff", "-handshaker-path", *handshakerPath) |
| 1937 |
| 1938 | splitHandshakeTests = append(splitHandshakeTests, shTest) |
| 1939 | } |
| 1940 |
| 1941 | for _, test := range tests { |
| 1942 | if test.protocol == dtls || |
| 1943 | test.testType != serverTest || |
| 1944 | test.skipHints { |
| 1945 | continue |
| 1946 | } |
| 1947 |
| 1948 | var matched bool |
| 1949 | if len(allowHintMismatchPattern) > 0 { |
| 1950 | matched, err = match(allowHintMismatchPattern, nil, test.name) |
| 1951 | if err != nil { |
| 1952 | return nil, fmt.Errorf("error matching pattern: %s", err) |
| 1953 | } |
| 1954 | } |
| 1955 |
| 1956 | shTest := test |
| 1957 | shTest.name += "-Hints" |
| 1958 | shTest.flags = make([]string, len(test.flags), len(test.flags)+3) |
| 1959 | copy(shTest.flags, test.flags) |
| 1960 | shTest.flags = append(shTest.flags, "-handshake-hints", "-handshaker-path", *handshakerPath) |
| 1961 | if matched { |
| 1962 | shTest.flags = append(shTest.flags, "-allow-hint-mismatch") |
| 1963 | } |
| 1964 |
| 1965 | splitHandshakeTests = append(splitHandshakeTests, shTest) |
| 1966 | } |
| 1967 |
| 1968 | return splitHandshakeTests, nil |
| 1969 | } |
| 1970 |
| 1971 | func worker(dispatcher *shimDispatcher, statusChan chan statusMsg, c chan *testCase, shimPath string, wg *sync.WaitGroup) { |
| 1972 | defer wg.Done() |
| 1973 |
| 1974 | for test := range c { |
| 1975 | var err error |
| 1976 |
| 1977 | if *mallocTest >= 0 { |
| 1978 | for mallocNumToFail := int64(*mallocTest); ; mallocNumToFail++ { |
| 1979 | statusChan <- statusMsg{test: test, statusType: statusStarted} |
| 1980 | if err = runTest(dispatcher, statusChan, test, shimPath, mallocNumToFail); err != errMoreMallocs { |
| 1981 | if err != nil { |
| 1982 | fmt.Printf("\n\nmalloc test failed at %d: %s\n", mallocNumToFail, err) |
| 1983 | } |
| 1984 | break |
| 1985 | } |
| 1986 | } |
| 1987 | } else if *repeatUntilFailure { |
| 1988 | for err == nil { |
| 1989 | statusChan <- statusMsg{test: test, statusType: statusStarted} |
| 1990 | err = runTest(dispatcher, statusChan, test, shimPath, -1) |
| 1991 | } |
| 1992 | } else { |
| 1993 | statusChan <- statusMsg{test: test, statusType: statusStarted} |
| 1994 | err = runTest(dispatcher, statusChan, test, shimPath, -1) |
| 1995 | } |
| 1996 | statusChan <- statusMsg{test: test, statusType: statusDone, err: err} |
| 1997 | } |
| 1998 | } |
| 1999 |
| 2000 | type statusType int |
| 2001 |
| 2002 | const ( |
| 2003 | statusStarted statusType = iota |
| 2004 | statusShimStarted |
| 2005 | statusDone |
| 2006 | ) |
| 2007 |
| 2008 | type statusMsg struct { |
| 2009 | test *testCase |
| 2010 | statusType statusType |
| 2011 | pid int |
| 2012 | err error |
| 2013 | } |
| 2014 |
| 2015 | func statusPrinter(doneChan chan *testresult.Results, statusChan chan statusMsg, total int) { |
| 2016 | var started, done, failed, unimplemented, lineLen int |
| 2017 |
| 2018 | testOutput := testresult.NewResults() |
| 2019 | for msg := range statusChan { |
| 2020 | if !*pipe { |
| 2021 | // Erase the previous status line. |
| 2022 | var erase string |
| 2023 | for i := 0; i < lineLen; i++ { |
| 2024 | erase += "\b \b" |
| 2025 | } |
| 2026 | fmt.Print(erase) |
| 2027 | } |
| 2028 |
| 2029 | if msg.statusType == statusStarted { |
| 2030 | started++ |
| 2031 | } else if msg.statusType == statusDone { |
| 2032 | done++ |
| 2033 |
| 2034 | if msg.err != nil { |
| 2035 | if msg.err == errUnimplemented { |
| 2036 | if *pipe { |
| 2037 | // Print each test instead of a status line. |
| 2038 | fmt.Printf("UNIMPLEMENTED (%s)\n", msg.test.name) |
| 2039 | } |
| 2040 | unimplemented++ |
| 2041 | if *allowUnimplemented { |
| 2042 | testOutput.AddSkip(msg.test.name) |
| 2043 | } else { |
| 2044 | testOutput.AddResult(msg.test.name, "SKIP", nil) |
| 2045 | } |
| 2046 | } else { |
| 2047 | fmt.Printf("FAILED (%s)\n%s\n", msg.test.name, msg.err) |
| 2048 | failed++ |
| 2049 | testOutput.AddResult(msg.test.name, "FAIL", msg.err) |
| 2050 | } |
| 2051 | } else { |
| 2052 | if *pipe { |
| 2053 | // Print each test instead of a status line. |
| 2054 | fmt.Printf("PASSED (%s)\n", msg.test.name) |
| 2055 | } |
| 2056 | testOutput.AddResult(msg.test.name, "PASS", nil) |
| 2057 | } |
| 2058 | } |
| 2059 |
| 2060 | if !*pipe { |
| 2061 | // Print a new status line. |
| 2062 | line := fmt.Sprintf("%d/%d/%d/%d/%d", failed, unimplemented, done, started, total) |
| 2063 | if msg.statusType == statusShimStarted && *waitForDebugger { |
| 2064 | // Note -wait-for-debugger limits the test to one worker, |
| 2065 | // otherwise some output would be skipped. |
| 2066 | line += fmt.Sprintf(" (%s: attach to process %d to continue)", msg.test.name, msg.pid) |
| 2067 | } |
| 2068 | lineLen = len(line) |
| 2069 | os.Stdout.WriteString(line) |
| 2070 | } |
| 2071 | } |
| 2072 |
| 2073 | doneChan <- testOutput |
| 2074 | } |
| 2075 |
| 2076 | func match(oneOfPatternIfAny []string, noneOfPattern []string, candidate string) (matched bool, err error) { |
| 2077 | matched = len(oneOfPatternIfAny) == 0 |
| 2078 |
| 2079 | var didMatch bool |
| 2080 | for _, pattern := range oneOfPatternIfAny { |
| 2081 | didMatch, err = filepath.Match(pattern, candidate) |
| 2082 | if err != nil { |
| 2083 | return false, err |
| 2084 | } |
| 2085 |
| 2086 | matched = didMatch || matched |
| 2087 | } |
| 2088 |
| 2089 | for _, pattern := range noneOfPattern { |
| 2090 | didMatch, err = filepath.Match(pattern, candidate) |
| 2091 | if err != nil { |
| 2092 | return false, err |
| 2093 | } |
| 2094 |
| 2095 | matched = !didMatch && matched |
| 2096 | } |
| 2097 |
| 2098 | return matched, nil |
| 2099 | } |
| 2100 |
| 2101 | func checkTests() { |
| 2102 | for _, test := range testCases { |
| 2103 | if !test.shouldFail && (len(test.expectedError) > 0 || len(test.expectedLocalError) > 0) { |
| 2104 | panic("Error expected without shouldFail in " + test.name) |
| 2105 | } |
| 2106 |
| 2107 | if test.expectResumeRejected && !test.resumeSession { |
| 2108 | panic("expectResumeRejected without resumeSession in " + test.name) |
| 2109 | } |
| 2110 |
| 2111 | if !test.skipVersionNameCheck { |
| 2112 | for _, ver := range tlsVersions { |
| 2113 | if !strings.Contains("-"+test.name+"-", "-"+ver.name+"-") { |
| 2114 | continue |
| 2115 | } |
| 2116 |
| 2117 | found := test.config.MaxVersion == ver.version || test.config.MinVersion == ver.version || test.expectations.version == ver.version |
| 2118 | if test.resumeConfig != nil { |
| 2119 | found = found || test.resumeConfig.MaxVersion == ver.version || test.resumeConfig.MinVersion == ver.version |
| 2120 | } |
| 2121 | if test.resumeExpectations != nil { |
| 2122 | found = found || test.resumeExpectations.version == ver.version |
| 2123 | } |
| 2124 | shimFlag := ver.shimFlag(test.protocol) |
| 2125 | for _, flag := range test.flags { |
| 2126 | if flag == shimFlag { |
| 2127 | found = true |
| 2128 | break |
| 2129 | } |
| 2130 | } |
| 2131 | if !found { |
| 2132 | panic(fmt.Sprintf("The name of test %q suggests that it's version specific, but the test does not reference %s", test.name, ver.name)) |
| 2133 | } |
| 2134 | } |
| 2135 | } |
| 2136 |
| 2137 | for _, protocol := range []protocol{tls, dtls, quic} { |
| 2138 | if strings.Contains("-"+test.name+"-", "-"+protocol.String()+"-") && test.protocol != protocol { |
| 2139 | panic(fmt.Sprintf("The name of test %q suggests that it tests %q, but the test does not reference it", test.name, protocol)) |
| 2140 | } |
| 2141 | } |
| 2142 | } |
| 2143 | } |
| 2144 |
| 2145 | func main() { |
| 2146 | flag.Parse() |
| 2147 | var err error |
| 2148 | if tmpDir, err = os.MkdirTemp("", "testing-certs"); err != nil { |
| 2149 | fmt.Fprintf(os.Stderr, "failed to make temporary directory: %s", err) |
| 2150 | os.Exit(1) |
| 2151 | } |
| 2152 | defer os.RemoveAll(tmpDir) |
| 2153 | initKeys() |
| 2154 | initCertificates() |
| 2155 |
| 2156 | if len(*shimConfigFile) != 0 { |
| 2157 | encoded, err := os.ReadFile(*shimConfigFile) |
| 2158 | if err != nil { |
| 2159 | fmt.Fprintf(os.Stderr, "Couldn't read config file %q: %s\n", *shimConfigFile, err) |
| 2160 | os.Exit(1) |
| 2161 | } |
| 2162 |
| 2163 | if err := json.Unmarshal(encoded, &shimConfig); err != nil { |
| 2164 | fmt.Fprintf(os.Stderr, "Couldn't decode config file %q: %s\n", *shimConfigFile, err) |
| 2165 | os.Exit(1) |
| 2166 | } |
| 2167 | } |
| 2168 |
| 2169 | if shimConfig.AllCurves == nil { |
| 2170 | for _, curve := range testCurves { |
| 2171 | shimConfig.AllCurves = append(shimConfig.AllCurves, int(curve.id)) |
| 2172 | } |
| 2173 | } |
| 2174 |
| 2175 | addBasicTests() |
| 2176 | addCipherSuiteTests() |
| 2177 | addBadECDSASignatureTests() |
| 2178 | addCBCPaddingTests() |
| 2179 | addCBCSplittingTests() |
| 2180 | addClientAuthTests() |
| 2181 | addDDoSCallbackTests() |
| 2182 | addVersionNegotiationTests() |
| 2183 | addMinimumVersionTests() |
| 2184 | addExtensionTests() |
| 2185 | addResumptionVersionTests() |
| 2186 | addExtendedMasterSecretTests() |
| 2187 | addRenegotiationTests() |
| 2188 | addDTLSReplayTests() |
| 2189 | addSignatureAlgorithmTests() |
| 2190 | addDTLSRetransmitTests() |
| 2191 | addDTLSReorderTests() |
| 2192 | addExportKeyingMaterialTests() |
| 2193 | addExportTrafficSecretsTests() |
| 2194 | addTLSUniqueTests() |
| 2195 | addUnknownExtensionTests() |
| 2196 | addRSAClientKeyExchangeTests() |
| 2197 | addCurveTests() |
| 2198 | addSessionTicketTests() |
| 2199 | addTLS13RecordTests() |
| 2200 | addAllStateMachineCoverageTests() |
| 2201 | addChangeCipherSpecTests() |
| 2202 | addEndOfFlightTests() |
| 2203 | addWrongMessageTypeTests() |
| 2204 | addTrailingMessageDataTests() |
| 2205 | addTLS13HandshakeTests() |
| 2206 | addTLS13CipherPreferenceTests() |
| 2207 | addPeekTests() |
| 2208 | addRecordVersionTests() |
| 2209 | addCertificateTests() |
| 2210 | addRetainOnlySHA256ClientCertTests() |
| 2211 | addECDSAKeyUsageTests() |
| 2212 | addRSAKeyUsageTests() |
| 2213 | addExtraHandshakeTests() |
| 2214 | addOmitExtensionsTests() |
| 2215 | addCertCompressionTests() |
| 2216 | addJDK11WorkaroundTests() |
| 2217 | addDelegatedCredentialTests() |
| 2218 | addEncryptedClientHelloTests() |
| 2219 | addHintMismatchTests() |
| 2220 | addCompliancePolicyTests() |
| 2221 | addCertificateSelectionTests() |
| 2222 | addKeyUpdateTests() |
| 2223 | addPAKETests() |
| 2224 | addTrustAnchorTests() |
| 2225 |
| 2226 | toAppend, err := convertToSplitHandshakeTests(testCases) |
| 2227 | if err != nil { |
| 2228 | fmt.Fprintf(os.Stderr, "Error making split handshake tests: %s", err) |
| 2229 | os.Exit(1) |
| 2230 | } |
| 2231 | testCases = append(testCases, toAppend...) |
| 2232 |
| 2233 | checkTests() |
| 2234 |
| 2235 | dispatcher, err := newShimDispatcher() |
| 2236 | if err != nil { |
| 2237 | fmt.Fprintf(os.Stderr, "Error opening socket: %s", err) |
| 2238 | os.Exit(1) |
| 2239 | } |
| 2240 | defer dispatcher.Close() |
| 2241 |
| 2242 | numWorkers := *numWorkersFlag |
| 2243 | if useDebugger() { |
| 2244 | numWorkers = 1 |
| 2245 | } |
| 2246 |
| 2247 | statusChan := make(chan statusMsg, numWorkers) |
| 2248 | testChan := make(chan *testCase, numWorkers) |
| 2249 | doneChan := make(chan *testresult.Results) |
| 2250 |
| 2251 | go statusPrinter(doneChan, statusChan, len(testCases)) |
| 2252 |
| 2253 | var wg sync.WaitGroup |
| 2254 | for i := 0; i < numWorkers; i++ { |
| 2255 | wg.Add(1) |
| 2256 | go worker(dispatcher, statusChan, testChan, *shimPath, &wg) |
| 2257 | } |
| 2258 |
| 2259 | var oneOfPatternIfAny, noneOfPattern []string |
| 2260 | if len(*testToRun) > 0 { |
| 2261 | oneOfPatternIfAny = strings.Split(*testToRun, ";") |
| 2262 | } |
| 2263 | if len(*skipTest) > 0 { |
| 2264 | noneOfPattern = strings.Split(*skipTest, ";") |
| 2265 | } |
| 2266 |
| 2267 | shardIndex, shardTotal, err := getSharding() |
| 2268 | if err != nil { |
| 2269 | fmt.Fprintln(os.Stderr, err) |
| 2270 | os.Exit(1) |
| 2271 | } |
| 2272 |
| 2273 | if shardTotal > 0 { |
| 2274 | fmt.Printf("This is shard %d of 0..%d (inclusive)\n", shardIndex, shardTotal-1) |
| 2275 | } |
| 2276 |
| 2277 | var foundTest bool |
| 2278 | for i := range testCases { |
| 2279 | if shardTotal > 0 && i%shardTotal != shardIndex { |
| 2280 | continue |
| 2281 | } |
| 2282 |
| 2283 | matched, err := match(oneOfPatternIfAny, noneOfPattern, testCases[i].name) |
| 2284 | if err != nil { |
| 2285 | fmt.Fprintf(os.Stderr, "Error matching pattern: %s\n", err) |
| 2286 | os.Exit(1) |
| 2287 | } |
| 2288 |
| 2289 | if !*includeDisabled { |
| 2290 | for pattern := range shimConfig.DisabledTests { |
| 2291 | isDisabled, err := filepath.Match(pattern, testCases[i].name) |
| 2292 | if err != nil { |
| 2293 | fmt.Fprintf(os.Stderr, "Error matching pattern %q from config file: %s\n", pattern, err) |
| 2294 | os.Exit(1) |
| 2295 | } |
| 2296 |
| 2297 | if isDisabled { |
| 2298 | matched = false |
| 2299 | break |
| 2300 | } |
| 2301 | } |
| 2302 | } |
| 2303 |
| 2304 | if matched { |
| 2305 | if foundTest && *useRR { |
| 2306 | fmt.Fprintf(os.Stderr, "Too many matching tests. Only one test can run when RR is enabled.\n") |
| 2307 | os.Exit(1) |
| 2308 | } |
| 2309 |
| 2310 | foundTest = true |
| 2311 | testChan <- &testCases[i] |
| 2312 |
| 2313 | // Only run one test if repeating until failure. |
| 2314 | if *repeatUntilFailure { |
| 2315 | break |
| 2316 | } |
| 2317 | } |
| 2318 | } |
| 2319 |
| 2320 | if !foundTest && shardTotal == 0 { |
| 2321 | fmt.Fprintf(os.Stderr, "No tests run\n") |
| 2322 | os.Exit(1) |
| 2323 | } |
| 2324 |
| 2325 | close(testChan) |
| 2326 | wg.Wait() |
| 2327 | close(statusChan) |
| 2328 | testOutput := <-doneChan |
| 2329 |
| 2330 | fmt.Printf("\n") |
| 2331 |
| 2332 | if *jsonOutput != "" { |
| 2333 | if err := testOutput.WriteToFile(*jsonOutput); err != nil { |
| 2334 | fmt.Fprintf(os.Stderr, "Error: %s\n", err) |
| 2335 | } |
| 2336 | } |
| 2337 |
| 2338 | if *useRR { |
| 2339 | fmt.Println("RR trace recorded. Replay with `rr replay`.") |
| 2340 | } |
| 2341 |
| 2342 | if !testOutput.HasUnexpectedResults() { |
| 2343 | os.Exit(1) |
| 2344 | } |
| 2345 | } |
| 2346 |