...

Source file src/pkg/crypto/tls/common.go

     1	// Copyright 2009 The Go Authors. All rights reserved.
     2	// Use of this source code is governed by a BSD-style
     3	// license that can be found in the LICENSE file.
     4	
     5	package tls
     6	
     7	import (
     8		"container/list"
     9		"crypto"
    10		"crypto/rand"
    11		"crypto/sha512"
    12		"crypto/x509"
    13		"errors"
    14		"fmt"
    15		"internal/cpu"
    16		"io"
    17		"math/big"
    18		"net"
    19		"os"
    20		"strings"
    21		"sync"
    22		"time"
    23	)
    24	
    25	const (
    26		VersionTLS10 = 0x0301
    27		VersionTLS11 = 0x0302
    28		VersionTLS12 = 0x0303
    29		VersionTLS13 = 0x0304
    30	
    31		// Deprecated: SSLv3 is cryptographically broken, and will be
    32		// removed in Go 1.14. See golang.org/issue/32716.
    33		VersionSSL30 = 0x0300
    34	)
    35	
    36	const (
    37		maxPlaintext       = 16384        // maximum plaintext payload length
    38		maxCiphertext      = 16384 + 2048 // maximum ciphertext payload length
    39		maxCiphertextTLS13 = 16384 + 256  // maximum ciphertext length in TLS 1.3
    40		recordHeaderLen    = 5            // record header length
    41		maxHandshake       = 65536        // maximum handshake we support (protocol max is 16 MB)
    42		maxUselessRecords  = 16           // maximum number of consecutive non-advancing records
    43	)
    44	
    45	// TLS record types.
    46	type recordType uint8
    47	
    48	const (
    49		recordTypeChangeCipherSpec recordType = 20
    50		recordTypeAlert            recordType = 21
    51		recordTypeHandshake        recordType = 22
    52		recordTypeApplicationData  recordType = 23
    53	)
    54	
    55	// TLS handshake message types.
    56	const (
    57		typeHelloRequest        uint8 = 0
    58		typeClientHello         uint8 = 1
    59		typeServerHello         uint8 = 2
    60		typeNewSessionTicket    uint8 = 4
    61		typeEndOfEarlyData      uint8 = 5
    62		typeEncryptedExtensions uint8 = 8
    63		typeCertificate         uint8 = 11
    64		typeServerKeyExchange   uint8 = 12
    65		typeCertificateRequest  uint8 = 13
    66		typeServerHelloDone     uint8 = 14
    67		typeCertificateVerify   uint8 = 15
    68		typeClientKeyExchange   uint8 = 16
    69		typeFinished            uint8 = 20
    70		typeCertificateStatus   uint8 = 22
    71		typeKeyUpdate           uint8 = 24
    72		typeNextProtocol        uint8 = 67  // Not IANA assigned
    73		typeMessageHash         uint8 = 254 // synthetic message
    74	)
    75	
    76	// TLS compression types.
    77	const (
    78		compressionNone uint8 = 0
    79	)
    80	
    81	// TLS extension numbers
    82	const (
    83		extensionServerName              uint16 = 0
    84		extensionStatusRequest           uint16 = 5
    85		extensionSupportedCurves         uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7
    86		extensionSupportedPoints         uint16 = 11
    87		extensionSignatureAlgorithms     uint16 = 13
    88		extensionALPN                    uint16 = 16
    89		extensionSCT                     uint16 = 18
    90		extensionSessionTicket           uint16 = 35
    91		extensionPreSharedKey            uint16 = 41
    92		extensionEarlyData               uint16 = 42
    93		extensionSupportedVersions       uint16 = 43
    94		extensionCookie                  uint16 = 44
    95		extensionPSKModes                uint16 = 45
    96		extensionCertificateAuthorities  uint16 = 47
    97		extensionSignatureAlgorithmsCert uint16 = 50
    98		extensionKeyShare                uint16 = 51
    99		extensionNextProtoNeg            uint16 = 13172 // not IANA assigned
   100		extensionRenegotiationInfo       uint16 = 0xff01
   101	)
   102	
   103	// TLS signaling cipher suite values
   104	const (
   105		scsvRenegotiation uint16 = 0x00ff
   106	)
   107	
   108	// CurveID is the type of a TLS identifier for an elliptic curve. See
   109	// https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
   110	//
   111	// In TLS 1.3, this type is called NamedGroup, but at this time this library
   112	// only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
   113	type CurveID uint16
   114	
   115	const (
   116		CurveP256 CurveID = 23
   117		CurveP384 CurveID = 24
   118		CurveP521 CurveID = 25
   119		X25519    CurveID = 29
   120	)
   121	
   122	// TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
   123	type keyShare struct {
   124		group CurveID
   125		data  []byte
   126	}
   127	
   128	// TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
   129	const (
   130		pskModePlain uint8 = 0
   131		pskModeDHE   uint8 = 1
   132	)
   133	
   134	// TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
   135	// session. See RFC 8446, Section 4.2.11.
   136	type pskIdentity struct {
   137		label               []byte
   138		obfuscatedTicketAge uint32
   139	}
   140	
   141	// TLS Elliptic Curve Point Formats
   142	// https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
   143	const (
   144		pointFormatUncompressed uint8 = 0
   145	)
   146	
   147	// TLS CertificateStatusType (RFC 3546)
   148	const (
   149		statusTypeOCSP uint8 = 1
   150	)
   151	
   152	// Certificate types (for certificateRequestMsg)
   153	const (
   154		certTypeRSASign   = 1
   155		certTypeECDSASign = 64 // ECDSA or EdDSA keys, see RFC 8422, Section 3.
   156	)
   157	
   158	// Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with
   159	// TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
   160	const (
   161		signaturePKCS1v15 uint8 = iota + 225
   162		signatureRSAPSS
   163		signatureECDSA
   164		signatureEd25519
   165	)
   166	
   167	// directSigning is a standard Hash value that signals that no pre-hashing
   168	// should be performed, and that the input should be signed directly. It is the
   169	// hash function associated with the Ed25519 signature scheme.
   170	var directSigning crypto.Hash = 0
   171	
   172	// supportedSignatureAlgorithms contains the signature and hash algorithms that
   173	// the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+
   174	// CertificateRequest. The two fields are merged to match with TLS 1.3.
   175	// Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.
   176	var supportedSignatureAlgorithms = []SignatureScheme{
   177		PSSWithSHA256,
   178		ECDSAWithP256AndSHA256,
   179		Ed25519,
   180		PSSWithSHA384,
   181		PSSWithSHA512,
   182		PKCS1WithSHA256,
   183		PKCS1WithSHA384,
   184		PKCS1WithSHA512,
   185		ECDSAWithP384AndSHA384,
   186		ECDSAWithP521AndSHA512,
   187		PKCS1WithSHA1,
   188		ECDSAWithSHA1,
   189	}
   190	
   191	// supportedSignatureAlgorithmsTLS12 contains the signature and hash algorithms
   192	// that are supported in TLS 1.2, where it is possible to distinguish the
   193	// protocol version. This is temporary, see Issue 32425.
   194	var supportedSignatureAlgorithmsTLS12 = []SignatureScheme{
   195		PKCS1WithSHA256,
   196		ECDSAWithP256AndSHA256,
   197		Ed25519,
   198		PKCS1WithSHA384,
   199		PKCS1WithSHA512,
   200		ECDSAWithP384AndSHA384,
   201		ECDSAWithP521AndSHA512,
   202		PKCS1WithSHA1,
   203		ECDSAWithSHA1,
   204	}
   205	
   206	// helloRetryRequestRandom is set as the Random value of a ServerHello
   207	// to signal that the message is actually a HelloRetryRequest.
   208	var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3.
   209		0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
   210		0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
   211		0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
   212		0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C,
   213	}
   214	
   215	const (
   216		// downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server
   217		// random as a downgrade protection if the server would be capable of
   218		// negotiating a higher version. See RFC 8446, Section 4.1.3.
   219		downgradeCanaryTLS12 = "DOWNGRD\x01"
   220		downgradeCanaryTLS11 = "DOWNGRD\x00"
   221	)
   222	
   223	// ConnectionState records basic TLS details about the connection.
   224	type ConnectionState struct {
   225		Version                     uint16                // TLS version used by the connection (e.g. VersionTLS12)
   226		HandshakeComplete           bool                  // TLS handshake is complete
   227		DidResume                   bool                  // connection resumes a previous TLS connection
   228		CipherSuite                 uint16                // cipher suite in use (TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, ...)
   229		NegotiatedProtocol          string                // negotiated next protocol (not guaranteed to be from Config.NextProtos)
   230		NegotiatedProtocolIsMutual  bool                  // negotiated protocol was advertised by server (client side only)
   231		ServerName                  string                // server name requested by client, if any (server side only)
   232		PeerCertificates            []*x509.Certificate   // certificate chain presented by remote peer
   233		VerifiedChains              [][]*x509.Certificate // verified chains built from PeerCertificates
   234		SignedCertificateTimestamps [][]byte              // SCTs from the peer, if any
   235		OCSPResponse                []byte                // stapled OCSP response from peer, if any
   236	
   237		// ekm is a closure exposed via ExportKeyingMaterial.
   238		ekm func(label string, context []byte, length int) ([]byte, error)
   239	
   240		// TLSUnique contains the "tls-unique" channel binding value (see RFC
   241		// 5929, section 3). For resumed sessions this value will be nil
   242		// because resumption does not include enough context (see
   243		// https://mitls.org/pages/attacks/3SHAKE#channelbindings). This will
   244		// change in future versions of Go once the TLS master-secret fix has
   245		// been standardized and implemented. It is not defined in TLS 1.3.
   246		TLSUnique []byte
   247	}
   248	
   249	// ExportKeyingMaterial returns length bytes of exported key material in a new
   250	// slice as defined in RFC 5705. If context is nil, it is not used as part of
   251	// the seed. If the connection was set to allow renegotiation via
   252	// Config.Renegotiation, this function will return an error.
   253	func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
   254		return cs.ekm(label, context, length)
   255	}
   256	
   257	// ClientAuthType declares the policy the server will follow for
   258	// TLS Client Authentication.
   259	type ClientAuthType int
   260	
   261	const (
   262		NoClientCert ClientAuthType = iota
   263		RequestClientCert
   264		RequireAnyClientCert
   265		VerifyClientCertIfGiven
   266		RequireAndVerifyClientCert
   267	)
   268	
   269	// requiresClientCert reports whether the ClientAuthType requires a client
   270	// certificate to be provided.
   271	func requiresClientCert(c ClientAuthType) bool {
   272		switch c {
   273		case RequireAnyClientCert, RequireAndVerifyClientCert:
   274			return true
   275		default:
   276			return false
   277		}
   278	}
   279	
   280	// ClientSessionState contains the state needed by clients to resume TLS
   281	// sessions.
   282	type ClientSessionState struct {
   283		sessionTicket      []uint8               // Encrypted ticket used for session resumption with server
   284		vers               uint16                // SSL/TLS version negotiated for the session
   285		cipherSuite        uint16                // Ciphersuite negotiated for the session
   286		masterSecret       []byte                // Full handshake MasterSecret, or TLS 1.3 resumption_master_secret
   287		serverCertificates []*x509.Certificate   // Certificate chain presented by the server
   288		verifiedChains     [][]*x509.Certificate // Certificate chains we built for verification
   289		receivedAt         time.Time             // When the session ticket was received from the server
   290	
   291		// TLS 1.3 fields.
   292		nonce  []byte    // Ticket nonce sent by the server, to derive PSK
   293		useBy  time.Time // Expiration of the ticket lifetime as set by the server
   294		ageAdd uint32    // Random obfuscation factor for sending the ticket age
   295	}
   296	
   297	// ClientSessionCache is a cache of ClientSessionState objects that can be used
   298	// by a client to resume a TLS session with a given server. ClientSessionCache
   299	// implementations should expect to be called concurrently from different
   300	// goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not
   301	// SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which
   302	// are supported via this interface.
   303	type ClientSessionCache interface {
   304		// Get searches for a ClientSessionState associated with the given key.
   305		// On return, ok is true if one was found.
   306		Get(sessionKey string) (session *ClientSessionState, ok bool)
   307	
   308		// Put adds the ClientSessionState to the cache with the given key. It might
   309		// get called multiple times in a connection if a TLS 1.3 server provides
   310		// more than one session ticket. If called with a nil *ClientSessionState,
   311		// it should remove the cache entry.
   312		Put(sessionKey string, cs *ClientSessionState)
   313	}
   314	
   315	// SignatureScheme identifies a signature algorithm supported by TLS. See
   316	// RFC 8446, Section 4.2.3.
   317	type SignatureScheme uint16
   318	
   319	const (
   320		// RSASSA-PKCS1-v1_5 algorithms.
   321		PKCS1WithSHA256 SignatureScheme = 0x0401
   322		PKCS1WithSHA384 SignatureScheme = 0x0501
   323		PKCS1WithSHA512 SignatureScheme = 0x0601
   324	
   325		// RSASSA-PSS algorithms with public key OID rsaEncryption.
   326		PSSWithSHA256 SignatureScheme = 0x0804
   327		PSSWithSHA384 SignatureScheme = 0x0805
   328		PSSWithSHA512 SignatureScheme = 0x0806
   329	
   330		// ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.
   331		ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
   332		ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
   333		ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
   334	
   335		// EdDSA algorithms.
   336		Ed25519 SignatureScheme = 0x0807
   337	
   338		// Legacy signature and hash algorithms for TLS 1.2.
   339		PKCS1WithSHA1 SignatureScheme = 0x0201
   340		ECDSAWithSHA1 SignatureScheme = 0x0203
   341	)
   342	
   343	// ClientHelloInfo contains information from a ClientHello message in order to
   344	// guide certificate selection in the GetCertificate callback.
   345	type ClientHelloInfo struct {
   346		// CipherSuites lists the CipherSuites supported by the client (e.g.
   347		// TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
   348		CipherSuites []uint16
   349	
   350		// ServerName indicates the name of the server requested by the client
   351		// in order to support virtual hosting. ServerName is only set if the
   352		// client is using SNI (see RFC 4366, Section 3.1).
   353		ServerName string
   354	
   355		// SupportedCurves lists the elliptic curves supported by the client.
   356		// SupportedCurves is set only if the Supported Elliptic Curves
   357		// Extension is being used (see RFC 4492, Section 5.1.1).
   358		SupportedCurves []CurveID
   359	
   360		// SupportedPoints lists the point formats supported by the client.
   361		// SupportedPoints is set only if the Supported Point Formats Extension
   362		// is being used (see RFC 4492, Section 5.1.2).
   363		SupportedPoints []uint8
   364	
   365		// SignatureSchemes lists the signature and hash schemes that the client
   366		// is willing to verify. SignatureSchemes is set only if the Signature
   367		// Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
   368		SignatureSchemes []SignatureScheme
   369	
   370		// SupportedProtos lists the application protocols supported by the client.
   371		// SupportedProtos is set only if the Application-Layer Protocol
   372		// Negotiation Extension is being used (see RFC 7301, Section 3.1).
   373		//
   374		// Servers can select a protocol by setting Config.NextProtos in a
   375		// GetConfigForClient return value.
   376		SupportedProtos []string
   377	
   378		// SupportedVersions lists the TLS versions supported by the client.
   379		// For TLS versions less than 1.3, this is extrapolated from the max
   380		// version advertised by the client, so values other than the greatest
   381		// might be rejected if used.
   382		SupportedVersions []uint16
   383	
   384		// Conn is the underlying net.Conn for the connection. Do not read
   385		// from, or write to, this connection; that will cause the TLS
   386		// connection to fail.
   387		Conn net.Conn
   388	}
   389	
   390	// CertificateRequestInfo contains information from a server's
   391	// CertificateRequest message, which is used to demand a certificate and proof
   392	// of control from a client.
   393	type CertificateRequestInfo struct {
   394		// AcceptableCAs contains zero or more, DER-encoded, X.501
   395		// Distinguished Names. These are the names of root or intermediate CAs
   396		// that the server wishes the returned certificate to be signed by. An
   397		// empty slice indicates that the server has no preference.
   398		AcceptableCAs [][]byte
   399	
   400		// SignatureSchemes lists the signature schemes that the server is
   401		// willing to verify.
   402		SignatureSchemes []SignatureScheme
   403	}
   404	
   405	// RenegotiationSupport enumerates the different levels of support for TLS
   406	// renegotiation. TLS renegotiation is the act of performing subsequent
   407	// handshakes on a connection after the first. This significantly complicates
   408	// the state machine and has been the source of numerous, subtle security
   409	// issues. Initiating a renegotiation is not supported, but support for
   410	// accepting renegotiation requests may be enabled.
   411	//
   412	// Even when enabled, the server may not change its identity between handshakes
   413	// (i.e. the leaf certificate must be the same). Additionally, concurrent
   414	// handshake and application data flow is not permitted so renegotiation can
   415	// only be used with protocols that synchronise with the renegotiation, such as
   416	// HTTPS.
   417	//
   418	// Renegotiation is not defined in TLS 1.3.
   419	type RenegotiationSupport int
   420	
   421	const (
   422		// RenegotiateNever disables renegotiation.
   423		RenegotiateNever RenegotiationSupport = iota
   424	
   425		// RenegotiateOnceAsClient allows a remote server to request
   426		// renegotiation once per connection.
   427		RenegotiateOnceAsClient
   428	
   429		// RenegotiateFreelyAsClient allows a remote server to repeatedly
   430		// request renegotiation.
   431		RenegotiateFreelyAsClient
   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.
   438	type 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		// Certificates contains one or more certificate chains to present to
   450		// the other side of the connection. Server configurations must include
   451		// at least one certificate or else set GetCertificate. Clients doing
   452		// client-authentication may set either Certificates or
   453		// GetClientCertificate.
   454		Certificates []Certificate
   455	
   456		// NameToCertificate maps from a certificate name to an element of
   457		// Certificates. Note that a certificate name can be of the form
   458		// '*.example.com' and so doesn't have to be a domain name as such.
   459		// See Config.BuildNameToCertificate
   460		// The nil value causes the first element of Certificates to be used
   461		// for all connections.
   462		NameToCertificate map[string]*Certificate
   463	
   464		// GetCertificate returns a Certificate based on the given
   465		// ClientHelloInfo. It will only be called if the client supplies SNI
   466		// information or if Certificates is empty.
   467		//
   468		// If GetCertificate is nil or returns nil, then the certificate is
   469		// retrieved from NameToCertificate. If NameToCertificate is nil, the
   470		// first element of Certificates will be used.
   471		GetCertificate func(*ClientHelloInfo) (*Certificate, error)
   472	
   473		// GetClientCertificate, if not nil, is called when a server requests a
   474		// certificate from a client. If set, the contents of Certificates will
   475		// be ignored.
   476		//
   477		// If GetClientCertificate returns an error, the handshake will be
   478		// aborted and that error will be returned. Otherwise
   479		// GetClientCertificate must return a non-nil Certificate. If
   480		// Certificate.Certificate is empty then no certificate will be sent to
   481		// the server. If this is unacceptable to the server then it may abort
   482		// the handshake.
   483		//
   484		// GetClientCertificate may be called multiple times for the same
   485		// connection if renegotiation occurs or if TLS 1.3 is in use.
   486		GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
   487	
   488		// GetConfigForClient, if not nil, is called after a ClientHello is
   489		// received from a client. It may return a non-nil Config in order to
   490		// change the Config that will be used to handle this connection. If
   491		// the returned Config is nil, the original Config will be used. The
   492		// Config returned by this callback may not be subsequently modified.
   493		//
   494		// If GetConfigForClient is nil, the Config passed to Server() will be
   495		// used for all connections.
   496		//
   497		// Uniquely for the fields in the returned Config, session ticket keys
   498		// will be duplicated from the original Config if not set.
   499		// Specifically, if SetSessionTicketKeys was called on the original
   500		// config but not on the returned config then the ticket keys from the
   501		// original config will be copied into the new config before use.
   502		// Otherwise, if SessionTicketKey was set in the original config but
   503		// not in the returned config then it will be copied into the returned
   504		// config before use. If neither of those cases applies then the key
   505		// material from the returned config will be used for session tickets.
   506		GetConfigForClient func(*ClientHelloInfo) (*Config, error)
   507	
   508		// VerifyPeerCertificate, if not nil, is called after normal
   509		// certificate verification by either a TLS client or server. It
   510		// receives the raw ASN.1 certificates provided by the peer and also
   511		// any verified chains that normal processing found. If it returns a
   512		// non-nil error, the handshake is aborted and that error results.
   513		//
   514		// If normal verification fails then the handshake will abort before
   515		// considering this callback. If normal verification is disabled by
   516		// setting InsecureSkipVerify, or (for a server) when ClientAuth is
   517		// RequestClientCert or RequireAnyClientCert, then this callback will
   518		// be considered but the verifiedChains argument will always be nil.
   519		VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
   520	
   521		// RootCAs defines the set of root certificate authorities
   522		// that clients use when verifying server certificates.
   523		// If RootCAs is nil, TLS uses the host's root CA set.
   524		RootCAs *x509.CertPool
   525	
   526		// NextProtos is a list of supported application level protocols, in
   527		// order of preference.
   528		NextProtos []string
   529	
   530		// ServerName is used to verify the hostname on the returned
   531		// certificates unless InsecureSkipVerify is given. It is also included
   532		// in the client's handshake to support virtual hosting unless it is
   533		// an IP address.
   534		ServerName string
   535	
   536		// ClientAuth determines the server's policy for
   537		// TLS Client Authentication. The default is NoClientCert.
   538		ClientAuth ClientAuthType
   539	
   540		// ClientCAs defines the set of root certificate authorities
   541		// that servers use if required to verify a client certificate
   542		// by the policy in ClientAuth.
   543		ClientCAs *x509.CertPool
   544	
   545		// InsecureSkipVerify controls whether a client verifies the
   546		// server's certificate chain and host name.
   547		// If InsecureSkipVerify is true, TLS accepts any certificate
   548		// presented by the server and any host name in that certificate.
   549		// In this mode, TLS is susceptible to man-in-the-middle attacks.
   550		// This should be used only for testing.
   551		InsecureSkipVerify bool
   552	
   553		// CipherSuites is a list of supported cipher suites for TLS versions up to
   554		// TLS 1.2. If CipherSuites is nil, a default list of secure cipher suites
   555		// is used, with a preference order based on hardware performance. The
   556		// default cipher suites might change over Go versions. Note that TLS 1.3
   557		// ciphersuites are not configurable.
   558		CipherSuites []uint16
   559	
   560		// PreferServerCipherSuites controls whether the server selects the
   561		// client's most preferred ciphersuite, or the server's most preferred
   562		// ciphersuite. If true then the server's preference, as expressed in
   563		// the order of elements in CipherSuites, is used.
   564		PreferServerCipherSuites bool
   565	
   566		// SessionTicketsDisabled may be set to true to disable session ticket and
   567		// PSK (resumption) support. Note that on clients, session ticket support is
   568		// also disabled if ClientSessionCache is nil.
   569		SessionTicketsDisabled bool
   570	
   571		// SessionTicketKey is used by TLS servers to provide session resumption.
   572		// See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
   573		// with random data before the first server handshake.
   574		//
   575		// If multiple servers are terminating connections for the same host
   576		// they should all have the same SessionTicketKey. If the
   577		// SessionTicketKey leaks, previously recorded and future TLS
   578		// connections using that key might be compromised.
   579		SessionTicketKey [32]byte
   580	
   581		// ClientSessionCache is a cache of ClientSessionState entries for TLS
   582		// session resumption. It is only used by clients.
   583		ClientSessionCache ClientSessionCache
   584	
   585		// MinVersion contains the minimum SSL/TLS version that is acceptable.
   586		// If zero, then TLS 1.0 is taken as the minimum.
   587		MinVersion uint16
   588	
   589		// MaxVersion contains the maximum SSL/TLS version that is acceptable.
   590		// If zero, then the maximum version supported by this package is used,
   591		// which is currently TLS 1.3.
   592		MaxVersion uint16
   593	
   594		// CurvePreferences contains the elliptic curves that will be used in
   595		// an ECDHE handshake, in preference order. If empty, the default will
   596		// be used. The client will use the first preference as the type for
   597		// its key share in TLS 1.3. This may change in the future.
   598		CurvePreferences []CurveID
   599	
   600		// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
   601		// When true, the largest possible TLS record size is always used. When
   602		// false, the size of TLS records may be adjusted in an attempt to
   603		// improve latency.
   604		DynamicRecordSizingDisabled bool
   605	
   606		// Renegotiation controls what types of renegotiation are supported.
   607		// The default, none, is correct for the vast majority of applications.
   608		Renegotiation RenegotiationSupport
   609	
   610		// KeyLogWriter optionally specifies a destination for TLS master secrets
   611		// in NSS key log format that can be used to allow external programs
   612		// such as Wireshark to decrypt TLS connections.
   613		// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
   614		// Use of KeyLogWriter compromises security and should only be
   615		// used for debugging.
   616		KeyLogWriter io.Writer
   617	
   618		serverInitOnce sync.Once // guards calling (*Config).serverInit
   619	
   620		// mutex protects sessionTicketKeys.
   621		mutex sync.RWMutex
   622		// sessionTicketKeys contains zero or more ticket keys. If the length
   623		// is zero, SessionTicketsDisabled must be true. The first key is used
   624		// for new tickets and any subsequent keys can be used to decrypt old
   625		// tickets.
   626		sessionTicketKeys []ticketKey
   627	}
   628	
   629	// ticketKeyNameLen is the number of bytes of identifier that is prepended to
   630	// an encrypted session ticket in order to identify the key used to encrypt it.
   631	const ticketKeyNameLen = 16
   632	
   633	// ticketKey is the internal representation of a session ticket key.
   634	type ticketKey struct {
   635		// keyName is an opaque byte string that serves to identify the session
   636		// ticket key. It's exposed as plaintext in every session ticket.
   637		keyName [ticketKeyNameLen]byte
   638		aesKey  [16]byte
   639		hmacKey [16]byte
   640	}
   641	
   642	// ticketKeyFromBytes converts from the external representation of a session
   643	// ticket key to a ticketKey. Externally, session ticket keys are 32 random
   644	// bytes and this function expands that into sufficient name and key material.
   645	func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
   646		hashed := sha512.Sum512(b[:])
   647		copy(key.keyName[:], hashed[:ticketKeyNameLen])
   648		copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
   649		copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
   650		return key
   651	}
   652	
   653	// maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session
   654	// ticket, and the lifetime we set for tickets we send.
   655	const maxSessionTicketLifetime = 7 * 24 * time.Hour
   656	
   657	// Clone returns a shallow clone of c. It is safe to clone a Config that is
   658	// being used concurrently by a TLS client or server.
   659	func (c *Config) Clone() *Config {
   660		// Running serverInit ensures that it's safe to read
   661		// SessionTicketsDisabled.
   662		c.serverInitOnce.Do(func() { c.serverInit(nil) })
   663	
   664		var sessionTicketKeys []ticketKey
   665		c.mutex.RLock()
   666		sessionTicketKeys = c.sessionTicketKeys
   667		c.mutex.RUnlock()
   668	
   669		return &Config{
   670			Rand:                        c.Rand,
   671			Time:                        c.Time,
   672			Certificates:                c.Certificates,
   673			NameToCertificate:           c.NameToCertificate,
   674			GetCertificate:              c.GetCertificate,
   675			GetClientCertificate:        c.GetClientCertificate,
   676			GetConfigForClient:          c.GetConfigForClient,
   677			VerifyPeerCertificate:       c.VerifyPeerCertificate,
   678			RootCAs:                     c.RootCAs,
   679			NextProtos:                  c.NextProtos,
   680			ServerName:                  c.ServerName,
   681			ClientAuth:                  c.ClientAuth,
   682			ClientCAs:                   c.ClientCAs,
   683			InsecureSkipVerify:          c.InsecureSkipVerify,
   684			CipherSuites:                c.CipherSuites,
   685			PreferServerCipherSuites:    c.PreferServerCipherSuites,
   686			SessionTicketsDisabled:      c.SessionTicketsDisabled,
   687			SessionTicketKey:            c.SessionTicketKey,
   688			ClientSessionCache:          c.ClientSessionCache,
   689			MinVersion:                  c.MinVersion,
   690			MaxVersion:                  c.MaxVersion,
   691			CurvePreferences:            c.CurvePreferences,
   692			DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
   693			Renegotiation:               c.Renegotiation,
   694			KeyLogWriter:                c.KeyLogWriter,
   695			sessionTicketKeys:           sessionTicketKeys,
   696		}
   697	}
   698	
   699	// serverInit is run under c.serverInitOnce to do initialization of c. If c was
   700	// returned by a GetConfigForClient callback then the argument should be the
   701	// Config that was passed to Server, otherwise it should be nil.
   702	func (c *Config) serverInit(originalConfig *Config) {
   703		if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 {
   704			return
   705		}
   706	
   707		alreadySet := false
   708		for _, b := range c.SessionTicketKey {
   709			if b != 0 {
   710				alreadySet = true
   711				break
   712			}
   713		}
   714	
   715		if !alreadySet {
   716			if originalConfig != nil {
   717				copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:])
   718			} else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
   719				c.SessionTicketsDisabled = true
   720				return
   721			}
   722		}
   723	
   724		if originalConfig != nil {
   725			originalConfig.mutex.RLock()
   726			c.sessionTicketKeys = originalConfig.sessionTicketKeys
   727			originalConfig.mutex.RUnlock()
   728		} else {
   729			c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
   730		}
   731	}
   732	
   733	func (c *Config) ticketKeys() []ticketKey {
   734		c.mutex.RLock()
   735		// c.sessionTicketKeys is constant once created. SetSessionTicketKeys
   736		// will only update it by replacing it with a new value.
   737		ret := c.sessionTicketKeys
   738		c.mutex.RUnlock()
   739		return ret
   740	}
   741	
   742	// SetSessionTicketKeys updates the session ticket keys for a server. The first
   743	// key will be used when creating new tickets, while all keys can be used for
   744	// decrypting tickets. It is safe to call this function while the server is
   745	// running in order to rotate the session ticket keys. The function will panic
   746	// if keys is empty.
   747	func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
   748		if len(keys) == 0 {
   749			panic("tls: keys must have at least one key")
   750		}
   751	
   752		newKeys := make([]ticketKey, len(keys))
   753		for i, bytes := range keys {
   754			newKeys[i] = ticketKeyFromBytes(bytes)
   755		}
   756	
   757		c.mutex.Lock()
   758		c.sessionTicketKeys = newKeys
   759		c.mutex.Unlock()
   760	}
   761	
   762	func (c *Config) rand() io.Reader {
   763		r := c.Rand
   764		if r == nil {
   765			return rand.Reader
   766		}
   767		return r
   768	}
   769	
   770	func (c *Config) time() time.Time {
   771		t := c.Time
   772		if t == nil {
   773			t = time.Now
   774		}
   775		return t()
   776	}
   777	
   778	func (c *Config) cipherSuites() []uint16 {
   779		s := c.CipherSuites
   780		if s == nil {
   781			s = defaultCipherSuites()
   782		}
   783		return s
   784	}
   785	
   786	var supportedVersions = []uint16{
   787		VersionTLS13,
   788		VersionTLS12,
   789		VersionTLS11,
   790		VersionTLS10,
   791		VersionSSL30,
   792	}
   793	
   794	func (c *Config) supportedVersions(isClient bool) []uint16 {
   795		versions := make([]uint16, 0, len(supportedVersions))
   796		for _, v := range supportedVersions {
   797			// TLS 1.0 is the default minimum version.
   798			if (c == nil || c.MinVersion == 0) && v < VersionTLS10 {
   799				continue
   800			}
   801			if c != nil && c.MinVersion != 0 && v < c.MinVersion {
   802				continue
   803			}
   804			if c != nil && c.MaxVersion != 0 && v > c.MaxVersion {
   805				continue
   806			}
   807			// TLS 1.0 is the minimum version supported as a client.
   808			if isClient && v < VersionTLS10 {
   809				continue
   810			}
   811			// TLS 1.3 is opt-out in Go 1.13.
   812			if v == VersionTLS13 && !isTLS13Supported() {
   813				continue
   814			}
   815			versions = append(versions, v)
   816		}
   817		return versions
   818	}
   819	
   820	// tls13Support caches the result for isTLS13Supported.
   821	var tls13Support struct {
   822		sync.Once
   823		cached bool
   824	}
   825	
   826	// isTLS13Supported returns whether the program enabled TLS 1.3 by not opting
   827	// out with GODEBUG=tls13=0. It's cached after the first execution.
   828	func isTLS13Supported() bool {
   829		tls13Support.Do(func() {
   830			tls13Support.cached = goDebugString("tls13") != "0"
   831		})
   832		return tls13Support.cached
   833	}
   834	
   835	// goDebugString returns the value of the named GODEBUG key.
   836	// GODEBUG is of the form "key=val,key2=val2".
   837	func goDebugString(key string) string {
   838		s := os.Getenv("GODEBUG")
   839		for i := 0; i < len(s)-len(key)-1; i++ {
   840			if i > 0 && s[i-1] != ',' {
   841				continue
   842			}
   843			afterKey := s[i+len(key):]
   844			if afterKey[0] != '=' || s[i:i+len(key)] != key {
   845				continue
   846			}
   847			val := afterKey[1:]
   848			for i, b := range val {
   849				if b == ',' {
   850					return val[:i]
   851				}
   852			}
   853			return val
   854		}
   855		return ""
   856	}
   857	
   858	func (c *Config) maxSupportedVersion(isClient bool) uint16 {
   859		supportedVersions := c.supportedVersions(isClient)
   860		if len(supportedVersions) == 0 {
   861			return 0
   862		}
   863		return supportedVersions[0]
   864	}
   865	
   866	// supportedVersionsFromMax returns a list of supported versions derived from a
   867	// legacy maximum version value. Note that only versions supported by this
   868	// library are returned. Any newer peer will use supportedVersions anyway.
   869	func supportedVersionsFromMax(maxVersion uint16) []uint16 {
   870		versions := make([]uint16, 0, len(supportedVersions))
   871		for _, v := range supportedVersions {
   872			if v > maxVersion {
   873				continue
   874			}
   875			versions = append(versions, v)
   876		}
   877		return versions
   878	}
   879	
   880	var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
   881	
   882	func (c *Config) curvePreferences() []CurveID {
   883		if c == nil || len(c.CurvePreferences) == 0 {
   884			return defaultCurvePreferences
   885		}
   886		return c.CurvePreferences
   887	}
   888	
   889	// mutualVersion returns the protocol version to use given the advertised
   890	// versions of the peer. Priority is given to the peer preference order.
   891	func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) {
   892		supportedVersions := c.supportedVersions(isClient)
   893		for _, peerVersion := range peerVersions {
   894			for _, v := range supportedVersions {
   895				if v == peerVersion {
   896					return v, true
   897				}
   898			}
   899		}
   900		return 0, false
   901	}
   902	
   903	// getCertificate returns the best certificate for the given ClientHelloInfo,
   904	// defaulting to the first element of c.Certificates.
   905	func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
   906		if c.GetCertificate != nil &&
   907			(len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
   908			cert, err := c.GetCertificate(clientHello)
   909			if cert != nil || err != nil {
   910				return cert, err
   911			}
   912		}
   913	
   914		if len(c.Certificates) == 0 {
   915			return nil, errors.New("tls: no certificates configured")
   916		}
   917	
   918		if len(c.Certificates) == 1 || c.NameToCertificate == nil {
   919			// There's only one choice, so no point doing any work.
   920			return &c.Certificates[0], nil
   921		}
   922	
   923		name := strings.ToLower(clientHello.ServerName)
   924		for len(name) > 0 && name[len(name)-1] == '.' {
   925			name = name[:len(name)-1]
   926		}
   927	
   928		if cert, ok := c.NameToCertificate[name]; ok {
   929			return cert, nil
   930		}
   931	
   932		// try replacing labels in the name with wildcards until we get a
   933		// match.
   934		labels := strings.Split(name, ".")
   935		for i := range labels {
   936			labels[i] = "*"
   937			candidate := strings.Join(labels, ".")
   938			if cert, ok := c.NameToCertificate[candidate]; ok {
   939				return cert, nil
   940			}
   941		}
   942	
   943		// If nothing matches, return the first certificate.
   944		return &c.Certificates[0], nil
   945	}
   946	
   947	// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
   948	// from the CommonName and SubjectAlternateName fields of each of the leaf
   949	// certificates.
   950	func (c *Config) BuildNameToCertificate() {
   951		c.NameToCertificate = make(map[string]*Certificate)
   952		for i := range c.Certificates {
   953			cert := &c.Certificates[i]
   954			x509Cert := cert.Leaf
   955			if x509Cert == nil {
   956				var err error
   957				x509Cert, err = x509.ParseCertificate(cert.Certificate[0])
   958				if err != nil {
   959					continue
   960				}
   961			}
   962			if len(x509Cert.Subject.CommonName) > 0 {
   963				c.NameToCertificate[x509Cert.Subject.CommonName] = cert
   964			}
   965			for _, san := range x509Cert.DNSNames {
   966				c.NameToCertificate[san] = cert
   967			}
   968		}
   969	}
   970	
   971	const (
   972		keyLogLabelTLS12           = "CLIENT_RANDOM"
   973		keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
   974		keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
   975		keyLogLabelClientTraffic   = "CLIENT_TRAFFIC_SECRET_0"
   976		keyLogLabelServerTraffic   = "SERVER_TRAFFIC_SECRET_0"
   977	)
   978	
   979	func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error {
   980		if c.KeyLogWriter == nil {
   981			return nil
   982		}
   983	
   984		logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret))
   985	
   986		writerMutex.Lock()
   987		_, err := c.KeyLogWriter.Write(logLine)
   988		writerMutex.Unlock()
   989	
   990		return err
   991	}
   992	
   993	// writerMutex protects all KeyLogWriters globally. It is rarely enabled,
   994	// and is only for debugging, so a global mutex saves space.
   995	var writerMutex sync.Mutex
   996	
   997	// A Certificate is a chain of one or more certificates, leaf first.
   998	type Certificate struct {
   999		Certificate [][]byte
  1000		// PrivateKey contains the private key corresponding to the public key in
  1001		// Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.
  1002		// For a server up to TLS 1.2, it can also implement crypto.Decrypter with
  1003		// an RSA PublicKey.
  1004		PrivateKey crypto.PrivateKey
  1005		// OCSPStaple contains an optional OCSP response which will be served
  1006		// to clients that request it.
  1007		OCSPStaple []byte
  1008		// SignedCertificateTimestamps contains an optional list of Signed
  1009		// Certificate Timestamps which will be served to clients that request it.
  1010		SignedCertificateTimestamps [][]byte
  1011		// Leaf is the parsed form of the leaf certificate, which may be
  1012		// initialized using x509.ParseCertificate to reduce per-handshake
  1013		// processing for TLS clients doing client authentication. If nil, the
  1014		// leaf certificate will be parsed as needed.
  1015		Leaf *x509.Certificate
  1016	}
  1017	
  1018	type handshakeMessage interface {
  1019		marshal() []byte
  1020		unmarshal([]byte) bool
  1021	}
  1022	
  1023	// lruSessionCache is a ClientSessionCache implementation that uses an LRU
  1024	// caching strategy.
  1025	type lruSessionCache struct {
  1026		sync.Mutex
  1027	
  1028		m        map[string]*list.Element
  1029		q        *list.List
  1030		capacity int
  1031	}
  1032	
  1033	type lruSessionCacheEntry struct {
  1034		sessionKey string
  1035		state      *ClientSessionState
  1036	}
  1037	
  1038	// NewLRUClientSessionCache returns a ClientSessionCache with the given
  1039	// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
  1040	// is used instead.
  1041	func NewLRUClientSessionCache(capacity int) ClientSessionCache {
  1042		const defaultSessionCacheCapacity = 64
  1043	
  1044		if capacity < 1 {
  1045			capacity = defaultSessionCacheCapacity
  1046		}
  1047		return &lruSessionCache{
  1048			m:        make(map[string]*list.Element),
  1049			q:        list.New(),
  1050			capacity: capacity,
  1051		}
  1052	}
  1053	
  1054	// Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry
  1055	// corresponding to sessionKey is removed from the cache instead.
  1056	func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
  1057		c.Lock()
  1058		defer c.Unlock()
  1059	
  1060		if elem, ok := c.m[sessionKey]; ok {
  1061			if cs == nil {
  1062				c.q.Remove(elem)
  1063				delete(c.m, sessionKey)
  1064			} else {
  1065				entry := elem.Value.(*lruSessionCacheEntry)
  1066				entry.state = cs
  1067				c.q.MoveToFront(elem)
  1068			}
  1069			return
  1070		}
  1071	
  1072		if c.q.Len() < c.capacity {
  1073			entry := &lruSessionCacheEntry{sessionKey, cs}
  1074			c.m[sessionKey] = c.q.PushFront(entry)
  1075			return
  1076		}
  1077	
  1078		elem := c.q.Back()
  1079		entry := elem.Value.(*lruSessionCacheEntry)
  1080		delete(c.m, entry.sessionKey)
  1081		entry.sessionKey = sessionKey
  1082		entry.state = cs
  1083		c.q.MoveToFront(elem)
  1084		c.m[sessionKey] = elem
  1085	}
  1086	
  1087	// Get returns the ClientSessionState value associated with a given key. It
  1088	// returns (nil, false) if no value is found.
  1089	func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
  1090		c.Lock()
  1091		defer c.Unlock()
  1092	
  1093		if elem, ok := c.m[sessionKey]; ok {
  1094			c.q.MoveToFront(elem)
  1095			return elem.Value.(*lruSessionCacheEntry).state, true
  1096		}
  1097		return nil, false
  1098	}
  1099	
  1100	// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
  1101	type dsaSignature struct {
  1102		R, S *big.Int
  1103	}
  1104	
  1105	type ecdsaSignature dsaSignature
  1106	
  1107	var emptyConfig Config
  1108	
  1109	func defaultConfig() *Config {
  1110		return &emptyConfig
  1111	}
  1112	
  1113	var (
  1114		once                        sync.Once
  1115		varDefaultCipherSuites      []uint16
  1116		varDefaultCipherSuitesTLS13 []uint16
  1117	)
  1118	
  1119	func defaultCipherSuites() []uint16 {
  1120		once.Do(initDefaultCipherSuites)
  1121		return varDefaultCipherSuites
  1122	}
  1123	
  1124	func defaultCipherSuitesTLS13() []uint16 {
  1125		once.Do(initDefaultCipherSuites)
  1126		return varDefaultCipherSuitesTLS13
  1127	}
  1128	
  1129	func initDefaultCipherSuites() {
  1130		var topCipherSuites []uint16
  1131	
  1132		// Check the cpu flags for each platform that has optimized GCM implementations.
  1133		// Worst case, these variables will just all be false.
  1134		var (
  1135			hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ
  1136			hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL
  1137			// Keep in sync with crypto/aes/cipher_s390x.go.
  1138			hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)
  1139	
  1140			hasGCMAsm = hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X
  1141		)
  1142	
  1143		if hasGCMAsm {
  1144			// If AES-GCM hardware is provided then prioritise AES-GCM
  1145			// cipher suites.
  1146			topCipherSuites = []uint16{
  1147				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1148				TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  1149				TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1150				TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  1151				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  1152				TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  1153			}
  1154			varDefaultCipherSuitesTLS13 = []uint16{
  1155				TLS_AES_128_GCM_SHA256,
  1156				TLS_CHACHA20_POLY1305_SHA256,
  1157				TLS_AES_256_GCM_SHA384,
  1158			}
  1159		} else {
  1160			// Without AES-GCM hardware, we put the ChaCha20-Poly1305
  1161			// cipher suites first.
  1162			topCipherSuites = []uint16{
  1163				TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  1164				TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  1165				TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1166				TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  1167				TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1168				TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  1169			}
  1170			varDefaultCipherSuitesTLS13 = []uint16{
  1171				TLS_CHACHA20_POLY1305_SHA256,
  1172				TLS_AES_128_GCM_SHA256,
  1173				TLS_AES_256_GCM_SHA384,
  1174			}
  1175		}
  1176	
  1177		varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
  1178		varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
  1179	
  1180	NextCipherSuite:
  1181		for _, suite := range cipherSuites {
  1182			if suite.flags&suiteDefaultOff != 0 {
  1183				continue
  1184			}
  1185			for _, existing := range varDefaultCipherSuites {
  1186				if existing == suite.id {
  1187					continue NextCipherSuite
  1188				}
  1189			}
  1190			varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
  1191		}
  1192	}
  1193	
  1194	func unexpectedMessageError(wanted, got interface{}) error {
  1195		return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
  1196	}
  1197	
  1198	func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
  1199		for _, s := range supportedSignatureAlgorithms {
  1200			if s == sigAlg {
  1201				return true
  1202			}
  1203		}
  1204		return false
  1205	}
  1206	
  1207	// signatureFromSignatureScheme maps a signature algorithm to the underlying
  1208	// signature method (without hash function).
  1209	func signatureFromSignatureScheme(signatureAlgorithm SignatureScheme) uint8 {
  1210		switch signatureAlgorithm {
  1211		case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512:
  1212			return signaturePKCS1v15
  1213		case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512:
  1214			return signatureRSAPSS
  1215		case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512:
  1216			return signatureECDSA
  1217		case Ed25519:
  1218			return signatureEd25519
  1219		default:
  1220			return 0
  1221		}
  1222	}
  1223	

View as plain text