state

package
v4.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package state holds the internal DTLS connection state used during and after the handshake.

Index

Constants

View Source
const MaxConnectionIDs = 32

MaxConnectionIDs bounds both retained local aliases and peer spare IDs. Issued aliases remain valid until close; reaching the limit stops issuance. the spec doesn't specify a limit, 32 is a reasonable default for the pion implementation, this limit should be configurable in the future.

Variables

This section is empty.

Functions

func HandshakeRecvSequence

func HandshakeRecvSequence(active Active) int

func NextHandshakeSendSequence

func NextHandshakeSendSequence(active Active) uint16

Types

type Active

type Active interface {
	CommonFields() *Common
	ShouldWrapConnectionID() bool
}

Active is a concrete DTLS version state that shares common connection fields.

func NewActive

func NewActive(isClient bool) Active

NewActive creates a DTLS 1.2 active state with initialized common fields.

type CIDReceiveSet

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

CIDReceiveSet CID bytes and membership checks.

func (*CIDReceiveSet) Add

func (s *CIDReceiveSet) Add(cid []byte)

Add copies cid into the accepted set.

func (*CIDReceiveSet) Clear

func (s *CIDReceiveSet) Clear()

Clear releases all accepted IDs.

func (*CIDReceiveSet) Clone

func (s *CIDReceiveSet) Clone() *CIDReceiveSet

Clone returns an independent snapshot for certificate verification.

func (*CIDReceiveSet) Contains

func (s *CIDReceiveSet) Contains(cid []byte) bool

Contains reports whether cid is accepted on inbound records.

func (*CIDReceiveSet) Len

func (s *CIDReceiveSet) Len() int

Len reports the number of accepted local IDs.

func (*CIDReceiveSet) Remove

func (s *CIDReceiveSet) Remove(cid []byte)

Remove stops accepting cid.

func (*CIDReceiveSet) Values

func (s *CIDReceiveSet) Values() [][]byte

Values returns owned copies of the accepted connection IDs.

type CIDReceiveState

type CIDReceiveState struct {
	// IDs contains accepted local CIDs.
	IDs *CIDReceiveSet
	// Expected reports whether protected peer datagrams must contain a CID.
	// CID-less unified records are allowed alongside a CID-carrying record.
	// Epoch-zero plaintext records have no CID field.
	Expected bool
	// Length is the number of CID bytes to parse after the C bit. DTLS 1.3
	// records do not encode this lengt
	Length int
	// CanSendNewConnectionID reports whether this endpoint may send
	// NewConnectionID. RFC 9147, Section 9 forbids that message when this
	// endpoint negotiated receiving an empty CID.
	CanSendNewConnectionID bool
}

CIDReceiveState describes locally generated CIDs carried in protected records sent by the peer.

type CIDSendState

type CIDSendState struct {
	// Spares owns peer IDs available for future selection, in issuance order.
	Spares [][]byte
	// UseCID reports whether records sent to the peer must set the C bit in the
	// DTLS 1.3 unified header and carry Active.
	UseCID bool
	// Active is the peer-provided CID currently used for outgoing records. It
	// may diverge from Common.RemoteConnectionID after NewConnectionID.
	Active []byte
}

CIDSendState describes peer-generated CIDs carried in protected records sent by this endpoint.

func (CIDSendState) Clone

func (s CIDSendState) Clone() CIDSendState

Clone returns an independent copy of the peer's active and spare connection IDs.

type CIDState

type CIDState struct {
	// Negotiated reports whether the connection_id extension was negotiated,
	// including when one or both endpoints advertised a zero-length CID.
	Negotiated bool
	// Receive controls parsing and updating CIDs carried by the peer.
	Receive CIDReceiveState
	// Send controls encoding and updating CIDs carried by this endpoint.
	Send CIDSendState
}

CIDState holds connection ID state negotiated for DTLS 1.3. RFC 9147 reuses the connection_id extension [1] and its directional semantics from RFC 9146, Section 3 [2], and defines the DTLS 1.3 record encoding and CID update messages in Sections 4.3 [3].

Each endpoint advertises the CID it wants to receive: Receive describes locally generated CIDs carried by the peer, while Send describes peer-generated CIDs carried by this endpoint. A present, zero-length connection_id extension still negotiates CID support, but disables CIDs in that direction. Negotiated must not be inferred from either CID length. [4]

The initial CID values remain in Common so a dual-stack ClientHello can be handed to DTLS 1.2 without losing its offer. The directional state here is separate because an active DTLS 1.3 CID can later change through the messages defined by RFC 9147, Section 9 [1].

