tls

Imports

Imports #

"strconv"
"internal/godebug"
"slices"
_ "unsafe"
"bytes"
"context"
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/internal/fips140/mlkem"
"crypto/internal/fips140/tls13"
"crypto/internal/hpke"
"crypto/rsa"
"crypto/subtle"
"crypto/tls/internal/fips140tls"
"crypto/x509"
"errors"
"fmt"
"hash"
"internal/byteorder"
"internal/godebug"
"io"
"net"
"slices"
"strconv"
"strings"
"time"
"bytes"
"context"
"crypto"
"crypto/hmac"
"crypto/internal/fips140/hkdf"
"crypto/internal/fips140/mlkem"
"crypto/internal/fips140/tls13"
"crypto/internal/hpke"
"crypto/rsa"
"crypto/tls/internal/fips140tls"
"errors"
"hash"
"internal/byteorder"
"io"
"slices"
"sort"
"time"
"crypto"
"crypto/ecdh"
"crypto/md5"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"errors"
"fmt"
"io"
"strconv"
"crypto/x509"
"runtime"
"sync"
"sync/atomic"
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/des"
"crypto/hmac"
"crypto/internal/boring"
fipsaes "crypto/internal/fips140/aes"
"crypto/internal/fips140/aes/gcm"
"crypto/rc4"
"crypto/sha1"
"crypto/sha256"
"fmt"
"hash"
"internal/cpu"
"runtime"
_ "unsafe"
"golang.org/x/crypto/chacha20poly1305"
"errors"
"fmt"
"slices"
"strings"
"golang.org/x/crypto/cryptobyte"
"crypto/ecdh"
"crypto/hmac"
"crypto/internal/fips140/mlkem"
"crypto/internal/fips140/tls13"
"errors"
"hash"
"io"
"crypto"
"crypto/hmac"
"crypto/internal/fips140/tls12"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"errors"
"fmt"
"hash"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"crypto/x509"
"errors"
"io"
"golang.org/x/crypto/cryptobyte"
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rsa"
"crypto/tls/internal/fips140tls"
"errors"
"fmt"
"hash"
"io"
"bytes"
"container/list"
"context"
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/sha512"
"crypto/tls/internal/fips140tls"
"crypto/x509"
"errors"
"fmt"
"internal/godebug"
"io"
"net"
"slices"
"strings"
"sync"
"time"
_ "unsafe"
"bytes"
"crypto/internal/hpke"
"errors"
"fmt"
"slices"
"strings"
"golang.org/x/crypto/cryptobyte"
"bytes"
"context"
"crypto"
"crypto/hmac"
"crypto/internal/fips140/hkdf"
"crypto/internal/fips140/mlkem"
"crypto/internal/fips140/tls13"
"crypto/rsa"
"crypto/subtle"
"errors"
"hash"
"slices"
"time"
"context"
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/subtle"
"crypto/tls/internal/fips140tls"
"crypto/x509"
"errors"
"fmt"
"hash"
"internal/byteorder"
"io"
"time"
"context"
"errors"
"fmt"
"bytes"
"context"
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"internal/godebug"
"net"
"os"
"strings"
"bytes"
"context"
"crypto/cipher"
"crypto/subtle"
"crypto/x509"
"errors"
"fmt"
"hash"
"internal/godebug"
"io"
"net"
"sync"
"sync/atomic"
"time"

Constants & Variables

CurveP256 const #

const CurveP256 CurveID = 23

CurveP384 const #

const CurveP384 CurveID = 24

CurveP521 const #

const CurveP521 CurveID = 25

ECDSAWithP256AndSHA256 const #

ECDSA algorithms. Only constrained to a specific curve in TLS 1.3.

const ECDSAWithP256AndSHA256 SignatureScheme = 0x0403

ECDSAWithP384AndSHA384 const #

const ECDSAWithP384AndSHA384 SignatureScheme = 0x0503

ECDSAWithP521AndSHA512 const #

const ECDSAWithP521AndSHA512 SignatureScheme = 0x0603

ECDSAWithSHA1 const #

const ECDSAWithSHA1 SignatureScheme = 0x0203

Ed25519 const #

EdDSA algorithms.

const Ed25519 SignatureScheme = 0x0807

NoClientCert const #

NoClientCert indicates that no client certificate should be requested during the handshake, and if any certificates are sent they will not be verified.

const NoClientCert ClientAuthType = iota

PKCS1WithSHA1 const #

Legacy signature and hash algorithms for TLS 1.2.

const PKCS1WithSHA1 SignatureScheme = 0x0201

PKCS1WithSHA256 const #

RSASSA-PKCS1-v1_5 algorithms.

const PKCS1WithSHA256 SignatureScheme = 0x0401

PKCS1WithSHA384 const #

const PKCS1WithSHA384 SignatureScheme = 0x0501

PKCS1WithSHA512 const #

const PKCS1WithSHA512 SignatureScheme = 0x0601

PSSWithSHA256 const #

RSASSA-PSS algorithms with public key OID rsaEncryption.

const PSSWithSHA256 SignatureScheme = 0x0804

PSSWithSHA384 const #

const PSSWithSHA384 SignatureScheme = 0x0805

PSSWithSHA512 const #

const PSSWithSHA512 SignatureScheme = 0x0806

QUICEncryptionLevelApplication const #

const QUICEncryptionLevelApplication

QUICEncryptionLevelEarly const #

const QUICEncryptionLevelEarly

QUICEncryptionLevelHandshake const #

const QUICEncryptionLevelHandshake

QUICEncryptionLevelInitial const #

const QUICEncryptionLevelInitial = *ast.CallExpr

QUICHandshakeDone const #

QUICHandshakeDone indicates that the TLS handshake has completed.

const QUICHandshakeDone

QUICNoEvent const #

QUICNoEvent indicates that there are no events available.

const QUICNoEvent QUICEventKind = iota

QUICRejectedEarlyData const #

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.

const QUICRejectedEarlyData

QUICResumeSession const #

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.

const QUICResumeSession

QUICSetReadSecret const #

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.

const QUICSetReadSecret

QUICSetWriteSecret const #

const QUICSetWriteSecret

QUICStoreSession const #

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.

const QUICStoreSession

QUICTransportParameters const #

QUICTransportParameters provides the peer's QUIC transport parameters. QUICEvent.Data is set.

const QUICTransportParameters

QUICTransportParametersRequired const #

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.

const QUICTransportParametersRequired

QUICWriteData const #

QUICWriteData provides data to send to the peer in CRYPTO frames. QUICEvent.Data is set.

const QUICWriteData

RenegotiateFreelyAsClient const #

RenegotiateFreelyAsClient allows a remote server to repeatedly request renegotiation.

const RenegotiateFreelyAsClient

RenegotiateNever const #

RenegotiateNever disables renegotiation.

const RenegotiateNever RenegotiationSupport = iota

RenegotiateOnceAsClient const #

RenegotiateOnceAsClient allows a remote server to request renegotiation once per connection.

const RenegotiateOnceAsClient

RequestClientCert const #

RequestClientCert indicates that a client certificate should be requested during the handshake, but does not require that the client send any certificates.

const RequestClientCert

RequireAndVerifyClientCert const #

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.

const RequireAndVerifyClientCert

RequireAnyClientCert const #

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.

const RequireAnyClientCert

TLS_AES_128_GCM_SHA256 const #

TLS 1.3 cipher suites.

const TLS_AES_128_GCM_SHA256 uint16 = 0x1301

TLS_AES_256_GCM_SHA384 const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_AES_256_GCM_SHA384 uint16 = 0x1302

TLS_CHACHA20_POLY1305_SHA256 const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_CHACHA20_POLY1305_SHA256 uint16 = 0x1303

TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xc009

TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xc023

TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02b

TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xc00a

TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xc02c

TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 = TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256

TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcca9

TLS_ECDHE_ECDSA_WITH_RC4_128_SHA const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_ECDHE_ECDSA_WITH_RC4_128_SHA uint16 = 0xc007

TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xc012

TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0xc013

TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xc027

TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02f

TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0xc014

TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xc030

TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305 const #

Legacy names for the corresponding cipher suites with the correct _SHA256 suffix, retained for backward compatibility.

const TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305 = TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256

TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcca8

TLS_ECDHE_RSA_WITH_RC4_128_SHA const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_ECDHE_RSA_WITH_RC4_128_SHA uint16 = 0xc011

TLS_FALLBACK_SCSV const #

TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator that the client is doing version fallback. See RFC 7507.

const TLS_FALLBACK_SCSV uint16 = 0x5600

TLS_RSA_WITH_3DES_EDE_CBC_SHA const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x000a

TLS_RSA_WITH_AES_128_CBC_SHA const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_RSA_WITH_AES_128_CBC_SHA uint16 = 0x002f

TLS_RSA_WITH_AES_128_CBC_SHA256 const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003c

TLS_RSA_WITH_AES_128_GCM_SHA256 const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009c

TLS_RSA_WITH_AES_256_CBC_SHA const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0035

TLS_RSA_WITH_AES_256_GCM_SHA384 const #

A list of cipher suite IDs that are, or have been, implemented by this package. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

const TLS_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009d

TLS_RSA_WITH_RC4_128_SHA const #

TLS 1.0 - 1.2 cipher suites.

const TLS_RSA_WITH_RC4_128_SHA uint16 = 0x0005

VerifyClientCertIfGiven const #

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.

const VerifyClientCertIfGiven

VersionSSL30 const #

Deprecated: SSLv3 is cryptographically broken, and is no longer supported by this package. See golang.org/issue/32716.

const VersionSSL30 = 0x0300

VersionTLS10 const #

const VersionTLS10 = 0x0301

VersionTLS11 const #

const VersionTLS11 = 0x0302

VersionTLS12 const #

const VersionTLS12 = 0x0303

VersionTLS13 const #

const VersionTLS13 = 0x0304

X25519 const #

const X25519 CurveID = 29

X25519MLKEM768 const #

const X25519MLKEM768 CurveID = 4588

_ClientAuthType_index var #

var _ClientAuthType_index = [...]uint8{...}

_ClientAuthType_name const #

const _ClientAuthType_name = "NoClientCertRequestClientCertRequireAnyClientCertVerifyClientCertIfGivenRequireAndVerifyClientCert"

_CurveID_index_0 var #

var _CurveID_index_0 = [...]uint8{...}

_CurveID_name_0 const #

const _CurveID_name_0 = "CurveP256CurveP384CurveP521"

_CurveID_name_1 const #

const _CurveID_name_1 = "X25519"

_CurveID_name_2 const #

const _CurveID_name_2 = "X25519MLKEM768"

_SignatureScheme_index_8 var #

var _SignatureScheme_index_8 = [...]uint8{...}

_SignatureScheme_name_0 const #

const _SignatureScheme_name_0 = "PKCS1WithSHA1"

_SignatureScheme_name_1 const #

const _SignatureScheme_name_1 = "ECDSAWithSHA1"

_SignatureScheme_name_2 const #

const _SignatureScheme_name_2 = "PKCS1WithSHA256"

_SignatureScheme_name_3 const #

const _SignatureScheme_name_3 = "ECDSAWithP256AndSHA256"

_SignatureScheme_name_4 const #

const _SignatureScheme_name_4 = "PKCS1WithSHA384"

_SignatureScheme_name_5 const #

const _SignatureScheme_name_5 = "ECDSAWithP384AndSHA384"

_SignatureScheme_name_6 const #

const _SignatureScheme_name_6 = "PKCS1WithSHA512"

_SignatureScheme_name_7 const #

const _SignatureScheme_name_7 = "ECDSAWithP521AndSHA512"

_SignatureScheme_name_8 const #

const _SignatureScheme_name_8 = "PSSWithSHA256PSSWithSHA384PSSWithSHA512Ed25519"

aeadNonceLength const #

const aeadNonceLength = 12

aesgcmCiphers var #

var aesgcmCiphers = map[uint16]bool{...}

alertAccessDenied const #

const alertAccessDenied alert = 49

alertBadCertificate const #

const alertBadCertificate alert = 42

alertBadCertificateHashValue const #

const alertBadCertificateHashValue alert = 114

alertBadCertificateStatusResponse const #

const alertBadCertificateStatusResponse alert = 113

alertBadRecordMAC const #

const alertBadRecordMAC alert = 20

alertCertificateExpired const #

const alertCertificateExpired alert = 45

alertCertificateRequired const #

const alertCertificateRequired alert = 116

alertCertificateRevoked const #

const alertCertificateRevoked alert = 44

alertCertificateUnknown const #

const alertCertificateUnknown alert = 46

alertCertificateUnobtainable const #

const alertCertificateUnobtainable alert = 111

alertCloseNotify const #

const alertCloseNotify alert = 0

alertDecodeError const #

const alertDecodeError alert = 50

alertDecompressionFailure const #

const alertDecompressionFailure alert = 30

alertDecryptError const #

const alertDecryptError alert = 51

alertDecryptionFailed const #

const alertDecryptionFailed alert = 21

alertECHRequired const #

const alertECHRequired alert = 121

alertExportRestriction const #

const alertExportRestriction alert = 60

alertHandshakeFailure const #

const alertHandshakeFailure alert = 40

alertIllegalParameter const #

const alertIllegalParameter alert = 47

alertInappropriateFallback const #

const alertInappropriateFallback alert = 86

alertInsufficientSecurity const #

const alertInsufficientSecurity alert = 71

alertInternalError const #

const alertInternalError alert = 80

alertLevelError const #

const alertLevelError = 2

alertLevelWarning const #

alert level

const alertLevelWarning = 1

alertMissingExtension const #

const alertMissingExtension alert = 109

alertNoApplicationProtocol const #

const alertNoApplicationProtocol alert = 120

alertNoRenegotiation const #

const alertNoRenegotiation alert = 100

alertProtocolVersion const #

