oscore

package
v3.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 22 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package oscore contains transport-independent RFC 8613 security-context and message-protection support.

Index

Examples

Constants

View Source
const (
	DefaultReplayHighWaterMargin = uint64(256)
	MaxReplayHighWaterMargin     = uint64(1024)
)
View Source
const MaxUnfragmentedSize = 65536

MaxUnfragmentedSize is the maximum reassembled OSCORE payload size used for Outer Blockwise transfers.

Variables

View Source
var (
	ErrInvalidContext          = errors.New("invalid OSCORE security context")
	ErrUnsupportedAlgorithm    = errors.New("unsupported OSCORE AEAD algorithm")
	ErrSenderSequenceExhausted = errors.New("OSCORE sender sequence number exhausted")
	ErrReplay                  = errors.New("OSCORE replay detected")
	ErrInvalidPartialIV        = errors.New("invalid OSCORE Partial IV")
	ErrPlaintextTooLarge       = errors.New("OSCORE plaintext exceeds AES-CCM limit")
)
View Source
var (
	ErrNestedOSCOREOption  = errors.New("nested OSCORE option is not supported")
	ErrInvalidOptionClass  = errors.New("invalid OSCORE option class")
	ErrInvalidInnerMessage = errors.New("invalid OSCORE inner message")
)
View Source
var (
	ErrNoSecurityContext         = errors.New("no matching OSCORE security context")
	ErrAmbiguousContext          = errors.New("multiple OSCORE security contexts are configured")
	ErrPlaintextDisabled         = errors.New("unprotected CoAP is not permitted")
	ErrOSCORERequired            = errors.New("OSCORE protection is required")
	ErrOSCOREDisabled            = errors.New("OSCORE-protected CoAP is not permitted")
	ErrReplayRecoveryRequired    = errors.New("OSCORE replay recovery Echo is required")
	ErrReplayRecoveryRateLimited = errors.New("OSCORE replay recovery challenge rate limited")
)
View Source
var (
	ErrInvalidOSCOREMessage = errors.New("invalid OSCORE message")
	ErrInvalidOSCOREOption  = errors.New("invalid OSCORE option")
	ErrUnsupportedOption    = errors.New("unsupported OSCORE option processing")
	ErrReplayTrackingLimit  = errors.New("OSCORE response replay tracking limit exceeded")
)
View Source
var (
	ErrInvalidReplayWindow = errors.New("invalid OSCORE replay window size")
	ErrInvalidReplayState  = errors.New("invalid OSCORE replay window state")
	ErrInternalProcessing  = errors.New("internal OSCORE processing failure")
)

Functions

func BuildAAD

func BuildAAD(requestKid, requestPartialIV []byte, options message.Options) ([]byte, error)

BuildAAD creates the RFC 8613 COSE_Encrypt0 Enc_structure. requestKid and requestPartialIV identify the original request for response binding. options must contain Class I options in RFC 7252 option encoding order; the current RFC 8613 option set defines none, so this is normally empty. This helper does not enforce nonce uniqueness or Exchange lifecycle.

func BuildAADWithAlgorithm

func BuildAADWithAlgorithm(algorithm AEADAlgorithm, requestKid, requestPartialIV []byte, options message.Options) ([]byte, error)

BuildAADWithAlgorithm creates the RFC 8613 COSE_Encrypt0 Enc_structure using algorithm. requestKid and requestPartialIV identify the original request for response binding. It does not enforce nonce uniqueness or Exchange lifecycle.

func CloneOptions

func CloneOptions(options message.Options) message.Options

CloneOptions returns a deep copy of options.

func ContextWithRequestInfo

func ContextWithRequestInfo(ctx context.Context, info RequestInfo) context.Context

ContextWithRequestInfo adds OSCORE request metadata to ctx. It is intended for transport adapters that have successfully processed an incoming request.

func ContextWithUnprotectedProcessingError

func ContextWithUnprotectedProcessingError(ctx context.Context) context.Context

ContextWithUnprotectedProcessingError marks a received response as an unprotected OSCORE processing error. The caller must pass a non-nil context.

func ContextWithUnprotectedProxyError

func ContextWithUnprotectedProxyError(ctx context.Context) context.Context

ContextWithUnprotectedProxyError marks an unprotected proxy-generated error.

func DecodeInner

func DecodeInner(plaintext []byte) (message.Message, error)

DecodeInner parses a CoAP request/response plaintext produced by EncodeInner. CoAP messaging-layer fields (type, token, and message ID) are not present in the OSCORE plaintext and are left unset. It does not authenticate plaintext; callers should normally use UnprotectRequest or UnprotectResponse.