1. https://datatracker.ietf.org/doc/html/rfc9147#section-9 2. https://datatracker.ietf.org/doc/html/rfc9146.html#section-3 3. https://datatracker.ietf.org/doc/html/rfc9147#section-4 4. https://datatracker.ietf.org/doc/html/rfc9146.html#section-3

type Common

type Common struct {
	LocalSequenceNumber  map[uint64]uint64
	RemoteSequenceNumber map[uint64]uint64

	LocalRandom, RemoteRandom handshake.Random
	CipherSuite               cryptosuite.Suite // nil if a cipherSuite hasn't been chosen
	PeerCertificates          [][]byte
	IdentityHint              []byte
	SessionID                 []byte
	NegotiatedProtocol        string

	RemoteSRTPMasterKeyIdentifier []byte

	// LocalCIDOffered reports whether the local endpoint sent a connection_id
	// extension.
	LocalCIDOffered bool
	// RemoteConnectionID is the connection ID that the remote endpoint
	// specifies should be sent.
	// For a server, this is the connection ID received in the ClientHello.
	// For a client, this is the connection ID received in the ServerHello.
	RemoteConnectionID []byte
	// RemoteCIDOffered reports whether the peer sent a connection_id
	// extension.
	RemoteCIDOffered bool
	// RRCNegotiated reports whether both peers exchanged the RFC 9853
	// extension. The negotiation is shared by DTLS 1.2 and DTLS 1.3.
	RRCNegotiated bool

	IsClient bool

	ServerName  string
	ECHAccepted bool

	ReplayDetector map[uint64]replaydetector.ReplayDetector

	PeerSupportedProtocols []string

	// LocalVersion is the DTLS version we intend to speak on this connection.
	LocalVersion protocol.Version
	// RemoteVersions are the DTLS versions advertised by the peer.
	RemoteVersions []protocol.Version

	// ClientHello snapshots are transient negotiation state.
	// they aren't serialized with resumable connection state.
	LocalClientHelloSnapshots  negotiation.ClientHelloSnapshots
	RemoteClientHelloSnapshots negotiation.ClientHelloSnapshots
	// contains filtered or unexported fields
}

Common is the protocol-independent connection state shared by DTLS versions.

func CommonState

func CommonState(active Active) *Common

CommonState returns the common state shared by an active DTLS version state.

func (*Common) AllocateLocalSequenceNumber

func (s *Common) AllocateLocalSequenceNumber(epoch, limit uint64) (uint64, error)

AllocateLocalSequenceNumber reserves a sequence number without exceeding the limit.

func (*Common) CommitNegotiatedExtensions

func (s *Common) CommitNegotiatedExtensions(decision *negotiation.ConnectionID)

CommitNegotiatedExtensions applies a fully validated extension decision.

func (*Common) ConnectionIDPending

func (s *Common) ConnectionIDPending() bool

ConnectionIDPending reports whether the client is waiting for a final CID decision.

func (*Common) HighestRemoteEpoch

func (s *Common) HighestRemoteEpoch() uint64

HighestRemoteEpoch is the newest epoch actually received, not merely keyed.

func (*Common) HighestRemoteSequenceNumber

func (s *Common) HighestRemoteSequenceNumber(epoch uint64) (uint64, bool)

HighestRemoteSequenceNumber distinguishes an unseen epoch from one that received record zero.

func (*Common) LocalConnectionID

func (s *Common) LocalConnectionID() []byte

func (*Common) LocalConnectionIDForInboundRecords

func (s *Common) LocalConnectionIDForInboundRecords() []byte

LocalConnectionIDForInboundRecords returns the negotiated CID, or the pending wire offer while a client is still waiting for ServerHello.

func (*Common) LocalEpoch

func (s *Common) LocalEpoch() uint64

func (*Common) NextLocalSequenceNumber

func (s *Common) NextLocalSequenceNumber(epoch uint64) uint64

func (*Common) RecordLocalClientHello

func (s *Common) RecordLocalClientHello(snapshot negotiation.ClientHelloSnapshot) error

RecordLocalClientHello retains an offer and publishes its pending CID.

func (*Common) RemoteEpoch

func (s *Common) RemoteEpoch() uint64

func (*Common) ResetConnectionIDs

func (s *Common) ResetConnectionIDs()

ResetConnectionIDs clears committed CID state and starts a new decision.

func (*Common) RetainTrafficCounters

func (s *Common) RetainTrafficCounters(keys *TrafficKeyState)

func (*Common) SRTPProtectionProfile

func (s *Common) SRTPProtectionProfile() extension.SRTPProtectionProfile

func (*Common) SetLocalConnectionID