const alertProtocolVersion alert = 70

alertRecordOverflow const #

const alertRecordOverflow alert = 22

alertText var #

var alertText = map[alert]string{...}

alertUnexpectedMessage const #

const alertUnexpectedMessage alert = 10

alertUnknownCA const #

const alertUnknownCA alert = 48

alertUnknownPSKIdentity const #

const alertUnknownPSKIdentity alert = 115

alertUnrecognizedName const #

const alertUnrecognizedName alert = 112

alertUnsupportedCertificate const #

const alertUnsupportedCertificate alert = 43

alertUnsupportedExtension const #

const alertUnsupportedExtension alert = 110

alertUserCanceled const #

const alertUserCanceled alert = 90

certTypeECDSASign const #

Certificate types (for certificateRequestMsg)

const certTypeECDSASign = 64

certTypeRSASign const #

Certificate types (for certificateRequestMsg)

const certTypeRSASign = 1

cipherSuites var #

var cipherSuites = []*cipherSuite{...}

cipherSuitesPreferenceOrder var #

cipherSuitesPreferenceOrder is the order in which we'll select (on the server) or advertise (on the client) TLS 1.0–1.2 cipher suites. Cipher suites are filtered but not reordered based on the application and peer's preferences, meaning we'll never select a suite lower in this list if any higher one is available. This makes it more defensible to keep weaker cipher suites enabled, especially on the server side where we get the last word, since there are no known downgrade attacks on cipher suites selection. The list is sorted by applying the following priority rules, stopping at the first (most important) applicable one: - Anything else comes before RC4 RC4 has practically exploitable biases. See https://www.rc4nomore.com. - Anything else comes before CBC_SHA256 SHA-256 variants of the CBC ciphersuites don't implement any Lucky13 countermeasures. See https://www.isg.rhul.ac.uk/tls/Lucky13.html and https://www.imperialviolet.org/2013/02/04/luckythirteen.html. - Anything else comes before 3DES 3DES has 64-bit blocks, which makes it fundamentally susceptible to birthday attacks. See https://sweet32.info. - ECDHE comes before anything else Once we got the broken stuff out of the way, the most important property a cipher suite can have is forward secrecy. We don't implement FFDHE, so that means ECDHE. - AEADs come before CBC ciphers Even with Lucky13 countermeasures, MAC-then-Encrypt CBC cipher suites are fundamentally fragile, and suffered from an endless sequence of padding oracle attacks. See https://eprint.iacr.org/2015/1129, https://www.imperialviolet.org/2014/12/08/poodleagain.html, and https://blog.cloudflare.com/yet-another-padding-oracle-in-openssl-cbc-ciphersuites/. - AES comes before ChaCha20 When AES hardware is available, AES-128-GCM and AES-256-GCM are faster than ChaCha20Poly1305. When AES hardware is not available, AES-128-GCM is one or more of: much slower, way more complex, and less safe (because not constant time) than ChaCha20Poly1305. We use this list if we think both peers have AES hardware, and cipherSuitesPreferenceOrderNoAES otherwise. - AES-128 comes before AES-256 The only potential advantages of AES-256 are better multi-target margins, and hypothetical post-quantum properties. Neither apply to TLS, and AES-256 is slower due to its four extra rounds (which don't contribute to the advantages above). - ECDSA comes before RSA The relative order of ECDSA and RSA cipher suites doesn't matter, as they depend on the certificate. Pick one to get a stable order.

var cipherSuitesPreferenceOrder = []uint16{...}

cipherSuitesPreferenceOrderNoAES var #

var cipherSuitesPreferenceOrderNoAES = []uint16{...}

cipherSuitesTLS13 var #

cipherSuitesTLS13 should be an internal detail, but widely used packages access it using linkname. Notable members of the hall of shame include: - github.com/quic-go/quic-go - github.com/sagernet/quic-go Do not remove or change the type signature. See go.dev/issue/67401. go:linkname cipherSuitesTLS13

var cipherSuitesTLS13 = []*cipherSuiteTLS13{...}

clientFinishedLabel const #

const clientFinishedLabel = "client finished"

clientSignatureContext const #

const clientSignatureContext = "TLS 1.3, client CertificateVerify\x00"

compressionNone const #

TLS compression types.

const compressionNone uint8 = 0

defaultCipherSuitesFIPS var #

defaultCipherSuitesFIPS are the FIPS-allowed cipher suites.

var defaultCipherSuitesFIPS = []uint16{...}

defaultCipherSuitesTLS13 var #

defaultCipherSuitesTLS13 is also the preference order, since there are no disabled by default TLS 1.3 cipher suites. The same AES vs ChaCha20 logic as cipherSuitesPreferenceOrder applies. defaultCipherSuitesTLS13 should be an internal detail, but widely used packages access it using linkname. Notable members of the hall of shame include: - github.com/quic-go/quic-go - github.com/sagernet/quic-go Do not remove or change the type signature. See go.dev/issue/67401. go:linkname defaultCipherSuitesTLS13

var defaultCipherSuitesTLS13 = []uint16{...}

defaultCipherSuitesTLS13FIPS var #

defaultCipherSuitesTLS13FIPS are the FIPS-allowed cipher suites for TLS 1.3.

var defaultCipherSuitesTLS13FIPS = []uint16{...}

defaultCipherSuitesTLS13NoAES var #

defaultCipherSuitesTLS13NoAES should be an internal detail, but widely used packages access it using linkname. Notable members of the hall of shame include: - github.com/quic-go/quic-go - github.com/sagernet/quic-go Do not remove or change the type signature. See go.dev/issue/67401. go:linkname defaultCipherSuitesTLS13NoAES

var defaultCipherSuitesTLS13NoAES = []uint16{...}

defaultCurvePreferencesFIPS var #

defaultCurvePreferencesFIPS are the FIPS-allowed curves, in preference order (most preferable first).

var defaultCurvePreferencesFIPS = []CurveID{...}

defaultMaxRSAKeySize const #

defaultMaxRSAKeySize is the maximum RSA key size in bits that we are willing to verify the signatures of during a TLS handshake.

const defaultMaxRSAKeySize = 8192

defaultSupportedSignatureAlgorithms var #

defaultSupportedSignatureAlgorithms contains the signature and hash algorithms that the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+ CertificateRequest. The two fields are merged to match with TLS 1.3. Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc.

var defaultSupportedSignatureAlgorithms = []SignatureScheme{...}

defaultSupportedSignatureAlgorithmsFIPS var #

defaultSupportedSignatureAlgorithmsFIPS currently are a subset of defaultSupportedSignatureAlgorithms without Ed25519 and SHA-1.

var defaultSupportedSignatureAlgorithmsFIPS = []SignatureScheme{...}

defaultSupportedVersionsFIPS var #

var defaultSupportedVersionsFIPS = []uint16{...}

deprecatedSessionTicketKey var #

deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was randomized for backwards compatibility but is not in use.

var deprecatedSessionTicketKey = *ast.CallExpr

directSigning var #

directSigning is a standard Hash value that signals that no pre-hashing should be performed, and that the input should be signed directly. It is the hash function associated with the Ed25519 signature scheme.

var directSigning crypto.Hash = 0

disabledCipherSuites var #

disabledCipherSuites are not used unless explicitly listed in Config.CipherSuites.

var disabledCipherSuites = map[uint16]bool{...}

downgradeCanaryTLS11 const #

const downgradeCanaryTLS11 = "DOWNGRD\x00"

downgradeCanaryTLS12 const #

downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server random as a downgrade protection if the server would be capable of negotiating a higher version. See RFC 8446, Section 4.1.3.

const downgradeCanaryTLS12 = "DOWNGRD\x01"

emptyConfig var #

var emptyConfig Config

errClientKeyExchange var #

var errClientKeyExchange = *ast.CallExpr

errEarlyCloseWrite var #

var errEarlyCloseWrite = *ast.CallExpr

errInvalidECHExt var #

var errInvalidECHExt = *ast.CallExpr

errMalformedECHConfig var #

var errMalformedECHConfig = *ast.CallExpr

errMalformedECHExt var #

var errMalformedECHExt = *ast.CallExpr

errNoCertificates var #

errNoCertificates should be an internal detail, but widely used packages access it using linkname. Notable members of the hall of shame include: - github.com/xtls/xray-core Do not remove or change the type signature. See go.dev/issue/67401. go:linkname errNoCertificates

var errNoCertificates = *ast.CallExpr

errServerKeyExchange var #

var errServerKeyExchange = *ast.CallExpr

errShutdown var #

var errShutdown = *ast.CallExpr

extendedMasterSecretLabel const #

const extendedMasterSecretLabel = "extended master secret"

extensionALPN const #

TLS extension numbers

const extensionALPN uint16 = 16

extensionCertificateAuthorities const #

TLS extension numbers

const extensionCertificateAuthorities uint16 = 47

extensionCookie const #

TLS extension numbers

const extensionCookie uint16 = 44

extensionECHOuterExtensions const #

TLS extension numbers

const extensionECHOuterExtensions uint16 = 0xfd00

extensionEarlyData const #

TLS extension numbers

const extensionEarlyData uint16 = 42

extensionEncryptedClientHello const #

TLS extension numbers

const extensionEncryptedClientHello uint16 = 0xfe0d

extensionExtendedMasterSecret const #

TLS extension numbers

const extensionExtendedMasterSecret uint16 = 23

extensionKeyShare const #

TLS extension numbers

const extensionKeyShare uint16 = 51

extensionPSKModes const #

TLS extension numbers

const extensionPSKModes uint16 = 45

extensionPreSharedKey const #

TLS extension numbers

const extensionPreSharedKey uint16 = 41

extensionQUICTransportParameters const #

TLS extension numbers

const extensionQUICTransportParameters uint16 = 57

extensionRenegotiationInfo const #

TLS extension numbers

const extensionRenegotiationInfo uint16 = 0xff01

extensionSCT const #

TLS extension numbers

const extensionSCT uint16 = 18

extensionServerName const #

TLS extension numbers

const extensionServerName uint16 = 0

extensionSessionTicket const #

TLS extension numbers

const extensionSessionTicket uint16 = 35

extensionSignatureAlgorithms const #

TLS extension numbers

const extensionSignatureAlgorithms uint16 = 13

extensionSignatureAlgorithmsCert const #

TLS extension numbers

const extensionSignatureAlgorithmsCert uint16 = 50

extensionStatusRequest const #

TLS extension numbers

const extensionStatusRequest uint16 = 5

extensionSupportedCurves const #

TLS extension numbers

const extensionSupportedCurves uint16 = 10

extensionSupportedPoints const #

TLS extension numbers

const extensionSupportedPoints uint16 = 11

extensionSupportedVersions const #

TLS extension numbers

const extensionSupportedVersions uint16 = 43

finishedVerifyLength const #

const finishedVerifyLength = 12

globalCertCache var #

var globalCertCache = *ast.CallExpr

hasAESGCMHardwareSupport var #

var hasAESGCMHardwareSupport = *ast.BinaryExpr

hasGCMAsmAMD64 var #

Keep in sync with crypto/internal/fips140/aes/gcm.supportsAESGCM.

var hasGCMAsmAMD64 = *ast.BinaryExpr

hasGCMAsmARM64 var #

var hasGCMAsmARM64 = *ast.BinaryExpr

hasGCMAsmPPC64 var #

var hasGCMAsmPPC64 = *ast.BinaryExpr

hasGCMAsmS390X var #

var hasGCMAsmS390X = *ast.BinaryExpr

helloRetryRequestRandom var #

helloRetryRequestRandom is set as the Random value of a ServerHello to signal that the message is actually a HelloRetryRequest.

var helloRetryRequestRandom = []byte{...}

innerECHExt const #

const innerECHExt echExtType = 1

keyExpansionLabel const #

const keyExpansionLabel = "key expansion"

keyLogLabelClientHandshake const #

const keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"

keyLogLabelClientTraffic const #

const keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0"

keyLogLabelServerHandshake const #

const keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET"

keyLogLabelServerTraffic const #

const keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0"

keyLogLabelTLS12 const #

const keyLogLabelTLS12 = "CLIENT_RANDOM"

masterSecretLabel const #

const masterSecretLabel = "master secret"

masterSecretLength const #

const masterSecretLength = 48

maxCiphertext const #

const maxCiphertext = *ast.BinaryExpr

maxCiphertextTLS13 const #

const maxCiphertextTLS13 = *ast.BinaryExpr

maxClientPSKIdentities const #

maxClientPSKIdentities is the number of client PSK identities the server will attempt to validate. It will ignore the rest not to let cheap ClientHello messages cause too much work in session ticket decryption attempts.

const maxClientPSKIdentities = 5

maxHandshake const #

const maxHandshake = 65536

maxHandshakeCertificateMsg const #

const maxHandshakeCertificateMsg = 262144

maxPlaintext const #

const maxPlaintext = 16384

maxSessionTicketLifetime const #

maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session ticket, and the lifetime we set for all tickets we send.

const maxSessionTicketLifetime = *ast.BinaryExpr

maxUselessRecords const #

const maxUselessRecords = 16

noncePrefixLength const #

const noncePrefixLength = 4

outBufPool var #

outBufPool pools the record-sized scratch buffers used by writeRecordLocked.

var outBufPool = sync.Pool{...}

outerECHExt const #

const outerECHExt echExtType = 0

pointFormatUncompressed const #

TLS Elliptic Curve Point Formats https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9

const pointFormatUncompressed uint8 = 0

pskModeDHE const #

TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.

const pskModeDHE uint8 = 1

pskModePlain const #

TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9.

const pskModePlain uint8 = 0

recordHeaderLen const #

const recordHeaderLen = 5

recordSizeBoostThreshold const #

recordSizeBoostThreshold is the number of bytes of application data sent after which the TLS record size will be increased to the maximum.

