crypto/tls

Package tls partially implements TLS 1.2, as specified in RFC 5246, and TLS 1.3, as specified in RFC 8446.

Types

type ClientSessionCache

 1type ClientSessionCache interface {
 2	// Get searches for a ClientSessionState associated with the given key.
 3	// On return, ok is true if one was found.
 4	Get(sessionKey string) (session *ClientSessionState, ok bool)
 5
 6	// Put adds the ClientSessionState to the cache with the given key. It might
 7	// get called multiple times in a connection if a TLS 1.3 server provides
 8	// more than one session ticket. If called with a nil *ClientSessionState,
 9	// it should remove the cache entry.
10	Put(sessionKey string, cs *ClientSessionState)
11}

ClientSessionCache is a cache of ClientSessionState objects that can be used by a client to resume a TLS session with a given server. ClientSessionCache implementations should expect to be called concurrently from different goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which are supported via this interface.

type Config

  1type Config struct {
  2	// Rand provides the source of entropy for nonces and RSA blinding.
  3	// If Rand is nil, TLS uses the cryptographic random reader in package
  4	// crypto/rand.
  5	// The Reader must be safe for use by multiple goroutines.
  6	Rand	io.Reader
  7
  8	// Time returns the current time as the number of seconds since the epoch.
  9	// If Time is nil, TLS uses time.Now.
 10	Time	func() time.Time
 11
 12	// Certificates contains one or more certificate chains to present to the
 13	// other side of the connection. The first certificate compatible with the
 14	// peer's requirements is selected automatically.
 15	//
 16	// Server configurations must set one of Certificates, GetCertificate or
 17	// GetConfigForClient. Clients doing client-authentication may set either
 18	// Certificates or GetClientCertificate.
 19	//
 20	// Note: if there are multiple Certificates, and they don't have the
 21	// optional field Leaf set, certificate selection will incur a significant
 22	// per-handshake performance cost.
 23	Certificates	[]Certificate
 24
 25	// NameToCertificate maps from a certificate name to an element of
 26	// Certificates. Note that a certificate name can be of the form
 27	// '*.example.com' and so doesn't have to be a domain name as such.
 28	//
 29	// Deprecated: NameToCertificate only allows associating a single
 30	// certificate with a given name. Leave this field nil to let the library
 31	// select the first compatible chain from Certificates.
 32	NameToCertificate	map[string]*Certificate
 33
 34	// GetCertificate returns a Certificate based on the given
 35	// ClientHelloInfo. It will only be called if the client supplies SNI
 36	// information or if Certificates is empty.
 37	//
 38	// If GetCertificate is nil or returns nil, then the certificate is
 39	// retrieved from NameToCertificate. If NameToCertificate is nil, the
 40	// best element of Certificates will be used.
 41	//
 42	// Once a Certificate is returned it should not be modified.
 43	GetCertificate	func(*ClientHelloInfo) (*Certificate, error)
 44
 45	// GetClientCertificate, if not nil, is called when a server requests a
 46	// certificate from a client. If set, the contents of Certificates will
 47	// be ignored.
 48	//
 49	// If GetClientCertificate returns an error, the handshake will be
 50	// aborted and that error will be returned. Otherwise
 51	// GetClientCertificate must return a non-nil Certificate. If
 52	// Certificate.Certificate is empty then no certificate will be sent to
 53	// the server. If this is unacceptable to the server then it may abort
 54	// the handshake.
 55	//
 56	// GetClientCertificate may be called multiple times for the same
 57	// connection if renegotiation occurs or if TLS 1.3 is in use.
 58	//
 59	// Once a Certificate is returned it should not be modified.
 60	GetClientCertificate	func(*CertificateRequestInfo) (*Certificate, error)
 61
 62	// GetConfigForClient, if not nil, is called after a ClientHello is
 63	// received from a client. It may return a non-nil Config in order to
 64	// change the Config that will be used to handle this connection. If
 65	// the returned Config is nil, the original Config will be used. The
 66	// Config returned by this callback may not be subsequently modified.
 67	//
 68	// If GetConfigForClient is nil, the Config passed to Server() will be
 69	// used for all connections.
 70	//
 71	// If SessionTicketKey was explicitly set on the returned Config, or if
 72	// SetSessionTicketKeys was called on the returned Config, those keys will
 73	// be used. Otherwise, the original Config keys will be used (and possibly
 74	// rotated if they are automatically managed).
 75	GetConfigForClient	func(*ClientHelloInfo) (*Config, error)
 76
 77	// VerifyPeerCertificate, if not nil, is called after normal
 78	// certificate verification by either a TLS client or server. It
 79	// receives the raw ASN.1 certificates provided by the peer and also
 80	// any verified chains that normal processing found. If it returns a
 81	// non-nil error, the handshake is aborted and that error results.
 82	//
 83	// If normal verification fails then the handshake will abort before
 84	// considering this callback. If normal verification is disabled (on the
 85	// client when InsecureSkipVerify is set, or on a server when ClientAuth is
 86	// RequestClientCert or RequireAnyClientCert), then this callback will be
 87	// considered but the verifiedChains argument will always be nil. When
 88	// ClientAuth is NoClientCert, this callback is not called on the server.
 89	// rawCerts may be empty on the server if ClientAuth is RequestClientCert or
 90	// VerifyClientCertIfGiven.
 91	//
 92	// This callback is not invoked on resumed connections, as certificates are
 93	// not re-verified on resumption.
 94	//
 95	// verifiedChains and its contents should not be modified.
 96	VerifyPeerCertificate	func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
 97
 98	// VerifyConnection, if not nil, is called after normal certificate
 99	// verification and after VerifyPeerCertificate by either a TLS client
100	// or server. If it returns a non-nil error, the handshake is aborted
101	// and that error results.
102	//
103	// If normal verification fails then the handshake will abort before
104	// considering this callback. This callback will run for all connections,
105	// including resumptions, regardless of InsecureSkipVerify or ClientAuth
106	// settings.
107	VerifyConnection	func(ConnectionState) error
108
109	// RootCAs defines the set of root certificate authorities
110	// that clients use when verifying server certificates.
111	// If RootCAs is nil, TLS uses the host's root CA set.
112	RootCAs	*x509.CertPool
113
114	// NextProtos is a list of supported application level protocols, in
115	// order of preference. If both peers support ALPN, the selected
116	// protocol will be one from this list, and the connection will fail
117	// if there is no mutually supported protocol. If NextProtos is empty
118	// or the peer doesn't support ALPN, the connection will succeed and
119	// ConnectionState.NegotiatedProtocol will be empty.
120	NextProtos	[]string
121
122	// ServerName is used to verify the hostname on the returned
123	// certificates unless InsecureSkipVerify is given. It is also included
124	// in the client's handshake to support virtual hosting unless it is
125	// an IP address.
126	ServerName	string
127
128	// ClientAuth determines the server's policy for
129	// TLS Client Authentication. The default is NoClientCert.
130	ClientAuth	ClientAuthType
131
132	// ClientCAs defines the set of root certificate authorities
133	// that servers use if required to verify a client certificate
134	// by the policy in ClientAuth.
135	ClientCAs	*x509.CertPool
136
137	// InsecureSkipVerify controls whether a client verifies the server's
138	// certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
139	// accepts any certificate presented by the server and any host name in that
140	// certificate. In this mode, TLS is susceptible to machine-in-the-middle
141	// attacks unless custom verification is used. This should be used only for
142	// testing or in combination with VerifyConnection or VerifyPeerCertificate.
143	InsecureSkipVerify	bool
144
145	// CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of
146	// the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.
147	//
148	// If CipherSuites is nil, a safe default list is used. The default cipher
149	// suites might change over time. In Go 1.22 RSA key exchange based cipher
150	// suites were removed from the default list, but can be re-added with the
151	// GODEBUG setting tlsrsakex=1. In Go 1.23 3DES cipher suites were removed
152	// from the default list, but can be re-added with the GODEBUG setting
153	// tls3des=1.
154	CipherSuites	[]uint16
155
156	// PreferServerCipherSuites is a legacy field and has no effect.
157	//
158	// It used to control whether the server would follow the client's or the
159	// server's preference. Servers now select the best mutually supported
160	// cipher suite based on logic that takes into account inferred client
161	// hardware, server hardware, and security.
162	//
163	// Deprecated: PreferServerCipherSuites is ignored.
164	PreferServerCipherSuites	bool
165
166	// SessionTicketsDisabled may be set to true to disable session ticket and
167	// PSK (resumption) support. Note that on clients, session ticket support is
168	// also disabled if ClientSessionCache is nil.
169	SessionTicketsDisabled	bool
170
171	// SessionTicketKey is used by TLS servers to provide session resumption.
172	// See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled
173	// with random data before the first server handshake.
174	//
175	// Deprecated: if this field is left at zero, session ticket keys will be
176	// automatically rotated every day and dropped after seven days. For
177	// customizing the rotation schedule or synchronizing servers that are
178	// terminating connections for the same host, use SetSessionTicketKeys.
179	SessionTicketKey	[32]byte
180
181	// ClientSessionCache is a cache of ClientSessionState entries for TLS
182	// session resumption. It is only used by clients.
183	ClientSessionCache	ClientSessionCache
184
185	// UnwrapSession is called on the server to turn a ticket/identity
186	// previously produced by [WrapSession] into a usable session.
187	//
188	// UnwrapSession will usually either decrypt a session state in the ticket
189	// (for example with [Config.EncryptTicket]), or use the ticket as a handle
190	// to recover a previously stored state. It must use [ParseSessionState] to
191	// deserialize the session state.
192	//
193	// If UnwrapSession returns an error, the connection is terminated. If it
194	// returns (nil, nil), the session is ignored. crypto/tls may still choose
195	// not to resume the returned session.
196	UnwrapSession	func(identity []byte, cs ConnectionState) (*SessionState, error)
197
198	// WrapSession is called on the server to produce a session ticket/identity.
199	//
200	// WrapSession must serialize the session state with [SessionState.Bytes].
201	// It may then encrypt the serialized state (for example with
202	// [Config.DecryptTicket]) and use it as the ticket, or store the state and
203	// return a handle for it.
204	//
205	// If WrapSession returns an error, the connection is terminated.
206	//
207	// Warning: the return value will be exposed on the wire and to clients in
208	// plaintext. The application is in charge of encrypting and authenticating
209	// it (and rotating keys) or returning high-entropy identifiers. Failing to
210	// do so correctly can compromise current, previous, and future connections
211	// depending on the protocol version.
212	WrapSession	func(ConnectionState, *SessionState) ([]byte, error)
213
214	// MinVersion contains the minimum TLS version that is acceptable.
215	//
216	// By default, TLS 1.2 is currently used as the minimum. TLS 1.0 is the
217	// minimum supported by this package.
218	//
219	// The server-side default can be reverted to TLS 1.0 by including the value
220	// "tls10server=1" in the GODEBUG environment variable.
221	MinVersion	uint16
222
223	// MaxVersion contains the maximum TLS version that is acceptable.
224	//
225	// By default, the maximum version supported by this package is used,
226	// which is currently TLS 1.3.
227	MaxVersion	uint16
228
229	// CurvePreferences contains the elliptic curves that will be used in
230	// an ECDHE handshake, in preference order. If empty, the default will
231	// be used. The client will use the first preference as the type for
232	// its key share in TLS 1.3. This may change in the future.
233	//
234	// From Go 1.23, the default includes the X25519Kyber768Draft00 hybrid
235	// post-quantum key exchange. To disable it, set CurvePreferences explicitly
236	// or use the GODEBUG=tlskyber=0 environment variable.
237	CurvePreferences	[]CurveID
238
239	// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
240	// When true, the largest possible TLS record size is always used. When
241	// false, the size of TLS records may be adjusted in an attempt to
242	// improve latency.
243	DynamicRecordSizingDisabled	bool
244
245	// Renegotiation controls what types of renegotiation are supported.
246	// The default, none, is correct for the vast majority of applications.
247	Renegotiation	RenegotiationSupport
248
249	// KeyLogWriter optionally specifies a destination for TLS master secrets
250	// in NSS key log format that can be used to allow external programs
251	// such as Wireshark to decrypt TLS connections.
252	// See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
253	// Use of KeyLogWriter compromises security and should only be
254	// used for debugging.
255	KeyLogWriter	io.Writer
256
257	// EncryptedClientHelloConfigList is a serialized ECHConfigList. If
258	// provided, clients will attempt to connect to servers using Encrypted
259	// Client Hello (ECH) using one of the provided ECHConfigs. Servers
260	// currently ignore this field.
261	//
262	// If the list contains no valid ECH configs, the handshake will fail
263	// and return an error.
264	//
265	// If EncryptedClientHelloConfigList is set, MinVersion, if set, must
266	// be VersionTLS13.
267	//
268	// When EncryptedClientHelloConfigList is set, the handshake will only
269	// succeed if ECH is sucessfully negotiated. If the server rejects ECH,
270	// an ECHRejectionError error will be returned, which may contain a new
271	// ECHConfigList that the server suggests using.
272	//
273	// How this field is parsed may change in future Go versions, if the
274	// encoding described in the final Encrypted Client Hello RFC changes.
275	EncryptedClientHelloConfigList	[]byte
276
277	// EncryptedClientHelloRejectionVerify, if not nil, is called when ECH is
278	// rejected, in order to verify the ECH provider certificate in the outer
279	// Client Hello. If it returns a non-nil error, the handshake is aborted and
280	// that error results.
281	//
282	// Unlike VerifyPeerCertificate and VerifyConnection, normal certificate
283	// verification will not be performed before calling
284	// EncryptedClientHelloRejectionVerify.
285	//
286	// If EncryptedClientHelloRejectionVerify is nil and ECH is rejected, the
287	// roots in RootCAs will be used to verify the ECH providers public
288	// certificate. VerifyPeerCertificate and VerifyConnection are not called
289	// when ECH is rejected, even if set, and InsecureSkipVerify is ignored.
290	EncryptedClientHelloRejectionVerify	func(ConnectionState) error
291}

A Config structure is used to configure a TLS client or server. After one has been passed to a TLS function it must not be modified. A Config may be reused; the tls package will also not modify it.

func BuildNameToCertificate

1func (c *Config) BuildNameToCertificate()

BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate from the CommonName and SubjectAlternateName fields of each of the leaf certificates.

Deprecated: NameToCertificate only allows associating a single certificate with a given name. Leave that field nil to let the library select the first compatible chain from Certificates.

func Clone

1func (c *Config) Clone() *Config

Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is being used concurrently by a TLS client or server.

func DecryptTicket

1func (c *Config) DecryptTicket(identity []byte, cs ConnectionState) (*SessionState, error)

DecryptTicket decrypts a ticket encrypted by Config.EncryptTicket. It can be used as a [Config.UnwrapSession] implementation.

If the ticket can’t be decrypted or parsed, DecryptTicket returns (nil, nil).

func EncryptTicket

1func (c *Config) EncryptTicket(cs ConnectionState, ss *SessionState) ([]byte, error)

EncryptTicket encrypts a ticket with the Config's configured (or default) session ticket keys. It can be used as a [Config.WrapSession] implementation.

func SetSessionTicketKeys

1func (c *Config) SetSessionTicketKeys(keys [][32]byte)

SetSessionTicketKeys updates the session ticket keys for a server.

The first key will be used when creating new tickets, while all keys can be used for decrypting tickets. It is safe to call this function while the server is running in order to rotate the session ticket keys. The function will panic if keys is empty.

Calling this function will turn off automatic session ticket key rotation.

If multiple servers are terminating connections for the same host they should all have the same session ticket keys. If the session ticket keys leaks, previously recorded and future TLS connections using those keys might be compromised.


© Matthias Hochgatterer – MastodonGithubRésumé