func EncodeInner

func EncodeInner(code codes.Code, options message.Options, payload []byte) ([]byte, error)

EncodeInner serializes the CoAP request/response fields that RFC 8613 puts in the COSE plaintext: Code, Class E options, and optionally payload. It is a serialization helper only and does not protect or authenticate the result.

func ExchangeTrackerKey

func ExchangeTrackerKey(token []byte) string

ExchangeTrackerKey returns the map key for a CoAP Token.

func IsInternalProcessingError

func IsInternalProcessingError(err error) bool

IsInternalProcessingError reports whether processing failed because of a local OSCORE configuration or persistence fault rather than a peer request.

func IsResponseCode

func IsResponseCode(code codes.Code) bool

IsResponseCode reports whether code is a CoAP response code.

func IsUnprotectedProcessingError

func IsUnprotectedProcessingError(ctx context.Context) bool

IsUnprotectedProcessingError reports whether the response context was marked as an unprotected OSCORE processing error by a client transport.

func IsUnprotectedProcessingErrorCode

func IsUnprotectedProcessingErrorCode(code codes.Code) bool

IsUnprotectedProcessingErrorCode reports whether RFC 8613 permits this response code for an OSCORE processing error without OSCORE protection.

func IsUnprotectedProxyError

func IsUnprotectedProxyError(ctx context.Context) bool

IsUnprotectedProxyError reports whether the response is an unprotected proxy-generated error for a proxied OSCORE request. Such responses are unauthenticated and may be spoofed by an on-path attacker.

func IsUnprotectedProxyErrorCode

func IsUnprotectedProxyErrorCode(code codes.Code) bool

IsUnprotectedProxyErrorCode reports whether code is an error response code other than one reserved for OSCORE processing errors.

func MatchesObserveRegistration

func MatchesObserveRegistration(registration, cancellation message.Options) bool

MatchesObserveRegistration reports whether options describe the same Observe registration, ignoring Observe and ETag as required for cancellation.

func PartialIVNumber

func PartialIVNumber(partialIV []byte) uint64

PartialIVNumber converts a big-endian Partial IV into its sequence number.

func ProcessingErrorCode

func ProcessingErrorCode(err error) codes.Code

ProcessingErrorCode maps peer-caused OSCORE errors to the unprotected response codes clients recognize. Internal processing errors map to 5.00 for classification and must not be sent as OSCORE processing-error responses.

func ProtectReplayRecoveryResponse

func ProtectReplayRecoveryResponse(err error, response message.Message) (message.Message, bool, error)

ProtectReplayRecoveryResponse builds a protected 4.01 response carrying the authenticated replay-recovery Echo challenge. The supplied response provides transport fields such as type and message ID; its code, token, options, and payload are replaced with the challenge response bound to the authenticated request.

func ProtectReplayRecoveryResponseForPeer

func ProtectReplayRecoveryResponseForPeer(
	err error,
	response message.Message,
	peer string,
) (message.Message, bool, error)

ProtectReplayRecoveryResponseForPeer applies the replay-recovery challenge budget independently to the supplied peer identity.

func ReplayRecoveryEcho

func ReplayRecoveryEcho(err error) ([]byte, bool)

ReplayRecoveryEcho returns a copy of the Echo challenge from a replay recovery error.

Types

type AADBuilder

type AADBuilder func(partialIV []byte) ([]byte, error)

AADBuilder builds the RFC 8613 COSE_Encrypt0 Enc_structure using the fresh Partial IV that Seal is about to use.

type AEADAlgorithm

type AEADAlgorithm uint64

AEADAlgorithm identifies a COSE AEAD algorithm supported by OSCORE.

const (
	// AEADAlgorithmAESCCM16_64_128 is AES-CCM with a 64-bit tag and 128-bit key.
	AEADAlgorithmAESCCM16_64_128 AEADAlgorithm = 10
	// AEADAlgorithmAESCCM16_64_256 is AES-CCM with a 64-bit tag and 256-bit key.
	AEADAlgorithmAESCCM16_64_256 AEADAlgorithm = 11
	// AEADAlgorithmAESCCM16_128_128 is AES-CCM with a 128-bit tag and 128-bit key.
	AEADAlgorithmAESCCM16_128_128 AEADAlgorithm = 30
	// AEADAlgorithmAESCCM16_128_256 is AES-CCM with a 128-bit tag and 256-bit key.
	AEADAlgorithmAESCCM16_128_256 AEADAlgorithm = 31
)