const recordSizeBoostThreshold = *ast.BinaryExpr

recordTypeAlert const #

const recordTypeAlert recordType = 21

recordTypeApplicationData const #

const recordTypeApplicationData recordType = 23

recordTypeChangeCipherSpec const #

const recordTypeChangeCipherSpec recordType = 20

recordTypeHandshake const #

const recordTypeHandshake recordType = 22

roleClient const #

roleClient and roleServer are meant to call supportedVersions and parents with more readability at the callsite.

const roleClient = true

roleServer const #

const roleServer = false

rsaKexCiphers var #

rsaKexCiphers contains the ciphers which use RSA based key exchange, which we also disable by default unless a GODEBUG is set.

var rsaKexCiphers = map[uint16]bool{...}

rsaSignatureSchemes var #

var rsaSignatureSchemes = []struct{...}{...}

scsvRenegotiation const #

TLS signaling cipher suite values

const scsvRenegotiation uint16 = 0x00ff

serverFinishedLabel const #

const serverFinishedLabel = "server finished"

serverSignatureContext const #

const serverSignatureContext = "TLS 1.3, server CertificateVerify\x00"

signatureECDSA const #

Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.

const signatureECDSA

signatureEd25519 const #

Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.

const signatureEd25519

signaturePKCS1v15 const #

Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.

const signaturePKCS1v15 uint8 = *ast.BinaryExpr

signaturePadding var #

var signaturePadding = []byte{...}

signatureRSAPSS const #

Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do.

const signatureRSAPSS

sortedSupportedAEADs var #

sortedSupportedAEADs is just a sorted version of hpke.SupportedAEADS. We need this so that when we insert them into ECHConfigs the ordering is stable.

var sortedSupportedAEADs []uint16

statusTypeOCSP const #

TLS CertificateStatusType (RFC 3546)

const statusTypeOCSP uint8 = 1

suiteECDHE const #

suiteECDHE indicates that the cipher suite involves elliptic curve Diffie-Hellman. This means that it should only be selected when the client indicates that it supports ECC with a curve and point format that we're happy with.

const suiteECDHE = *ast.BinaryExpr

suiteECSign const #

suiteECSign indicates that the cipher suite involves an ECDSA or EdDSA signature and therefore may only be selected when the server's certificate is ECDSA or EdDSA. If this is not set then the cipher suite is RSA based.

const suiteECSign

suiteSHA384 const #

suiteSHA384 indicates that the cipher suite uses SHA384 as the handshake hash.

const suiteSHA384

suiteTLS12 const #

suiteTLS12 indicates that the cipher suite should only be advertised and accepted when using TLS 1.2.

const suiteTLS12

supportedOnlyTLS12 var #

var supportedOnlyTLS12 = []uint16{...}

supportedOnlyTLS13 var #

var supportedOnlyTLS13 = []uint16{...}

supportedUpToTLS12 var #

var supportedUpToTLS12 = []uint16{...}

supportedVersions var #

var supportedVersions = []uint16{...}

tcpMSSEstimate const #

tcpMSSEstimate is a conservative estimate of the TCP maximum segment size (MSS). A constant is used, rather than querying the kernel for the actual MSS, to avoid complexity. The value here is the IPv6 minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40 bytes) and a TCP header with timestamps (32 bytes).

const tcpMSSEstimate = 1208

tdesCiphers var #

tdesCiphers contains 3DES ciphers, which we also disable by default unless a GODEBUG is set.

var tdesCiphers = map[uint16]bool{...}

testingOnlyForceClientHelloSignatureAlgorithms var #

var testingOnlyForceClientHelloSignatureAlgorithms []SignatureScheme

testingOnlyForceDowngradeCanary var #

testingOnlyForceDowngradeCanary is set in tests to force the server side to include downgrade canaries even if it's using its highers supported version.

var testingOnlyForceDowngradeCanary bool

ticketKeyLifetime const #

ticketKeyLifetime is how long a ticket key remains valid and can be used to resume a client connection.

const ticketKeyLifetime = *ast.BinaryExpr

ticketKeyRotation const #

ticketKeyRotation is how often the server should rotate the session ticket key that is used for new tickets.

const ticketKeyRotation = *ast.BinaryExpr

tls10server var #

var tls10server = *ast.CallExpr

tls3des var #

var tls3des = *ast.CallExpr

tlsmaxrsasize var #

var tlsmaxrsasize = *ast.CallExpr

tlsmlkem var #

var tlsmlkem = *ast.CallExpr

tlsrsakex var #

var tlsrsakex = *ast.CallExpr

tlsunsafeekm var #

var tlsunsafeekm = *ast.CallExpr

typeCertificate const #

TLS handshake message types.

const typeCertificate uint8 = 11

typeCertificateRequest const #

TLS handshake message types.

const typeCertificateRequest uint8 = 13

typeCertificateStatus const #

TLS handshake message types.

const typeCertificateStatus uint8 = 22

typeCertificateVerify const #

TLS handshake message types.

const typeCertificateVerify uint8 = 15

typeClientHello const #

TLS handshake message types.

const typeClientHello uint8 = 1

typeClientKeyExchange const #

TLS handshake message types.

const typeClientKeyExchange uint8 = 16

typeEncryptedExtensions const #

TLS handshake message types.

const typeEncryptedExtensions uint8 = 8

typeEndOfEarlyData const #

TLS handshake message types.

const typeEndOfEarlyData uint8 = 5

typeFinished const #

TLS handshake message types.

const typeFinished uint8 = 20

typeHelloRequest const #

TLS handshake message types.

const typeHelloRequest uint8 = 0

typeKeyUpdate const #

TLS handshake message types.

const typeKeyUpdate uint8 = 24

typeMessageHash const #

TLS handshake message types.

const typeMessageHash uint8 = 254

typeNewSessionTicket const #

TLS handshake message types.

const typeNewSessionTicket uint8 = 4

typeServerHello const #

TLS handshake message types.

const typeServerHello uint8 = 2

typeServerHelloDone const #

TLS handshake message types.

const typeServerHelloDone uint8 = 14

typeServerKeyExchange const #

TLS handshake message types.

const typeServerKeyExchange uint8 = 12

writerMutex var #

writerMutex protects all KeyLogWriters globally. It is rarely enabled, and is only for debugging, so a global mutex saves space.

var writerMutex sync.Mutex

x25519PublicKeySize const #

const x25519PublicKeySize = 32

x509keypairleaf var #

var x509keypairleaf = *ast.CallExpr

Type Aliases

AlertError type #

An AlertError is a TLS alert. When using a QUIC transport, QUICConn methods will return an error which wraps AlertError rather than sending a TLS alert.

type AlertError uint8

ClientAuthType type #

ClientAuthType declares the policy the server will follow for TLS Client Authentication.

type ClientAuthType int

CurveID type #

CurveID is the type of a TLS identifier for a key exchange mechanism. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8. In TLS 1.2, this registry used to support only elliptic curves. In TLS 1.3, it was extended to other groups and renamed NamedGroup. See RFC 8446, Section 4.2.7. It was then also extended to other mechanisms, such as hybrid post-quantum KEMs.

type CurveID uint16

QUICEncryptionLevel type #

QUICEncryptionLevel represents a QUIC encryption level used to transmit handshake messages.

type QUICEncryptionLevel int

QUICEventKind type #

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

type QUICEventKind int

RenegotiationSupport type #

RenegotiationSupport enumerates the different levels of support for TLS renegotiation. TLS renegotiation is the act of performing subsequent handshakes on a connection after the first. This significantly complicates the state machine and has been the source of numerous, subtle security issues. Initiating a renegotiation is not supported, but support for accepting renegotiation requests may be enabled. Even when enabled, the server may not change its identity between handshakes (i.e. the leaf certificate must be the same). Additionally, concurrent handshake and application data flow is not permitted so renegotiation can only be used with protocols that synchronise with the renegotiation, such as HTTPS. Renegotiation is not defined in TLS 1.3.

type RenegotiationSupport int

SignatureScheme type #

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

type SignatureScheme uint16

alert type #

type alert uint8

echExtType type #

type echExtType uint8

marshalingFunction type #

The marshalingFunction type is an adapter to allow the use of ordinary functions as cryptobyte.MarshalingValue.

type marshalingFunction func(b *cryptobyte.Builder) error

prfFunc type #

type prfFunc func(secret []byte, label string, seed []byte, keyLen int) []byte

recordType type #

TLS record types.

type recordType uint8

Interfaces

ClientSessionCache interface #

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

type ClientSessionCache interface {
Get(sessionKey string) (session *ClientSessionState, ok bool)
Put(sessionKey string, cs *ClientSessionState)
}

aead interface #

type aead interface {
cipher.AEAD
explicitNonceLen() int
}

cbcMode interface #

cbcMode is an interface for block ciphers using cipher block chaining.

type cbcMode interface {
cipher.BlockMode
SetIV([]byte)
}

constantTimeHash interface #

type constantTimeHash interface {
hash.Hash
ConstantTimeSum(b []byte) []byte
}

handshakeMessage interface #

type handshakeMessage interface {
marshal() ([]byte, error)
unmarshal([]byte) bool
}

handshakeMessageWithOriginalBytes interface #

type handshakeMessageWithOriginalBytes interface {
handshakeMessage
originalBytes() []byte
}

keyAgreement interface #

A keyAgreement implements the client and server side of a TLS 1.0–1.2 key agreement protocol by generating and processing key exchange messages.

type keyAgreement interface {
generateServerKeyExchange(*Config, *Certificate, *clientHelloMsg, *serverHelloMsg) (*serverKeyExchangeMsg, error)
processClientKeyExchange(*Config, *Certificate, *clientKeyExchangeMsg, uint16) ([]byte, error)
processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, *x509.Certificate, *serverKeyExchangeMsg) error
generateClientKeyExchange(*Config, *clientHelloMsg, *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error)
}

transcriptHash interface #

type transcriptHash interface {
Write([]byte) (int, error)
}

Structs

Certificate struct #

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

type Certificate struct {
Certificate [][]byte
PrivateKey crypto.PrivateKey
SupportedSignatureAlgorithms []SignatureScheme
OCSPStaple []byte
SignedCertificateTimestamps [][]byte
Leaf *x509.Certificate
}

CertificateRequestInfo struct #

CertificateRequestInfo contains information from a server's CertificateRequest message, which is used to demand a certificate and proof of control from a client.

type CertificateRequestInfo struct {
AcceptableCAs [][]byte
SignatureSchemes []SignatureScheme
Version uint16
ctx context.Context
}

CertificateVerificationError struct #

CertificateVerificationError is returned when certificate verification fails during the handshake.

type CertificateVerificationError struct {
UnverifiedCertificates []*x509.Certificate
Err error
}

CipherSuite struct #

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

type CipherSuite struct {
ID uint16
Name string
SupportedVersions []uint16
Insecure bool
}

ClientHelloInfo struct #

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

type ClientHelloInfo struct {
CipherSuites []uint16
ServerName string
SupportedCurves []CurveID
SupportedPoints []uint8
SignatureSchemes []SignatureScheme
SupportedProtos []string
SupportedVersions []uint16
Extensions []uint16
Conn net.Conn
config *Config
ctx context.Context
}

ClientSessionState struct #

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

type ClientSessionState struct {
session *SessionState
}

Config struct #

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.

type Config struct {
Rand io.Reader
Time func() time.Time
Certificates []Certificate
NameToCertificate map[string]*Certificate
GetCertificate func(*ClientHelloInfo) (*Certificate, error)
GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
GetConfigForClient func(*ClientHelloInfo) (*Config, error)
VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
VerifyConnection func(ConnectionState) error
RootCAs *x509.CertPool
NextProtos []string
ServerName string
ClientAuth ClientAuthType
ClientCAs *x509.CertPool
InsecureSkipVerify bool
CipherSuites []uint16
PreferServerCipherSuites bool
SessionTicketsDisabled bool
SessionTicketKey [32]byte
ClientSessionCache ClientSessionCache
UnwrapSession func(identity []byte, cs ConnectionState) (*SessionState, error)
WrapSession func(ConnectionState, *SessionState) ([]byte, error)
MinVersion uint16
MaxVersion uint16
CurvePreferences []CurveID
DynamicRecordSizingDisabled bool
Renegotiation RenegotiationSupport
KeyLogWriter io.Writer
EncryptedClientHelloConfigList []byte
EncryptedClientHelloRejectionVerify func(ConnectionState) error
EncryptedClientHelloKeys []EncryptedClientHelloKey
mutex sync.RWMutex
sessionTicketKeys []ticketKey
autoSessionTicketKeys []ticketKey
}

Conn struct #

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

type Conn struct {
conn net.Conn
isClient bool
handshakeFn func(context.Context) error
quic *quicState
isHandshakeComplete atomic.Bool
handshakeMutex sync.Mutex
handshakeErr error
vers uint16
haveVers bool
config *Config
handshakes int
extMasterSecret bool
didResume bool
didHRR bool
cipherSuite uint16
curveID CurveID
ocspResponse []byte
scts [][]byte
peerCertificates []*x509.Certificate
activeCertHandles []*activeCert
verifiedChains [][]*x509.Certificate
serverName string
secureRenegotiation bool
ekm func(label string, context []byte, length int) ([]byte, error)
resumptionSecret []byte
echAccepted bool
ticketKeys []ticketKey
clientFinishedIsFirst bool
closeNotifyErr error
closeNotifySent bool
clientFinished [12]byte
serverFinished [12]byte
clientProtocol string
in halfConn
out halfConn
rawInput bytes.Buffer
input bytes.Reader
hand bytes.Buffer
buffering bool
sendBuf []byte
bytesSent int64
packetsSent int64
retryCount int
activeCall atomic.Int32
tmp [16]byte
}

ConnectionState struct #

ConnectionState records basic TLS details about the connection.