func (s *Common) SetLocalConnectionID(v []byte)

func (*Common) SetLocalEpoch

func (s *Common) SetLocalEpoch(epoch uint64)

func (*Common) SetLocalSequenceNumber

func (s *Common) SetLocalSequenceNumber(epoch, sequenceNumber uint64)

func (*Common) SetRemoteEpoch

func (s *Common) SetRemoteEpoch(epoch uint64)

func (*Common) SetSRTPProtectionProfile

func (s *Common) SetSRTPProtectionProfile(profile extension.SRTPProtectionProfile)

func (*Common) UpdateRemoteSequenceNumber

func (s *Common) UpdateRemoteSequenceNumber(epoch, sequenceNumber uint64)

UpdateRemoteSequenceNumber records a successfully deprotected sequence number.

type EarlyDataStatus

type EarlyDataStatus uint8

EarlyDataStatus tracks client offers and the server's acceptance decision.

const (
	EarlyDataNone EarlyDataStatus = iota
	EarlyDataReady
	EarlyDataAccepted
	EarlyDataRejected
)

type KeySchedule

type KeySchedule struct {
	EarlySecret     []byte
	HandshakeSecret []byte

	// MasterSecret is TLS/DTLS 1.3's key-schedule master secret, not the
	// DTLS 1.2 PRF master_secret.
	MasterSecret []byte

	HandshakeTraffic TrafficSecrets

	ClientApplicationTrafficSecret0 []byte
	ServerApplicationTrafficSecret0 []byte

	ExporterMasterSecret   []byte
	ResumptionMasterSecret []byte
}

type PSK

type PSK struct {
	Ticket              *SessionTicket
	Identity            []byte
	IdentityHint        []byte
	Secret              []byte
	Hash                crypto.Hash
	External            bool
	ObfuscatedTicketAge uint32
	PeerCertificates    [][]byte
}

PSK associates an offered identity state with its secret, hash, and binder label.

https://www.rfc-editor.org/rfc/rfc8446.html#section-4.2.11

type Session

type Session struct {
	ID                   []byte
	Secret               []byte //nolint:gosec // Session stores intentionally retain the resumption secret.
	Ticket               *SessionTicket
	Version              uint8
	IsClient             bool
	CipherSuiteID        cryptosuite.ID
	ExtendedMasterSecret bool
	PeerCertificates     [][]byte
	IdentityHint         []byte
	PSKHash              [sha256.Size]byte
}

Session stores authenticated resumption metadata for either protocol version.

type SessionTicket

type SessionTicket struct {
	NegotiatedProtocol string
	MaxEarlyDataSize   uint32 // Maximum early-data bytes; zero disables early data.
	CipherSuite        cryptosuite.ID
	Lifetime           uint32 // Seconds from CreatedAt.
	AgeAdd             uint32
	Nonce              []byte
	CreatedAt          time.Time
	ServerName         string
	PeerCertificates   [][]byte
}

SessionTicket holds DTLS 1.3 ticket metadata alongside its identity and PSK.

type State

type State = State12

State is retained as the DTLS 1.2 state alias for callers that still only support DTLS 1.2 resumption/state serialization.

type State12

type State12 struct {
	HandshakeComplete  atomic.Bool
	RemoteReplayCutoff uint64
	*Common
	Protection cryptosuite.Protection

	PreMasterSecret   []byte
	MasterSecret      []byte
	ResumeSession     *Session
	PSKHash           [sha256.Size]byte
	ServerCertificate *tls.Certificate

	ExtendedMasterSecret        bool
	RemoteSupportsRenegotiation bool

	NamedCurve   elliptic.Curve
	LocalKeypair *elliptic.Keypair

	Cookie                []byte
	HasHelloVerifyRequest bool
	HandshakeSendSequence int
	HandshakeRecvSequence int

	RemoteCertRequestAlgs      []signaturehash.Algorithm
	RemoteSignatureSchemes     []signaturehash.Algorithm // signature_algorithms from peer
	RemoteCertSignatureSchemes []signaturehash.Algorithm // signature_algorithms_cert from peer

	RemoteRequestedCertificate bool
	LocalCertificatesVerify    []byte
	LocalVerifyData            []byte
	LocalKeySignature          []byte

	ClientKeyExchange        *handshake.MessageClientKeyExchange
	ClientFlightProcessed    bool
	PeerCertificatesVerified bool
	// contains filtered or unexported fields
}

State12 holds state that is meaningful only for DTLS 1.2.

func Activate12

func Activate12(active Active) *State12

Activate12 returns a DTLS 1.2 active state, preserving common fields and handshake sequence counters.