type Context

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

Context holds the derived keys and mutable sender and recipient state for one pair of OSCORE endpoints. A Context must not be copied after first use.

Example (DirectAPI)
package main

import (
	"errors"
	"fmt"

	"github.com/plgd-dev/go-coap/v3/message"
	"github.com/plgd-dev/go-coap/v3/message/codes"
	"github.com/plgd-dev/go-coap/v3/net/oscore"
)

func main() {
	// This example uses volatile sequence and replay state; never reuse these
	// settings with a production sender key.
	masterSecret := []byte("public test-only secret")
	clientContext, err := oscore.NewContext(oscore.ContextConfig{
		UnsafeVolatileSenderSequence: true,
		AcceptReplayStateLoss:        true,
		MasterSecret:                 masterSecret,
		SenderID:                     []byte("client"),
		RecipientID:                  []byte("server"),
	})
	if err != nil {
		panic(err)
	}
	serverContext, err := oscore.NewContext(oscore.ContextConfig{
		UnsafeVolatileSenderSequence: true,
		AcceptReplayStateLoss:        true,
		MasterSecret:                 masterSecret,
		SenderID:                     []byte("server"),
		RecipientID:                  []byte("client"),
	})
	if err != nil {
		panic(err)
	}
	clientProcessor, err := oscore.NewProcessor(oscore.ProcessorConfig{
		Contexts:        []*oscore.Context{clientContext},
		PlaintextPolicy: oscore.PlaintextDisabled,
	})
	if err != nil {
		panic(err)
	}
	serverProcessor, err := oscore.NewProcessor(oscore.ProcessorConfig{
		Contexts:        []*oscore.Context{serverContext},
		PlaintextPolicy: oscore.PlaintextDisabled,
	})
	if err != nil {
		panic(err)
	}

	protectedRequest, exchange, err := clientProcessor.ProtectRequest(message.Message{
		Code:  codes.GET,
		Token: message.Token{1},
	})
	if err != nil {
		panic(err)
	}
	request, _, serverExchange, err := serverProcessor.ProcessIncomingRequest(protectedRequest)
	if err != nil {
		panic(err)
	}
	protectedResponse, err := serverContext.ProtectResponse(message.Message{
		Code:    codes.NotFound,
		Token:   request.Token,
		Payload: []byte("not found"),
	}, serverExchange)
	if err != nil {
		panic(err)
	}
	_, duplicateErr := serverContext.ProtectResponse(message.Message{
		Code:    codes.NotFound,
		Token:   request.Token,
		Payload: []byte("different plaintext"),
	}, serverExchange)
	response, err := clientProcessor.UnprotectResponse(protectedResponse, clientContext, exchange)
	if err != nil {
		panic(err)
	}
	fmt.Printf("authenticated payload: %s\n", response.Payload)
	fmt.Printf("duplicate protection rejected: %t\n", errors.Is(duplicateErr, oscore.ErrReplay))

	observeRequestOptions, _, err := (message.Options{}).SetObserve(nil, 0)
	if err != nil {
		panic(err)
	}
	protectedObserveRequest, observeExchange, err := clientProcessor.ProtectRequest(message.Message{
		Code: codes.GET, Token: message.Token{2}, Options: observeRequestOptions,
	})
	if err != nil {
		panic(err)
	}
	observeRequest, _, serverObserveExchange, err := serverProcessor.ProcessIncomingRequest(protectedObserveRequest)
	if err != nil {
		panic(err)
	}
	observeResponseOptions, _, err := (message.Options{}).SetObserve(make([]byte, 4), 1)
	if err != nil {
		panic(err)
	}
	notificationsAccepted := true
	for range 2 {
		notification, protectErr := serverContext.ProtectResponseWithPartialIV(message.Message{
			Code: codes.Content, Token: observeRequest.Token,
			Options: observeResponseOptions, Payload: []byte("update"),
		}, serverObserveExchange)
		if protectErr != nil {
			panic(protectErr)
		}
		openedNotification, unprotectErr := clientProcessor.UnprotectResponse(
			notification, clientContext, observeExchange,
		)
		if unprotectErr != nil {
			panic(unprotectErr)
		}
		notificationsAccepted = notificationsAccepted &&
			openedNotification.Options.HasOption(message.Observe)
	}
	fmt.Printf("Observe notifications accepted: %t\n", notificationsAccepted)
}
Output:
authenticated payload: not found
duplicate protection rejected: true
Observe notifications accepted: true

