dtls

package module
v4.0.0-rc.3 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: MIT Imports: 55 Imported by: 3

README


Pion DTLS

A Go implementation of DTLS

Pion DTLS Sourcegraph Widget join us on Discord Follow us on Bluesky
GitHub Workflow Status Go Reference Coverage Status Go Report Card


Native DTLS 1.2 and DTLS 1.3 implementation in the Go programming language.

A long term goal is a professional security review, and maybe an inclusion in stdlib.

[!WARNING] This branch is currently frozen from tagging while DTLS 1.3 work is underway.

DTLS 1.3 and breaking changes should target the main branch. Bug fixes and DTLS 1.2 improvments should target the v3 branch, which can be used for tags until DTLS 1.3 is ready.

RFCs

Implemented

Features

Pion DTLS supports DTLS 1.2 and DTLS 1.3. We welcome contributions and bug fixes.

Current features

  • DTLS 1.2 and DTLS 1.3 client/server
  • Key Exchange via ECDHE(curve25519, nistp256, nistp384) and PSK
  • Packet loss and re-ordering is handled during handshaking
  • Key export (RFC 5705)
  • DTLS 1.2 session serialization and resumption
  • Extended Master Secret extension (RFC 7627)
  • ALPN extension (RFC 7301)

Supported ciphers

DTLS 1.3
DTLS 1.2: ECDHE
  • TLS_ECDHE_ECDSA_WITH_AES_128_CCM (RFC 6655)
  • TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 (RFC 6655)
  • TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 (RFC 5289)
  • TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (RFC 5289)
  • TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 (RFC 5289)
  • TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (RFC 5289)
  • TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA (RFC 8422)
  • TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (RFC 8422)
  • TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 (RFC 7905)
  • TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (RFC 7905)
DTLS 1.2: PSK
  • TLS_PSK_WITH_AES_128_CCM (RFC 6655)
  • TLS_PSK_WITH_AES_128_CCM_8 (RFC 6655)
  • TLS_PSK_WITH_AES_256_CCM_8 (RFC 6655)
  • TLS_PSK_WITH_AES_128_GCM_SHA256 (RFC 5487)
  • TLS_PSK_WITH_AES_128_CBC_SHA256 (RFC 5487)
  • TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 (RFC 7905)
DTLS 1.2: ECDHE & PSK
  • TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 (RFC 5489)

Excluded Features

  • DTLS 1.0
  • Renegotiation
  • Compression

Pion DTLS

For a DTLS 1.2 Server that listens on 127.0.0.1:4444

go run examples/listen/selfsign/main.go

For a DTLS 1.2 Client that connects to 127.0.0.1:4444

go run examples/dial/selfsign/main.go

OpenSSL

Pion DTLS can connect to itself and OpenSSL.

  // Generate a certificate
  openssl ecparam -out key.pem -name prime256v1 -genkey
  openssl req -new -sha256 -key key.pem -out server.csr
  openssl x509 -req -sha256 -days 365 -in server.csr -signkey key.pem -out cert.pem

  // Use with examples/dial/selfsign/main.go
  openssl s_server -dtls1_2 -cert cert.pem -key key.pem -accept 4444

  // Use with examples/listen/selfsign/main.go
  openssl s_client -dtls1_2 -connect 127.0.0.1:4444 -debug -cert cert.pem -key key.pem

Using with PSK

Pion DTLS also comes with examples that do key exchange via DTLS 1.2 PSK.

Pion DTLS

go run examples/listen/psk/main.go
go run examples/dial/psk/main.go

OpenSSL

  // Use with examples/dial/psk/main.go
  openssl s_server -dtls1_2 -accept 4444 -nocert -psk abc123 -cipher PSK-AES128-CCM8

  // Use with examples/listen/psk/main.go
  openssl s_client -dtls1_2 -connect 127.0.0.1:4444 -psk abc123 -cipher PSK-AES128-CCM8

Community

Pion has an active community on the Discord.

Follow the Pion Bluesky or Pion Twitter for project updates and important WebRTC news.

We are always looking to support your projects. Please reach out if you have something to build! If you need commercial support or don't want to use public methods you can contact us at team@pion.ly

Contributing

Check out the contributing wiki to join the group of amazing people making this project possible