type ConnectionState struct {
Version uint16
HandshakeComplete bool
DidResume bool
CipherSuite uint16
NegotiatedProtocol string
NegotiatedProtocolIsMutual bool
ServerName string
PeerCertificates []*x509.Certificate
VerifiedChains [][]*x509.Certificate
SignedCertificateTimestamps [][]byte
OCSPResponse []byte
TLSUnique []byte
ECHAccepted bool
ekm func(label string, context []byte, length int) ([]byte, error)
testingOnlyDidHRR bool
testingOnlyCurveID CurveID
}

Dialer struct #

Dialer dials TLS connections given a configuration and a Dialer for the underlying connection.

type Dialer struct {
NetDialer *net.Dialer
Config *Config
}

ECHRejectionError struct #

ECHRejectionError is the error type returned when ECH is rejected by a remote server. If the server offered a ECHConfigList to use for retries, the RetryConfigList field will contain this list. The client may treat an ECHRejectionError with an empty set of RetryConfigs as a secure signal from the server.

type ECHRejectionError struct {
RetryConfigList []byte
}

EncryptedClientHelloKey struct #

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

type EncryptedClientHelloKey struct {
Config []byte
PrivateKey []byte
SendAsRetry bool
}

QUICConfig struct #

A QUICConfig configures a [QUICConn].

type QUICConfig struct {
TLSConfig *Config
EnableSessionEvents bool
}

QUICConn struct #

A QUICConn represents a connection which uses a QUIC implementation as the underlying transport as described in RFC 9001. Methods of QUICConn are not safe for concurrent use.

type QUICConn struct {
conn *Conn
sessionTicketSent bool
}

QUICEvent struct #

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.

type QUICEvent struct {
Kind QUICEventKind
Level QUICEncryptionLevel
Data []byte
Suite uint16
SessionState *SessionState
}

QUICSessionTicketOptions struct #

type QUICSessionTicketOptions struct {
EarlyData bool
Extra [][]byte
}

RecordHeaderError struct #

RecordHeaderError is returned when a TLS record header is invalid.

type RecordHeaderError struct {
Msg string
RecordHeader [5]byte
Conn net.Conn
}

SessionState struct #

A SessionState is a resumable session.

type SessionState struct {
Extra [][]byte
EarlyData bool
version uint16
isClient bool
cipherSuite uint16
createdAt uint64
secret []byte
extMasterSecret bool
peerCertificates []*x509.Certificate
activeCertHandles []*activeCert
ocspResponse []byte
scts [][]byte
verifiedChains [][]*x509.Certificate
alpnProtocol string
useBy uint64
ageAdd uint32
ticket []byte
}

activeCert struct #

activeCert is a handle to a certificate held in the cache. Once there are no alive activeCerts for a given certificate, the certificate is removed from the cache by a finalizer.

type activeCert struct {
cert *x509.Certificate
}

atLeastReader struct #

atLeastReader reads from R, stopping with EOF once at least N bytes have been read. It is different from an io.LimitedReader in that it doesn't cut short the last Read call, and in that it considers an early EOF an error.

type atLeastReader struct {
R io.Reader
N int64
}

cacheEntry struct #

type cacheEntry struct {
refs atomic.Int64
cert *x509.Certificate
}

certCache struct #

certCache implements an intern table for reference counted x509.Certificates, implemented in a similar fashion to BoringSSL's CRYPTO_BUFFER_POOL. This allows for a single x509.Certificate to be kept in memory and referenced from multiple Conns. Returned references should not be mutated by callers. Certificates are still safe to use after they are removed from the cache. Certificates are returned wrapped in an activeCert struct that should be held by the caller. When references to the activeCert are freed, the number of references to the certificate in the cache is decremented. Once the number of references reaches zero, the entry is evicted from the cache. The main difference between this implementation and CRYPTO_BUFFER_POOL is that CRYPTO_BUFFER_POOL is a more generic structure which supports blobs of data, rather than specific structures. Since we only care about x509.Certificates, certCache is implemented as a specific cache, rather than a generic one. See https://boringssl.googlesource.com/boringssl/+/master/include/openssl/pool.h and https://boringssl.googlesource.com/boringssl/+/master/crypto/pool/pool.c for the BoringSSL reference.

type certCache struct {
sync.Map
}

certificateMsg struct #

type certificateMsg struct {
certificates [][]byte
}

certificateMsgTLS13 struct #

type certificateMsgTLS13 struct {
certificate Certificate
ocspStapling bool
scts bool
}

certificateRequestMsg struct #

type certificateRequestMsg struct {
hasSignatureAlgorithm bool
certificateTypes []byte
supportedSignatureAlgorithms []SignatureScheme
certificateAuthorities [][]byte
}

certificateRequestMsgTLS13 struct #

type certificateRequestMsgTLS13 struct {
ocspStapling bool
scts bool
supportedSignatureAlgorithms []SignatureScheme
supportedSignatureAlgorithmsCert []SignatureScheme
certificateAuthorities [][]byte
}

certificateStatusMsg struct #

type certificateStatusMsg struct {
response []byte
}

certificateVerifyMsg struct #

type certificateVerifyMsg struct {
hasSignatureAlgorithm bool
signatureAlgorithm SignatureScheme
signature []byte
}

cipherSuite struct #

A cipherSuite is a TLS 1.0–1.2 cipher suite, and defines the key exchange mechanism, as well as the cipher+MAC pair or the AEAD.

type cipherSuite struct {
id uint16
keyLen int
macLen int
ivLen int
ka func(version uint16) keyAgreement
flags int
cipher func(key []byte, iv []byte, isRead bool) any
mac func(key []byte) hash.Hash
aead func(key []byte, fixedNonce []byte) aead
}

cipherSuiteTLS13 struct #

A cipherSuiteTLS13 defines only the pair of the AEAD algorithm and hash algorithm to be used with HKDF. See RFC 8446, Appendix B.4.

type cipherSuiteTLS13 struct {
id uint16
keyLen int
aead func(key []byte, fixedNonce []byte) aead
hash crypto.Hash
}

clientHandshakeState struct #

type clientHandshakeState struct {
c *Conn
ctx context.Context
serverHello *serverHelloMsg
hello *clientHelloMsg
suite *cipherSuite
finishedHash finishedHash
masterSecret []byte
session *SessionState
ticket []byte
}

clientHandshakeStateTLS13 struct #

type clientHandshakeStateTLS13 struct {
c *Conn
ctx context.Context
serverHello *serverHelloMsg
hello *clientHelloMsg
keyShareKeys *keySharePrivateKeys
session *SessionState
earlySecret *tls13.EarlySecret
binderKey []byte
certReq *certificateRequestMsgTLS13
usingPSK bool
sentDummyCCS bool
suite *cipherSuiteTLS13
transcript hash.Hash
masterSecret *tls13.MasterSecret
trafficSecret []byte
echContext *echClientContext
}

clientHelloMsg struct #

type clientHelloMsg struct {
original []byte
vers uint16
random []byte
sessionId []byte
cipherSuites []uint16
compressionMethods []uint8
serverName string
ocspStapling bool
supportedCurves []CurveID
supportedPoints []uint8
ticketSupported bool
sessionTicket []uint8
supportedSignatureAlgorithms []SignatureScheme
supportedSignatureAlgorithmsCert []SignatureScheme
secureRenegotiationSupported bool
secureRenegotiation []byte
extendedMasterSecret bool
alpnProtocols []string
scts bool
supportedVersions []uint16
cookie []byte
keyShares []keyShare
earlyData bool
pskModes []uint8
pskIdentities []pskIdentity
pskBinders [][]byte
quicTransportParameters []byte
encryptedClientHello []byte
extensions []uint16
}

clientKeyExchangeMsg struct #

type clientKeyExchangeMsg struct {
ciphertext []byte
}

cthWrapper struct #

cthWrapper wraps any hash.Hash that implements ConstantTimeSum, and replaces with that all calls to Sum. It's used to obtain a ConstantTimeSum-based HMAC.

type cthWrapper struct {
h constantTimeHash
}

ecdheKeyAgreement struct #

ecdheKeyAgreement implements a TLS key agreement where the server generates an ephemeral EC public/private key pair and signs it. The pre-master secret is then calculated using ECDH. The signature may be ECDSA, Ed25519 or RSA.

type ecdheKeyAgreement struct {
version uint16
isRSA bool
key *ecdh.PrivateKey
ckx *clientKeyExchangeMsg
preMasterSecret []byte
}

echCipher struct #

type echCipher struct {
KDFID uint16
AEADID uint16
}

echClientContext struct #

type echClientContext struct {
config *echConfig
hpkeContext *hpke.Sender
encapsulatedKey []byte
innerHello *clientHelloMsg
innerTranscript hash.Hash
kdfID uint16
aeadID uint16
echRejected bool
retryConfigs []byte
}

echConfig struct #

type echConfig struct {
raw []byte
Version uint16
Length uint16
ConfigID uint8
KemID uint16
PublicKey []byte
SymmetricCipherSuite []echCipher
MaxNameLength uint8
PublicName []byte
Extensions []echExtension
}

echExtension struct #

type echExtension struct {
Type uint16
Data []byte
}

echServerContext struct #

type echServerContext struct {
hpkeContext *hpke.Receipient
configID uint8
ciphersuite echCipher
transcript hash.Hash
inner bool
}

encryptedExtensionsMsg struct #

type encryptedExtensionsMsg struct {
alpnProtocol string
quicTransportParameters []byte
earlyData bool
echRetryConfigs []byte
}

endOfEarlyDataMsg struct #

type endOfEarlyDataMsg struct {

}

finishedHash struct #

A finishedHash calculates the hash of a set of handshake messages suitable for including in a Finished message.

type finishedHash struct {
client hash.Hash
server hash.Hash
clientMD5 hash.Hash
serverMD5 hash.Hash
buffer []byte
version uint16
prf prfFunc
}

finishedMsg struct #

type finishedMsg struct {
verifyData []byte
}

halfConn struct #

A halfConn represents one direction of the record layer connection, either sending or receiving.

type halfConn struct {
sync.Mutex
err error
version uint16
cipher any
mac hash.Hash
seq [8]byte
scratchBuf [13]byte
nextCipher any
nextMac hash.Hash
level QUICEncryptionLevel
trafficSecret []byte
}

helloRequestMsg struct #

type helloRequestMsg struct {

}

keyShare struct #

TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.

type keyShare struct {
group CurveID
data []byte
}

keySharePrivateKeys struct #

type keySharePrivateKeys struct {
curveID CurveID
ecdhe *ecdh.PrivateKey
mlkem *mlkem.DecapsulationKey768
}

keyUpdateMsg struct #

type keyUpdateMsg struct {
updateRequested bool
}

listener struct #

A listener implements a network listener (net.Listener) for TLS connections.

type listener struct {
net.Listener
config *Config
}

lruSessionCache struct #

lruSessionCache is a ClientSessionCache implementation that uses an LRU caching strategy.

type lruSessionCache struct {
sync.Mutex
m map[string]*list.Element
q *list.List
capacity int
}

lruSessionCacheEntry struct #

type lruSessionCacheEntry struct {
sessionKey string
state *ClientSessionState
}

newSessionTicketMsg struct #

type newSessionTicketMsg struct {
ticket []byte
}

newSessionTicketMsgTLS13 struct #

type newSessionTicketMsgTLS13 struct {
lifetime uint32
ageAdd uint32
nonce []byte
label []byte
maxEarlyData uint32
}

permanentError struct #

type permanentError struct {
err net.Error
}

prefixNonceAEAD struct #

prefixNonceAEAD wraps an AEAD and prefixes a fixed portion of the nonce to each call.

type prefixNonceAEAD struct {
nonce [aeadNonceLength]byte
aead cipher.AEAD
}

pskIdentity struct #

TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved session. See RFC 8446, Section 4.2.11.

type pskIdentity struct {
label []byte
obfuscatedTicketAge uint32
}

quicState struct #

type quicState struct {
events []QUICEvent
nextEvent int
eventArr [8]QUICEvent
started bool
signalc chan struct{...}
blockedc chan struct{...}
cancelc <-chan struct{...}
cancel context.CancelFunc
waitingForDrain bool
readbuf []byte
transportParams []byte
enableSessionEvents bool
}

rawExtension struct #

type rawExtension struct {
extType uint16
data []byte
}

rsaKeyAgreement struct #

rsaKeyAgreement implements the standard TLS key agreement where the client encrypts the pre-master secret to the server's public key.

type rsaKeyAgreement struct {

}

serverHandshakeState struct #

serverHandshakeState contains details of a server handshake in progress. It's discarded once the handshake has completed.

type serverHandshakeState struct {
c *Conn
ctx context.Context
clientHello *clientHelloMsg
hello *serverHelloMsg
suite *cipherSuite
ecdheOk bool
ecSignOk bool
rsaDecryptOk bool
rsaSignOk bool
sessionState *SessionState
finishedHash finishedHash
masterSecret []byte
cert *Certificate
}

serverHandshakeStateTLS13 struct #

type serverHandshakeStateTLS13 struct {
c *Conn
ctx context.Context
clientHello *clientHelloMsg
hello *serverHelloMsg
sentDummyCCS bool
usingPSK bool
earlyData bool
suite *cipherSuiteTLS13
cert *Certificate
sigAlg SignatureScheme
earlySecret *tls13.EarlySecret
sharedKey []byte
handshakeSecret *tls13.HandshakeSecret
masterSecret *tls13.MasterSecret
trafficSecret []byte
transcript hash.Hash
clientFinished []byte
echContext *echServerContext
}

serverHelloDoneMsg struct #

type serverHelloDoneMsg struct {

}

serverHelloMsg struct #

