-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
snmp.go
295 lines (259 loc) · 11 KB
/
snmp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2020-present Datadog, Inc.
package snmp
import (
"errors"
"fmt"
"hash/fnv"
"net"
"sort"
"strconv"
"time"
"github.com/gosnmp/gosnmp"
pkgconfigsetup "github.com/DataDog/datadog-agent/pkg/config/setup"
"github.com/DataDog/datadog-agent/pkg/config/structure"
"github.com/DataDog/datadog-agent/pkg/snmp/gosnmplib"
"github.com/DataDog/datadog-agent/pkg/snmp/snmpintegration"
)
const (
defaultPort = 161
defaultTimeout = 5
defaultRetries = 3
)
// ListenerConfig holds global configuration for SNMP discovery
type ListenerConfig struct {
Workers int `mapstructure:"workers"`
DiscoveryInterval int `mapstructure:"discovery_interval"`
AllowedFailures int `mapstructure:"discovery_allowed_failures"`
Loader string `mapstructure:"loader"`
CollectDeviceMetadata bool `mapstructure:"collect_device_metadata"`
CollectTopology bool `mapstructure:"collect_topology"`
MinCollectionInterval uint `mapstructure:"min_collection_interval"`
Namespace string `mapstructure:"namespace"`
UseDeviceISAsHostname bool `mapstructure:"use_device_id_as_hostname"`
Configs []Config `mapstructure:"configs"`
PingConfig snmpintegration.PingConfig `mapstructure:"ping"`
// legacy
AllowedFailuresLegacy int `mapstructure:"allowed_failures"`
}
// Config holds configuration for a particular subnet
type Config struct {
Network string `mapstructure:"network_address"`
Port uint16 `mapstructure:"port"`
Version string `mapstructure:"snmp_version"`
Timeout int `mapstructure:"timeout"`
Retries int `mapstructure:"retries"`
OidBatchSize int `mapstructure:"oid_batch_size"`
Community string `mapstructure:"community_string"`
User string `mapstructure:"user"`
AuthKey string `mapstructure:"authKey"`
AuthProtocol string `mapstructure:"authProtocol"`
PrivKey string `mapstructure:"privKey"`
PrivProtocol string `mapstructure:"privProtocol"`
ContextEngineID string `mapstructure:"context_engine_id"`
ContextName string `mapstructure:"context_name"`
IgnoredIPAddresses map[string]bool `mapstructure:"ignored_ip_addresses"`
ADIdentifier string `mapstructure:"ad_identifier"`
Loader string `mapstructure:"loader"`
CollectDeviceMetadataConfig *bool `mapstructure:"collect_device_metadata"`
CollectDeviceMetadata bool
CollectTopologyConfig *bool `mapstructure:"collect_topology"`
CollectTopology bool
UseDeviceIDAsHostnameConfig *bool `mapstructure:"use_device_id_as_hostname"`
UseDeviceIDAsHostname bool
Namespace string `mapstructure:"namespace"`
Tags []string `mapstructure:"tags"`
MinCollectionInterval uint `mapstructure:"min_collection_interval"`
// InterfaceConfigs is a map of IP to a list of snmpintegration.InterfaceConfig
InterfaceConfigs map[string][]snmpintegration.InterfaceConfig `mapstructure:"interface_configs"`
PingConfig snmpintegration.PingConfig `mapstructure:"ping"`
// Legacy
NetworkLegacy string `mapstructure:"network"`
VersionLegacy string `mapstructure:"version"`
CommunityLegacy string `mapstructure:"community"`
AuthKeyLegacy string `mapstructure:"authentication_key"`
AuthProtocolLegacy string `mapstructure:"authentication_protocol"`
PrivKeyLegacy string `mapstructure:"privacy_key"`
PrivProtocolLegacy string `mapstructure:"privacy_protocol"`
}
type intOrBoolPtr interface {
*int | *bool
}
// ErrNoConfigGiven is returned when the SNMP listener config was not found
var ErrNoConfigGiven = errors.New("no config given for snmp_listener")
// NewListenerConfig parses configuration and returns a built ListenerConfig
func NewListenerConfig() (ListenerConfig, error) {
var snmpConfig ListenerConfig
// Set defaults before unmarshalling
snmpConfig.CollectDeviceMetadata = true
snmpConfig.CollectTopology = true
ddcfg := pkgconfigsetup.Datadog()
if ddcfg.IsSet("network_devices.autodiscovery") {
err := structure.UnmarshalKey(ddcfg, "network_devices.autodiscovery", &snmpConfig, structure.ImplicitlyConvertArrayToMapSet)
if err != nil {
return snmpConfig, err
}
} else if ddcfg.IsSet("snmp_listener") {
err := structure.UnmarshalKey(ddcfg, "snmp_listener", &snmpConfig, structure.ImplicitlyConvertArrayToMapSet)
if err != nil {
return snmpConfig, err
}
} else {
return snmpConfig, ErrNoConfigGiven
}
if snmpConfig.AllowedFailures == 0 && snmpConfig.AllowedFailuresLegacy != 0 {
snmpConfig.AllowedFailures = snmpConfig.AllowedFailuresLegacy
}
// Set the default values, we can't otherwise on an array
for i := range snmpConfig.Configs {
// We need to modify the struct in place
config := &snmpConfig.Configs[i]
if config.Port == 0 {
config.Port = defaultPort
}
if config.Timeout == 0 {
config.Timeout = defaultTimeout
}
if config.Retries == 0 {
config.Retries = defaultRetries
}
if config.CollectDeviceMetadataConfig != nil {
config.CollectDeviceMetadata = *config.CollectDeviceMetadataConfig
} else {
config.CollectDeviceMetadata = snmpConfig.CollectDeviceMetadata
}
if config.CollectTopologyConfig != nil {
config.CollectTopology = *config.CollectTopologyConfig
} else {
config.CollectTopology = snmpConfig.CollectTopology
}
if config.UseDeviceIDAsHostnameConfig != nil {
config.UseDeviceIDAsHostname = *config.UseDeviceIDAsHostnameConfig
} else {
config.UseDeviceIDAsHostname = snmpConfig.UseDeviceISAsHostname
}
if config.Loader == "" {
config.Loader = snmpConfig.Loader
}
if config.MinCollectionInterval == 0 {
config.MinCollectionInterval = snmpConfig.MinCollectionInterval
}
// Ping config
config.PingConfig.Enabled = firstNonNil(config.PingConfig.Enabled, snmpConfig.PingConfig.Enabled)
config.PingConfig.Linux.UseRawSocket = firstNonNil(config.PingConfig.Linux.UseRawSocket, snmpConfig.PingConfig.Linux.UseRawSocket)
config.PingConfig.Interval = firstNonNil(config.PingConfig.Interval, snmpConfig.PingConfig.Interval)
config.PingConfig.Timeout = firstNonNil(config.PingConfig.Timeout, snmpConfig.PingConfig.Timeout)
config.PingConfig.Count = firstNonNil(config.PingConfig.Count, snmpConfig.PingConfig.Count)
config.Namespace = firstNonEmpty(config.Namespace, snmpConfig.Namespace, pkgconfigsetup.Datadog().GetString("network_devices.namespace"))
config.Community = firstNonEmpty(config.Community, config.CommunityLegacy)
config.AuthKey = firstNonEmpty(config.AuthKey, config.AuthKeyLegacy)
config.AuthProtocol = firstNonEmpty(config.AuthProtocol, config.AuthProtocolLegacy)
config.PrivKey = firstNonEmpty(config.PrivKey, config.PrivKeyLegacy)
config.PrivProtocol = firstNonEmpty(config.PrivProtocol, config.PrivProtocolLegacy)
config.Network = firstNonEmpty(config.Network, config.NetworkLegacy)
config.Version = firstNonEmpty(config.Version, config.VersionLegacy)
}
return snmpConfig, nil
}
// Digest returns an hash value representing the data stored in this configuration, minus the network address
func (c *Config) Digest(address string) string {
h := fnv.New64()
// Hash write never returns an error
h.Write([]byte(address)) //nolint:errcheck
h.Write([]byte(fmt.Sprintf("%d", c.Port))) //nolint:errcheck
h.Write([]byte(c.Version)) //nolint:errcheck
h.Write([]byte(c.Community)) //nolint:errcheck
h.Write([]byte(c.User)) //nolint:errcheck
h.Write([]byte(c.AuthKey)) //nolint:errcheck
h.Write([]byte(c.AuthProtocol)) //nolint:errcheck
h.Write([]byte(c.PrivKey)) //nolint:errcheck
h.Write([]byte(c.PrivProtocol)) //nolint:errcheck
h.Write([]byte(c.ContextEngineID)) //nolint:errcheck
h.Write([]byte(c.ContextName)) //nolint:errcheck
h.Write([]byte(c.Loader)) //nolint:errcheck
h.Write([]byte(c.Namespace)) //nolint:errcheck
// Sort the addresses to get a stable digest
addresses := make([]string, 0, len(c.IgnoredIPAddresses))
for ip := range c.IgnoredIPAddresses {
addresses = append(addresses, ip)
}
sort.Strings(addresses)
for _, ip := range addresses {
h.Write([]byte(ip)) //nolint:errcheck
}
return strconv.FormatUint(h.Sum64(), 16)
}
// BuildSNMPParams returns a valid GoSNMP struct to start making queries
func (c *Config) BuildSNMPParams(deviceIP string) (*gosnmp.GoSNMP, error) {
if c.Community == "" && c.User == "" {
return nil, errors.New("No authentication mechanism specified")
}
var version gosnmp.SnmpVersion
if c.Version == "1" {
version = gosnmp.Version1
} else if c.Version == "2" || (c.Version == "" && c.Community != "") {
version = gosnmp.Version2c
} else if c.Version == "3" || (c.Version == "" && c.User != "") {
version = gosnmp.Version3
} else {
return nil, fmt.Errorf("SNMP version not supported: %s", c.Version)
}
authProtocol, err := gosnmplib.GetAuthProtocol(c.AuthProtocol)
if err != nil {
return nil, err
}
privProtocol, err := gosnmplib.GetPrivProtocol(c.PrivProtocol)
if err != nil {
return nil, err
}
msgFlags := gosnmp.NoAuthNoPriv
if c.PrivKey != "" {
msgFlags = gosnmp.AuthPriv
} else if c.AuthKey != "" {
msgFlags = gosnmp.AuthNoPriv
}
return &gosnmp.GoSNMP{
Target: deviceIP,
Port: c.Port,
Community: c.Community,
Transport: "udp",
Version: version,
Timeout: time.Duration(c.Timeout) * time.Second,
Retries: c.Retries,
SecurityModel: gosnmp.UserSecurityModel,
MsgFlags: msgFlags,
ContextEngineID: c.ContextEngineID,
ContextName: c.ContextName,
SecurityParameters: &gosnmp.UsmSecurityParameters{
UserName: c.User,
AuthenticationProtocol: authProtocol,
AuthenticationPassphrase: c.AuthKey,
PrivacyProtocol: privProtocol,
PrivacyPassphrase: c.PrivKey,
},
}, nil
}
// IsIPIgnored checks the given IP against IgnoredIPAddresses
func (c *Config) IsIPIgnored(ip net.IP) bool {
ipString := ip.String()
_, present := c.IgnoredIPAddresses[ipString]
return present
}
func firstNonEmpty(strings ...string) string {
for index, s := range strings {
if s != "" || index == len(strings)-1 {
return s
}
}
return ""
}
func firstNonNil[T intOrBoolPtr](params ...T) T {
for _, p := range params {
if p != nil {
return p
}
}
return nil
}