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