type serverHelloMsg struct {
original []byte
vers uint16
random []byte
sessionId []byte
cipherSuite uint16
compressionMethod uint8
ocspStapling bool
ticketSupported bool
secureRenegotiationSupported bool
secureRenegotiation []byte
extendedMasterSecret bool
alpnProtocol string
scts [][]byte
supportedVersion uint16
serverShare keyShare
selectedIdentityPresent bool
selectedIdentity uint16
supportedPoints []uint8
encryptedClientHello []byte
serverNameAck bool
cookie []byte
selectedGroup CurveID
}

serverKeyExchangeMsg struct #

type serverKeyExchangeMsg struct {
key []byte
}

ticketKey struct #

ticketKey is the internal representation of a session ticket key.

type ticketKey struct {
aesKey [16]byte
hmacKey [16]byte
created time.Time
}

timeoutError struct #

type timeoutError struct {

}

xorNonceAEAD struct #

xorNonceAEAD wraps an AEAD by XORing in a fixed pattern to the nonce before each call.

type xorNonceAEAD struct {
nonceMask [aeadNonceLength]byte
aead cipher.AEAD
}

Functions

Accept method #

Accept waits for and returns the next incoming TLS connection. The returned connection is of type *Conn.

func (l *listener) Accept() (net.Conn, error)

BlockSize method #

func (c *cthWrapper) BlockSize() int

BuildNameToCertificate method #

BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate from the CommonName and SubjectAlternateName fields of each of the leaf certificates. Deprecated: NameToCertificate only allows associating a single certificate with a given name. Leave that field nil to let the library select the first compatible chain from Certificates.

func (c *Config) BuildNameToCertificate()

Bytes method #

Bytes encodes the session, including any private fields, so that it can be parsed by [ParseSessionState]. The encoding contains secret values critical to the security of future and possibly past sessions. The specific encoding should be considered opaque and may change incompatibly between Go versions.

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

CipherSuiteName function #

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

func CipherSuiteName(id uint16) string

CipherSuites function #

CipherSuites returns a list of cipher suites currently implemented by this package, excluding those with security issues, which are returned by [InsecureCipherSuites]. The list is sorted by ID. Note that the default cipher suites selected by this package might depend on logic that can't be captured by a static list, and might not match those returned by this function.

func CipherSuites() []*CipherSuite

Client function #

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

Clone method #

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

func (c *Config) Clone() *Config

Close method #

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

func (q *QUICConn) Close() error

Close method #

Close closes the connection.

func (c *Conn) Close() error

CloseWrite method #

CloseWrite shuts down the writing side of the connection. It should only be called once the handshake has completed and does not call CloseWrite on the underlying connection. Most callers should just use [Conn.Close].

func (c *Conn) CloseWrite() error

ConnectionState method #

ConnectionState returns basic TLS details about the connection.

func (c *Conn) ConnectionState() ConnectionState

ConnectionState method #

ConnectionState returns basic TLS details about the connection.

func (q *QUICConn) ConnectionState() ConnectionState

Context method #

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 (c *ClientHelloInfo) Context() context.Context

Context method #

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 (c *CertificateRequestInfo) Context() context.Context

DecryptTicket method #

DecryptTicket decrypts a ticket encrypted by [Config.EncryptTicket]. It can be used as a [Config.UnwrapSession] implementation. If the ticket can't be decrypted or parsed, DecryptTicket returns (nil, nil).

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

Dial function #

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.

func Dial(network string, addr string, config *Config) (*Conn, error)

Dial method #

Dial connects to the given network address and initiates a TLS handshake, returning the resulting TLS connection. The returned [Conn], if any, will always be of type *[Conn]. Dial uses context.Background internally; to specify the context, use [Dialer.DialContext].

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

DialContext method #

DialContext connects to the given network address and initiates a TLS handshake, returning the resulting TLS connection. The provided Context must be non-nil. If the context expires before the connection is complete, an error is returned. Once successfully connected, any expiration of the context will not affect the connection. The returned [Conn], if any, will always be of type *[Conn].

func (d *Dialer) DialContext(ctx context.Context, network string, addr string) (net.Conn, error)

DialWithDialer function #

DialWithDialer connects to the given network address using dialer.Dial and then initiates a TLS handshake, returning the resulting TLS connection. Any timeout or deadline given in the dialer apply to connection and TLS handshake as a whole. DialWithDialer interprets a nil configuration as equivalent to the zero configuration; see the documentation of [Config] for the defaults. DialWithDialer uses context.Background internally; to specify the context, use [Dialer.DialContext] with NetDialer set to the desired dialer.

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

EncryptTicket method #

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

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

Error method #

func (e *CertificateVerificationError) Error() string

Error method #

func (e AlertError) Error() string

Error method #

func (timeoutError) Error() string

Error method #

func (e *permanentError) Error() string

Error method #

func (e RecordHeaderError) Error() string

Error method #

func (e *ECHRejectionError) Error() string

Error method #

func (e alert) Error() string

ExportKeyingMaterial method #

ExportKeyingMaterial returns length bytes of exported key material in a new slice as defined in RFC 5705. If context is nil, it is not used as part of the seed. If the connection was set to allow renegotiation via Config.Renegotiation, or if the connections supports neither TLS 1.3 nor Extended Master Secret, this function will return an error. Exporting key material without Extended Master Secret or TLS 1.3 was disabled in Go 1.22 due to security issues (see the Security Considerations sections of RFC 5705 and RFC 7627), but can be re-enabled with the GODEBUG setting tlsunsafeekm=1.

func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error)

Get method #

Get returns the [ClientSessionState] value associated with a given key. It returns (nil, false) if no value is found.

func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool)

HandleData method #

HandleData handles handshake bytes received from the peer. It may produce connection events, which may be read with [QUICConn.NextEvent].

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

Handshake method #

Handshake runs the client or server handshake protocol if it has not yet been run. Most uses of this package need not call Handshake explicitly: the first [Conn.Read] or [Conn.Write] will call it automatically. For control over canceling or setting a timeout on a handshake, use [Conn.HandshakeContext] or the [Dialer]'s DialContext method instead. In order to avoid denial of service attacks, the maximum RSA key size allowed in certificates sent by either the TLS server or client is limited to 8192 bits. This limit can be overridden by setting tlsmaxrsasize in the GODEBUG environment variable (e.g. GODEBUG=tlsmaxrsasize=4096).

func (c *Conn) Handshake() error

HandshakeContext method #

HandshakeContext runs the client or server handshake protocol if it has not yet been run. The provided Context must be non-nil. If the context is canceled before the handshake is complete, the handshake is interrupted and an error is returned. Once the handshake has completed, cancellation of the context will not affect the connection. Most uses of this package need not call HandshakeContext explicitly: the first [Conn.Read] or [Conn.Write] will call it automatically.

func (c *Conn) HandshakeContext(ctx context.Context) error

InsecureCipherSuites function #

InsecureCipherSuites returns a list of cipher suites currently implemented by this package and which have security issues. Most applications should not use the cipher suites in this list, and should only use those returned by [CipherSuites].

func InsecureCipherSuites() []*CipherSuite

Listen function #

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

LoadX509KeyPair function #

LoadX509KeyPair reads and parses a public/private key pair from a pair of files. The files must contain PEM encoded data. The certificate file may contain intermediate certificates following the leaf certificate to form a certificate chain. On successful return, Certificate.Leaf will be populated. Before Go 1.23 Certificate.Leaf was left nil, and the parsed certificate was discarded. This behavior can be re-enabled by setting "x509keypairleaf=0" in the GODEBUG environment variable.

func LoadX509KeyPair(certFile string, keyFile string) (Certificate, error)

LocalAddr method #

LocalAddr returns the local network address.

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

Marshal method #

func (f marshalingFunction) Marshal(b *cryptobyte.Builder) error

NetConn method #

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

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

NewLRUClientSessionCache function #

NewLRUClientSessionCache returns a [ClientSessionCache] with the given capacity that uses an LRU strategy. If capacity is < 1, a default capacity is used instead.

func NewLRUClientSessionCache(capacity int) ClientSessionCache

NewListener function #

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.

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

NewResumptionState function #

NewResumptionState returns a state value that can be returned by [ClientSessionCache.Get] to resume a previous session. state needs to be returned by [ParseSessionState], and the ticket and session state must have been returned by [ClientSessionState.ResumptionState].

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

NextEvent method #

NextEvent returns the next event occurring on the connection. It returns an event with a Kind of [QUICNoEvent] when no events are available.

func (q *QUICConn) NextEvent() QUICEvent

NonceSize method #

func (f *prefixNonceAEAD) NonceSize() int

NonceSize method #

func (f *xorNonceAEAD) NonceSize() int

OCSPResponse method #

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

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

Open method #

func (f *prefixNonceAEAD) Open(out []byte, nonce []byte, ciphertext []byte, additionalData []byte) ([]byte, error)

Open method #

func (f *xorNonceAEAD) Open(out []byte, nonce []byte, ciphertext []byte, additionalData []byte) ([]byte, error)

Overhead method #

func (f *xorNonceAEAD) Overhead() int

Overhead method #

func (f *prefixNonceAEAD) Overhead() int

ParseSessionState function #

ParseSessionState parses a [SessionState] encoded by [SessionState.Bytes].

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

Put method #

Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry corresponding to sessionKey is removed from the cache instead.

func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState)

QUICClient function #

QUICClient returns a new TLS client side connection using QUICTransport as the underlying transport. The config cannot be nil. The config's MinVersion must be at least TLS 1.3.

func QUICClient(config *QUICConfig) *QUICConn

QUICServer function #

QUICServer returns a new TLS server side connection using QUICTransport as the underlying transport. The config cannot be nil. The config's MinVersion must be at least TLS 1.3.

func QUICServer(config *QUICConfig) *QUICConn

Read method #

func (r *atLeastReader) Read(p []byte) (int, error)

Read method #

Read reads data from the connection. As Read calls [Conn.Handshake], in order to prevent indefinite blocking a deadline must be set for both Read and [Conn.Write] before Read is called when the handshake has not yet completed. See [Conn.SetDeadline], [Conn.SetReadDeadline], and [Conn.SetWriteDeadline].

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

RemoteAddr method #

RemoteAddr returns the remote network address.

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

Reset method #

func (c *cthWrapper) Reset()

ResumptionState method #

ResumptionState returns the session ticket sent by the server (also known as the session's identity) and the state necessary to resume this session. It can be called by [ClientSessionCache.Put] to serialize (with [SessionState.Bytes]) and store the session.

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

Seal method #

func (f *prefixNonceAEAD) Seal(out []byte, nonce []byte, plaintext []byte, additionalData []byte) []byte

Seal method #

func (f *xorNonceAEAD) Seal(out []byte, nonce []byte, plaintext []byte, additionalData []byte) []byte

SendSessionTicket method #

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

func (q *QUICConn) SendSessionTicket(opts QUICSessionTicketOptions) error

Server function #

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

SetDeadline method #

SetDeadline sets the read and write deadlines associated with the connection. A zero value for t means [Conn.Read] and [Conn.Write] will not time out. After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.

func (c *Conn) SetDeadline(t time.Time) error

SetReadDeadline method #

SetReadDeadline sets the read deadline on the underlying connection. A zero value for t means [Conn.Read] will not time out.

func (c *Conn) SetReadDeadline(t time.Time) error

SetSessionTicketKeys method #

SetSessionTicketKeys updates the session ticket keys for a server. The first key will be used when creating new tickets, while all keys can be used for decrypting tickets. It is safe to call this function while the server is running in order to rotate the session ticket keys. The function will panic if keys is empty. Calling this function will turn off automatic session ticket key rotation. If multiple servers are terminating connections for the same host they should all have the same session ticket keys. If the session ticket keys leaks, previously recorded and future TLS connections using those keys might be compromised.

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

SetTransportParameters method #

SetTransportParameters sets the transport parameters to send to the peer. Server connections may delay setting the transport parameters until after receiving the client's transport parameters. See [QUICTransportParametersRequired].

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

SetWriteDeadline method #

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

func (c *Conn) SetWriteDeadline(t time.Time) error

Size method #

func (c *cthWrapper) Size() int

Start method #

Start starts the client or server handshake protocol. It may produce connection events, which may be read with [QUICConn.NextEvent]. Start must be called at most once.

func (q *QUICConn) Start(ctx context.Context) error

StoreSession method #

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

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

String method #

func (e alert) String() string

String method #

func (i SignatureScheme) String() string

String method #

func (i ClientAuthType) String() string

String method #

func (i CurveID) String() string

String method #

func (l QUICEncryptionLevel) String() string

Sum method #

func (h finishedHash) Sum() []byte

Sum method #

func (c *cthWrapper) Sum(b []byte) []byte

SupportsCertificate method #

SupportsCertificate returns nil if the provided certificate is supported by the client that sent the ClientHello. Otherwise, it returns an error describing the reason for the incompatibility. If this [ClientHelloInfo] was passed to a GetConfigForClient or GetCertificate callback, this method will take into account the associated [Config]. Note that if GetConfigForClient returns a different [Config], the change can't be accounted for by this method. This function will call x509.ParseCertificate unless c.Leaf is set, which can incur a significant performance cost.

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

SupportsCertificate method #

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

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

Temporary method #

func (e *permanentError) Temporary() bool

Temporary method #

func (timeoutError) Temporary() bool

Timeout method #

func (e *permanentError) Timeout() bool

Timeout method #

func (timeoutError) Timeout() bool

Unwrap method #

func (e *CertificateVerificationError) Unwrap() error

Unwrap method #

func (e *permanentError) Unwrap() error

VerifyHostname method #

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 (c *Conn) VerifyHostname(host string) error

VersionName function #

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

func VersionName(version uint16) string

Write method #

func (h *finishedHash) Write(msg []byte) (n int, err error)

Write method #

func (c *cthWrapper) Write(p []byte) (int, error)

Write method #

Write writes data to the connection. As Write calls [Conn.Handshake], in order to prevent indefinite blocking a deadline must be set for both [Conn.Read] and Write before Write is called when the handshake has not yet completed. See [Conn.SetDeadline], [Conn.SetReadDeadline], and [Conn.SetWriteDeadline].

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

X509KeyPair function #

X509KeyPair parses a public/private key pair from a pair of PEM encoded data. On successful return, Certificate.Leaf will be populated. Before Go 1.23 Certificate.Leaf was left nil, and the parsed certificate was discarded. This behavior can be re-enabled by setting "x509keypairleaf=0" in the GODEBUG environment variable.

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

_ function #

func _()

_ function #

func _()

_ function #

func _()

active method #

active increments the number of references to the entry, wraps the certificate in the entry in an activeCert, and sets the finalizer. Note that there is a race between active and the finalizer set on the returned activeCert, triggered if active is called after the ref count is decremented such that refs may be > 0 when evict is called. We consider this safe, since the caller holding an activeCert for an entry that is no longer in the cache is fine, with the only side effect being the memory overhead of there being more than one distinct reference to a certificate alive at once.

func (cc *certCache) active(e *cacheEntry) *activeCert

addBytesWithLength function #

addBytesWithLength appends a sequence of bytes to the cryptobyte.Builder. If the length of the sequence is not the value specified, it produces an error.

func addBytesWithLength(b *cryptobyte.Builder, v []byte, n int)

addUint64 function #

addUint64 appends a big-endian, 64-bit value to the cryptobyte.Builder.

func addUint64(b *cryptobyte.Builder, v uint64)

aeadAESGCM function #

func aeadAESGCM(key []byte, noncePrefix []byte) aead

aeadAESGCMTLS13 function #

aeadAESGCMTLS13 should be an internal detail, but widely used packages access it using linkname. Notable members of the hall of shame include: - github.com/xtls/xray-core - github.com/v2fly/v2ray-core Do not remove or change the type signature. See go.dev/issue/67401. go:linkname aeadAESGCMTLS13

func aeadAESGCMTLS13(key []byte, nonceMask []byte) aead

aeadChaCha20Poly1305 function #

func aeadChaCha20Poly1305(key []byte, nonceMask []byte) aead

aesgcmPreferred function #

aesgcmPreferred returns whether the first known cipher in the preference list is an AES-GCM cipher, implying the peer has hardware support for it.

func aesgcmPreferred(ciphers []uint16) bool

buildRetryConfigList function #

func buildRetryConfigList(keys []EncryptedClientHelloKey) ([]byte, error)

certificateRequestInfoFromMsg function #

certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS <= 1.2 CertificateRequest, making an effort to fill in missing information.

func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo

certificatesToBytesSlice function #

func certificatesToBytesSlice(certs []*x509.Certificate) [][]byte

changeCipherSpec method #

changeCipherSpec changes the encryption and MAC states to the ones previously passed to prepareCipherSpec.

func (hc *halfConn) changeCipherSpec() error

checkALPN function #

checkALPN ensure that the server's choice of ALPN protocol is compatible with the protocols that we advertised in the ClientHello.

func checkALPN(clientProtos []string, serverProto string, quic bool) error

checkForResumption method #

checkForResumption reports whether we should perform resumption on this connection.

func (hs *serverHandshakeState) checkForResumption() error

checkForResumption method #

func (hs *serverHandshakeStateTLS13) checkForResumption() error

checkKeySize function #

func checkKeySize(n int) (max int, ok bool)

checkServerHelloOrHRR method #

checkServerHelloOrHRR does validity checks that apply to both ServerHello and HelloRetryRequest messages. It sets hs.suite.

func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error

cipher3DES function #

func cipher3DES(key []byte, iv []byte, isRead bool) any

cipherAES function #

func cipherAES(key []byte, iv []byte, isRead bool) any

cipherRC4 function #

func cipherRC4(key []byte, iv []byte, isRead bool) any

cipherSuiteByID function #

func cipherSuiteByID(id uint16) *cipherSuite

cipherSuiteOk method #

func (hs *serverHandshakeState) cipherSuiteOk(c *cipherSuite) bool

cipherSuiteTLS13ByID function #

func cipherSuiteTLS13ByID(id uint16) *cipherSuiteTLS13

cipherSuites method #

func (c *Config) cipherSuites() []uint16

clientHandshake method #

func (c *Conn) clientHandshake(ctx context.Context) (err error)

clientHelloInfo function #

func clientHelloInfo(ctx context.Context, c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo

clientSessionCacheKey method #

clientSessionCacheKey returns a key used to cache sessionTickets that could be used to resume previously negotiated TLS sessions with a server.

func (c *Conn) clientSessionCacheKey() string

clientSum method #

clientSum returns the contents of the verify_data member of a client's Finished message.

func (h finishedHash) clientSum(masterSecret []byte) []byte

clone method #

func (m *clientHelloMsg) clone() *clientHelloMsg

cloneHash function #

cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler interfaces implemented by standard library hashes to clone the state of in to a new instance of h. It returns nil if the operation fails.

func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash

closeNotify method #

func (c *Conn) closeNotify() error

computeAndUpdateOuterECHExtension function #

func computeAndUpdateOuterECHExtension(outer *clientHelloMsg, inner *clientHelloMsg, ech *echClientContext, useKey bool) error

computeAndUpdatePSK function #

func computeAndUpdatePSK(m *clientHelloMsg, binderKey []byte, transcript hash.Hash, finishedHash func([]byte, hash.Hash) []byte) error

connectionStateLocked method #

func (c *Conn) connectionStateLocked() ConnectionState

curveForCurveID function #

func curveForCurveID(id CurveID) (ecdh.Curve, bool)

curveIDForCurve function #

func curveIDForCurve(curve ecdh.Curve) (CurveID, bool)

curvePreferences method #

func (c *Config) curvePreferences(version uint16) []CurveID

decodeInnerClientHello function #

func decodeInnerClientHello(outer *clientHelloMsg, encoded []byte) (*clientHelloMsg, error)

decrypt method #

decrypt authenticates and decrypts the record if protection is active at this stage. The returned plaintext might overlap with the input.

func (hc *halfConn) decrypt(record []byte) ([]byte, recordType, error)

decryptECHPayload function #

func decryptECHPayload(context *hpke.Receipient, hello []byte, payload []byte) ([]byte, error)

decryptTicket method #

func (c *Config) decryptTicket(encrypted []byte, ticketKeys []ticketKey) []byte

defaultCipherSuites function #

func defaultCipherSuites() []uint16

defaultConfig function #

func defaultConfig() *Config

defaultCurvePreferences function #

defaultCurvePreferences is the default set of supported key exchanges, as well as the preference order.

func defaultCurvePreferences() []CurveID

dial function #

func dial(ctx context.Context, netDialer *net.Dialer, network string, addr string, config *Config) (*Conn, error)

discardHandshakeBuffer method #

discardHandshakeBuffer is called when there is no more need to buffer the entirety of the handshake messages.

func (h *finishedHash) discardHandshakeBuffer()

doFullHandshake method #

func (hs *serverHandshakeState) doFullHandshake() error

doFullHandshake method #

func (hs *clientHandshakeState) doFullHandshake() error

doHelloRetryRequest method #

func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) (*keyShare, error)

doResumeHandshake method #

func (hs *serverHandshakeState) doResumeHandshake() error

ecdheECDSAKA function #

func ecdheECDSAKA(version uint16) keyAgreement

ecdheRSAKA function #

func ecdheRSAKA(version uint16) keyAgreement

ekmFromMasterSecret function #

ekmFromMasterSecret generates exported keying material as defined in RFC 5705.

func ekmFromMasterSecret(version uint16, suite *cipherSuite, masterSecret []byte, clientRandom []byte, serverRandom []byte) (func(string, []byte, int) ([]byte, error))

encodeInnerClientHello function #

func encodeInnerClientHello(inner *clientHelloMsg, maxNameLength int) ([]byte, error)

encrypt method #

encrypt encrypts payload, adding the appropriate nonce and/or MAC, and appends it to record, which must already contain the record header.

func (hc *halfConn) encrypt(record []byte, payload []byte, rand io.Reader) ([]byte, error)

encryptTicket method #

func (c *Config) encryptTicket(state []byte, ticketKeys []ticketKey) ([]byte, error)

establishHandshakeKeys method #

func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error

establishKeys method #

func (hs *serverHandshakeState) establishKeys() error

establishKeys method #

func (hs *clientHandshakeState) establishKeys() error

evict method #

evict removes a cacheEntry from the cache.

func (cc *certCache) evict(e *cacheEntry)

explicitNonceLen method #

func (f *prefixNonceAEAD) explicitNonceLen() int

explicitNonceLen method #

explicitNonceLen returns the number of bytes of explicit nonce or IV included in each record. Explicit nonces are present only in CBC modes after TLS 1.0 and in certain AEAD modes in TLS 1.2.

func (hc *halfConn) explicitNonceLen() int

explicitNonceLen method #

func (f *xorNonceAEAD) explicitNonceLen() int

exportKeyingMaterial method #

exportKeyingMaterial implements RFC5705 exporters for TLS 1.3 according to RFC 8446, Section 7.5.

func (c *cipherSuiteTLS13) exportKeyingMaterial(s *tls13.MasterSecret, transcript hash.Hash) (func(string, []byte, int) ([]byte, error))

extMasterFromPreMasterSecret function #

extMasterFromPreMasterSecret generates the extended master secret from the pre-master secret. See RFC 7627.

func extMasterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret []byte, transcript []byte) []byte

extractPadding function #

extractPadding returns, in constant time, the length of the padding to remove from the end of payload. It also returns a byte which is equal to 255 if the padding was valid and 0 otherwise. See RFC 2246, Section 6.2.3.2.

func extractPadding(payload []byte) (toRemove int, good byte)

extractRawExtensions function #

func extractRawExtensions(hello *clientHelloMsg) ([]rawExtension, error)

finishedHash method #

finishedHash generates the Finished verify_data or PskBinderEntry according to RFC 8446, Section 4.4.4. See sections 4.4 and 4.2.11.2 for the baseKey selection.

func (c *cipherSuiteTLS13) finishedHash(baseKey []byte, transcript hash.Hash) []byte

fipsAllowCert function #

func fipsAllowCert(c *x509.Certificate) bool

fipsAllowChain function #

func fipsAllowChain(chain []*x509.Certificate) bool

fipsAllowedChains function #

fipsAllowedChains returns chains that are allowed to be used in a TLS connection based on the current fips140tls enforcement setting. If fips140tls is not required, the chains are returned as-is with no processing. Otherwise, the returned chains are filtered to only those allowed by FIPS 140-3. If this results in no chains it returns an error.

func fipsAllowedChains(chains [][]*x509.Certificate) ([][]*x509.Certificate, error)

flush method #

func (c *Conn) flush() (int, error)

generateClientKeyExchange method #

func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error)

generateClientKeyExchange method #

func (ka rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error)

generateECDHEKey function #

generateECDHEKey returns a PrivateKey that implements Diffie-Hellman according to RFC 8446, Section 4.2.8.2.

func generateECDHEKey(rand io.Reader, curveID CurveID) (*ecdh.PrivateKey, error)

generateOuterECHExt function #

func generateOuterECHExt(id uint8, kdfID uint16, aeadID uint16, encodedKey []byte, payload []byte) ([]byte, error)

generateServerKeyExchange method #

func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error)

generateServerKeyExchange method #

func (ka rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error)

getCertificate method #

getCertificate returns the best certificate for the given ClientHelloInfo, defaulting to the first element of c.Certificates.

func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error)

getClientCertificate method #

func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error)

handleKeyUpdate method #

func (c *Conn) handleKeyUpdate(keyUpdate *keyUpdateMsg) error

handleNewSessionTicket method #

func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error

handlePostHandshakeMessage method #

handlePostHandshakeMessage processes a handshake message arrived after the handshake is complete. Up to TLS 1.2, it indicates the start of a renegotiation.

func (c *Conn) handlePostHandshakeMessage() error

handleRenegotiation method #

handleRenegotiation processes a HelloRequest handshake message.

func (c *Conn) handleRenegotiation() error

handshake method #

func (hs *serverHandshakeStateTLS13) handshake() error

handshake method #

handshake requires hs.c, hs.hello, hs.serverHello, hs.keyShareKeys, and, optionally, hs.session, hs.earlySecret and hs.binderKey to be set.

func (hs *clientHandshakeStateTLS13) handshake() error

handshake method #

func (hs *serverHandshakeState) handshake() error

handshake method #

Does the handshake, either a full one or resumes old session. Requires hs.c, hs.hello, hs.serverHello, and, optionally, hs.session to be set.

func (hs *clientHandshakeState) handshake() error

handshakeContext method #

func (c *Conn) handshakeContext(ctx context.Context) (ret error)

hashForClientCertificate method #

hashForClientCertificate returns the handshake messages so far, pre-hashed if necessary, suitable for signing by a TLS client certificate.

func (h finishedHash) hashForClientCertificate(sigType uint8, hashAlg crypto.Hash) []byte

hashForServerKeyExchange function #

hashForServerKeyExchange hashes the given slices and returns their digest using the given hash function (for TLS 1.2) or using a default based on the sigType (for earlier TLS versions). For Ed25519 signatures, which don't do pre-hashing, it returns the concatenation of the slices.

func hashForServerKeyExchange(sigType uint8, hashFunc crypto.Hash, version uint16, slices ...[]byte) []byte

hostnameInSNI function #

hostnameInSNI converts name into an appropriate hostname for SNI. Literal IP addresses and absolute FQDNs are not permitted as SNI values. See RFC 6066, Section 3.

func hostnameInSNI(name string) string

illegalClientHelloChange function #

illegalClientHelloChange reports whether the two ClientHello messages are different, with the exception of the changes allowed before and after a HelloRetryRequest. See RFC 8446, Section 4.1.2.

