Movatterモバイル変換


[0]ホーム

URL:


tls

packagestandard library
go1.25.5Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2025 License:BSD-3-ClauseImports:52Imported by:177,174

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

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

FIPS 140-3 mode

When the program is inFIPS 140-3 mode, this package behaves as if onlySP 800-140C and SP 800-140D approved protocol versions, cipher suites,signature algorithms, certificate public key types and sizes, and keyexchange and derivation algorithms were implemented. Others are silentlyignored and not negotiated, or rejected. This set may depend on thealgorithms supported by the FIPS 140-3 Go Cryptographic Module selected withGOFIPS140, and may change across Go versions.

Index

Examples

Constants

View Source
const (// TLS 1.0 - 1.2 cipher suites.TLS_RSA_WITH_RC4_128_SHAuint16 = 0x0005TLS_RSA_WITH_3DES_EDE_CBC_SHAuint16 = 0x000aTLS_RSA_WITH_AES_128_CBC_SHAuint16 = 0x002fTLS_RSA_WITH_AES_256_CBC_SHAuint16 = 0x0035TLS_RSA_WITH_AES_128_CBC_SHA256uint16 = 0x003cTLS_RSA_WITH_AES_128_GCM_SHA256uint16 = 0x009cTLS_RSA_WITH_AES_256_GCM_SHA384uint16 = 0x009dTLS_ECDHE_ECDSA_WITH_RC4_128_SHAuint16 = 0xc007TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHAuint16 = 0xc009TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHAuint16 = 0xc00aTLS_ECDHE_RSA_WITH_RC4_128_SHAuint16 = 0xc011TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHAuint16 = 0xc012TLS_ECDHE_RSA_WITH_AES_128_CBC_SHAuint16 = 0xc013TLS_ECDHE_RSA_WITH_AES_256_CBC_SHAuint16 = 0xc014TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256uint16 = 0xc023TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256uint16 = 0xc027TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256uint16 = 0xc02fTLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256uint16 = 0xc02bTLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384uint16 = 0xc030TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384uint16 = 0xc02cTLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256uint16 = 0xcca8TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256uint16 = 0xcca9// TLS 1.3 cipher suites.TLS_AES_128_GCM_SHA256uint16 = 0x1301TLS_AES_256_GCM_SHA384uint16 = 0x1302TLS_CHACHA20_POLY1305_SHA256uint16 = 0x1303// TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator// that the client is doing version fallback. SeeRFC 7507.TLS_FALLBACK_SCSVuint16 = 0x5600// Legacy names for the corresponding cipher suites with the correct _SHA256// suffix, retained for backward compatibility.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305   =TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 =TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256)

A list of cipher suite IDs that are, or have been, implemented by thispackage.

Seehttps://www.iana.org/assignments/tls-parameters/tls-parameters.xml

View Source
const (VersionTLS10 = 0x0301VersionTLS11 = 0x0302VersionTLS12 = 0x0303VersionTLS13 = 0x0304// Deprecated: SSLv3 is cryptographically broken, and is no longer// supported by this package. See golang.org/issue/32716.VersionSSL30 = 0x0300)
View Source
const (QUICEncryptionLevelInitial =QUICEncryptionLevel(iota)QUICEncryptionLevelEarlyQUICEncryptionLevelHandshakeQUICEncryptionLevelApplication)

Variables

This section is empty.

Functions

funcCipherSuiteNameadded ingo1.14

func CipherSuiteName(iduint16)string

CipherSuiteName returns the standard name for the passed cipher suite ID(e.g. "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"), or a fallback representationof the ID value if the cipher suite is not implemented by this package.

funcListen

func Listen(network, laddrstring, config *Config) (net.Listener,error)

Listen creates a TLS listener accepting connections on thegiven network address using net.Listen.The configuration config must be non-nil and must includeat least one certificate or else set GetCertificate.

funcNewListener

func NewListener(innernet.Listener, config *Config)net.Listener

NewListener creates a Listener which accepts connections from an innerListener and wraps each connection withServer.The configuration config must be non-nil and must includeat least one certificate or else set GetCertificate.

funcVersionNameadded ingo1.21.0

func VersionName(versionuint16)string

VersionName returns the name for the provided TLS version number(e.g. "TLS 1.3"), or a fallback representation of the value if theversion is not implemented by this package.

Types

typeAlertErroradded ingo1.21.0

type AlertErroruint8

An AlertError is a TLS alert.

When using a QUIC transport, QUICConn methods will return an errorwhich wraps AlertError rather than sending a TLS alert.

func (AlertError)Erroradded ingo1.21.0

func (eAlertError) Error()string

typeCertificate

type Certificate struct {Certificate [][]byte// PrivateKey contains the private key corresponding to the public key in// Leaf. This must implement crypto.Signer with an RSA, ECDSA or Ed25519 PublicKey.// For a server up to TLS 1.2, it can also implement crypto.Decrypter with// an RSA PublicKey.PrivateKeycrypto.PrivateKey// SupportedSignatureAlgorithms is an optional list restricting what// signature algorithms the PrivateKey can be used for.SupportedSignatureAlgorithms []SignatureScheme// OCSPStaple contains an optional OCSP response which will be served// to clients that request it.OCSPStaple []byte// SignedCertificateTimestamps contains an optional list of Signed// Certificate Timestamps which will be served to clients that request it.SignedCertificateTimestamps [][]byte// Leaf is the parsed form of the leaf certificate, which may be initialized// using x509.ParseCertificate to reduce per-handshake processing. If nil,// the leaf certificate will be parsed as needed.Leaf *x509.Certificate}

A Certificate is a chain of one or more certificates, leaf first.

funcLoadX509KeyPair

func LoadX509KeyPair(certFile, keyFilestring) (Certificate,error)

LoadX509KeyPair reads and parses a public/private key pair from a pair offiles. The files must contain PEM encoded data. The certificate file maycontain intermediate certificates following the leaf certificate to form acertificate chain. On successful return, Certificate.Leaf will be populated.

Before Go 1.23 Certificate.Leaf was left nil, and the parsed certificate wasdiscarded. This behavior can be re-enabled by setting "x509keypairleaf=0"in the GODEBUG environment variable.

Example
package mainimport ("crypto/tls""log")func main() {cert, err := tls.LoadX509KeyPair("testdata/example-cert.pem", "testdata/example-key.pem")if err != nil {log.Fatal(err)}cfg := &tls.Config{Certificates: []tls.Certificate{cert}}listener, err := tls.Listen("tcp", ":2000", cfg)if err != nil {log.Fatal(err)}_ = listener}

funcX509KeyPair

func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate,error)

X509KeyPair parses a public/private key pair from a pair ofPEM encoded data. On successful return, Certificate.Leaf will be populated.

Before Go 1.23 Certificate.Leaf was left nil, and the parsed certificate wasdiscarded. This behavior can be re-enabled by setting "x509keypairleaf=0"in the GODEBUG environment variable.

Example
package mainimport ("crypto/tls""log")func main() {certPem := []byte(`-----BEGIN CERTIFICATE-----MIIBhTCCASugAwIBAgIQIRi6zePL6mKjOipn+dNuaTAKBggqhkjOPQQDAjASMRAwDgYDVQQKEwdBY21lIENvMB4XDTE3MTAyMDE5NDMwNloXDTE4MTAyMDE5NDMwNlowEjEQMA4GA1UEChMHQWNtZSBDbzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABD0d7VNhbWvZLWPuj/RtHFjvtJBEwOkhbN/BnnE8rnZR8+sbwnc/KhCk3FhnpHZnQz7B5aETbbIgmuvewdjvSBSjYzBhMA4GA1UdDwEB/wQEAwICpDATBgNVHSUEDDAKBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1UdEQQiMCCCDmxvY2FsaG9zdDo1NDUzgg4xMjcuMC4wLjE6NTQ1MzAKBggqhkjOPQQDAgNIADBFAiEA2zpJEPQyz6/lWf86aX6PepsntZv2GYlA5UpabfT2EZICICpJ5h/iI+i341gBmLiAFQOyTDT+/wQc6MF9+Yw1Yy0t-----END CERTIFICATE-----`)keyPem := []byte(`-----BEGIN EC PRIVATE KEY-----MHcCAQEEIIrYSSNQFaA2Hwf1duRSxKtLYX5CB04fSeQ6tF1aY/PuoAoGCCqGSM49AwEHoUQDQgAEPR3tU2Fta9ktY+6P9G0cWO+0kETA6SFs38GecTyudlHz6xvCdz8qEKTcWGekdmdDPsHloRNtsiCa697B2O9IFA==-----END EC PRIVATE KEY-----`)cert, err := tls.X509KeyPair(certPem, keyPem)if err != nil {log.Fatal(err)}cfg := &tls.Config{Certificates: []tls.Certificate{cert}}listener, err := tls.Listen("tcp", ":2000", cfg)if err != nil {log.Fatal(err)}_ = listener}

Example (HttpServer)
package mainimport ("crypto/tls""log""net/http""time")func main() {certPem := []byte(`-----BEGIN CERTIFICATE-----MIIBhTCCASugAwIBAgIQIRi6zePL6mKjOipn+dNuaTAKBggqhkjOPQQDAjASMRAwDgYDVQQKEwdBY21lIENvMB4XDTE3MTAyMDE5NDMwNloXDTE4MTAyMDE5NDMwNlowEjEQMA4GA1UEChMHQWNtZSBDbzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABD0d7VNhbWvZLWPuj/RtHFjvtJBEwOkhbN/BnnE8rnZR8+sbwnc/KhCk3FhnpHZnQz7B5aETbbIgmuvewdjvSBSjYzBhMA4GA1UdDwEB/wQEAwICpDATBgNVHSUEDDAKBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1UdEQQiMCCCDmxvY2FsaG9zdDo1NDUzgg4xMjcuMC4wLjE6NTQ1MzAKBggqhkjOPQQDAgNIADBFAiEA2zpJEPQyz6/lWf86aX6PepsntZv2GYlA5UpabfT2EZICICpJ5h/iI+i341gBmLiAFQOyTDT+/wQc6MF9+Yw1Yy0t-----END CERTIFICATE-----`)keyPem := []byte(`-----BEGIN EC PRIVATE KEY-----MHcCAQEEIIrYSSNQFaA2Hwf1duRSxKtLYX5CB04fSeQ6tF1aY/PuoAoGCCqGSM49AwEHoUQDQgAEPR3tU2Fta9ktY+6P9G0cWO+0kETA6SFs38GecTyudlHz6xvCdz8qEKTcWGekdmdDPsHloRNtsiCa697B2O9IFA==-----END EC PRIVATE KEY-----`)cert, err := tls.X509KeyPair(certPem, keyPem)if err != nil {log.Fatal(err)}cfg := &tls.Config{Certificates: []tls.Certificate{cert}}srv := &http.Server{TLSConfig:    cfg,ReadTimeout:  time.Minute,WriteTimeout: time.Minute,}log.Fatal(srv.ListenAndServeTLS("", ""))}

typeCertificateRequestInfoadded ingo1.8

type CertificateRequestInfo struct {// AcceptableCAs contains zero or more, DER-encoded, X.501// Distinguished Names. These are the names of root or intermediate CAs// that the server wishes the returned certificate to be signed by. An// empty slice indicates that the server has no preference.AcceptableCAs [][]byte// SignatureSchemes lists the signature schemes that the server is// willing to verify.SignatureSchemes []SignatureScheme// Version is the TLS version that was negotiated for this connection.Versionuint16// contains filtered or unexported fields}

CertificateRequestInfo contains information from a server'sCertificateRequest message, which is used to demand a certificate and proofof control from a client.

func (*CertificateRequestInfo)Contextadded ingo1.17

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.

func (*CertificateRequestInfo)SupportsCertificateadded ingo1.14

func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate)error

SupportsCertificate returns nil if the provided certificate is supported bythe server that sent the CertificateRequest. Otherwise, it returns an errordescribing the reason for the incompatibility.

typeCertificateVerificationErroradded ingo1.20

type CertificateVerificationError struct {// UnverifiedCertificates and its contents should not be modified.UnverifiedCertificates []*x509.CertificateErrerror}

CertificateVerificationError is returned when certificate verification fails during the handshake.

func (*CertificateVerificationError)Erroradded ingo1.20

func (*CertificateVerificationError)Unwrapadded ingo1.20

typeCipherSuiteadded ingo1.14

type CipherSuite struct {IDuint16Namestring// Supported versions is the list of TLS protocol versions that can// negotiate this cipher suite.SupportedVersions []uint16// Insecure is true if the cipher suite has known security issues// due to its primitives, design, or implementation.Insecurebool}

CipherSuite is a TLS cipher suite. Note that most functions in this packageaccept and expose cipher suite IDs instead of this type.

funcCipherSuitesadded ingo1.14

func CipherSuites() []*CipherSuite

CipherSuites returns a list of cipher suites currently implemented by thispackage, excluding those with security issues, which are returned byInsecureCipherSuites.

The list is sorted by ID. Note that the default cipher suites selected bythis package might depend on logic that can't be captured by a static list,and might not match those returned by this function.

funcInsecureCipherSuitesadded ingo1.14

func InsecureCipherSuites() []*CipherSuite

InsecureCipherSuites returns a list of cipher suites currently implemented bythis package and which have security issues.

Most applications should not use the cipher suites in this list, and shouldonly use those returned byCipherSuites.

typeClientAuthType

type ClientAuthTypeint

ClientAuthType declares the policy the server will follow forTLS Client Authentication.

const (// NoClientCert indicates that no client certificate should be requested// during the handshake, and if any certificates are sent they will not// be verified.NoClientCertClientAuthType =iota// RequestClientCert indicates that a client certificate should be requested// during the handshake, but does not require that the client send any// certificates.RequestClientCert// RequireAnyClientCert indicates that a client certificate should be requested// during the handshake, and that at least one certificate is required to be// sent by the client, but that certificate is not required to be valid.RequireAnyClientCert// VerifyClientCertIfGiven indicates that a client certificate should be requested// during the handshake, but does not require that the client sends a// certificate. If the client does send a certificate it is required to be// valid.VerifyClientCertIfGiven// RequireAndVerifyClientCert indicates that a client certificate should be requested// during the handshake, and that at least one valid certificate is required// to be sent by the client.RequireAndVerifyClientCert)

func (ClientAuthType)Stringadded ingo1.15

func (iClientAuthType) String()string

typeClientHelloInfoadded ingo1.4

type ClientHelloInfo struct {// CipherSuites lists the CipherSuites supported by the client (e.g.// TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).CipherSuites []uint16// ServerName indicates the name of the server requested by the client// in order to support virtual hosting. ServerName is only set if the// client is using SNI (seeRFC 4366, Section 3.1).ServerNamestring// SupportedCurves lists the key exchange mechanisms supported by the// client. It was renamed to "supported groups" in TLS 1.3, seeRFC 8446,// Section 4.2.7 and [CurveID].//// SupportedCurves may be nil in TLS 1.2 and lower if the Supported Elliptic// Curves Extension is not being used (seeRFC 4492, Section 5.1.1).SupportedCurves []CurveID// SupportedPoints lists the point formats supported by the client.// SupportedPoints is set only if the Supported Point Formats Extension// is being used (seeRFC 4492, Section 5.1.2).SupportedPoints []uint8// SignatureSchemes lists the signature and hash schemes that the client// is willing to verify. SignatureSchemes is set only if the Signature// Algorithms Extension is being used (seeRFC 5246, Section 7.4.1.4.1).SignatureSchemes []SignatureScheme// SupportedProtos lists the application protocols supported by the client.// SupportedProtos is set only if the Application-Layer Protocol// Negotiation Extension is being used (seeRFC 7301, Section 3.1).//// Servers can select a protocol by setting Config.NextProtos in a// GetConfigForClient return value.SupportedProtos []string// SupportedVersions lists the TLS versions supported by the client.// For TLS versions less than 1.3, this is extrapolated from the max// version advertised by the client, so values other than the greatest// might be rejected if used.SupportedVersions []uint16// Extensions lists the IDs of the extensions presented by the client// in the ClientHello.Extensions []uint16// Conn is the underlying net.Conn for the connection. Do not read// from, or write to, this connection; that will cause the TLS// connection to fail.Connnet.Conn// contains filtered or unexported fields}

ClientHelloInfo contains information from a ClientHello message in order toguide application logic in the GetCertificate and GetConfigForClient callbacks.

func (*ClientHelloInfo)Contextadded ingo1.17

func (c *ClientHelloInfo) Context()context.Context

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.

func (*ClientHelloInfo)SupportsCertificateadded ingo1.14

func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate)error

SupportsCertificate returns nil if the provided certificate is supported bythe client that sent the ClientHello. Otherwise, it returns an errordescribing the reason for the incompatibility.

If thisClientHelloInfo was passed to a GetConfigForClient or GetCertificatecallback, this method will take into account the associatedConfig. Note thatif GetConfigForClient returns a differentConfig, the change can't beaccounted for by this method.

This function will call x509.ParseCertificate unless c.Leaf is set, which canincur a significant performance cost.

typeClientSessionCacheadded ingo1.3

type ClientSessionCache interface {// Get searches for a ClientSessionState associated with the given key.// On return, ok is true if one was found.Get(sessionKeystring) (session *ClientSessionState, okbool)// Put adds the ClientSessionState to the cache with the given key. It might// get called multiple times in a connection if a TLS 1.3 server provides// more than one session ticket. If called with a nil *ClientSessionState,// it should remove the cache entry.Put(sessionKeystring, cs *ClientSessionState)}

ClientSessionCache is a cache of ClientSessionState objects that can be usedby a client to resume a TLS session with a given server. ClientSessionCacheimplementations should expect to be called concurrently from differentgoroutines. Up to TLS 1.2, only ticket-based resumption is supported, notSessionID-based resumption. In TLS 1.3 they were merged into PSK modes, whichare supported via this interface.

funcNewLRUClientSessionCacheadded ingo1.3

func NewLRUClientSessionCache(capacityint)ClientSessionCache

NewLRUClientSessionCache returns aClientSessionCache with the givencapacity that uses an LRU strategy. If capacity is < 1, a default capacityis used instead.

typeClientSessionStateadded ingo1.3

type ClientSessionState struct {// contains filtered or unexported fields}

ClientSessionState contains the state needed by a client toresume a previous TLS session.

funcNewResumptionStateadded ingo1.21.0

func NewResumptionState(ticket []byte, state *SessionState) (*ClientSessionState,error)

NewResumptionState returns a state value that can be returned by[ClientSessionCache.Get] to resume a previous session.

state needs to be returned byParseSessionState, and the ticket and sessionstate must have been returned byClientSessionState.ResumptionState.

func (*ClientSessionState)ResumptionStateadded ingo1.21.0

func (cs *ClientSessionState) ResumptionState() (ticket []byte, state *SessionState, errerror)

ResumptionState returns the session ticket sent by the server (also known asthe session's identity) and the state necessary to resume this session.

It can be called by [ClientSessionCache.Put] to serialize (withSessionState.Bytes) and store the session.

typeConfig

type Config struct {// Rand provides the source of entropy for nonces and RSA blinding.// If Rand is nil, TLS uses the cryptographic random reader in package// crypto/rand.// The Reader must be safe for use by multiple goroutines.Randio.Reader// Time returns the current time as the number of seconds since the epoch.// If Time is nil, TLS uses time.Now.Time func()time.Time// Certificates contains one or more certificate chains to present to the// other side of the connection. The first certificate compatible with the// peer's requirements is selected automatically.//// Server configurations must set one of Certificates, GetCertificate or// GetConfigForClient. Clients doing client-authentication may set either// Certificates or GetClientCertificate.//// Note: if there are multiple Certificates, and they don't have the// optional field Leaf set, certificate selection will incur a significant// per-handshake performance cost.Certificates []Certificate// NameToCertificate maps from a certificate name to an element of// Certificates. Note that a certificate name can be of the form// '*.example.com' and so doesn't have to be a domain name as such.//// Deprecated: NameToCertificate only allows associating a single// certificate with a given name. Leave this field nil to let the library// select the first compatible chain from Certificates.NameToCertificate map[string]*Certificate// GetCertificate returns a Certificate based on the given// ClientHelloInfo. It will only be called if the client supplies SNI// information or if Certificates is empty.//// If GetCertificate is nil or returns nil, then the certificate is// retrieved from NameToCertificate. If NameToCertificate is nil, the// best element of Certificates will be used.//// Once a Certificate is returned it should not be modified.GetCertificate func(*ClientHelloInfo) (*Certificate,error)// GetClientCertificate, if not nil, is called when a server requests a// certificate from a client. If set, the contents of Certificates will// be ignored.//// If GetClientCertificate returns an error, the handshake will be// aborted and that error will be returned. Otherwise// GetClientCertificate must return a non-nil Certificate. If// Certificate.Certificate is empty then no certificate will be sent to// the server. If this is unacceptable to the server then it may abort// the handshake.//// GetClientCertificate may be called multiple times for the same// connection if renegotiation occurs or if TLS 1.3 is in use.//// Once a Certificate is returned it should not be modified.GetClientCertificate func(*CertificateRequestInfo) (*Certificate,error)// GetConfigForClient, if not nil, is called after a ClientHello is// received from a client. It may return a non-nil Config in order to// change the Config that will be used to handle this connection. If// the returned Config is nil, the original Config will be used. The// Config returned by this callback may not be subsequently modified.//// If GetConfigForClient is nil, the Config passed to Server() will be// used for all connections.//// If SessionTicketKey was explicitly set on the returned Config, or if// SetSessionTicketKeys was called on the returned Config, those keys will// be used. Otherwise, the original Config keys will be used (and possibly// rotated if they are automatically managed).GetConfigForClient func(*ClientHelloInfo) (*Config,error)// VerifyPeerCertificate, if not nil, is called after normal// certificate verification by either a TLS client or server. It// receives the raw ASN.1 certificates provided by the peer and also// any verified chains that normal processing found. If it returns a// non-nil error, the handshake is aborted and that error results.//// If normal verification fails then the handshake will abort before// considering this callback. If normal verification is disabled (on the// client when InsecureSkipVerify is set, or on a server when ClientAuth is// RequestClientCert or RequireAnyClientCert), then this callback will be// considered but the verifiedChains argument will always be nil. When// ClientAuth is NoClientCert, this callback is not called on the server.// rawCerts may be empty on the server if ClientAuth is RequestClientCert or// VerifyClientCertIfGiven.//// This callback is not invoked on resumed connections, as certificates are// not re-verified on resumption.//// verifiedChains and its contents should not be modified.VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate)error// VerifyConnection, if not nil, is called after normal certificate// verification and after VerifyPeerCertificate by either a TLS client// or server. If it returns a non-nil error, the handshake is aborted// and that error results.//// If normal verification fails then the handshake will abort before// considering this callback. This callback will run for all connections,// including resumptions, regardless of InsecureSkipVerify or ClientAuth// settings.VerifyConnection func(ConnectionState)error// RootCAs defines the set of root certificate authorities// that clients use when verifying server certificates.// If RootCAs is nil, TLS uses the host's root CA set.RootCAs *x509.CertPool// NextProtos is a list of supported application level protocols, in// order of preference. If both peers support ALPN, the selected// protocol will be one from this list, and the connection will fail// if there is no mutually supported protocol. If NextProtos is empty// or the peer doesn't support ALPN, the connection will succeed and// ConnectionState.NegotiatedProtocol will be empty.NextProtos []string// ServerName is used to verify the hostname on the returned// certificates unless InsecureSkipVerify is given. It is also included// in the client's handshake to support virtual hosting unless it is// an IP address.ServerNamestring// ClientAuth determines the server's policy for// TLS Client Authentication. The default is NoClientCert.ClientAuthClientAuthType// ClientCAs defines the set of root certificate authorities// that servers use if required to verify a client certificate// by the policy in ClientAuth.ClientCAs *x509.CertPool// InsecureSkipVerify controls whether a client verifies the server's// certificate chain and host name. If InsecureSkipVerify is true, crypto/tls// accepts any certificate presented by the server and any host name in that// certificate. In this mode, TLS is susceptible to machine-in-the-middle// attacks unless custom verification is used. This should be used only for// testing or in combination with VerifyConnection or VerifyPeerCertificate.InsecureSkipVerifybool// CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of// the list is ignored. Note that TLS 1.3 ciphersuites are not configurable.//// If CipherSuites is nil, a safe default list is used. The default cipher// suites might change over time. In Go 1.22 RSA key exchange based cipher// suites were removed from the default list, but can be re-added with the// GODEBUG setting tlsrsakex=1. In Go 1.23 3DES cipher suites were removed// from the default list, but can be re-added with the GODEBUG setting// tls3des=1.CipherSuites []uint16// PreferServerCipherSuites is a legacy field and has no effect.//// It used to control whether the server would follow the client's or the// server's preference. Servers now select the best mutually supported// cipher suite based on logic that takes into account inferred client// hardware, server hardware, and security.//// Deprecated: PreferServerCipherSuites is ignored.PreferServerCipherSuitesbool// SessionTicketsDisabled may be set to true to disable session ticket and// PSK (resumption) support. Note that on clients, session ticket support is// also disabled if ClientSessionCache is nil.SessionTicketsDisabledbool// SessionTicketKey is used by TLS servers to provide session resumption.// SeeRFC 5077 and the PSK mode ofRFC 8446. If zero, it will be filled// with random data before the first server handshake.//// Deprecated: if this field is left at zero, session ticket keys will be// automatically rotated every day and dropped after seven days. For// customizing the rotation schedule or synchronizing servers that are// terminating connections for the same host, use SetSessionTicketKeys.SessionTicketKey [32]byte// ClientSessionCache is a cache of ClientSessionState entries for TLS// session resumption. It is only used by clients.ClientSessionCacheClientSessionCache// UnwrapSession is called on the server to turn a ticket/identity// previously produced by [WrapSession] into a usable session.//// UnwrapSession will usually either decrypt a session state in the ticket// (for example with [Config.EncryptTicket]), or use the ticket as a handle// to recover a previously stored state. It must use [ParseSessionState] to// deserialize the session state.//// If UnwrapSession returns an error, the connection is terminated. If it// returns (nil, nil), the session is ignored. crypto/tls may still choose// not to resume the returned session.UnwrapSession func(identity []byte, csConnectionState) (*SessionState,error)// WrapSession is called on the server to produce a session ticket/identity.//// WrapSession must serialize the session state with [SessionState.Bytes].// It may then encrypt the serialized state (for example with// [Config.DecryptTicket]) and use it as the ticket, or store the state and// return a handle for it.//// If WrapSession returns an error, the connection is terminated.//// Warning: the return value will be exposed on the wire and to clients in// plaintext. The application is in charge of encrypting and authenticating// it (and rotating keys) or returning high-entropy identifiers. Failing to// do so correctly can compromise current, previous, and future connections// depending on the protocol version.WrapSession func(ConnectionState, *SessionState) ([]byte,error)// MinVersion contains the minimum TLS version that is acceptable.//// By default, TLS 1.2 is currently used as the minimum. TLS 1.0 is the// minimum supported by this package.//// The server-side default can be reverted to TLS 1.0 by including the value// "tls10server=1" in the GODEBUG environment variable.MinVersionuint16// MaxVersion contains the maximum TLS version that is acceptable.//// By default, the maximum version supported by this package is used,// which is currently TLS 1.3.MaxVersionuint16// CurvePreferences contains a set of supported key exchange mechanisms.// The name refers to elliptic curves for legacy reasons, see [CurveID].// The order of the list is ignored, and key exchange mechanisms are chosen// from this list using an internal preference order. If empty, the default// will be used.//// From Go 1.24, the default includes the [X25519MLKEM768] hybrid// post-quantum key exchange. To disable it, set CurvePreferences explicitly// or use the GODEBUG=tlsmlkem=0 environment variable.CurvePreferences []CurveID// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.// When true, the largest possible TLS record size is always used. When// false, the size of TLS records may be adjusted in an attempt to// improve latency.DynamicRecordSizingDisabledbool// Renegotiation controls what types of renegotiation are supported.// The default, none, is correct for the vast majority of applications.RenegotiationRenegotiationSupport// KeyLogWriter optionally specifies a destination for TLS master secrets// in NSS key log format that can be used to allow external programs// such as Wireshark to decrypt TLS connections.// Seehttps://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.// Use of KeyLogWriter compromises security and should only be// used for debugging.KeyLogWriterio.Writer// EncryptedClientHelloConfigList is a serialized ECHConfigList. If// provided, clients will attempt to connect to servers using Encrypted// Client Hello (ECH) using one of the provided ECHConfigs.//// Servers do not use this field. In order to configure ECH for servers, see// the EncryptedClientHelloKeys field.//// If the list contains no valid ECH configs, the handshake will fail// and return an error.//// If EncryptedClientHelloConfigList is set, MinVersion, if set, must// be VersionTLS13.//// When EncryptedClientHelloConfigList is set, the handshake will only// succeed if ECH is successfully negotiated. If the server rejects ECH,// an ECHRejectionError error will be returned, which may contain a new// ECHConfigList that the server suggests using.//// How this field is parsed may change in future Go versions, if the// encoding described in the final Encrypted Client Hello RFC changes.EncryptedClientHelloConfigList []byte// EncryptedClientHelloRejectionVerify, if not nil, is called when ECH is// rejected by the remote server, in order to verify the ECH provider// certificate in the outer ClientHello. If it returns a non-nil error, the// handshake is aborted and that error results.//// On the server side this field is not used.//// Unlike VerifyPeerCertificate and VerifyConnection, normal certificate// verification will not be performed before calling// EncryptedClientHelloRejectionVerify.//// If EncryptedClientHelloRejectionVerify is nil and ECH is rejected, the// roots in RootCAs will be used to verify the ECH providers public// certificate. VerifyPeerCertificate and VerifyConnection are not called// when ECH is rejected, even if set, and InsecureSkipVerify is ignored.EncryptedClientHelloRejectionVerify func(ConnectionState)error// GetEncryptedClientHelloKeys, if not nil, is called when by a server when// a client attempts ECH.//// If GetEncryptedClientHelloKeys is not nil, [EncryptedClientHelloKeys] is// ignored.//// If GetEncryptedClientHelloKeys returns an error, the handshake will be// aborted and the error will be returned. Otherwise,// GetEncryptedClientHelloKeys must return a non-nil slice of// [EncryptedClientHelloKey] that represents the acceptable ECH keys.//// For further details, see [EncryptedClientHelloKeys].GetEncryptedClientHelloKeys func(*ClientHelloInfo) ([]EncryptedClientHelloKey,error)// EncryptedClientHelloKeys are the ECH keys to use when a client// attempts ECH.//// If EncryptedClientHelloKeys is set, MinVersion, if set, must be// VersionTLS13.//// If a client attempts ECH, but it is rejected by the server, the server// will send a list of configs to retry based on the set of// EncryptedClientHelloKeys which have the SendAsRetry field set.//// If GetEncryptedClientHelloKeys is non-nil, EncryptedClientHelloKeys is// ignored.//// On the client side, this field is ignored. In order to configure ECH for// clients, see the EncryptedClientHelloConfigList field.EncryptedClientHelloKeys []EncryptedClientHelloKey// contains filtered or unexported fields}

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

Example (KeyLogWriter)
package mainimport ("crypto/tls""log""net/http""net/http/httptest""os")// zeroSource is an io.Reader that returns an unlimited number of zero bytes.type zeroSource struct{}func (zeroSource) Read(b []byte) (n int, err error) {clear(b)return len(b), nil}func main() {// Debugging TLS applications by decrypting a network traffic capture.// WARNING: Use of KeyLogWriter compromises security and should only be// used for debugging.// Dummy test HTTP server for the example with insecure random so output is// reproducible.server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))server.TLS = &tls.Config{Rand: zeroSource{}, // for example only; don't do this.}server.StartTLS()defer server.Close()// Typically the log would go to an open file:// w, err := os.OpenFile("tls-secrets.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)w := os.Stdoutclient := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{KeyLogWriter: w,Rand:               zeroSource{}, // for reproducible output; don't do this.InsecureSkipVerify: true,         // test server certificate is not trusted.},},}resp, err := client.Get(server.URL)if err != nil {log.Fatalf("Failed to get URL: %v", err)}resp.Body.Close()// The resulting file can be used with Wireshark to decrypt the TLS// connection by setting (Pre)-Master-Secret log filename in SSL Protocol// preferences.}

Example (VerifyConnection)
package mainimport ("crypto/tls""crypto/x509")func main() {// VerifyConnection can be used to replace and customize connection// verification. This example shows a VerifyConnection implementation that// will be approximately equivalent to what crypto/tls does normally to// verify the peer's certificate.// Client side configuration._ = &tls.Config{// Set InsecureSkipVerify to skip the default validation we are// replacing. This will not disable VerifyConnection.InsecureSkipVerify: true,VerifyConnection: func(cs tls.ConnectionState) error {opts := x509.VerifyOptions{DNSName:       cs.ServerName,Intermediates: x509.NewCertPool(),}for _, cert := range cs.PeerCertificates[1:] {opts.Intermediates.AddCert(cert)}_, err := cs.PeerCertificates[0].Verify(opts)return err},}// Server side configuration._ = &tls.Config{// Require client certificates (or VerifyConnection will run anyway and// panic accessing cs.PeerCertificates[0]) but don't verify them with the// default verifier. This will not disable VerifyConnection.ClientAuth: tls.RequireAnyClientCert,VerifyConnection: func(cs tls.ConnectionState) error {opts := x509.VerifyOptions{DNSName:       cs.ServerName,Intermediates: x509.NewCertPool(),KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},}for _, cert := range cs.PeerCertificates[1:] {opts.Intermediates.AddCert(cert)}_, err := cs.PeerCertificates[0].Verify(opts)return err},}// Note that when certificates are not handled by the default verifier// ConnectionState.VerifiedChains will be nil.}

func (*Config)BuildNameToCertificatedeprecated

func (c *Config) BuildNameToCertificate()

BuildNameToCertificate parses c.Certificates and builds c.NameToCertificatefrom the CommonName and SubjectAlternateName fields of each of the leafcertificates.

Deprecated: NameToCertificate only allows associating a single certificatewith a given name. Leave that field nil to let the library select the firstcompatible chain from Certificates.

func (*Config)Cloneadded ingo1.8

func (c *Config) Clone() *Config

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

func (*Config)DecryptTicketadded ingo1.21.0

func (c *Config) DecryptTicket(identity []byte, csConnectionState) (*SessionState,error)

DecryptTicket decrypts a ticket encrypted byConfig.EncryptTicket. It canbe used as a [Config.UnwrapSession] implementation.

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

func (*Config)EncryptTicketadded ingo1.21.0

func (c *Config) EncryptTicket(csConnectionState, ss *SessionState) ([]byte,error)

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

func (*Config)SetSessionTicketKeysadded ingo1.5

func (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 beused for decrypting tickets. It is safe to call this function while theserver is running in order to rotate the session ticket keys. The functionwill 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 shouldall have the same session ticket keys. If the session ticket keys leaks,previously recorded and future TLS connections using those keys might becompromised.

typeConn

type Conn struct {// contains filtered or unexported fields}

A Conn represents a secured connection.It implements the net.Conn interface.

funcClient

func Client(connnet.Conn, config *Config) *Conn

Client returns a new TLS client side connectionusing conn as the underlying transport.The config cannot be nil: users must set either ServerName orInsecureSkipVerify in the config.

funcDial

func Dial(network, addrstring, config *Config) (*Conn,error)

Dial connects to the given network address using net.Dialand then initiates a TLS handshake, returning the resultingTLS connection.Dial interprets a nil configuration as equivalent tothe zero configuration; see the documentation of Configfor the defaults.

Example
package mainimport ("crypto/tls""crypto/x509")func main() {// Connecting with a custom root-certificate set.const rootPEM = `-- GlobalSign Root R2, valid until Dec 15, 2021-----BEGIN CERTIFICATE-----MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6ErPLv4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklqtTleiDTsvHgMCJiEbKjNS7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzdC9XZzPnqJworc5HGnRusyMvo4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pazq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCBmTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IHV2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9iYWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4GsJ0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRDLenVOavSot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG79G+dwfCMNYxdAfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg==-----END CERTIFICATE-----`// First, create the set of root certificates. For this example we only// have one. It's also possible to omit this in order to use the// default root set of the current operating system.roots := x509.NewCertPool()ok := roots.AppendCertsFromPEM([]byte(rootPEM))if !ok {panic("failed to parse root certificate")}conn, err := tls.Dial("tcp", "mail.google.com:443", &tls.Config{RootCAs: roots,})if err != nil {panic("failed to connect: " + err.Error())}conn.Close()}

funcDialWithDialeradded ingo1.3

func DialWithDialer(dialer *net.Dialer, network, addrstring, config *Config) (*Conn,error)

DialWithDialer connects to the given network address using dialer.Dial andthen initiates a TLS handshake, returning the resulting TLS connection. Anytimeout or deadline given in the dialer apply to connection and TLShandshake as a whole.

DialWithDialer interprets a nil configuration as equivalent to the zeroconfiguration; see the documentation ofConfig for the defaults.

DialWithDialer uses context.Background internally; to specify the context,useDialer.DialContext with NetDialer set to the desired dialer.

funcServer

func Server(connnet.Conn, config *Config) *Conn

Server returns a new TLS server side connectionusing conn as the underlying transport.The configuration config must be non-nil and must includeat least one certificate or else set GetCertificate.

func (*Conn)Close

func (c *Conn) Close()error

Close closes the connection.

func (*Conn)CloseWriteadded ingo1.8

func (c *Conn) CloseWrite()error

CloseWrite shuts down the writing side of the connection. It should only becalled once the handshake has completed and does not call CloseWrite on theunderlying connection. Most callers should just useConn.Close.

func (*Conn)ConnectionState

func (c *Conn) ConnectionState()ConnectionState

ConnectionState returns basic TLS details about the connection.

func (*Conn)Handshake

func (c *Conn) Handshake()error

Handshake runs the client or server handshakeprotocol if it has not yet been run.

Most uses of this package need not call Handshake explicitly: thefirstConn.Read orConn.Write will call it automatically.

For control over canceling or setting a timeout on a handshake, useConn.HandshakeContext or theDialer's DialContext method instead.

In order to avoid denial of service attacks, the maximum RSA key size allowedin certificates sent by either the TLS server or client is limited to 8192bits. This limit can be overridden by setting tlsmaxrsasize in the GODEBUGenvironment variable (e.g. GODEBUG=tlsmaxrsasize=4096).

func (*Conn)HandshakeContextadded ingo1.17

func (c *Conn) HandshakeContext(ctxcontext.Context)error

HandshakeContext runs the client or server handshakeprotocol if it has not yet been run.

The provided Context must be non-nil. If the context is canceled beforethe handshake is complete, the handshake is interrupted and an error is returned.Once the handshake has completed, cancellation of the context will not affect theconnection.

Most uses of this package need not call HandshakeContext explicitly: thefirstConn.Read orConn.Write will call it automatically.

func (*Conn)LocalAddr

func (c *Conn) LocalAddr()net.Addr

LocalAddr returns the local network address.

func (*Conn)NetConnadded ingo1.18

func (c *Conn) NetConn()net.Conn

NetConn returns the underlying connection that is wrapped by c.Note that writing to or reading from this connection directly will corrupt theTLS session.

func (*Conn)OCSPResponse

func (c *Conn) OCSPResponse() []byte

OCSPResponse returns the stapled OCSP response from the TLS server, ifany. (Only valid for client connections.)

func (*Conn)Read

func (c *Conn) Read(b []byte) (int,error)

Read reads data from the connection.

As Read callsConn.Handshake, in order to prevent indefinite blocking a deadlinemust be set for both Read andConn.Write before Read is called when the handshakehas not yet completed. SeeConn.SetDeadline,Conn.SetReadDeadline, andConn.SetWriteDeadline.

func (*Conn)RemoteAddr

func (c *Conn) RemoteAddr()net.Addr

RemoteAddr returns the remote network address.

func (*Conn)SetDeadline

func (c *Conn) SetDeadline(ttime.Time)error

SetDeadline sets the read and write deadlines associated with the connection.A zero value for t meansConn.Read andConn.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.

func (*Conn)SetReadDeadline

func (c *Conn) SetReadDeadline(ttime.Time)error

SetReadDeadline sets the read deadline on the underlying connection.A zero value for t meansConn.Read will not time out.

func (*Conn)SetWriteDeadline

func (c *Conn) SetWriteDeadline(ttime.Time)error

SetWriteDeadline sets the write deadline on the underlying connection.A zero value for t meansConn.Write will not time out.After aConn.Write has timed out, the TLS state is corrupt and all future writes will return the same error.

func (*Conn)VerifyHostname

func (c *Conn) VerifyHostname(hoststring)error

VerifyHostname checks that the peer certificate chain is valid forconnecting to host. If so, it returns nil; if not, it returns an errordescribing the problem.

func (*Conn)Write

func (c *Conn) Write(b []byte) (int,error)

Write writes data to the connection.

As Write callsConn.Handshake, in order to prevent indefinite blocking a deadlinemust be set for bothConn.Read and Write before Write is called when the handshakehas not yet completed. SeeConn.SetDeadline,Conn.SetReadDeadline, andConn.SetWriteDeadline.

typeConnectionState

type ConnectionState struct {// Version is the TLS version used by the connection (e.g. VersionTLS12).Versionuint16// HandshakeComplete is true if the handshake has concluded.HandshakeCompletebool// DidResume is true if this connection was successfully resumed from a// previous session with a session ticket or similar mechanism.DidResumebool// CipherSuite is the cipher suite negotiated for the connection (e.g.// TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256).CipherSuiteuint16// CurveID is the key exchange mechanism used for the connection. The name// refers to elliptic curves for legacy reasons, see [CurveID]. If a legacy// RSA key exchange is used, this value is zero.CurveIDCurveID// NegotiatedProtocol is the application protocol negotiated with ALPN.NegotiatedProtocolstring// NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation.//// Deprecated: this value is always true.NegotiatedProtocolIsMutualbool// ServerName is the value of the Server Name Indication extension sent by// the client. It's available both on the server and on the client side.ServerNamestring// PeerCertificates are the parsed certificates sent by the peer, in the// order in which they were sent. The first element is the leaf certificate// that the connection is verified against.//// On the client side, it can't be empty. On the server side, it can be// empty if Config.ClientAuth is not RequireAnyClientCert or// RequireAndVerifyClientCert.//// PeerCertificates and its contents should not be modified.PeerCertificates []*x509.Certificate// VerifiedChains is a list of one or more chains where the first element is// PeerCertificates[0] and the last element is from Config.RootCAs (on the// client side) or Config.ClientCAs (on the server side).//// On the client side, it's set if Config.InsecureSkipVerify is false. On// the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven// (and the peer provided a certificate) or RequireAndVerifyClientCert.//// VerifiedChains and its contents should not be modified.VerifiedChains [][]*x509.Certificate// SignedCertificateTimestamps is a list of SCTs provided by the peer// through the TLS handshake for the leaf certificate, if any.SignedCertificateTimestamps [][]byte// OCSPResponse is a stapled Online Certificate Status Protocol (OCSP)// response provided by the peer for the leaf certificate, if any.OCSPResponse []byte// TLSUnique contains the "tls-unique" channel binding value (seeRFC 5929,// Section 3). This value will be nil for TLS 1.3 connections and for// resumed connections that don't support Extended Master Secret (RFC 7627).TLSUnique []byte// ECHAccepted indicates if Encrypted Client Hello was offered by the client// and accepted by the server. Currently, ECH is supported only on the// client side.ECHAcceptedbool// contains filtered or unexported fields}

ConnectionState records basic TLS details about the connection.

func (*ConnectionState)ExportKeyingMaterialadded ingo1.11

func (cs *ConnectionState) ExportKeyingMaterial(labelstring, context []byte, lengthint) ([]byte,error)

ExportKeyingMaterial returns length bytes of exported key material in a newslice as defined inRFC 5705. If context is nil, it is not used as part ofthe seed. If the connection was set to allow renegotiation viaConfig.Renegotiation, or if the connections supports neither TLS 1.3 norExtended Master Secret, this function will return an error.

Exporting key material without Extended Master Secret or TLS 1.3 was disabledin Go 1.22 due to security issues (see the Security Considerations sectionsofRFC 5705 andRFC 7627), but can be re-enabled with the GODEBUG settingtlsunsafeekm=1.

typeCurveIDadded ingo1.3

type CurveIDuint16

CurveID is the type of a TLS identifier for a key exchange mechanism. Seehttps://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. SeeRFC 8446, Section4.2.7. It was then also extended to other mechanisms, such as hybridpost-quantum KEMs.

const (CurveP256CurveID = 23CurveP384CurveID = 24CurveP521CurveID = 25X25519CurveID = 29X25519MLKEM768CurveID = 4588)

func (CurveID)Stringadded ingo1.15

func (iCurveID) String()string

typeDialeradded ingo1.15

type Dialer struct {// NetDialer is the optional dialer to use for the TLS connections'// underlying TCP connections.// A nil NetDialer is equivalent to the net.Dialer zero value.NetDialer *net.Dialer// Config is the TLS configuration to use for new connections.// A nil configuration is equivalent to the zero// configuration; see the documentation of Config for the// defaults.Config *Config}

Dialer dials TLS connections given a configuration and a Dialer for theunderlying connection.

func (*Dialer)Dialadded ingo1.15

func (d *Dialer) Dial(network, addrstring) (net.Conn,error)

Dial connects to the given network address and initiates a TLShandshake, returning the resulting TLS connection.

The returnedConn, if any, will always be of type *Conn.

Dial uses context.Background internally; to specify the context,useDialer.DialContext.

func (*Dialer)DialContextadded ingo1.15

func (d *Dialer) DialContext(ctxcontext.Context, network, addrstring) (net.Conn,error)

DialContext connects to the given network address and initiates a TLShandshake, returning the resulting TLS connection.

The provided Context must be non-nil. If the context expires beforethe connection is complete, an error is returned. Once successfullyconnected, any expiration of the context will not affect theconnection.

The returnedConn, if any, will always be of type *Conn.

typeECHRejectionErroradded ingo1.23.0

type ECHRejectionError struct {RetryConfigList []byte}

ECHRejectionError is the error type returned when ECH is rejected by a remoteserver. If the server offered a ECHConfigList to use for retries, theRetryConfigList field will contain this list.

The client may treat an ECHRejectionError with an empty set of RetryConfigsas a secure signal from the server.

func (*ECHRejectionError)Erroradded ingo1.23.0

func (e *ECHRejectionError) Error()string

typeEncryptedClientHelloKeyadded ingo1.24.0

type EncryptedClientHelloKey struct {// Config should be a marshalled ECHConfig associated with PrivateKey. This// must match the config provided to clients byte-for-byte. The config// should only specify the DHKEM(X25519, HKDF-SHA256) KEM ID (0x0020), the// HKDF-SHA256 KDF ID (0x0001), and a subset of the following AEAD IDs:// AES-128-GCM (0x0001), AES-256-GCM (0x0002), ChaCha20Poly1305 (0x0003).Config []byte// PrivateKey should be a marshalled private key. Currently, we expect// this to be the output of [ecdh.PrivateKey.Bytes].PrivateKey []byte// SendAsRetry indicates if Config should be sent as part of the list of// retry configs when ECH is requested by the client but rejected by the// server.SendAsRetrybool}

EncryptedClientHelloKey holds a private key that is associatedwith a specific ECH config known to a client.

typeQUICConfigadded ingo1.21.0

type QUICConfig struct {TLSConfig *Config// EnableSessionEvents may be set to true to enable the// [QUICStoreSession] and [QUICResumeSession] events for client connections.// When this event is enabled, sessions are not automatically// stored in the client session cache.// The application should use [QUICConn.StoreSession] to store sessions.EnableSessionEventsbool}

A QUICConfig configures aQUICConn.

typeQUICConnadded ingo1.21.0

type QUICConn struct {// contains filtered or unexported fields}

A QUICConn represents a connection which uses a QUIC implementation as the underlyingtransport as described inRFC 9001.

Methods of QUICConn are not safe for concurrent use.

funcQUICClientadded ingo1.21.0

func QUICClient(config *QUICConfig) *QUICConn

QUICClient returns a new TLS client side connection using QUICTransport as theunderlying transport. The config cannot be nil.

The config's MinVersion must be at least TLS 1.3.

funcQUICServeradded ingo1.21.0

func QUICServer(config *QUICConfig) *QUICConn

QUICServer returns a new TLS server side connection using QUICTransport as theunderlying transport. The config cannot be nil.

The config's MinVersion must be at least TLS 1.3.

func (*QUICConn)Closeadded ingo1.21.0

func (q *QUICConn) Close()error

Close closes the connection and stops any in-progress handshake.

func (*QUICConn)ConnectionStateadded ingo1.21.0

func (q *QUICConn) ConnectionState()ConnectionState

ConnectionState returns basic TLS details about the connection.

func (*QUICConn)HandleDataadded ingo1.21.0

func (q *QUICConn) HandleData(levelQUICEncryptionLevel, data []byte)error

HandleData handles handshake bytes received from the peer.It may produce connection events, which may be read withQUICConn.NextEvent.

func (*QUICConn)NextEventadded ingo1.21.0

func (q *QUICConn) NextEvent()QUICEvent

NextEvent returns the next event occurring on the connection.It returns an event with a Kind ofQUICNoEvent when no events are available.

func (*QUICConn)SendSessionTicketadded ingo1.21.0

func (q *QUICConn) SendSessionTicket(optsQUICSessionTicketOptions)error

SendSessionTicket sends a session ticket to the client.It produces connection events, which may be read withQUICConn.NextEvent.Currently, it can only be called once.

func (*QUICConn)SetTransportParametersadded ingo1.21.0

func (q *QUICConn) SetTransportParameters(params []byte)

SetTransportParameters sets the transport parameters to send to the peer.

Server connections may delay setting the transport parameters until afterreceiving the client's transport parameters. SeeQUICTransportParametersRequired.

func (*QUICConn)Startadded ingo1.21.0

func (q *QUICConn) Start(ctxcontext.Context)error

Start starts the client or server handshake protocol.It may produce connection events, which may be read withQUICConn.NextEvent.

Start must be called at most once.

func (*QUICConn)StoreSessionadded ingo1.23.0

func (q *QUICConn) StoreSession(session *SessionState)error

StoreSession stores a session previously received in a QUICStoreSession eventin the ClientSessionCache.The application may process additional events or modify the SessionStatebefore storing the session.

typeQUICEncryptionLeveladded ingo1.21.0

type QUICEncryptionLevelint

QUICEncryptionLevel represents a QUIC encryption level used to transmithandshake messages.

func (QUICEncryptionLevel)Stringadded ingo1.21.0

func (lQUICEncryptionLevel) String()string

typeQUICEventadded ingo1.21.0

type QUICEvent struct {KindQUICEventKind// Set for QUICSetReadSecret, QUICSetWriteSecret, and QUICWriteData.LevelQUICEncryptionLevel// Set for QUICTransportParameters, QUICSetReadSecret, QUICSetWriteSecret, and QUICWriteData.// The contents are owned by crypto/tls, and are valid until the next NextEvent call.Data []byte// Set for QUICSetReadSecret and QUICSetWriteSecret.Suiteuint16// Set for QUICResumeSession and QUICStoreSession.SessionState *SessionState}

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.

typeQUICEventKindadded ingo1.21.0

type QUICEventKindint

A QUICEventKind is a type of operation on a QUIC connection.

const (// QUICNoEvent indicates that there are no events available.QUICNoEventQUICEventKind =iota// QUICSetReadSecret and QUICSetWriteSecret provide the read and write// secrets for a given encryption level.// QUICEvent.Level, QUICEvent.Data, and QUICEvent.Suite are set.//// Secrets for the Initial encryption level are derived from the initial// destination connection ID, and are not provided by the QUICConn.QUICSetReadSecretQUICSetWriteSecret// QUICWriteData provides data to send to the peer in CRYPTO frames.// QUICEvent.Data is set.QUICWriteData// QUICTransportParameters provides the peer's QUIC transport parameters.// QUICEvent.Data is set.QUICTransportParameters// QUICTransportParametersRequired indicates that the caller must provide// QUIC transport parameters to send to the peer. The caller should set// the transport parameters with QUICConn.SetTransportParameters and call// QUICConn.NextEvent again.//// If transport parameters are set before calling QUICConn.Start, the// connection will never generate a QUICTransportParametersRequired event.QUICTransportParametersRequired// QUICRejectedEarlyData indicates that the server rejected 0-RTT data even// if we offered it. It's returned before QUICEncryptionLevelApplication// keys are returned.// This event only occurs on client connections.QUICRejectedEarlyData// QUICHandshakeDone indicates that the TLS handshake has completed.QUICHandshakeDone// QUICResumeSession indicates that a client is attempting to resume a previous session.// [QUICEvent.SessionState] is set.//// For client connections, this event occurs when the session ticket is selected.// For server connections, this event occurs when receiving the client's session ticket.//// The application may set [QUICEvent.SessionState.EarlyData] to false before the// next call to [QUICConn.NextEvent] to decline 0-RTT even if the session supports it.QUICResumeSession// QUICStoreSession indicates that the server has provided state permitting// the client to resume the session.// [QUICEvent.SessionState] is set.// The application should use [QUICConn.StoreSession] session to store the [SessionState].// The application may modify the [SessionState] before storing it.// This event only occurs on client connections.QUICStoreSession)

typeQUICSessionTicketOptionsadded ingo1.21.0

type QUICSessionTicketOptions struct {// EarlyData specifies whether the ticket may be used for 0-RTT.EarlyDataboolExtra     [][]byte}

typeRecordHeaderErroradded ingo1.6

type RecordHeaderError struct {// Msg contains a human readable string that describes the error.Msgstring// RecordHeader contains the five bytes of TLS record header that// triggered the error.RecordHeader [5]byte// Conn provides the underlying net.Conn in the case that a client// sent an initial handshake that didn't look like TLS.// It is nil if there's already been a handshake or a TLS alert has// been written to the connection.Connnet.Conn}

RecordHeaderError is returned when a TLS record header is invalid.

func (RecordHeaderError)Erroradded ingo1.6

func (eRecordHeaderError) Error()string

typeRenegotiationSupportadded ingo1.7

type RenegotiationSupportint

RenegotiationSupport enumerates the different levels of support for TLSrenegotiation. TLS renegotiation is the act of performing subsequenthandshakes on a connection after the first. This significantly complicatesthe state machine and has been the source of numerous, subtle securityissues. Initiating a renegotiation is not supported, but support foraccepting 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, concurrenthandshake and application data flow is not permitted so renegotiation canonly be used with protocols that synchronise with the renegotiation, such asHTTPS.

Renegotiation is not defined in TLS 1.3.

const (// RenegotiateNever disables renegotiation.RenegotiateNeverRenegotiationSupport =iota// RenegotiateOnceAsClient allows a remote server to request// renegotiation once per connection.RenegotiateOnceAsClient// RenegotiateFreelyAsClient allows a remote server to repeatedly// request renegotiation.RenegotiateFreelyAsClient)

typeSessionStateadded ingo1.21.0

type SessionState struct {// Extra is ignored by crypto/tls, but is encoded by [SessionState.Bytes]// and parsed by [ParseSessionState].//// This allows [Config.UnwrapSession]/[Config.WrapSession] and// [ClientSessionCache] implementations to store and retrieve additional// data alongside this session.//// To allow different layers in a protocol stack to share this field,// applications must only append to it, not replace it, and must use entries// that can be recognized even if out of order (for example, by starting// with an id and version prefix).Extra [][]byte// EarlyData indicates whether the ticket can be used for 0-RTT in a QUIC// connection. The application may set this to false if it is true to// decline to offer 0-RTT even if supported.EarlyDatabool// contains filtered or unexported fields}

A SessionState is a resumable session.

funcParseSessionStateadded ingo1.21.0

func ParseSessionState(data []byte) (*SessionState,error)

ParseSessionState parses aSessionState encoded bySessionState.Bytes.

func (*SessionState)Bytesadded ingo1.21.0

func (s *SessionState) Bytes() ([]byte,error)

Bytes encodes the session, including any private fields, so that it can beparsed byParseSessionState. The encoding contains secret values criticalto the security of future and possibly past sessions.

The specific encoding should be considered opaque and may change incompatiblybetween Go versions.

typeSignatureSchemeadded ingo1.8

type SignatureSchemeuint16

SignatureScheme identifies a signature algorithm supported by TLS. SeeRFC 8446, Section 4.2.3.

const (// RSASSA-PKCS1-v1_5 algorithms.PKCS1WithSHA256SignatureScheme = 0x0401PKCS1WithSHA384SignatureScheme = 0x0501PKCS1WithSHA512SignatureScheme = 0x0601// RSASSA-PSS algorithms with public key OID rsaEncryption.PSSWithSHA256SignatureScheme = 0x0804PSSWithSHA384SignatureScheme = 0x0805PSSWithSHA512SignatureScheme = 0x0806// ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.ECDSAWithP256AndSHA256SignatureScheme = 0x0403ECDSAWithP384AndSHA384SignatureScheme = 0x0503ECDSAWithP521AndSHA512SignatureScheme = 0x0603// EdDSA algorithms.Ed25519SignatureScheme = 0x0807// Legacy signature and hash algorithms for TLS 1.2.PKCS1WithSHA1SignatureScheme = 0x0201ECDSAWithSHA1SignatureScheme = 0x0203)

func (SignatureScheme)Stringadded ingo1.15

func (iSignatureScheme) String()string

Notes

Bugs

Source Files

View all Source files

Directories

PathSynopsis
internal
fips140tls
Package fips140tls controls whether crypto/tls requires FIPS-approved settings.
Package fips140tls controls whether crypto/tls requires FIPS-approved settings.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp