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
5 changes: 5 additions & 0 deletions codec_decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,10 @@ func decodeCraftedCases() []decodeCase {
// Version and community.
{name: "crafted/version/0", in: craftedMsg(0, craftedPDU(Response, craftedVBL(nullVB)))},
{name: "crafted/version/2", in: craftedMsg(2, craftedPDU(Response, craftedVBL(nullVB)))},
// The version is known before the octets after the message: a bad
// version (RFC 3412 section 4.2.1).
{name: "crafted/version/2-trailing-octets", in: append(craftedMsg(2, craftedPDU(Response, craftedVBL(nullVB))), 0x00)},
{name: "crafted/version/1-trailing-octets", in: append(craftedMsg(1, craftedPDU(Response, craftedVBL(nullVB))), 0x00)},
{name: "crafted/version/3-with-community", in: craftedMsg(3, craftedPDU(Response, craftedVBL(nullVB)))},
{name: "crafted/version/256", in: craftedMsg(256, craftedPDU(Response, craftedVBL(nullVB)))},
{name: "crafted/version/-1", in: craftedMsg(-1, craftedPDU(Response, craftedVBL(nullVB)))},
Expand Down Expand Up @@ -658,6 +662,7 @@ func decodeCraftedCases() []decodeCase {
{name: "crafted/v3/flags-reserved-bits", in: craftedV3(intTLV(42), intTLV(65507), octets("\xfc"), intTLV(3), craftedNoAuthUSM, craftedScopedResp)},
{name: "crafted/v3/flags-integer", in: craftedV3(intTLV(42), intTLV(65507), intTLV(0), intTLV(3), craftedNoAuthUSM, craftedScopedResp)},
{name: "crafted/v3/security-model-2", in: craftedV3(intTLV(42), intTLV(65507), octets("\x00"), intTLV(2), craftedNoAuthUSM, craftedScopedResp)},
{name: "crafted/v3/msg-global-data-empty", in: craftedV3(nil, nil, nil, nil, craftedNoAuthUSM, craftedScopedResp)},
{name: "crafted/v3/msg-id-negative", in: craftedV3(intTLV(-1), intTLV(65507), octets("\x00"), intTLV(3), craftedNoAuthUSM, craftedScopedResp)},
{name: "crafted/v3/msg-id-octet-string", in: craftedV3(octets("\x2a"), intTLV(65507), octets("\x00"), intTLV(3), craftedNoAuthUSM, craftedScopedResp)},
{name: "crafted/v3/msg-id-2147483647", in: craftedV3(intTLV(math.MaxInt32), intTLV(65507), octets("\x00"), intTLV(3), craftedNoAuthUSM, craftedScopedResp)},
Expand Down
2 changes: 1 addition & 1 deletion codec_encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func TestMarshalLongOctetStringFields(t *testing.T) {
// Longer than the decoder takes: the fields as the encoder
// laid them out.
_, err = (&Client{}).DecodeMessage(msg)
require.ErrorIs(t, err, ErrInvalidMsgs)
require.ErrorIs(t, err, ErrASNParse)
m := splitV3Message(t, msg)
if got := (fields{engineID: string(m.usm[0]), userName: string(m.usm[3])}); got != want {
t.Errorf("encoded %+v, want %+v", got, want)
Expand Down
8 changes: 6 additions & 2 deletions codec_failure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,10 @@ func TestDecodeFailurePartialResults(t *testing.T) {
"not a sequence": {in: cat([]byte{0x31}, craftedValue(intTLV(5))[1:]), wantErr: header + "invalid packet header", want: with(decodedFields{}, func(*decodedFields) {})},
"version": {in: tlv(0x30, bad, octets("public"), vbl), wantErr: header + "error parsing SNMP packet version" + notInt, want: with(decodedFields{}, func(*decodedFields) {})},
"community": {in: tlv(0x30, intTLV(1), bad, vbl), wantErr: header + "error parsing community string" + notStr, want: with(decodedFields{version: Version2c}, func(*decodedFields) {})},
"octet after the message": {
in: cat(craftedMsg(1, craftedPDU(Response, vbl)), []byte{0x00}), wantErr: header + "error verifying packet sanity: 1 bytes after the TLV",
want: with(decodedFields{}, func(*decodedFields) {}),
},

// PDU header.
"request ID": {in: craftedMsg(1, tlv(byte(Response), bad, intTLV(2), intTLV(3), vbl)), wantErr: body + "error parsing SNMP packet request ID" + notInt, want: resp},
Expand Down Expand Up @@ -208,7 +212,7 @@ func TestDecodeFailurePartialResults(t *testing.T) {
// TestDecodeUSMFields pins RFC 3414 section 3.2 step 1: each USM field must
// be of its type, and the engine boots and time within 0..2147483647 once cut
// to 32 bits (as net-snmp v5.9.4 reads them); anything else fails the header
// parse with ErrInvalidMsgs, on the raw path too.
// parse with ErrASNParse, on the raw path too.
func TestDecodeUSMFields(t *testing.T) {
const engineID = "\x80\x00\x1f\x88\x04codec-engine"
fields := func(edit func(f [][]byte)) []byte {
Expand Down Expand Up @@ -238,7 +242,7 @@ func TestDecodeUSMFields(t *testing.T) {
t.Run(name, func(t *testing.T) {
_, err := (&Client{}).DecodeMessage(tc.in)
if tc.invalid {
assert.ErrorIs(t, err, ErrInvalidMsgs)
assert.ErrorIs(t, err, ErrASNParse)
} else {
assert.NoError(t, err)
}
Expand Down
11 changes: 8 additions & 3 deletions codec_fuzz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,23 @@ func codecFuzzSeeds(tb testing.TB) [][]byte {
}

// FuzzUnmarshal checks that DecodeMessage returns quickly, does not panic
// and does not write into its input. Its corpus in testdata/fuzz/FuzzUnmarshal
// is also pinned by TestDecodeCharacterization.
// and does not write into its input, and that its errors and those of
// UnmarshalTrap's single path each have one category. Its corpus in
// testdata/fuzz/FuzzUnmarshal is also pinned by TestDecodeCharacterization.
func FuzzUnmarshal(f *testing.F) {
for _, seed := range codecFuzzSeeds(f) {
f.Add(seed)
}

vhandle := Client{}
receiver := Client{Version: Version3}
f.Fuzz(func(t *testing.T, data []byte) {
stime := time.Now()
in := bytes.Clone(data)
_, _ = vhandle.DecodeMessage(in)
_, err := vhandle.DecodeMessage(in)
checkCategory(t, "DecodeMessage", err)
_, err = receiver.UnmarshalTrap(bytes.Clone(data), true)
checkCategory(t, "UnmarshalTrap", err)

if e := time.Since(stime); e > (time.Second * 1) {
t.Errorf("DecodeMessage() took too long: %s", e)
Expand Down
49 changes: 14 additions & 35 deletions codec_golden_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,45 +203,24 @@ func readGoldenFile(path string) ([]goldenSection, error) {
return sections, nil
}

// codecSentinels are the exported errors a codec result is matched against.
var codecSentinels = []struct {
name string
err error
}{
{"ErrBase128IntegerTooLarge", ErrBase128IntegerTooLarge},
{"ErrBase128IntegerTruncated", ErrBase128IntegerTruncated},
{"ErrFloatBufferTooShort", ErrFloatBufferTooShort},
{"ErrFloatTooLarge", ErrFloatTooLarge},
{"ErrIntegerTooLarge", ErrIntegerTooLarge},
{"ErrInvalidOidLength", ErrInvalidOidLength},
{"ErrInvalidPacketLength", ErrInvalidPacketLength},
{"ErrZeroByteBuffer", ErrZeroByteBuffer},
{"ErrZeroLenInteger", ErrZeroLenInteger},
{"ErrDecryption", ErrDecryption},
{"ErrInvalidMsgs", ErrInvalidMsgs},
{"ErrNotInTimeWindow", ErrNotInTimeWindow},
{"ErrUnknownEngineID", ErrUnknownEngineID},
{"ErrUnknownPDUHandlers", ErrUnknownPDUHandlers},
{"ErrUnknownReportPDU", ErrUnknownReportPDU},
{"ErrUnknownSecurityLevel", ErrUnknownSecurityLevel},
{"ErrUnknownSecurityModels", ErrUnknownSecurityModels},
{"ErrUnknownUsername", ErrUnknownUsername},
{"ErrWrongDigest", ErrWrongDigest},
}

// dumpError describes an error by the exported sentinels it matches; the
// message text is not part of the pinned behavior.
// dumpError describes an error by the categories it matches and the
// unexported decode errors it wraps besides (decodeDetails); the message text
// is not part of the pinned behavior.
func dumpError(err error) string {
var matched []string
for _, s := range codecSentinels {
if errors.Is(err, s.err) {
matched = append(matched, s.name)
out := "error"
if names := categoriesOf(err); len(names) > 0 {
out += " (" + strings.Join(names, ", ") + ")"
}
var details []string
for _, d := range decodeDetails {
if errors.Is(err, d.err) {
details = append(details, d.name)
}
}
if len(matched) == 0 {
return "error"
if len(details) > 0 {
out += " detail (" + strings.Join(details, ", ") + ")"
}
return "error (" + strings.Join(matched, ", ") + ")"
return out
}

// observe runs fn and reports whether it panicked and whether it wrote to
Expand Down
83 changes: 56 additions & 27 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,15 @@
// "request timeout (after N retries)", which matches the attempt's reason with
// [errors.Is] and [errors.As] (the timeout, a [net.Error]). When the request
// discarded messages, such an error, and one at the Context's deadline, also
// matches the reason of the one that came closest to answering it (the last
// authentic reply naming the request, by its SNMPv3 msgID, else the last naming
// it, by that msgID or as an SNMPv1 or SNMPv2c Response with one of its
// request IDs, else the last one whose ID could not be read, as one of another
// SNMP version; messages to other requests do not count), and its text ends
// with ": last discarded reply: " and that reason's text. An answer's error
// status ([Message].ErrorStatus) is not an error of the request. Connect uses
// Timeout and the Context too, for its lookup of Target and its dial together.
// matches the reason, and so the category (see Errors), of the one that came
// closest to answering it (the last authentic reply naming the request, by its
// SNMPv3 msgID, else the last naming it, by that msgID or as an SNMPv1 or
// SNMPv2c Response with one of its request IDs, else the last one whose ID
// could not be read, as one of another SNMP version; messages to other
// requests do not count), and its text ends with ": last discarded reply: "
// and that reason's text. An answer's error status ([Message].ErrorStatus) is
// not an error of the request. Connect uses Timeout and the Context too, for
// its lookup of Target and its dial together.
//
// # Hooks
//
Expand Down Expand Up @@ -151,7 +152,8 @@
// b; one that differs leaves the request outstanding, as in net-snmp). A reply
// that fails is discarded like one that does not decode; the error of a request
// that then times out or ends at the Context's deadline also matches the
// step's, [ErrNotInTimeWindow] for the time window (see Attempts and timeouts).
// step's, [ErrNotInTimeWindow] for the time window, and [ErrUnmatchedReply]
// for a reply that does not answer (see Attempts and timeouts).
//
// The client takes the engine ID of each answer whose digest it checked and of
// each Response, which name the request's (security processing, the rule
Expand Down Expand Up @@ -372,22 +374,49 @@
//
// # Errors
//
// The errors named after the counters a Report carries ([ErrUnknownUsername],
// [ErrWrongDigest] and the others) are also the categories of the library's
// own rejections of a message: an error of decoding an SNMPv3 message, a trap
// or a reply, unwraps ([errors.Is]) to the counter of the RFC 3412 section 7.2
// or RFC 3414 section 3.2 step that rejected it, with its own text:
// [ErrUnknownSecurityModels] for another security model, [ErrInvalidMsgs] for
// privacy without authentication and, in place of snmpInASNParseErrs, which
// has no error of its own, for a header or a scoped PDU that does not parse
// before decryption, [ErrUnknownEngineID] through [ErrDecryption] for the
// security processing, [ErrUnknownSecurityLevel] for a trap receiver's minimum
// level too. A decode error also unwraps to [ErrInvalidPacketLength] when a
// length caused it, besides its category: after a wrong privacy key, a
// decrypted scoped PDU whose length runs past its plaintext matches both
// [ErrDecryption] and [ErrInvalidPacketLength]. A request that times out or
// ends at the Context's deadline after discarded replies fails with an error
// that also matches the reason of the one that came closest to answering it (see Attempts and timeouts), so it matches
// these errors without a Report. A local failure, such as a key that does not
// fit its protocol, matches none of them.
// Every error of an incoming message unwraps ([errors.Is]) to exactly one
// category, an exported error named after the counter RFC 3412, RFC 3414 or
// RFC 3418 counts the message in, as net-snmp v5.9.4 counts it, with a text of
// its own: an error of DecodeMessage, of UnmarshalTrap, and the reason a
// request discards a reply for. The categories:
//
// - [ErrASNParse] (snmpInASNParseErrs): the message does not parse, of any
// version: its encoding, a header field of another type or outside its
// range, the USM parameters (RFC 3414 section 3.2 step 1; net-snmp counts
// msgPrivacyParameters that do not parse in usmStatsDecryptionErrors), a
// scoped PDU of the other type than the privFlag asks for or one that does
// not parse in plaintext, the PDU, an unknown PDU type and a varbind (RFC
// 3412 section 7.2 steps 2 and 7);
// - [ErrBadVersion] (snmpInBadVersions): a version other than SNMPv1, SNMPv2c
// and SNMPv3 (RFC 3412 section 4.2.1; net-snmp counts a negative one in
// snmpInASNParseErrs too);
// - [ErrUnknownSecurityModels]: another security model (step 4);
// - [ErrInvalidMsgs]: privacy without authentication (step 5 d);
// - [ErrUnknownEngineID] through [ErrDecryption]: the security processing
// (RFC 3414 section 3.2 steps 3 to 8), [ErrUnknownSecurityLevel] for a
// trap receiver's minimum level too, and [ErrDecryption] for a decrypted
// plaintext that is not a SEQUENCE of a contextEngineID and a contextName,
// as a wrong privacy key yields (net-snmp counts it in snmpInASNParseErrs;
// a PDU that does not parse after them is [ErrASNParse]);
// - [ErrUnmatchedReply]: a reply that does not answer the request: of another
// version, naming none of its attempts, neither a Response nor a Report,
// or with another request ID, security level, user name, engine ID or
// context (RFC 3412 section 7.2 steps 10 a and 12 b).
//
// A request answered by an SNMPv3 Report fails with the error of the Report's
// counter, the same errors ([ErrUnknownPDUHandlers] too), or
// [ErrUnknownReportPDU] for a counter the library does not know. A request
// that times out or ends at the Context's deadline after discarded replies
// fails with an error that also matches the category of the one that came
// closest to answering it (see Attempts and timeouts). So a category says why
// a message was rejected, by the agent or by the library, not who rejected
// it. A local failure, such as a configuration error, a key that does not
// derive or fit its protocol, or a protocol FIPS 140-only mode refuses,
// matches none of them, nor does a transport error or a timeout without a
// discarded reply.
//
// The categories are variables only so that errors.Is can match them; do not
// assign to them. The library makes some of its errors with their values when
// the package is initialized and others when the error occurs, so after an
// assignment its errors match the old value or the new one.
package gosnmp
39 changes: 13 additions & 26 deletions engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -630,18 +630,22 @@ func receiveReply(level SecurityLevel, got, want *SecurityParameters, keys *usmK
}

// 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).
// security processing's (RFC 3412 section 7.2 steps 3, 10 and 12 b): the
// message does not answer the request, ErrUnmatchedReply.
var (
errOtherVersion = errors.New("the reply is of another SNMP version than the request")
errOtherMessage = errors.New("the reply's msgID names no attempt of the request")
errNotAnswer = errors.New("the reply is neither a Response nor an SNMPv3 Report")
errOtherRequestID = errors.New("the reply's request ID does not match the request")
errOtherLevel = errors.New("the reply's security level is not the request's")
errOtherUser = errors.New("the reply's user name is not the request's")
errOtherEngine = errors.New("the reply's engine ID is not the request's")
errOtherContext = errors.New("the reply's context is not the request's")
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
Expand Down Expand Up @@ -701,23 +705,6 @@ const (
snmpUnknownPDUHandlers = ".1.3.6.1.6.3.11.2.1.3.0"
)

// The errors of a request answered by a Report: one per Report counter the
// library knows, and ErrUnknownReportPDU for any other counter. The library's
// own rejections of a message unwrap to the counter's error too (see the
// package documentation, Errors).
var (
ErrDecryption = errors.New("decryption error")
ErrInvalidMsgs = errors.New("invalid messages")
ErrNotInTimeWindow = errors.New("not in time window")
ErrUnknownEngineID = errors.New("unknown engine id")
ErrUnknownPDUHandlers = errors.New("unknown pdu handlers")
ErrUnknownReportPDU = errors.New("unknown report pdu")
ErrUnknownSecurityLevel = errors.New("unknown security level")
ErrUnknownSecurityModels = errors.New("unknown security models")
ErrUnknownUsername = errors.New("unknown username")
ErrWrongDigest = errors.New("wrong digest")
)

// reportKind is what the counter an SNMPv3 Report carries means to a request.
type reportKind struct {
// err is the request's error.
Expand Down
12 changes: 11 additions & 1 deletion engine_fuzz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,17 @@ func FuzzEngineReply(f *testing.F) {
}
}
f.Fuzz(func(t *testing.T, which uint8, reply []byte) {
x := engineReplyClient(engineReplyRequests[int(which)%len(engineReplyRequests)])
r := engineReplyRequests[int(which)%len(engineReplyRequests)]
// The reason the first exchange would discard the reply for, or the
// error of a Report that answers it, is in exactly one category.
e := engineReplyExchange(t, r)
read, _, err := e.decode(reply, nil)
if err == nil {
_, err = e.answers(read, nil)
}
checkCategory(t, "the reply", err)

x := engineReplyClient(r)
// One read per exchange (the discovery, the request, a resend), each
// followed by the attempt's timeout.
exchange := []scriptedRead{{data: reply}, {err: os.ErrDeadlineExceeded}}
Expand Down
15 changes: 3 additions & 12 deletions engine_harness_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,8 @@ func replyTo(req []byte, edit func(*Message), vbs ...VarBind) []byte {
return b
}

// engineSentinels are the errors an engine result is checked against.
// engineSentinels are the errors an engine result is checked against besides
// the categories (errorCategories).
var engineSentinels = []struct {
name string
err error
Expand All @@ -517,16 +518,6 @@ var engineSentinels = []struct {
{"syscall.EHOSTUNREACH", syscall.EHOSTUNREACH},
{"syscall.EACCES", syscall.EACCES},
{"errEngineWrite", errEngineWrite},
{"ErrDecryption", ErrDecryption},
{"ErrInvalidMsgs", ErrInvalidMsgs},
{"ErrNotInTimeWindow", ErrNotInTimeWindow},
{"ErrUnknownEngineID", ErrUnknownEngineID},
{"ErrUnknownPDUHandlers", ErrUnknownPDUHandlers},
{"ErrUnknownReportPDU", ErrUnknownReportPDU},
{"ErrUnknownSecurityLevel", ErrUnknownSecurityLevel},
{"ErrUnknownSecurityModels", ErrUnknownSecurityModels},
{"ErrUnknownUsername", ErrUnknownUsername},
{"ErrWrongDigest", ErrWrongDigest},
}

// describeEngineError gives the text of err and what it is: the sentinels it
Expand All @@ -535,7 +526,7 @@ var engineSentinels = []struct {
func describeEngineError(err error) string {
text := err.Error()
var equals, is []string
for _, s := range engineSentinels {
for _, s := range slices.Concat(engineSentinels, errorCategories) {
switch {
case err == s.err: //nolint:errorlint // the identity is what is described
equals = append(equals, s.name)
Expand Down
Loading
Loading