func illegalClientHelloChange(ch *clientHelloMsg, ch1 *clientHelloMsg) bool

incSeq method #

incSeq increments the sequence number.

func (hc *halfConn) incSeq()

init function #

func init()

initLegacySessionTicketKeyRLocked method #

initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is randomized if empty, and that sessionTicketKeys is populated from it otherwise.

func (c *Config) initLegacySessionTicketKeyRLocked()

isPQKeyExchange function #

func isPQKeyExchange(curve CurveID) bool

isSupportedSignatureAlgorithm function #

func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool

isTLS13OnlyKeyExchange function #

func isTLS13OnlyKeyExchange(curve CurveID) bool

keysFromMasterSecret function #

keysFromMasterSecret generates the connection keys from the master secret, given the lengths of the MAC key, cipher key and IV, as defined in RFC 2246, Section 6.3.

func keysFromMasterSecret(version uint16, suite *cipherSuite, masterSecret []byte, clientRandom []byte, serverRandom []byte, macLen int, keyLen int, ivLen int) (clientMAC []byte, serverMAC []byte, clientKey []byte, serverKey []byte, clientIV []byte, serverIV []byte)

leaf method #

leaf returns the parsed leaf certificate, either from c.Leaf or by parsing the corresponding c.Certificate[0].

func (c *Certificate) leaf() (*x509.Certificate, error)

legacyTypeAndHashFromPublicKey function #

legacyTypeAndHashFromPublicKey returns the fixed signature type and crypto.Hash for a given public key used with TLS 1.0 and 1.1, before the introduction of signature algorithm negotiation.

func legacyTypeAndHashFromPublicKey(pub crypto.PublicKey) (sigType uint8, hash crypto.Hash, err error)

loadSession method #

func (c *Conn) loadSession(hello *clientHelloMsg) (session *SessionState, earlySecret *tls13.EarlySecret, binderKey []byte, err error)

macSHA1 function #

macSHA1 returns a SHA-1 based constant time MAC.

func macSHA1(key []byte) hash.Hash

macSHA256 function #

macSHA256 returns a SHA-256 based MAC. This is only supported in TLS 1.2 and is currently only used in disabled-by-default cipher suites.

func macSHA256(key []byte) hash.Hash

makeClientHello method #

func (c *Conn) makeClientHello() (*clientHelloMsg, *keySharePrivateKeys, *echClientContext, error)

marshal method #

func (m *certificateVerifyMsg) marshal() ([]byte, error)

marshal method #

func (m *keyUpdateMsg) marshal() ([]byte, error)

marshal method #

func (m *clientHelloMsg) marshal() ([]byte, error)

marshal method #

func (m *serverHelloMsg) marshal() ([]byte, error)

marshal method #

func (m *endOfEarlyDataMsg) marshal() ([]byte, error)

marshal method #

func (m *certificateMsg) marshal() ([]byte, error)

marshal method #

func (m *encryptedExtensionsMsg) marshal() ([]byte, error)

marshal method #

func (m *certificateRequestMsg) marshal() ([]byte, error)

marshal method #

func (m *newSessionTicketMsgTLS13) marshal() ([]byte, error)

marshal method #

func (m *certificateMsgTLS13) marshal() ([]byte, error)

marshal method #

func (m *certificateRequestMsgTLS13) marshal() ([]byte, error)

marshal method #

func (m *clientKeyExchangeMsg) marshal() ([]byte, error)

marshal method #

func (m *serverHelloDoneMsg) marshal() ([]byte, error)

marshal method #

func (m *serverKeyExchangeMsg) marshal() ([]byte, error)

marshal method #

func (*helloRequestMsg) marshal() ([]byte, error)

marshal method #

func (m *newSessionTicketMsg) marshal() ([]byte, error)

marshal method #

func (m *finishedMsg) marshal() ([]byte, error)

marshal method #

func (m *certificateStatusMsg) marshal() ([]byte, error)

marshalCertificate function #

func marshalCertificate(b *cryptobyte.Builder, certificate Certificate)

marshalEncryptedClientHelloConfigList function #

func marshalEncryptedClientHelloConfigList(configs []EncryptedClientHelloKey) ([]byte, error)

marshalMsg method #

func (m *clientHelloMsg) marshalMsg(echInner bool) ([]byte, error)

marshalWithoutBinders method #

marshalWithoutBinders returns the ClientHello through the PreSharedKeyExtension.identities field, according to RFC 8446, Section 4.2.11.2. Note that m.pskBinders must be set to slices of the correct length.

func (m *clientHelloMsg) marshalWithoutBinders() ([]byte, error)

masterFromPreMasterSecret function #

masterFromPreMasterSecret generates the master secret from the pre-master secret. See RFC 5246, Section 8.1.

func masterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret []byte, clientRandom []byte, serverRandom []byte) []byte

maxPayloadSizeForWrite method #

maxPayloadSizeForWrite returns the maximum TLS payload size to use for the next application data record. There is the following trade-off: - For latency-sensitive applications, such as web browsing, each TLS record should fit in one TCP segment. - For throughput-sensitive applications, such as large file transfers, larger TLS records better amortize framing and encryption overheads. A simple heuristic that works well in practice is to use small records for the first 1MB of data, then use larger records for subsequent data, and reset back to smaller records after the connection becomes idle. See "High Performance Web Networking", Chapter 4, or: https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/ In the interests of simplicity and determinism, this code does not attempt to reset the record size once the connection is idle, however.

func (c *Conn) maxPayloadSizeForWrite(typ recordType) int

maxSupportedVersion method #

func (c *Config) maxSupportedVersion(isClient bool) uint16

md5SHA1Hash function #

md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the concatenation of an MD5 and SHA1 hash.

func md5SHA1Hash(slices [][]byte) []byte

mutualCipherSuite function #

mutualCipherSuite returns a cipherSuite given a list of supported ciphersuites and the id requested by the peer.

func mutualCipherSuite(have []uint16, want uint16) *cipherSuite

mutualCipherSuiteTLS13 function #

func mutualCipherSuiteTLS13(have []uint16, want uint16) *cipherSuiteTLS13

mutualVersion method #

mutualVersion returns the protocol version to use given the advertised versions of the peer. Priority is given to the peer preference order.

func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool)

negotiateALPN function #

negotiateALPN picks a shared ALPN protocol that both sides support in server preference order. If ALPN is not configured or the peer doesn't support it, it returns "" and no error.

func negotiateALPN(serverProtos []string, clientProtos []string, quic bool) (string, error)

netDialer method #

func (d *Dialer) netDialer() *net.Dialer

newCert method #

newCert returns a x509.Certificate parsed from der. If there is already a copy of the certificate in the cache, a reference to the existing certificate will be returned. Otherwise, a fresh certificate will be added to the cache, and the reference returned. The returned reference should not be mutated.

func (cc *certCache) newCert(der []byte) (*activeCert, error)

newConstantTimeHash function #

func newConstantTimeHash(h func() hash.Hash) (func() hash.Hash)

newFinishedHash function #

func newFinishedHash(version uint16, cipherSuite *cipherSuite) finishedHash

newQUICConn function #

func newQUICConn(conn *Conn, config *QUICConfig) *QUICConn

newRecordHeaderError method #

func (c *Conn) newRecordHeaderError(conn net.Conn, msg string) (err RecordHeaderError)

nextTrafficSecret method #

nextTrafficSecret generates the next traffic secret, given the current one, according to RFC 8446, Section 7.2.

func (c *cipherSuiteTLS13) nextTrafficSecret(trafficSecret []byte) []byte

noEKMBecauseNoEMS function #

noEKMBecauseNoEMS is used as a value of ConnectionState.ekm when Extended Master Secret is not negotiated and thus we wish to fail all key-material export requests.

func noEKMBecauseNoEMS(label string, context []byte, length int) ([]byte, error)

noEKMBecauseRenegotiation function #

noEKMBecauseRenegotiation is used as a value of ConnectionState.ekm when renegotiation is enabled and thus we wish to fail all key-material export requests.

func noEKMBecauseRenegotiation(label string, context []byte, length int) ([]byte, error)

originalBytes method #

func (m *clientHelloMsg) originalBytes() []byte

originalBytes method #

func (m *serverHelloMsg) originalBytes() []byte

pHash function #

pHash implements the P_hash function, as defined in RFC 4346, Section 5.

func pHash(result []byte, secret []byte, seed []byte, hash func() hash.Hash)

parseECHConfig function #

func parseECHConfig(enc []byte) (skip bool, ec echConfig, err error)

parseECHConfigList function #

parseECHConfigList parses a draft-ietf-tls-esni-18 ECHConfigList, returning a slice of parsed ECHConfigs, in the same order they were parsed, or an error if the list is malformed.

func parseECHConfigList(data []byte) ([]echConfig, error)

parseECHExt function #

func parseECHExt(ext []byte) (echType echExtType, cs echCipher, configID uint8, encap []byte, payload []byte, err error)

parsePrivateKey function #

Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates PKCS #1 private keys by default, while OpenSSL 1.0.0 generates PKCS #8 keys. OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.

func parsePrivateKey(der []byte) (crypto.PrivateKey, error)

pickCertificate method #

func (hs *serverHandshakeStateTLS13) pickCertificate() error

pickCipherSuite method #

func (hs *clientHandshakeState) pickCipherSuite() error

pickCipherSuite method #

func (hs *serverHandshakeState) pickCipherSuite() error

pickECHCipherSuite function #

func pickECHCipherSuite(suites []echCipher) (echCipher, error)

pickECHConfig function #

func pickECHConfig(list []echConfig) *echConfig

pickTLSVersion method #

func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error

prepareCipherSpec method #

prepareCipherSpec sets the encryption and MAC states that a subsequent changeCipherSpec will use.

func (hc *halfConn) prepareCipherSpec(version uint16, cipher any, mac hash.Hash)

prf10 function #

prf10 implements the TLS 1.0 pseudo-random function, as defined in RFC 2246, Section 5.

func prf10(secret []byte, label string, seed []byte, keyLen int) []byte

prf12 function #

prf12 implements the TLS 1.2 pseudo-random function, as defined in RFC 5246, Section 5.

func prf12(hashFunc func() hash.Hash) prfFunc

prfAndHashForVersion function #

func prfAndHashForVersion(version uint16, suite *cipherSuite) (prfFunc, crypto.Hash)

prfForVersion function #

func prfForVersion(version uint16, suite *cipherSuite) prfFunc

processCertsFromClient method #

processCertsFromClient takes a chain of client certificates either from a Certificates message and verifies them.

func (c *Conn) processCertsFromClient(certificate Certificate) error

processClientHello method #

func (hs *serverHandshakeState) processClientHello() error

processClientHello method #

func (hs *serverHandshakeStateTLS13) processClientHello() error

processClientKeyExchange method #

func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error)

processClientKeyExchange method #

func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error)

processECHClientHello method #

func (c *Conn) processECHClientHello(outer *clientHelloMsg) (*clientHelloMsg, *echServerContext, error)

processHelloRetryRequest method #

processHelloRetryRequest handles the HRR in hs.serverHello, modifies and resends hs.hello, and reads the new ServerHello into hs.serverHello.

func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error

processServerHello method #

func (hs *clientHandshakeState) processServerHello() (bool, error)

processServerHello method #

func (hs *clientHandshakeStateTLS13) processServerHello() error

processServerKeyExchange method #

func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error

processServerKeyExchange method #

func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error

quicError function #

quicError ensures err is an AlertError. If err is not already, quicError wraps it with alertInternalError.

func quicError(err error) error

quicGetTransportParameters method #

func (c *Conn) quicGetTransportParameters() ([]byte, error)

quicHandshakeComplete method #

func (c *Conn) quicHandshakeComplete()

quicReadHandshakeBytes method #

func (c *Conn) quicReadHandshakeBytes(n int) error

quicRejectedEarlyData method #

func (c *Conn) quicRejectedEarlyData()

quicResumeSession method #

func (c *Conn) quicResumeSession(session *SessionState) error

quicSetReadSecret method #

func (c *Conn) quicSetReadSecret(level QUICEncryptionLevel, suite uint16, secret []byte)

quicSetTransportParameters method #

func (c *Conn) quicSetTransportParameters(params []byte)

quicSetWriteSecret method #

func (c *Conn) quicSetWriteSecret(level QUICEncryptionLevel, suite uint16, secret []byte)

quicStoreSession method #

func (c *Conn) quicStoreSession(session *SessionState)

quicWaitForSignal method #

quicWaitForSignal notifies the QUICConn that handshake progress is blocked, and waits for a signal that the handshake should proceed. The handshake may become blocked waiting for handshake bytes or for the user to provide transport parameters.

func (c *Conn) quicWaitForSignal() error

quicWriteCryptoData method #

func (c *Conn) quicWriteCryptoData(level QUICEncryptionLevel, data []byte)

rand method #

func (c *Config) rand() io.Reader

readChangeCipherSpec method #

func (c *Conn) readChangeCipherSpec() error

readClientCertificate method #

func (hs *serverHandshakeStateTLS13) readClientCertificate() error

readClientFinished method #

func (hs *serverHandshakeStateTLS13) readClientFinished() error

readClientHello method #

readClientHello reads a ClientHello message and selects the protocol version.

func (c *Conn) readClientHello(ctx context.Context) (*clientHelloMsg, *echServerContext, error)

readFinished method #

func (hs *serverHandshakeState) readFinished(out []byte) error

readFinished method #

func (hs *clientHandshakeState) readFinished(out []byte) error

readFromUntil method #

readFromUntil reads from r into c.rawInput until c.rawInput contains at least n bytes or else returns an error.

func (c *Conn) readFromUntil(r io.Reader, n int) error

readHandshake method #

readHandshake reads the next handshake message from the record layer. If transcript is non-nil, the message is written to the passed transcriptHash.