func NewContext

func NewContext(cfg ContextConfig) (*Context, error)

NewContext derives keys for the configured AEAD algorithm. The zero-value Algorithm selects AES-CCM-16-64-128. Input byte slices are consumed during construction; identifier slices retained by the Context are copied. Go cannot guarantee complete zeroization of temporary secret copies.

func (*Context) Algorithm

func (c *Context) Algorithm() AEADAlgorithm

Algorithm returns the COSE AEAD algorithm configured for this context.

func (*Context) IDContext

func (c *Context) IDContext() ([]byte, bool)

IDContext returns a copy of the ID Context and whether one was configured. The boolean distinguishes an absent ID Context from a present empty one.

func (*Context) NextPartialIV

func (c *Context) NextPartialIV() ([]byte, error)

NextPartialIV reserves the next sender sequence number and returns its minimal OSCORE Partial IV encoding. A reserved value remains consumed even if the caller later fails to send a message.

func (*Context) Open

func (c *Context) Open(partialIV, ciphertext, aad []byte) ([]byte, error)

Open authenticates and decrypts a serialized inner message. The recipient replay window is updated only after authentication succeeds. It does not bind the plaintext to a CoAP request or response Exchange.

func (*Context) OpenResponse

func (c *Context) OpenResponse(partialIV, ciphertext, aad []byte) ([]byte, error)

OpenResponse authenticates a response with its own Partial IV, using the response sender ID for nonce construction. It does not update request replay state or enforce response replay/order; use UnprotectResponse for exchange-scoped response replay protection.

func (*Context) OpenResponseForExchange

func (c *Context) OpenResponseForExchange(responsePartialIV, requestPartialIV, ciphertext, aad []byte) ([]byte, error)

OpenResponseForExchange opens a response that is bound to an original request. Responses without a Partial IV use the request nonce and do not advance the recipient replay window. This primitive does not track exchange completion, enforce response replay/order, or authenticate the Exchange lifecycle; use UnprotectResponse with the Exchange returned by ProtectRequest or UnprotectRequest.

func (*Context) ProtectRequest

func (c *Context) ProtectRequest(request message.Message) (message.Message, Exchange, error)

ProtectRequest protects an outgoing CoAP request and returns the Exchange that must be retained for response processing. Keep the Exchange with the request; retransmissions should reuse the protected message rather than protecting a new request with the same application exchange.

func (*Context) ProtectResponse

func (c *Context) ProtectResponse(response message.Message, exchange Exchange) (message.Message, error)

ProtectResponse protects the ordinary response bound to exchange. It uses the request Partial IV as its nonce and therefore succeeds at most once per Exchange, including across copies and concurrent calls. Resend the returned protected message for retransmission.

func (*Context) ProtectResponseWithPartialIV

func (c *Context) ProtectResponseWithPartialIV(response message.Message, exchange Exchange) (message.Message, error)

ProtectResponseWithPartialIV protects a response with a fresh sender Partial IV. Unlike ProtectResponse, it consumes a sequence number and includes that Partial IV in the OSCORE option. The response AAD remains bound to the original request exchange. Repeated use is supported for Observe and Q-Block Exchanges; an ordinary Exchange remains one-shot.

func (*Context) RecipientID

func (c *Context) RecipientID() []byte

RecipientID returns a copy of the recipient identifier.

func (*Context) ReplayMessagesRejectedBelowCutoff

func (c *Context) ReplayMessagesRejectedBelowCutoff() uint64

ReplayMessagesRejectedBelowCutoff reports the number of inbound sequences rejected below the durable high-water cutoff loaded when this context was created. It can be sampled by application metrics after receiver restarts.

func (*Context) Seal

func (c *Context) Seal(plaintext []byte, buildAAD AADBuilder) (partialIV, ciphertext []byte, err error)

Seal protects the serialized inner message with the sender context. The method reserves a fresh sequence number before building the AAD or encrypting. This low-level primitive does not enforce CoAP Exchange lifecycle; callers must preserve Partial IV uniqueness and use high-level message methods for exchange-bound messages.

func (*Context) SealResponse

func (c *Context) SealResponse(plaintext []byte, buildAAD AADBuilder) (partialIV, ciphertext []byte, err error)

SealResponse protects a response with its own Partial IV, using the response sender ID for nonce construction. This low-level primitive does not track Exchange lifecycle or response ordering.

func (*Context) SealResponseWithRequestNonce

func (c *Context) SealResponseWithRequestNonce(plaintext, requestPartialIV []byte, buildAAD AADBuilder) ([]byte, error)

