Documentation
¶
Overview ¶
Package dtls implements Datagram Transport Layer Security (DTLS) 1.2 and 1.3.
Index ¶
- Variables
- func Listen(conn net.PacketConn, opts ...ServerOption) (net.Listener, error)
- func ListenAddr(network string, laddr *net.UDPAddr, opts ...ServerOption) (net.Listener, error)
- func NewListener(inner dtlsnet.PacketListener, opts ...ServerOption) (net.Listener, error)
- func OnlySendCIDGenerator() func() []byte
- func RandomCIDGenerator(size int) func() []byte
- type CIDPathMigrationPolicy
- type CertificateRequestInfo
- type ClientAuthType
- type ClientHelloInfo
- type ClientOption
- type Conn
- func Client(conn net.PacketConn, raddr net.Addr, opts ...ClientOption) (*Conn, error)
- func Dial(network string, rAddr *net.UDPAddr, opts ...ClientOption) (*Conn, error)
- func Resume(state *State, conn net.PacketConn, rAddr net.Addr, opts ...Option) (*Conn, error)
- func Server(conn net.PacketConn, raddr net.Addr, opts ...ServerOption) (*Conn, error)
- func (c *Conn) AddPath(socket net.PacketConn) (*Path, error)
- func (c *Conn) Close() error
- func (c *Conn) ConnectionState() (State, bool)
- func (c *Conn) ExportState() (State, error)
- func (c *Conn) Handshake() error
- func (c *Conn) HandshakeContext(ctx context.Context) error
- func (c *Conn) LocalAddr() net.Addr
- func (c *Conn) Read(buff []byte) (n int, err error)
- func (c *Conn) RemoteAddr() net.Addr
- func (c *Conn) RemoteSRTPMasterKeyIdentifier() ([]byte, bool)
- func (c *Conn) SelectedSRTPProtectionProfile() (SRTPProtectionProfile, bool)
- func (c *Conn) SetDeadline(t time.Time) error
- func (c *Conn) SetReadDeadline(t time.Time) error
- func (c *Conn) SetWriteDeadline(t time.Time) error
- func (c *Conn) UpdateKeys(ctx context.Context, options KeyUpdateOptions) error
- func (c *Conn) Write(payload []byte) (int, error)
- type DetachedConn
- func (c *DetachedConn) Close() error
- func (c *DetachedConn) ConnectionState() (State, bool)
- func (c *DetachedConn) EventReady() <-chan struct{}
- func (c *DetachedConn) HandleDatagram(datagram []byte, addr net.Addr) error
- func (c *DetachedConn) NextEvent() DetachedEvent
- func (c *DetachedConn) RemoteSRTPMasterKeyIdentifier() ([]byte, bool)
- func (c *DetachedConn) SelectedSRTPProtectionProfile() (SRTPProtectionProfile, bool)
- func (c *DetachedConn) Start(ctx context.Context) error
- func (c *DetachedConn) Write(data []byte) (int, error)
- func (c *DetachedConn) WriteEarlyData(data []byte) (int, error)
- type DetachedEvent
- type DetachedEventKind
- type ECHOption
- type ECHRejectionError
- type EarlyDataSessionStore
- type EncryptedClientHelloKey
- type ExtendedMasterSecretType
- type KeyUpdateOptions
- type KeyUsageStats
- type Option
- func WithCertificateSignatureSchemes(schemes ...tls.SignatureScheme) Option
- func WithCertificates(certs ...tls.Certificate) Option
- func WithCipherSuites(suites ...cryptosuite.ID) Option
- func WithClientHelloMessageHook(fn func(handshake.MessageClientHello) handshake.Message) Option
- func WithConnectionID(generator func() []byte, policy CIDPathMigrationPolicy) Option
- func WithCustomCipherSuites(fn func() []cryptosuite.Suite) Option
- func WithDisableRetransmitBackoff(disable bool) Option
- func WithECH(opts ...ECHOption) Option
- func WithEllipticCurves(curves ...elliptic.Curve) Option
- func WithExtendedMasterSecret(ems ExtendedMasterSecretType) Option
- func WithFlightInterval(interval time.Duration) Option
- func WithGetClientCertificate(fn func(*CertificateRequestInfo) (*tls.Certificate, error)) Option
- func WithHelloRandomBytesGenerator(fn func() [handshake.RandomBytesLength]byte) Option
- func WithInsecureHashes(allow bool) Option
- func WithInsecureSkipVerify(skip bool) Option
- func WithKeyLogWriter(writer io.Writer) Option
- func WithLoggerFactory(factory logging.LoggerFactory) Option
- func WithMTU(mtu int) Option
- func WithMaxVersion(version protocol.Version) Option
- func WithMinVersion(version protocol.Version) Option
- func WithPSK(client PSKClientCallback, server PSKServerCallback, opts ...PSKOption) Option
- func WithPaddingLengthGenerator(fn func(uint) uint) Option
- func WithReceiveBufferSize(size int) Option
- func WithReplayProtectionWindow(window int) Option
- func WithRootCAs(pool *x509.CertPool) Option
- func WithSRTPMasterKeyIdentifier(identifier []byte) Option
- func WithSRTPProtectionProfiles(profiles ...SRTPProtectionProfile) Option
- func WithServerName(name string) Option
- func WithSessionStore(store SessionStore, opts ...SessionOption) Option
- func WithSignatureSchemes(schemes ...tls.SignatureScheme) Option
- func WithSupportedProtocols(protocols ...string) Option
- func WithVerifyConnection(fn func(*State) error) Option
- func WithVerifyPeerCertificate(fn func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error) Option
- type PSK
- type PSKClientCallback
- type PSKOption
- type PSKServerCallback
- type Path
- type Role
- type SRTPProtectionProfile
- type ServerOption
- func WithCertificateRequestMessageHook(fn func(handshake.Message) handshake.Message) ServerOption
- func WithClientAuth(auth ClientAuthType) ServerOption
- func WithClientCAs(pool *x509.CertPool) ServerOption
- func WithGetCertificate(fn func(*ClientHelloInfo) (*tls.Certificate, error)) ServerOption
- func WithInsecureSkipVerifyHello(skip bool) ServerOption
- func WithOnConnectionAttempt(fn func(net.Addr) error) ServerOption
- func WithServerHelloMessageHook(fn func(handshake.MessageServerHello) handshake.Message) ServerOption
- type Session
- type SessionOption
- type SessionStore
- type SessionTicket
- type State
- func (s *State) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error)
- func (s *State) MarshalBinary() ([]byte, error)
- func (s *State) NegotiatedVersion() protocol.Version
- func (s *State) RemoteRandomBytes() [handshake.RandomBytesLength]byte
- func (s *State) Role() Role
- func (s *State) UnmarshalBinary(data []byte) error
Constants ¶
This section is empty.
Variables ¶
var ErrConnClosed = dtlserrors.ErrConnClosed
ErrConnClosed indicates that the connection is closed.
Functions ¶
func Listen ¶
func Listen(conn net.PacketConn, opts ...ServerOption) (net.Listener, error)
Listen creates a DTLS listener over an existing packet connection.
func ListenAddr ¶
ListenAddr creates a DTLS listener bound to laddr.
func NewListener ¶
func NewListener(inner dtlsnet.PacketListener, opts ...ServerOption) (net.Listener, error)
NewListener creates a DTLS listener which accepts connections from an inner packet listener.
func OnlySendCIDGenerator ¶
func OnlySendCIDGenerator() func() []byte
OnlySendCIDGenerator enables sending Connection IDs negotiated with a peer, but indicates to the peer that sending Connection IDs in return is not necessary.
func RandomCIDGenerator ¶
RandomCIDGenerator is a random Connection ID generator where CID is the specified size. Specifying a size of 0 will indicate to peers that sending a Connection ID is not necessary.
Types ¶
type CIDPathMigrationPolicy ¶
type CIDPathMigrationPolicy uint8
CIDPathMigrationPolicy controls how connection IDs permit peer address changes.
const ( // CIDPathMigrationReject retains the current peer address and logs CID path // migration attempts. This is required when no reachability validation // strategy is configured // https://datatracker.ietf.org/doc/html/rfc9146#section-6 // https://datatracker.ietf.org/doc/html/rfc9147#section-11 CIDPathMigrationReject CIDPathMigrationPolicy = iota // CIDPathMigrationUnsafe immediately accepts an authenticated CID path. // It is intended only for transports, such as ICE, that validate paths // outside DTLS. CIDPathMigrationUnsafe // CIDPathMigrationRRC validates a CID path with return routability checks // before accepting it. RRC is advertised and negotiated only in this mode. // https://datatracker.ietf.org/doc/html/rfc9853 CIDPathMigrationRRC )
type CertificateRequestInfo ¶
type CertificateRequestInfo struct {
// CertificateTypes lists the certificate types accepted by the server.
// A nil slice indicates no restriction (DTLS 1.3).
CertificateTypes []clientcertificate.Type
// AcceptableCAs contains zero or more, DER-encoded, X.501
// Distinguished Names. These are the names of root or intermediate CAs
// that the server wishes the returned certificate to be signed by. An
// empty slice indicates that the server has no preference.
AcceptableCAs [][]byte
// SignatureSchemes lists the signature schemes that the server is
// willing to verify.
SignatureSchemes []tls.SignatureScheme
// contains filtered or unexported fields
}
CertificateRequestInfo contains information from a server's CertificateRequest message, which is used to demand a certificate and proof of control from a client.
func (*CertificateRequestInfo) SupportsCertificate ¶
func (cri *CertificateRequestInfo) SupportsCertificate(certificate *tls.Certificate) error
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. NOTE: original src: https://github.com/golang/go/blob/29b9a328d268d53833d2cc063d1d8b4bf6852675/src/crypto/tls/common.go#L1273
type ClientAuthType ¶
type ClientAuthType int
ClientAuthType declares the policy the server will follow for TLS Client Authentication.
const ( NoClientCert ClientAuthType = iota RequestClientCert RequireAnyClientCert VerifyClientCertIfGiven RequireAndVerifyClientCert )
ClientAuthType enums.
type ClientHelloInfo ¶
type ClientHelloInfo struct {
// ServerName indicates the name of the server requested by the client
// in order to support virtual hosting. ServerName is only set if the
// client is using SNI (see RFC 4366, Section 3.1).
ServerName string
// CipherSuites lists the CipherSuites supported by the client (e.g.
// TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
CipherSuites []cryptosuite.ID
// RandomBytes stores the client hello random bytes
RandomBytes [handshake.RandomBytesLength]byte
// The following offer fields are populated for WithECHGetKeys.
SupportedCurves []elliptic.Curve
SupportedPoints []elliptic.CurvePointFormat
SignatureSchemes []tls.SignatureScheme
SupportedProtos []string
SupportedVersions []protocol.Version
Extensions []extension.Type
HelloRetryRequest bool
// Conn identifies the DTLS connection. Do not read or write through it
// while the handshake callback is running.
Conn net.Conn
// contains filtered or unexported fields
}
ClientHelloInfo contains information from a ClientHello message in order to guide certificate and ECH key selection.
func (*ClientHelloInfo) Context ¶
func (c *ClientHelloInfo) Context() context.Context
Context returns the handshake context for ECH key selection. It is canceled when the handshake ends. Other callback paths currently return nil.
type ClientOption ¶
type ClientOption interface {
// contains filtered or unexported methods
}
ClientOption configures a DTLS client.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn represents a DTLS connection.
func Client ¶
func Client(conn net.PacketConn, raddr net.Addr, opts ...ClientOption) (*Conn, error)
Client establishes a DTLS connection over an existing packet connection.
func Resume ¶
Resume imports state returned by ExportState, directly or after serialization. ConnectionState snapshots and older serialized snapshots cannot be resumed. Resume consumes the state; serialized copies must not be reused, including in another process.
func Server ¶
func Server(conn net.PacketConn, raddr net.Addr, opts ...ServerOption) (*Conn, error)
Server establishes a server-side DTLS connection over an existing packet connection.
func (*Conn) AddPath ¶
func (c *Conn) AddPath(socket net.PacketConn) (*Path, error)
AddPath adds a dedicated, unconnected packet socket to an established DTLS 1.3 connection with a nonempty peer CID. CIDPathMigrationRRC requires negotiated RRC, CIDPathMigrationUnsafe allows switching without validation. The peer address stays unchanged. On success, the connection owns socket and closes it when the path or connection closes.
func (*Conn) ConnectionState ¶
ConnectionState returns basic DTLS details about the connection. During a handshake it returns the latest published handshake snapshot. Note that this replaced the `Export` function of v1.
func (*Conn) ExportState ¶
ExportState stops an established connection without close_notify, closes its transport, and returns the final state for Resume. Once shutdown begins the source cannot be used again, even if export fails. Resume exported state at most once across all processes and serialized copies.
func (*Conn) Handshake ¶
Handshake runs the client or server DTLS 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.
func (*Conn) HandshakeContext ¶
HandshakeContext runs the client or server DTLS 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. Connection read and write deadlines also apply to the corresponding handshake I/O, independently of the context deadline.
Most uses of this package need not call HandshakeContext explicitly: the first Conn.Read or Conn.Write will call it automatically.
func (*Conn) Read ¶
Read reads data from the connection. Before the handshake completes, Read also performs handshake reads and writes. Set both read and write deadlines (or use SetDeadline) to bound that I/O, or call HandshakeContext explicitly. Deadlines are not reset after the handshake.
func (*Conn) RemoteAddr ¶
RemoteAddr implements net.Conn.RemoteAddr.
func (*Conn) RemoteSRTPMasterKeyIdentifier ¶
RemoteSRTPMasterKeyIdentifier returns the MasterKeyIdentifier value from the use_srtp.
func (*Conn) SelectedSRTPProtectionProfile ¶
func (c *Conn) SelectedSRTPProtectionProfile() (SRTPProtectionProfile, bool)
SelectedSRTPProtectionProfile returns the selected SRTPProtectionProfile.
func (*Conn) SetDeadline ¶
SetDeadline implements net.Conn.SetDeadline.
func (*Conn) SetReadDeadline ¶
SetReadDeadline implements net.Conn.SetReadDeadline.
func (*Conn) SetWriteDeadline ¶
SetWriteDeadline implements net.Conn.SetWriteDeadline.
func (*Conn) UpdateKeys ¶
func (c *Conn) UpdateKeys(ctx context.Context, options KeyUpdateOptions) error
UpdateKeys requests a DTLS 1.3 application traffic-key update. It returns only after the peer acknowledges the KeyUpdate and the next local write generation has been committed.
func (*Conn) Write ¶
Write writes len(payload) bytes from payload to the DTLS connection. Before the handshake completes, Write also performs handshake reads and writes. Set both read and write deadlines (or use SetDeadline) to bound that I/O, or call HandshakeContext explicitly. Deadlines are not reset after the handshake.
type DetachedConn ¶
type DetachedConn struct {
// contains filtered or unexported fields
}
DetachedConn is a DTLS connection whose datagram transport is supplied by its caller. It remains active for application and post-handshake traffic. This API is inspired by crypto/tls.QUICConn, Start, HandleDatagram, Write, and Close must not be called concurrently with one another. EventReady may be selected concurrently. After a driving method returns, call NextEvent until it returns DetachedNoEvent.
func DetachedClient ¶
func DetachedClient(remoteAddr net.Addr, opts ...ClientOption) (*DetachedConn, error)
DetachedClient returns a new detached client connection. Call Start before supplying datagrams.
func DetachedServer ¶
func DetachedServer(remoteAddr net.Addr, opts ...ServerOption) (*DetachedConn, error)
DetachedServer returns a new detached server connection. Call Start before supplying datagrams.
func (*DetachedConn) Close ¶
func (c *DetachedConn) Close() error
Close closes the detached connection.
func (*DetachedConn) ConnectionState ¶
func (c *DetachedConn) ConnectionState() (State, bool)
ConnectionState returns the current DTLS connection state.
func (*DetachedConn) EventReady ¶
func (c *DetachedConn) EventReady() <-chan struct{}
EventReady is signaled when NextEvent may return an event and may be selected alongside transport input. Signals are coalesced It's the caller's responsibility to drain NextEvent until it returns DetachedNoEvent.
func (*DetachedConn) HandleDatagram ¶
func (c *DetachedConn) HandleDatagram(datagram []byte, addr net.Addr) error
HandleDatagram supplies one datagram received from addr and runs DTLS until it is blocked again. It may produce events. A nil addr uses the connection's current remote address. It does not retain datagram after returning.
func (*DetachedConn) NextEvent ¶
func (c *DetachedConn) NextEvent() DetachedEvent
NextEvent returns the next pending event, or DetachedNoEvent when the queue is empty.
func (*DetachedConn) RemoteSRTPMasterKeyIdentifier ¶
func (c *DetachedConn) RemoteSRTPMasterKeyIdentifier() ([]byte, bool)
RemoteSRTPMasterKeyIdentifier returns the peer's negotiated SRTP MKI.
func (*DetachedConn) SelectedSRTPProtectionProfile ¶
func (c *DetachedConn) SelectedSRTPProtectionProfile() (SRTPProtectionProfile, bool)
SelectedSRTPProtectionProfile returns the negotiated SRTP profile.
func (*DetachedConn) Start ¶
func (c *DetachedConn) Start(ctx context.Context) error
Start starts the handshake and runs it until it needs peer input. It may produce events and must be called at most once.
func (*DetachedConn) Write ¶
func (c *DetachedConn) Write(data []byte) (int, error)
Write encrypts plaintext application data and may produce events. The handshake must be complete.
func (*DetachedConn) WriteEarlyData ¶
func (c *DetachedConn) WriteEarlyData(data []byte) (int, error)
WriteEarlyData sends client application data before handshake completion, after DetachedEarlyDataReady. Early data may be replayed or rejected; a successful write does not imply server acceptance. Rejected data is not automatically resent.
type DetachedEvent ¶
type DetachedEvent struct {
Kind DetachedEventKind
Datagrams [][]byte
Data []byte
Addr net.Addr
Err error
}
DetachedEvent is an event produced by a DetachedConn. Fields are populated according to Kind. Its byte slices are owned by the caller.
type DetachedEventKind ¶
type DetachedEventKind uint8
DetachedEventKind identifies an event produced by a DetachedConn.
const ( // DetachedNoEvent indicates that no event is available. DetachedNoEvent DetachedEventKind = iota // DetachedWriteDatagrams provides one complete DTLS output batch in // Datagrams and its destination in Addr. DetachedWriteDatagrams // DetachedApplicationData provides plaintext received from the peer in Data. // Servers opting into early data may receive it before DetachedHandshakeDone. DetachedApplicationData // DetachedHandshakeDone indicates that the handshake has completed. DetachedHandshakeDone // DetachedClosed indicates that the connection has terminated with Err. DetachedClosed // DetachedEarlyDataReady indicates that the client may call WriteEarlyData. // 0-RTT only. DetachedEarlyDataReady // DetachedEarlyDataAccepted indicates that the server accepted the client's // early data. It does not indicate delivery or handshake completion. // 0-RTT only. DetachedEarlyDataAccepted // DetachedEarlyDataRejected indicates that the server rejected the client's // early data. The application decides whether to retry after the handshake. // 0-RTT only. DetachedEarlyDataRejected )
type ECHOption ¶
type ECHOption interface {
// contains filtered or unexported methods
}
ECHOption configures ECH-specific settings in WithECH.
func WithECHConfigList ¶
WithECHConfigList sets the client's encoded ECHConfigList. A nil list disables ECH. Unset version bounds default to DTLS 1.3. MinVersion must not be DTLS 1.2. Configs are validated during the handshake. Rejection returns ECHRejectionError,Early data uses the same session-ticket and replay policy as connections without ECH.
func WithECHGetKeys ¶
func WithECHGetKeys(fn func(*ClientHelloInfo) ([]EncryptedClientHelloKey, error)) ECHOption
WithECHGetKeys sets the server's ECH key callback, overriding WithECHKeys. It runs only when ECH is offered, receiving the outer ClientHello before decryption and again when preparing retry configurations after rejection. An error aborts the handshake. A nil callback uses the static keys.
func WithECHKeys ¶
func WithECHKeys(keys []EncryptedClientHelloKey) ECHOption
WithECHKeys sets the server's ECH keys. SendAsRetry selects configurations to include in ECH rejection. Unknown configuration versions are skipped during decryption. WithECHGetKeys overrides these keys.
func WithECHRejectionVerify ¶
WithECHRejectionVerify sets the client's ECH provider certificate verifier. It replaces normal certificate verification on rejection. A nil callback uses RootCAs and the ECH public name. VerifyPeerCertificate, VerifyConnection, and InsecureSkipVerify are ignored on rejection. An error aborts the handshake.
type ECHRejectionError ¶
type ECHRejectionError = ech.RejectionError
ECHRejectionError reports authenticated ECH rejection and retry configurations for a new connection. The rejected connection cannot carry application data.
type EarlyDataSessionStore ¶
type EarlyDataSessionStore interface {
SessionStore
Claim(ticket []byte, expiresAt time.Time) (bool, error)
}
EarlyDataSessionStore optionally supports replay-protected early data. Claim atomically marks a ticket used for early data, returning true only once. Claims must be shared across all servers using the tickets and retained until expiresAt, even if the session is updated or deleted. Claim preserves the session for ordinary resumption. Errors reject early data, not resumption.
type EncryptedClientHelloKey ¶
EncryptedClientHelloKey associates an encoded ECHConfig with its HPKE private key. SendAsRetry includes the configuration in authenticated ECH rejection.
type ExtendedMasterSecretType ¶
type ExtendedMasterSecretType int
ExtendedMasterSecretType declares the policy the client and server will follow for the Extended Master Secret extension.
const ( RequestExtendedMasterSecret ExtendedMasterSecretType = iota RequireExtendedMasterSecret DisableExtendedMasterSecret )
ExtendedMasterSecretType enums.
type KeyUpdateOptions ¶
type KeyUpdateOptions struct {
// RequestPeerUpdate asks the peer to update its sending keys in response.
RequestPeerUpdate bool
}
KeyUpdateOptions controls a DTLS 1.3 application traffic-key update.
type KeyUsageStats ¶
type KeyUsageStats struct {
WriteEpoch uint64
ReadEpoch uint64
SealedRecords uint64
AuthenticationFailures uint64
RecommendedLimits cryptosuite.UsageLimits
// Remaining counts are zero when unspecified or at/above the recommendation.
RemainingSealedRecords uint64
RemainingAuthenticationFailures uint64
}
KeyUsageStats reports usage of the current directional record keys. It excludes older keys retained for retransmissions. Counters restart for each new key. DTLS 1.3 connections can use Conn.UpdateKeys to rotate keys. Recommendations are advisory and do not affect the connection.
type Option ¶
type Option interface {
ServerOption
ClientOption
}
Option is an option that can be used with both client and server. This is used for options that apply to both sides of a connection, such as in the Resume function where the side is determined at runtime.
func WithCertificateSignatureSchemes ¶
func WithCertificateSignatureSchemes(schemes ...tls.SignatureScheme) Option
WithCertificateSignatureSchemes sets the signature and hash schemes that may be used in digital signatures for X.509 certificates. If not set, the signature_algorithms_cert extension is not sent, and SignatureSchemes is used for both handshake signatures and certificate chain validation, as specified in RFC 8446 Section 4.2.3. For functional options, an explicitly empty slice is not allowed.
func WithCertificates ¶
func WithCertificates(certs ...tls.Certificate) Option
WithCertificates sets the certificate chain to present to the other side of the connection. For functional options, an explicitly empty slice is not allowed.
func WithCipherSuites ¶
func WithCipherSuites(suites ...cryptosuite.ID) Option
WithCipherSuites sets the supported cipher suites. For functional options, an explicitly empty slice is not allowed.
func WithClientHelloMessageHook ¶
func WithClientHelloMessageHook(fn func(handshake.MessageClientHello) handshake.Message) Option
WithClientHelloMessageHook sets the client hello message hook. Returns an error if the hook is nil.
func WithConnectionID ¶
func WithConnectionID(generator func() []byte, policy CIDPathMigrationPolicy) Option
WithConnectionID enables connection IDs and configures how authenticated connection ID records may change the peer address. The generator must always return IDs of the same length, at most 255 bytes. A zero length advertises support for sending a peer's CID without asking the peer to send one in return.
func WithCustomCipherSuites ¶
func WithCustomCipherSuites(fn func() []cryptosuite.Suite) Option
WithCustomCipherSuites sets the custom cipher suites provider. Returns an error if the provider is nil.
func WithDisableRetransmitBackoff ¶
WithDisableRetransmitBackoff disables retransmit backoff.
func WithECH ¶
WithECH configures Encrypted Client Hello. Go 1.26 or newer is required. Client-only settings are ignored by servers, and server-only settings by clients.
func WithEllipticCurves ¶
WithEllipticCurves sets the elliptic curves in preference order. For functional options, an explicitly empty slice is not allowed. Clients default to X25519, X25519MLKEM768, P-256, P-384 and send a key share for the first. Servers, and clients with early data enabled, default to X25519MLKEM768, X25519, P-256, P-384.
func WithExtendedMasterSecret ¶
func WithExtendedMasterSecret(ems ExtendedMasterSecretType) Option
WithExtendedMasterSecret sets the extended master secret policy. Returns an error if the type is invalid.
func WithFlightInterval ¶
WithFlightInterval sets the flight interval for handshake messages. Returns an error if the interval is not positive.
func WithGetClientCertificate ¶
func WithGetClientCertificate(fn func(*CertificateRequestInfo) (*tls.Certificate, error)) Option
WithGetClientCertificate sets the client certificate getter callback. Returns an error if the callback is nil.
func WithHelloRandomBytesGenerator ¶
func WithHelloRandomBytesGenerator(fn func() [handshake.RandomBytesLength]byte) Option
WithHelloRandomBytesGenerator sets the hello random bytes generator. Returns an error if the generator is nil.
func WithInsecureHashes ¶
WithInsecureHashes allows the use of insecure hash algorithms.
func WithInsecureSkipVerify ¶
WithInsecureSkipVerify skips certificate verification. This should only be used for testing.
func WithKeyLogWriter ¶
WithKeyLogWriter sets the key log writer for debugging. Use of KeyLogWriter compromises security and should only be used for debugging.
func WithLoggerFactory ¶
func WithLoggerFactory(factory logging.LoggerFactory) Option
WithLoggerFactory sets the logger factory for creating loggers.
func WithMTU ¶
WithMTU sets the size used for handshake fragmentation and record packing. The default is 1200 bytes.
func WithMaxVersion ¶
WithMaxVersion sets the maximum DTLS version that is acceptable. By default, DTLS 1.3 is used as the maximum.
func WithMinVersion ¶
WithMinVersion sets the minimum DTLS version that is acceptable. By default, DTLS 1.2 is used as the minimum.
func WithPSK ¶
func WithPSK(client PSKClientCallback, server PSKServerCallback, opts ...PSKOption) Option
WithPSK sets the client offer and server lookup callbacks. The server accepts at most 32 identities per offer unless overridden by opts. A nil callback disables PSK for that role. Both callbacks may be nil.
func WithPaddingLengthGenerator ¶
WithPaddingLengthGenerator sets the padding length generator. Returns an error if the generator is nil.
func WithReceiveBufferSize ¶
WithReceiveBufferSize sets the size of the in-memory buffers used to read incoming datagrams. A datagram larger than this size cannot be received — depending on the transport it is truncated or rejected — so it must be at least as large as the largest datagram the peer may send. The default is 8192 bytes.
This does not change the kernel socket receive buffer (SO_RCVBUF); use net.UDPConn.SetReadBuffer for that. Returns an error if the buffer size is not positive or greater than the 65535.
func WithReplayProtectionWindow ¶
WithReplayProtectionWindow sets the replay protection window size. Returns an error if the window size is negative.
func WithRootCAs ¶
WithRootCAs sets the root certificate authorities.
func WithSRTPMasterKeyIdentifier ¶
WithSRTPMasterKeyIdentifier sets the SRTP master key identifier.
func WithSRTPProtectionProfiles ¶
func WithSRTPProtectionProfiles(profiles ...SRTPProtectionProfile) Option
WithSRTPProtectionProfiles sets the SRTP protection profiles. For functional options, an explicitly empty slice is not allowed.
func WithServerName ¶
WithServerName sets the server name for certificate verification.
func WithSessionStore ¶
func WithSessionStore(store SessionStore, opts ...SessionOption) Option
WithSessionStore sets the session store and options for resumption.
func WithSignatureSchemes ¶
func WithSignatureSchemes(schemes ...tls.SignatureScheme) Option
WithSignatureSchemes sets the signature schemes. For functional options, an explicitly empty slice is not allowed.
func WithSupportedProtocols ¶
WithSupportedProtocols sets the supported application protocols for ALPN. For functional options, an explicitly empty slice is not allowed.
func WithVerifyConnection ¶
WithVerifyConnection sets the connection verification callback. The callback also runs after Finished on resumed connections. Returns an error if the callback is nil.
func WithVerifyPeerCertificate ¶
func WithVerifyPeerCertificate(fn func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error) Option
WithVerifyPeerCertificate sets the peer certificate verification callback. Clients also call it on cached certificates before offering resumption. Rejection falls back to a full handshake, where the callback runs again on the newly received certificate. Accepted resumption calls it only once. Returns an error if the callback is nil.
type PSK ¶
type PSK struct {
Identity []byte
Key []byte
// Hash is the DTLS 1.3 PSK hash: crypto.SHA256 or crypto.SHA384.
// Zero defaults to crypto.SHA256. It does not select the DTLS 1.2 cipher hash.
Hash crypto.Hash
}
PSK is an external pre-shared key and its identity.
type PSKClientCallback ¶
PSKClientCallback supplies the client's PSKs once per connection. DTLS 1.3 offers all entries in order and DTLS 1.2 uses only the first. An error aborts the handshake. The callback does not receive a DTLS 1.2 server hint.
type PSKOption ¶
type PSKOption interface {
// contains filtered or unexported methods
}
PSKOption configures PSK-specific settings in WithPSK.
func WithPSKIdentityLimit ¶
WithPSKIdentityLimit sets the maximum number of identities accepted by the server. The limit must be positive. Offers exceeding it are rejected before the server callback.
type PSKServerCallback ¶
PSKServerCallback selects a PSK from the client's offered identities. The returned PSK must include an offered Identity, its Key, and Hash. Return nil, nil if none match. An error aborts the handshake. DTLS 1.2 supplies one identity. DTLS 1.3 may call again after a retry.
type Path ¶
type Path struct {
// contains filtered or unexported fields
}
Path is a local transport to the connection's current peer. Obtain one with Conn.AddPath, validate it with Path.Probe, then use Path.Switch to move application writes. With CIDPathMigrationUnsafe, Switch skips validation. All methods may be called concurrently.
func (*Path) Close ¶
Close releases an inactive path's socket and cancels any pending Probe. Closing the active path returns an error.
func (*Path) Probe ¶
Probe checks reachability using RRC, reserving a peer CID on the first call. Each call performs a new check and honors ctx and the write deadline. Probe requires CIDPathMigrationRRC, it is unavailable in unsafe mode. RRC validation takes at most one second after obtaining a CID. A failed check leaves application writes on the current path and requires a successful retry before switching.
func (*Path) Switch ¶
Switch makes this validated path the connection's application write path. It changes LocalAddr and the outgoing CID atomically with respect to writers. Existing sockets keep receiving until closed. The peer address must still match the address validated by Probe. With CIDPathMigrationUnsafe, Switch skips validation and reuses the active CID for a new path.
type SRTPProtectionProfile ¶
type SRTPProtectionProfile = extension.SRTPProtectionProfile
SRTPProtectionProfile defines the parameters and options that are in effect for the SRTP processing https://tools.ietf.org/html/rfc5764#section-4.1.2
const ( SRTP_AES128_CM_HMAC_SHA1_80 SRTPProtectionProfile = extension.SRTP_AES128_CM_HMAC_SHA1_80 // nolint: revive,staticcheck SRTP_AES128_CM_HMAC_SHA1_32 SRTPProtectionProfile = extension.SRTP_AES128_CM_HMAC_SHA1_32 // nolint: revive,staticcheck SRTP_AES256_CM_SHA1_80 SRTPProtectionProfile = extension.SRTP_AES256_CM_SHA1_80 // nolint: revive,staticcheck SRTP_AES256_CM_SHA1_32 SRTPProtectionProfile = extension.SRTP_AES256_CM_SHA1_32 // nolint: revive,staticcheck SRTP_NULL_HMAC_SHA1_80 SRTPProtectionProfile = extension.SRTP_NULL_HMAC_SHA1_80 // nolint: revive,staticcheck SRTP_NULL_HMAC_SHA1_32 SRTPProtectionProfile = extension.SRTP_NULL_HMAC_SHA1_32 // nolint: revive,staticcheck SRTP_AEAD_AES_128_GCM SRTPProtectionProfile = extension.SRTP_AEAD_AES_128_GCM // nolint: revive,staticcheck SRTP_AEAD_AES_256_GCM SRTPProtectionProfile = extension.SRTP_AEAD_AES_256_GCM // nolint: revive,staticcheck )
type ServerOption ¶
type ServerOption interface {
// contains filtered or unexported methods
}
ServerOption configures a DTLS server.
func WithCertificateRequestMessageHook ¶
func WithCertificateRequestMessageHook(fn func(handshake.Message) handshake.Message) ServerOption
WithCertificateRequestMessageHook sets the certificate request message hook for DTLS 1.2 and 1.3. The hook receives a *dtls12.MessageCertificateRequest or *dtls13.MessageCertificateRequest. The returned handshake message replaces the original message. Returns an error if the hook is nil. This option is only applicable to servers.
func WithClientAuth ¶
func WithClientAuth(auth ClientAuthType) ServerOption
WithClientAuth sets the client authentication policy. Returns an error if the type is invalid. This option is only applicable to servers.
func WithClientCAs ¶
func WithClientCAs(pool *x509.CertPool) ServerOption
WithClientCAs sets the client certificate authorities. This option is only applicable to servers.
func WithGetCertificate ¶
func WithGetCertificate(fn func(*ClientHelloInfo) (*tls.Certificate, error)) ServerOption
WithGetCertificate sets the certificate getter callback. Returns an error if the callback is nil. This option is only applicable to servers.
func WithInsecureSkipVerifyHello ¶
func WithInsecureSkipVerifyHello(skip bool) ServerOption
WithInsecureSkipVerifyHello skips hello verify phase on the server. This has implication on DoS attack resistance. This option is only applicable to servers.
func WithOnConnectionAttempt ¶
func WithOnConnectionAttempt(fn func(net.Addr) error) ServerOption
WithOnConnectionAttempt sets the connection attempt callback. Returns an error if the callback is nil. This option is only applicable to servers.
func WithServerHelloMessageHook ¶
func WithServerHelloMessageHook(fn func(handshake.MessageServerHello) handshake.Message) ServerOption
WithServerHelloMessageHook sets the server hello message hook for DTLS 1.2 and 1.3. For DTLS 1.3, the hook is also called for HelloRetryRequest. It must preserve the selected version, cipher suite, key share, PSK identity, and retry cookie. Returns an error if the hook is nil. This option is only applicable to servers.
type Session ¶
type Session struct {
// ID stores a DTLS 1.2 session ID or a DTLS 1.3 ticket identity.
ID []byte
// Secret stores a DTLS 1.2 master secret or a DTLS 1.3 resumption PSK.
Secret []byte //nolint:gosec // Session stores intentionally retain the resumption secret.
// Ticket is non-nil for DTLS 1.3 sessions.
Ticket *SessionTicket
// Version identifies entries with authentication and negotiation metadata.
// Legacy entries without this metadata require a full handshake.
Version uint8
// IsClient binds the session to the endpoint role that authenticated it.
IsClient bool
// The following fields retain negotiation and authentication state.
CipherSuiteID cryptosuite.ID
ExtendedMasterSecret bool
PeerCertificates [][]byte
IdentityHint []byte // Original PSK identity, including for DTLS 1.3 tickets.
PSKHash [sha256.Size]byte
}
Session store data needed in resumption.
type SessionOption ¶
type SessionOption interface {
// contains filtered or unexported methods
}
SessionOption configures session-specific settings in WithSessionStore.
func WithMaxEarlyDataSize ¶
func WithMaxEarlyDataSize(size uint32) SessionOption
WithMaxEarlyDataSize opts detached connections into early data. Servers advertise this limit in new session tickets; clients may offer early data using cached tickets. Zero (the default) disables early data. A nonzero size requires a store implementing EarlyDataSessionStore. Use inside WithSessionStore.
type SessionStore ¶
type SessionStore interface {
// Set save a session.
// For client, use server name as key.
// For server, use session id.
Set(key []byte, s Session) error
// Get fetch a session.
Get(key []byte) (Session, error)
// Del clean saved session.
Del(key []byte) error
}
SessionStore defines methods needed for session resumption. Stores must preserve every Session field, including authentication metadata. Entries containing only an ID and Secret require a full handshake.
type SessionTicket ¶
type SessionTicket = dtlsstate.SessionTicket
SessionTicket contains the metadata needed to use a DTLS 1.3 ticket.
type State ¶
type State struct {
CipherSuiteID cryptosuite.ID
PeerCertificates [][]byte
IdentityHint []byte
SessionID []byte
NegotiatedProtocol string
// ServerName is the negotiated SNI, or the public name during ECH rejection verification.
ServerName string
// ECHAccepted reports whether ECH was negotiated successfully.
ECHAccepted bool
// KeyUsage is the current record keys' usage.
KeyUsage *KeyUsageStats
// contains filtered or unexported fields
}
State holds the dtls connection state and implements both encoding.BinaryMarshaler and encoding.BinaryUnmarshaler.
func (*State) ExportKeyingMaterial ¶
ExportKeyingMaterial returns length bytes of exported key material in a new slice as defined in https://www.rfc-editor.org/rfc/rfc5705.html#section-4 for DTLS 1.2 and https://www.rfc-editor.org/rfc/rfc8446.html#section-7.5 for DTLS 1.3. This allows protocols to use DTLS for key establishment, but then use some of the keying material for their own purposes.
func (*State) MarshalBinary ¶
MarshalBinary serializes a snapshot without affecting the source connection. Only state returned by ExportState can be resumed. Resume exported state at most once across all processes and serialized copies.
func (*State) NegotiatedVersion ¶
NegotiatedVersion returns the DTLS version negotiated for this connection.
func (*State) RemoteRandomBytes ¶
func (s *State) RemoteRandomBytes() [handshake.RandomBytesLength]byte
RemoteRandomBytes returns the remote client hello random bytes.
func (*State) UnmarshalBinary ¶
UnmarshalBinary is a binary.BinaryUnmarshaler.UnmarshalBinary implementation.
Validate decoded state for both protocol versions.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
dial/cid
command
Package main implements an example DTLS client using a pre-shared key.
|
Package main implements an example DTLS client using a pre-shared key. |
|
dial/psk
command
Package main implements an example DTLS client using a pre-shared key.
|
Package main implements an example DTLS client using a pre-shared key. |
|
dial/selfsign
command
Package main implements a DTLS client using self-signed certificates.
|
Package main implements a DTLS client using self-signed certificates. |
|
dial/verify
command
Package main implements a DTLS client using a client certificate.
|
Package main implements a DTLS client using a client certificate. |
|
listen/cid
command
Package main implements a DTLS server using a pre-shared key.
|
Package main implements a DTLS server using a pre-shared key. |
|
listen/psk
command
Package main implements a DTLS server using a pre-shared key.
|
Package main implements a DTLS server using a pre-shared key. |
|
listen/selfsign
command
Package main implements an example DTLS server using self-signed certificates.
|
Package main implements an example DTLS server using self-signed certificates. |
|
listen/verify
command
Package main implements an example DTLS server which verifies client certificates.
|
Package main implements an example DTLS server which verifies client certificates. |
|
listen/verify-brute-force-protection
command
Package main implements an example DTLS server which verifies client certificates.
|
Package main implements an example DTLS server which verifies client certificates. |
|
resumption-dtls13
command
Package main demonstrates DTLS resumption and optional client 0-RTT.
|
Package main demonstrates DTLS resumption and optional client 0-RTT. |
|
util
Package util provides auxiliary utilities used in examples
|
Package util provides auxiliary utilities used in examples |
|
internal
|
|
|
ciphersuite
Package ciphersuite provides TLS ciphers as registered with IANA.
|
Package ciphersuite provides TLS ciphers as registered with IANA. |
|
clienthello
Package clienthello parses DTLS ClientHello framing.
|
Package clienthello parses DTLS ClientHello framing. |
|
closer
Package closer provides signaling channel for shutdown
|
Package closer provides signaling channel for shutdown |
|
config
Package config contains internal handshake configuration.
|
Package config contains internal handshake configuration. |
|
ech
Package ech implements wire and cryptographic helpers for https://www.rfc-editor.org/rfc/rfc9849.
|
Package ech implements wire and cryptographic helpers for https://www.rfc-editor.org/rfc/rfc9849. |
|
errors
Package errors centralizes internal DTLS error values.
|
Package errors centralizes internal DTLS error values. |
|
flight
Package flight contains shared internal flight state and helpers.
|
Package flight contains shared internal flight state and helpers. |
|
flight/flight12
Package flight12 contains DTLS 1.2 flight handlers.
|
Package flight12 contains DTLS 1.2 flight handlers. |
|
flight/flight13
Package flight13 contains DTLS 1.3 flight handlers.
|
Package flight13 contains DTLS 1.3 flight handlers. |
|
fragmentbuffer
Package fragmentbuffer reassembles fragmented DTLS handshake messages.
|
Package fragmentbuffer reassembles fragmented DTLS handshake messages. |
|
handshake
Package dtlshandshake contains DTLS handshake FSM, transcript, and key schedule helpers.
|
Package dtlshandshake contains DTLS handshake FSM, transcript, and key schedule helpers. |
|
handshakecrypto
Package handshakecrypto contains internal handshake cryptography helpers.
|
Package handshakecrypto contains internal handshake cryptography helpers. |
|
handshakewire
Package handshakewire provides shared handshake types and extension decoding.
|
Package handshakewire provides shared handshake types and extension decoding. |
|
negotiation
Package negotiation finalizes ClientHello offers and validates handshake negotiation against them.
|
Package negotiation finalizes ClientHello offers and validates handshake negotiation against them. |
|
net
Package net implements DTLS specific networking primitives.
|
Package net implements DTLS specific networking primitives. |
|
net/udp
Package udp implements DTLS specific UDP networking primitives.
|
Package udp implements DTLS specific UDP networking primitives. |
|
recordwire
Package recordwire supplies shared header layout for framing and protection.
|
Package recordwire supplies shared header layout for framing and protection. |
|
rrc
Package rrc implements RFC 9853 path validation and amplification accounting.
|
Package rrc implements RFC 9853 path validation and amplification accounting. |
|
state
Package state holds the internal DTLS connection state used during and after the handshake.
|
Package state holds the internal DTLS connection state used during and after the handshake. |
|
util
Package util contains small helpers used across the repo
|
Package util contains small helpers used across the repo |
|
pkg
|
|
|
crypto/ccm
Package ccm implements a CCM, Counter with CBC-MAC as per RFC 3610.
|
Package ccm implements a CCM, Counter with CBC-MAC as per RFC 3610. |
|
crypto/ciphersuite
Package ciphersuite defines cipher-suite descriptors, immutable record metadata, protection capabilities, and DTLS record-protection contracts.
|
Package ciphersuite defines cipher-suite descriptors, immutable record metadata, protection capabilities, and DTLS record-protection contracts. |
|
crypto/clientcertificate
Package clientcertificate provides all the support Client Certificate types
|
Package clientcertificate provides all the support Client Certificate types |
|
crypto/elliptic
Package elliptic provides elliptic curve cryptography for DTLS
|
Package elliptic provides elliptic curve cryptography for DTLS |
|
crypto/fingerprint
Package fingerprint provides a helper to create fingerprint string from certificate
|
Package fingerprint provides a helper to create fingerprint string from certificate |
|
crypto/hash
Package hash provides TLS HashAlgorithm as defined in TLS 1.2
|
Package hash provides TLS HashAlgorithm as defined in TLS 1.2 |
|
crypto/keyschedule
Package keyschedule implements DTLS 1.3's key derivation related functions
|
Package keyschedule implements DTLS 1.3's key derivation related functions |
|
crypto/prf
Package prf implements TLS 1.2 Pseudorandom functions
|
Package prf implements TLS 1.2 Pseudorandom functions |
|
crypto/selfsign
Package selfsign is a test helper that generates self signed certificate.
|
Package selfsign is a test helper that generates self signed certificate. |
|
crypto/signature
Package signature provides our implemented Signature Algorithms
|
Package signature provides our implemented Signature Algorithms |
|
crypto/signaturehash
Package signaturehash provides the SignatureHashAlgorithm as defined in TLS 1.2
|
Package signaturehash provides the SignatureHashAlgorithm as defined in TLS 1.2 |
|
net
Package net defines packet-oriented primitives that are compatible with net in the standard library.
|
Package net defines packet-oriented primitives that are compatible with net in the standard library. |
|
protocol
Package protocol provides the DTLS wire format
|
Package protocol provides the DTLS wire format |
|
protocol/alert
Package alert implements TLS alert protocol https://tools.ietf.org/html/rfc5246#section-7.2
|
Package alert implements TLS alert protocol https://tools.ietf.org/html/rfc5246#section-7.2 |
|
protocol/extension
Package extension provides TLS extension framing and payload codecs.
|
Package extension provides TLS extension framing and payload codecs. |
|
protocol/extension/dtls12
Package dtls12 implements extension payloads specific to DTLS 1.2.
|
Package dtls12 implements extension payloads specific to DTLS 1.2. |
|
protocol/extension/dtls13
Package dtls13 implements extension payloads specific to DTLS 1.3.
|
Package dtls13 implements extension payloads specific to DTLS 1.3. |
|
protocol/handshake
Package handshake provides the DTLS wire protocol for handshakes
|
Package handshake provides the DTLS wire protocol for handshakes |
|
protocol/handshake/dtls12
Package dtls12 implements certificate message wire formats for DTLS 1.2.
|
Package dtls12 implements certificate message wire formats for DTLS 1.2. |
|
protocol/handshake/dtls13
Package dtls13 implements certificate message wire formats for DTLS 1.3.
|
Package dtls13 implements certificate message wire formats for DTLS 1.3. |
|
protocol/recordlayer
Package recordlayer frames, inspects, and encodes DTLS wire records.
|
Package recordlayer frames, inspects, and encodes DTLS wire records. |