From 2ad36e7a2722fb893528fb4d90118c50459cfa2d Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 12:51:41 +0200 Subject: [PATCH 1/3] refactor: tableUser in receiver.go, beside the receiver's user table The receiver's user-table entry was declared in v3_usm.go, though only receiver.go and receiver_answer.go use it. A move only. --- receiver.go | 8 ++++++++ v3_usm.go | 8 -------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/receiver.go b/receiver.go index f5fb710..3b5986a 100644 --- a/receiver.go +++ b/receiver.go @@ -39,6 +39,14 @@ type Receiver struct { local *localEngine } +// tableUser is a user a receiver decodes messages for, with its keys localized +// to the engine ID it is registered for, the only one whose messages it +// decodes (Receiver). +type tableUser struct { + user User + keys usmKeys +} + // ReceiverConfig configures a Receiver. type ReceiverConfig struct { // Users are the SNMPv3 users of each engine: an SNMPv3 message is diff --git a/v3_usm.go b/v3_usm.go index e025cb5..1c3e993 100644 --- a/v3_usm.go +++ b/v3_usm.go @@ -385,14 +385,6 @@ func (h *SecurityParameters) marshal(dst []byte, level SecurityLevel, auth AuthP return ber.EndMoving(dst, start, off) } -// tableUser is a user a receiver decodes messages for, with its keys localized -// to the engine ID it is registered for, the only one whose messages it -// decodes (Receiver). -type tableUser struct { - user User - keys usmKeys -} - // inbound is an SNMPv3 message in security processing for one user (RFC 3414 // section 3.2): the message, which is never written, where its authentication // parameters and msgData are, the user and its keys for the message's engine From e06cbc594f2e11314bb3c5573587a81f013df684 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 12:52:43 +0200 Subject: [PATCH 2/3] refactor: reply acceptance in engine_reply.go engine.go keeps a request's attempts: send, request, the exchange and its attempt types, sendOneRequest and the attempt loop. engine_reply.go takes what decides about a reply: the discard ranking, matching a reply to an attempt, its decode and security checks, whether it answers the request, and the Report kinds. Declarations move unchanged. --- engine.go | 307 ---------------------------------------------- engine_reply.go | 316 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 316 insertions(+), 307 deletions(-) create mode 100644 engine_reply.go diff --git a/engine.go b/engine.go index cc7d6bb..18166e7 100644 --- a/engine.go +++ b/engine.go @@ -5,13 +5,11 @@ package gosnmp import ( - "bytes" "context" "errors" "fmt" "net" "os" - "strings" "time" ) @@ -115,17 +113,6 @@ func requestPanicked(v any) error { return fmt.Errorf("request panicked: %v", v) } -// resyncKindOf returns the kind of result, an answer, when it is a Report; -// its resync field marks one that resynchronizes the client with the agent's -// engine. -func resyncKindOf(result *Message) reportKind { - if result == nil { - return reportKind{} - } - kind, _ := reportKindOf(result) - return kind -} - // exchange is one request on its way through the attempts sendOneRequest // makes. type exchange struct { @@ -155,23 +142,6 @@ type exchange struct { outOfWindow bool } -// discardRank orders the messages an exchange discards by how close they came -// to answering it, by the ID that names its attempts: the msgID of an SNMPv3 -// request, the request ID of another. Zero is a message that answers another -// request, whose reason is not recorded. -type discardRank uint8 - -const ( - // rankUnread: a message whose ID could not be read. - rankUnread discardRank = iota + 1 - // rankNamed: a message with the ID of one of the exchange's attempts that - // did not authenticate. - rankNamed - // rankAuthentic: an authentic message with the msgID of one of the - // exchange's attempts. - rankAuthentic -) - // attemptKind is how an attempt ended. type attemptKind uint8 @@ -444,280 +414,3 @@ func (e *exchange) await(conn transport, earlier []sentIDs) attemptOutcome { e.discard(rejected, rankAuthentic) } } - -// discard records err, the reason a message of rank was discarded, when it -// came closer to answering the request than the discards before it, or as -// close and later. -func (e *exchange) discard(err error, rank discardRank) { - if rank != 0 && rank >= e.discardedRank { - e.discarded, e.discardedRank = err, rank - } -} - -// rankOf returns the rank of a discarded message: read is the message as far -// as decode read it when it read the ID that names the request's attempts, and -// verified reports that its digest checked. A message that names none of the -// exchange's attempts (attemptOf) answers another request: rank zero; so does -// an SNMPv1 or SNMPv2c message other than a Response, whose request ID -// names no request. A verified request or inform (the Confirmed Class), such -// as the request sent back unchanged, proves the client's key, not the -// agent's: it ranks as a named message, below an authentic reply. -func (e *exchange) rankOf(read *Message, verified bool, earlier []sentIDs) discardRank { - if read == nil { - return rankUnread - } - if !e.named(read, earlier) || e.req.Version != Version3 && read.PDUType != Response { - return 0 - } - if verified && !read.PDUType.confirmed() { - return rankAuthentic - } - return rankNamed -} - -// attemptOf returns the IDs the exchange's attempt that reply names sent the -// request with, the current attempt's or one of earlier: by the msgID for an -// SNMPv3 request (RFC 3412 section 7.2 step 10 a), else by the request ID; -// false when reply names none. -func (e *exchange) attemptOf(reply *Message, earlier []sentIDs) (sentIDs, bool) { - if current := (sentIDs{e.req.RequestID, e.req.MsgID}); e.names(reply, current) { - return current, true - } - for _, ids := range earlier { - if e.names(reply, ids) { - return ids, true - } - } - return sentIDs{}, false -} - -// names reports whether reply names the attempt that sent the request with -// ids: by the msgID for an SNMPv3 request, else by the request ID. -func (e *exchange) names(reply *Message, ids sentIDs) bool { - if e.req.Version == Version3 { - return reply.MsgID == ids.msgID - } - return reply.RequestID == ids.requestID -} - -// named reports whether reply names one of the exchange's attempts -// (attemptOf). -func (e *exchange) named(reply *Message, earlier []sentIDs) bool { - _, ok := e.attemptOf(reply, earlier) - return ok -} - -// decode decodes a message read for the request: the header, which fails a -// message of another SNMP version than the request's and, for an SNMPv3 -// request, one whose msgID names none of the exchange's attempts (attemptOf), -// before security processing; for an SNMPv3 request, the security processing -// by the message's own level (RFC 3414 section 3.2: receiveReply, the digest -// exactly when it asks for authentication, decryption exactly when it asks for -// privacy) with the exchange's keys, which no reply changes: no key derives -// for an engine a reply names; then the scoped PDU and the PDU. It reports -// whether the message's digest checked with the request's key. With an error -// it returns the message as far as it read it when it read the ID that names -// the request's attempts (rankOf), else nil. -func (e *exchange) decode(resp []byte, earlier []sentIDs) (_ *Message, verified bool, _ error) { - reply := &Message{} - v3 := e.req.Version == Version3 - cursor, w, err := unmarshalHeader(resp, reply) - switch { - case err != nil: - case reply.Version != e.req.Version: - err = errOtherVersion - case !v3: - case !e.named(reply, earlier): - err = errOtherMessage - default: - err = receiveReply(reply.SecurityLevel, &reply.SecurityParameters, &e.req.SecurityParameters, &e.sec.keys) - } - // read is reply, as far as it was read, when an error ends the decode: for - // an SNMPv3 request when the SNMPv3 header's msgID decoded, for another - // when the PDU's request ID did (atPDU: the decode reached the PDU, which - // for an SNMPv3 request is after its msgID). - read := func(atPDU bool) *Message { - if v3 && w.msgIDRead || atPDU && requestIDRead(resp, cursor) { - return reply - } - return nil - } - if err != nil { - return read(false), false, err - } - if v3 { - if reply.SecurityLevel.authFlag() { - in := inbound{msg: resp, wire: w, keys: e.sec.keys} - if err = in.verify(); err != nil { - return read(false), false, err - } - verified = true - } - if resp, cursor, err = unmarshalScopedPDU(resp, cursor, reply, reply.SecurityLevel.privFlag(), &e.sec.keys); err != nil { - return read(false), verified, err - } - } - if err = unmarshalPayload(resp, cursor, reply); err != nil { - return read(true), verified, err - } - return reply, verified, nil -} - -// receiveReply applies RFC 3414 section 3.2 steps 4 and 5 to a reply at level -// whose USM parameters are got, to a request whose are want and whose keys are -// keys: the reply's user is the request's (else errUnknownUser), or the empty -// user of discovery, which has no protocols (as net-snmp's), so it names no -// reply that asks for authentication; a reply that asks for authentication -// names the request's engine ID, the only one the request's keys serve (else -// errUnknownUser); the request's keys have the protocols the level asks for. -func receiveReply(level SecurityLevel, got, want *SecurityParameters, keys *usmKeys) error { - if got.UserName != want.UserName { - if got.UserName != "" { - return errUnknownUser - } - if level.authFlag() { - return errNoAuthForMsg - } - } - if level.authFlag() && !bytes.Equal(got.AuthoritativeEngineID, want.AuthoritativeEngineID) { - return errUnknownUser - } - switch needAuth, needPriv := missingProtocol(keys.authProtocol, keys.privProtocol, level); { - case needAuth: - return errNoAuthForMsg - case needPriv: - return errNoPrivForMsg - } - return nil -} - -// The reasons a message is discarded for after the header decoded, besides -// security processing's (RFC 3412 section 7.2 steps 3, 10 and 12 b): the -// message does not answer the request, ErrUnmatchedReply. -var ( - errOtherVersion = unmatched("the reply is of another SNMP version than the request") - errOtherMessage = unmatched("the reply's msgID names no attempt of the request") - errNotAnswer = unmatched("the reply is neither a Response nor an SNMPv3 Report") - errOtherRequestID = unmatched("the reply's request ID does not match the request") - errOtherLevel = unmatched("the reply's security level is not the request's") - errOtherUser = unmatched("the reply's user name is not the request's") - errOtherEngine = unmatched("the reply's engine ID is not the request's") - errOtherContext = unmatched("the reply's context is not the request's") -) - -// unmatched returns the error with text, of ErrUnmatchedReply. -func unmatched(text string) error { return inCategory(ErrUnmatchedReply, errors.New(text)) } - -// answers reports whether reply, a message decode read for the request, answers -// it, with the error of a Report that does, or else the reason it does not (RFC -// 3412 section 7.2 steps 11 and 12; net-snmp's snmpv3_verify_msg). An SNMPv3 -// Report answers, whatever its request ID, level and context (security -// processing bound its user, and with authentication its engine ID), with its -// counter's error (reportKindOf), none for a resync Report. A Response answers -// with the request ID of the attempt it names (attemptOf: an SNMPv3 one by its -// msgID, so with that attempt's pair of IDs) and, for SNMPv3, the request's -// security level (the auth and priv flags), user name, engine ID, context -// engine ID and context name (step 12 b). Nothing else answers: a request sent -// back unchanged, SNMPv1 and SNMPv2c Reports. A message that does not answer -// leaves the request outstanding, as net-snmp does (step 12 b discards the -// request unless the model or level differs): a forged one cannot end it. -func (e *exchange) answers(reply *Message, earlier []sentIDs) (bool, error) { - if kind, ok := reportKindOf(reply); ok { - if kind.resync { - return true, nil - } - return true, kind.err - } - if reply.PDUType != Response { - return false, errNotAnswer - } - if ids, ok := e.attemptOf(reply, earlier); !ok || ids.requestID != reply.RequestID { - return false, errOtherRequestID - } - if e.req.Version != Version3 { - return true, nil - } - req := e.req - got, want := &reply.SecurityParameters, &req.SecurityParameters - switch { - case reply.SecurityLevel != req.SecurityLevel: - return false, errOtherLevel - case got.UserName != want.UserName: - return false, errOtherUser - case !bytes.Equal(got.AuthoritativeEngineID, want.AuthoritativeEngineID): - return false, errOtherEngine - case !bytes.Equal(reply.ContextEngineID, req.ContextEngineID) || reply.ContextName != req.ContextName: - return false, errOtherContext - } - return true, nil -} - -// The names of the counters an SNMPv3 Report can carry, with instance 0: the -// User-based Security Model's (RFC 3414) and message processing's (RFC 3412). -const ( - usmStatsUnsupportedSecLevels = ".1.3.6.1.6.3.15.1.1.1.0" - usmStatsNotInTimeWindows = ".1.3.6.1.6.3.15.1.1.2.0" - usmStatsUnknownUserNames = ".1.3.6.1.6.3.15.1.1.3.0" - usmStatsUnknownEngineIDs = ".1.3.6.1.6.3.15.1.1.4.0" - usmStatsWrongDigests = ".1.3.6.1.6.3.15.1.1.5.0" - usmStatsDecryptionErrors = ".1.3.6.1.6.3.15.1.1.6.0" - snmpUnknownSecurityModels = ".1.3.6.1.6.3.11.2.1.1.0" - snmpInvalidMsgs = ".1.3.6.1.6.3.11.2.1.2.0" - snmpUnknownPDUHandlers = ".1.3.6.1.6.3.11.2.1.3.0" -) - -// reportKind is what the counter an SNMPv3 Report carries means to a request. -type reportKind struct { - // err is the request's error. - err error - // resync marks the Reports that say the request's engine ID or time is out - // of date: they answer without err. discoverEngine takes the engine - // parameters of one; request sends the request again with them, or returns - // err when it may not or when a resync Report answers that too. - resync bool - // namesEngine marks the Report that names the engine ID the request - // should have had (RFC 3414 section 3.2 step 3): a resend takes the - // Report's engine ID along with its boots and time. - namesEngine bool - // timeWindow marks the Report that says the request's engine boots and - // time are outside the time window (RFC 3414 section 3.2 step 7 b). - timeWindow bool -} - -// reportKinds are the counters of the USM (RFC 3414) and of message processing -// (RFC 3412) a Report can carry, by the counter's OID (reportCounter). -var reportKinds = map[string]reportKind{ //nolint:gochecknoglobals // a read-only table - reportCounter(usmStatsUnsupportedSecLevels): {err: ErrUnknownSecurityLevel}, - reportCounter(usmStatsNotInTimeWindows): {err: ErrNotInTimeWindow, resync: true, timeWindow: true}, - reportCounter(usmStatsUnknownUserNames): {err: ErrUnknownUsername}, - reportCounter(usmStatsUnknownEngineIDs): {err: ErrUnknownEngineID, resync: true, namesEngine: true}, - reportCounter(usmStatsWrongDigests): {err: ErrWrongDigest}, - reportCounter(usmStatsDecryptionErrors): {err: ErrDecryption}, - reportCounter(snmpUnknownSecurityModels): {err: ErrUnknownSecurityModels}, - reportCounter(snmpInvalidMsgs): {err: ErrInvalidMsgs}, - reportCounter(snmpUnknownPDUHandlers): {err: ErrUnknownPDUHandlers}, -} - -// reportKindOf returns the kind of m as a Report, and false when m is not an -// SNMPv3 Report. The agent puts the counter of the error it detected in the -// Report's varbinds; the Report's request ID is the request's, or 0 when the -// agent could not read it. As in net-snmp's snmpv3_get_report_type, the first -// varbind names the counter, with one instance sub-identifier of any value; -// none, or another name, gives ErrUnknownReportPDU. -func reportKindOf(m *Message) (reportKind, bool) { - if m.Version != Version3 || m.PDUType != Report { - return reportKind{}, false - } - if len(m.VarBinds) > 0 { - if kind, ok := reportKinds[reportCounter(m.VarBinds[0].Name)]; ok { - return kind, true - } - } - return reportKind{err: ErrUnknownReportPDU}, true -} - -// reportCounter returns name, an OID, without its last sub-identifier: the -// counter of a Report's varbind name, without the instance. -func reportCounter(name string) string { - return name[:max(strings.LastIndexByte(name, '.'), 0)] -} diff --git a/engine_reply.go b/engine_reply.go new file mode 100644 index 0000000..fe2931b --- /dev/null +++ b/engine_reply.go @@ -0,0 +1,316 @@ +// Copyright 2012 The GoSNMP Authors. All rights reserved. Use of this +// source code is governed by a BSD-style license that can be found in the +// LICENSE file. + +package gosnmp + +import ( + "bytes" + "errors" + "strings" +) + +// discardRank orders the messages an exchange discards by how close they came +// to answering it, by the ID that names its attempts: the msgID of an SNMPv3 +// request, the request ID of another. Zero is a message that answers another +// request, whose reason is not recorded. +type discardRank uint8 + +const ( + // rankUnread: a message whose ID could not be read. + rankUnread discardRank = iota + 1 + // rankNamed: a message with the ID of one of the exchange's attempts that + // did not authenticate. + rankNamed + // rankAuthentic: an authentic message with the msgID of one of the + // exchange's attempts. + rankAuthentic +) + +// discard records err, the reason a message of rank was discarded, when it +// came closer to answering the request than the discards before it, or as +// close and later. +func (e *exchange) discard(err error, rank discardRank) { + if rank != 0 && rank >= e.discardedRank { + e.discarded, e.discardedRank = err, rank + } +} + +// rankOf returns the rank of a discarded message: read is the message as far +// as decode read it when it read the ID that names the request's attempts, and +// verified reports that its digest checked. A message that names none of the +// exchange's attempts (attemptOf) answers another request: rank zero; so does +// an SNMPv1 or SNMPv2c message other than a Response, whose request ID +// names no request. A verified request or inform (the Confirmed Class), such +// as the request sent back unchanged, proves the client's key, not the +// agent's: it ranks as a named message, below an authentic reply. +func (e *exchange) rankOf(read *Message, verified bool, earlier []sentIDs) discardRank { + if read == nil { + return rankUnread + } + if !e.named(read, earlier) || e.req.Version != Version3 && read.PDUType != Response { + return 0 + } + if verified && !read.PDUType.confirmed() { + return rankAuthentic + } + return rankNamed +} + +// attemptOf returns the IDs the exchange's attempt that reply names sent the +// request with, the current attempt's or one of earlier: by the msgID for an +// SNMPv3 request (RFC 3412 section 7.2 step 10 a), else by the request ID; +// false when reply names none. +func (e *exchange) attemptOf(reply *Message, earlier []sentIDs) (sentIDs, bool) { + if current := (sentIDs{e.req.RequestID, e.req.MsgID}); e.names(reply, current) { + return current, true + } + for _, ids := range earlier { + if e.names(reply, ids) { + return ids, true + } + } + return sentIDs{}, false +} + +// names reports whether reply names the attempt that sent the request with +// ids: by the msgID for an SNMPv3 request, else by the request ID. +func (e *exchange) names(reply *Message, ids sentIDs) bool { + if e.req.Version == Version3 { + return reply.MsgID == ids.msgID + } + return reply.RequestID == ids.requestID +} + +// named reports whether reply names one of the exchange's attempts +// (attemptOf). +func (e *exchange) named(reply *Message, earlier []sentIDs) bool { + _, ok := e.attemptOf(reply, earlier) + return ok +} + +// decode decodes a message read for the request: the header, which fails a +// message of another SNMP version than the request's and, for an SNMPv3 +// request, one whose msgID names none of the exchange's attempts (attemptOf), +// before security processing; for an SNMPv3 request, the security processing +// by the message's own level (RFC 3414 section 3.2: receiveReply, the digest +// exactly when it asks for authentication, decryption exactly when it asks for +// privacy) with the exchange's keys, which no reply changes: no key derives +// for an engine a reply names; then the scoped PDU and the PDU. It reports +// whether the message's digest checked with the request's key. With an error +// it returns the message as far as it read it when it read the ID that names +// the request's attempts (rankOf), else nil. +func (e *exchange) decode(resp []byte, earlier []sentIDs) (_ *Message, verified bool, _ error) { + reply := &Message{} + v3 := e.req.Version == Version3 + cursor, w, err := unmarshalHeader(resp, reply) + switch { + case err != nil: + case reply.Version != e.req.Version: + err = errOtherVersion + case !v3: + case !e.named(reply, earlier): + err = errOtherMessage + default: + err = receiveReply(reply.SecurityLevel, &reply.SecurityParameters, &e.req.SecurityParameters, &e.sec.keys) + } + // read is reply, as far as it was read, when an error ends the decode: for + // an SNMPv3 request when the SNMPv3 header's msgID decoded, for another + // when the PDU's request ID did (atPDU: the decode reached the PDU, which + // for an SNMPv3 request is after its msgID). + read := func(atPDU bool) *Message { + if v3 && w.msgIDRead || atPDU && requestIDRead(resp, cursor) { + return reply + } + return nil + } + if err != nil { + return read(false), false, err + } + if v3 { + if reply.SecurityLevel.authFlag() { + in := inbound{msg: resp, wire: w, keys: e.sec.keys} + if err = in.verify(); err != nil { + return read(false), false, err + } + verified = true + } + if resp, cursor, err = unmarshalScopedPDU(resp, cursor, reply, reply.SecurityLevel.privFlag(), &e.sec.keys); err != nil { + return read(false), verified, err + } + } + if err = unmarshalPayload(resp, cursor, reply); err != nil { + return read(true), verified, err + } + return reply, verified, nil +} + +// receiveReply applies RFC 3414 section 3.2 steps 4 and 5 to a reply at level +// whose USM parameters are got, to a request whose are want and whose keys are +// keys: the reply's user is the request's (else errUnknownUser), or the empty +// user of discovery, which has no protocols (as net-snmp's), so it names no +// reply that asks for authentication; a reply that asks for authentication +// names the request's engine ID, the only one the request's keys serve (else +// errUnknownUser); the request's keys have the protocols the level asks for. +func receiveReply(level SecurityLevel, got, want *SecurityParameters, keys *usmKeys) error { + if got.UserName != want.UserName { + if got.UserName != "" { + return errUnknownUser + } + if level.authFlag() { + return errNoAuthForMsg + } + } + if level.authFlag() && !bytes.Equal(got.AuthoritativeEngineID, want.AuthoritativeEngineID) { + return errUnknownUser + } + switch needAuth, needPriv := missingProtocol(keys.authProtocol, keys.privProtocol, level); { + case needAuth: + return errNoAuthForMsg + case needPriv: + return errNoPrivForMsg + } + return nil +} + +// The reasons a message is discarded for after the header decoded, besides +// security processing's (RFC 3412 section 7.2 steps 3, 10 and 12 b): the +// message does not answer the request, ErrUnmatchedReply. +var ( + errOtherVersion = unmatched("the reply is of another SNMP version than the request") + errOtherMessage = unmatched("the reply's msgID names no attempt of the request") + errNotAnswer = unmatched("the reply is neither a Response nor an SNMPv3 Report") + errOtherRequestID = unmatched("the reply's request ID does not match the request") + errOtherLevel = unmatched("the reply's security level is not the request's") + errOtherUser = unmatched("the reply's user name is not the request's") + errOtherEngine = unmatched("the reply's engine ID is not the request's") + errOtherContext = unmatched("the reply's context is not the request's") +) + +// unmatched returns the error with text, of ErrUnmatchedReply. +func unmatched(text string) error { return inCategory(ErrUnmatchedReply, errors.New(text)) } + +// answers reports whether reply, a message decode read for the request, answers +// it, with the error of a Report that does, or else the reason it does not (RFC +// 3412 section 7.2 steps 11 and 12; net-snmp's snmpv3_verify_msg). An SNMPv3 +// Report answers, whatever its request ID, level and context (security +// processing bound its user, and with authentication its engine ID), with its +// counter's error (reportKindOf), none for a resync Report. A Response answers +// with the request ID of the attempt it names (attemptOf: an SNMPv3 one by its +// msgID, so with that attempt's pair of IDs) and, for SNMPv3, the request's +// security level (the auth and priv flags), user name, engine ID, context +// engine ID and context name (step 12 b). Nothing else answers: a request sent +// back unchanged, SNMPv1 and SNMPv2c Reports. A message that does not answer +// leaves the request outstanding, as net-snmp does (step 12 b discards the +// request unless the model or level differs): a forged one cannot end it. +func (e *exchange) answers(reply *Message, earlier []sentIDs) (bool, error) { + if kind, ok := reportKindOf(reply); ok { + if kind.resync { + return true, nil + } + return true, kind.err + } + if reply.PDUType != Response { + return false, errNotAnswer + } + if ids, ok := e.attemptOf(reply, earlier); !ok || ids.requestID != reply.RequestID { + return false, errOtherRequestID + } + if e.req.Version != Version3 { + return true, nil + } + req := e.req + got, want := &reply.SecurityParameters, &req.SecurityParameters + switch { + case reply.SecurityLevel != req.SecurityLevel: + return false, errOtherLevel + case got.UserName != want.UserName: + return false, errOtherUser + case !bytes.Equal(got.AuthoritativeEngineID, want.AuthoritativeEngineID): + return false, errOtherEngine + case !bytes.Equal(reply.ContextEngineID, req.ContextEngineID) || reply.ContextName != req.ContextName: + return false, errOtherContext + } + return true, nil +} + +// The names of the counters an SNMPv3 Report can carry, with instance 0: the +// User-based Security Model's (RFC 3414) and message processing's (RFC 3412). +const ( + usmStatsUnsupportedSecLevels = ".1.3.6.1.6.3.15.1.1.1.0" + usmStatsNotInTimeWindows = ".1.3.6.1.6.3.15.1.1.2.0" + usmStatsUnknownUserNames = ".1.3.6.1.6.3.15.1.1.3.0" + usmStatsUnknownEngineIDs = ".1.3.6.1.6.3.15.1.1.4.0" + usmStatsWrongDigests = ".1.3.6.1.6.3.15.1.1.5.0" + usmStatsDecryptionErrors = ".1.3.6.1.6.3.15.1.1.6.0" + snmpUnknownSecurityModels = ".1.3.6.1.6.3.11.2.1.1.0" + snmpInvalidMsgs = ".1.3.6.1.6.3.11.2.1.2.0" + snmpUnknownPDUHandlers = ".1.3.6.1.6.3.11.2.1.3.0" +) + +// reportKind is what the counter an SNMPv3 Report carries means to a request. +type reportKind struct { + // err is the request's error. + err error + // resync marks the Reports that say the request's engine ID or time is out + // of date: they answer without err. discoverEngine takes the engine + // parameters of one; request sends the request again with them, or returns + // err when it may not or when a resync Report answers that too. + resync bool + // namesEngine marks the Report that names the engine ID the request + // should have had (RFC 3414 section 3.2 step 3): a resend takes the + // Report's engine ID along with its boots and time. + namesEngine bool + // timeWindow marks the Report that says the request's engine boots and + // time are outside the time window (RFC 3414 section 3.2 step 7 b). + timeWindow bool +} + +// reportKinds are the counters of the USM (RFC 3414) and of message processing +// (RFC 3412) a Report can carry, by the counter's OID (reportCounter). +var reportKinds = map[string]reportKind{ //nolint:gochecknoglobals // a read-only table + reportCounter(usmStatsUnsupportedSecLevels): {err: ErrUnknownSecurityLevel}, + reportCounter(usmStatsNotInTimeWindows): {err: ErrNotInTimeWindow, resync: true, timeWindow: true}, + reportCounter(usmStatsUnknownUserNames): {err: ErrUnknownUsername}, + reportCounter(usmStatsUnknownEngineIDs): {err: ErrUnknownEngineID, resync: true, namesEngine: true}, + reportCounter(usmStatsWrongDigests): {err: ErrWrongDigest}, + reportCounter(usmStatsDecryptionErrors): {err: ErrDecryption}, + reportCounter(snmpUnknownSecurityModels): {err: ErrUnknownSecurityModels}, + reportCounter(snmpInvalidMsgs): {err: ErrInvalidMsgs}, + reportCounter(snmpUnknownPDUHandlers): {err: ErrUnknownPDUHandlers}, +} + +// reportKindOf returns the kind of m as a Report, and false when m is not an +// SNMPv3 Report. The agent puts the counter of the error it detected in the +// Report's varbinds; the Report's request ID is the request's, or 0 when the +// agent could not read it. As in net-snmp's snmpv3_get_report_type, the first +// varbind names the counter, with one instance sub-identifier of any value; +// none, or another name, gives ErrUnknownReportPDU. +func reportKindOf(m *Message) (reportKind, bool) { + if m.Version != Version3 || m.PDUType != Report { + return reportKind{}, false + } + if len(m.VarBinds) > 0 { + if kind, ok := reportKinds[reportCounter(m.VarBinds[0].Name)]; ok { + return kind, true + } + } + return reportKind{err: ErrUnknownReportPDU}, true +} + +// resyncKindOf returns the kind of result, an answer, when it is a Report; +// its resync field marks one that resynchronizes the client with the agent's +// engine. +func resyncKindOf(result *Message) reportKind { + if result == nil { + return reportKind{} + } + kind, _ := reportKindOf(result) + return kind +} + +// reportCounter returns name, an OID, without its last sub-identifier: the +// counter of a Report's varbind name, without the instance. +func reportCounter(name string) string { + return name[:max(strings.LastIndexByte(name, '.'), 0)] +} From 17d388621ab9928066e11a9ea839a426bd026dda Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 12:53:13 +0200 Subject: [PATCH 3/3] test: name the test files inherited from upstream by what they test The codec's packet tests and its read tests move under the codec_ prefix the other codec tests use (marshal_test.go, helper_test.go), the Version stringer test to message_test.go (misc_test.go), and the client test helpers to client_helpers_test.go (testclient_test.go), as the receiver's are in receiver_helpers_test.go. Renames only. --- testclient_test.go => client_helpers_test.go | 0 marshal_test.go => codec_marshal_test.go | 0 helper_test.go => codec_reads_test.go | 0 misc_test.go => message_test.go | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename testclient_test.go => client_helpers_test.go (100%) rename marshal_test.go => codec_marshal_test.go (100%) rename helper_test.go => codec_reads_test.go (100%) rename misc_test.go => message_test.go (100%) diff --git a/testclient_test.go b/client_helpers_test.go similarity index 100% rename from testclient_test.go rename to client_helpers_test.go diff --git a/marshal_test.go b/codec_marshal_test.go similarity index 100% rename from marshal_test.go rename to codec_marshal_test.go diff --git a/helper_test.go b/codec_reads_test.go similarity index 100% rename from helper_test.go rename to codec_reads_test.go diff --git a/misc_test.go b/message_test.go similarity index 100% rename from misc_test.go rename to message_test.go