version: 1.10

package tls

import "crypto/tls"

Overview

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

Index

Examples

Package files

alert.go cipher_suites.go common.go conn.go handshake_client.go handshake_messages.go handshake_server.go key_agreement.go prf.go ticket.go tls.go

Constants

  1. const (
  2. TLS_RSA_WITH_RC4_128_SHA uint16 = 0x0005
  3. TLS_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x000a
  4. TLS_RSA_WITH_AES_128_CBC_SHA uint16 = 0x002f
  5. TLS_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0035
  6. TLS_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003c
  7. TLS_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009c
  8. TLS_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009d
  9. TLS_ECDHE_ECDSA_WITH_RC4_128_SHA uint16 = 0xc007
  10. TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xc009
  11. TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xc00a
  12. TLS_ECDHE_RSA_WITH_RC4_128_SHA uint16 = 0xc011
  13. TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xc012
  14. TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0xc013
  15. TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0xc014
  16. TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xc023
  17. TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xc027
  18. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02f
  19. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02b
  20. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xc030
  21. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xc02c
  22. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305 uint16 = 0xcca8
  23. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 uint16 = 0xcca9
  24.  
  25. // TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator
  26. // that the client is doing version fallback. See
  27. // https://tools.ietf.org/html/rfc7507.
  28. TLS_FALLBACK_SCSV uint16 = 0x5600
  29. )

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

Taken from http://www.iana.org/assignments/tls-parameters/tls-parameters.xml

  1. const (
  2. VersionSSL30 = 0x0300
  3. VersionTLS10 = 0x0301
  4. VersionTLS11 = 0x0302
  5. VersionTLS12 = 0x0303
  6. )

func Listen

  1. func Listen(network, laddr string, config Config) (net.Listener, error)
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.

func NewListener

  1. func NewListener(inner net.Listener, config Config) net.Listener
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.

type Certificate

  1. type Certificate struct {
  2. Certificate [][]byte
  3. // PrivateKey contains the private key corresponding to the public key
  4. // in Leaf. For a server, this must implement crypto.Signer and/or
  5. // crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
  6. // (performing client authentication), this must be a crypto.Signer
  7. // with an RSA or ECDSA PublicKey.
  8. PrivateKey crypto.PrivateKey
  9. // OCSPStaple contains an optional OCSP response which will be served
  10. // to clients that request it.
  11. OCSPStaple []byte
  12. // SignedCertificateTimestamps contains an optional list of Signed
  13. // Certificate Timestamps which will be served to clients that request it.
  14. SignedCertificateTimestamps [][]byte
  15. // Leaf is the parsed form of the leaf certificate, which may be
  16. // initialized using x509.ParseCertificate to reduce per-handshake
  17. // processing for TLS clients doing client authentication. If nil, the
  18. // leaf certificate will be parsed as needed.
  19. Leaf x509.Certificate
  20. }
A Certificate is a chain of one or more certificates, leaf first.

func LoadX509KeyPair

  1. func LoadX509KeyPair(certFile, keyFile string) (Certificate, error)
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 nil because the parsed form of the certificate is not retained.

func X509KeyPair

  1. func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error)
X509KeyPair parses a public/private key pair from a pair of PEM encoded data. On successful return, Certificate.Leaf will be nil because the parsed form of the certificate is not retained.

type CertificateRequestInfo

  1. type CertificateRequestInfo struct {
  2. // AcceptableCAs contains zero or more, DER-encoded, X.501
  3. // Distinguished Names. These are the names of root or intermediate CAs
  4. // that the server wishes the returned certificate to be signed by. An
  5. // empty slice indicates that the server has no preference.
  6. AcceptableCAs [][]byte
  7.  
  8. // SignatureSchemes lists the signature schemes that the server is
  9. // willing to verify.
  10. SignatureSchemes []SignatureScheme
  11. }
CertificateRequestInfo contains information from a server’s CertificateRequest message, which is used to demand a certificate and proof of control from a client.

type ClientAuthType

  1. type ClientAuthType int
ClientAuthType declares the policy the server will follow for TLS Client Authentication.
  1. const (
  2. NoClientCert ClientAuthType = iota
  3. RequestClientCert
  4. RequireAnyClientCert
  5. VerifyClientCertIfGiven
  6. RequireAndVerifyClientCert
  7. )

