This package is not in the latest version of its module.
Go to latest Published: May 7, 2026 License: BSD-3-ClauseThe Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Modules with tagged versions give importers more predictable builds.
When a project reaches major version v1 it is considered stable.
Package tls partially implements TLS 1.2, as specified in RFC 5246, and TLS 1.3, as specified in RFC 8446.
When the program is in FIPS 140-3 mode, this package behaves as if only SP 800-140C and SP 800-140D approved protocol versions, cipher suites, signature algorithms, certificate public key types and sizes, and key exchange and derivation algorithms were implemented. Others are silently ignored and not negotiated, or rejected. This set may depend on the algorithms supported by the FIPS 140-3 Go Cryptographic Module selected with GOFIPS140, and may change across Go versions.
A list of cipher suite IDs that are, or have been, implemented by this package.
See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml
This section is empty.
CipherSuiteName returns the standard name for the passed cipher suite ID (e.g. "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"), or a fallback representation of the ID value if the cipher suite is not implemented by this package.
Listen creates a TLS listener accepting connections on the given network address using net.Listen. The configuration config must be non-nil and must include at least one certificate or else set GetCertificate.
NewListener creates a Listener which accepts connections from an inner Listener and wraps each connection with Server. The configuration config must be non-nil and must include at least one certificate or else set GetCertificate.
VersionName returns the name for the provided TLS version number (e.g. "TLS 1.3"), or a fallback representation of the value if the version is not implemented by this package.
An AlertError is a TLS alert.
When using a QUIC transport, QUICConn methods will return an error which wraps AlertError rather than sending a TLS alert.
A Certificate is a chain of one or more certificates, leaf first.
LoadX509KeyPair reads and parses a public/private key pair from a pair of files. The files must contain PEM encoded data. The certificate file may contain intermediate certificates following the leaf certificate to form a certificate chain. On successful return, Certificate.Leaf will be populated.
Before Go 1.23 Certificate.Leaf was left nil, and the parsed certificate was discarded. This behavior can be re-enabled by setting "x509keypairleaf=0" in the GODEBUG environment variable.
Example ¶X509KeyPair parses a public/private key pair from a pair of PEM encoded data. On successful return, Certificate.Leaf will be populated.
Before Go 1.23 Certificate.Leaf was left nil, and the parsed certificate was discarded. This behavior can be re-enabled by setting "x509keypairleaf=0" in the GODEBUG environment variable.
Example ¶CertificateRequestInfo contains information from a server's CertificateRequest message, which is used to demand a certificate and proof of control from a client.
Context returns the context of the handshake that is in progress. This context is a child of the context passed to HandshakeContext, if any, and is canceled when the handshake concludes.
SupportsCertificate returns nil if the provided certificate is supported by the server that sent the CertificateRequest. Otherwise, it returns an error describing the reason for the incompatibility.
CertificateVerificationError is returned when certificate verification fails during the handshake.
CipherSuite is a TLS cipher suite. Note that most functions in this package accept and expose cipher suite IDs instead of this type.
CipherSuites returns a list of cipher suites currently implemented by this package, excluding those with security issues, which are returned by InsecureCipherSuites.
The list is sorted by ID. Note that the default cipher suites selected by this package might depend on logic that can't be captured by a static list, and might not match those returned by this function.
InsecureCipherSuites returns a list of cipher suites currently implemented by this package and which have security issues.
Most applications should not use the cipher suites in this list, and should only use those returned by CipherSuites.
ClientAuthType declares the policy the server will follow for TLS Client Authentication.
ClientHelloInfo contains information from a ClientHello message in order to guide application logic in the GetCertificate and GetConfigForClient callbacks.
Context returns the context of the handshake that is in progress. This context is a child of the context passed to HandshakeContext, if any, and is canceled when the handshake concludes.
SupportsCertificate returns nil if the provided certificate is supported by the client that sent the ClientHello. Otherwise, it returns an error describing the reason for the incompatibility.
If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate callback, this method will take into account the associated Config. Note that if GetConfigForClient returns a different Config, the change can't be accounted for by this method.
This function will call x509.ParseCertificate unless c.Leaf is set, which can incur a significant performance cost.
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.
NewLRUClientSessionCache returns a ClientSessionCache with the given capacity that uses an LRU strategy. If capacity is < 1, a default capacity is used instead.
ClientSessionState contains the state needed by a client to resume a previous TLS session.
NewResumptionState returns a state value that can be returned by [ClientSessionCache.Get] to resume a previous session.
state needs to be returned by ParseSessionState, and the ticket and session state must have been returned by ClientSessionState.ResumptionState.
ResumptionState returns the session ticket sent by the server (also known as the session's identity) and the state necessary to resume this session.
It can be called by [ClientSessionCache.Put] to serialize (with SessionState.Bytes) and store the session.
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.
Example (KeyLogWriter) ¶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.
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.
The returned Config can share session ticket keys with the original Config, which means connections could be resumed across the two Configs. WARNING: [Config.VerifyPeerCertificate] does not get called on resumed connections, including connections that were originally established on the parent Config. If that is not intended, use [Config.VerifyConnection] instead, or set [Config.SessionTicketsDisabled].
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).
EncryptTicket encrypts a ticket with the Config's configured (or default) session ticket keys. It can be used as a [Config.WrapSession] implementation.
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.
A Conn represents a secured connection. It implements the net.Conn interface.
Client returns a new TLS client side connection using conn as the underlying transport. The config cannot be nil: users must set either ServerName or InsecureSkipVerify in the config.
Dial connects to the given network address using net.Dial and then initiates a TLS handshake, returning the resulting TLS connection. Dial interprets a nil configuration as equivalent to the zero configuration; see the documentation of Config for the defaults.
Example ¶DialWithDialer connects to the given network address using dialer.Dial and then initiates a TLS handshake, returning the resulting TLS connection. Any timeout or deadline given in the dialer apply to connection and TLS handshake as a whole.
DialWithDialer interprets a nil configuration as equivalent to the zero configuration; see the documentation of Config for the defaults.
DialWithDialer uses context.Background internally; to specify the context, use Dialer.DialContext with NetDialer set to the desired dialer.
Server returns a new TLS server side connection using conn as the underlying transport. The configuration config must be non-nil and must include at least one certificate or else set GetCertificate.
CloseWrite shuts down the writing side of the connection. It should only be called once the handshake has completed and does not call CloseWrite on the underlying connection. Most callers should just use Conn.Close.
ConnectionState returns basic TLS details about the connection.
Handshake runs the client or server handshake protocol if it has not yet been run.
Most uses of this package need not call Handshake explicitly: the first Conn.Read or Conn.Write will call it automatically.
For control over canceling or setting a timeout on a handshake, use Conn.HandshakeContext or the Dialer's DialContext method instead.
In order to avoid denial of service attacks, the maximum RSA key size allowed in certificates sent by either the TLS server or client is limited to 8192 bits. This limit can be overridden by setting tlsmaxrsasize in the GODEBUG environment variable (e.g. GODEBUG=tlsmaxrsasize=4096).
HandshakeContext runs the client or server handshake protocol if it has not yet been run.
The provided Context must be non-nil. If the context is canceled before the handshake is complete, the handshake is interrupted and an error is returned. Once the handshake has completed, cancellation of the context will not affect the connection.
Most uses of this package need not call HandshakeContext explicitly: the first Conn.Read or Conn.Write will call it automatically.
NetConn returns the underlying connection that is wrapped by c. Note that writing to or reading from this connection directly will corrupt the TLS session.
OCSPResponse returns the stapled OCSP response from the TLS server, if any. (Only valid for client connections.)
Read reads data from the connection.
As Read calls Conn.Handshake, in order to prevent indefinite blocking a deadline must be set for both Read and Conn.Write before Read is called when the handshake has not yet completed. See Conn.SetDeadline, Conn.SetReadDeadline, and Conn.SetWriteDeadline.
RemoteAddr returns the remote network address.
SetDeadline sets the read and write deadlines associated with the connection. A zero value for t means Conn.Read and Conn.Write will not time out. After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
SetReadDeadline sets the read deadline on the underlying connection. A zero value for t means Conn.Read will not time out.
SetWriteDeadline sets the write deadline on the underlying connection. A zero value for t means Conn.Write will not time out. After a Conn.Write has timed out, the TLS state is corrupt and all future writes will return the same error.
VerifyHostname checks that the peer certificate chain is valid for connecting to host. If so, it returns nil; if not, it returns an error describing the problem.
Write writes data to the connection.
As Write calls Conn.Handshake, in order to prevent indefinite blocking a deadline must be set for both Conn.Read and Write before Write is called when the handshake has not yet completed. See Conn.SetDeadline, Conn.SetReadDeadline, and Conn.SetWriteDeadline.
ConnectionState records basic TLS details about the connection.
ExportKeyingMaterial returns length bytes of exported key material in a new slice as defined in RFC 5705. If context is nil, it is not used as part of the seed. If the connection was set to allow renegotiation via Config.Renegotiation, or if the connections supports neither TLS 1.3 nor Extended Master Secret, this function will return an error.
Exporting key material without Extended Master Secret or TLS 1.3 was disabled in Go 1.22 due to security issues (see the Security Considerations sections of RFC 5705 and RFC 7627), but can be re-enabled with the GODEBUG setting tlsunsafeekm=1.
CurveID is the type of a TLS identifier for a key exchange mechanism. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
In TLS 1.2, this registry used to support only elliptic curves. In TLS 1.3, it was extended to other groups and renamed NamedGroup. See RFC 8446, Section 4.2.7. It was then also extended to other mechanisms, such as hybrid post-quantum KEMs.
Dialer dials TLS connections given a configuration and a Dialer for the underlying connection.
Dial connects to the given network address and initiates a TLS handshake, returning the resulting TLS connection.
The returned Conn, if any, will always be of type *Conn.
Dial uses context.Background internally; to specify the context, use Dialer.DialContext.
DialContext connects to the given network address and initiates a TLS handshake, returning the resulting TLS connection.
The provided Context must be non-nil. If the context expires before the connection is complete, an error is returned. Once successfully connected, any expiration of the context will not affect the connection.
ECHRejectionError is the error type returned when ECH is rejected by a remote server. If the server offered a ECHConfigList to use for retries, the RetryConfigList field will contain this list.
The client may treat an ECHRejectionError with an empty set of RetryConfigs as a secure signal from the server.
EncryptedClientHelloKey holds a private key that is associated with a specific ECH config known to a client.
A QUICConfig configures a QUICConn.
A QUICConn represents a connection which uses a QUIC implementation as the underlying transport as described in RFC 9001.
Methods of QUICConn are not safe for concurrent use.
QUICClient returns a new TLS client side connection using QUICTransport as the underlying transport. The config cannot be nil.
The config's MinVersion must be at least TLS 1.3.
QUICServer returns a new TLS server side connection using QUICTransport as the underlying transport. The config cannot be nil.
The config's MinVersion must be at least TLS 1.3.
Close closes the connection and stops any in-progress handshake.
ConnectionState returns basic TLS details about the connection.
HandleData handles handshake bytes received from the peer. It may produce connection events, which may be read with QUICConn.NextEvent.
NextEvent returns the next event occurring on the connection. It returns an event with a Kind of QUICNoEvent when no events are available.
SendSessionTicket sends a session ticket to the client. It produces connection events, which may be read with QUICConn.NextEvent. Currently, it can only be called once.
SetTransportParameters sets the transport parameters to send to the peer.
Server connections may delay setting the transport parameters until after receiving the client's transport parameters. See QUICTransportParametersRequired.
Start starts the client or server handshake protocol. It may produce connection events, which may be read with QUICConn.NextEvent.
Start must be called at most once.
StoreSession stores a session previously received in a QUICStoreSession event in the ClientSessionCache. The application may process additional events or modify the SessionState before storing the session.
QUICEncryptionLevel represents a QUIC encryption level used to transmit handshake messages.
A QUICEvent is an event occurring on a QUIC connection.
The type of event is specified by the Kind field. The contents of the other fields are kind-specific.
A QUICEventKind is a type of operation on a QUIC connection.
RecordHeaderError is returned when a TLS record header is invalid.
RenegotiationSupport enumerates the different levels of support for TLS renegotiation. TLS renegotiation is the act of performing subsequent handshakes on a connection after the first. This significantly complicates the state machine and has been the source of numerous, subtle security issues. Initiating a renegotiation is not supported, but support for accepting renegotiation requests may be enabled.
Even when enabled, the server may not change its identity between handshakes (i.e. the leaf certificate must be the same). Additionally, concurrent handshake and application data flow is not permitted so renegotiation can only be used with protocols that synchronise with the renegotiation, such as HTTPS.
Renegotiation is not defined in TLS 1.3.
A SessionState is a resumable session.
ParseSessionState parses a SessionState encoded by SessionState.Bytes.
Bytes encodes the session, including any private fields, so that it can be parsed by ParseSessionState. The encoding contains secret values critical to the security of future and possibly past sessions.
The specific encoding should be considered opaque and may change incompatibly between Go versions.
SignatureScheme identifies a signature algorithm supported by TLS. See RFC 8446, Section 4.2.3.
The crypto/tls package only implements some countermeasures against Lucky13 attacks on CBC-mode encryption, and only on SHA1 variants. See http://www.isg.rhul.ac.uk/tls/TLStiming.pdf and https://www.imperialviolet.org/2013/02/04/luckythirteen.html.
|
internal
|
|
|
fips140tls
Package fips140tls controls whether crypto/tls requires FIPS-approved settings.
|
Package fips140tls controls whether crypto/tls requires FIPS-approved settings. |
| ? | : This menu |
| / | : Search site |
| f or F | : Jump to |
| y or Y | : Canonical URL |