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
31 changes: 21 additions & 10 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -123,10 +124,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
Expand Down Expand Up @@ -162,8 +165,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
}
38 changes: 38 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
})
}
}
}
}
29 changes: 20 additions & 9 deletions codec_encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand All @@ -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)
}
})
}
Expand Down
172 changes: 167 additions & 5 deletions codec_failure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
package gosnmp

import (
"errors"
"fmt"
"math"
"slices"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -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
Expand All @@ -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).
Expand Down Expand Up @@ -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
}
Loading
Loading