SealResponseWithRequestNonce protects a non-notification response using the request Partial IV and request sender ID. No new sender sequence number is consumed and the response OSCORE option can be empty. This low-level primitive does not track Exchange lifecycle; repeated use with the same request Partial IV can reuse an AEAD nonce. Prefer ProtectResponse.

func (*Context) SenderID

func (c *Context) SenderID() []byte

SenderID returns a copy of the sender identifier.

func (*Context) TagSize

func (c *Context) TagSize() int

TagSize returns the authentication tag size, in bytes, for the context's configured AEAD algorithm.

func (*Context) UnprotectRequest

func (c *Context) UnprotectRequest(request message.Message) (message.Message, Exchange, error)

UnprotectRequest authenticates and decrypts an incoming OSCORE request and returns the Exchange required to protect its response.

func (*Context) UnprotectResponse

func (c *Context) UnprotectResponse(response message.Message, exchange Exchange) (message.Message, error)

UnprotectResponse authenticates and decrypts a response bound to exchange. The Exchange must have been created by this Context; it remains valid after the Context is removed from a Processor because the Exchange retains that Context for in-flight response processing. Ordinary responses without a Partial IV and duplicate response Partial IVs are accepted at most once per Exchange. Failed authentication does not consume the Exchange.

func (*Context) ValidateQBlock2ObserveWindow

func (c *Context) ValidateQBlock2ObserveWindow(required uint64) error

ValidateQBlock2ObserveWindow verifies that this context can track every fragment in the configured Q-Block2 body and retry budget.

type ContextConfig

type ContextConfig struct {
	// Algorithm is a COSE AEAD algorithm. Zero selects AES-CCM-16-64-128.
	Algorithm AEADAlgorithm
	// MasterSecret is high-entropy secret material provisioned securely to
	// both peers, not a human password. NewContext derives its keys immediately
	// and does not retain this slice.
	MasterSecret         []byte
	MasterSalt           []byte
	IDContext            []byte
	SenderID             []byte
	RecipientID          []byte
	SenderSequenceNumber uint64
	SenderSequenceStore  SenderSequenceReserver
	ReplayWindowSize     uint8
	ReplayWindowStore    ReplayWindowStore
	// QBlock2ObserveWindowSize bounds authenticated PIVs retained for
	// out-of-order Q-Block2 Observe fragments. Zero selects a window sized for
	// the default Q-Block retry configuration and maximum tracked body.
	QBlock2ObserveWindowSize uint64
	// UnsafeVolatileSenderSequence explicitly accepts in-memory sender sequence
	// state when SenderSequenceStore is not configured. Restarting with the
	// same sender key can reuse Partial IVs and AEAD nonces; see RFC 8613
	// Appendix B.2. Use only when this risk is acceptable.
	UnsafeVolatileSenderSequence bool
	// AcceptReplayStateLoss explicitly accepts that replay protection resets
	// after a restart when no ReplayWindowStore is configured.
	AcceptReplayStateLoss bool
	// RequireEchoRecovery challenges requests with a fresh, context-specific
	// Echo option after a receiver restart. The authenticated request carrying
	// the challenge seeds the replay window before application dispatch. Use
	// it when replay state was not persisted; it cannot be combined with
	// ReplayWindowStore.
	RequireEchoRecovery bool
}

ContextConfig contains pre-established RFC 8613 security-context parameters. Set SenderSequenceNumber to the next sequence number to use, or provide a SenderSequenceStore for durable reservations across process restarts. Without a store, explicitly set UnsafeVolatileSenderSequence to accept in-memory sequence state. Restarting with the same sender key can then reuse Partial IVs and AEAD nonces; see RFC 8613 Appendix B.2. Never reset the sequence number for an existing sender key. Configure ReplayWindowStore for durable inbound replay state, set RequireEchoRecovery after a receiver restart, or explicitly set AcceptReplayStateLoss to allow an unprotected volatile replay window.

type Exchange

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

Exchange binds a response to the request that established its OSCORE AAD and nonce context. Keep the exact value returned by ProtectRequest or UnprotectRequest with the CoAP token until the exchange completes; response replay state is shared by copies of this value.

func (Exchange) CompleteQBlock2Representation

func (e Exchange) CompleteQBlock2Representation(highestPartialIV uint64) error

CompleteQBlock2Representation retires per-fragment replay entries after the caller has successfully assembled a protected Q-Block2 Observe representation.

func (Exchange) HasResponse

func (e Exchange) HasResponse() bool