func (c *Conn) readHandshake(transcript transcriptHash) (any, error)

readHandshakeBytes method #

readHandshakeBytes reads handshake data until c.hand contains at least n bytes.

func (c *Conn) readHandshakeBytes(n int) error

readRecord method #

func (c *Conn) readRecord() error

readRecordOrCCS method #

readRecordOrCCS reads one or more TLS records from the connection and updates the record layer state. Some invariants: - c.in must be locked - c.input must be empty During the handshake one and only one of the following will happen: - c.hand grows - c.in.changeCipherSpec is called - an error is returned After the handshake one and only one of the following will happen: - c.hand grows - c.input is set - an error is returned

func (c *Conn) readRecordOrCCS(expectChangeCipherSpec bool) error

readServerCertificate method #

func (hs *clientHandshakeStateTLS13) readServerCertificate() error

readServerFinished method #

func (hs *clientHandshakeStateTLS13) readServerFinished() error

readServerParameters method #

func (hs *clientHandshakeStateTLS13) readServerParameters() error

readSessionTicket method #

func (hs *clientHandshakeState) readSessionTicket() error

readUint16LengthPrefixed function #

readUint16LengthPrefixed acts like s.ReadUint16LengthPrefixed, but targets a []byte instead of a cryptobyte.String.

func readUint16LengthPrefixed(s *cryptobyte.String, out *[]byte) bool

readUint24LengthPrefixed function #

readUint24LengthPrefixed acts like s.ReadUint24LengthPrefixed, but targets a []byte instead of a cryptobyte.String.

func readUint24LengthPrefixed(s *cryptobyte.String, out *[]byte) bool

readUint64 function #

readUint64 decodes a big-endian, 64-bit value into out and advances over it. It reports whether the read was successful.

func readUint64(s *cryptobyte.String, out *uint64) bool

readUint8LengthPrefixed function #

readUint8LengthPrefixed acts like s.ReadUint8LengthPrefixed, but targets a []byte instead of a cryptobyte.String.

func readUint8LengthPrefixed(s *cryptobyte.String, out *[]byte) bool

requestClientCert method #

func (hs *serverHandshakeStateTLS13) requestClientCert() bool

requiresClientCert function #

requiresClientCert reports whether the ClientAuthType requires a client certificate to be provided.

func requiresClientCert(c ClientAuthType) bool

retryReadRecord method #

retryReadRecord recurs into readRecordOrCCS to drop a non-advancing record, like a warning alert, empty application_data, or a change_cipher_spec in TLS 1.3.

func (c *Conn) retryReadRecord(expectChangeCipherSpec bool) error

roundUp function #

func roundUp(a int, b int) int

rsaKA function #

func rsaKA(version uint16) keyAgreement

saveSessionTicket method #

func (hs *clientHandshakeState) saveSessionTicket() error

selectCipherSuite function #

selectCipherSuite returns the first TLS 1.0–1.2 cipher suite from ids which is also in supportedIDs and passes the ok filter.

func selectCipherSuite(ids []uint16, supportedIDs []uint16, ok func(*cipherSuite) bool) *cipherSuite

selectSignatureScheme function #

selectSignatureScheme picks a SignatureScheme from the peer's preference list that works with the selected certificate. It's only called for protocol versions that support signature algorithms, so TLS 1.2 and 1.3.

func selectSignatureScheme(vers uint16, c *Certificate, peerAlgs []SignatureScheme) (SignatureScheme, error)

sendAlert method #

sendAlert sends a TLS alert message.

func (c *Conn) sendAlert(err alert) error

sendAlertLocked method #

sendAlertLocked sends a TLS alert message.

func (c *Conn) sendAlertLocked(err alert) error

sendClientCertificate method #

func (hs *clientHandshakeStateTLS13) sendClientCertificate() error

sendClientFinished method #

func (hs *clientHandshakeStateTLS13) sendClientFinished() error

sendDummyChangeCipherSpec method #

sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.

func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error

sendDummyChangeCipherSpec method #

sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.

func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error

sendFinished method #

func (hs *clientHandshakeState) sendFinished(out []byte) error

sendFinished method #

func (hs *serverHandshakeState) sendFinished(out []byte) error

sendServerCertificate method #

func (hs *serverHandshakeStateTLS13) sendServerCertificate() error

sendServerFinished method #

func (hs *serverHandshakeStateTLS13) sendServerFinished() error

sendServerParameters method #

func (hs *serverHandshakeStateTLS13) sendServerParameters() error

sendSessionTicket method #

func (hs *serverHandshakeState) sendSessionTicket() error

sendSessionTicket method #

func (c *Conn) sendSessionTicket(earlyData bool, extra [][]byte) error

sendSessionTickets method #

func (hs *serverHandshakeStateTLS13) sendSessionTickets() error

serverHandshake method #

serverHandshake performs a TLS handshake as a server.

func (c *Conn) serverHandshake(ctx context.Context) error

serverResumedSession method #

func (hs *clientHandshakeState) serverResumedSession() bool

serverSum method #

serverSum returns the contents of the verify_data member of a server's Finished message.

func (h finishedHash) serverSum(masterSecret []byte) []byte

sessionState method #

sessionState returns a partially filled-out [SessionState] with information from the current connection.

func (c *Conn) sessionState() *SessionState

setErrorLocked method #

func (hc *halfConn) setErrorLocked(err error) error

setTrafficSecret method #

func (hc *halfConn) setTrafficSecret(suite *cipherSuiteTLS13, level QUICEncryptionLevel, secret []byte)

sha1Hash function #

sha1Hash calculates a SHA1 hash over the given byte slices.

func sha1Hash(slices [][]byte) []byte

shouldSendSessionTickets method #

func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool

signatureSchemesForCertificate function #

signatureSchemesForCertificate returns the list of supported SignatureSchemes for a given certificate, based on the public key and the protocol version, and optionally filtered by its explicit SupportedSignatureAlgorithms. This function must be kept in sync with supportedSignatureAlgorithms. FIPS filtering is applied in the caller, selectSignatureScheme.

func signatureSchemesForCertificate(version uint16, cert *Certificate) []SignatureScheme

signedMessage function #

signedMessage returns the pre-hashed (if necessary) message to be signed by certificate keys in TLS 1.3. See RFC 8446, Section 4.4.3.

func signedMessage(sigHash crypto.Hash, context string, transcript hash.Hash) []byte

skipUint16LengthPrefixed function #

func skipUint16LengthPrefixed(s *cryptobyte.String) bool

skipUint8LengthPrefixed function #

func skipUint8LengthPrefixed(s *cryptobyte.String) bool

sliceForAppend function #

sliceForAppend extends the input slice by n bytes. head is the full extended slice, while tail is the appended part. If the original slice has sufficient capacity no allocation is performed.

func sliceForAppend(in []byte, n int) (head []byte, tail []byte)

splitPreMasterSecret function #

Split a premaster secret in two as specified in RFC 4346, Section 5.

func splitPreMasterSecret(secret []byte) (s1 []byte, s2 []byte)

supportedSignatureAlgorithms function #

supportedSignatureAlgorithms returns the supported signature algorithms.

func supportedSignatureAlgorithms() []SignatureScheme

supportedVersions method #

func (c *Config) supportedVersions(isClient bool) []uint16

supportedVersionsFromMax function #

supportedVersionsFromMax returns a list of supported versions derived from a legacy maximum version value. Note that only versions supported by this library are returned. Any newer peer will use supportedVersions anyway.

func supportedVersionsFromMax(maxVersion uint16) []uint16

supportsCurve method #

func (c *Config) supportsCurve(version uint16, curve CurveID) bool

supportsECDHE function #

supportsECDHE returns whether ECDHE key exchanges can be used with this pre-TLS 1.3 client.

func supportsECDHE(c *Config, version uint16, supportedCurves []CurveID, supportedPoints []uint8) bool

ticketKeyFromBytes method #

ticketKeyFromBytes converts from the external representation of a session ticket key to a ticketKey. Externally, session ticket keys are 32 random bytes and this function expands that into sufficient name and key material.

func (c *Config) ticketKeyFromBytes(b [32]byte) (key ticketKey)

ticketKeys method #

ticketKeys returns the ticketKeys for this connection. If configForClient has explicitly set keys, those will be returned. Otherwise, the keys on c will be used and may be rotated if auto-managed. During rotation, any expired session ticket keys are deleted from c.sessionTicketKeys. If the session ticket key that is currently encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys) is not fresh, then a new session ticket key will be created and prepended to c.sessionTicketKeys.

func (c *Config) ticketKeys(configForClient *Config) []ticketKey

time method #

func (c *Config) time() time.Time

tls10MAC function #

tls10MAC implements the TLS 1.0 MAC function. RFC 2246, Section 6.2.3.

func tls10MAC(h hash.Hash, out []byte, seq []byte, header []byte, data []byte, extra []byte) []byte

trafficKey method #

trafficKey generates traffic keys according to RFC 8446, Section 7.3.

func (c *cipherSuiteTLS13) trafficKey(trafficSecret []byte) (key []byte, iv []byte)

transcriptMsg function #

transcriptMsg is a helper used to hash messages which are not hashed when they are read from, or written to, the wire. This is typically the case for messages which are either not sent, or need to be hashed out of order from when they are read/written. For most messages, the message is marshalled using their marshal method, since their wire representation is idempotent. For clientHelloMsg and serverHelloMsg, we store the original wire representation of the message and use that for hashing, since unmarshal/marshal are not idempotent due to extension ordering and other malleable fields, which may cause differences between what was received and what we marshal.

func transcriptMsg(msg handshakeMessage, h transcriptHash) error

typeAndHashFromSignatureScheme function #

typeAndHashFromSignatureScheme returns the corresponding signature type and crypto.Hash for a given TLS SignatureScheme.

func typeAndHashFromSignatureScheme(signatureAlgorithm SignatureScheme) (sigType uint8, hash crypto.Hash, err error)

unexpectedMessageError function #

func unexpectedMessageError(wanted any, got any) error

unmarshal method #

func (m *certificateMsg) unmarshal(data []byte) bool

unmarshal method #

func (m *clientHelloMsg) unmarshal(data []byte) bool

unmarshal method #

func (m *certificateRequestMsgTLS13) unmarshal(data []byte) bool

unmarshal method #

func (m *endOfEarlyDataMsg) unmarshal(data []byte) bool

unmarshal method #

func (m *keyUpdateMsg) unmarshal(data []byte) bool

unmarshal method #

func (m *certificateStatusMsg) unmarshal(data []byte) bool

unmarshal method #

func (m *finishedMsg) unmarshal(data []byte) bool

unmarshal method #

func (m *certificateMsgTLS13) unmarshal(data []byte) bool

unmarshal method #

func (m *encryptedExtensionsMsg) unmarshal(data []byte) bool

unmarshal method #

func (m *certificateRequestMsg) unmarshal(data []byte) bool

unmarshal method #

func (m *serverHelloMsg) unmarshal(data []byte) bool

unmarshal method #

func (m *newSessionTicketMsgTLS13) unmarshal(data []byte) bool

unmarshal method #

func (m *serverKeyExchangeMsg) unmarshal(data []byte) bool

unmarshal method #

func (m *newSessionTicketMsg) unmarshal(data []byte) bool

unmarshal method #

func (m *clientKeyExchangeMsg) unmarshal(data []byte) bool

unmarshal method #

func (m *serverHelloDoneMsg) unmarshal(data []byte) bool

unmarshal method #

func (*helloRequestMsg) unmarshal(data []byte) bool

unmarshal method #

func (m *certificateVerifyMsg) unmarshal(data []byte) bool

unmarshalCertificate function #

func unmarshalCertificate(s *cryptobyte.String, certificate *Certificate) bool

unmarshalHandshakeMessage method #

func (c *Conn) unmarshalHandshakeMessage(data []byte, transcript transcriptHash) (handshakeMessage, error)

unsupportedCertificateError function #

unsupportedCertificateError returns a helpful error for certificates with an unsupported private key.

func unsupportedCertificateError(cert *Certificate) error

updateBinders method #

updateBinders updates the m.pskBinders field. The supplied binders must have the same length as the current m.pskBinders.

func (m *clientHelloMsg) updateBinders(pskBinders [][]byte) error

validDNSName function #

validDNSName is a rather rudimentary check for the validity of a DNS name. This is used to check if the public_name in a ECHConfig is valid when we are picking a config. This can be somewhat lax because even if we pick a valid-looking name, the DNS layer will later reject it anyway.

func validDNSName(name string) bool

verifyHandshakeSignature function #

verifyHandshakeSignature verifies a signature against pre-hashed (if required) handshake contents.

func verifyHandshakeSignature(sigType uint8, pubkey crypto.PublicKey, hashFunc crypto.Hash, signed []byte, sig []byte) error

verifyServerCertificate method #

verifyServerCertificate parses and verifies the provided chain, setting c.verifiedChains and c.peerCertificates or sending the appropriate alert.

func (c *Conn) verifyServerCertificate(certificates [][]byte) error

write method #

func (c *Conn) write(data []byte) (int, error)

writeChangeCipherRecord method #

writeChangeCipherRecord writes a ChangeCipherSpec message to the connection and updates the record layer state.

func (c *Conn) writeChangeCipherRecord() error

writeHandshakeRecord method #

writeHandshakeRecord writes a handshake message to the connection and updates the record layer state. If transcript is non-nil the marshaled message is written to it.

func (c *Conn) writeHandshakeRecord(msg handshakeMessage, transcript transcriptHash) (int, error)

writeKeyLog method #

func (c *Config) writeKeyLog(label string, clientRandom []byte, secret []byte) error

writeRecordLocked method #

writeRecordLocked writes a TLS record with the given type and payload to the connection and updates the record layer state.

func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error)

Generated with Arrow