sessionSequence

fun sessionSequence(length: Int = 8, random: Random = PlatformCsprng): TokenGenerator(source)

Sequence numbers on secure sessions and random tokens elsewhere, the default of every endpoint.

Towards a peer on a DTLS session (Endpoint.Secure) or a TLS connection (Endpoint.Tcp or Endpoint.WebSocket with usesTls, that is coaps+tcp and coaps+ws), the token is a sequence number in its shortest form, starting at zero (the empty token) for each session or connection, as RFC 9175 §4.2 says a client SHOULD do with a security protocol that does not bind responses to requests, and towards every other peer length bytes of random, the platform's CSPRNG by default.

Why that is safe and better on a secure channel (RFC 9175 §4):

  • The count never repeats while the session's keys last, so no response, however late, and no notification of an earlier observation can be taken for the answer to a newer request; random tokens only make that unlikely. The endpoint calls forget when the session ends or the connection closes, and opens a new connection to the same peer only after that, so a new count starts with new keys and never runs on an old one.

  • That the token is predictable gives nothing away: an attacker who is not the peer cannot inject a message into a DTLS session or a TLS connection, and the peer can answer any token it was sent.

  • On a connection tokens are scoped to that connection (RFC 8323 §3.3, §4.3), whose reliable, ordered delivery also means no stale copy of an old message arrives under a new token, and the short tokens save up to 8 bytes in every message.

  • Plain UDP, TCP and WebSockets keep random tokens, since there the token is what stops off-path response spoofing (RFC 7252 §5.3.1); so does a server behind a reverse proxy that terminates TLS, which sees plain coap+tcp or coap+ws.