type ClientHelloInfo

  1. type ClientHelloInfo struct {
  2. // CipherSuites lists the CipherSuites supported by the client (e.g.
  3. // TLS_RSA_WITH_RC4_128_SHA).
  4. CipherSuites []uint16
  5.  
  6. // ServerName indicates the name of the server requested by the client
  7. // in order to support virtual hosting. ServerName is only set if the
  8. // client is using SNI (see
  9. // http://tools.ietf.org/html/rfc4366#section-3.1).
  10. ServerName string
  11.  
  12. // SupportedCurves lists the elliptic curves supported by the client.
  13. // SupportedCurves is set only if the Supported Elliptic Curves
  14. // Extension is being used (see
  15. // http://tools.ietf.org/html/rfc4492#section-5.1.1).
  16. SupportedCurves []CurveID
  17.  
  18. // SupportedPoints lists the point formats supported by the client.
  19. // SupportedPoints is set only if the Supported Point Formats Extension
  20. // is being used (see
  21. // http://tools.ietf.org/html/rfc4492#section-5.1.2).
  22. SupportedPoints []uint8
  23.  
  24. // SignatureSchemes lists the signature and hash schemes that the client
  25. // is willing to verify. SignatureSchemes is set only if the Signature
  26. // Algorithms Extension is being used (see
  27. // https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1).
  28. SignatureSchemes []SignatureScheme
  29.  
  30. // SupportedProtos lists the application protocols supported by the client.
  31. // SupportedProtos is set only if the Application-Layer Protocol
  32. // Negotiation Extension is being used (see
  33. // https://tools.ietf.org/html/rfc7301#section-3.1).
  34. //
  35. // Servers can select a protocol by setting Config.NextProtos in a
  36. // GetConfigForClient return value.
  37. SupportedProtos []string
  38.  
  39. // SupportedVersions lists the TLS versions supported by the client.
  40. // For TLS versions less than 1.3, this is extrapolated from the max
  41. // version advertised by the client, so values other than the greatest
  42. // might be rejected if used.
  43. SupportedVersions []uint16
  44.  
  45. // Conn is the underlying net.Conn for the connection. Do not read
  46. // from, or write to, this connection; that will cause the TLS
  47. // connection to fail.
  48. Conn net.Conn
  49. }
ClientHelloInfo contains information from a ClientHello message in order to guide certificate selection in the GetCertificate callback.

type ClientSessionCache

  1. type 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.
  7. Put(sessionKey string, cs ClientSessionState)
  8. }
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. Only ticket-based resumption is supported, not SessionID-based resumption.

func NewLRUClientSessionCache

  1. func NewLRUClientSessionCache(capacity int) ClientSessionCache
NewLRUClientSessionCache returns a ClientSessionCache with the given capacity that uses an LRU strategy. If capacity is < 1, a default capacity is used instead.

type ClientSessionState

  1. type ClientSessionState struct {
  2. // contains filtered or unexported fields
  3. }
ClientSessionState contains the state needed by clients to resume TLS sessions.

