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