func As12

func As12(active Active) (*State12, error)

func NewState12

func NewState12(isClient bool) State12

NewState12 creates DTLS 1.2 state with initialized common fields.

func (*State12) CommonFields

func (s *State12) CommonFields() *Common

CommonFields returns the embedded common state.

func (*State12) InitCipherSuite

func (s *State12) InitCipherSuite() error

func (*State12) Open

func (s *State12) Open(record cryptosuite.Record, protected []byte) ([]byte, error)

Open counts authentication failures under the DTLS 1.2 read key.

func (*State12) RemoteServerKeyExchange

func (s *State12) RemoteServerKeyExchange() *handshake.MessageServerKeyExchange

RemoteServerKeyExchange returns the parsed server key exchange.

func (*State12) RestoreUsage

func (s *State12) RestoreUsage(sealed, failed uint64)

RestoreUsage restores counters before an imported connection starts processing records.

func (*State12) Seal

func (s *State12) Seal(record cryptosuite.Record, plaintext []byte) ([]byte, error)

Seal counts successful encryption under the DTLS 1.2 write key.

func (*State12) Session

func (s *State12) Session() Session

Session snapshots the authenticated DTLS 1.2 session.

func (*State12) SetRemoteServerKeyExchange

func (s *State12) SetRemoteServerKeyExchange(message *handshake.MessageServerKeyExchange)

SetRemoteServerKeyExchange retains the parsed server key exchange for the remainder of the handshake.

func (*State12) ShouldWrapConnectionID

func (s *State12) ShouldWrapConnectionID() bool

ShouldWrapConnectionID reports whether outgoing DTLS 1.2 records should use CID record encoding.

func (*State12) Usage

func (s *State12) Usage() (sealed, failed uint64)

Usage returns successful seals and authentication failures for the key pair.

type State13

type State13 struct {
	*Common
	ECH              *ech.ClientContext
	ECHServer        *ech.ServerContext
	EarlyDataStatus  EarlyDataStatus
	EarlyDataLimit   uint32
	EarlyDataBytes   uint64
	EarlyDataPSK     *PSK
	EarlyClientHello []byte

	// PendingEarlyKeyLog retains the early traffic secret until ECH selects the client random.
	PendingEarlyKeyLog []byte

	CID         CIDState
	KeySchedule KeySchedule
	TrafficKeys *TrafficKeyState

	// ReplayCutoff is the highest rejected record sequence number per epoch.
	ReplayCutoff map[uint64]uint64

	// KeyAgreementSecret is the ECDHE or hybrid shared secret that feeds the
	// TLS 1.3 HKDF key schedule, or Hash.length zero bytes for psk_ke.
	KeyAgreementSecret []byte

	// LocalPSKs retains the client offers across retries. PSK is set after selection.
	LocalPSKs   []PSK
	PSK         []byte
	PSKIdentity uint16
	PSKOnly     bool // Negotiated psk_ke, without a key share.

	SelectedGroup elliptic.Curve

	LocalKeypair  *elliptic.Keypair
	LocalKeypairs map[elliptic.Curve]*elliptic.Keypair

	LocalKeyEntries []extension13.KeyShareEntry

	RemoteKeyEntries    []extension13.KeyShareEntry
	HasRemoteKeyEntries bool
	RemoteGroups        []elliptic.Curve

	Cookie                []byte
	HelloRetryRequest     negotiation.RetryRequest
	HandshakeSendSequence int
	HandshakeRecvSequence int

	RemoteSignatureSchemes     []signaturehash.Algorithm // signature_algorithms from peer
	RemoteCertSignatureSchemes []signaturehash.Algorithm // signature_algorithms_cert from peer

	// RemoteCertificateRequest is the authenticated and decoded request
	// kept for the client's final flight.
	RemoteCertificateRequest *handshake13.MessageCertificateRequest
}

State13 holds state that is meaningful only for DTLS 1.3.

func Activate13

func Activate13(active Active) *State13

Activate13 returns a DTLS 1.3 active state, preserving common fields and handshake sequence counters.

func As13

func As13(active Active) (*State13, error)

func Clone13ForVerification

func Clone13ForVerification(state *State13, peerCertificates [][]byte) *State13

Clone13ForVerification returns a DTLS 1.3 state snapshot containing the certificates from the flight being verified.

func NewState13

func NewState13(isClient bool) State13

NewState13 creates DTLS 1.3 state with initialized common fields.

func (*State13) AdvanceHandshakeRecvSequence

func (s *State13) AdvanceHandshakeRecvSequence()

