1// Copyright 2009 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 5package runner 6 7import ( 8 "container/list" 9 "crypto" 10 "crypto/ecdsa" 11 "crypto/rand" 12 "crypto/x509" 13 "fmt" 14 "io" 15 "math/big" 16 "strings" 17 "sync" 18 "time" 19) 20 21const ( 22 VersionSSL30 = 0x0300 23 VersionTLS10 = 0x0301 24 VersionTLS11 = 0x0302 25 VersionTLS12 = 0x0303 26 VersionTLS13 = 0x0304 27) 28 29const ( 30 VersionDTLS10 = 0xfeff 31 VersionDTLS12 = 0xfefd 32) 33 34var allTLSWireVersions = []uint16{ 35 VersionTLS13, 36 VersionTLS12, 37 VersionTLS11, 38 VersionTLS10, 39 VersionSSL30, 40} 41 42var allDTLSWireVersions = []uint16{ 43 VersionDTLS12, 44 VersionDTLS10, 45} 46 47const ( 48 maxPlaintext = 16384 // maximum plaintext payload length 49 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length 50 tlsRecordHeaderLen = 5 // record header length 51 dtlsRecordHeaderLen = 13 52 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB) 53 54 minVersion = VersionSSL30 55 maxVersion = VersionTLS13 56) 57 58// TLS record types. 59type recordType uint8 60 61const ( 62 recordTypeChangeCipherSpec recordType = 20 63 recordTypeAlert recordType = 21 64 recordTypeHandshake recordType = 22 65 recordTypeApplicationData recordType = 23 66 recordTypePlaintextHandshake recordType = 24 67) 68 69// TLS handshake message types. 70const ( 71 typeHelloRequest uint8 = 0 72 typeClientHello uint8 = 1 73 typeServerHello uint8 = 2 74 typeHelloVerifyRequest uint8 = 3 75 typeNewSessionTicket uint8 = 4 76 typeEndOfEarlyData uint8 = 5 77 typeHelloRetryRequest uint8 = 6 78 typeEncryptedExtensions uint8 = 8 79 typeCertificate uint8 = 11 80 typeServerKeyExchange uint8 = 12 81 typeCertificateRequest uint8 = 13 82 typeServerHelloDone uint8 = 14 83 typeCertificateVerify uint8 = 15 84 typeClientKeyExchange uint8 = 16 85 typeFinished uint8 = 20 86 typeCertificateStatus uint8 = 22 87 typeKeyUpdate uint8 = 24 88 typeCompressedCertificate uint8 = 25 // Not IANA assigned 89 typeNextProtocol uint8 = 67 // Not IANA assigned 90 typeChannelID uint8 = 203 // Not IANA assigned 91 typeMessageHash uint8 = 254 92) 93 94// TLS compression types. 95const ( 96 compressionNone uint8 = 0 97) 98 99// TLS extension numbers 100const ( 101 extensionServerName uint16 = 0 102 extensionStatusRequest uint16 = 5 103 extensionSupportedCurves uint16 = 10 104 extensionSupportedPoints uint16 = 11 105 extensionSignatureAlgorithms uint16 = 13 106 extensionUseSRTP uint16 = 14 107 extensionALPN uint16 = 16 108 extensionSignedCertificateTimestamp uint16 = 18 109 extensionPadding uint16 = 21 110 extensionExtendedMasterSecret uint16 = 23 111 extensionTokenBinding uint16 = 24 112 extensionCompressedCertAlgs uint16 = 27 113 extensionSessionTicket uint16 = 35 114 extensionPreSharedKey uint16 = 41 115 extensionEarlyData uint16 = 42 116 extensionSupportedVersions uint16 = 43 117 extensionCookie uint16 = 44 118 extensionPSKKeyExchangeModes uint16 = 45 119 extensionCertificateAuthorities uint16 = 47 120 extensionSignatureAlgorithmsCert uint16 = 50 121 extensionKeyShare uint16 = 51 122 extensionCustom uint16 = 1234 // not IANA assigned 123 extensionNextProtoNeg uint16 = 13172 // not IANA assigned 124 extensionRenegotiationInfo uint16 = 0xff01 125 extensionQUICTransportParams uint16 = 0xffa5 // draft-ietf-quic-tls-13 126 extensionChannelID uint16 = 30032 // not IANA assigned 127 extensionDelegatedCredentials uint16 = 0xff02 // not IANA assigned 128) 129 130// TLS signaling cipher suite values 131const ( 132 scsvRenegotiation uint16 = 0x00ff 133) 134 135var tls13HelloRetryRequest = []uint8{ 136 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 137 0x02, 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 138 0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c, 139} 140 141// CurveID is the type of a TLS identifier for an elliptic curve. See 142// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8 143type CurveID uint16 144 145const ( 146 CurveP224 CurveID = 21 147 CurveP256 CurveID = 23 148 CurveP384 CurveID = 24 149 CurveP521 CurveID = 25 150 CurveX25519 CurveID = 29 151 CurveCECPQ2 CurveID = 16696 152) 153 154// TLS Elliptic Curve Point Formats 155// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9 156const ( 157 pointFormatUncompressed uint8 = 0 158 pointFormatCompressedPrime uint8 = 1 159) 160 161// TLS CertificateStatusType (RFC 3546) 162const ( 163 statusTypeOCSP uint8 = 1 164) 165 166// Certificate types (for certificateRequestMsg) 167const ( 168 CertTypeRSASign = 1 // A certificate containing an RSA key 169 CertTypeDSSSign = 2 // A certificate containing a DSA key 170 CertTypeRSAFixedDH = 3 // A certificate containing a static DH key 171 CertTypeDSSFixedDH = 4 // A certificate containing a static DH key 172 173 // See RFC4492 sections 3 and 5.5. 174 CertTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA. 175 CertTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA. 176 CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA. 177 178 // Rest of these are reserved by the TLS spec 179) 180 181// signatureAlgorithm corresponds to a SignatureScheme value from TLS 1.3. Note 182// that TLS 1.3 names the production 'SignatureScheme' to avoid colliding with 183// TLS 1.2's SignatureAlgorithm but otherwise refers to them as 'signature 184// algorithms' throughout. We match the latter. 185type signatureAlgorithm uint16 186 187const ( 188 // RSASSA-PKCS1-v1_5 algorithms 189 signatureRSAPKCS1WithMD5 signatureAlgorithm = 0x0101 190 signatureRSAPKCS1WithSHA1 signatureAlgorithm = 0x0201 191 signatureRSAPKCS1WithSHA256 signatureAlgorithm = 0x0401 192 signatureRSAPKCS1WithSHA384 signatureAlgorithm = 0x0501 193 signatureRSAPKCS1WithSHA512 signatureAlgorithm = 0x0601 194 195 // ECDSA algorithms 196 signatureECDSAWithSHA1 signatureAlgorithm = 0x0203 197 signatureECDSAWithP256AndSHA256 signatureAlgorithm = 0x0403 198 signatureECDSAWithP384AndSHA384 signatureAlgorithm = 0x0503 199 signatureECDSAWithP521AndSHA512 signatureAlgorithm = 0x0603 200 201 // RSASSA-PSS algorithms 202 signatureRSAPSSWithSHA256 signatureAlgorithm = 0x0804 203 signatureRSAPSSWithSHA384 signatureAlgorithm = 0x0805 204 signatureRSAPSSWithSHA512 signatureAlgorithm = 0x0806 205 206 // EdDSA algorithms 207 signatureEd25519 signatureAlgorithm = 0x0807 208 signatureEd448 signatureAlgorithm = 0x0808 209) 210 211// supportedSignatureAlgorithms contains the default supported signature 212// algorithms. 213var supportedSignatureAlgorithms = []signatureAlgorithm{ 214 signatureRSAPSSWithSHA256, 215 signatureRSAPKCS1WithSHA256, 216 signatureECDSAWithP256AndSHA256, 217 signatureRSAPKCS1WithSHA1, 218 signatureECDSAWithSHA1, 219 signatureEd25519, 220} 221 222// SRTP protection profiles (See RFC 5764, section 4.1.2) 223const ( 224 SRTP_AES128_CM_HMAC_SHA1_80 uint16 = 0x0001 225 SRTP_AES128_CM_HMAC_SHA1_32 = 0x0002 226) 227 228// PskKeyExchangeMode values (see RFC 8446, section 4.2.9) 229const ( 230 pskKEMode = 0 231 pskDHEKEMode = 1 232) 233 234// KeyUpdateRequest values (see RFC 8446, section 4.6.3) 235const ( 236 keyUpdateNotRequested = 0 237 keyUpdateRequested = 1 238) 239 240// ConnectionState records basic TLS details about the connection. 241type ConnectionState struct { 242 Version uint16 // TLS version used by the connection (e.g. VersionTLS12) 243 HandshakeComplete bool // TLS handshake is complete 244 DidResume bool // connection resumes a previous TLS connection 245 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...) 246 NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos) 247 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server 248 NegotiatedProtocolFromALPN bool // protocol negotiated with ALPN 249 ServerName string // server name requested by client, if any (server side only) 250 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer 251 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates 252 ChannelID *ecdsa.PublicKey // the channel ID for this connection 253 TokenBindingNegotiated bool // whether Token Binding was negotiated 254 TokenBindingParam uint8 // the negotiated Token Binding key parameter 255 SRTPProtectionProfile uint16 // the negotiated DTLS-SRTP protection profile 256 TLSUnique []byte // the tls-unique channel binding 257 SCTList []byte // signed certificate timestamp list 258 PeerSignatureAlgorithm signatureAlgorithm // algorithm used by the peer in the handshake 259 CurveID CurveID // the curve used in ECDHE 260 QUICTransportParams []byte // the QUIC transport params received from the peer 261} 262 263// ClientAuthType declares the policy the server will follow for 264// TLS Client Authentication. 265type ClientAuthType int 266 267const ( 268 NoClientCert ClientAuthType = iota 269 RequestClientCert 270 RequireAnyClientCert 271 VerifyClientCertIfGiven 272 RequireAndVerifyClientCert 273) 274 275// ClientSessionState contains the state needed by clients to resume TLS 276// sessions. 277type ClientSessionState struct { 278 sessionId []uint8 // Session ID supplied by the server. nil if the session has a ticket. 279 sessionTicket []uint8 // Encrypted ticket used for session resumption with server 280 vers uint16 // SSL/TLS version negotiated for the session 281 wireVersion uint16 // Wire SSL/TLS version negotiated for the session 282 cipherSuite uint16 // Ciphersuite negotiated for the session 283 masterSecret []byte // MasterSecret generated by client on a full handshake 284 handshakeHash []byte // Handshake hash for Channel ID purposes. 285 serverCertificates []*x509.Certificate // Certificate chain presented by the server 286 extendedMasterSecret bool // Whether an extended master secret was used to generate the session 287 sctList []byte 288 ocspResponse []byte 289 earlyALPN string 290 ticketCreationTime time.Time 291 ticketExpiration time.Time 292 ticketAgeAdd uint32 293 maxEarlyDataSize uint32 294} 295 296// ClientSessionCache is a cache of ClientSessionState objects that can be used 297// by a client to resume a TLS session with a given server. ClientSessionCache 298// implementations should expect to be called concurrently from different 299// goroutines. 300type ClientSessionCache interface { 301 // Get searches for a ClientSessionState associated with the given key. 302 // On return, ok is true if one was found. 303 Get(sessionKey string) (session *ClientSessionState, ok bool) 304 305 // Put adds the ClientSessionState to the cache with the given key. 306 Put(sessionKey string, cs *ClientSessionState) 307} 308 309// ServerSessionCache is a cache of sessionState objects that can be used by a 310// client to resume a TLS session with a given server. ServerSessionCache 311// implementations should expect to be called concurrently from different 312// goroutines. 313type ServerSessionCache interface { 314 // Get searches for a sessionState associated with the given session 315 // ID. On return, ok is true if one was found. 316 Get(sessionId string) (session *sessionState, ok bool) 317 318 // Put adds the sessionState to the cache with the given session ID. 319 Put(sessionId string, session *sessionState) 320} 321 322// CertCompressionAlg is a certificate compression algorithm, specified as a 323// pair of functions for compressing and decompressing certificates. 324type CertCompressionAlg struct { 325 // Compress returns a compressed representation of the input. 326 Compress func([]byte) []byte 327 // Decompress depresses the contents of in and writes the result to out, which 328 // will be the correct size. It returns true on success and false otherwise. 329 Decompress func(out, in []byte) bool 330} 331 332// A Config structure is used to configure a TLS client or server. 333// After one has been passed to a TLS function it must not be 334// modified. A Config may be reused; the tls package will also not 335// modify it. 336type Config struct { 337 // Rand provides the source of entropy for nonces and RSA blinding. 338 // If Rand is nil, TLS uses the cryptographic random reader in package 339 // crypto/rand. 340 // The Reader must be safe for use by multiple goroutines. 341 Rand io.Reader 342 343 // Time returns the current time as the number of seconds since the epoch. 344 // If Time is nil, TLS uses time.Now. 345 Time func() time.Time 346 347 // Certificates contains one or more certificate chains 348 // to present to the other side of the connection. 349 // Server configurations must include at least one certificate. 350 Certificates []Certificate 351 352 // NameToCertificate maps from a certificate name to an element of 353 // Certificates. Note that a certificate name can be of the form 354 // '*.example.com' and so doesn't have to be a domain name as such. 355 // See Config.BuildNameToCertificate 356 // The nil value causes the first element of Certificates to be used 357 // for all connections. 358 NameToCertificate map[string]*Certificate 359 360 // RootCAs defines the set of root certificate authorities 361 // that clients use when verifying server certificates. 362 // If RootCAs is nil, TLS uses the host's root CA set. 363 RootCAs *x509.CertPool 364 365 // NextProtos is a list of supported, application level protocols. 366 NextProtos []string 367 368 // ServerName is used to verify the hostname on the returned 369 // certificates unless InsecureSkipVerify is given. It is also included 370 // in the client's handshake to support virtual hosting. 371 ServerName string 372 373 // ClientAuth determines the server's policy for 374 // TLS Client Authentication. The default is NoClientCert. 375 ClientAuth ClientAuthType 376 377 // ClientCAs defines the set of root certificate authorities 378 // that servers use if required to verify a client certificate 379 // by the policy in ClientAuth. 380 ClientCAs *x509.CertPool 381 382 // ClientCertificateTypes defines the set of allowed client certificate 383 // types. The default is CertTypeRSASign and CertTypeECDSASign. 384 ClientCertificateTypes []byte 385 386 // InsecureSkipVerify controls whether a client verifies the 387 // server's certificate chain and host name. 388 // If InsecureSkipVerify is true, TLS accepts any certificate 389 // presented by the server and any host name in that certificate. 390 // In this mode, TLS is susceptible to man-in-the-middle attacks. 391 // This should be used only for testing. 392 InsecureSkipVerify bool 393 394 // CipherSuites is a list of supported cipher suites. If CipherSuites 395 // is nil, TLS uses a list of suites supported by the implementation. 396 CipherSuites []uint16 397 398 // PreferServerCipherSuites controls whether the server selects the 399 // client's most preferred ciphersuite, or the server's most preferred 400 // ciphersuite. If true then the server's preference, as expressed in 401 // the order of elements in CipherSuites, is used. 402 PreferServerCipherSuites bool 403 404 // SessionTicketsDisabled may be set to true to disable session ticket 405 // (resumption) support. 406 SessionTicketsDisabled bool 407 408 // SessionTicketKey is used by TLS servers to provide session 409 // resumption. See RFC 5077. If zero, it will be filled with 410 // random data before the first server handshake. 411 // 412 // If multiple servers are terminating connections for the same host 413 // they should all have the same SessionTicketKey. If the 414 // SessionTicketKey leaks, previously recorded and future TLS 415 // connections using that key are compromised. 416 SessionTicketKey [32]byte 417 418 // ClientSessionCache is a cache of ClientSessionState entries 419 // for TLS session resumption. 420 ClientSessionCache ClientSessionCache 421 422 // ServerSessionCache is a cache of sessionState entries for TLS session 423 // resumption. 424 ServerSessionCache ServerSessionCache 425 426 // MinVersion contains the minimum SSL/TLS version that is acceptable. 427 // If zero, then SSLv3 is taken as the minimum. 428 MinVersion uint16 429 430 // MaxVersion contains the maximum SSL/TLS version that is acceptable. 431 // If zero, then the maximum version supported by this package is used, 432 // which is currently TLS 1.2. 433 MaxVersion uint16 434 435 // CurvePreferences contains the elliptic curves that will be used in 436 // an ECDHE handshake, in preference order. If empty, the default will 437 // be used. 438 CurvePreferences []CurveID 439 440 // DefaultCurves contains the elliptic curves for which public values will 441 // be sent in the ClientHello's KeyShare extension. If this value is nil, 442 // all supported curves will have public values sent. This field is ignored 443 // on servers. 444 DefaultCurves []CurveID 445 446 // ChannelID contains the ECDSA key for the client to use as 447 // its TLS Channel ID. 448 ChannelID *ecdsa.PrivateKey 449 450 // RequestChannelID controls whether the server requests a TLS 451 // Channel ID. If negotiated, the client's public key is 452 // returned in the ConnectionState. 453 RequestChannelID bool 454 455 // TokenBindingParams contains a list of TokenBindingKeyParameters 456 // (draft-ietf-tokbind-protocol-16) to attempt to negotiate. If 457 // nil, Token Binding will not be negotiated. 458 TokenBindingParams []byte 459 460 // TokenBindingVersion contains the serialized ProtocolVersion to 461 // use when negotiating Token Binding. 462 TokenBindingVersion uint16 463 464 // ExpectTokenBindingParams is checked by a server that the client 465 // sent ExpectTokenBindingParams as its list of Token Binding 466 // paramters. 467 ExpectTokenBindingParams []byte 468 469 // PreSharedKey, if not nil, is the pre-shared key to use with 470 // the PSK cipher suites. 471 PreSharedKey []byte 472 473 // PreSharedKeyIdentity, if not empty, is the identity to use 474 // with the PSK cipher suites. 475 PreSharedKeyIdentity string 476 477 // MaxEarlyDataSize controls the maximum number of bytes that the 478 // server will accept in early data and advertise in a 479 // NewSessionTicketMsg. If 0, no early data will be accepted and 480 // the early_data extension in the NewSessionTicketMsg will be omitted. 481 MaxEarlyDataSize uint32 482 483 // SRTPProtectionProfiles, if not nil, is the list of SRTP 484 // protection profiles to offer in DTLS-SRTP. 485 SRTPProtectionProfiles []uint16 486 487 // SignSignatureAlgorithms, if not nil, overrides the default set of 488 // supported signature algorithms to sign with. 489 SignSignatureAlgorithms []signatureAlgorithm 490 491 // VerifySignatureAlgorithms, if not nil, overrides the default set of 492 // supported signature algorithms that are accepted. 493 VerifySignatureAlgorithms []signatureAlgorithm 494 495 // QUICTransportParams, if not empty, will be sent in the QUIC 496 // transport parameters extension. 497 QUICTransportParams []byte 498 499 CertCompressionAlgs map[uint16]CertCompressionAlg 500 501 // Bugs specifies optional misbehaviour to be used for testing other 502 // implementations. 503 Bugs ProtocolBugs 504 505 serverInitOnce sync.Once // guards calling (*Config).serverInit 506} 507 508type BadValue int 509 510const ( 511 BadValueNone BadValue = iota 512 BadValueNegative 513 BadValueZero 514 BadValueLimit 515 BadValueLarge 516 NumBadValues 517) 518 519type RSABadValue int 520 521const ( 522 RSABadValueNone RSABadValue = iota 523 RSABadValueCorrupt 524 RSABadValueTooLong 525 RSABadValueTooShort 526 RSABadValueWrongVersion1 527 RSABadValueWrongVersion2 528 RSABadValueWrongBlockType 529 RSABadValueWrongLeadingByte 530 RSABadValueNoZero 531 NumRSABadValues 532) 533 534type ProtocolBugs struct { 535 // InvalidSignature specifies that the signature in a ServerKeyExchange 536 // or CertificateVerify message should be invalid. 537 InvalidSignature bool 538 539 // SendCurve, if non-zero, causes the server to send the specified curve 540 // ID in ServerKeyExchange (TLS 1.2) or ServerHello (TLS 1.3) rather 541 // than the negotiated one. 542 SendCurve CurveID 543 544 // InvalidECDHPoint, if true, causes the ECC points in 545 // ServerKeyExchange or ClientKeyExchange messages to be invalid. 546 InvalidECDHPoint bool 547 548 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature 549 // can be invalid. 550 BadECDSAR BadValue 551 BadECDSAS BadValue 552 553 // MaxPadding causes CBC records to have the maximum possible padding. 554 MaxPadding bool 555 // PaddingFirstByteBad causes the first byte of the padding to be 556 // incorrect. 557 PaddingFirstByteBad bool 558 // PaddingFirstByteBadIf255 causes the first byte of padding to be 559 // incorrect if there's a maximum amount of padding (i.e. 255 bytes). 560 PaddingFirstByteBadIf255 bool 561 562 // FailIfNotFallbackSCSV causes a server handshake to fail if the 563 // client doesn't send the fallback SCSV value. 564 FailIfNotFallbackSCSV bool 565 566 // DuplicateExtension causes an extra empty extension of bogus type to 567 // be emitted in either the ClientHello or the ServerHello. 568 DuplicateExtension bool 569 570 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA 571 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No 572 // Certificate message is sent and no signature is added to 573 // ServerKeyExchange. 574 UnauthenticatedECDH bool 575 576 // SkipHelloVerifyRequest causes a DTLS server to skip the 577 // HelloVerifyRequest message. 578 SkipHelloVerifyRequest bool 579 580 // SkipCertificateStatus, if true, causes the server to skip the 581 // CertificateStatus message. This is legal because CertificateStatus is 582 // optional, even with a status_request in ServerHello. 583 SkipCertificateStatus bool 584 585 // SkipServerKeyExchange causes the server to skip sending 586 // ServerKeyExchange messages. 587 SkipServerKeyExchange bool 588 589 // SkipNewSessionTicket causes the server to skip sending the 590 // NewSessionTicket message despite promising to in ServerHello. 591 SkipNewSessionTicket bool 592 593 // UseFirstSessionTicket causes the client to cache only the first session 594 // ticket received. 595 UseFirstSessionTicket bool 596 597 // SkipClientCertificate causes the client to skip the Certificate 598 // message. 599 SkipClientCertificate bool 600 601 // SkipChangeCipherSpec causes the implementation to skip 602 // sending the ChangeCipherSpec message (and adjusting cipher 603 // state accordingly for the Finished message). 604 SkipChangeCipherSpec bool 605 606 // SkipFinished causes the implementation to skip sending the Finished 607 // message. 608 SkipFinished bool 609 610 // SkipEndOfEarlyData causes the implementation to skip 611 // end_of_early_data. 612 SkipEndOfEarlyData bool 613 614 // NonEmptyEndOfEarlyData causes the implementation to end an extra byte in the 615 // EndOfEarlyData. 616 NonEmptyEndOfEarlyData bool 617 618 // SkipCertificateVerify, if true causes peer to skip sending a 619 // CertificateVerify message after the Certificate message. 620 SkipCertificateVerify bool 621 622 // EarlyChangeCipherSpec causes the client to send an early 623 // ChangeCipherSpec message before the ClientKeyExchange. A value of 624 // zero disables this behavior. One and two configure variants for 625 // 1.0.1 and 0.9.8 modes, respectively. 626 EarlyChangeCipherSpec int 627 628 // StrayChangeCipherSpec causes every pre-ChangeCipherSpec handshake 629 // message in DTLS to be prefaced by stray ChangeCipherSpec record. This 630 // may be used to test DTLS's handling of reordered ChangeCipherSpec. 631 StrayChangeCipherSpec bool 632 633 // ReorderChangeCipherSpec causes the ChangeCipherSpec message to be 634 // sent at start of each flight in DTLS. Unlike EarlyChangeCipherSpec, 635 // the cipher change happens at the usual time. 636 ReorderChangeCipherSpec bool 637 638 // FragmentAcrossChangeCipherSpec causes the implementation to fragment 639 // the Finished (or NextProto) message around the ChangeCipherSpec 640 // messages. 641 FragmentAcrossChangeCipherSpec bool 642 643 // SendExtraChangeCipherSpec causes the implementation to send extra 644 // ChangeCipherSpec messages. 645 SendExtraChangeCipherSpec int 646 647 // SendPostHandshakeChangeCipherSpec causes the implementation to send 648 // a ChangeCipherSpec record before every application data record. 649 SendPostHandshakeChangeCipherSpec bool 650 651 // SendUnencryptedFinished, if true, causes the Finished message to be 652 // send unencrypted before ChangeCipherSpec rather than after it. 653 SendUnencryptedFinished bool 654 655 // PartialEncryptedExtensionsWithServerHello, if true, causes the TLS 656 // 1.3 server to send part of EncryptedExtensions unencrypted 657 // in the same record as ServerHello. 658 PartialEncryptedExtensionsWithServerHello bool 659 660 // PartialClientFinishedWithClientHello, if true, causes the TLS 1.2 661 // or TLS 1.3 client to send part of Finished unencrypted in the same 662 // record as ClientHello. 663 PartialClientFinishedWithClientHello bool 664 665 // PartialClientFinishedWithSecondClientHello, if true, causes the 666 // TLS 1.3 client to send part of Finished unencrypted in the same 667 // record as the second ClientHello. 668 PartialClientFinishedWithSecondClientHello bool 669 670 // PartialEndOfEarlyDataWithClientHello, if true, causes the TLS 1.3 671 // client to send part of EndOfEarlyData unencrypted in the same record 672 // as ClientHello. 673 PartialEndOfEarlyDataWithClientHello bool 674 675 // PartialSecondClientHelloAfterFirst, if true, causes the TLS 1.3 client 676 // to send part of the second ClientHello in the same record as the first 677 // one. 678 PartialSecondClientHelloAfterFirst bool 679 680 // PartialClientKeyExchangeWithClientHello, if true, causes the TLS 1.2 681 // client to send part of the ClientKeyExchange in the same record as 682 // the ClientHello. 683 PartialClientKeyExchangeWithClientHello bool 684 685 // PartialNewSessionTicketWithServerHelloDone, if true, causes the TLS 1.2 686 // server to send part of the NewSessionTicket in the same record as 687 // ServerHelloDone. 688 PartialNewSessionTicketWithServerHelloDone bool 689 690 // PartialNewSessionTicketWithServerHelloDone, if true, causes the TLS 1.2 691 // server to send part of the Finshed in the same record as ServerHelloDone. 692 PartialFinishedWithServerHelloDone bool 693 694 // PartialServerHelloWithHelloRetryRequest, if true, causes the TLS 1.3 695 // server to send part of the ServerHello in the same record as 696 // HelloRetryRequest. 697 PartialServerHelloWithHelloRetryRequest bool 698 699 // TrailingDataWithFinished, if true, causes the record containing the 700 // Finished message to include an extra byte of data at the end. 701 TrailingDataWithFinished bool 702 703 // SendV2ClientHello causes the client to send a V2ClientHello 704 // instead of a normal ClientHello. 705 SendV2ClientHello bool 706 707 // SendFallbackSCSV causes the client to include 708 // TLS_FALLBACK_SCSV in the ClientHello. 709 SendFallbackSCSV bool 710 711 // SendRenegotiationSCSV causes the client to include the renegotiation 712 // SCSV in the ClientHello. 713 SendRenegotiationSCSV bool 714 715 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a 716 // handshake record. Handshake messages will be split into multiple 717 // records at the specified size, except that the client_version will 718 // never be fragmented. For DTLS, it is the maximum handshake fragment 719 // size, not record size; DTLS allows multiple handshake fragments in a 720 // single handshake record. See |PackHandshakeFragments|. 721 MaxHandshakeRecordLength int 722 723 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to 724 // the first 6 bytes of the ClientHello. 725 FragmentClientVersion bool 726 727 // FragmentAlert will cause all alerts to be fragmented across 728 // two records. 729 FragmentAlert bool 730 731 // DoubleAlert will cause all alerts to be sent as two copies packed 732 // within one record. 733 DoubleAlert bool 734 735 // SendSpuriousAlert, if non-zero, will cause an spurious, unwanted 736 // alert to be sent. 737 SendSpuriousAlert alert 738 739 // BadRSAClientKeyExchange causes the client to send a corrupted RSA 740 // ClientKeyExchange which would not pass padding checks. 741 BadRSAClientKeyExchange RSABadValue 742 743 // RenewTicketOnResume causes the server to renew the session ticket and 744 // send a NewSessionTicket message during an abbreviated handshake. 745 RenewTicketOnResume bool 746 747 // SendClientVersion, if non-zero, causes the client to send the 748 // specified value in the ClientHello version field. 749 SendClientVersion uint16 750 751 // OmitSupportedVersions, if true, causes the client to omit the 752 // supported versions extension. 753 OmitSupportedVersions bool 754 755 // SendSupportedVersions, if non-empty, causes the client to send a 756 // supported versions extension with the values from array. 757 SendSupportedVersions []uint16 758 759 // NegotiateVersion, if non-zero, causes the server to negotiate the 760 // specifed wire version rather than the version supported by either 761 // peer. 762 NegotiateVersion uint16 763 764 // NegotiateVersionOnRenego, if non-zero, causes the server to negotiate 765 // the specified wire version on renegotiation rather than retaining it. 766 NegotiateVersionOnRenego uint16 767 768 // ExpectFalseStart causes the server to, on full handshakes, 769 // expect the peer to False Start; the server Finished message 770 // isn't sent until we receive an application data record 771 // from the peer. 772 ExpectFalseStart bool 773 774 // AlertBeforeFalseStartTest, if non-zero, causes the server to, on full 775 // handshakes, send an alert just before reading the application data 776 // record to test False Start. This can be used in a negative False 777 // Start test to determine whether the peer processed the alert (and 778 // closed the connection) before or after sending app data. 779 AlertBeforeFalseStartTest alert 780 781 // ExpectServerName, if not empty, is the hostname the client 782 // must specify in the server_name extension. 783 ExpectServerName string 784 785 // SwapNPNAndALPN switches the relative order between NPN and ALPN in 786 // both ClientHello and ServerHello. 787 SwapNPNAndALPN bool 788 789 // ALPNProtocol, if not nil, sets the ALPN protocol that a server will 790 // return. 791 ALPNProtocol *string 792 793 // AcceptAnySession causes the server to resume sessions regardless of 794 // the version associated with the session or cipher suite. It also 795 // causes the server to look in both TLS 1.2 and 1.3 extensions to 796 // process a ticket. 797 AcceptAnySession bool 798 799 // SendBothTickets, if true, causes the client to send tickets in both 800 // TLS 1.2 and 1.3 extensions. 801 SendBothTickets bool 802 803 // FilterTicket, if not nil, causes the client to modify a session 804 // ticket before sending it in a resume handshake. 805 FilterTicket func([]byte) ([]byte, error) 806 807 // TicketSessionIDLength, if non-zero, is the length of the session ID 808 // to send with a ticket resumption offer. 809 TicketSessionIDLength int 810 811 // EmptyTicketSessionID, if true, causes the client to send an empty 812 // session ID with a ticket resumption offer. For simplicity, this will 813 // also cause the client to interpret a ServerHello with empty session 814 // ID as a resumption. (A client which sends empty session ID is 815 // normally expected to look ahead for ChangeCipherSpec.) 816 EmptyTicketSessionID bool 817 818 // SendClientHelloSessionID, if not nil, is the session ID sent in the 819 // ClientHello. 820 SendClientHelloSessionID []byte 821 822 // ExpectClientHelloSessionID, if true, causes the server to fail the 823 // connection if there is not a session ID in the ClientHello. 824 ExpectClientHelloSessionID bool 825 826 // EchoSessionIDInFullHandshake, if true, causes the server to echo the 827 // ClientHello session ID, even in TLS 1.2 full handshakes. 828 EchoSessionIDInFullHandshake bool 829 830 // ExpectNoTLS12Session, if true, causes the server to fail the 831 // connection if either a session ID or TLS 1.2 ticket is offered. 832 ExpectNoTLS12Session bool 833 834 // ExpectNoTLS13PSK, if true, causes the server to fail the connection 835 // if a TLS 1.3 PSK is offered. 836 ExpectNoTLS13PSK bool 837 838 // ExpectNoTLS13PSKAfterHRR, if true, causes the server to fail the connection 839 // if a TLS 1.3 PSK is offered after HRR. 840 ExpectNoTLS13PSKAfterHRR bool 841 842 // RequireExtendedMasterSecret, if true, requires that the peer support 843 // the extended master secret option. 844 RequireExtendedMasterSecret bool 845 846 // NoExtendedMasterSecret causes the client and server to behave as if 847 // they didn't support an extended master secret in the initial 848 // handshake. 849 NoExtendedMasterSecret bool 850 851 // NoExtendedMasterSecretOnRenegotiation causes the client and server to 852 // behave as if they didn't support an extended master secret in 853 // renegotiation handshakes. 854 NoExtendedMasterSecretOnRenegotiation bool 855 856 // EmptyRenegotiationInfo causes the renegotiation extension to be 857 // empty in a renegotiation handshake. 858 EmptyRenegotiationInfo bool 859 860 // BadRenegotiationInfo causes the renegotiation extension value in a 861 // renegotiation handshake to be incorrect at the start. 862 BadRenegotiationInfo bool 863 864 // BadRenegotiationInfoEnd causes the renegotiation extension value in 865 // a renegotiation handshake to be incorrect at the end. 866 BadRenegotiationInfoEnd bool 867 868 // NoRenegotiationInfo disables renegotiation info support in all 869 // handshakes. 870 NoRenegotiationInfo bool 871 872 // NoRenegotiationInfoInInitial disables renegotiation info support in 873 // the initial handshake. 874 NoRenegotiationInfoInInitial bool 875 876 // NoRenegotiationInfoAfterInitial disables renegotiation info support 877 // in renegotiation handshakes. 878 NoRenegotiationInfoAfterInitial bool 879 880 // RequireRenegotiationInfo, if true, causes the client to return an 881 // error if the server doesn't reply with the renegotiation extension. 882 RequireRenegotiationInfo bool 883 884 // SequenceNumberMapping, if non-nil, is the mapping function to apply 885 // to the sequence number of outgoing packets. For both TLS and DTLS, 886 // the two most-significant bytes in the resulting sequence number are 887 // ignored so that the DTLS epoch cannot be changed. 888 SequenceNumberMapping func(uint64) uint64 889 890 // RSAEphemeralKey, if true, causes the server to send a 891 // ServerKeyExchange message containing an ephemeral key (as in 892 // RSA_EXPORT) in the plain RSA key exchange. 893 RSAEphemeralKey bool 894 895 // SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the 896 // client offers when negotiating SRTP. MKI support is still missing so 897 // the peer must still send none. 898 SRTPMasterKeyIdentifer string 899 900 // SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the 901 // server sends in the ServerHello instead of the negotiated one. 902 SendSRTPProtectionProfile uint16 903 904 // NoSignatureAlgorithms, if true, causes the client to omit the 905 // signature and hashes extension. 906 // 907 // For a server, it will cause an empty list to be sent in the 908 // CertificateRequest message. None the less, the configured set will 909 // still be enforced. 910 NoSignatureAlgorithms bool 911 912 // NoSupportedCurves, if true, causes the client to omit the 913 // supported_curves extension. 914 NoSupportedCurves bool 915 916 // RequireSameRenegoClientVersion, if true, causes the server 917 // to require that all ClientHellos match in offered version 918 // across a renego. 919 RequireSameRenegoClientVersion bool 920 921 // ExpectInitialRecordVersion, if non-zero, is the expected value of 922 // record-layer version field before the protocol version is determined. 923 ExpectInitialRecordVersion uint16 924 925 // SendRecordVersion, if non-zero, is the value to send as the 926 // record-layer version. 927 SendRecordVersion uint16 928 929 // SendInitialRecordVersion, if non-zero, is the value to send as the 930 // record-layer version before the protocol version is determined. 931 SendInitialRecordVersion uint16 932 933 // MaxPacketLength, if non-zero, is the maximum acceptable size for a 934 // packet. 935 MaxPacketLength int 936 937 // SendCipherSuite, if non-zero, is the cipher suite value that the 938 // server will send in the ServerHello. This does not affect the cipher 939 // the server believes it has actually negotiated. 940 SendCipherSuite uint16 941 942 // SendCipherSuites, if not nil, is the cipher suite list that the 943 // client will send in the ClientHello. This does not affect the cipher 944 // the client believes it has actually offered. 945 SendCipherSuites []uint16 946 947 // AppDataBeforeHandshake, if not nil, causes application data to be 948 // sent immediately before the first handshake message. 949 AppDataBeforeHandshake []byte 950 951 // AppDataAfterChangeCipherSpec, if not nil, causes application data to 952 // be sent immediately after ChangeCipherSpec. 953 AppDataAfterChangeCipherSpec []byte 954 955 // AlertAfterChangeCipherSpec, if non-zero, causes an alert to be sent 956 // immediately after ChangeCipherSpec. 957 AlertAfterChangeCipherSpec alert 958 959 // TimeoutSchedule is the schedule of packet drops and simulated 960 // timeouts for before each handshake leg from the peer. 961 TimeoutSchedule []time.Duration 962 963 // PacketAdaptor is the packetAdaptor to use to simulate timeouts. 964 PacketAdaptor *packetAdaptor 965 966 // MockQUICTransport is the mockQUICTransport used when testing 967 // QUIC interfaces. 968 MockQUICTransport *mockQUICTransport 969 970 // ReorderHandshakeFragments, if true, causes handshake fragments in 971 // DTLS to overlap and be sent in the wrong order. It also causes 972 // pre-CCS flights to be sent twice. (Post-CCS flights consist of 973 // Finished and will trigger a spurious retransmit.) 974 ReorderHandshakeFragments bool 975 976 // ReverseHandshakeFragments, if true, causes handshake fragments in 977 // DTLS to be reversed within a flight. 978 ReverseHandshakeFragments bool 979 980 // MixCompleteMessageWithFragments, if true, causes handshake 981 // messages in DTLS to redundantly both fragment the message 982 // and include a copy of the full one. 983 MixCompleteMessageWithFragments bool 984 985 // RetransmitFinished, if true, causes the DTLS Finished message to be 986 // sent twice. 987 RetransmitFinished bool 988 989 // SendInvalidRecordType, if true, causes a record with an invalid 990 // content type to be sent immediately following the handshake. 991 SendInvalidRecordType bool 992 993 // SendWrongMessageType, if non-zero, causes messages of the specified 994 // type to be sent with the wrong value. 995 SendWrongMessageType byte 996 997 // SendTrailingMessageData, if non-zero, causes messages of the 998 // specified type to be sent with trailing data. 999 SendTrailingMessageData byte 1000 1001 // FragmentMessageTypeMismatch, if true, causes all non-initial 1002 // handshake fragments in DTLS to have the wrong message type. 1003 FragmentMessageTypeMismatch bool 1004 1005 // FragmentMessageLengthMismatch, if true, causes all non-initial 1006 // handshake fragments in DTLS to have the wrong message length. 1007 FragmentMessageLengthMismatch bool 1008 1009 // SplitFragments, if non-zero, causes the handshake fragments in DTLS 1010 // to be split across two records. The value of |SplitFragments| is the 1011 // number of bytes in the first fragment. 1012 SplitFragments int 1013 1014 // SendEmptyFragments, if true, causes handshakes to include empty 1015 // fragments in DTLS. 1016 SendEmptyFragments bool 1017 1018 // SendSplitAlert, if true, causes an alert to be sent with the header 1019 // and record body split across multiple packets. The peer should 1020 // discard these packets rather than process it. 1021 SendSplitAlert bool 1022 1023 // FailIfResumeOnRenego, if true, causes renegotiations to fail if the 1024 // client offers a resumption or the server accepts one. 1025 FailIfResumeOnRenego bool 1026 1027 // IgnorePeerCipherPreferences, if true, causes the peer's cipher 1028 // preferences to be ignored. 1029 IgnorePeerCipherPreferences bool 1030 1031 // IgnorePeerSignatureAlgorithmPreferences, if true, causes the peer's 1032 // signature algorithm preferences to be ignored. 1033 IgnorePeerSignatureAlgorithmPreferences bool 1034 1035 // IgnorePeerCurvePreferences, if true, causes the peer's curve 1036 // preferences to be ignored. 1037 IgnorePeerCurvePreferences bool 1038 1039 // BadFinished, if true, causes the Finished hash to be broken. 1040 BadFinished bool 1041 1042 // PackHandshakeFragments, if true, causes handshake fragments in DTLS 1043 // to be packed into individual handshake records, up to the specified 1044 // record size. 1045 PackHandshakeFragments int 1046 1047 // PackHandshakeRecords, if non-zero, causes handshake and 1048 // ChangeCipherSpec records in DTLS to be packed into individual 1049 // packets, up to the specified packet size. 1050 PackHandshakeRecords int 1051 1052 // PackAppDataWithHandshake, if true, extends PackHandshakeRecords to 1053 // additionally include the first application data record sent after the 1054 // final Finished message in a handshake. (If the final Finished message 1055 // is sent by the peer, this option has no effect.) This requires that 1056 // the runner rather than shim speak first in a given test. 1057 PackAppDataWithHandshake bool 1058 1059 // SplitAndPackAppData, if true, causes application data in DTLS to be 1060 // split into two records each and packed into one packet. 1061 SplitAndPackAppData bool 1062 1063 // PackHandshakeFlight, if true, causes each handshake flight in TLS to 1064 // be packed into records, up to the largest size record available. 1065 PackHandshakeFlight bool 1066 1067 // AdvertiseAllConfiguredCiphers, if true, causes the client to 1068 // advertise all configured cipher suite values. 1069 AdvertiseAllConfiguredCiphers bool 1070 1071 // EmptyCertificateList, if true, causes the server to send an empty 1072 // certificate list in the Certificate message. 1073 EmptyCertificateList bool 1074 1075 // ExpectNewTicket, if true, causes the client to abort if it does not 1076 // receive a new ticket. 1077 ExpectNewTicket bool 1078 1079 // RequireClientHelloSize, if not zero, is the required length in bytes 1080 // of the ClientHello /record/. This is checked by the server. 1081 RequireClientHelloSize int 1082 1083 // CustomExtension, if not empty, contains the contents of an extension 1084 // that will be added to client/server hellos. 1085 CustomExtension string 1086 1087 // CustomUnencryptedExtension, if not empty, contains the contents of 1088 // an extension that will be added to ServerHello in TLS 1.3. 1089 CustomUnencryptedExtension string 1090 1091 // ExpectedCustomExtension, if not nil, contains the expected contents 1092 // of a custom extension. 1093 ExpectedCustomExtension *string 1094 1095 // CustomTicketExtension, if not empty, contains the contents of an 1096 // extension what will be added to NewSessionTicket in TLS 1.3. 1097 CustomTicketExtension string 1098 1099 // CustomTicketExtension, if not empty, contains the contents of an 1100 // extension what will be added to HelloRetryRequest in TLS 1.3. 1101 CustomHelloRetryRequestExtension string 1102 1103 // NoCloseNotify, if true, causes the close_notify alert to be skipped 1104 // on connection shutdown. 1105 NoCloseNotify bool 1106 1107 // SendAlertOnShutdown, if non-zero, is the alert to send instead of 1108 // close_notify on shutdown. 1109 SendAlertOnShutdown alert 1110 1111 // ExpectCloseNotify, if true, requires a close_notify from the peer on 1112 // shutdown. Records from the peer received after close_notify is sent 1113 // are not discard. 1114 ExpectCloseNotify bool 1115 1116 // SendLargeRecords, if true, allows outgoing records to be sent 1117 // arbitrarily large. 1118 SendLargeRecords bool 1119 1120 // NegotiateALPNAndNPN, if true, causes the server to negotiate both 1121 // ALPN and NPN in the same connetion. 1122 NegotiateALPNAndNPN bool 1123 1124 // SendALPN, if non-empty, causes the server to send the specified 1125 // string in the ALPN extension regardless of the content or presence of 1126 // the client offer. 1127 SendALPN string 1128 1129 // SendUnencryptedALPN, if non-empty, causes the server to send the 1130 // specified string in a ServerHello ALPN extension in TLS 1.3. 1131 SendUnencryptedALPN string 1132 1133 // SendEmptySessionTicket, if true, causes the server to send an empty 1134 // session ticket. 1135 SendEmptySessionTicket bool 1136 1137 // SendPSKKeyExchangeModes, if present, determines the PSK key exchange modes 1138 // to send. 1139 SendPSKKeyExchangeModes []byte 1140 1141 // ExpectNoNewSessionTicket, if present, means that the client will fail upon 1142 // receipt of a NewSessionTicket message. 1143 ExpectNoNewSessionTicket bool 1144 1145 // DuplicateTicketEarlyData causes an extra empty extension of early_data to 1146 // be sent in NewSessionTicket. 1147 DuplicateTicketEarlyData bool 1148 1149 // ExpectTicketEarlyData, if true, means that the client will fail upon 1150 // absence of the early_data extension. 1151 ExpectTicketEarlyData bool 1152 1153 // ExpectTicketAge, if non-zero, is the expected age of the ticket that the 1154 // server receives from the client. 1155 ExpectTicketAge time.Duration 1156 1157 // SendTicketAge, if non-zero, is the ticket age to be sent by the 1158 // client. 1159 SendTicketAge time.Duration 1160 1161 // FailIfSessionOffered, if true, causes the server to fail any 1162 // connections where the client offers a non-empty session ID or session 1163 // ticket. 1164 FailIfSessionOffered bool 1165 1166 // SendHelloRequestBeforeEveryAppDataRecord, if true, causes a 1167 // HelloRequest handshake message to be sent before each application 1168 // data record. This only makes sense for a server. 1169 SendHelloRequestBeforeEveryAppDataRecord bool 1170 1171 // SendHelloRequestBeforeEveryHandshakeMessage, if true, causes a 1172 // HelloRequest handshake message to be sent before each handshake 1173 // message. This only makes sense for a server. 1174 SendHelloRequestBeforeEveryHandshakeMessage bool 1175 1176 // BadChangeCipherSpec, if not nil, is the body to be sent in 1177 // ChangeCipherSpec records instead of {1}. 1178 BadChangeCipherSpec []byte 1179 1180 // BadHelloRequest, if not nil, is what to send instead of a 1181 // HelloRequest. 1182 BadHelloRequest []byte 1183 1184 // RequireSessionTickets, if true, causes the client to require new 1185 // sessions use session tickets instead of session IDs. 1186 RequireSessionTickets bool 1187 1188 // RequireSessionIDs, if true, causes the client to require new sessions use 1189 // session IDs instead of session tickets. 1190 RequireSessionIDs bool 1191 1192 // NullAllCiphers, if true, causes every cipher to behave like the null 1193 // cipher. 1194 NullAllCiphers bool 1195 1196 // SendSCTListOnResume, if not nil, causes the server to send the 1197 // supplied SCT list in resumption handshakes. 1198 SendSCTListOnResume []byte 1199 1200 // SendSCTListOnRenegotiation, if not nil, causes the server to send the 1201 // supplied SCT list on renegotiation. 1202 SendSCTListOnRenegotiation []byte 1203 1204 // SendOCSPResponseOnResume, if not nil, causes the server to advertise 1205 // OCSP stapling in resumption handshakes and, if applicable, send the 1206 // supplied stapled response. 1207 SendOCSPResponseOnResume []byte 1208 1209 // SendOCSPResponseOnResume, if not nil, causes the server to send the 1210 // supplied OCSP response on renegotiation. 1211 SendOCSPResponseOnRenegotiation []byte 1212 1213 // SendExtensionOnCertificate, if not nil, causes the runner to send the 1214 // supplied bytes in the extensions on the Certificate message. 1215 SendExtensionOnCertificate []byte 1216 1217 // SendOCSPOnIntermediates, if not nil, causes the server to send the 1218 // supplied OCSP on intermediate certificates in the Certificate message. 1219 SendOCSPOnIntermediates []byte 1220 1221 // SendSCTOnIntermediates, if not nil, causes the server to send the 1222 // supplied SCT on intermediate certificates in the Certificate message. 1223 SendSCTOnIntermediates []byte 1224 1225 // SendDuplicateCertExtensions, if true, causes the server to send an extra 1226 // copy of the OCSP/SCT extensions in the Certificate message. 1227 SendDuplicateCertExtensions bool 1228 1229 // ExpectNoExtensionsOnIntermediate, if true, causes the client to 1230 // reject extensions on intermediate certificates. 1231 ExpectNoExtensionsOnIntermediate bool 1232 1233 // RecordPadding is the number of bytes of padding to add to each 1234 // encrypted record in TLS 1.3. 1235 RecordPadding int 1236 1237 // OmitRecordContents, if true, causes encrypted records in TLS 1.3 to 1238 // be missing their body and content type. Padding, if configured, is 1239 // still added. 1240 OmitRecordContents bool 1241 1242 // OuterRecordType, if non-zero, is the outer record type to use instead 1243 // of application data. 1244 OuterRecordType recordType 1245 1246 // SendSignatureAlgorithm, if non-zero, causes all signatures to be sent 1247 // with the given signature algorithm rather than the one negotiated. 1248 SendSignatureAlgorithm signatureAlgorithm 1249 1250 // SkipECDSACurveCheck, if true, causes all ECDSA curve checks to be 1251 // skipped. 1252 SkipECDSACurveCheck bool 1253 1254 // IgnoreSignatureVersionChecks, if true, causes all signature 1255 // algorithms to be enabled at all TLS versions. 1256 IgnoreSignatureVersionChecks bool 1257 1258 // NegotiateRenegotiationInfoAtAllVersions, if true, causes 1259 // Renegotiation Info to be negotiated at all versions. 1260 NegotiateRenegotiationInfoAtAllVersions bool 1261 1262 // NegotiateNPNAtAllVersions, if true, causes NPN to be negotiated at 1263 // all versions. 1264 NegotiateNPNAtAllVersions bool 1265 1266 // NegotiateEMSAtAllVersions, if true, causes EMS to be negotiated at 1267 // all versions. 1268 NegotiateEMSAtAllVersions bool 1269 1270 // AdvertiseTicketExtension, if true, causes the ticket extension to be 1271 // advertised in server extensions 1272 AdvertiseTicketExtension bool 1273 1274 // NegotiatePSKResumption, if true, causes the server to attempt pure PSK 1275 // resumption. 1276 NegotiatePSKResumption bool 1277 1278 // AlwaysSelectPSKIdentity, if true, causes the server in TLS 1.3 to 1279 // always acknowledge a session, regardless of one was offered. 1280 AlwaysSelectPSKIdentity bool 1281 1282 // SelectPSKIdentityOnResume, if non-zero, causes the server to select 1283 // the specified PSK identity index rather than the actual value. 1284 SelectPSKIdentityOnResume uint16 1285 1286 // ExtraPSKIdentity, if true, causes the client to send an extra PSK 1287 // identity. 1288 ExtraPSKIdentity bool 1289 1290 // MissingKeyShare, if true, causes the TLS 1.3 implementation to skip 1291 // sending a key_share extension and use the zero ECDHE secret 1292 // instead. 1293 MissingKeyShare bool 1294 1295 // SecondClientHelloMissingKeyShare, if true, causes the second TLS 1.3 1296 // ClientHello to skip sending a key_share extension and use the zero 1297 // ECDHE secret instead. 1298 SecondClientHelloMissingKeyShare bool 1299 1300 // MisinterpretHelloRetryRequestCurve, if non-zero, causes the TLS 1.3 1301 // client to pretend the server requested a HelloRetryRequest with the 1302 // given curve rather than the actual one. 1303 MisinterpretHelloRetryRequestCurve CurveID 1304 1305 // DuplicateKeyShares, if true, causes the TLS 1.3 client to send two 1306 // copies of each KeyShareEntry. 1307 DuplicateKeyShares bool 1308 1309 // SendEarlyAlert, if true, sends a fatal alert after the ClientHello. 1310 SendEarlyAlert bool 1311 1312 // SendFakeEarlyDataLength, if non-zero, is the amount of early data to 1313 // send after the ClientHello. 1314 SendFakeEarlyDataLength int 1315 1316 // SendStrayEarlyHandshake, if non-zero, causes the client to send a stray 1317 // handshake record before sending end of early data. 1318 SendStrayEarlyHandshake bool 1319 1320 // OmitEarlyDataExtension, if true, causes the early data extension to 1321 // be omitted in the ClientHello. 1322 OmitEarlyDataExtension bool 1323 1324 // SendEarlyDataOnSecondClientHello, if true, causes the TLS 1.3 client to 1325 // send early data after the second ClientHello. 1326 SendEarlyDataOnSecondClientHello bool 1327 1328 // InterleaveEarlyData, if true, causes the TLS 1.3 client to send early 1329 // data interleaved with the second ClientHello and the client Finished. 1330 InterleaveEarlyData bool 1331 1332 // SendEarlyData causes a TLS 1.3 client to send the provided data 1333 // in application data records immediately after the ClientHello, 1334 // provided that the client offers a TLS 1.3 session. It will do this 1335 // whether or not the server advertised early data for the ticket. 1336 SendEarlyData [][]byte 1337 1338 // ExpectEarlyDataAccepted causes a TLS 1.3 client to check that early data 1339 // was accepted by the server. 1340 ExpectEarlyDataAccepted bool 1341 1342 // AlwaysAcceptEarlyData causes a TLS 1.3 server to always accept early data 1343 // regardless of ALPN mismatch. 1344 AlwaysAcceptEarlyData bool 1345 1346 // AlwaysRejectEarlyData causes a TLS 1.3 server to always reject early data. 1347 AlwaysRejectEarlyData bool 1348 1349 // SendEarlyDataExtension, if true, causes a TLS 1.3 server to send the 1350 // early_data extension in EncryptedExtensions, independent of whether 1351 // it was accepted. 1352 SendEarlyDataExtension bool 1353 1354 // ExpectEarlyData causes a TLS 1.3 server to read application 1355 // data after the ClientHello (assuming the server is able to 1356 // derive the key under which the data is encrypted) before it 1357 // sends a ServerHello. It checks that the application data it 1358 // reads matches what is provided in ExpectEarlyData and errors if 1359 // the number of records or their content do not match. 1360 ExpectEarlyData [][]byte 1361 1362 // ExpectLateEarlyData causes a TLS 1.3 server to read application 1363 // data after the ServerFinished (assuming the server is able to 1364 // derive the key under which the data is encrypted) before it 1365 // sends the ClientFinished. It checks that the application data it 1366 // reads matches what is provided in ExpectLateEarlyData and errors if 1367 // the number of records or their content do not match. 1368 ExpectLateEarlyData [][]byte 1369 1370 // SendHalfRTTData causes a TLS 1.3 server to send the provided 1371 // data in application data records before reading the client's 1372 // Finished message. 1373 SendHalfRTTData [][]byte 1374 1375 // ExpectHalfRTTData causes a TLS 1.3 client, if 0-RTT was accepted, to 1376 // read application data after reading the server's Finished message and 1377 // before sending any subsequent handshake messages. It checks that the 1378 // application data it reads matches what is provided in 1379 // ExpectHalfRTTData and errors if the number of records or their 1380 // content do not match. 1381 ExpectHalfRTTData [][]byte 1382 1383 // EmptyEncryptedExtensions, if true, causes the TLS 1.3 server to 1384 // emit an empty EncryptedExtensions block. 1385 EmptyEncryptedExtensions bool 1386 1387 // EncryptedExtensionsWithKeyShare, if true, causes the TLS 1.3 server to 1388 // include the KeyShare extension in the EncryptedExtensions block. 1389 EncryptedExtensionsWithKeyShare bool 1390 1391 // AlwaysSendHelloRetryRequest, if true, causes a HelloRetryRequest to 1392 // be sent by the server, even if empty. 1393 AlwaysSendHelloRetryRequest bool 1394 1395 // SecondHelloRetryRequest, if true, causes the TLS 1.3 server to send 1396 // two HelloRetryRequests instead of one. 1397 SecondHelloRetryRequest bool 1398 1399 // SendHelloRetryRequestCurve, if non-zero, causes the server to send 1400 // the specified curve in a HelloRetryRequest. 1401 SendHelloRetryRequestCurve CurveID 1402 1403 // SendHelloRetryRequestCipherSuite, if non-zero, causes the server to send 1404 // the specified cipher suite in a HelloRetryRequest. 1405 SendHelloRetryRequestCipherSuite uint16 1406 1407 // SendHelloRetryRequestCookie, if not nil, contains a cookie to be 1408 // sent by the server in HelloRetryRequest. 1409 SendHelloRetryRequestCookie []byte 1410 1411 // DuplicateHelloRetryRequestExtensions, if true, causes all 1412 // HelloRetryRequest extensions to be sent twice. 1413 DuplicateHelloRetryRequestExtensions bool 1414 1415 // SendServerHelloVersion, if non-zero, causes the server to send the 1416 // specified value in ServerHello version field. 1417 SendServerHelloVersion uint16 1418 1419 // SendServerSupportedVersionExtension, if non-zero, causes the server to send 1420 // the specified value in supported_versions extension in the ServerHello (but 1421 // not the HelloRetryRequest). 1422 SendServerSupportedVersionExtension uint16 1423 1424 // OmitServerSupportedVersionExtension, if true, causes the server to 1425 // omit the supported_versions extension in the ServerHello (but not the 1426 // HelloRetryRequest) 1427 OmitServerSupportedVersionExtension bool 1428 1429 // SkipHelloRetryRequest, if true, causes the TLS 1.3 server to not send 1430 // HelloRetryRequest. 1431 SkipHelloRetryRequest bool 1432 1433 // PackHelloRequestWithFinished, if true, causes the TLS server to send 1434 // HelloRequest in the same record as Finished. 1435 PackHelloRequestWithFinished bool 1436 1437 // ExpectMissingKeyShare, if true, causes the TLS server to fail the 1438 // connection if the selected curve appears in the client's initial 1439 // ClientHello. That is, it requires that a HelloRetryRequest be sent. 1440 ExpectMissingKeyShare bool 1441 1442 // SendExtraFinished, if true, causes an extra Finished message to be 1443 // sent. 1444 SendExtraFinished bool 1445 1446 // SendRequestContext, if not empty, is the request context to send in 1447 // a TLS 1.3 CertificateRequest. 1448 SendRequestContext []byte 1449 1450 // OmitCertificateRequestAlgorithms, if true, omits the signature_algorithm 1451 // extension in a TLS 1.3 CertificateRequest. 1452 OmitCertificateRequestAlgorithms bool 1453 1454 // SendCustomCertificateRequest, if non-zero, send an additional custom 1455 // extension in a TLS 1.3 CertificateRequest. 1456 SendCustomCertificateRequest uint16 1457 1458 // SendSNIWarningAlert, if true, causes the server to send an 1459 // unrecognized_name alert before the ServerHello. 1460 SendSNIWarningAlert bool 1461 1462 // SendCompressionMethods, if not nil, is the compression method list to 1463 // send in the ClientHello. 1464 SendCompressionMethods []byte 1465 1466 // SendCompressionMethod is the compression method to send in the 1467 // ServerHello. 1468 SendCompressionMethod byte 1469 1470 // AlwaysSendPreSharedKeyIdentityHint, if true, causes the server to 1471 // always send a ServerKeyExchange for PSK ciphers, even if the identity 1472 // hint is empty. 1473 AlwaysSendPreSharedKeyIdentityHint bool 1474 1475 // TrailingKeyShareData, if true, causes the client key share list to 1476 // include a trailing byte. 1477 TrailingKeyShareData bool 1478 1479 // InvalidChannelIDSignature, if true, causes the client to generate an 1480 // invalid Channel ID signature. 1481 InvalidChannelIDSignature bool 1482 1483 // ExpectGREASE, if true, causes messages without GREASE values to be 1484 // rejected. See draft-davidben-tls-grease-01. 1485 ExpectGREASE bool 1486 1487 // OmitPSKsOnSecondClientHello, if true, causes the client to omit the 1488 // PSK extension on the second ClientHello. 1489 OmitPSKsOnSecondClientHello bool 1490 1491 // OnlyCorruptSecondPSKBinder, if true, causes the options below to 1492 // only apply to the second PSK binder. 1493 OnlyCorruptSecondPSKBinder bool 1494 1495 // SendShortPSKBinder, if true, causes the client to send a PSK binder 1496 // that is one byte shorter than it should be. 1497 SendShortPSKBinder bool 1498 1499 // SendInvalidPSKBinder, if true, causes the client to send an invalid 1500 // PSK binder. 1501 SendInvalidPSKBinder bool 1502 1503 // SendNoPSKBinder, if true, causes the client to send no PSK binders. 1504 SendNoPSKBinder bool 1505 1506 // SendExtraPSKBinder, if true, causes the client to send an extra PSK 1507 // binder. 1508 SendExtraPSKBinder bool 1509 1510 // PSKBinderFirst, if true, causes the client to send the PSK Binder 1511 // extension as the first extension instead of the last extension. 1512 PSKBinderFirst bool 1513 1514 // NoOCSPStapling, if true, causes the client to not request OCSP 1515 // stapling. 1516 NoOCSPStapling bool 1517 1518 // NoSignedCertificateTimestamps, if true, causes the client to not 1519 // request signed certificate timestamps. 1520 NoSignedCertificateTimestamps bool 1521 1522 // SendSupportedPointFormats, if not nil, is the list of supported point 1523 // formats to send in ClientHello or ServerHello. If set to a non-nil 1524 // empty slice, no extension will be sent. 1525 SendSupportedPointFormats []byte 1526 1527 // SendServerSupportedCurves, if true, causes the server to send its 1528 // supported curves list in the ServerHello (TLS 1.2) or 1529 // EncryptedExtensions (TLS 1.3) message. This is invalid in TLS 1.2 and 1530 // valid in TLS 1.3. 1531 SendServerSupportedCurves bool 1532 1533 // MaxReceivePlaintext, if non-zero, is the maximum plaintext record 1534 // length accepted from the peer. 1535 MaxReceivePlaintext int 1536 1537 // ExpectPackedEncryptedHandshake, if non-zero, requires that the peer maximally 1538 // pack their encrypted handshake messages, fitting at most the 1539 // specified number of plaintext bytes per record. 1540 ExpectPackedEncryptedHandshake int 1541 1542 // SendTicketLifetime, if non-zero, is the ticket lifetime to send in 1543 // NewSessionTicket messages. 1544 SendTicketLifetime time.Duration 1545 1546 // SendServerNameAck, if true, causes the server to acknowledge the SNI 1547 // extension. 1548 SendServerNameAck bool 1549 1550 // ExpectCertificateReqNames, if not nil, contains the list of X.509 1551 // names that must be sent in a CertificateRequest from the server. 1552 ExpectCertificateReqNames [][]byte 1553 1554 // RenegotiationCertificate, if not nil, is the certificate to use on 1555 // renegotiation handshakes. 1556 RenegotiationCertificate *Certificate 1557 1558 // ExpectNoCertificateAuthoritiesExtension, if true, causes the client to 1559 // reject CertificateRequest with the CertificateAuthorities extension. 1560 ExpectNoCertificateAuthoritiesExtension bool 1561 1562 // UseLegacySigningAlgorithm, if non-zero, is the signature algorithm 1563 // to use when signing in TLS 1.1 and earlier where algorithms are not 1564 // negotiated. 1565 UseLegacySigningAlgorithm signatureAlgorithm 1566 1567 // SendServerHelloAsHelloRetryRequest, if true, causes the server to 1568 // send ServerHello messages with a HelloRetryRequest type field. 1569 SendServerHelloAsHelloRetryRequest bool 1570 1571 // RejectUnsolicitedKeyUpdate, if true, causes all unsolicited 1572 // KeyUpdates from the peer to be rejected. 1573 RejectUnsolicitedKeyUpdate bool 1574 1575 // OmitExtensions, if true, causes the extensions field in ClientHello 1576 // and ServerHello messages to be omitted. 1577 OmitExtensions bool 1578 1579 // EmptyExtensions, if true, causes the extensions field in ClientHello 1580 // and ServerHello messages to be present, but empty. 1581 EmptyExtensions bool 1582 1583 // ExpectOmitExtensions, if true, causes the client to reject 1584 // ServerHello messages that do not omit extensions. 1585 ExpectOmitExtensions bool 1586 1587 // ExpectRecordSplitting, if true, causes application records to only be 1588 // accepted if they follow a 1/n-1 record split. 1589 ExpectRecordSplitting bool 1590 1591 // PadClientHello, if non-zero, pads the ClientHello to a multiple of 1592 // that many bytes. 1593 PadClientHello int 1594 1595 // SendTLS13DowngradeRandom, if true, causes the server to send the 1596 // TLS 1.3 anti-downgrade signal. 1597 SendTLS13DowngradeRandom bool 1598 1599 // CheckTLS13DowngradeRandom, if true, causes the client to check the 1600 // TLS 1.3 anti-downgrade signal regardless of its variant. 1601 CheckTLS13DowngradeRandom bool 1602 1603 // IgnoreTLS13DowngradeRandom, if true, causes the client to ignore the 1604 // TLS 1.3 anti-downgrade signal. 1605 IgnoreTLS13DowngradeRandom bool 1606 1607 // SendCompressedCoordinates, if true, causes ECDH key shares over NIST 1608 // curves to use compressed coordinates. 1609 SendCompressedCoordinates bool 1610 1611 // SetX25519HighBit, if true, causes X25519 key shares to set their 1612 // high-order bit. 1613 SetX25519HighBit bool 1614 1615 // DuplicateCompressedCertAlgs, if true, causes two, equal, certificate 1616 // compression algorithm IDs to be sent. 1617 DuplicateCompressedCertAlgs bool 1618 1619 // ExpectedCompressedCert specifies the compression algorithm ID that must be 1620 // used on this connection, or zero if there are no special requirements. 1621 ExpectedCompressedCert uint16 1622 1623 // SendCertCompressionAlgId, if not zero, sets the algorithm ID that will be 1624 // sent in the compressed certificate message. 1625 SendCertCompressionAlgId uint16 1626 1627 // SendCertUncompressedLength, if not zero, sets the uncompressed length that 1628 // will be sent in the compressed certificate message. 1629 SendCertUncompressedLength uint32 1630 1631 // SendClientHelloWithFixes, if not nil, sends the specified byte string 1632 // instead of the ClientHello. This string is incorporated into the 1633 // transcript as if it were the real ClientHello, but the handshake will 1634 // otherwise behave as if this was not sent in terms of what ciphers it 1635 // will accept, etc. 1636 // 1637 // The input is modified to match key share entries. DefaultCurves must 1638 // be configured to match. The random and session ID fields are 1639 // extracted from the ClientHello. 1640 SendClientHelloWithFixes []byte 1641 1642 // SendJDK11DowngradeRandom, if true, causes the server to send the JDK 1643 // 11 downgrade signal. 1644 SendJDK11DowngradeRandom bool 1645 1646 // ExpectJDK11DowngradeRandom is whether the client should expect the 1647 // server to send the JDK 11 downgrade signal. 1648 ExpectJDK11DowngradeRandom bool 1649 1650 // FailIfHelloRetryRequested causes a handshake failure if a server requests a 1651 // hello retry. 1652 FailIfHelloRetryRequested bool 1653 1654 // FailedIfCECPQ2Offered will cause a server to reject a ClientHello if CECPQ2 1655 // is supported. 1656 FailIfCECPQ2Offered bool 1657 1658 // ExpectKeyShares, if not nil, lists (in order) the curves that a ClientHello 1659 // should have key shares for. 1660 ExpectedKeyShares []CurveID 1661 1662 // ExpectDelegatedCredentials, if true, requires that the handshake present 1663 // delegated credentials. 1664 ExpectDelegatedCredentials bool 1665 1666 // FailIfDelegatedCredentials, if true, causes a handshake failure if the 1667 // server returns delegated credentials. 1668 FailIfDelegatedCredentials bool 1669 1670 // DisableDelegatedCredentials, if true, disables client support for delegated 1671 // credentials. 1672 DisableDelegatedCredentials bool 1673} 1674 1675func (c *Config) serverInit() { 1676 if c.SessionTicketsDisabled { 1677 return 1678 } 1679 1680 // If the key has already been set then we have nothing to do. 1681 for _, b := range c.SessionTicketKey { 1682 if b != 0 { 1683 return 1684 } 1685 } 1686 1687 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil { 1688 c.SessionTicketsDisabled = true 1689 } 1690} 1691 1692func (c *Config) rand() io.Reader { 1693 r := c.Rand 1694 if r == nil { 1695 return rand.Reader 1696 } 1697 return r 1698} 1699 1700func (c *Config) time() time.Time { 1701 t := c.Time 1702 if t == nil { 1703 t = time.Now 1704 } 1705 return t() 1706} 1707 1708func (c *Config) cipherSuites() []uint16 { 1709 s := c.CipherSuites 1710 if s == nil { 1711 s = defaultCipherSuites() 1712 } 1713 return s 1714} 1715 1716func (c *Config) minVersion(isDTLS bool) uint16 { 1717 ret := uint16(minVersion) 1718 if c != nil && c.MinVersion != 0 { 1719 ret = c.MinVersion 1720 } 1721 if isDTLS { 1722 // The lowest version of DTLS is 1.0. There is no DSSL 3.0. 1723 if ret < VersionTLS10 { 1724 return VersionTLS10 1725 } 1726 // There is no such thing as DTLS 1.1. 1727 if ret == VersionTLS11 { 1728 return VersionTLS12 1729 } 1730 } 1731 return ret 1732} 1733 1734func (c *Config) maxVersion(isDTLS bool) uint16 { 1735 ret := uint16(maxVersion) 1736 if c != nil && c.MaxVersion != 0 { 1737 ret = c.MaxVersion 1738 } 1739 if isDTLS { 1740 // We only implement up to DTLS 1.2. 1741 if ret > VersionTLS12 { 1742 return VersionTLS12 1743 } 1744 // There is no such thing as DTLS 1.1. 1745 if ret == VersionTLS11 { 1746 return VersionTLS10 1747 } 1748 } 1749 return ret 1750} 1751 1752var defaultCurvePreferences = []CurveID{CurveCECPQ2, CurveX25519, CurveP256, CurveP384, CurveP521} 1753 1754func (c *Config) curvePreferences() []CurveID { 1755 if c == nil || len(c.CurvePreferences) == 0 { 1756 return defaultCurvePreferences 1757 } 1758 return c.CurvePreferences 1759} 1760 1761func (c *Config) defaultCurves() map[CurveID]bool { 1762 defaultCurves := make(map[CurveID]bool) 1763 curves := c.DefaultCurves 1764 if c == nil || c.DefaultCurves == nil { 1765 curves = c.curvePreferences() 1766 } 1767 for _, curveID := range curves { 1768 defaultCurves[curveID] = true 1769 } 1770 return defaultCurves 1771} 1772 1773func wireToVersion(vers uint16, isDTLS bool) (uint16, bool) { 1774 if isDTLS { 1775 switch vers { 1776 case VersionDTLS12: 1777 return VersionTLS12, true 1778 case VersionDTLS10: 1779 return VersionTLS10, true 1780 } 1781 } else { 1782 switch vers { 1783 case VersionSSL30, VersionTLS10, VersionTLS11, VersionTLS12, VersionTLS13: 1784 return vers, true 1785 } 1786 } 1787 1788 return 0, false 1789} 1790 1791// isSupportedVersion checks if the specified wire version is acceptable. If so, 1792// it returns true and the corresponding protocol version. Otherwise, it returns 1793// false. 1794func (c *Config) isSupportedVersion(wireVers uint16, isDTLS bool) (uint16, bool) { 1795 vers, ok := wireToVersion(wireVers, isDTLS) 1796 if !ok || c.minVersion(isDTLS) > vers || vers > c.maxVersion(isDTLS) { 1797 return 0, false 1798 } 1799 return vers, true 1800} 1801 1802func (c *Config) supportedVersions(isDTLS bool) []uint16 { 1803 versions := allTLSWireVersions 1804 if isDTLS { 1805 versions = allDTLSWireVersions 1806 } 1807 var ret []uint16 1808 for _, vers := range versions { 1809 if _, ok := c.isSupportedVersion(vers, isDTLS); ok { 1810 ret = append(ret, vers) 1811 } 1812 } 1813 return ret 1814} 1815 1816// getCertificateForName returns the best certificate for the given name, 1817// defaulting to the first element of c.Certificates if there are no good 1818// options. 1819func (c *Config) getCertificateForName(name string) *Certificate { 1820 if len(c.Certificates) == 1 || c.NameToCertificate == nil { 1821 // There's only one choice, so no point doing any work. 1822 return &c.Certificates[0] 1823 } 1824 1825 name = strings.ToLower(name) 1826 for len(name) > 0 && name[len(name)-1] == '.' { 1827 name = name[:len(name)-1] 1828 } 1829 1830 if cert, ok := c.NameToCertificate[name]; ok { 1831 return cert 1832 } 1833 1834 // try replacing labels in the name with wildcards until we get a 1835 // match. 1836 labels := strings.Split(name, ".") 1837 for i := range labels { 1838 labels[i] = "*" 1839 candidate := strings.Join(labels, ".") 1840 if cert, ok := c.NameToCertificate[candidate]; ok { 1841 return cert 1842 } 1843 } 1844 1845 // If nothing matches, return the first certificate. 1846 return &c.Certificates[0] 1847} 1848 1849func (c *Config) signSignatureAlgorithms() []signatureAlgorithm { 1850 if c != nil && c.SignSignatureAlgorithms != nil { 1851 return c.SignSignatureAlgorithms 1852 } 1853 return supportedSignatureAlgorithms 1854} 1855 1856func (c *Config) verifySignatureAlgorithms() []signatureAlgorithm { 1857 if c != nil && c.VerifySignatureAlgorithms != nil { 1858 return c.VerifySignatureAlgorithms 1859 } 1860 return supportedSignatureAlgorithms 1861} 1862 1863// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate 1864// from the CommonName and SubjectAlternateName fields of each of the leaf 1865// certificates. 1866func (c *Config) BuildNameToCertificate() { 1867 c.NameToCertificate = make(map[string]*Certificate) 1868 for i := range c.Certificates { 1869 cert := &c.Certificates[i] 1870 x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) 1871 if err != nil { 1872 continue 1873 } 1874 if len(x509Cert.Subject.CommonName) > 0 { 1875 c.NameToCertificate[x509Cert.Subject.CommonName] = cert 1876 } 1877 for _, san := range x509Cert.DNSNames { 1878 c.NameToCertificate[san] = cert 1879 } 1880 } 1881} 1882 1883// A Certificate is a chain of one or more certificates, leaf first. 1884type Certificate struct { 1885 Certificate [][]byte 1886 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey 1887 // OCSPStaple contains an optional OCSP response which will be served 1888 // to clients that request it. 1889 OCSPStaple []byte 1890 // SignedCertificateTimestampList contains an optional encoded 1891 // SignedCertificateTimestampList structure which will be 1892 // served to clients that request it. 1893 SignedCertificateTimestampList []byte 1894 // Leaf is the parsed form of the leaf certificate, which may be 1895 // initialized using x509.ParseCertificate to reduce per-handshake 1896 // processing for TLS clients doing client authentication. If nil, the 1897 // leaf certificate will be parsed as needed. 1898 Leaf *x509.Certificate 1899} 1900 1901// A TLS record. 1902type record struct { 1903 contentType recordType 1904 major, minor uint8 1905 payload []byte 1906} 1907 1908type handshakeMessage interface { 1909 marshal() []byte 1910 unmarshal([]byte) bool 1911} 1912 1913// lruSessionCache is a client or server session cache implementation 1914// that uses an LRU caching strategy. 1915type lruSessionCache struct { 1916 sync.Mutex 1917 1918 m map[string]*list.Element 1919 q *list.List 1920 capacity int 1921} 1922 1923type lruSessionCacheEntry struct { 1924 sessionKey string 1925 state interface{} 1926} 1927 1928// Put adds the provided (sessionKey, cs) pair to the cache. 1929func (c *lruSessionCache) Put(sessionKey string, cs interface{}) { 1930 c.Lock() 1931 defer c.Unlock() 1932 1933 if elem, ok := c.m[sessionKey]; ok { 1934 entry := elem.Value.(*lruSessionCacheEntry) 1935 entry.state = cs 1936 c.q.MoveToFront(elem) 1937 return 1938 } 1939 1940 if c.q.Len() < c.capacity { 1941 entry := &lruSessionCacheEntry{sessionKey, cs} 1942 c.m[sessionKey] = c.q.PushFront(entry) 1943 return 1944 } 1945 1946 elem := c.q.Back() 1947 entry := elem.Value.(*lruSessionCacheEntry) 1948 delete(c.m, entry.sessionKey) 1949 entry.sessionKey = sessionKey 1950 entry.state = cs 1951 c.q.MoveToFront(elem) 1952 c.m[sessionKey] = elem 1953} 1954 1955// Get returns the value associated with a given key. It returns (nil, 1956// false) if no value is found. 1957func (c *lruSessionCache) Get(sessionKey string) (interface{}, bool) { 1958 c.Lock() 1959 defer c.Unlock() 1960 1961 if elem, ok := c.m[sessionKey]; ok { 1962 c.q.MoveToFront(elem) 1963 return elem.Value.(*lruSessionCacheEntry).state, true 1964 } 1965 return nil, false 1966} 1967 1968// lruClientSessionCache is a ClientSessionCache implementation that 1969// uses an LRU caching strategy. 1970type lruClientSessionCache struct { 1971 lruSessionCache 1972} 1973 1974func (c *lruClientSessionCache) Put(sessionKey string, cs *ClientSessionState) { 1975 c.lruSessionCache.Put(sessionKey, cs) 1976} 1977 1978func (c *lruClientSessionCache) Get(sessionKey string) (*ClientSessionState, bool) { 1979 cs, ok := c.lruSessionCache.Get(sessionKey) 1980 if !ok { 1981 return nil, false 1982 } 1983 return cs.(*ClientSessionState), true 1984} 1985 1986// lruServerSessionCache is a ServerSessionCache implementation that 1987// uses an LRU caching strategy. 1988type lruServerSessionCache struct { 1989 lruSessionCache 1990} 1991 1992func (c *lruServerSessionCache) Put(sessionId string, session *sessionState) { 1993 c.lruSessionCache.Put(sessionId, session) 1994} 1995 1996func (c *lruServerSessionCache) Get(sessionId string) (*sessionState, bool) { 1997 cs, ok := c.lruSessionCache.Get(sessionId) 1998 if !ok { 1999 return nil, false 2000 } 2001 return cs.(*sessionState), true 2002} 2003 2004// NewLRUClientSessionCache returns a ClientSessionCache with the given 2005// capacity that uses an LRU strategy. If capacity is < 1, a default capacity 2006// is used instead. 2007func NewLRUClientSessionCache(capacity int) ClientSessionCache { 2008 const defaultSessionCacheCapacity = 64 2009 2010 if capacity < 1 { 2011 capacity = defaultSessionCacheCapacity 2012 } 2013 return &lruClientSessionCache{ 2014 lruSessionCache{ 2015 m: make(map[string]*list.Element), 2016 q: list.New(), 2017 capacity: capacity, 2018 }, 2019 } 2020} 2021 2022// NewLRUServerSessionCache returns a ServerSessionCache with the given 2023// capacity that uses an LRU strategy. If capacity is < 1, a default capacity 2024// is used instead. 2025func NewLRUServerSessionCache(capacity int) ServerSessionCache { 2026 const defaultSessionCacheCapacity = 64 2027 2028 if capacity < 1 { 2029 capacity = defaultSessionCacheCapacity 2030 } 2031 return &lruServerSessionCache{ 2032 lruSessionCache{ 2033 m: make(map[string]*list.Element), 2034 q: list.New(), 2035 capacity: capacity, 2036 }, 2037 } 2038} 2039 2040// TODO(jsing): Make these available to both crypto/x509 and crypto/tls. 2041type dsaSignature struct { 2042 R, S *big.Int 2043} 2044 2045type ecdsaSignature dsaSignature 2046 2047var emptyConfig Config 2048 2049func defaultConfig() *Config { 2050 return &emptyConfig 2051} 2052 2053var ( 2054 once sync.Once 2055 varDefaultCipherSuites []uint16 2056) 2057 2058func defaultCipherSuites() []uint16 { 2059 once.Do(initDefaultCipherSuites) 2060 return varDefaultCipherSuites 2061} 2062 2063func initDefaultCipherSuites() { 2064 for _, suite := range cipherSuites { 2065 if suite.flags&suitePSK == 0 { 2066 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id) 2067 } 2068 } 2069} 2070 2071func unexpectedMessageError(wanted, got interface{}) error { 2072 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted) 2073} 2074 2075func isSupportedSignatureAlgorithm(sigAlg signatureAlgorithm, sigAlgs []signatureAlgorithm) bool { 2076 for _, s := range sigAlgs { 2077 if s == sigAlg { 2078 return true 2079 } 2080 } 2081 return false 2082} 2083 2084var ( 2085 // See RFC 8446, section 4.1.3. 2086 downgradeTLS13 = []byte{0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44, 0x01} 2087 downgradeTLS12 = []byte{0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44, 0x00} 2088 2089 // This is a non-standard randomly-generated value. 2090 downgradeJDK11 = []byte{0xed, 0xbf, 0xb4, 0xa8, 0xc2, 0x47, 0x10, 0xff} 2091) 2092 2093func containsGREASE(values []uint16) bool { 2094 for _, v := range values { 2095 if isGREASEValue(v) { 2096 return true 2097 } 2098 } 2099 return false 2100} 2101