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
12 changes: 8 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ For support and help with this fork, open an [issue](https://github.com/netdata/

GoSNMP has the following SNMP functions:

* **NewClient** - makes a client of a `Config`, which it checks, with defaults for a zero port (161), timeout (1 s) and `MaxOids` (60).
* **Get** - one or more OIDs, up to `MaxOids` (60 by default).
* **WalkAll** - retrieve a subtree of values using GETNEXT.
* **BulkWalkAll** - retrieve a subtree of values using GETBULK (SNMPv2c and SNMPv3 only), with the walk's max-repetitions.
Expand Down Expand Up @@ -60,21 +61,24 @@ https://pkg.go.dev/github.com/netdata/gosnmp
Here is the body of `examples/example/main.go`, which imports the package as `g`:

```go
// A Client literal configures the client: SNMPv2c to port 161 with the
// community "public"; Connect fills in MaxOids (60).
client := &g.Client{
// NewClient makes the client of a configuration, which it checks: SNMPv2c
// to port 161 with the community "public"; MaxOids takes its default (60).
client, err := g.NewClient(g.Config{
Target: "192.168.1.10",
Port: 161,
Community: "public",
Version: g.Version2c,
Timeout: 2 * time.Second,
Retries: 3,
})
if err != nil {
log.Fatalf("NewClient() err: %v", err)
}
// Connect and each request take a context that bounds that call only:
// here both end within 30 seconds.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
err := client.Connect(ctx)
err = client.Connect(ctx)
if err != nil {
log.Fatalf("Connect() err: %v", err)
}
Expand Down
4 changes: 2 additions & 2 deletions codec_bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func BenchmarkDecode(b *testing.B) {
for _, in := range inputs {
b.Run(in.name, func(b *testing.B) {
data := in.in()
x := &Client{}
x := mustClient(Config{})
b.ReportAllocs()
for b.Loop() {
if _, err := x.DecodeMessage(data); err != nil {
Expand All @@ -47,7 +47,7 @@ func BenchmarkEncode(b *testing.B) {
for i := range oids {
oids[i] = VarBind{Name: ".1.3.6.1.2.1.2.2.1.10." + strconv.Itoa(i+1), Value: NullValue()}
}
response, err := (&Client{}).DecodeMessage(kyoceraResponseBytes())
response, err := mustClient(Config{}).DecodeMessage(kyoceraResponseBytes())
if err != nil {
b.Fatal(err)
}
Expand Down
8 changes: 4 additions & 4 deletions codec_decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ type decodeCase struct {
// dumpDecode decodes c with DecodeMessage and, for a case with SNMPv3
// credentials, with a receiver of its own (dumpReceive).
func dumpDecode(t *testing.T, c decodeCase) string {
x := &Client{}
x := mustClient(Config{})
if c.decoder != nil {
x = c.decoder()
}
Expand Down Expand Up @@ -80,7 +80,7 @@ func dumpDecode(t *testing.T, c decodeCase) string {
d.line("input: modified " + dumpBytes(in))
}
dumpPacket(&d, p)
dumpReencode(&d, p, &x.User, c.in)
dumpReencode(&d, p, &x.config.User, c.in)
dumpReceive(t, &d, c)
return d.String()
}
Expand All @@ -97,7 +97,7 @@ func dumpReceive(t *testing.T, d *dumpWriter, c decodeCase) {
}
// A user NewReceiver refuses, such as one with a protocol and no
// passphrase, is refused for every engine ID.
user := c.decoder().User
user := c.decoder().config.User
if _, err := NewReceiver(ReceiverConfig{Users: []EngineUser{{EngineID: []byte(codecEngineID), User: user}}}); err != nil {
d.line("receive: NewReceiver " + dumpError(err))
return
Expand Down Expand Up @@ -448,7 +448,7 @@ func usmUser(auth AuthProtocol, authPass string, priv PrivProtocol, privPass str
// usmDecoder returns a decoder configured for the synthetic codec-user credentials.
func usmDecoder(auth AuthProtocol, authPass string, priv PrivProtocol, privPass string) func() *Client {
return func() *Client {
return &Client{User: usmUser(auth, authPass, priv, privPass)}
return mustClient(Config{User: usmUser(auth, authPass, priv, privPass)})
}
}

Expand Down
42 changes: 20 additions & 22 deletions codec_encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func TestMarshalLongOctetStringFields(t *testing.T) {
if len(want.engineID) > maxDecodedEngineIDLen {
// Longer than the decoder takes: the fields as the encoder
// laid them out.
_, err = (&Client{}).DecodeMessage(msg)
_, err = mustClient(Config{}).DecodeMessage(msg)
require.ErrorIs(t, err, ErrASNParse)
m := splitV3Message(t, msg)
if got := (fields{engineID: string(m.usm[0]), userName: string(m.usm[3])}); got != want {
Expand All @@ -83,7 +83,7 @@ func TestMarshalLongOctetStringFields(t *testing.T) {
return
}

decoded, err := (&Client{}).DecodeMessage(msg)
decoded, err := mustClient(Config{}).DecodeMessage(msg)
if err != nil {
t.Fatalf("decoding the encoded message: %v\nmessage: %x", err, msg)
}
Expand Down Expand Up @@ -262,7 +262,7 @@ func TestEncodeReportableFlag(t *testing.T) {
continue // EncodeMessage has no SNMPv1 trap fields
}
t.Run(fmt.Sprintf("EncodeMessage/%v/%v", pdu, level), func(t *testing.T) {
x := &Client{Version: Version3, SecurityLevel: level, User: codecUser(levelAuth(level), NoPriv)}
x := mustClient(Config{Version: Version3, SecurityLevel: level, User: codecUser(levelAuth(level), NoPriv)})
seedEngine(codecEngineID, 7, 1234)(x) // EncodeMessage signs with the engine state's keys
msg, err := x.EncodeMessage(pdu, vars, 0, 0)
if err != nil {
Expand All @@ -286,19 +286,18 @@ func classFlags(level SecurityLevel, pdu PDUType) SecurityLevel {
}

// TestInvalidSecurityLevel checks that a security level other than the three
// fails: the encoder's check (Message.Encode) and the client's (validate, as
// Connect, EncodeMessage and DecodeMessage run it); privacy without
// authentication has its own error in the encoder.
// fails: the encoder's check (Message.Encode) and the client's (NewClient);
// privacy without authentication has its own error in the encoder.
func TestInvalidSecurityLevel(t *testing.T) {
const invalid = "validate: SecurityLevel must be populated with an appropriate security level"
const invalid = " is not NoAuthNoPriv, AuthNoPriv or AuthPriv"
tests := map[string]struct {
level SecurityLevel
encodeErr, valid string
}{
"privacy without authentication": {level: AuthPriv &^ AuthNoPriv, encodeErr: "unable to marshal SNMPv3 msgFlags: privacy without authentication", valid: invalid},
"the reportableFlag's bit": {level: reportableFlag, encodeErr: "unable to marshal SNMPv3 security level 4: not NoAuthNoPriv, AuthNoPriv or AuthPriv", valid: invalid},
"authNoPriv and another bit": {level: AuthNoPriv | reportableFlag, encodeErr: "unable to marshal SNMPv3 security level 5: not NoAuthNoPriv, AuthNoPriv or AuthPriv", valid: invalid},
"authPriv and another bit": {level: AuthPriv | 0x80, encodeErr: "unable to marshal SNMPv3 security level 131: not NoAuthNoPriv, AuthNoPriv or AuthPriv", valid: invalid},
"privacy without authentication": {level: AuthPriv &^ AuthNoPriv, encodeErr: "unable to marshal SNMPv3 msgFlags: privacy without authentication", valid: "Config.SecurityLevel SecurityLevel(2)" + invalid},
"the reportableFlag's bit": {level: reportableFlag, encodeErr: "unable to marshal SNMPv3 security level 4: not NoAuthNoPriv, AuthNoPriv or AuthPriv", valid: "Config.SecurityLevel SecurityLevel(4)" + invalid},
"authNoPriv and another bit": {level: AuthNoPriv | reportableFlag, encodeErr: "unable to marshal SNMPv3 security level 5: not NoAuthNoPriv, AuthNoPriv or AuthPriv", valid: "Config.SecurityLevel SecurityLevel(5)" + invalid},
"authPriv and another bit": {level: AuthPriv | 0x80, encodeErr: "unable to marshal SNMPv3 security level 131: not NoAuthNoPriv, AuthNoPriv or AuthPriv", valid: "Config.SecurityLevel SecurityLevel(131)" + invalid},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
Expand All @@ -308,9 +307,9 @@ func TestInvalidSecurityLevel(t *testing.T) {
PDUType: GetRequest, MsgID: 1, RequestID: 1,
}).Encode(&user)
require.EqualError(t, err, tc.encodeErr)
x := &Client{Version: Version3, SecurityLevel: tc.level, User: user}
_, err = x.EncodeMessage(GetRequest, nil, 0, 0)
x, err := NewClient(Config{Version: Version3, SecurityLevel: tc.level, User: user})
require.EqualError(t, err, tc.valid)
require.Nil(t, x)
})
}
}
Expand Down Expand Up @@ -680,8 +679,7 @@ func encodeCases(t *testing.T) []encodeCase {
// fixedIDs starts the client's ID counters at 0, so that its request ID
// and msgID are 1 (a client draws random ones otherwise).
fixedIDs := func(x *Client) *Client {
x.SetRequestID(0)
x.SetMsgID(0)
x.requestID, x.msgID = 0, 0
return x
}
marshal := func(p *Message) func() ([]byte, error) { return func() ([]byte, error) { return p.Encode(nil) } }
Expand Down Expand Up @@ -844,36 +842,36 @@ func encodeCases(t *testing.T) []encodeCase {

// EncodeMessage builds the message from the client's configuration.
{"encode-packet/v1/get-request", func() ([]byte, error) {
x := fixedIDs(&Client{Version: Version1, Community: "public"})
x := fixedIDs(mustClient(Config{Version: Version1, Community: "public"}))
return x.EncodeMessage(GetRequest, nullVar, 0, 0)
}},
{"encode-packet/v2c/getbulk-request", func() ([]byte, error) {
x := fixedIDs(&Client{Version: Version2c, Community: "public"})
x := fixedIDs(mustClient(Config{Version: Version2c, Community: "public"}))
return x.EncodeMessage(GetBulkRequest, nullVar, 1, 10)
}},
{"encode-packet/v2c/getbulk-request/max-repetitions-max-uint32", func() ([]byte, error) {
x := fixedIDs(&Client{Version: Version2c, Community: "public"})
x := fixedIDs(mustClient(Config{Version: Version2c, Community: "public"}))
return x.EncodeMessage(GetBulkRequest, nullVar, 0, math.MaxUint32)
}},
// An SNMPv3 one takes the engine state a request learned: the codec
// engine with boots 7 and time 1234.
{"encode-packet/v3/auth-no-priv/sha", func() ([]byte, error) {
x := fixedIDs(&Client{
x := fixedIDs(mustClient(Config{
Version: Version3,
SecurityLevel: AuthNoPriv,
User: codecUser(SHA, NoPriv),
ContextName: "codec-context",
})
}))
seedEngine(codecEngineID, 7, 1234)(x)
return x.EncodeMessage(GetRequest, nullVar, 0, 0)
}},
{"encode-packet/v3/auth-priv/sha-aes", func() ([]byte, error) {
x := fixedIDs(&Client{
x := fixedIDs(mustClient(Config{
Version: Version3,
SecurityLevel: AuthPriv,
User: codecUser(SHA, AES),
ContextName: "codec-context",
})
}))
seedEngine(codecEngineID, 7, 1234)(x)
return x.EncodeMessage(GetRequest, nullVar, 0, 0)
}},
Expand Down
30 changes: 4 additions & 26 deletions codec_failure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ func TestDecodeFailureNoMessage(t *testing.T) {

for name, tc := range tests {
t.Run(name, func(t *testing.T) {
p, err := (&Client{}).DecodeMessage(tc.in)
p, err := mustClient(Config{}).DecodeMessage(tc.in)
if assert.Error(t, err) {
assert.Equal(t, tc.wantErr, err.Error())
}
Expand All @@ -122,28 +122,6 @@ func TestDecodeFailureNoMessage(t *testing.T) {
}
}

// TestDecodeMessagePrepareFailure pins that DecodeMessage checks the client's
// configuration as Connect does and returns no message with its error.
func TestDecodeMessagePrepareFailure(t *testing.T) {
tests := map[string]struct {
x *Client
wantErr string
}{
"negative MaxOids": {x: &Client{MaxOids: -1}, wantErr: "field MaxOids cannot be less than 0"},
"SNMPv3 user without a name": {
x: &Client{Version: Version3, SecurityLevel: NoAuthNoPriv},
wantErr: "User.Name is required",
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
p, err := tc.x.DecodeMessage(craftedMsg(1, craftedPDU(Response, craftedVBL(craftedVB(intTLV(5))))))
assert.EqualError(t, err, tc.wantErr)
assert.Nil(t, p)
})
}
}

// 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
Expand Down Expand Up @@ -175,7 +153,7 @@ func TestDecodeUSMFields(t *testing.T) {
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
_, err := (&Client{}).DecodeMessage(tc.in)
_, err := mustClient(Config{}).DecodeMessage(tc.in)
if tc.invalid {
assert.ErrorIs(t, err, ErrASNParse)
} else {
Expand All @@ -200,10 +178,10 @@ func TestUnknownPDUTypeError(t *testing.T) {
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
_, err := (&Client{Version: Version2c}).DecodeMessage(craftedMsg(1, pdu(tc.tag)))
_, err := mustClient(Config{Version: Version2c}).DecodeMessage(craftedMsg(1, pdu(tc.tag)))
assert.EqualError(t, err, "unable to decode packet body: "+tc.want, "SNMPv2c")

v3 := &Client{Version: Version3, User: User{Name: "codec-user"}}
v3 := mustClient(Config{Version: Version3, User: User{Name: "codec-user"}})
_, err = v3.DecodeMessage(craftedV3NoAuth(tlv(0x30, craftedEngineID, octets("ctx"), pdu(tc.tag))))
assert.EqualError(t, err, "unable to decode packet body: "+tc.want, "SNMPv3")

Expand Down
4 changes: 2 additions & 2 deletions codec_fuzz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func FuzzDecodeReencode(f *testing.F) {
}

f.Fuzz(func(t *testing.T, data []byte) {
first, err := (&Client{}).DecodeMessage(bytes.Clone(data))
first, err := mustClient(Config{}).DecodeMessage(bytes.Clone(data))
if err != nil {
return
}
Expand All @@ -107,7 +107,7 @@ func FuzzDecodeReencode(f *testing.F) {
t.Fatalf("decoded packet does not encode: %v\ninput: %x", err, data)
}

second, err := (&Client{}).DecodeMessage(bytes.Clone(encoded))
second, err := mustClient(Config{}).DecodeMessage(bytes.Clone(encoded))
if err != nil {
t.Fatalf("re-encoded packet does not decode: %v\ninput: %x\nre-encoded: %x", err, data, encoded)
}
Expand Down
49 changes: 23 additions & 26 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,23 @@
//
// # Lifecycle
//
// A client is a [Client] whose exported fields configure it. The package
// [NewClient] makes a [Client] from a [Config]: it checks the configuration,
// fills in its defaults (Port 161, Timeout 1 s, [MaxOids]) and fails with an
// error naming the field it rejects, such as a negative Retries or an SNMPv3
// user the security level does not fit. The client keeps the configuration as
// it is: nothing changes it, and the client does not show it. The package
// declares no interface of the client for tests to mock: code that mocks it
// declares one of its own with the methods it calls. [Client.Connect] fills in
// the default [MaxOids], checks the SNMPv3 configuration and opens the client's
// connection, a UDP socket connected to Target and Port, which replaces the one
// it had (a failed Connect keeps it). The client has no other connection: a
// request before its first successful Connect fails before it sends anything,
// with an error that says so. The client
// owns its connection: [Client.Close] closes it, and so does a Connect that
// replaces it. Connect may be called again after Close. A request reads the
// client's configuration when it starts and does not change it: a change the
// caller makes during a request applies from the next one, but the SNMPv3
// engine state the client learns during a request serves the rest of it (see
// SNMPv3). A request resolves no name: Connect looks up Target, and a request
// writes to the peer of the socket Connect opened. The request IDs and msgIDs
// start at a random value on first use unless [Client.SetRequestID] and
// [Client.SetMsgID] set them, and Connect does not reset them.
// declares one of its own with the methods it calls. [Client.Connect] opens the
// client's connection, a UDP socket connected to Target and Port, which
// replaces the one it had (a failed Connect keeps it); an empty Target fails
// it, and a client that only encodes and decodes messages needs neither. The
// client has no other connection: a request before its first successful
// Connect fails before it sends anything, with an error that says so. The
// client owns its connection: [Client.Close] closes it, and so does a Connect
// that replaces it. Connect may be called again after Close. A request
// resolves no name: Connect looks up Target, and a request writes to the peer
// of the socket Connect opened. The request IDs and msgIDs start at random
// values NewClient draws, and Connect does not reset them.
//
// Connect, Get and the walks take a context first, which bounds that call
// only: Connect's lookup of Target and its dial, not the connection; each
Expand Down Expand Up @@ -120,8 +120,7 @@
// ID nor a 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
// (a protocol without a passphrase; FIPS 140-only mode refuses MD5 and SHA-1)
// end the request with the derivation's error, before any discovery.
// (FIPS 140-only mode refuses MD5 and SHA-1) fail NewClient.
//
// 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
Expand All @@ -133,11 +132,8 @@
// authentication carries the clock's values (as net-snmp; RFC 3414 section 3.1
// step 6 c sends zeros).
//
// A request takes the configuration into the engine state at its start: another
// User, set since the last request started, keeps the engine ID and clock and
// derives its keys for the engine ID. [Client.ForgetEngine] makes the next
// request start over and discover the engine again; a request that is running
// keeps the state it has.
// [Client.ForgetEngine] makes the next request start over and discover the
// engine again; a request that is running keeps the state it has.
//
// A reply whose msgID names none of the request's attempts is discarded before
// security processing. A reply then goes through the security processing of RFC
Expand Down Expand Up @@ -340,9 +336,10 @@
// 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 when its
// engine state takes an engine ID (discovery, an answer it takes, a Report lent
// to a resend) or another User; decoding a reply derives none.
// 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 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 authentication, the privacy key
// only to decrypt it. A [Receiver] derives its users' keys for their engine IDs
Expand Down
Loading
Loading