HasResponse reports whether a response has been successfully authenticated for this exchange.

func (Exchange) IsObserve

func (e Exchange) IsObserve() bool

IsObserve reports whether the Exchange is bound to an Observe registration.

func (Exchange) RequestIdentifier

func (e Exchange) RequestIdentifier() []byte

RequestIdentifier returns a copy of the request identifier bound to the Exchange.

func (Exchange) RequestPartialIVBytes

func (e Exchange) RequestPartialIVBytes() []byte

RequestPartialIVBytes returns a copy of the request Partial IV bound to the Exchange.

type ExchangeTracker

type ExchangeTracker[T any] map[string]T

ExchangeTracker stores transport-specific exchange state by CoAP Token. Callers serialize access with their transport lock.

func NewExchangeTracker

func NewExchangeTracker[T any]() ExchangeTracker[T]

NewExchangeTracker creates an empty token-to-exchange tracker.

func (ExchangeTracker[T]) Match

func (t ExchangeTracker[T]) Match(
	key string,
	expected Exchange,
	exchangeOf func(T) Exchange,
) (T, error)

Match verifies that key still refers to the expected OSCORE exchange.

type OptionClass

type OptionClass uint8

OptionClass identifies the protection applied to a CoAP option field.

const (
	// ClassE options are encrypted and integrity protected.
	ClassE OptionClass = iota
	// ClassI options are carried outside the ciphertext and integrity protected
	// through the external AAD. RFC 8613 currently defines no Class I options.
	ClassI
	// ClassU options are carried outside the ciphertext without OSCORE protection.
	ClassU
	// ClassBoth options may be carried in either the Inner or Outer message.
	ClassBoth
)

func ClassifyOption

func ClassifyOption(id message.OptionID) OptionClass

ClassifyOption returns the OSCORE classes supported by an option. Options that support both Inner and Outer processing are classified as ClassBoth; callers should prefer Inner processing unless they need the Outer behavior.

Unknown options default to Class E, as required by RFC 8613.

type OptionSplit

type OptionSplit struct {
	Inner message.Options
	Outer message.Options
}

OptionSplit separates inner Class E and outer Class U options. No Class I options are currently defined by RFC 8613. The returned option values alias the input; callers must preserve their lifetime.

func SplitOptions

func SplitOptions(options message.Options) (OptionSplit, error)

SplitOptions separates options according to their RFC 8613 default class. It returns option values that alias the input and does not apply message authentication or Exchange lifecycle checks.

type OptionValue

type OptionValue struct {
	PartialIV    []byte
	IDContext    []byte
	SenderID     []byte
	IDContextSet bool
	SenderIDSet  bool
}

OptionValue contains the fields encoded by the RFC 8613 OSCORE option. Presence booleans distinguish an absent field from a present empty value.

func UnmarshalOption

func UnmarshalOption(value []byte) (OptionValue, error)

UnmarshalOption decodes the value of an RFC 8613 OSCORE option.

func (OptionValue) MarshalBinary

func (o OptionValue) MarshalBinary() ([]byte, error)

MarshalBinary encodes an OSCORE option value.

type OutgoingContextSelector

type OutgoingContextSelector func(request message.Message, contexts []*Context) (*Context, error)

OutgoingContextSelector chooses a security context for an outgoing request. The contexts slice is a snapshot of the processor's configured contexts. Return one of those contexts or an error; returning nil without an error is treated as ErrNoSecurityContext.

type PlaintextPolicy

type PlaintextPolicy uint8

PlaintextPolicy defines which incoming message protection modes a Processor accepts. The zero value rejects plaintext.

const (
	// PlaintextDisabled accepts only OSCORE-protected messages. It is the
	// zero-value policy.
	PlaintextDisabled PlaintextPolicy = iota
	// PlaintextAllowed accepts both plaintext and OSCORE-protected messages.
	PlaintextAllowed
	// PlaintextOnly accepts only plaintext messages.
	PlaintextOnly
)

type Processor

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

Processor selects contexts for incoming protected requests and applies the endpoint's plaintext policy. Responses remain explicitly bound to the context and Exchange returned by ProcessIncomingRequest.

func NewProcessor

func NewProcessor(cfg ProcessorConfig) (*Processor, error)

NewProcessor validates the configured contexts and plaintext policy.

func (*Processor) AddContext

func (p *Processor) AddContext(context *Context) error

AddContext adds a bidirectional context to the processor. Its recipient ID and ID Context must be unique among configured peers.

func (*Processor) MaxRequestOverhead

