proto

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: AGPL-3.0 Imports: 11 Imported by: 0 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 proto is a reference implementation of the OpenCharUI E2E handshake and AEAD session (spec/PROTOCOL.md §4-§6). The relay itself never calls this package — channel 0x01/0x02 payloads are opaque to it. It exists so the Go side can (a) generate cross-checked test vectors and (b) drive the fakeagent/fakeclient test harnesses used to validate the server and, later, amallo and web against a real peer.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrBadLength       = errors.New("proto: wrong-length input")
	ErrBadMAC          = errors.New("proto: HELLO MAC verification failed")
	ErrPairMismatch    = errors.New("proto: HELLO pair_id does not match")
	ErrRoleReflection  = errors.New("proto: peer HELLO has the same role as us")
	ErrBadVersion      = errors.New("proto: unsupported protocol version")
	ErrBadPoint        = errors.New("proto: ephemeral public key is not a valid P-256 point")
	ErrConfirmMismatch = errors.New("proto: CONFIRM tag verification failed")
	ErrConfirmRole     = errors.New("proto: CONFIRM role does not match expected peer")
)
View Source
var (
	ErrCounterMismatch  = errors.New("proto: ciphertext counter does not match expected value (spec §5: no gap, no reorder tolerance)")
	ErrCounterExhausted = errors.New("proto: direction counter exhausted; session MUST be torn down, never wrapped")
	ErrAuthFailed       = errors.New("proto: AEAD authentication failed (tampered ciphertext or AAD)")
)

Functions

func BuildConfirm

func BuildConfirm(prk []byte, role Role) []byte

BuildConfirm encodes this side's CONFIRM (spec §4.5). role is the sender's own role.

func BuildHello

func BuildHello(psk []byte, role Role, pairID [pairIDLen]byte, epk []byte, nonce [nonceLen]byte) ([]byte, error)

BuildHello encodes and MACs a HELLO message (spec §4.3). nonce must be exactly 32 bytes — callers pass a fresh random nonce in production and a vector-fixed nonce when generating test vectors.

func EphemeralRawScalar

func EphemeralRawScalar(e *Ephemeral) []byte

EphemeralRawScalar returns the raw 32-byte P-256 private scalar backing e. Production handshake code never needs this — session key material is always derived through ECDH — but cmd/genvectors publishes it so other implementations can reconstruct the exact same key pair from a vector input via EphemeralFromScalar.

func ErrorCode

func ErrorCode(err error) string

ErrorCode maps a proto error to the stable string used in test vectors' "expect_error" field. This indirection exists because Go error identity (via errors.Is) is not something Rust or TypeScript can share — vectors need a plain string every implementation agrees on.

func KMac

func KMac(psk []byte) []byte

KMac and PSKIKM re-export the two intermediate HKDF values used inside BuildHello/VerifyHello and DeriveSession. Normal handshake code never needs these directly; they exist so cmd/genvectors can publish intermediate values in the shared test vectors, letting the Rust and TypeScript implementations cross-check each derivation step independently rather than only the final session keys.

func PSKIKM

func PSKIKM(psk []byte, transcript [32]byte) []byte

func Transcript

func Transcript(helloAgent, helloWeb []byte) [32]byte

Transcript computes spec §4.4's canonical, role-ordered transcript hash. helloAgent and helloWeb are the exact 147-byte HELLO wire encodings — agent's HELLO always precedes web's in the hash input, regardless of which one either side observed first.

func VerifyConfirm

func VerifyConfirm(prk []byte, raw []byte, expectRole Role) error

VerifyConfirm checks a peer's CONFIRM. expectRole is the *peer's* expected role (i.e. the role opposite to the verifier). No channel-0x01 frame may be sent or accepted before this succeeds (spec §4.5) — enforced by callers, not by this function.

Types

type Ephemeral

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

Ephemeral wraps one P-256 ECDH key pair, used for exactly one handshake and never persisted or reused across reconnects (spec §4.2).

func EphemeralFromScalar

func EphemeralFromScalar(scalar []byte) (*Ephemeral, error)

EphemeralFromScalar constructs a deterministic key pair from a raw 32-byte big-endian scalar. This exists solely so test vectors can make the handshake a pure function: the vector supplies the "random" input instead of the implementation generating it. Every implementation of this spec MUST expose an equivalent seam — see testdata/vectors and the build plan's note that this seam must not be retrofitted later.

func GenerateEphemeral

func GenerateEphemeral() (*Ephemeral, error)

GenerateEphemeral creates a fresh, random ephemeral key pair.

func (*Ephemeral) ECDH

func (e *Ephemeral) ECDH(peerEpk []byte) ([]byte, error)

ECDH performs the key agreement against a peer's HELLO-carried public key and returns the shared X-coordinate (spec §4.4's ecdh_x). peerEpk is the raw 65-byte uncompressed point from the peer's HELLO; ErrBadPoint if it is not a valid point on P-256 (this is also where invalid-curve attacks are rejected — crypto/ecdh validates on import).

func (*Ephemeral) PublicKeyBytes

func (e *Ephemeral) PublicKeyBytes() []byte

PublicKeyBytes returns the uncompressed SEC1 encoding (65 bytes) used as `epk` in HELLO.

type HelloFields

type HelloFields struct {
	Ver    byte
	Role   Role
	PairID [pairIDLen]byte
	Epk    []byte // 65 bytes
	Nonce  [nonceLen]byte
	Mac    []byte // 32 bytes
	Raw    []byte // the exact 147 bytes, needed verbatim for the transcript
}

HelloFields is a parsed, not-yet-verified HELLO.

func ParseHello

func ParseHello(raw []byte) (HelloFields, error)

ParseHello splits a raw HELLO without verifying it — use VerifyHello for the authenticated path. Exposed separately because negative test vectors need to observe "parses fine, fails verification" distinctly.

func VerifyHello

func VerifyHello(psk []byte, raw []byte, expectPairID [pairIDLen]byte, ownRole Role) (HelloFields, error)

VerifyHello parses raw and applies every check from spec §4.3: MAC, pair_id match, role-reflection defence, and point validity. ownRole is the verifier's own role, used to reject a reflected HELLO with the same role as the verifier — a peer's HELLO must always have the *other* role.

type Opener

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

Opener decrypts and authenticates one direction of a session. It rejects any payload whose counter is not exactly the next expected value — no window, no reordering (spec §5).

func NewOpener

func NewOpener(key, prefix []byte) (*Opener, error)

NewOpener builds an Opener for a 32-byte AES-256 key and 4-byte nonce prefix. Use the *other* direction's key/prefix than the paired Sealer — e.g. an agent's Opener uses KW2A/NPW2A while its Sealer uses KA2W/NPA2W.

func (*Opener) Open

func (o *Opener) Open(headerBytes, payload []byte) ([]byte, error)

Open verifies and decrypts a channel-0x01 payload. headerBytes must be the exact outer-frame header bytes that accompanied this payload on the wire (see wire.OuterHeader.HeaderBytes).

type Role

type Role byte

Role mirrors spec §4.3 (agent=0x01, client=0x02) — deliberately not the wire.Role string type, since this is the single-byte form that goes inside HMAC/transcript input.

const (
	RoleAgent  Role = 0x01
	RoleClient Role = 0x02
)

type Sealer

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

Sealer encrypts one direction of a session (spec §5). It owns the counter exclusively.

spec §5.1 is not a suggestion: exactly one Sealer must exist per direction, and it must not be shared across goroutines/tasks without an external mutex serializing every call to Seal. Concurrent unsynchronized use produces two frames encrypted under the same nonce, which breaks AES-GCM catastrophically (authentication key recovery, plaintext XOR disclosure). This type's zero built-in synchronization is deliberate: it pushes implementers toward the "one owning task, fed by a channel" pattern described in the plan, rather than a mutex that invites sharing the Sealer across call sites "for convenience".

func NewSealer

func NewSealer(key, prefix []byte) (*Sealer, error)

NewSealer builds a Sealer for a 32-byte AES-256 key and 4-byte nonce prefix (one of SessionKeys.KA2W/KW2A paired with NPA2W/NPW2A).

func NewSealerAt

func NewSealerAt(key, prefix []byte, startCounter uint64) *Sealer

NewSealerAt builds a Sealer whose counter starts at startCounter rather than 0. Test/vector-generation only: normal sessions always start a fresh Sealer at counter 0 (spec §5.1 — keys are never reused across reconnects, so there is never a legitimate production reason to resume a counter). It exists so cmd/genvectors can publish AEAD vectors at specific counter values, including the 2^32 boundary, without a real implementation exposing a public "set counter" foot-gun.

func (*Sealer) Seal

func (s *Sealer) Seal(headerBytes, plaintext []byte) ([]byte, error)

Seal encrypts plaintext for the given outer-frame header bytes (spec §5: AAD = outer_header_bytes || counter) and returns the full channel-0x01 payload: [counter:8][ciphertext||tag]. It advances the internal counter by one. Returns ErrCounterExhausted — a hard failure, never a silent wrap — if the counter would overflow.

type SessionKeys

type SessionKeys struct {
	PRK   []byte // 32 bytes; kept only to derive CONFIRM tags
	KA2W  []byte // 32 bytes, AES-256 key for agent->web
	KW2A  []byte // 32 bytes, AES-256 key for web->agent
	NPA2W []byte // 4 bytes, nonce prefix agent->web
	NPW2A []byte // 4 bytes, nonce prefix web->agent
}

SessionKeys holds everything derived from one handshake (spec §4.4).

func DeriveSession

func DeriveSession(psk []byte, transcript [32]byte, ecdhX []byte) (SessionKeys, error)

DeriveSession computes the session keys from the PSK, the transcript, and the raw ECDH shared secret (spec §4.4). psk_ikm is folded into the PRK extraction specifically so that a relay without the PSK — even one that swapped both ephemeral public keys in transit — cannot derive anything past this point.

Jump to

Keyboard shortcuts

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