Funding

NLnet foundation logo NLnet foundation logo

The DTLS 1.3 implementation in this project is funded through the NGI0 Commons Fund, a fund established by NLnet with financial support from the European Commission's Next Generation Internet programme, under the aegis of DG Communications Networks, Content and Technology under grant agreement No 101135429. Additional funding is made available by the Swiss State Secretariat for Education, Research and Innovation (SERI). Learn more on the NLnet project page.

License

MIT License - see LICENSE for full text

Documentation

Overview

Package dtls implements Datagram Transport Layer Security (DTLS) 1.2 and 1.3.

Index

Constants

View Source
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
)

Variables

View Source
var ErrConnClosed = dtlserrors.ErrConnClosed

ErrConnClosed indicates that the connection is closed.

View Source
var ErrStateSerializationUnsupported = errors.New("dtls: state serialization unsupported for this protocol version") //nolint:gochecknoglobals

ErrStateSerializationUnsupported indicates that the negotiated DTLS version cannot be represented by the public DTLS 1.2-shaped State snapshot.

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

func ListenAddr(network string, laddr *net.UDPAddr, opts ...ServerOption) (net.Listener, error)

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

func RandomCIDGenerator(size int) func() []byte

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 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
}

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
}

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

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 Dial

func Dial(network string, rAddr *net.UDPAddr, opts ...ClientOption) (*Conn, error)

Dial connects to the given network address and establishes a DTLS connection on top.

func Resume

func Resume(state *State, conn net.PacketConn, rAddr net.Addr, opts ...Option) (*Conn, error)

Resume imports an already established dtls connection using a specific dtls state.

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) Close

func (c *Conn) Close() error

Close closes the connection.

func (*Conn) ConnectionState

func (c *Conn) ConnectionState() (State, bool)

ConnectionState returns basic DTLS details about the connection. Note that this replaced the `Export` function of v1.

func (*Conn) Handshake

func (c *Conn) Handshake() error

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

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

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.

Most uses of this package need not call HandshakeContext explicitly: the first Conn.Read or Conn.Write will call it automatically.

func (*Conn) LocalAddr

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

LocalAddr implements net.Conn.LocalAddr.

func (*Conn) Read

func (c *Conn) Read(buff []byte) (n int, err error)

Read reads data from the connection.

func (*Conn) RemoteAddr

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

RemoteAddr implements net.Conn.RemoteAddr.

func (*Conn) RemoteSRTPMasterKeyIdentifier

func (c *Conn) RemoteSRTPMasterKeyIdentifier() ([]byte, bool)

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

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

SetDeadline implements net.Conn.SetDeadline.

func (*Conn) SetReadDeadline

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

SetReadDeadline implements net.Conn.SetReadDeadline.

func (*Conn) SetWriteDeadline

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

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

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

Write writes len(payload) bytes from payload to the DTLS connection.

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.

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.
	DetachedApplicationData
	// DetachedHandshakeDone indicates that the handshake has completed.
	DetachedHandshakeDone
	// DetachedClosed indicates that the connection has terminated with Err.
	DetachedClosed
)

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

func WithDisableRetransmitBackoff(disable bool) Option

WithDisableRetransmitBackoff disables retransmit backoff.

func WithEllipticCurves

func WithEllipticCurves(curves ...elliptic.Curve) Option

WithEllipticCurves sets the elliptic curves. For functional options, an explicitly empty slice is not allowed.

func WithExtendedMasterSecret

func WithExtendedMasterSecret(ems ExtendedMasterSecretType) Option

WithExtendedMasterSecret sets the extended master secret policy. Returns an error if the type is invalid.

func WithFlightInterval

func WithFlightInterval(interval time.Duration) Option

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

func WithInsecureHashes(allow bool) Option

WithInsecureHashes allows the use of insecure hash algorithms.

func WithInsecureSkipVerify

func WithInsecureSkipVerify(skip bool) Option

WithInsecureSkipVerify skips certificate verification. This should only be used for testing.

func WithKeyLogWriter

func WithKeyLogWriter(writer io.Writer) Option

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

func WithMTU(mtu int) Option

WithMTU sets the size used for handshake fragmentation and record packing. The default is 1200 bytes.

