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.
10 "crypto/internal/boring"
31 // VersionTLS13 is under development in this library and can't be selected
32 // nor negotiated yet on either side.
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 = 5 // maximum number of consecutive non-advancing records
44 minVersion = VersionTLS10
45 maxVersion = VersionTLS12
52 recordTypeChangeCipherSpec recordType = 20
53 recordTypeAlert recordType = 21
54 recordTypeHandshake recordType = 22
55 recordTypeApplicationData recordType = 23
58 // TLS handshake message types.
60 typeHelloRequest uint8 = 0
61 typeClientHello uint8 = 1
62 typeServerHello uint8 = 2
63 typeNewSessionTicket uint8 = 4
64 typeCertificate uint8 = 11
65 typeServerKeyExchange uint8 = 12
66 typeCertificateRequest uint8 = 13
67 typeServerHelloDone uint8 = 14
68 typeCertificateVerify uint8 = 15
69 typeClientKeyExchange uint8 = 16
70 typeFinished uint8 = 20
71 typeCertificateStatus uint8 = 22
72 typeNextProtocol uint8 = 67 // Not IANA assigned
75 // TLS compression types.
77 compressionNone uint8 = 0
80 // TLS extension numbers
82 extensionServerName uint16 = 0
83 extensionStatusRequest uint16 = 5
84 extensionSupportedCurves uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7
85 extensionSupportedPoints uint16 = 11
86 extensionSignatureAlgorithms uint16 = 13
87 extensionALPN uint16 = 16
88 extensionSCT uint16 = 18
89 extensionSessionTicket uint16 = 35
90 extensionPreSharedKey uint16 = 41
91 extensionSupportedVersions uint16 = 43
92 extensionCookie uint16 = 44
93 extensionPSKModes uint16 = 45
94 extensionSignatureAlgorithmsCert uint16 = 50
95 extensionKeyShare uint16 = 51
96 extensionNextProtoNeg uint16 = 13172 // not IANA assigned
97 extensionRenegotiationInfo uint16 = 0xff01
100 // TLS signaling cipher suite values
102 scsvRenegotiation uint16 = 0x00ff
105 // CurveID is the type of a TLS identifier for an elliptic curve. See
106 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
108 // In TLS 1.3, this type is called NamedGroup, but at this time this library
109 // only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
113 CurveP256 CurveID = 23
114 CurveP384 CurveID = 24
115 CurveP521 CurveID = 25
119 // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
120 type keyShare struct {
125 // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.
127 pskModePlain uint8 = 0
131 // TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
132 // session. See RFC 8446, Section 4.2.11.
133 type pskIdentity struct {
135 obfuscatedTicketAge uint32
138 // TLS Elliptic Curve Point Formats
139 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
141 pointFormatUncompressed uint8 = 0
144 // TLS CertificateStatusType (RFC 3546)
146 statusTypeOCSP uint8 = 1
149 // Certificate types (for certificateRequestMsg)
151 certTypeRSASign = 1 // A certificate containing an RSA key
152 certTypeDSSSign = 2 // A certificate containing a DSA key
153 certTypeRSAFixedDH = 3 // A certificate containing a static DH key
154 certTypeDSSFixedDH = 4 // A certificate containing a static DH key
156 // See RFC 4492 sections 3 and 5.5.
157 certTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
158 certTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
159 certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
161 // Rest of these are reserved by the TLS spec
164 // Signature algorithms (for internal signaling use). Starting at 16 to avoid overlap with
165 // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.
167 signaturePKCS1v15 uint8 = iota + 16
172 // defaultSupportedSignatureAlgorithms 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 defaultSupportedSignatureAlgorithms = []SignatureScheme{
178 ECDSAWithP256AndSHA256,
180 ECDSAWithP384AndSHA384,
182 ECDSAWithP521AndSHA512,
187 // ConnectionState records basic TLS details about the connection.
188 type ConnectionState struct {
189 Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
190 HandshakeComplete bool // TLS handshake is complete
191 DidResume bool // connection resumes a previous TLS connection
192 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
193 NegotiatedProtocol string // negotiated next protocol (not guaranteed to be from Config.NextProtos)
194 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server (client side only)
195 ServerName string // server name requested by client, if any (server side only)
196 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
197 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
198 SignedCertificateTimestamps [][]byte // SCTs from the server, if any
199 OCSPResponse []byte // stapled OCSP response from server, if any
201 // ekm is a closure exposed via ExportKeyingMaterial.
202 ekm func(label string, context []byte, length int) ([]byte, error)
204 // TLSUnique contains the "tls-unique" channel binding value (see RFC
205 // 5929, section 3). For resumed sessions this value will be nil
206 // because resumption does not include enough context (see
207 // https://mitls.org/pages/attacks/3SHAKE#channelbindings). This will
208 // change in future versions of Go once the TLS master-secret fix has
209 // been standardized and implemented.
213 // ExportKeyingMaterial returns length bytes of exported key material in a new
214 // slice as defined in RFC 5705. If context is nil, it is not used as part of
215 // the seed. If the connection was set to allow renegotiation via
216 // Config.Renegotiation, this function will return an error.
217 func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) {
218 return cs.ekm(label, context, length)
221 // ClientAuthType declares the policy the server will follow for
222 // TLS Client Authentication.
223 type ClientAuthType int
226 NoClientCert ClientAuthType = iota
229 VerifyClientCertIfGiven
230 RequireAndVerifyClientCert
233 // ClientSessionState contains the state needed by clients to resume TLS
235 type ClientSessionState struct {
236 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
237 vers uint16 // SSL/TLS version negotiated for the session
238 cipherSuite uint16 // Ciphersuite negotiated for the session
239 masterSecret []byte // MasterSecret generated by client on a full handshake
240 serverCertificates []*x509.Certificate // Certificate chain presented by the server
241 verifiedChains [][]*x509.Certificate // Certificate chains we built for verification
244 // ClientSessionCache is a cache of ClientSessionState objects that can be used
245 // by a client to resume a TLS session with a given server. ClientSessionCache
246 // implementations should expect to be called concurrently from different
247 // goroutines. Only ticket-based resumption is supported, not SessionID-based
249 type ClientSessionCache interface {
250 // Get searches for a ClientSessionState associated with the given key.
251 // On return, ok is true if one was found.
252 Get(sessionKey string) (session *ClientSessionState, ok bool)
254 // Put adds the ClientSessionState to the cache with the given key.
255 Put(sessionKey string, cs *ClientSessionState)
258 // SignatureScheme identifies a signature algorithm supported by TLS. See
259 // RFC 8446, Section 4.2.3.
260 type SignatureScheme uint16
263 PKCS1WithSHA1 SignatureScheme = 0x0201
264 PKCS1WithSHA256 SignatureScheme = 0x0401
265 PKCS1WithSHA384 SignatureScheme = 0x0501
266 PKCS1WithSHA512 SignatureScheme = 0x0601
268 PSSWithSHA256 SignatureScheme = 0x0804
269 PSSWithSHA384 SignatureScheme = 0x0805
270 PSSWithSHA512 SignatureScheme = 0x0806
272 ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
273 ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
274 ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
276 // Legacy signature and hash algorithms for TLS 1.2.
277 ECDSAWithSHA1 SignatureScheme = 0x0203
280 // ClientHelloInfo contains information from a ClientHello message in order to
281 // guide certificate selection in the GetCertificate callback.
282 type ClientHelloInfo struct {
283 // CipherSuites lists the CipherSuites supported by the client (e.g.
284 // TLS_RSA_WITH_RC4_128_SHA).
285 CipherSuites []uint16
287 // ServerName indicates the name of the server requested by the client
288 // in order to support virtual hosting. ServerName is only set if the
289 // client is using SNI (see RFC 4366, Section 3.1).
292 // SupportedCurves lists the elliptic curves supported by the client.
293 // SupportedCurves is set only if the Supported Elliptic Curves
294 // Extension is being used (see RFC 4492, Section 5.1.1).
295 SupportedCurves []CurveID
297 // SupportedPoints lists the point formats supported by the client.
298 // SupportedPoints is set only if the Supported Point Formats Extension
299 // is being used (see RFC 4492, Section 5.1.2).
300 SupportedPoints []uint8
302 // SignatureSchemes lists the signature and hash schemes that the client
303 // is willing to verify. SignatureSchemes is set only if the Signature
304 // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1).
305 SignatureSchemes []SignatureScheme
307 // SupportedProtos lists the application protocols supported by the client.
308 // SupportedProtos is set only if the Application-Layer Protocol
309 // Negotiation Extension is being used (see RFC 7301, Section 3.1).
311 // Servers can select a protocol by setting Config.NextProtos in a
312 // GetConfigForClient return value.
313 SupportedProtos []string
315 // SupportedVersions lists the TLS versions supported by the client.
316 // For TLS versions less than 1.3, this is extrapolated from the max
317 // version advertised by the client, so values other than the greatest
318 // might be rejected if used.
319 SupportedVersions []uint16
321 // Conn is the underlying net.Conn for the connection. Do not read
322 // from, or write to, this connection; that will cause the TLS
323 // connection to fail.
327 // CertificateRequestInfo contains information from a server's
328 // CertificateRequest message, which is used to demand a certificate and proof
329 // of control from a client.
330 type CertificateRequestInfo struct {
331 // AcceptableCAs contains zero or more, DER-encoded, X.501
332 // Distinguished Names. These are the names of root or intermediate CAs
333 // that the server wishes the returned certificate to be signed by. An
334 // empty slice indicates that the server has no preference.
335 AcceptableCAs [][]byte
337 // SignatureSchemes lists the signature schemes that the server is
338 // willing to verify.
339 SignatureSchemes []SignatureScheme
342 // RenegotiationSupport enumerates the different levels of support for TLS
343 // renegotiation. TLS renegotiation is the act of performing subsequent
344 // handshakes on a connection after the first. This significantly complicates
345 // the state machine and has been the source of numerous, subtle security
346 // issues. Initiating a renegotiation is not supported, but support for
347 // accepting renegotiation requests may be enabled.
349 // Even when enabled, the server may not change its identity between handshakes
350 // (i.e. the leaf certificate must be the same). Additionally, concurrent
351 // handshake and application data flow is not permitted so renegotiation can
352 // only be used with protocols that synchronise with the renegotiation, such as
354 type RenegotiationSupport int
357 // RenegotiateNever disables renegotiation.
358 RenegotiateNever RenegotiationSupport = iota
360 // RenegotiateOnceAsClient allows a remote server to request
361 // renegotiation once per connection.
362 RenegotiateOnceAsClient
364 // RenegotiateFreelyAsClient allows a remote server to repeatedly
365 // request renegotiation.
366 RenegotiateFreelyAsClient
369 // A Config structure is used to configure a TLS client or server.
370 // After one has been passed to a TLS function it must not be
371 // modified. A Config may be reused; the tls package will also not
374 // Rand provides the source of entropy for nonces and RSA blinding.
375 // If Rand is nil, TLS uses the cryptographic random reader in package
377 // The Reader must be safe for use by multiple goroutines.
380 // Time returns the current time as the number of seconds since the epoch.
381 // If Time is nil, TLS uses time.Now.
382 Time func() time.Time
384 // Certificates contains one or more certificate chains to present to
385 // the other side of the connection. Server configurations must include
386 // at least one certificate or else set GetCertificate. Clients doing
387 // client-authentication may set either Certificates or
388 // GetClientCertificate.
389 Certificates []Certificate
391 // NameToCertificate maps from a certificate name to an element of
392 // Certificates. Note that a certificate name can be of the form
393 // '*.example.com' and so doesn't have to be a domain name as such.
394 // See Config.BuildNameToCertificate
395 // The nil value causes the first element of Certificates to be used
396 // for all connections.
397 NameToCertificate map[string]*Certificate
399 // GetCertificate returns a Certificate based on the given
400 // ClientHelloInfo. It will only be called if the client supplies SNI
401 // information or if Certificates is empty.
403 // If GetCertificate is nil or returns nil, then the certificate is
404 // retrieved from NameToCertificate. If NameToCertificate is nil, the
405 // first element of Certificates will be used.
406 GetCertificate func(*ClientHelloInfo) (*Certificate, error)
408 // GetClientCertificate, if not nil, is called when a server requests a
409 // certificate from a client. If set, the contents of Certificates will
412 // If GetClientCertificate returns an error, the handshake will be
413 // aborted and that error will be returned. Otherwise
414 // GetClientCertificate must return a non-nil Certificate. If
415 // Certificate.Certificate is empty then no certificate will be sent to
416 // the server. If this is unacceptable to the server then it may abort
419 // GetClientCertificate may be called multiple times for the same
420 // connection if renegotiation occurs or if TLS 1.3 is in use.
421 GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
423 // GetConfigForClient, if not nil, is called after a ClientHello is
424 // received from a client. It may return a non-nil Config in order to
425 // change the Config that will be used to handle this connection. If
426 // the returned Config is nil, the original Config will be used. The
427 // Config returned by this callback may not be subsequently modified.
429 // If GetConfigForClient is nil, the Config passed to Server() will be
430 // used for all connections.
432 // Uniquely for the fields in the returned Config, session ticket keys
433 // will be duplicated from the original Config if not set.
434 // Specifically, if SetSessionTicketKeys was called on the original
435 // config but not on the returned config then the ticket keys from the
436 // original config will be copied into the new config before use.
437 // Otherwise, if SessionTicketKey was set in the original config but
438 // not in the returned config then it will be copied into the returned
439 // config before use. If neither of those cases applies then the key
440 // material from the returned config will be used for session tickets.
441 GetConfigForClient func(*ClientHelloInfo) (*Config, error)
443 // VerifyPeerCertificate, if not nil, is called after normal
444 // certificate verification by either a TLS client or server. It
445 // receives the raw ASN.1 certificates provided by the peer and also
446 // any verified chains that normal processing found. If it returns a
447 // non-nil error, the handshake is aborted and that error results.
449 // If normal verification fails then the handshake will abort before
450 // considering this callback. If normal verification is disabled by
451 // setting InsecureSkipVerify, or (for a server) when ClientAuth is
452 // RequestClientCert or RequireAnyClientCert, then this callback will
453 // be considered but the verifiedChains argument will always be nil.
454 VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
456 // RootCAs defines the set of root certificate authorities
457 // that clients use when verifying server certificates.
458 // If RootCAs is nil, TLS uses the host's root CA set.
459 RootCAs *x509.CertPool
461 // NextProtos is a list of supported application level protocols, in
462 // order of preference.
465 // ServerName is used to verify the hostname on the returned
466 // certificates unless InsecureSkipVerify is given. It is also included
467 // in the client's handshake to support virtual hosting unless it is
471 // ClientAuth determines the server's policy for
472 // TLS Client Authentication. The default is NoClientCert.
473 ClientAuth ClientAuthType
475 // ClientCAs defines the set of root certificate authorities
476 // that servers use if required to verify a client certificate
477 // by the policy in ClientAuth.
478 ClientCAs *x509.CertPool
480 // InsecureSkipVerify controls whether a client verifies the
481 // server's certificate chain and host name.
482 // If InsecureSkipVerify is true, TLS accepts any certificate
483 // presented by the server and any host name in that certificate.
484 // In this mode, TLS is susceptible to man-in-the-middle attacks.
485 // This should be used only for testing.
486 InsecureSkipVerify bool
488 // CipherSuites is a list of supported cipher suites. If CipherSuites
489 // is nil, TLS uses a list of suites supported by the implementation.
490 CipherSuites []uint16
492 // PreferServerCipherSuites controls whether the server selects the
493 // client's most preferred ciphersuite, or the server's most preferred
494 // ciphersuite. If true then the server's preference, as expressed in
495 // the order of elements in CipherSuites, is used.
496 PreferServerCipherSuites bool
498 // SessionTicketsDisabled may be set to true to disable session ticket
499 // (resumption) support. Note that on clients, session ticket support is
500 // also disabled if ClientSessionCache is nil.
501 SessionTicketsDisabled bool
503 // SessionTicketKey is used by TLS servers to provide session
504 // resumption. See RFC 5077. If zero, it will be filled with
505 // random data before the first server handshake.
507 // If multiple servers are terminating connections for the same host
508 // they should all have the same SessionTicketKey. If the
509 // SessionTicketKey leaks, previously recorded and future TLS
510 // connections using that key are compromised.
511 SessionTicketKey [32]byte
513 // ClientSessionCache is a cache of ClientSessionState entries for TLS
514 // session resumption. It is only used by clients.
515 ClientSessionCache ClientSessionCache
517 // MinVersion contains the minimum SSL/TLS version that is acceptable.
518 // If zero, then TLS 1.0 is taken as the minimum.
521 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
522 // If zero, then the maximum version supported by this package is used,
523 // which is currently TLS 1.2.
526 // CurvePreferences contains the elliptic curves that will be used in
527 // an ECDHE handshake, in preference order. If empty, the default will
529 CurvePreferences []CurveID
531 // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
532 // When true, the largest possible TLS record size is always used. When
533 // false, the size of TLS records may be adjusted in an attempt to
535 DynamicRecordSizingDisabled bool
537 // Renegotiation controls what types of renegotiation are supported.
538 // The default, none, is correct for the vast majority of applications.
539 Renegotiation RenegotiationSupport
541 // KeyLogWriter optionally specifies a destination for TLS master secrets
542 // in NSS key log format that can be used to allow external programs
543 // such as Wireshark to decrypt TLS connections.
544 // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
545 // Use of KeyLogWriter compromises security and should only be
546 // used for debugging.
547 KeyLogWriter io.Writer
549 serverInitOnce sync.Once // guards calling (*Config).serverInit
551 // mutex protects sessionTicketKeys.
553 // sessionTicketKeys contains zero or more ticket keys. If the length
554 // is zero, SessionTicketsDisabled must be true. The first key is used
555 // for new tickets and any subsequent keys can be used to decrypt old
557 sessionTicketKeys []ticketKey
560 // ticketKeyNameLen is the number of bytes of identifier that is prepended to
561 // an encrypted session ticket in order to identify the key used to encrypt it.
562 const ticketKeyNameLen = 16
564 // ticketKey is the internal representation of a session ticket key.
565 type ticketKey struct {
566 // keyName is an opaque byte string that serves to identify the session
567 // ticket key. It's exposed as plaintext in every session ticket.
568 keyName [ticketKeyNameLen]byte
573 // ticketKeyFromBytes converts from the external representation of a session
574 // ticket key to a ticketKey. Externally, session ticket keys are 32 random
575 // bytes and this function expands that into sufficient name and key material.
576 func ticketKeyFromBytes(b [32]byte) (key ticketKey) {
577 hashed := sha512.Sum512(b[:])
578 copy(key.keyName[:], hashed[:ticketKeyNameLen])
579 copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16])
580 copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32])
584 // Clone returns a shallow clone of c. It is safe to clone a Config that is
585 // being used concurrently by a TLS client or server.
586 func (c *Config) Clone() *Config {
587 // Running serverInit ensures that it's safe to read
588 // SessionTicketsDisabled.
589 c.serverInitOnce.Do(func() { c.serverInit(nil) })
591 var sessionTicketKeys []ticketKey
593 sessionTicketKeys = c.sessionTicketKeys
599 Certificates: c.Certificates,
600 NameToCertificate: c.NameToCertificate,
601 GetCertificate: c.GetCertificate,
602 GetClientCertificate: c.GetClientCertificate,
603 GetConfigForClient: c.GetConfigForClient,
604 VerifyPeerCertificate: c.VerifyPeerCertificate,
606 NextProtos: c.NextProtos,
607 ServerName: c.ServerName,
608 ClientAuth: c.ClientAuth,
609 ClientCAs: c.ClientCAs,
610 InsecureSkipVerify: c.InsecureSkipVerify,
611 CipherSuites: c.CipherSuites,
612 PreferServerCipherSuites: c.PreferServerCipherSuites,
613 SessionTicketsDisabled: c.SessionTicketsDisabled,
614 SessionTicketKey: c.SessionTicketKey,
615 ClientSessionCache: c.ClientSessionCache,
616 MinVersion: c.MinVersion,
617 MaxVersion: c.MaxVersion,
618 CurvePreferences: c.CurvePreferences,
619 DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled,
620 Renegotiation: c.Renegotiation,
621 KeyLogWriter: c.KeyLogWriter,
622 sessionTicketKeys: sessionTicketKeys,
626 // serverInit is run under c.serverInitOnce to do initialization of c. If c was
627 // returned by a GetConfigForClient callback then the argument should be the
628 // Config that was passed to Server, otherwise it should be nil.
629 func (c *Config) serverInit(originalConfig *Config) {
630 if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 {
635 for _, b := range c.SessionTicketKey {
643 if originalConfig != nil {
644 copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:])
645 } else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
646 c.SessionTicketsDisabled = true
651 if originalConfig != nil {
652 originalConfig.mutex.RLock()
653 c.sessionTicketKeys = originalConfig.sessionTicketKeys
654 originalConfig.mutex.RUnlock()
656 c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)}
660 func (c *Config) ticketKeys() []ticketKey {
662 // c.sessionTicketKeys is constant once created. SetSessionTicketKeys
663 // will only update it by replacing it with a new value.
664 ret := c.sessionTicketKeys
669 // SetSessionTicketKeys updates the session ticket keys for a server. The first
670 // key will be used when creating new tickets, while all keys can be used for
671 // decrypting tickets. It is safe to call this function while the server is
672 // running in order to rotate the session ticket keys. The function will panic
674 func (c *Config) SetSessionTicketKeys(keys [][32]byte) {
676 panic("tls: keys must have at least one key")
679 newKeys := make([]ticketKey, len(keys))
680 for i, bytes := range keys {
681 newKeys[i] = ticketKeyFromBytes(bytes)
685 c.sessionTicketKeys = newKeys
689 func (c *Config) rand() io.Reader {
697 func (c *Config) time() time.Time {
705 func (c *Config) cipherSuites() []uint16 {
707 return fipsCipherSuites(c)
711 s = defaultCipherSuites()
716 func (c *Config) minVersion() uint16 {
718 return fipsMinVersion(c)
720 if c == nil || c.MinVersion == 0 {
726 func (c *Config) maxVersion() uint16 {
728 return fipsMaxVersion(c)
730 if c == nil || c.MaxVersion == 0 {
736 var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521}
738 func (c *Config) curvePreferences() []CurveID {
740 return fipsCurvePreferences(c)
742 if c == nil || len(c.CurvePreferences) == 0 {
743 return defaultCurvePreferences
745 return c.CurvePreferences
748 // mutualVersion returns the protocol version to use given the advertised
749 // version of the peer.
750 func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
751 minVersion := c.minVersion()
752 maxVersion := c.maxVersion()
754 if vers < minVersion {
757 if vers > maxVersion {
763 // getCertificate returns the best certificate for the given ClientHelloInfo,
764 // defaulting to the first element of c.Certificates.
765 func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
766 if c.GetCertificate != nil &&
767 (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
768 cert, err := c.GetCertificate(clientHello)
769 if cert != nil || err != nil {
774 if len(c.Certificates) == 0 {
775 return nil, errors.New("tls: no certificates configured")
778 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
779 // There's only one choice, so no point doing any work.
780 return &c.Certificates[0], nil
783 name := strings.ToLower(clientHello.ServerName)
784 for len(name) > 0 && name[len(name)-1] == '.' {
785 name = name[:len(name)-1]
788 if cert, ok := c.NameToCertificate[name]; ok {
792 // try replacing labels in the name with wildcards until we get a
794 labels := strings.Split(name, ".")
795 for i := range labels {
797 candidate := strings.Join(labels, ".")
798 if cert, ok := c.NameToCertificate[candidate]; ok {
803 // If nothing matches, return the first certificate.
804 return &c.Certificates[0], nil
807 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
808 // from the CommonName and SubjectAlternateName fields of each of the leaf
810 func (c *Config) BuildNameToCertificate() {
811 c.NameToCertificate = make(map[string]*Certificate)
812 for i := range c.Certificates {
813 cert := &c.Certificates[i]
814 if cert.Leaf == nil {
815 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
821 x509Cert := cert.Leaf
822 if len(x509Cert.Subject.CommonName) > 0 {
823 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
825 for _, san := range x509Cert.DNSNames {
826 c.NameToCertificate[san] = cert
831 // writeKeyLog logs client random and master secret if logging was enabled by
832 // setting c.KeyLogWriter.
833 func (c *Config) writeKeyLog(clientRandom, masterSecret []byte) error {
834 if c.KeyLogWriter == nil {
838 logLine := []byte(fmt.Sprintf("CLIENT_RANDOM %x %x\n", clientRandom, masterSecret))
841 _, err := c.KeyLogWriter.Write(logLine)
847 // writerMutex protects all KeyLogWriters globally. It is rarely enabled,
848 // and is only for debugging, so a global mutex saves space.
849 var writerMutex sync.Mutex
851 // A Certificate is a chain of one or more certificates, leaf first.
852 type Certificate struct {
854 // PrivateKey contains the private key corresponding to the public key
855 // in Leaf. For a server, this must implement crypto.Signer and/or
856 // crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
857 // (performing client authentication), this must be a crypto.Signer
858 // with an RSA or ECDSA PublicKey.
859 PrivateKey crypto.PrivateKey
860 // OCSPStaple contains an optional OCSP response which will be served
861 // to clients that request it.
863 // SignedCertificateTimestamps contains an optional list of Signed
864 // Certificate Timestamps which will be served to clients that request it.
865 SignedCertificateTimestamps [][]byte
866 // Leaf is the parsed form of the leaf certificate, which may be
867 // initialized using x509.ParseCertificate to reduce per-handshake
868 // processing for TLS clients doing client authentication. If nil, the
869 // leaf certificate will be parsed as needed.
870 Leaf *x509.Certificate
873 type handshakeMessage interface {
875 unmarshal([]byte) bool
878 // lruSessionCache is a ClientSessionCache implementation that uses an LRU
880 type lruSessionCache struct {
883 m map[string]*list.Element
888 type lruSessionCacheEntry struct {
890 state *ClientSessionState
893 // NewLRUClientSessionCache returns a ClientSessionCache with the given
894 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity
896 func NewLRUClientSessionCache(capacity int) ClientSessionCache {
897 const defaultSessionCacheCapacity = 64
900 capacity = defaultSessionCacheCapacity
902 return &lruSessionCache{
903 m: make(map[string]*list.Element),
909 // Put adds the provided (sessionKey, cs) pair to the cache.
910 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
914 if elem, ok := c.m[sessionKey]; ok {
915 entry := elem.Value.(*lruSessionCacheEntry)
917 c.q.MoveToFront(elem)
921 if c.q.Len() < c.capacity {
922 entry := &lruSessionCacheEntry{sessionKey, cs}
923 c.m[sessionKey] = c.q.PushFront(entry)
928 entry := elem.Value.(*lruSessionCacheEntry)
929 delete(c.m, entry.sessionKey)
930 entry.sessionKey = sessionKey
932 c.q.MoveToFront(elem)
933 c.m[sessionKey] = elem
936 // Get returns the ClientSessionState value associated with a given key. It
937 // returns (nil, false) if no value is found.
938 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
942 if elem, ok := c.m[sessionKey]; ok {
943 c.q.MoveToFront(elem)
944 return elem.Value.(*lruSessionCacheEntry).state, true
949 // TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
950 type dsaSignature struct {
954 type ecdsaSignature dsaSignature
956 var emptyConfig Config
958 func defaultConfig() *Config {
964 varDefaultCipherSuites []uint16
965 varDefaultCipherSuitesTLS13 []uint16
968 func defaultCipherSuites() []uint16 {
969 once.Do(initDefaultCipherSuites)
970 return varDefaultCipherSuites
973 func defaultCipherSuitesTLS13() []uint16 {
974 once.Do(initDefaultCipherSuites)
975 return varDefaultCipherSuitesTLS13
978 func initDefaultCipherSuites() {
979 var topCipherSuites []uint16
981 // Check the cpu flags for each platform that has optimized GCM implementations.
982 // Worst case, these variables will just all be false.
984 hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ
985 hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL
986 // Keep in sync with crypto/aes/cipher_s390x.go.
987 hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)
989 hasGCMAsm = hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X
992 if hasGCMAsm || boring.Enabled {
993 // If BoringCrypto is enabled, always prioritize AES-GCM.
994 // If AES-GCM hardware is provided then prioritise AES-GCM
996 topCipherSuites = []uint16{
997 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
998 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
999 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1000 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
1001 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1002 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1004 varDefaultCipherSuitesTLS13 = []uint16{
1005 TLS_AES_128_GCM_SHA256,
1006 TLS_CHACHA20_POLY1305_SHA256,
1007 TLS_AES_256_GCM_SHA384,
1010 // Without AES-GCM hardware, we put the ChaCha20-Poly1305
1011 // cipher suites first.
1012 topCipherSuites = []uint16{
1013 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1014 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1015 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
1016 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
1017 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
1018 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
1020 varDefaultCipherSuitesTLS13 = []uint16{
1021 TLS_CHACHA20_POLY1305_SHA256,
1022 TLS_AES_128_GCM_SHA256,
1023 TLS_AES_256_GCM_SHA384,
1027 varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites))
1028 varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...)
1031 for _, suite := range cipherSuites {
1032 if suite.flags&suiteDefaultOff != 0 {
1035 for _, existing := range varDefaultCipherSuites {
1036 if existing == suite.id {
1037 continue NextCipherSuite
1040 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1044 func unexpectedMessageError(wanted, got interface{}) error {
1045 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1048 func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool {
1049 for _, s := range supportedSignatureAlgorithms {
1057 // signatureFromSignatureScheme maps a signature algorithm to the underlying
1058 // signature method (without hash function).
1059 func signatureFromSignatureScheme(signatureAlgorithm SignatureScheme) uint8 {
1060 switch signatureAlgorithm {
1061 case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512:
1062 return signaturePKCS1v15
1063 case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512:
1064 return signatureRSAPSS
1065 case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512:
1066 return signatureECDSA