Documentation
¶
Overview ¶
Package security hosts the ZMTP security mechanisms NULL and PLAIN plus the RFC 27 ZAP authorization codec. Each mechanism implements Mech so the session layer drives them through the same state-machine loop. CURVE lives in the security/curve subpackage because it also exposes key-pair primitives to callers.
Choosing an extension point ¶
ZMTP defines exactly three mechanisms — NULL, PLAIN, and CURVE — and gozmq implements all three. (libzmq additionally ships GSSAPI, specified separately in RFC 38; gozmq does not implement it.) A fourth mechanism would not interoperate with any other ZMTP peer, so for nearly every application the shipped three are the complete set.
What applications usually want to customize is authorization policy, not the mechanism. That is pluggable without touching the wire: implement ZAPHandler and install it with gozmq.WithZAPHandler. A ZAP handler decides which PLAIN credentials or CURVE public keys are allowed, per RFC 27, while the vetted mechanism implementations keep handling the cryptography.
Mech is nonetheless a public interface, so an out-of-tree mechanism is possible — for a private protocol variant, or a fault-injecting test double. Treat it as a last resort: a Mech sits directly on the wire, so a mistake there is a security bug. See the Mech documentation before starting.
Index ¶
- Constants
- Variables
- func DecodeError(body []byte) (reason string, isError bool, err error)
- func DecodeMetadata(b []byte) (map[string]string, error)
- func DecodeReady(body []byte) (map[string]string, error)
- func EncodeMetadata(meta map[string]string) []byte
- func EncodeReady(meta map[string]string) []byte
- func EncodeZAPRequest(req *ZAPRequest) [][]byte
- func EncodeZAPResponse(resp *ZAPResponse) [][]byte
- type Mech
- type MechBase
- func (b *MechBase) AsServer() bool
- func (b *MechBase) AuthorizeZAP(mech string, credentials [][]byte) error
- func (b *MechBase) ConfigureZAP(handler ZAPHandler, domain, address string)
- func (b *MechBase) MergePeerMetadata(props map[string]string)
- func (b *MechBase) Metadata() map[string]string
- func (b *MechBase) PeerMetadata() map[string]string
- func (b *MechBase) Role() Role
- type Role
- type ZAPHandler
- type ZAPRequest
- type ZAPResponse
Constants ¶
const ( ZAPStatusOK = "200" ZAPStatusTempError = "300" ZAPStatusClientError = "400" ZAPStatusServerError = "500" )
ZAP status codes (RFC 27 §3.2).
Variables ¶
var ErrZAPTemporary = errors.New("gozmq/security/zap: temporary authentication failure")
ErrZAPTemporary, when wrapped by a ZAPHandler error, marks the failure as temporary: a 300 response instead of 400/500. Wrap it via fmt.Errorf("...: %w", security.ErrZAPTemporary).
Functions ¶
func DecodeError ¶
DecodeError reports whether body is a ZMTP ERROR command: the reply a peer sends in place of the expected handshake command when it rejects the handshake, e.g. after a ZAP denial. isError is false for any other command, including one too malformed to name. When isError is true, reason is the peer's reason text, or err wraps gozmq.ErrMalformedFrame if that text is truncated. A mechanism should report a decoded ERROR as an error wrapping gozmq.ErrAuthFailed.
It tolerates the mis-encoded ERROR name libzmq emits.
func DecodeMetadata ¶
DecodeMetadata parses a ZMTP 3.1 §5.2 property list. It returns an error wrapping gozmq.ErrMalformedFrame on a truncated or malformed list.
func DecodeReady ¶
DecodeReady parses the wire bytes of a peer's READY command and returns its metadata properties. It returns an error wrapping gozmq.ErrMalformedFrame when body is not a well-formed READY — a truncated command, a different command name, or malformed properties.
Feed the result to MechBase.MergePeerMetadata so the session layer sees the peer's identity and socket type. (The session layer runs the Socket-Type compatibility check itself after the handshake.)
A peer that rejects the handshake answers with ERROR instead of READY; check for that with DecodeError first.
func EncodeMetadata ¶
EncodeMetadata returns the ZMTP 3.1 §5.2 property-list encoding of meta: for each entry, a one-byte name length, the name, a four-byte big-endian value length, and the value. Mechanisms that carry metadata in something other than a bare READY — PLAIN's INITIATE, CURVE's sealed boxes — encode with this and frame it themselves.
Property names must be at most 255 bytes and values at most 2^32-1 bytes; longer entries panic, since they cannot be produced by any valid configuration.
func EncodeReady ¶
EncodeReady returns the wire bytes of a ZMTP READY command whose body is the given metadata properties. Pass the map from MechBase.Metadata to advertise exactly what gozmq expects the peer to see.
The same size limits as EncodeMetadata apply.
func EncodeZAPRequest ¶
func EncodeZAPRequest(req *ZAPRequest) [][]byte
EncodeZAPRequest serializes req into the RFC 27 §3.1 multi-frame form. The returned slice holds the request frames in order and aliases req.RequestID, req.Identity, and each req.Credentials[i] — callers must not mutate those byte slices while the encoded frames are in flight.
func EncodeZAPResponse ¶
func EncodeZAPResponse(resp *ZAPResponse) [][]byte
EncodeZAPResponse serializes resp into RFC 27 §3.2 multi-frame form. A nil Metadata map is treated as empty (zero-length frame 5). The returned slice does NOT alias resp's fields — we allocate fresh frames because responses typically flow on a socket that will pool/retain them.
Metadata a property list cannot carry (a name over 255 bytes, or a value over 2^32-1) is a policy bug; rather than panic inside a handshake, the response is replaced with a 500 carrying no user-id or metadata.
Types ¶
type Mech ¶
type Mech interface {
// Name is the greeting mechanism token (e.g. "NULL", "PLAIN", "CURVE"),
// unpadded; the greeting encoder pads to 20 bytes.
Name() string
// AsServer reports the value of the greeting as-server byte.
AsServer() bool
// NextHandshake advances the handshake. On the first call, in is nil.
// Returns the next outbound command (may be empty on final step) and
// done=true when the handshake is complete.
NextHandshake(in []byte) (out []byte, done bool, err error)
// EncodeFrame rewrites a plaintext frame body and its ZMTP flags into
// their wire form. NULL/PLAIN preserve both body and flags. CURVE, as
// libzmq does, moves MORE and COMMAND into the encrypted MESSAGE inner
// flags byte and clears them from the wire flags.
EncodeFrame(flags uint8, plain []byte) (wireFlags uint8, wire []byte, err error)
// DecodeFrame reverses EncodeFrame. The returned flags are the logical
// post-decode frame flags seen by the session layer. A mechanism that
// authenticates frames must derive them from authenticated data only
// (CURVE ignores the outer wire flags, which are not under the MAC, as
// libzmq does). Returns ErrMalformedFrame on MAC failure.
DecodeFrame(flags uint8, wire []byte) (plainFlags uint8, plain []byte, err error)
// Metadata returns local properties sent in READY. Must return after
// the handshake is seeded.
Metadata() map[string]string
// PeerMetadata returns the properties the peer advertised during the
// handshake. The session layer reads it once NextHandshake reports done,
// to check Socket-Type compatibility and learn the peer's Identity; a
// nil map at that point fails the session.
PeerMetadata() map[string]string
}
Mech drives a single handshake exchange and, for mechanisms that require it (CURVE), wraps/unwraps every subsequent frame body.
The handshake is modeled as a lock-step NextHandshake loop. The session layer drives it:
out, done, err := mech.NextHandshake(nil) // seed
for !done {
write(out); in := read()
out, done, err = mech.NextHandshake(in)
}
For NULL the handshake is a single READY exchange; for CURVE it is the five-step HELLO/WELCOME/INITIATE/READY/MESSAGE sequence.
Implementing this interface out of tree is supported but is a serious undertaking: a Mech sits directly on the wire, and a mistake in NextHandshake, EncodeFrame, or DecodeFrame is a security bug, not a correctness bug. Embed MechBase to inherit the metadata and ZAP plumbing, read the relevant RFC (23 for the ZMTP framing, 24 for PLAIN, 25/26 for CURVE, 27 for ZAP), and test against libzmq. Prefer the shipped mechanisms — NULL, PLAIN, CURVE — plus a ZAPHandler for authorization policy, which is the extension point most applications actually want.
A mechanism whose EncodeFrame and DecodeFrame leave bodies and flags unchanged (as NULL and PLAIN do) may also implement
IdentityFraming() bool
returning true; the session then skips both calls and uses its zero-copy framing path. Without it, EncodeFrame and DecodeFrame run on every traffic-phase frame.
func NewNull ¶
NewNull returns a NULL security mechanism configured for role and advertising localMeta in its READY command. A nil localMeta is treated as an empty property list. The returned value is not safe for concurrent use; the session layer drives NextHandshake single-threaded.
func NewPlainClient ¶
NewPlainClient returns a PLAIN mechanism configured as the initiator. It advertises localMeta in its outbound INITIATE. username and password are sent verbatim in HELLO, per RFC 24 §4 (length-prefixed, max 255 each). localMeta may be nil.
func NewPlainServer ¶
NewPlainServer returns a PLAIN mechanism configured as the acceptor. The authenticate callback is invoked once on receipt of HELLO; returning false causes the mechanism to emit an ERROR command and return an error wrapping gozmq.ErrAuthFailed from the next NextHandshake call so the session layer tears the connection down. A nil authenticate callback is equivalent to one that always returns false.
Implementations of authenticate should compare the supplied password using crypto/subtle.ConstantTimeCompare (or compare salted hashes) rather than ==, so a network peer cannot use response timing to probe the password byte-by-byte. The credentials are not retained by the mechanism after the authentication decision is made.
type MechBase ¶
type MechBase struct {
// contains filtered or unexported fields
}
MechBase is the state shared by every security mechanism: the role, the local metadata advertised during the handshake, the peer metadata learned from it, and the optional server-side ZAP handler with its verdict. Mechanisms embed it by value; like the mechanisms themselves it is not safe for concurrent use.
func NewMechBase ¶
NewMechBase returns the shared mechanism state for role, holding a private copy of localMeta. A nil localMeta is treated as an empty property list.
func (*MechBase) AuthorizeZAP ¶
AuthorizeZAP consults the configured handler with the mechanism-specific credentials. A rejection is an authorization failure whatever the handler returned, so its error is wrapped with ErrAuthFailed unless it already wraps it (the handler's error stays in the chain). It is a no-op (returning nil) when no handler is configured. On success the handler's user-id and metadata are kept for MechBase.MergePeerMetadata.
func (*MechBase) ConfigureZAP ¶
func (b *MechBase) ConfigureZAP(handler ZAPHandler, domain, address string)
ConfigureZAP installs a server-side ZAP handler. The socket calls it, before the handshake, on any server-side mechanism that has this method when its Context has a handler, so a mechanism embedding MechBase only needs to call MechBase.AuthorizeZAP. Client-side mechanisms ignore it.
func (*MechBase) MergePeerMetadata ¶
MergePeerMetadata stores props as the peer metadata, adding what ZAP returned. Mechanisms call it from the handshake step that parses the peer's metadata-bearing command. ZAP metadata only fills in property names the peer did not send (names compare case-insensitively, as in ZMTP), so a policy cannot rewrite the peer's Identity or Socket-Type. A non-empty ZAP user-id becomes the "User-Id" property, as in libzmq, replacing any the peer claimed for itself.
func (*MechBase) Metadata ¶
Metadata returns a copy of the local metadata properties sent in the mechanism's metadata-bearing handshake command (READY or INITIATE). The copy guards against external mutation after construction.
func (*MechBase) PeerMetadata ¶
PeerMetadata returns a copy of the peer metadata stored by MechBase.MergePeerMetadata, or nil before then.
type Role ¶
type Role uint8
Role distinguishes the initiator (client, from Connect) from the acceptor (server, from Bind) within a single session. Some security mechanisms and socket patterns branch on role.
type ZAPHandler ¶
type ZAPHandler func(domain, address, mech string, credentials [][]byte) (userID string, metadata map[string]string, err error)
ZAPHandler is an RFC 27 authorization policy. It is given the ZAP domain, the peer's address, the mechanism name, and that mechanism's credentials (PLAIN: username and password; CURVE: the client's 32-byte long-term public key; NULL: none), and accepts the peer by returning a nil error.
gozmq.WithZAPHandler installs one on a Context, which then calls it directly from the server side of each handshake, concurrently when handshakes overlap; a rejection fails the handshake with an error that wraps both gozmq.ErrAuthFailed and the one returned here. On success a non-empty userID becomes the peer's "User-Id" property, and metadata adds properties under names the peer did not send itself.
ServeRequest adapts the same function to the RFC 27 wire protocol, mapping its error to a status code:
- nil error -> 200 OK
- error wrapping ErrZAPTemporary -> 300 Temporary Error
- error wrapping ErrAuthFailed -> 400 Client Error
- any other error -> 500 Server Error
so, for wire interop, a rejection should wrap gozmq.ErrAuthFailed.
func (ZAPHandler) ServeRequest ¶
func (h ZAPHandler) ServeRequest(reqFrames [][]byte) [][]byte
ServeRequest executes one request/response cycle. It parses the raw frames, invokes h, and serializes the reply. Malformed input produces a 500 response per RFC 27 §3.2 so the peer mechanism sees a terminating failure rather than a timeout.
The frames slice ownership is the caller's; this function does not retain or mutate it.
type ZAPRequest ¶
type ZAPRequest struct {
Version string // must be "1.0"
RequestID []byte // opaque, echoed in response
Domain string
Address string
Identity []byte
Mechanism string // "NULL" | "PLAIN" | "CURVE"
Credentials [][]byte // mechanism-specific
}
ZAPRequest is the decoded form of a RFC 27 §3.1 request. All frames are kept as []byte because the identity and credentials are opaque binary.
func DecodeZAPRequest ¶
func DecodeZAPRequest(frames [][]byte) (*ZAPRequest, error)
DecodeZAPRequest parses a multi-frame ZAP request. The returned ZAPRequest's byte-slice fields reference the input frames — callers that need independent ownership must copy.
Errors wrap gozmq.ErrMalformedFrame. We are strict about version: only "1.0" is accepted, matching libzmq's zap_handler_v2.
type ZAPResponse ¶
type ZAPResponse struct {
Version string
RequestID []byte
StatusCode string
StatusText string
UserID string
Metadata map[string]string
}
ZAPResponse is the decoded form of a RFC 27 §3.2 response.
func DecodeZAPResponse ¶
func DecodeZAPResponse(frames [][]byte) (*ZAPResponse, error)
DecodeZAPResponse parses a multi-frame ZAP response. Version mismatch or a short frame count produces ErrMalformedFrame.