func WithMaxVersion

func WithMaxVersion(version protocol.Version) Option

WithMaxVersion sets the maximum TLS version that is acceptable. By default, DTLS 1.2 is currently used as the maximum.

func WithMinVersion

func WithMinVersion(version protocol.Version) Option

WithMinVersion sets the minimum TLS version that is acceptable. By default, DTLS 1.2 is currently used as the minimum as it's the only supported version.

func WithPSK

func WithPSK(callback PSKCallback) Option

WithPSK sets the pre-shared key callback. Returns an error if the callback is nil.

func WithPSKIdentityHint

func WithPSKIdentityHint(hint []byte) Option

WithPSKIdentityHint sets the PSK identity hint.

func WithPaddingLengthGenerator

func WithPaddingLengthGenerator(fn func(uint) uint) Option

WithPaddingLengthGenerator sets the padding length generator. Returns an error if the generator is nil.

func WithReceiveBufferSize

func WithReceiveBufferSize(size int) Option

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

func WithReplayProtectionWindow(window int) Option

WithReplayProtectionWindow sets the replay protection window size. Returns an error if the window size is negative.

func WithRootCAs

func WithRootCAs(pool *x509.CertPool) Option

WithRootCAs sets the root certificate authorities.

func WithSRTPMasterKeyIdentifier

func WithSRTPMasterKeyIdentifier(identifier []byte) Option

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

func WithServerName(name string) Option

WithServerName sets the server name for certificate verification.

func WithSessionStore

func WithSessionStore(store SessionStore) Option

WithSessionStore sets the session store 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

func WithSupportedProtocols(protocols ...string) Option

WithSupportedProtocols sets the supported application protocols for ALPN. For functional options, an explicitly empty slice is not allowed.

func WithVerifyConnection

func WithVerifyConnection(fn func(*State) error) Option

WithVerifyConnection sets the connection verification callback. 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. Returns an error if the callback is nil.

type PSKCallback

type PSKCallback func([]byte) ([]byte, error)

PSKCallback is called once we have the remote's PSKIdentityHint. If the remote provided none it will be nil.

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

func (p *Path) Close() error

Close releases an inactive path's socket and cancels any pending Probe. Closing the active path returns an error.

func (*Path) Probe

func (p *Path) Probe(ctx context.Context) error

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

func (p *Path) Switch() error

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 Role

type Role uint8

Role indicates which side of the DTLS handshake an endpoint took.

const (
	// RoleUnknown is the zero value, used when the role is not yet resolved.
	RoleUnknown Role = iota
	// RoleClient is the endpoint that sends the ClientHello.
	RoleClient
	// RoleServer is the endpoint that answers with the ServerHello.
	RoleServer
)

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.MessageCertificateRequest) handshake.Message) ServerOption

WithCertificateRequestMessageHook sets the certificate request message hook. 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. Returns an error if the hook is nil. This option is only applicable to servers.

type Session

type Session struct {
	// ID store session id
	ID []byte
	// Secret store session master secret
	Secret []byte //nolint:gosec // no real risk of exporting the secret.
}

Session store data needed in resumption.

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.

type State

type State struct {
	CipherSuiteID      cryptosuite.ID
	PeerCertificates   [][]byte
	IdentityHint       []byte
	SessionID          []byte
	NegotiatedProtocol string
	// 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

func (s *State) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error)

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

func (s *State) MarshalBinary() ([]byte, error)

MarshalBinary is a binary.BinaryMarshaler.MarshalBinary implementation.

func (*State) NegotiatedVersion

func (s *State) NegotiatedVersion() protocol.Version

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) Role

func (s *State) Role() Role

Role reports which side of the handshake the local endpoint took.

func (*State) UnmarshalBinary

func (s *State) UnmarshalBinary(data []byte) error

UnmarshalBinary is a binary.BinaryUnmarshaler.UnmarshalBinary implementation.

Directories

Path Synopsis
Package e2e contains end to end tests for pion/dtls
Package e2e contains end to end tests for pion/dtls
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.
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.
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.
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.
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/recordlayer
Package recordlayer frames, inspects, and encodes DTLS wire records.
Package recordlayer frames, inspects, and encodes DTLS wire records.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL