Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
File renamed without changes.
File renamed without changes.
307 changes: 0 additions & 307 deletions engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@
package gosnmp

import (
"bytes"
"context"
"errors"
"fmt"
"net"
"os"
"strings"
"time"
)

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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)]
}
Loading
Loading