From 7a8a4f52ce2a064de3ccb0a04942d34d9ef56af4 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 11:38:00 +0200 Subject: [PATCH 01/11] test: pin the range of every INTEGER header field without a cut TestHeaderIntegers probes each INTEGER header field of a message, PDU and SNMPv1 trap (the request ID, error-status, error-index, non-repeaters, max-repetitions, generic and specific trap, msgID, msgMaxSize, engine boots and time, the version and the security model) at its bounds, next to them, and at the bounds moved by 2^32. A value outside the range must fail the message; today the decoder cuts each field to 32 bits before checking it, so a five-octet error-status of 2^32 reads as noError and a version of 2^32+1 as SNMPv2c. TestDecodeUSMFields no longer accepts an engine boots of 2^32+5. The test fails until the decoder reads header INTEGERs whole. --- codec_failure_test.go | 172 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 167 insertions(+), 5 deletions(-) diff --git a/codec_failure_test.go b/codec_failure_test.go index 940aee6..74844c8 100644 --- a/codec_failure_test.go +++ b/codec_failure_test.go @@ -5,6 +5,10 @@ package gosnmp import ( + "errors" + "fmt" + "math" + "slices" "testing" "github.com/stretchr/testify/assert" @@ -123,9 +127,9 @@ func TestDecodeFailureNoMessage(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 ErrASNParse, on the raw path too. +// be of its type, and the engine boots and time within 0..2147483647, never +// cut to 32 bits (TestHeaderIntegers); anything else fails the header parse +// with ErrASNParse, on the raw path too. func TestDecodeUSMFields(t *testing.T) { const engineID = "\x80\x00\x1f\x88\x04codec-engine" // usm builds a message whose USM parameters are the fields, edited, in a @@ -150,8 +154,8 @@ func TestDecodeUSMFields(t *testing.T) { "auth parameters as an INTEGER": {in: fields(func(f [][]byte) { f[4] = intTLV(3) }), invalid: true}, "priv parameters as an INTEGER": {in: fields(func(f [][]byte) { f[5] = intTLV(4) }), invalid: true}, "boots 2147483647": {in: fields(func(f [][]byte) { f[1] = intTLV(2147483647) })}, - // 2^32+5, cut to 5 on every platform. - "boots 4294967301": {in: fields(func(f [][]byte) { f[1] = intTLV(4294967301) })}, + // 2^32+5, whose low 32 bits are 5. + "boots 4294967301": {in: fields(func(f [][]byte) { f[1] = intTLV(4294967301) }), invalid: true}, "boots -1": {in: fields(func(f [][]byte) { f[1] = intTLV(-1) }), invalid: true}, "time -2147483648": {in: fields(func(f [][]byte) { f[2] = intTLV(-2147483648) }), invalid: true}, // The fields in another container than a SEQUENCE (RFC 3414 section 2.4). @@ -198,3 +202,161 @@ func TestUnknownPDUTypeError(t *testing.T) { }) } } + +// TestHeaderIntegers pins the one rule of the INTEGER header fields of every +// message, PDU and SNMPv1 trap: the field is read whole, up to 64 bits, and +// must lie in its range, which the decoded field holds without a cut; a value +// outside it fails the message (ErrASNParse), also one whose low 32 bits lie +// in the range. The probes are each field's bounds, the values next to them, +// and the bounds moved by 2^32. +func TestHeaderIntegers(t *testing.T) { + nullVBL := craftedVBL(craftedVB(tlv(byte(Null)))) + pdu := func(tag PDUType, a, b, c int64) []byte { + return craftedMsg(1, tlv(byte(tag), intTLV(a), intTLV(b), intTLV(c), nullVBL)) + } + trap := func(generic, specific int64) []byte { + return craftedV1Trap(craftedEnterprise, craftedAgentAddress, intTLV(generic), intTLV(specific), craftedTimestamp, nullVBL) + } + v3 := func(msgID, maxSize, boots, engineTime int64) []byte { + usm := craftedUSM(craftedEngineID, intTLV(boots), intTLV(engineTime), octets("codec-user"), octets(""), octets("")) + return craftedV3(intTLV(msgID), intTLV(maxSize), octets("\x00"), intTLV(3), usm, craftedScopedResp) + } + sat := func(v int64) int64 { return min(v, 255) } // the counts read above 255 as 255 + fields := map[string]struct { + msg func(v int64) []byte + get func(m *Message) int64 + lo, hi int64 + // held is the value the field holds for v in the range; nil: v. + held func(v int64) int64 + }{ + // The request ID keeps its 32 bits, sent as an Integer32 or unsigned. + "request ID": { + msg: func(v int64) []byte { return pdu(Response, v, 0, 0) }, get: func(m *Message) int64 { return int64(m.RequestID) }, + lo: math.MinInt32, hi: math.MaxUint32, held: func(v int64) int64 { return int64(uint32(v)) }, //nolint:gosec // the two's complement + }, + "error status": { + msg: func(v int64) []byte { return pdu(Response, 1, v, 0) }, get: func(m *Message) int64 { return int64(m.ErrorStatus) }, + lo: 0, hi: 255, + }, + "error index": { + msg: func(v int64) []byte { return pdu(Response, 1, 0, v) }, get: func(m *Message) int64 { return int64(m.ErrorIndex) }, + lo: 0, hi: math.MaxInt32, held: sat, + }, + "non-repeaters": { + msg: func(v int64) []byte { return pdu(GetBulkRequest, 1, v, 10) }, get: func(m *Message) int64 { return int64(m.NonRepeaters) }, + lo: 0, hi: math.MaxInt32, held: sat, + }, + "max-repetitions": { + msg: func(v int64) []byte { return pdu(GetBulkRequest, 1, 0, v) }, get: func(m *Message) int64 { return int64(m.MaxRepetitions) }, + lo: 0, hi: math.MaxInt32, + }, + "generic trap": { + msg: func(v int64) []byte { return trap(v, 1) }, get: func(m *Message) int64 { return int64(m.GenericTrap) }, + lo: math.MinInt32, hi: math.MaxInt32, + }, + "specific trap": { + msg: func(v int64) []byte { return trap(6, v) }, get: func(m *Message) int64 { return int64(m.SpecificTrap) }, + lo: math.MinInt32, hi: math.MaxInt32, + }, + "msgID": { + msg: func(v int64) []byte { return v3(v, 65507, 7, 1234) }, get: func(m *Message) int64 { return int64(m.MsgID) }, + lo: 0, hi: math.MaxInt32, + }, + "msgMaxSize": { + msg: func(v int64) []byte { return v3(42, v, 7, 1234) }, get: func(m *Message) int64 { return int64(m.MsgMaxSize) }, + lo: 484, hi: math.MaxInt32, + }, + "msgAuthoritativeEngineBoots": { + msg: func(v int64) []byte { return v3(42, 65507, v, 1234) }, + get: func(m *Message) int64 { return int64(m.SecurityParameters.AuthoritativeEngineBoots) }, + lo: 0, hi: math.MaxInt32, + }, + "msgAuthoritativeEngineTime": { + msg: func(v int64) []byte { return v3(42, 65507, 7, v) }, + get: func(m *Message) int64 { return int64(m.SecurityParameters.AuthoritativeEngineTime) }, + lo: 0, hi: math.MaxInt32, + }, + } + type result struct { + value int64 + err error // the error's category + } + for name, f := range fields { + probes := []int64{f.lo, f.hi, f.lo - 1, f.hi + 1, f.lo + 1<<32, f.hi - 1<<32} + slices.Sort(probes) + for _, v := range slices.Compact(probes) { + t.Run(fmt.Sprintf("%s/%d", name, v), func(t *testing.T) { + want := result{err: ErrASNParse} + if f.lo <= v && v <= f.hi { + want = result{value: v} + if f.held != nil { + want.value = f.held(v) + } + } + m, err := mustClient(Config{}).DecodeMessage(f.msg(v)) + var got result + if err != nil { + got.err = headerCategory(err) + assert.Nil(t, m) + } else { + got.value = f.get(m) + } + assert.Equal(t, want, got) + }) + } + } + + // The version and the security model, whose values are a set: any other + // version is a bad version (RFC 3412 section 4.2.1), any other model in + // 1..2147483647 another security model. + tests := map[string]struct { + in []byte + want result + }{ + "version 1": {in: craftedMsg(1, craftedPDU(Response, nullVBL)), want: result{value: 1}}, + "version 0 (SNMPv1)": {in: craftedMsg(0, craftedPDU(Response, nullVBL)), want: result{value: 0}}, + "version 2^32": {in: craftedMsg(1<<32, craftedPDU(Response, nullVBL)), want: result{err: ErrBadVersion}}, + "version 2^32+1": {in: craftedMsg(1<<32+1, craftedPDU(Response, nullVBL)), want: result{err: ErrBadVersion}}, + "version -2^32+1": {in: craftedMsg(-1<<32+1, craftedPDU(Response, nullVBL)), want: result{err: ErrBadVersion}}, + "version 2^32+3": {in: craftedMsg(1<<32+3, craftedPDU(Response, nullVBL)), want: result{err: ErrBadVersion}}, + "security model 3": {in: v3Model(3), want: result{value: 3}}, + "security model 2147483647": {in: v3Model(math.MaxInt32), want: result{err: ErrUnknownSecurityModels}}, + "security model 0": {in: v3Model(0), want: result{err: ErrASNParse}}, + "security model 2^31": {in: v3Model(1 << 31), want: result{err: ErrASNParse}}, + "security model 2^32+3": {in: v3Model(1<<32 + 3), want: result{err: ErrASNParse}}, + "security model -2^32+3": {in: v3Model(-1<<32 + 3), want: result{err: ErrASNParse}}, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + m, err := mustClient(Config{}).DecodeMessage(tc.in) + var got result + switch { + case err != nil: + got.err = headerCategory(err) + assert.Nil(t, m) + case m.Version == Version3: + got.value = 3 // the only model that decodes + default: + got.value = int64(m.Version) + } + assert.Equal(t, tc.want, got) + }) + } +} + +// v3Model returns an SNMPv3 message whose security model is model. +func v3Model(model int64) []byte { + return craftedV3(intTLV(42), intTLV(65507), octets("\x00"), intTLV(model), craftedNoAuthUSM, craftedScopedResp) +} + +// headerCategory returns the category of a header field's error: the first of +// ErrASNParse, ErrBadVersion and ErrUnknownSecurityModels it matches, else +// err. +func headerCategory(err error) error { + for _, c := range []error{ErrASNParse, ErrBadVersion, ErrUnknownSecurityModels} { + if errors.Is(err, c) { + return c + } + } + return err +} From 7c753c75e4d13a1cbd77f247cd9598843f522a1d Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 11:40:56 +0200 Subject: [PATCH 02/11] fix: read header INTEGERs whole and never cut them to 32 bits Every INTEGER header field went through readInt32, which cut the value to 32 bits before the field's range check, so a value beyond 32 bits whose low 32 bits lay in the range was taken: a five-octet error-status of 2^32 read as noError, a version of 2^32+1 as SNMPv2c, a request ID of 2^32 as 0, an SNMPv1 specific trap of 2^31 as -2147483648, a security model of 2^32+3 as the USM. readInteger is now the one reader of these fields: it reads the INTEGER whole (up to eight octets) and checks it against the field's range before the caller narrows it; a value outside the range fails the message with ErrASNParse, or ErrBadVersion for the version. The ranges: the request ID an Integer32 or its 32 bits sent unsigned; error-status 0..255; error-index, non-repeaters and max-repetitions 0..2147483647 (the counts still read as 255 above 255); generic and specific trap Integer32; msgID 0..2147483647; msgMaxSize 484..2147483647; the security model 1..2147483647; engine boots and time 0..2147483647. net-snmp cuts these fields first; the decoder is now stricter for them, and the package documentation lists it. Values keep their rule: an Integer value is still cut to 32 bits, and Counter32, Gauge32, TimeTicks and Uinteger32 values and the SNMPv1 timestamp (a TimeTicks) keep their low 32 bits, as net-snmp reads them. Error texts: an error-index, non-repeaters or max-repetitions out of range reads "N is outside 0..2147483647" (was "N is negative"); the request ID and the generic and specific trap gain "N is outside lo..hi" errors. --- doc.go | 40 +++++++++------- pdu.go | 88 ++++++++++++++++++++---------------- testdata/codec/decode.golden | 25 ++-------- v3.go | 47 +++++++------------ value.go | 3 +- 5 files changed, 93 insertions(+), 110 deletions(-) diff --git a/doc.go b/doc.go index fe7bb88..40ff17e 100644 --- a/doc.go +++ b/doc.go @@ -468,20 +468,22 @@ // set for requests and informs, clear for responses, reports and traps. // // The decoder applies one rule per value type and header field, with the same -// results on every platform. An INTEGER, value or header field, has one to -// eight octets and is cut to 32 bits by two's complement (an Integer32, RFC -// 2578 section 7.1.1); Uinteger32, Counter32, Gauge32 and TimeTicks values are -// unsigned, of one to eight octets or nine with a leading zero, and keep their -// low 32 bits; an OBJECT IDENTIFIER has at most 128 arcs. A header field must -// be of its type and, once cut, within its range, or it fails the message, as a -// missing one does: the version SNMPv1, SNMPv2c or SNMPv3; the community, -// contextEngineID and contextName OCTET STRINGs; the error status 0..255; the -// error index and non-repeaters not negative, read as 255 above it (the most -// their fields hold); max-repetitions not negative; an SNMPv1 trap's enterprise -// an OBJECT IDENTIFIER, its agent address four octets, an IpAddress or an OCTET -// STRING, and its timestamp TimeTicks or another unsigned type, as net-snmp -// v5.9.4 takes it. The SNMPv3 header takes net-snmp's field rules (RFC 3412 -// section 6, RFC 3414 section 2.4): msgID 0..2147483647, msgMaxSize +// results on every platform. An INTEGER has one to eight octets: an Integer +// value is cut to 32 bits by two's complement (an Integer32, RFC 2578 section +// 7.1.1), an INTEGER header field is read whole; Uinteger32, Counter32, Gauge32 +// and TimeTicks values are unsigned, of one to eight octets or nine with a +// leading zero, and keep their low 32 bits; an OBJECT IDENTIFIER has at most +// 128 arcs. A header field must be of its type and within its range, or it +// fails the message, as a missing one does: the version SNMPv1, SNMPv2c or +// SNMPv3; the community, contextEngineID and contextName OCTET STRINGs; the +// request ID an Integer32, or its 32 bits sent unsigned; the error status +// 0..255; the error index and non-repeaters 0..2147483647, read as 255 above +// it (the most their fields hold); max-repetitions 0..2147483647; an SNMPv1 +// trap's enterprise an OBJECT IDENTIFIER, its agent address four octets, an +// IpAddress or an OCTET STRING, its generic and specific trap Integer32s, and +// its timestamp TimeTicks or another unsigned type, as net-snmp v5.9.4 takes +// it, read as such a value. The SNMPv3 header takes net-snmp's field rules +// (RFC 3412 section 6, RFC 3414 section 2.4): msgID 0..2147483647, msgMaxSize // 484..2147483647, msgFlags an OCTET STRING of one octet, the User-based // Security Model's number, flags that do not ask for privacy without // authentication, the USM fields of their types, an engine ID of at most 64 @@ -505,9 +507,13 @@ // from net-snmp v5.9.4: // // - an empty OBJECT IDENTIFIER reads as .0.0, not .0 -// - an INTEGER outside the int32 range keeps its low 32 bits as an int32 -// (3000000000 reads -1294967296), where net-snmp keeps them unsigned above -// it and negates them below it +// - an Integer value outside the int32 range keeps its low 32 bits as an +// int32 (3000000000 reads -1294967296), where net-snmp keeps them unsigned +// above it and negates them below it +// - an INTEGER header field outside its range fails the message also when +// its low 32 bits lie in it, where net-snmp cuts it to 32 bits first (a +// version of 2^32+1 reads as SNMPv2c there, an error status of 2^32 as +// noError) // - the community and context fields take OCTET STRINGs only, and an SNMPv1 // agent address four octets or an empty IpAddress, where net-snmp takes // other string types (of up to four octets for the agent address) diff --git a/pdu.go b/pdu.go index ec1ee5a..e4ffbbf 100644 --- a/pdu.go +++ b/pdu.go @@ -17,9 +17,11 @@ import ( // -- Header fields ------------------------------------------------------------ // A message, PDU or SNMPv1 trap header field, or a varbind name, has one rule: -// its tag, then its range once cut to 32 bits; a field that breaks it, or is -// missing, fails the message. The reads take the reader as a parameter and -// keep it nowhere, so that it stays on the caller's stack. +// its tag, then its range; a field that breaks it, or is missing, fails the +// message. An INTEGER field is read whole, up to 64 bits, and never cut to 32 +// bits (readInteger), so a value outside its range fails even when its low 32 +// bits lie in it; net-snmp v5.9.4 cuts it first. The reads take the reader as +// a parameter and keep it nowhere, so that it stays on the caller's stack. // Errors of a header field that is missing or of another tag than its rule's. var ( @@ -43,13 +45,28 @@ func readTagged(r *ber.Reader, want ValueType, notTag error) ([]byte, error) { return content, err } -// readInt32 reads the next field, an INTEGER, cut to 32 bits (int32Value). -func readInt32(r *ber.Reader) (int32, error) { +// readInteger reads the next field, an INTEGER of one to eight octets, whole, +// and returns it when it lies in lo..hi, without a cut: the one reader of the +// INTEGER header fields. +func readInteger(r *ber.Reader, lo, hi int64) (int64, error) { content, err := readTagged(r, Integer, errNotInteger) if err != nil { return 0, err } - return int32Value(content) + v, err := ber.Int64(content) + switch { + case err != nil: + return 0, err + case v < lo || v > hi: + return 0, fmt.Errorf("%d is outside %d..%d", v, lo, hi) + } + return v, nil +} + +// readInteger32 reads the next field, an Integer32 (readInteger). +func readInteger32(r *ber.Reader) (int32, error) { + v, err := readInteger(r, math.MinInt32, math.MaxInt32) + return int32(v), err //nolint:gosec // -2147483648..2147483647 } // readOctets reads the next field, an OCTET STRING, whose content aliases the @@ -68,21 +85,16 @@ func readOID(r *ber.Reader) (string, error) { return ber.OID(content) } -// readCount reads an error index or non-repeaters: an INTEGER (readInt32) that -// is not negative, saturated at 255, the most their one-octet fields hold (RFC -// 3416 allows up to 2147483647: a request of more than 255 varbinds can be -// answered with a larger error index). +// readCount reads an error index or non-repeaters: an INTEGER of 0..2147483647 +// (RFC 3416's max-bindings), saturated at 255, the most their one-octet fields +// hold (a request of more than 255 varbinds can be answered with a larger +// error index). func readCount(r *ber.Reader) (uint8, error) { - v, err := readInt32(r) - switch { - case err != nil: + v, err := readInteger(r, 0, math.MaxInt32) + if err != nil { return 0, err - case v < 0: - return 0, fmt.Errorf("%d is negative", v) - case v > math.MaxUint8: - return math.MaxUint8, nil } - return uint8(v), nil + return uint8(min(v, math.MaxUint8)), nil //nolint:gosec // 0..255 } // readAgentAddress reads an SNMPv1 trap's agent address (RFC 1157's @@ -187,7 +199,7 @@ func readVersion(packet []byte) (Version, int, error) { switch { case err != nil: return 0, 0, inCategory(ErrASNParse, err) - case version != int32(Version1) && version != int32(Version2c) && version != int32(Version3): + case version != int64(Version1) && version != int64(Version2c) && version != int64(Version3): return 0, 0, inCategory(ErrBadVersion, fmt.Errorf("error parsing SNMP packet version: %d is not 0, 1 or 3", version)) case after != 0: return 0, 0, inCategory(ErrASNParse, fmt.Errorf("error verifying packet sanity: %d bytes after the TLV", after)) @@ -198,9 +210,10 @@ func readVersion(packet []byte) (Version, int, error) { } // readVersionField reads the message SEQUENCE, whose declared length must fit -// the packet, and its first field, an INTEGER (readInt32); it returns the -// reader of the fields after it and the number of octets after the SEQUENCE. -func readVersionField(packet []byte) (ber.Reader, int32, int, error) { +// the packet, and its first field, an INTEGER of any value (readInteger); it +// returns the reader of the fields after it and the number of octets after the +// SEQUENCE. +func readVersionField(packet []byte) (ber.Reader, int64, int, error) { if len(packet) < 2 { return ber.Reader{}, 0, 0, errEmptyPacket } @@ -214,7 +227,7 @@ func readVersionField(packet []byte) (ber.Reader, int32, int, error) { } r := ber.NewReader(msg) - version, err := readInt32(&r) + version, err := readInteger(&r, math.MinInt64, math.MaxInt64) if err != nil { return ber.Reader{}, 0, 0, fmt.Errorf("error parsing SNMP packet version: %w", err) } @@ -290,18 +303,19 @@ func readPayload(packet []byte, cursor int, m *Message) error { // readRequestID reads the request ID of the PDU at packet, which must span // packet, of a type other than the SNMPv1 trap: an Integer32, returned as its -// two's complement, with the reader of the PDU's fields after it. +// two's complement, or the same 32 bits sent unsigned (2^31..2^32-1, which +// net-snmp v5.9.4 keeps too), with the reader of the PDU's fields after it. func readRequestID(packet []byte) (ber.Reader, uint32, error) { pdu, err := readWhole(packet) if err != nil { return ber.Reader{}, 0, fmt.Errorf("error verifying the PDU's length: %w", err) } r := ber.NewReader(pdu) - requestID, err := readInt32(&r) + requestID, err := readInteger(&r, math.MinInt32, math.MaxUint32) if err != nil { return ber.Reader{}, 0, fmt.Errorf("error parsing SNMP packet request ID: %w", err) } - return r, uint32(requestID), nil //nolint:gosec // the Integer32's two's complement + return r, uint32(requestID), nil //nolint:gosec // its 32 bits } // requestIDRead reports whether the PDU at packet[cursor:] decodes as far as @@ -339,30 +353,24 @@ func unmarshalPDU(packet []byte, pduType PDUType, m *Message) error { } // readBulkFields reads a GetBulkRequest's non-repeaters (readCount) and -// max-repetitions, not negative (RFC 3416 section 3). +// max-repetitions, 0..2147483647 (RFC 3416 section 3). func readBulkFields(r *ber.Reader, m *Message) error { var err error if m.NonRepeaters, err = readCount(r); err != nil { return fmt.Errorf("error parsing SNMP packet non repeaters: %w", err) } - maxRepetitions, err := readInt32(r) - if err == nil && maxRepetitions < 0 { - err = fmt.Errorf("%d is negative", maxRepetitions) - } + maxRepetitions, err := readInteger(r, 0, math.MaxInt32) if err != nil { return fmt.Errorf("error parsing SNMP packet max repetitions: %w", err) } - m.MaxRepetitions = uint32(maxRepetitions) //nolint:gosec // not negative + m.MaxRepetitions = uint32(maxRepetitions) //nolint:gosec // 0..2147483647 return nil } // readErrorFields reads a PDU's error status, 0..255, and error index // (readCount) (RFC 3416 section 3). func readErrorFields(r *ber.Reader, m *Message) error { - errorStatus, err := readInt32(r) - if err == nil && (errorStatus < 0 || errorStatus > math.MaxUint8) { - err = fmt.Errorf("%d is outside 0..255", errorStatus) - } + errorStatus, err := readInteger(r, 0, math.MaxUint8) if err != nil { return fmt.Errorf("error parsing SNMP packet error: %w", err) } @@ -375,8 +383,8 @@ func readErrorFields(r *ber.Reader, m *Message) error { // unmarshalTrapV1 reads an SNMPv1 trap PDU: the enterprise, an OBJECT // IDENTIFIER; the agent address (readAgentAddress); the generic and specific -// trap, INTEGERs cut to 32 bits; the timestamp (readTimestamp); and the -// varbinds. Fields read before an error stay set. +// trap, Integer32s; the timestamp (readTimestamp); and the varbinds. Fields +// read before an error stay set. func unmarshalTrapV1(packet []byte, m *Message) error { pdu, err := readWhole(packet) if err != nil { @@ -390,10 +398,10 @@ func unmarshalTrapV1(packet []byte, m *Message) error { if m.AgentAddress, err = readAgentAddress(&r); err != nil { return fmt.Errorf("error parsing SNMPv1 trap agent address: %w", err) } - if m.GenericTrap, err = readInt32(&r); err != nil { + if m.GenericTrap, err = readInteger32(&r); err != nil { return fmt.Errorf("error parsing SNMPv1 trap generic trap: %w", err) } - if m.SpecificTrap, err = readInt32(&r); err != nil { + if m.SpecificTrap, err = readInteger32(&r); err != nil { return fmt.Errorf("error parsing SNMPv1 trap specific trap: %w", err) } if m.Timestamp, err = readTimestamp(&r); err != nil { diff --git a/testdata/codec/decode.golden b/testdata/codec/decode.golden index 0bd3542..0bfbb00 100644 --- a/testdata/codec/decode.golden +++ b/testdata/codec/decode.golden @@ -664,13 +664,7 @@ decode: error (ErrBadVersion) decode: error (ErrBadVersion) == crafted/version/2^32+1 -decode: ok -version: 1 (2c) -community: "public" -pdu: 0xa2 (Response) request-id=1 error=0 (NoError) error-index=0 non-repeaters=0 max-repetitions=0 -varbinds: 1 -vb[0]: .1.3.6.1.2.1.1.5.0 0x05 (Null) -reencode: 302602010104067075626c6963a219020101020100020100300e300c06082b060102010105000500 +decode: error (ErrBadVersion) == crafted/version/octet-string decode: error (ErrASNParse) @@ -847,13 +841,7 @@ vb[0]: .1.3.6.1.2.1.1.5.0 0x05 (Null) reencode: 302902010104067075626c6963a21c020480000000020100020100300e300c06082b060102010105000500 == crafted/pdu/request-id-2^32 -decode: ok -version: 1 (2c) -community: "public" -pdu: 0xa2 (Response) request-id=0 error=0 (NoError) error-index=0 non-repeaters=0 max-repetitions=0 -varbinds: 1 -vb[0]: .1.3.6.1.2.1.1.5.0 0x05 (Null) -reencode: 302602010104067075626c6963a219020100020100020100300e300c06082b060102010105000500 +decode: error (ErrASNParse) == crafted/pdu/request-id-9-octets decode: error (ErrASNParse) detail (ber.ErrIntegerTooLarge) @@ -1885,14 +1873,7 @@ vb[0]: .1.3.6.1.2.1.1.5.0 0x05 (Null) reencode: identical == crafted/trap-v1/specific-2^31 -decode: ok -version: 0 (1) -community: "public" -pdu: 0xa4 (Trap) request-id=0 error=0 (NoError) error-index=0 non-repeaters=0 max-repetitions=0 -trap-v1: enterprise=".1.3.6.1.4.1.20372" agent-address="192.0.2.1" generic=6 specific=-2147483648 timestamp=256 -varbinds: 1 -vb[0]: .1.3.6.1.2.1.1.5.0 0x05 (Null) -reencode: 303a02010004067075626c6963a42d06082b06010401819f144004c000020102010602048000000043020100300e300c06082b060102010105000500 +decode: error (ErrASNParse) == crafted/trap-v1/timestamp-2^32 decode: ok diff --git a/v3.go b/v3.go index a5928cd..2207068 100644 --- a/v3.go +++ b/v3.go @@ -12,6 +12,7 @@ import ( "bytes" "errors" "fmt" + "math" "github.com/netdata/gosnmp/internal/ber" "github.com/netdata/gosnmp/internal/usm" @@ -273,30 +274,23 @@ func parseV3(packet []byte, cursor int, m *Message) (v3Wire, error) { } // readGlobalData reads msgGlobalData from r into m and w (RFC 3412 section 6) -// by net-snmp's field rules, each range applying once the INTEGER is cut to -// 32 bits: msgID an INTEGER of 0..2147483647, msgMaxSize one of -// 484..2147483647, msgFlags an OCTET STRING of one octet, the security model -// an INTEGER of 1..2147483647, the User-based Security Model's 3 (another -// value is another model), and then the flags may not ask for privacy without -// authentication. +// by its ranges, each INTEGER read whole (readInteger): msgID an INTEGER of +// 0..2147483647, msgMaxSize one of 484..2147483647, msgFlags an OCTET STRING +// of one octet, the security model an INTEGER of 1..2147483647, the User-based +// Security Model's 3 (another value is another model), and then the flags may +// not ask for privacy without authentication. func readGlobalData(r *ber.Reader, m *Message, w *v3Wire) error { - msgID, err := readInt32(r) - if err == nil && msgID < 0 { - err = fmt.Errorf("%d is outside 0..%d", msgID, maxMsgID) - } + msgID, err := readInteger(r, 0, maxMsgID) if err != nil { return fmt.Errorf("error parsing SNMPV3 message ID: %w", err) } - m.MsgID = uint32(msgID) //nolint:gosec // not negative + m.MsgID = uint32(msgID) //nolint:gosec // 0..maxMsgID w.msgIDRead = true - maxSize, err := readInt32(r) - if err == nil && maxSize < minMsgMaxSize { - err = fmt.Errorf("%d is outside %d..%d", maxSize, minMsgMaxSize, maxMsgMaxSize) - } + maxSize, err := readInteger(r, minMsgMaxSize, maxMsgMaxSize) if err != nil { return fmt.Errorf("error parsing SNMPV3 msgMaxSize: %w", err) } - m.MsgMaxSize = uint32(maxSize) //nolint:gosec // at least minMsgMaxSize + m.MsgMaxSize = uint32(maxSize) //nolint:gosec // minMsgMaxSize..maxMsgMaxSize flags, err := readOctets(r) switch { case errors.Is(err, errNotOctets): @@ -309,10 +303,7 @@ func readGlobalData(r *ber.Reader, m *Message, w *v3Wire) error { // The level: the reportableFlag and the reserved bits stay on the wire. m.SecurityLevel = SecurityLevel(flags[0]) & AuthPriv w.reportable = flags[0]&reportableFlag != 0 - model, err := readInt32(r) - if err == nil && model < 1 { - err = fmt.Errorf("%d is outside 1..2147483647", model) - } + model, err := readInteger(r, 1, math.MaxInt32) if err != nil { return fmt.Errorf("error parsing SNMPV3 msgSecModel: %w", err) } @@ -330,9 +321,8 @@ func readGlobalData(r *ber.Reader, m *Message, w *v3Wire) error { // section 2.4), into m's SecurityParameters (copies) and w: the USM fields // bounded by their SEQUENCE and the SEQUENCE by the OCTET STRING, each of its // type, the engine ID at most 64 octets (net-snmp's), the engine boots and time -// within 0..2147483647 (RFC 3414 section 3.2 step 1) once cut to 32 bits, and -// the user name at most 32 octets; msgData starts right after -// msgPrivacyParameters. +// within 0..2147483647 (RFC 3414 section 3.2 step 1), and the user name at +// most 32 octets; msgData starts right after msgPrivacyParameters. func readSecurityParameters(packet []byte, off int, m *Message, w *v3Wire) error { if PDUType(packet[off]) != PDUType(OctetString) { return errors.New("invalid SNMPV3 Security Parameters") @@ -404,17 +394,14 @@ func usmOctets(r *ber.Reader, name string) ([]byte, error) { } // usmEngineValue reads msgAuthoritativeEngineBoots or -// msgAuthoritativeEngineTime: an INTEGER of at most maxEngineValue (RFC 3414 -// section 2.4) once cut to 32 bits, as net-snmp v5.9.4 cuts it. +// msgAuthoritativeEngineTime: an INTEGER of 0..maxEngineValue (RFC 3414 +// section 2.4), read whole (readInteger). func usmEngineValue(r *ber.Reader, name string) (uint32, error) { - v, err := readInt32(r) - if err == nil && v < 0 { - err = fmt.Errorf("%d is outside 0..%d", v, maxEngineValue) - } + v, err := readInteger(r, 0, maxEngineValue) if err != nil { return 0, fmt.Errorf("error parsing %s%s: %w", usmField, name, err) } - return uint32(v), nil //nolint:gosec // not negative + return uint32(v), nil //nolint:gosec // 0..maxEngineValue } // tlvAt returns the extent of the content of the TLV at packet[off:end], diff --git a/value.go b/value.go index 864e8d5..7b82ff8 100644 --- a/value.go +++ b/value.go @@ -337,7 +337,8 @@ func decodeValue(tag ValueType, content []byte) (Value, error) { // int32Value decodes INTEGER content of one to eight octets and cuts it to 32 // bits by two's complement, the width of SNMP's Integer32 (RFC 2578 section // 7.1.1), on every platform. net-snmp v5.9.4 cuts too, but keeps a value above -// 2^31-1 as its low 32 bits, unsigned, which a 32-bit int cannot hold. +// 2^31-1 as its low 32 bits, unsigned, which a 32-bit int cannot hold. It reads +// Integer values; the INTEGER header fields are read whole (readInteger). func int32Value(content []byte) (int32, error) { v, err := ber.Int64(content) return int32(v), err //nolint:gosec // the cut From 9528b1446cc98a73f060a58e15d4083dacf78ba3 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 11:42:28 +0200 Subject: [PATCH 03/11] test: NewClient must refuse a privacy cipher FIPS 140-only mode refuses Under GODEBUG=fips140=only, NewClient refuses keys that do not derive, but accepts an authPriv configuration whose privacy cipher the mode refuses (DES, and AES-CFB, which every AES protocol uses): every request then fails at its first encrypted message. TestEngineV3FIPS140OnlyNewClient now takes the security level per case and expects an error naming Config.User.PrivProtocol for each privacy protocol at authPriv, a client for a privacy protocol at authNoPriv, and the derivation error for an MD5 user at noAuthNoPriv (NewClient derives every key, whatever the level). The authPriv cases fail until NewClient checks the cipher. --- engine_v3_fips_test.go | 50 ++++++++++++++++++++++++++++++++---------- 1 file changed, 38 insertions(+), 12 deletions(-) diff --git a/engine_v3_fips_test.go b/engine_v3_fips_test.go index 4b2f7b8..08aa0f0 100644 --- a/engine_v3_fips_test.go +++ b/engine_v3_fips_test.go @@ -49,30 +49,56 @@ func TestEngineV3FIPS140Only(t *testing.T) { engineGolden.check(t, "v3-fips", results) } -// TestEngineV3FIPS140OnlyNewClient checks that the user's keys must derive -// when NewClient makes the client, before any discovery: a refusal fails -// NewClient with an error naming the user. +// TestEngineV3FIPS140OnlyNewClient checks that NewClient refuses, before any +// discovery, a configuration whose messages FIPS 140-only mode would refuse, +// with an error naming the field: keys that do not derive (MD5, SHA-1), at +// any level, since NewClient derives every key; and, at a level with privacy, +// a privacy cipher the mode refuses (DES, AES-CFB: every privacy protocol). A +// level without privacy takes any privacy protocol. func TestEngineV3FIPS140OnlyNewClient(t *testing.T) { if !fips140.Enforced() { t.Skip("run with GODEBUG=fips140=only") } - tests := map[string]struct { + const ( + md5Refused = "Config.User: crypto/md5: use of MD5 is not allowed in FIPS 140-only mode" + sha1Refused = "Config.User: crypto/sha1: use of SHA-1 is not allowed in FIPS 140-only mode" + ) + type test struct { + level SecurityLevel auth AuthProtocol priv PrivProtocol - wantErr string - }{ - "MD5": {auth: MD5, priv: NoPriv, wantErr: "Config.User: crypto/md5: use of MD5 is not allowed in FIPS 140-only mode"}, - "SHA": {auth: SHA, priv: NoPriv, wantErr: "Config.User: crypto/sha1: use of SHA-1 is not allowed in FIPS 140-only mode"}, - "SHA-AES": {auth: SHA, priv: AES, wantErr: "Config.User: crypto/sha1: use of SHA-1 is not allowed in FIPS 140-only mode"}, + wantErr string // "" for a client + } + tests := map[string]test{ + "MD5": {level: AuthNoPriv, auth: MD5, wantErr: md5Refused}, + "SHA": {level: AuthNoPriv, auth: SHA, wantErr: sha1Refused}, + "SHA-AES": {level: AuthPriv, auth: SHA, priv: AES, wantErr: sha1Refused}, + "MD5 at noAuthNoPriv": {level: NoAuthNoPriv, auth: MD5, wantErr: md5Refused}, + "SHA256": {level: AuthNoPriv, auth: SHA256}, + "SHA256-DES at authNoPriv": {level: AuthNoPriv, auth: SHA256, priv: DES}, + } + for _, priv := range usmPrivProtocols[1:] { + cipher := "AES-CFB" + if priv == DES { + cipher = "DES" + } + tests["SHA256-"+priv.String()] = test{ + level: AuthPriv, auth: SHA256, priv: priv, + wantErr: "Config.User.PrivProtocol " + priv.String() + ": " + cipher + " is not allowed in FIPS 140-only mode", + } } for name, tc := range tests { t.Run(name, func(t *testing.T) { user := User{Name: "codec-user", AuthProtocol: tc.auth, AuthPassphrase: "codec-auth-pass", PrivProtocol: tc.priv} - level := AuthNoPriv if tc.priv > NoPriv { - user.PrivPassphrase, level = "codec-priv-pass", AuthPriv + user.PrivPassphrase = "codec-priv-pass" + } + x, err := NewClient(Config{Version: Version3, SecurityLevel: tc.level, User: user, ContextName: "codec-context"}) + if tc.wantErr == "" { + assert.NoError(t, err) + assert.NotNil(t, x) + return } - x, err := NewClient(Config{Version: Version3, SecurityLevel: level, User: user, ContextName: "codec-context"}) assert.EqualError(t, err, tc.wantErr) assert.Nil(t, x) }) From 49894cba267b7b6371a274dc3653306118080098 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 11:44:07 +0200 Subject: [PATCH 04/11] fix: NewClient refuses a privacy cipher FIPS 140-only mode refuses In FIPS 140-only mode NewClient refused keys that do not derive (MD5, SHA-1) but took an authPriv configuration whose privacy cipher the mode refuses: DES, and AES-CFB, which every AES protocol uses. Each request then failed at its first encrypted message, after discovery. At a level with privacy, NewClient now also checks that the process may use the cipher (usm.Priv.CheckUse, the rule the encoder applies) and fails with an error naming the field, "Config.User.PrivProtocol AES: AES-CFB is not allowed in FIPS 140-only mode". A level without privacy does not use the cipher and takes any privacy protocol. The NewClient, SNMPv3 and Keys documentation say so, and the Keys section names DES besides AES-CFB. The FIPS engine golden's three authPriv scenarios, which showed each request failing to encrypt, can no longer be built: an authNoPriv scenario of a DES user replaces them, and TestUSMFIPS140OnlyEncrypt pins the encoder's refusal for every privacy protocol. TestUSMFIPS140OnlyDecrypt builds its client at authNoPriv, which decodes the authPriv message all the same. --- client.go | 20 +++++++++++++++----- doc.go | 15 +++++++++------ engine_v3_fips_test.go | 22 +++++++++++++--------- testdata/engine/v3-fips.golden | 32 +++++++------------------------- v3_usm_test.go | 34 +++++++++++++++++++++++++++++++++- 5 files changed, 77 insertions(+), 46 deletions(-) diff --git a/client.go b/client.go index 938d000..e35c641 100644 --- a/client.go +++ b/client.go @@ -123,10 +123,12 @@ type Client struct { // Version other than the three, and a negative Timeout, Retries or MaxOids // fail it; so do, for SNMPv3, a security level other than the three, a user // the level does not fit (a name outside 1..32 octets, a protocol out of its -// set, a protocol the level needs missing, a protocol without a passphrase) -// and keys that do not derive (FIPS 140-only mode refuses MD5 and SHA-1). The -// SNMPv3 fields of an SNMPv1 or SNMPv2c client are not checked. Its errors -// name the field. The client keeps the configuration: nothing changes it. +// set, a protocol the level needs missing, a protocol without a passphrase), +// keys that do not derive, at any level (FIPS 140-only mode refuses MD5 and +// SHA-1), and, at AuthPriv, a privacy cipher the process cannot use (FIPS +// 140-only mode refuses DES and AES-CFB, so every privacy protocol). The SNMPv3 +// fields of an SNMPv1 or SNMPv2c client are not checked. Its errors name the +// field. The client keeps the configuration: nothing changes it. func NewClient(config Config) (*Client, error) { if err := config.check(); err != nil { return nil, err @@ -162,8 +164,16 @@ func (c *Config) check() error { } // The keys derive for the engine ID discovery finds; before it, they must // derive all the same: FIPS 140-only mode, for one, refuses MD5 and SHA-1. - if _, err := c.User.localize(nil); err != nil { + keys, err := c.User.localize(nil) + if err != nil { return fmt.Errorf("Config.User: %w", err) } + // A level with privacy encrypts every request with the cipher, which the + // process must be able to use: FIPS 140-only mode refuses DES and AES-CFB. + if c.SecurityLevel.privFlag() { + if err := keys.privProtocol.spec().CheckUse(keys.priv); err != nil { + return fmt.Errorf("Config.User.PrivProtocol %v: %w", c.User.PrivProtocol, err) + } + } return nil } diff --git a/doc.go b/doc.go index 40ff17e..e79e688 100644 --- a/doc.go +++ b/doc.go @@ -330,7 +330,9 @@ // context engine ID: see below). An answer without an engine ID ends the // request with an error that matches [ErrUnknownEngineID]: the client learns // nothing, and the next request discovers again. Keys that do not derive (FIPS -// 140-only mode refuses MD5 and SHA-1) fail NewClient. +// 140-only mode refuses MD5 and SHA-1) fail NewClient, and so does, at +// AuthPriv, a privacy cipher the mode refuses (DES and AES-CFB, so every +// privacy protocol). // // The engine boots and time are a clock: the latest values received and when, // advancing with the local clock (RFC 3414 section 2.3); each attempt of a @@ -427,11 +429,12 @@ // protocol's hash (RFC 3414, RFC 7860), a privacy key the cipher's key (AES's, // or DES's 16 octets of key and pre-IV); the salt of an encrypted message is 8 // octets. Signing, verifying, encrypting and decrypting refuse anything else, -// and AES-CFB in FIPS 140-only mode, with an error. A [User] holds passphrases, -// not keys: the keys derive from non-empty passphrases of any length (RFC 3414 -// section 11.2 asks for at least 8 octets), localized to the engine ID at hand -// (RFC 3414 section 2.6). A client derives them once when it is made, for no -// engine ID, to check that they derive, and when its engine state takes an +// and DES and AES-CFB in FIPS 140-only mode, with an error. A [User] holds +// passphrases, not keys: the keys derive from non-empty passphrases of any +// length (RFC 3414 section 11.2 asks for at least 8 octets), localized to the +// engine ID at hand (RFC 3414 section 2.6). A client derives them once when it +// is made, for no engine ID, to check that they derive (and, at AuthPriv, that +// the process may use the privacy cipher), and when its engine state takes an // engine ID (discovery, an answer it takes, a Report lent to a resend); // decoding a reply derives none. [Client.DecodeMessage] derives them for the // engine ID a message names, the authentication key when the message asks for diff --git a/engine_v3_fips_test.go b/engine_v3_fips_test.go index 08aa0f0..675f68e 100644 --- a/engine_v3_fips_test.go +++ b/engine_v3_fips_test.go @@ -15,21 +15,25 @@ import ( ) // v3FIPSScenarios are the scenarios of TestEngineV3FIPS140Only. A user whose -// keys FIPS 140-only mode refuses to derive fails NewClient -// (TestEngineV3FIPS140OnlyNewClient). +// keys FIPS 140-only mode refuses to derive, or an authPriv user, whose cipher +// it refuses, fails NewClient (TestEngineV3FIPS140OnlyNewClient); the encoder's +// own refusal is TestUSMFIPS140OnlyEncrypt's. func v3FIPSScenarios() map[string]v3Scenario { return map[string]v3Scenario{ - "discovery/noauth": {user: "codec-noauth"}, - "discovery/sha256-des": {user: "codec-sha256-des"}, - "discovery/sha256-aes": {user: "codec-sha256-aes"}, - "discovery/sha512-aes256c": {user: "codec-sha512-aes256c"}, + "discovery/noauth": {user: "codec-noauth"}, + // The user's privacy protocol is one the mode refuses; a level + // without privacy does not use it. + "discovery/sha256-des-authnopriv": { + user: "codec-sha256-des", config: func(c *Config) { c.SecurityLevel = AuthNoPriv }, + }, } } // TestEngineV3FIPS140Only pins, when run with GODEBUG=fips140=only, what the -// request engine does when FIPS 140-only mode refuses an algorithm: MD5 and -// SHA-1 for the key derivation and digests, DES and AES-CFB for privacy. -// The agent runs without enforcement. testdata/engine/v3-fips.golden holds +// request engine does in FIPS 140-only mode with the configurations NewClient +// takes there: discovery and requests without authentication, and an +// authNoPriv user whose privacy protocol the mode refuses. The agent runs +// without enforcement. testdata/engine/v3-fips.golden holds // the transcripts; regenerate it with // GODEBUG=fips140=only go test -run TestEngineV3FIPS140Only -update . func TestEngineV3FIPS140Only(t *testing.T) { diff --git a/testdata/engine/v3-fips.golden b/testdata/engine/v3-fips.golden index b610bfd..a5d4831 100644 --- a/testdata/engine/v3-fips.golden +++ b/testdata/engine/v3-fips.golden @@ -15,35 +15,17 @@ 0s result: packet 3 msgID=2002 noAuthNoPriv Response id=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-noauth"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error 0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=none context engine="\x80\x00\x1f\x88\x04codec-agent" -== v3-fips/discovery/sha256-aes -0s client: user="codec-sha256-aes" authPriv timeout=1s retries=2 +== v3-fips/discovery/sha256-des-authnopriv +0s client: user="codec-sha256-des" authNoPriv timeout=1s retries=2 0s deadline +1s 0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] 0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) 0s agent answers #1 after 0s 0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] 0s deadline +1s -0s result: packet nil, error "marshal: usm: encrypting: AES-CFB is not allowed in FIPS 140-only mode" *fmt.wrapError -0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - -== v3-fips/discovery/sha256-des -0s client: user="codec-sha256-des" authPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s result: packet nil, error "marshal: usm: encrypting: DES is not allowed in FIPS 140-only mode" *fmt.wrapError -0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - -== v3-fips/discovery/sha512-aes256c -0s client: user="codec-sha512-aes256c" authPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s result: packet nil, error "marshal: usm: encrypting: AES-CFB is not allowed in FIPS 140-only mode" *fmt.wrapError +0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-sha256-des" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] +0s agent: answers #2 with Response id=1002 msgID=2002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) +0s agent answers #2 after 0s +0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-sha256-des" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] +0s result: packet 3 msgID=2002 authNoPriv Response id=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-sha256-des"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error 0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" diff --git a/v3_usm_test.go b/v3_usm_test.go index d3bf976..569ce3e 100644 --- a/v3_usm_test.go +++ b/v3_usm_test.go @@ -587,6 +587,36 @@ func TestUSMFIPS140OnlyEncodeNoAuth(t *testing.T) { } } +// TestUSMFIPS140OnlyEncrypt checks, when run with GODEBUG=fips140=only, that +// Message.Encode refuses to encrypt with a cipher the mode refuses (DES, +// AES-CFB), for every privacy protocol, with a local failure that unwraps to +// no category; NewClient refuses such a client before any request +// (TestEngineV3FIPS140OnlyNewClient). +func TestUSMFIPS140OnlyEncrypt(t *testing.T) { + if !fips140.Enforced() { + t.Skip("run with GODEBUG=fips140=only") + } + for _, priv := range usmPrivProtocols[1:] { + t.Run(priv.String(), func(t *testing.T) { + cipher := "AES-CFB" + if priv == DES { + cipher = "DES" + } + user := User{ + Name: "codec-user", AuthProtocol: SHA256, AuthPassphrase: "codec-auth-pass", + PrivProtocol: priv, PrivPassphrase: "codec-priv-pass", + } + out, err := (&Message{ + Version: Version3, SecurityLevel: AuthPriv, PDUType: SNMPv2Trap, VarBinds: usmCharVarbinds, + SecurityParameters: SecurityParameters{AuthoritativeEngineID: []byte(usmCharEngineID), UserName: "codec-user"}, + }).Encode(&user) + require.EqualError(t, err, "usm: encrypting: "+cipher+" is not allowed in FIPS 140-only mode") + assert.Nil(t, out) + assert.Empty(t, categoriesOf(err), "a local failure is in no category") + }) + } +} + // TestUSMFIPS140OnlyDecrypt checks, when run with GODEBUG=fips140=only, that // a receiver whose privacy cipher the mode refuses (DES, AES-CFB) rejects an // authPriv message made with enforcement off with the refusal, a local @@ -621,8 +651,10 @@ func TestUSMFIPS140OnlyDecrypt(t *testing.T) { }).Encode(&user) require.NoError(t, err) }) + // The decoders take the message's level: a client at authNoPriv, + // which NewClient takes in this mode, decodes the authPriv one. client := func() *Client { - return mustClient(Config{Version: Version3, SecurityLevel: AuthPriv, User: user}) + return mustClient(Config{Version: Version3, SecurityLevel: AuthNoPriv, User: user}) } paths := map[string]func() error{ "receiver": func() error { From d8249729e6f17fcd535023fe000bf81b4778bf24 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 11:44:46 +0200 Subject: [PATCH 05/11] test: pin that NewClient derives every key, whatever the level NewClient derives the user's keys for no engine ID, the authentication and privacy keys both, also at a level that uses neither, so that a key that does not derive fails NewClient and not a later request; no test outside FIPS 140-only mode held it. TestNewClientDerivesEveryKey makes a client for every authentication protocol, privacy protocol and level that fit together, each with passphrases of its own, and checks that deriving the keys again adds no password-to-key result to the package's cache. Deriving only the level's keys fails 78 of its cases. --- client_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/client_test.go b/client_test.go index aadd740..66fe77e 100644 --- a/client_test.go +++ b/client_test.go @@ -5,10 +5,13 @@ package gosnmp import ( + "crypto/fips140" + "fmt" "testing" "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // TestNewClient pins what NewClient makes of a configuration: the client keeps @@ -105,3 +108,38 @@ func TestNewClient(t *testing.T) { }) } } + +// TestNewClientDerivesEveryKey pins that NewClient derives every key of its +// user, for no engine ID, whatever the level, so that a key that does not +// derive fails it and not a later request: deriving them again adds nothing to +// the package's cache of password-to-key results. Every authentication +// protocol, privacy protocol and level that fit together; each case has +// passphrases of its own. +func TestNewClientDerivesEveryKey(t *testing.T) { + if fips140.Enforced() { + t.Skip("MD5 and SHA-1 keys do not derive in FIPS 140-only mode (TestEngineV3FIPS140OnlyNewClient)") + } + for _, auth := range usmAuthProtocols[1:] { + for _, priv := range usmPrivProtocols { + for _, level := range []SecurityLevel{NoAuthNoPriv, AuthNoPriv, AuthPriv} { + if level == AuthPriv && priv == NoPriv { + continue + } + name := fmt.Sprintf("%v-%v-%v", auth, priv, level) + t.Run(name, func(t *testing.T) { + user := User{Name: "codec-user", AuthProtocol: auth, AuthPassphrase: name + "-auth"} + if priv > NoPriv { + user.PrivProtocol, user.PrivPassphrase = priv, name+"-priv" + } + _, err := NewClient(Config{Version: Version3, SecurityLevel: level, User: user}) + require.NoError(t, err) + + before := passwordCache.Len() + _, err = user.localize(nil) + require.NoError(t, err) + assert.Equal(t, before, passwordCache.Len(), "a key NewClient did not derive") + }) + } + } + } +} From 61d5101f3fe7b82379ee8f38b968a93601771abe Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 11:46:39 +0200 Subject: [PATCH 06/11] docs: state the walks' differences from net-snmp, ErrAnswered's reach and a zero Client's IDs WalkAll said net-snmp's snmpwalk differs from it "only" for a name before rootOid, though BulkWalkAll lists differences WalkAll shares. WalkAll now differs from snmpwalk where BulkWalkAll differs from snmpbulkwalk, plus the name before rootOid (which snmpwalk takes in the subtree and fails its increasing check on) and snmpwalk's check of a name against the one before it in the same answer. BulkWalkAll's list gains the two it lacked: net-snmp prints the varbind that fails its increasing check, and every varbind of the leaf Get's answer. The package documentation said ErrAnswered is how a caller tells an agent that answered from one that did not; a walk whose answer fails its increasing check returns an error that is not marked, and it now says so. A zero Client, which NewClient did not make, numbers its request IDs from 1; the Client documentation now says so. --- client.go | 11 ++++++----- doc.go | 3 ++- walk.go | 19 +++++++++++++------ 3 files changed, 21 insertions(+), 12 deletions(-) diff --git a/client.go b/client.go index e35c641..a9d9aaf 100644 --- a/client.go +++ b/client.go @@ -80,11 +80,12 @@ type Config struct { // Client is an SNMP client: NewClient makes it from a Config, Connect opens // its connection, and its methods send requests. A zero Client, which -// NewClient did not make, has a zero configuration without its defaults: it -// can only encode SNMPv1 messages and decode messages. A Client is not safe for -// concurrent use, Close excepted: requests share its connection, receive -// buffer and deadline, so run one request at a time, or give each goroutine -// its own Client. +// NewClient did not make, has a zero configuration without its defaults: it can +// only encode SNMPv1 messages, whose request IDs it numbers from 1 where +// NewClient draws a random start, and decode messages. A Client is not safe for +// concurrent use, Close excepted: requests share its connection, receive buffer +// and deadline, so run one request at a time, or give each goroutine its own +// Client. type Client struct { // config is the configuration NewClient checked, with its defaults. config Config diff --git a/doc.go b/doc.go index e79e688..1671877 100644 --- a/doc.go +++ b/doc.go @@ -166,7 +166,8 @@ // discarded replies included; errors of the caller's own code (a context it // gave, and a panic in one) pass through unchanged. A failed request returns no // message, so this is how a caller tells an agent that answered from one that -// did not. +// did not, but for a walk whose answer fails its increasing check: that error +// is not marked (see [Client.BulkWalkAll]). // // 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 diff --git a/walk.go b/walk.go index f105cbe..461cc46 100644 --- a/walk.go +++ b/walk.go @@ -42,9 +42,12 @@ import ( // error for a name in the subtree, rootOid included, that is not after the // requested one (each name of an answer is compared with the requested one). // It also differs from net-snmp where a failed Get of a leaf rootOid (a -// timeout, a Report) fails the walk, which net-snmp ignores, and where the -// walk stops at the first value that ends it, while net-snmp goes on printing -// the values of the same answer that lie in the subtree. +// timeout, a Report) fails the walk, which net-snmp ignores; where the walk +// stops at the first value that ends it, while net-snmp goes on printing the +// values of the same answer that lie in the subtree; where net-snmp prints the +// varbind that fails its increasing check, which the walk does not return; and +// where net-snmp prints every varbind of the leaf Get's answer, of which the +// walk takes the first. // ctx bounds the walk, each of its requests and the Get of a leaf root: a done // ctx ends the walk with its error and the values before it, and a nil ctx // fails it before its first request is sent. maxRepetitions is the @@ -60,9 +63,13 @@ func (c *Client) BulkWalkAll(ctx context.Context, rootOid string, maxRepetitions // WalkAll walks the subtree under rootOid with GETNEXT requests, one per // value, where BulkWalkAll asks for many at a time, and returns its values and // how the walk ended. It walks SNMPv1 agents too, and otherwise starts, ends -// and fails as BulkWalkAll does; net-snmp's snmpwalk differs only for a name -// before rootOid, which fails its increasing check where WalkAll ends (or, as -// the first answer, gets rootOid). +// and fails as BulkWalkAll does. It differs from net-snmp's snmpwalk where +// BulkWalkAll differs from snmpbulkwalk, and for a name before rootOid, which +// snmpwalk takes in the subtree and so fails its increasing check, where +// WalkAll ends (or, as the first answer, gets rootOid); snmpwalk also checks +// each name against the one before it in the same answer, where WalkAll checks +// it against the requested one, which differs only for an answer of more than +// the one varbind it asks for. func (c *Client) WalkAll(ctx context.Context, rootOid string) (results []VarBind, end WalkEnd, err error) { return c.walk(ctx, GetNextRequest, rootOid, 0) } From 8a0933b1c66d3b9a6cbe911cfd85752a9c99db72 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 11:46:39 +0200 Subject: [PATCH 07/11] refactor: drop interrupt's guard against a second interrupt interrupt ignored a call for an attempt it had already interrupted. Only the context.AfterFunc that interruptible registers for each attempt calls it, and AfterFunc calls its function at most once, so the guard never fires; no test can reach it. The interrupted channel stays: clear waits on it. --- transport.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/transport.go b/transport.go index 1379ca6..6d768dd 100644 --- a/transport.go +++ b/transport.go @@ -137,12 +137,12 @@ func (a attemptInterrupts) clear() { // interrupt makes the pending and later reads and writes of attempt seq fail // at once, with a deadline in the past on its connection, while the attempt -// runs; once one interrupt has started, others do nothing. It sets the +// runs; the context's AfterFunc runs it at most once per attempt. It sets the // deadline without mu, which a slow SetDeadline then cannot hold. func (c *Client) interrupt(seq uint64) { c.mu.Lock() conn := c.attempt.conn - if conn == nil || c.attempt.seq != seq || c.attempt.interrupted != nil { + if conn == nil || c.attempt.seq != seq { c.mu.Unlock() return } From ea51260aa81119e6fdfd999277e4bf5c549a58d7 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 11:47:36 +0200 Subject: [PATCH 08/11] fix: name the missing SNMPv1 agent address in its encode error Encoding an SNMPv1 trap whose agent address is the zero netip.Addr failed with "unable to marshal SNMPv1 AgentAddress: invalid IP is not an IPv4 address", the zero Addr's text. It now fails with "unable to marshal SNMPv1 AgentAddress: no address"; an address of another family keeps its text. TestMarshalUnencodableValues pins both. --- codec_encode_test.go | 29 ++++++++++++++++++++--------- pdu.go | 5 ++++- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/codec_encode_test.go b/codec_encode_test.go index 176a49e..ea810f2 100644 --- a/codec_encode_test.go +++ b/codec_encode_test.go @@ -100,7 +100,8 @@ func TestMarshalLongOctetStringFields(t *testing.T) { } // TestMarshalUnencodableValues checks that Message.Encode reports caller values -// it cannot encode as errors instead of panicking. +// it cannot encode as errors instead of panicking, with the error's text where +// the case gives one. func TestMarshalUnencodableValues(t *testing.T) { varbind := func(value Value) *Message { return &Message{ @@ -121,19 +122,29 @@ func TestMarshalUnencodableValues(t *testing.T) { GenericTrap: 6, } } - tests := map[string]*Message{ - "ObjectIdentifier with an empty OID": varbind(ObjectIdentifierValue("")), - "IPAddress of the zero Addr": varbind(IPAddressValue(netip.Addr{})), - "v1 trap with an empty agent address": trap(netip.Addr{}), - "v1 trap with an IPv6 agent address": trap(netip.MustParseAddr("2001:db8::1")), + tests := map[string]struct { + msg *Message + wantErr string + }{ + "ObjectIdentifier with an empty OID": {msg: varbind(ObjectIdentifierValue(""))}, + "IPAddress of the zero Addr": {msg: varbind(IPAddressValue(netip.Addr{}))}, + "v1 trap with an empty agent address": { + msg: trap(netip.Addr{}), wantErr: "unable to marshal SNMPv1 AgentAddress: no address", + }, + "v1 trap with an IPv6 agent address": { + msg: trap(netip.MustParseAddr("2001:db8::1")), wantErr: "unable to marshal SNMPv1 AgentAddress: 2001:db8::1 is not an IPv4 address", + }, } - for name, packet := range tests { + for name, tc := range tests { t.Run(name, func(t *testing.T) { var err error - panicked, _ := observe(func() { _, err = packet.Encode(nil) }) + panicked, _ := observe(func() { _, err = tc.msg.Encode(nil) }) if panicked || err == nil { - t.Errorf("Encode panicked: %v, error: %v; want an error", panicked, err) + t.Fatalf("Encode panicked: %v, error: %v; want an error", panicked, err) + } + if tc.wantErr != "" { + require.EqualError(t, err, tc.wantErr) } }) } diff --git a/pdu.go b/pdu.go index e4ffbbf..1e4fa0f 100644 --- a/pdu.go +++ b/pdu.go @@ -581,7 +581,10 @@ func (m *Message) appendTrapV1Header(dst []byte) ([]byte, error) { return nil, err } agentAddress := m.AgentAddress.Unmap() - if !agentAddress.Is4() { + switch { + case !agentAddress.IsValid(): + return nil, errors.New("unable to marshal SNMPv1 AgentAddress: no address") + case !agentAddress.Is4(): return nil, fmt.Errorf("unable to marshal SNMPv1 AgentAddress: %v is not an IPv4 address", m.AgentAddress) } octets := agentAddress.As4() From dfb213abc5c7766655b9926f7b9da7e3c4b302a0 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 11:48:53 +0200 Subject: [PATCH 09/11] refactor: one Close check at the exit of a request without a reply sendOneRequest checked whether Close had run in two places: after an attempt without a reply, where it overrode the attempt's outcome, and at the decision not to retry. Every exit without a reply now goes through one place, which returns the closed error once Close has run, whatever ended the request. A retryable attempt that Close ended now reaches the retry decision, and with retries left one more attempt, which fails at once on the closed client; the request ends with the same error and no wait. TestCloseWinsOverAttemptOutcome passes unchanged, with the same calls of the context's Err in each case; without the check, all ten of its cases fail. --- engine.go | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/engine.go b/engine.go index 3be9371..cc7d6bb 100644 --- a/engine.go +++ b/engine.go @@ -185,7 +185,7 @@ const ( // attemptTransportError: the write or the read failed otherwise. attemptTransportError // attemptClosed: the write or the read failed on a closed connection - // (net.ErrClosed), or Close closed the client. + // (net.ErrClosed). attemptClosed // attemptContextDone: the context was done when the attempt would start. attemptContextDone @@ -268,10 +268,10 @@ type sentIDs struct { // discovery is set, an SNMPv3 one with the engine boots and time of sec's clock // and its keys, and returns the reply that answers it, and whether the reply's // engine parameters were committed into the engine state, retrying up to -// Retries times. Once Close closed the client, a request that ends without a -// reply ends with net.ErrClosed, whatever else ended it: an attempt's outcome -// or the decision not to retry. An exchange that ends without an answer goes -// through unanswered. +// Retries times. A request that ends without a reply goes through its one +// exit: once Close closed the client, it ends with net.ErrClosed, whatever +// ended it (an attempt's outcome or the decision not to retry), and an +// exchange that ends without an answer goes through unanswered. func (c *Client) sendOneRequest(ctx context.Context, req *Message, discovery bool, sec attemptSecurity) (*Message, bool, error) { e := exchange{c: c, req: req, ctx: ctx, discovery: discovery, sec: sec} // The IDs of the attempts before the current one, in a local array, not a @@ -282,23 +282,21 @@ func (c *Client) sendOneRequest(ctx context.Context, req *Message, discovery boo earlier := sent[:0] for n := 0; ; n++ { out := e.attempt(earlier) - if out.kind != attemptReply && c.isClosed() { - out = attemptOutcome{kind: attemptClosed, err: errClosed} - } - if !out.kind.retryable() { - if out.kind != attemptReply { - out.err = e.unanswered(out.err) - } + if out.kind == attemptReply { return out.reply, out.committed, out.err } - // A retryable attempt has stamped req with its IDs. - earlier = append(earlier, sentIDs{req.RequestID, req.MsgID}) - if err := e.endErr(n, out); err != nil { - if c.isClosed() { - err = errClosed + err := out.err + if out.kind.retryable() { + // A retryable attempt has stamped req with its IDs. + earlier = append(earlier, sentIDs{req.RequestID, req.MsgID}) + if err = e.endErr(n, out); err == nil { + continue } - return nil, false, e.unanswered(err) } + if c.isClosed() { + err = errClosed + } + return nil, false, e.unanswered(err) } } From 46b83edbf057c9a75cc4373d94653391d3c9e9d2 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 12:14:01 +0200 Subject: [PATCH 10/11] test: pin Close with retries left and the writes of each Close case Since the one Close check moved to the request's exit, an attempt that Close ends in the connection's code reaches the retry decision and, with retries left, one more attempt, which fails at once on the closed client. TestCloseWinsOverAttemptOutcome ran those cases with no retries only; it now runs each at 0 and 2 retries and checks the writes of every case, so an attempt that wrote on the closed client after Close would fail it. --- engine_requests_test.go | 70 +++++++++++++++++++++++------------------ 1 file changed, 39 insertions(+), 31 deletions(-) diff --git a/engine_requests_test.go b/engine_requests_test.go index 69937a2..b40ebd9 100644 --- a/engine_requests_test.go +++ b/engine_requests_test.go @@ -1397,38 +1397,40 @@ func (c *errOnCall) Err() error { // without a reply, that once Close has run the request fails with the // client's closed error, which wraps net.ErrClosed: Close runs as an attempt // ends otherwise, or as the request decides whether to retry, through the -// connection's or the context's code. +// connection's or the context's code. An attempt Close ends in the +// connection's code runs with retries left too: the retry decision and the +// next attempt, which fails at once on the closed client, write nothing more. func TestCloseWinsOverAttemptOutcome(t *testing.T) { tests := map[string]struct { retries int // set makes the attempt end so, closing x as it does; cancel ends ctx. set func(x *Client, c *fakeTransport, cancel context.CancelFunc) // errCall, when set, is the call of the context's Err that cancels it - // and closes x, its last call, after writes writes. + // and closes x, its last call. writes is the number of writes. errCall, writes int }{ - "read timeout": {set: func(x *Client, c *fakeTransport, _ context.CancelFunc) { + "read timeout": {writes: 1, set: func(x *Client, c *fakeTransport, _ context.CancelFunc) { c.failRead = func(int) error { _ = x.Close(); return os.ErrDeadlineExceeded } }}, - "write timeout": {set: func(x *Client, c *fakeTransport, _ context.CancelFunc) { + "write timeout": {writes: 1, set: func(x *Client, c *fakeTransport, _ context.CancelFunc) { c.failWrite = func(int) error { _ = x.Close(); return os.ErrDeadlineExceeded } }}, - "read error": {set: func(x *Client, c *fakeTransport, _ context.CancelFunc) { + "read error": {writes: 1, set: func(x *Client, c *fakeTransport, _ context.CancelFunc) { c.failRead = func(int) error { _ = x.Close(); return refused } }}, - "write error": {set: func(x *Client, c *fakeTransport, _ context.CancelFunc) { + "write error": {writes: 1, set: func(x *Client, c *fakeTransport, _ context.CancelFunc) { c.failWrite = func(int) error { _ = x.Close(); return errEngineWrite } }}, - "closed read": {set: func(x *Client, c *fakeTransport, _ context.CancelFunc) { + "closed read": {writes: 1, set: func(x *Client, c *fakeTransport, _ context.CancelFunc) { c.failRead = func(int) error { _ = x.Close(); return closedRead } }}, - "deadline failure": {set: func(x *Client, c *fakeTransport, _ context.CancelFunc) { + "deadline failure": {writes: 0, set: func(x *Client, c *fakeTransport, _ context.CancelFunc) { c.deadlineErr = errors.New("codec deadline failure") c.beforeDeadline = func() { _ = x.Close() } }}, // The context's interrupt ends the read, and the caller closes the // client, as a caller that ends a job does. - "context interrupt": {set: func(x *Client, c *fakeTransport, cancel context.CancelFunc) { + "context interrupt": {writes: 1, set: func(x *Client, c *fakeTransport, cancel context.CancelFunc) { c.failRead = func(int) error { cancel(); _ = x.Close(); return os.ErrDeadlineExceeded } }}, // Every attempt times out. The context's Err runs at each attempt's @@ -1446,28 +1448,34 @@ func TestCloseWinsOverAttemptOutcome(t *testing.T) { }, } for name, tc := range tests { - t.Run(name, func(t *testing.T) { - conn := newFakeTransport(nil, nil) - config := engineConfig(Version2c) - config.Retries = tc.retries - x := newEngineClientFrom(t, conn, config) - base, cancel := context.WithCancel(context.Background()) - defer cancel() - ctx := base - if tc.errCall != 0 { - ctx = &errOnCall{Context: base, n: tc.errCall, act: func() { cancel(); _ = x.Close() }} - } - tc.set(x, conn, cancel) - - res, err := x.Get(ctx, []string{engineOID}) - assert.Nil(t, res) - require.ErrorIs(t, err, errClosed) - require.ErrorIs(t, err, net.ErrClosed) - if c, ok := ctx.(*errOnCall); ok { - assert.Equal(t, [2]int{tc.errCall, tc.writes}, [2]int{c.calls, conn.writes}, - "the context's Err calls and the writes: Close ran where the case says") - } - }) + retries := []int{tc.retries} + if tc.errCall == 0 { + retries = []int{0, 2} + } + for _, r := range retries { + t.Run(fmt.Sprintf("%s/retries %d", name, r), func(t *testing.T) { + conn := newFakeTransport(nil, nil) + config := engineConfig(Version2c) + config.Retries = r + x := newEngineClientFrom(t, conn, config) + base, cancel := context.WithCancel(context.Background()) + defer cancel() + ctx := base + if tc.errCall != 0 { + ctx = &errOnCall{Context: base, n: tc.errCall, act: func() { cancel(); _ = x.Close() }} + } + tc.set(x, conn, cancel) + + res, err := x.Get(ctx, []string{engineOID}) + assert.Nil(t, res) + require.ErrorIs(t, err, errClosed) + require.ErrorIs(t, err, net.ErrClosed) + assert.Equal(t, tc.writes, conn.writes, "the writes") + if c, ok := ctx.(*errOnCall); ok { + assert.Equal(t, tc.errCall, c.calls, "the context's Err calls: Close ran where the case says") + } + }) + } } } From 7d9d3a781d560ec6f52dfc1769135d9122024fe7 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 12:14:52 +0200 Subject: [PATCH 11/11] docs: the header ranges' effects, a privacy key's hash, snmpwalk's exception values - The differences from net-snmp name a case the header rule adds: an SNMPv1 generic or specific trap of 2^31..2^32-1, sent unsigned, fails the message, where net-snmp keeps it; the request ID keeps those 32 bits. - Message: an error index or non-repeaters above 2147483647 fails the message (256..2147483647 still reads as 255). - unmarshalPDU points at readRequestID for the request ID's rule. - User: a privacy key derives with the authentication protocol's hash, MD5 without one, which is why FIPS 140-only mode refuses a user with a privacy protocol and no authentication protocol. - WalkAll: snmpwalk prints an exception value before rootOid and ends there, without failing its increasing check. --- doc.go | 2 ++ message.go | 3 ++- pdu.go | 6 +++--- v3_usm.go | 4 ++-- walk.go | 10 +++++----- 5 files changed, 14 insertions(+), 11 deletions(-) diff --git a/doc.go b/doc.go index 1671877..371d7d7 100644 --- a/doc.go +++ b/doc.go @@ -518,6 +518,8 @@ // its low 32 bits lie in it, where net-snmp cuts it to 32 bits first (a // version of 2^32+1 reads as SNMPv2c there, an error status of 2^32 as // noError) +// - an SNMPv1 generic or specific trap of 2^31..2^32-1, sent unsigned, fails +// the message, where net-snmp keeps it (the request ID keeps those 32 bits) // - the community and context fields take OCTET STRINGs only, and an SNMPv1 // agent address four octets or an empty IpAddress, where net-snmp takes // other string types (of up to four octets for the agent address) diff --git a/message.go b/message.go index 29fa07d..26d1083 100644 --- a/message.go +++ b/message.go @@ -57,7 +57,8 @@ type Message struct { // ErrorStatus and ErrorIndex are the PDU's error status and index; a // GetBulkRequest has NonRepeaters and MaxRepetitions in their place. // Decoded, an error status outside 0..255 fails the message, and an error - // index or non-repeaters above 255 reads as 255. + // index or non-repeaters of 256..2147483647 reads as 255, and a larger one + // fails the message. ErrorStatus ErrorStatus ErrorIndex uint8 NonRepeaters uint8 diff --git a/pdu.go b/pdu.go index 1e4fa0f..0878f60 100644 --- a/pdu.go +++ b/pdu.go @@ -332,9 +332,9 @@ func requestIDRead(packet []byte, cursor int) bool { } // unmarshalPDU reads a PDU of pduType other than the SNMPv1 trap: the request -// ID, an Integer32 whose two's complement RequestID holds; the fields after it -// (readBulkFields of a GetBulkRequest, readErrorFields of any other PDU); and -// the varbinds. Fields read before an error stay set. +// ID (readRequestID); the fields after it (readBulkFields of a GetBulkRequest, +// readErrorFields of any other PDU); and the varbinds. Fields read before an +// error stay set. func unmarshalPDU(packet []byte, pduType PDUType, m *Message) error { r, requestID, err := readRequestID(packet) if err != nil { diff --git a/v3_usm.go b/v3_usm.go index 467532b..e025cb5 100644 --- a/v3_usm.go +++ b/v3_usm.go @@ -123,8 +123,8 @@ type User struct { AuthPassphrase string // PrivProtocol is the privacy protocol and PrivPassphrase the passphrase - // its key derives from, with the authentication protocol's hash; zero - // means unset. + // its key derives from, with the authentication protocol's hash, MD5 + // without one; zero means unset. PrivProtocol PrivProtocol PrivPassphrase string } diff --git a/walk.go b/walk.go index 461cc46..6cbd27c 100644 --- a/walk.go +++ b/walk.go @@ -65,11 +65,11 @@ func (c *Client) BulkWalkAll(ctx context.Context, rootOid string, maxRepetitions // how the walk ended. It walks SNMPv1 agents too, and otherwise starts, ends // and fails as BulkWalkAll does. It differs from net-snmp's snmpwalk where // BulkWalkAll differs from snmpbulkwalk, and for a name before rootOid, which -// snmpwalk takes in the subtree and so fails its increasing check, where -// WalkAll ends (or, as the first answer, gets rootOid); snmpwalk also checks -// each name against the one before it in the same answer, where WalkAll checks -// it against the requested one, which differs only for an answer of more than -// the one varbind it asks for. +// snmpwalk takes in the subtree, failing its increasing check or, with an +// exception value, printing it and ending, where WalkAll ends (or, as the first +// answer, gets rootOid); snmpwalk also checks each name against the one before +// it in the same answer, where WalkAll checks it against the requested one, +// which differs only for an answer of more than the one varbind it asks for. func (c *Client) WalkAll(ctx context.Context, rootOid string) (results []VarBind, end WalkEnd, err error) { return c.walk(ctx, GetNextRequest, rootOid, 0) }