func (p *Processor) MaxRequestOverhead(optionCount int, observes bool) uint32

MaxRequestOverhead returns a conservative bound for the additional wire size OSCORE adds to a request with the given number of options. It accounts for the largest configured request option (including ID Context and KID), the inner code, AEAD tag, and option delta growth after class splitting.

func (*Processor) ProcessIncomingRequest

func (p *Processor) ProcessIncomingRequest(request message.Message) (message.Message, *Context, Exchange, error)

ProcessIncomingRequest returns plaintext requests unchanged only when the configured policy allows them. Once an OSCORE option is present, all parse, context, replay, and authentication failures are returned without fallback. For protected requests, the returned context and Exchange must be retained to protect any corresponding response.

func (*Processor) ProtectRequest

func (p *Processor) ProtectRequest(request message.Message) (message.Message, Exchange, error)

ProtectRequest protects an outgoing request using the sole configured context, or the configured OutgoingContextSelector when multiple contexts are available.

func (*Processor) ProtectRequestWithContext

func (p *Processor) ProtectRequestWithContext(request message.Message) (message.Message, *Context, Exchange, error)

ProtectRequestWithContext protects an outgoing request and returns the context needed to open its response. Multiple configured contexts require an OutgoingContextSelector.

func (*Processor) RemoveContext

func (p *Processor) RemoveContext(recipientID, idContext []byte) error

func (*Processor) UnprotectResponse

func (p *Processor) UnprotectResponse(response message.Message, context *Context, exchange Exchange) (message.Message, error)

UnprotectResponse decrypts a response using the context bound to exchange. The supplied context must be the same Context instance used to create the Exchange; a context removed from this Processor remains valid for an in-flight Exchange. Removing a context prevents future selection, but does not zeroize its keys or revoke operations already holding it.

func (*Processor) ValidateQBlock2ObserveWindow

func (p *Processor) ValidateQBlock2ObserveWindow(required uint64) error

RemoveContext removes the configured context identified by recipientID and ID Context. A nil ID Context means absent; a non-nil empty slice means present but empty. Operations that selected the context before removal, and exchanges, may complete; subsequent selection does not include it. Operations holding a pre-removal context snapshot may also complete. Key material is not modified or zeroed while existing Exchanges may still reference the Context. ValidateQBlock2ObserveWindow rejects a processor whose outgoing contexts cannot retain the requested number of authenticated Q-Block2 fragment IDs.

type ProcessorConfig

type ProcessorConfig struct {
	Contexts                []*Context
	OutgoingContextSelector OutgoingContextSelector
	// PlaintextPolicy selects the accepted incoming message protection modes.
	// Its zero value is PlaintextDisabled.
	PlaintextPolicy PlaintextPolicy
}

ProcessorConfig configures pre-established contexts and endpoint plaintext policy. A Processor is opt-in; applications that do not create one retain their existing CoAP behavior.

type ProxyTarget

type ProxyTarget struct {
	Scheme string
	Host   string
	Port   string
	Path   []string
	Query  []string
}

ProxyTarget is a CoAP origin extracted from a Proxy-Uri. Path and Query contain decoded URI components and are populated when present.

func ParseProxyURI

func ParseProxyURI(value string) (ProxyTarget, error)

ParseProxyURI parses a coap or coaps Proxy-Uri and decomposes its path and query into the components used by OSCORE and CoAP proxy processing.

func (ProxyTarget) Address

func (t ProxyTarget) Address() string

Address returns a host:port suitable for dialing the target.

func (ProxyTarget) AuthorityURI

func (t ProxyTarget) AuthorityURI() string

AuthorityURI returns the Proxy-Uri authority form required by RFC 8613.

type ReplayWindow

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

ReplayWindow rejects duplicate or stale Partial IV values. Authentication is performed while holding the window lock so concurrent copies cannot both be accepted. The window advances only after verify returns nil.

func NewReplayWindow

func NewReplayWindow(size uint8) (*ReplayWindow, error)

NewReplayWindow creates a sliding replay window of 1 to 64 sequence numbers. A size of zero selects the RFC default of 32; larger values are rejected.

func (*ReplayWindow) Accept

func (w *ReplayWindow) Accept(sequence uint64, verify func() error) error

Accept verifies a sequence number and records it only after successful authentication.

func (*ReplayWindow) RejectedBelowCutoff

func (w *ReplayWindow) RejectedBelowCutoff() uint64

RejectedBelowCutoff returns the number of inbound sequences rejected below the high-water cutoff loaded when this replay window was created.

