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