type Config

  1. type 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. // Time returns the current time as the number of seconds since the epoch.
  8. // If Time is nil, TLS uses time.Now.
  9. Time func() time.Time
  10. // Certificates contains one or more certificate chains to present to
  11. // the other side of the connection. Server configurations must include
  12. // at least one certificate or else set GetCertificate. Clients doing
  13. // client-authentication may set either Certificates or
  14. // GetClientCertificate.
  15. Certificates []Certificate
  16. // NameToCertificate maps from a certificate name to an element of
  17. // Certificates. Note that a certificate name can be of the form
  18. // '.example.com' and so doesn't have to be a domain name as such.
  19. // See Config.BuildNameToCertificate
  20. // The nil value causes the first element of Certificates to be used
  21. // for all connections.
  22. NameToCertificate map[string]Certificate
  23. // GetCertificate returns a Certificate based on the given
  24. // ClientHelloInfo. It will only be called if the client supplies SNI
  25. // information or if Certificates is empty.
  26. //
  27. // If GetCertificate is nil or returns nil, then the certificate is
  28. // retrieved from NameToCertificate. If NameToCertificate is nil, the
  29. // first element of Certificates will be used.
  30. GetCertificate func(ClientHelloInfo) (Certificate, error)
  31. // GetClientCertificate, if not nil, is called when a server requests a
  32. // certificate from a client. If set, the contents of Certificates will
  33. // be ignored.
  34. //
  35. // If GetClientCertificate returns an error, the handshake will be
  36. // aborted and that error will be returned. Otherwise
  37. // GetClientCertificate must return a non-nil Certificate. If
  38. // Certificate.Certificate is empty then no certificate will be sent to
  39. // the server. If this is unacceptable to the server then it may abort
  40. // the handshake.
  41. //
  42. // GetClientCertificate may be called multiple times for the same
  43. // connection if renegotiation occurs or if TLS 1.3 is in use.
  44. GetClientCertificate func(CertificateRequestInfo) (Certificate, error)
  45. // GetConfigForClient, if not nil, is called after a ClientHello is
  46. // received from a client. It may return a non-nil Config in order to
  47. // change the Config that will be used to handle this connection. If
  48. // the returned Config is nil, the original Config will be used. The
  49. // Config returned by this callback may not be subsequently modified.
  50. //
  51. // If GetConfigForClient is nil, the Config passed to Server() will be
  52. // used for all connections.
  53. //
  54. // Uniquely for the fields in the returned Config, session ticket keys
  55. // will be duplicated from the original Config if not set.
  56. // Specifically, if SetSessionTicketKeys was called on the original
  57. // config but not on the returned config then the ticket keys from the
  58. // original config will be copied into the new config before use.
  59. // Otherwise, if SessionTicketKey was set in the original config but
  60. // not in the returned config then it will be copied into the returned
  61. // config before use. If neither of those cases applies then the key
  62. // material from the returned config will be used for session tickets.
  63. GetConfigForClient func(ClientHelloInfo) (Config, error)
  64. // VerifyPeerCertificate, if not nil, is called after normal
  65. // certificate verification by either a TLS client or server. It
  66. // receives the raw ASN.1 certificates provided by the peer and also
  67. // any verified chains that normal processing found. If it returns a
  68. // non-nil error, the handshake is aborted and that error results.
  69. //
  70. // If normal verification fails then the handshake will abort before
  71. // considering this callback. If normal verification is disabled by
  72. // setting InsecureSkipVerify, or (for a server) when ClientAuth is
  73. // RequestClientCert or RequireAnyClientCert, then this callback will
  74. // be considered but the verifiedChains argument will always be nil.
  75. VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]x509.Certificate) error
  76.  
  77. // RootCAs defines the set of root certificate authorities
  78. // that clients use when verifying server certificates.
  79. // If RootCAs is nil, TLS uses the host's root CA set.
  80. RootCAs x509.CertPool
  81. // NextProtos is a list of supported, application level protocols.
  82. NextProtos []string
  83. // ServerName is used to verify the hostname on the returned
  84. // certificates unless InsecureSkipVerify is given. It is also included
  85. // in the client's handshake to support virtual hosting unless it is
  86. // an IP address.
  87. ServerName string
  88. // ClientAuth determines the server's policy for
  89. // TLS Client Authentication. The default is NoClientCert.
  90. ClientAuth ClientAuthType
  91. // ClientCAs defines the set of root certificate authorities
  92. // that servers use if required to verify a client certificate
  93. // by the policy in ClientAuth.
  94. ClientCAs x509.CertPool
  95.  
  96. // InsecureSkipVerify controls whether a client verifies the
  97. // server's certificate chain and host name.
  98. // If InsecureSkipVerify is true, TLS accepts any certificate
  99. // presented by the server and any host name in that certificate.
  100. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  101. // This should be used only for testing.
  102. InsecureSkipVerify bool
  103.  
  104. // CipherSuites is a list of supported cipher suites. If CipherSuites
  105. // is nil, TLS uses a list of suites supported by the implementation.
  106. CipherSuites []uint16
  107.  
  108. // PreferServerCipherSuites controls whether the server selects the
  109. // client's most preferred ciphersuite, or the server's most preferred
  110. // ciphersuite. If true then the server's preference, as expressed in
  111. // the order of elements in CipherSuites, is used.
  112. PreferServerCipherSuites bool
  113.  
  114. // SessionTicketsDisabled may be set to true to disable session ticket
  115. // (resumption) support.
  116. SessionTicketsDisabled bool
  117.  
  118. // SessionTicketKey is used by TLS servers to provide session
  119. // resumption. See RFC 5077. If zero, it will be filled with
  120. // random data before the first server handshake.
  121. //
  122. // If multiple servers are terminating connections for the same host
  123. // they should all have the same SessionTicketKey. If the
  124. // SessionTicketKey leaks, previously recorded and future TLS
  125. // connections using that key are compromised.
  126. SessionTicketKey [32]byte
  127.  
  128. // ClientSessionCache is a cache of ClientSessionState entries for TLS
  129. // session resumption.
  130. ClientSessionCache ClientSessionCache
  131.  
  132. // MinVersion contains the minimum SSL/TLS version that is acceptable.
  133. // If zero, then TLS 1.0 is taken as the minimum.
  134. MinVersion uint16
  135.  
  136. // MaxVersion contains the maximum SSL/TLS version that is acceptable.
  137. // If zero, then the maximum version supported by this package is used,
  138. // which is currently TLS 1.2.
  139. MaxVersion uint16
  140.  
  141. // CurvePreferences contains the elliptic curves that will be used in
  142. // an ECDHE handshake, in preference order. If empty, the default will
  143. // be used.
  144. CurvePreferences []CurveID
  145.  
  146. // DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
  147. // When true, the largest possible TLS record size is always used. When
  148. // false, the size of TLS records may be adjusted in an attempt to
  149. // improve latency.
  150. DynamicRecordSizingDisabled bool
  151.  
  152. // Renegotiation controls what types of renegotiation are supported.
  153. // The default, none, is correct for the vast majority of applications.
  154. Renegotiation RenegotiationSupport
  155.  
  156. // KeyLogWriter optionally specifies a destination for TLS master secrets
  157. // in NSS key log format that can be used to allow external programs
  158. // such as Wireshark to decrypt TLS connections.
  159. // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
  160. // Use of KeyLogWriter compromises security and should only be
  161. // used for debugging.
  162. KeyLogWriter io.Writer
  163. // contains filtered or unexported fields
  164. }
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: // 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.Stdout client := &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. // Output: // CLIENT_RANDOM 0000000000000000000000000000000000000000000000000000000000000000 baca0df460a688e44ce018b025183cc2353ae01f89755ef766eedd3ecc302888ee3b3a22962e45f48c20df15a98c0e80