type ReplayWindowHighWaterMarginProvider

type ReplayWindowHighWaterMarginProvider interface {
	ReplayWindowHighWaterMargin() uint64
}

ReplayWindowHighWaterMarginProvider optionally configures the number of accepted sequence advances between durable high-water mark writes.

type ReplayWindowHighWaterStore

type ReplayWindowHighWaterStore interface {
	LoadHighWater() (uint64, bool, error)
	SaveHighWater(uint64) error
}

ReplayWindowHighWaterStore optionally persists an exclusive sequence boundary in batches. After restart, sequences below the boundary are rejected, trading a bounded amount of availability for fewer durable writes.

type ReplayWindowState

type ReplayWindowState struct {
	HighestSequence uint64
	Bitmap          uint64
	Started         bool
	WindowSize      uint8
}

ReplayWindowState is the durable state needed to continue replay protection after a receiver restart.

type ReplayWindowStore

type ReplayWindowStore interface {
	Load() (ReplayWindowState, error)
	Save(ReplayWindowState) error
}

ReplayWindowStore loads and durably saves a receiver's replay state. Save must atomically persist sufficient replay state before returning nil. Stores implementing ReplayWindowHighWaterStore may persist a stricter exclusive sequence cutoff instead of the complete bitmap. Use a store dedicated to one Context and coordinate access if receiver processes can concurrently use the same security context.

type RequestInfo

type RequestInfo struct {
	RecipientID  []byte
	IDContext    []byte
	IDContextSet bool
	Protected    bool
}

RequestInfo describes the OSCORE identity of an incoming request. RecipientID is the request sender's identifier as seen by this endpoint. IDContextSet distinguishes an absent ID Context from a present empty one.

func RequestInfoFromContext

func RequestInfoFromContext(ctx context.Context) (RequestInfo, bool)

RequestInfoFromContext returns the OSCORE request metadata attached by a transport adapter. The returned identifier slices are independent copies.

type ResponseRequirements

type ResponseRequirements map[string]map[Exchange]time.Time

ResponseRequirements tracks tokens and exchanges that require OSCORE protection on their responses. Callers serialize access to this type.

func NewResponseRequirements

func NewResponseRequirements() ResponseRequirements

NewResponseRequirements creates an empty response requirement tracker.

func (ResponseRequirements) Add

func (r ResponseRequirements) Add(token string, exchange Exchange, expires time.Time)

Add records an exchange requirement. A zero expiry means no time-based expiry while the transport consumer remains active.

func (ResponseRequirements) Expire

func (r ResponseRequirements) Expire(now time.Time)

Expire removes all requirements whose non-zero expiry has passed.

func (ResponseRequirements) Has

func (r ResponseRequirements) Has(token string, now time.Time) bool

Has reports whether token has an unexpired response requirement.

func (ResponseRequirements) HasToken

func (r ResponseRequirements) HasToken(token string) bool

HasToken reports whether token has any response requirement, regardless of expiry.

func (ResponseRequirements) Remove

func (r ResponseRequirements) Remove(token string, exchange Exchange)

Remove removes one exchange requirement.

func (ResponseRequirements) RemoveMatching

func (r ResponseRequirements) RemoveMatching(token string, predicate func(Exchange) bool)

RemoveMatching removes requirements matching predicate.

func (ResponseRequirements) RemoveToken

func (r ResponseRequirements) RemoveToken(token string)

RemoveToken removes every requirement for token.

func (ResponseRequirements) Retain

func (r ResponseRequirements) Retain(token string, exchange Exchange)

Retain keeps an exchange requirement active until explicitly removed.

type SenderSequenceReserver

type SenderSequenceReserver interface {
	Reserve() (uint64, error)
}

SenderSequenceReserver returns sender sequence numbers from durably reserved space. Implementations shared by multiple Context instances must coordinate reservations so that a number is never returned more than once. Values may be skipped, including after a restart. A returned number remains consumed even if message protection or transmission later fails.

type SequenceBinder

type SequenceBinder interface {
	Bind(fingerprint [sha256.Size]byte) error
}

SequenceBinder associates a sender sequence store with the OSCORE sender context whose Partial IVs it reserves.

Directories

Path Synopsis
Package proxy provides a minimal opaque forwarder for OSCORE-protected CoAP requests.
Package proxy provides a minimal opaque forwarder for OSCORE-protected CoAP requests.
Package store provides file-backed OSCORE state stores.
Package store provides file-backed OSCORE state stores.

Jump to

Keyboard shortcuts

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