AdvanceHandshakeRecvSequence marks a post-handshake message as processed.

func (*State13) CommitNegotiatedExtensions

func (s *State13) CommitNegotiatedExtensions(decision *negotiation.ConnectionID)

CommitNegotiatedExtensions applies a fully validated extension decision.

func (*State13) CommonFields

func (s *State13) CommonFields() *Common

CommonFields returns the embedded common state.

func (*State13) HandshakeSequences

func (s *State13) HandshakeSequences() (send, receive int)

HandshakeSequences snapshots the counters while post-handshake messages advance them.

func (*State13) ResetConnectionIDs

func (s *State13) ResetConnectionIDs()

ResetConnectionIDs clears the connection IDs and CID state.

func (*State13) ShouldWrapConnectionID

func (*State13) ShouldWrapConnectionID() bool

ShouldWrapConnectionID reports whether outgoing records should use the legacy DTLS 1.2 CID record encoding.

type TrafficGeneration

type TrafficGeneration struct {
	CipherSuite cryptosuite.Suite // Optional override for early data before cipher negotiation.
	Epoch       uint64
	Generation  uint64
	Secret      []byte // nolint:gosec
	Protection  cryptosuite.TrafficProtection
	// contains filtered or unexported fields
}

TrafficGeneration binds an epoch and traffic-secret generation to the record protection derived from that secret. Caller must not modify the secret or protection after creation.

func (*TrafficGeneration) Capabilities

func (g *TrafficGeneration) Capabilities(negotiated cryptosuite.Suite) (cryptosuite.Capabilities, error)

Capabilities uses the generation's suite when available, otherwise the negotiated suite. Early-data keys retain the ticket's suite.

func (*TrafficGeneration) Clone

func (*TrafficGeneration) Open

func (g *TrafficGeneration) Open(record cryptosuite.Record, protected []byte) ([]byte, error)

Open counts only typed authentication failures, preserving the provider error.

func (*TrafficGeneration) RestoreUsage

func (g *TrafficGeneration) RestoreUsage(sealed, failed uint64)

RestoreUsage restores counters before a deserialized generation is installed.

func (*TrafficGeneration) Seal

func (g *TrafficGeneration) Seal(record cryptosuite.Record, plaintext []byte) ([]byte, error)

Seal counts successful encryptions, including those followed by masking or transport failures. Recommended usage limits are advisory.

func (*TrafficGeneration) Usage

func (g *TrafficGeneration) Usage() (sealed, failed uint64)

Usage returns counters for this key. Counts saturate at math.MaxUint64.

type TrafficKeyState

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

TrafficKeyState owns directional DTLS 1.3 traffic generations.

func (*TrafficKeyState) Clone

func (s *TrafficKeyState) Clone() *TrafficKeyState

func (*TrafficKeyState) CurrentRead

func (s *TrafficKeyState) CurrentRead() (*TrafficGeneration, bool)

CurrentRead returns the current read generation.

func (*TrafficKeyState) CurrentWrite

func (s *TrafficKeyState) CurrentWrite() (*TrafficGeneration, bool)

CurrentWrite returns the current write generation.

func (*TrafficKeyState) Discard

func (s *TrafficKeyState) Discard(epoch uint64)

Discard removes both directions of an epoch when its keys are no longer usable.

func (*TrafficKeyState) Generations

func (s *TrafficKeyState) Generations() (write, read []*TrafficGeneration)

Generations returns read-only generations.

func (*TrafficKeyState) Install

func (s *TrafficKeyState) Install(write, read *TrafficGeneration)

Install any supplied current write and read generations. Pass nil for a direction that should remain unchanged.

func (*TrafficKeyState) Read

func (s *TrafficKeyState) Read(epoch uint64) (*TrafficGeneration, bool)

Read returns the read generation associated with epoch.

func (*TrafficKeyState) ReadCandidate

func (s *TrafficKeyState) ReadCandidate(epochLow uint8, currentEpoch uint64) (*TrafficGeneration, bool)

ReadCandidate selects the current or most recent past epoch with matching low bits. A missing generation does not allow falling back to an older matching epoch. https://www.rfc-editor.org/rfc/rfc9147.html#section-4.2.2

func (*TrafficKeyState) RetainEpochs

func (s *TrafficKeyState) RetainEpochs(writeEpochs []uint64)

func (*TrafficKeyState) Write

func (s *TrafficKeyState) Write(epoch uint64) (*TrafficGeneration, bool)

Write returns the write generation associated with epoch.

type TrafficSecrets

type TrafficSecrets struct {
	Client []byte
	Server []byte
}

Jump to

Keyboard shortcuts

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