func (Config) BuildNameToCertificate

  1. func (c Config) BuildNameToCertificate()
BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate from the CommonName and SubjectAlternateName fields of each of the leaf certificates.

func (Config) Clone

  1. func (c Config) Clone() Config
Clone returns a shallow clone of c. It is safe to clone a Config that is being used concurrently by a TLS client or server.

func (Config) SetSessionTicketKeys

  1. 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 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.

type Conn

  1. type Conn struct {
  2. // contains filtered or unexported fields
  3. }
A Conn represents a secured connection. It implements the net.Conn interface.

func Client

  1. func Client(conn net.Conn, config Config) Conn
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.

func Dial

  1. func Dial(network, addr string, config Config) (Conn, error)
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: // Connecting with a custom root-certificate set. const rootPEM = -----BEGIN CERTIFICATE----- MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7 qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYD VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2g K4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYI KwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5n ZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY /iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/ zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6 yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx -----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()

func DialWithDialer

  1. func DialWithDialer(dialer net.Dialer, network, addr string, config Config) (Conn, error)
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.

func Server

  1. func Server(conn net.Conn, config Config) Conn
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.

func (Conn) Close

  1. func (c Conn) Close() error
Close closes the connection.

func (Conn) CloseWrite

  1. func (c Conn) CloseWrite() error
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 Close.

func (Conn) ConnectionState

  1. func (c Conn) ConnectionState() ConnectionState
ConnectionState returns basic TLS details about the connection.

func (Conn) Handshake

  1. func (c Conn) Handshake() error
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 Read or Write will call it automatically.

func (Conn) LocalAddr

  1. func (c Conn) LocalAddr() net.Addr
LocalAddr returns the local network address.

func (Conn) OCSPResponse

  1. func (c Conn) OCSPResponse() []byte
OCSPResponse returns the stapled OCSP response from the TLS server, if any. (Only valid for client connections.)

func (Conn) Read

  1. func (c Conn) Read(b []byte) (n int, err error)
Read can be made to time out and return a net.Error with Timeout() == true after a fixed time limit; see SetDeadline and SetReadDeadline.

func (Conn) RemoteAddr

  1. func (c Conn) RemoteAddr() net.Addr
RemoteAddr returns the remote network address.

func (Conn) SetDeadline

  1. func (c Conn) SetDeadline(t time.Time) error
SetDeadline sets the read and write deadlines associated with the connection. A zero value for t means Read and 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

  1. func (c Conn) SetReadDeadline(t time.Time) error
SetReadDeadline sets the read deadline on the underlying connection. A zero value for t means Read will not time out.

func (Conn) SetWriteDeadline

  1. func (c Conn) SetWriteDeadline(t time.Time) error
SetWriteDeadline sets the write deadline on the underlying connection. A zero value for t means 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) VerifyHostname

  1. func (c Conn) VerifyHostname(host string) 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.

func (Conn) Write

  1. func (c Conn) Write(b []byte) (int, error)
Write writes data to the connection.

type ConnectionState

  1. type ConnectionState struct {
  2. Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
  3. HandshakeComplete bool // TLS handshake is complete
  4. DidResume bool // connection resumes a previous TLS connection
  5. CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, …)
  6. NegotiatedProtocol string // negotiated next protocol (not guaranteed to be from Config.NextProtos)
  7. NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server (client side only)
  8. ServerName string // server name requested by client, if any (server side only)
  9. PeerCertificates []x509.Certificate // certificate chain presented by remote peer
  10. VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
  11. SignedCertificateTimestamps [][]byte // SCTs from the server, if any
  12. OCSPResponse []byte // stapled OCSP response from server, if any
  13.  
  14. // TLSUnique contains the "tls-unique" channel binding value (see RFC
  15. // 5929, section 3). For resumed sessions this value will be nil
  16. // because resumption does not include enough context (see
  17. // https://mitls.org/pages/attacks/3SHAKE#channelbindings). This will
  18. // change in future versions of Go once the TLS master-secret fix has
  19. // been standardized and implemented.
  20. TLSUnique []byte
  21. }
ConnectionState records basic TLS details about the connection.

type CurveID

  1. type CurveID uint16
CurveID is the type of a TLS identifier for an elliptic curve. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
  1. const (
  2. CurveP256 CurveID = 23
  3. CurveP384 CurveID = 24
  4. CurveP521 CurveID = 25
  5. X25519 CurveID = 29
  6. )

type RecordHeaderError

  1. type RecordHeaderError struct {
  2. // Msg contains a human readable string that describes the error.
  3. Msg string
  4. // RecordHeader contains the five bytes of TLS record header that
  5. // triggered the error.
  6. RecordHeader [5]byte
  7. }
RecordHeaderError results when a TLS record header is invalid.

func (RecordHeaderError) Error

  1. func (e RecordHeaderError) Error() string

type RenegotiationSupport

  1. type RenegotiationSupport int
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.
  1. const (
  2. // RenegotiateNever disables renegotiation.
  3. RenegotiateNever RenegotiationSupport = iota
  4.  
  5. // RenegotiateOnceAsClient allows a remote server to request
  6. // renegotiation once per connection.
  7. RenegotiateOnceAsClient
  8.  
  9. // RenegotiateFreelyAsClient allows a remote server to repeatedly
  10. // request renegotiation.
  11. RenegotiateFreelyAsClient
  12. )

type SignatureScheme

  1. type SignatureScheme uint16
SignatureScheme identifies a signature algorithm supported by TLS. See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.3.
  1. const (
  2. PKCS1WithSHA1 SignatureScheme = 0x0201
  3. PKCS1WithSHA256 SignatureScheme = 0x0401
  4. PKCS1WithSHA384 SignatureScheme = 0x0501
  5. PKCS1WithSHA512 SignatureScheme = 0x0601
  6.  
  7. PSSWithSHA256 SignatureScheme = 0x0804
  8. PSSWithSHA384 SignatureScheme = 0x0805
  9. PSSWithSHA512 SignatureScheme = 0x0806
  10.  
  11. ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
  12. ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
  13. ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
  14.  
  15. // Legacy signature and hash algorithms for TLS 1.2.
  16. ECDSAWithSHA1 SignatureScheme = 0x0203
  17. )

Bugs