forked from slayercat/GoSNMPServer
/
agentcontrol.go
310 lines (269 loc) · 8.76 KB
/
agentcontrol.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package GoSNMPServer
import (
"reflect"
"strings"
"time"
"github.com/pkg/errors"
"github.com/shirou/gopsutil/host"
"github.com/slayercat/gosnmp"
)
type FuncGetAuthoritativeEngineTime func() uint32
//MasterAgent identifys software which runs on managed devices
// One server (port) could ONLY have one MasterAgent
type MasterAgent struct {
SecurityConfig SecurityConfig
SubAgents []*SubAgent
Logger ILogger
priv struct {
communityToSubAgent map[string]*SubAgent
defaultSubAgent *SubAgent
}
}
type SecurityConfig struct {
NoSecurity bool
// AuthoritativeEngineID is SNMPV3 AuthoritativeEngineID
AuthoritativeEngineID SNMPEngineID
// AuthoritativeEngineBoots is SNMPV3 AuthoritativeEngineBoots
AuthoritativeEngineBoots uint32
// OnGetAuthoritativeEngineTime will be called to get SNMPV3 AuthoritativeEngineTime
// if sets to nil, the sys boottime will be used
OnGetAuthoritativeEngineTime FuncGetAuthoritativeEngineTime
Users []gosnmp.UsmSecurityParameters
}
func (v *SecurityConfig) FindForUser(name string) *gosnmp.UsmSecurityParameters {
if v.Users == nil {
return nil
}
for item, user := range v.Users {
if user.UserName == name {
return &v.Users[item]
}
}
return nil
}
type SNMPEngineID struct {
// See https://tools.ietf.org/html/rfc3411#section-5
// SnmpEngineID ::= TEXTUAL-CONVENTION
// SYNTAX OCTET STRING (SIZE(5..32))
EngineIDData string
}
func (t *SNMPEngineID) Marshal() []byte {
// msgAuthoritativeEngineID: 80004fb8054445534b544f502d4a3732533245343ab63bc8
// 1... .... = Engine ID Conformance: RFC3411 (SNMPv3)
// Engine Enterprise ID: pysnmp (20408)
// Engine ID Format: Octets, administratively assigned (5)
// Engine ID Data: 4445534b544f502d4a3732533245343ab63bc8
var tm = []byte{
0x80, 0x00, 0x4f, 0xb8, 0x05,
}
toAppend := []byte(t.EngineIDData)
maxDefineallowed := 32 - 5
if len(toAppend) > maxDefineallowed { //Max 32 bytes
toAppend = toAppend[:maxDefineallowed]
}
tm = append(tm, toAppend...)
return tm
}
func (t *MasterAgent) syncAndCheck() error {
if len(t.SubAgents) == 0 {
return errors.WithStack(errors.Errorf("MasterAgent shell have at least one SubAgents"))
}
if t.SecurityConfig.NoSecurity && len(t.SubAgents) != 1 {
return errors.WithStack(errors.Errorf("NoSecurity MasterAgent shell have one one SubAgent"))
}
if t.Logger == nil {
//Set New NIL Logger
t.Logger = NewDiscardLogger()
}
if t.SecurityConfig.OnGetAuthoritativeEngineTime == nil {
t.SecurityConfig.OnGetAuthoritativeEngineTime = DefaultGetAuthoritativeEngineTime
}
if t.SecurityConfig.AuthoritativeEngineID.EngineIDData == "" {
t.SecurityConfig.AuthoritativeEngineID = DefaultAuthoritativeEngineID()
}
return nil
}
func (t *MasterAgent) ReadyForWork() error {
if err := t.syncAndCheck(); err != nil {
return err
}
return t.SyncConfig()
}
func (t *MasterAgent) getUserNameFromRequest(request *gosnmp.SnmpPacket) string {
var username string
if val, ok := request.SecurityParameters.(*gosnmp.UsmSecurityParameters); !ok {
panic(errors.WithMessagef(ErrUnsupportedPacketData, "GoSNMP .Unknown Type:%v", reflect.TypeOf(request.SecurityParameters)))
} else {
username = val.UserName
}
return username
}
func (t *MasterAgent) ResponseForBuffer(i []byte) ([]byte, error) {
// Decode
vhandle := gosnmp.GoSNMP{}
vhandle.Logger = &SnmpLoggerAdapter{t.Logger}
mb, _ := t.getUsmSecurityParametersFromUser("")
vhandle.SecurityParameters = mb
request, decodeError := vhandle.SnmpDecodePacket(i)
switch request.Version {
case gosnmp.Version1, gosnmp.Version2c:
return t.marshalPkt(t.ResponseForPkt(request))
//
case gosnmp.Version3:
// check for initial - discover response / non Privacy Items
if decodeError == nil && len(request.Variables) == 0 {
val, err := t.ResponseForPkt(request)
if val == nil {
return t.marshalPkt(request, err)
} else {
return t.marshalPkt(val, err)
}
}
//v3 might want for Privacy
if request.SecurityParameters == nil {
return nil, errors.WithMessagef(ErrUnsupportedPacketData, "GoSNMP Returns %v", decodeError)
}
username := t.getUserNameFromRequest(request)
usm, err := t.getUsmSecurityParametersFromUser(username)
if err != nil {
return nil, err
}
if decodeError != nil {
t.Logger.Debugf("v3 decode [will fail with non password] meet %v", err)
vhandle.SecurityParameters = &gosnmp.UsmSecurityParameters{
UserName: usm.UserName,
AuthenticationProtocol: usm.AuthenticationProtocol,
PrivacyProtocol: usm.PrivacyProtocol,
AuthenticationPassphrase: usm.AuthenticationPassphrase,
PrivacyPassphrase: usm.PrivacyPassphrase,
Logger: vhandle.Logger,
}
request, err = vhandle.SnmpDecodePacket(i)
if err != nil {
return nil, errors.WithMessagef(ErrUnsupportedPacketData, "GoSNMP Returns %v", err)
}
}
val, err := t.ResponseForPkt(request)
if val == nil {
request.SecurityParameters = vhandle.SecurityParameters
return t.marshalPkt(request, err)
} else {
securityParamters := usm
securityParamters.GenKeys()
securityParamters.GenSalt()
val.SecurityParameters = securityParamters
return t.marshalPkt(val, err)
}
}
return nil, errors.WithStack(ErrUnsupportedProtoVersion)
}
func (t *MasterAgent) marshalPkt(pkt *gosnmp.SnmpPacket, err error) ([]byte, error) {
// when err. marshal error pkt
if pkt == nil {
pkt = &gosnmp.SnmpPacket{}
}
if err != nil {
t.Logger.Debugf("Will marshal: %v", err)
errFill := t.fillErrorPkt(err, pkt)
if errFill != nil {
return nil, err
}
return pkt.MarshalMsg()
}
out, err := pkt.MarshalMsg()
return out, err
}
func (t *MasterAgent) getUsmSecurityParametersFromUser(username string) (*gosnmp.UsmSecurityParameters, error) {
if username == "" {
return &gosnmp.UsmSecurityParameters{
Logger: &SnmpLoggerAdapter{t.Logger},
AuthoritativeEngineID: string(t.SecurityConfig.AuthoritativeEngineID.Marshal()),
AuthoritativeEngineBoots: t.SecurityConfig.AuthoritativeEngineBoots,
AuthoritativeEngineTime: t.SecurityConfig.OnGetAuthoritativeEngineTime(),
}, nil
}
if val := t.SecurityConfig.FindForUser(username); val != nil {
fval := val.Copy().(*gosnmp.UsmSecurityParameters)
fval.Logger = &SnmpLoggerAdapter{t.Logger}
fval.AuthoritativeEngineID = string(t.SecurityConfig.AuthoritativeEngineID.Marshal())
fval.AuthoritativeEngineBoots = t.SecurityConfig.AuthoritativeEngineBoots
fval.AuthoritativeEngineTime = t.SecurityConfig.OnGetAuthoritativeEngineTime()
return fval, nil
} else {
return nil, errors.WithStack(ErrNoPermission)
}
}
func (t *MasterAgent) fillErrorPkt(err error, io *gosnmp.SnmpPacket) error {
io.PDUType = gosnmp.GetResponse
if errors.Is(err, ErrNoSNMPInstance) {
io.Error = gosnmp.NoAccess
} else if errors.Is(err, ErrUnsupportedOperation) {
io.Error = gosnmp.ResourceUnavailable
} else if errors.Is(err, ErrNoPermission) {
io.Error = gosnmp.AuthorizationError
} else if errors.Is(err, ErrUnsupportedPacketData) {
io.Error = gosnmp.BadValue
} else {
io.Error = gosnmp.GenErr
}
io.ErrorIndex = 0
return nil
}
func (t *MasterAgent) ResponseForPkt(i *gosnmp.SnmpPacket) (*gosnmp.SnmpPacket, error) {
// Find for which SubAgent
community := getPktContextOrCommunity(i)
subAgent := t.findForSubAgent(community)
if subAgent == nil {
return i, errors.WithStack(ErrNoSNMPInstance)
}
return subAgent.Serve(i)
}
func (t *MasterAgent) SyncConfig() error {
t.priv.defaultSubAgent = nil
t.priv.communityToSubAgent = make(map[string]*SubAgent)
for id, current := range t.SubAgents {
t.SubAgents[id].Logger = t.Logger
t.SubAgents[id].master = t
if err := t.SubAgents[id].SyncConfig(); err != nil {
return err
}
if len(current.CommunityIDs) == 0 || t.SecurityConfig.NoSecurity {
if t.priv.defaultSubAgent != nil {
return errors.Errorf("SyncConfig: Config Error: duplicate default agent")
}
t.priv.defaultSubAgent = current
continue
}
for _, val := range current.CommunityIDs {
if _, exists := t.priv.communityToSubAgent[val]; exists {
return errors.Errorf("SyncConfig: Config Error: duplicate value:%s", val)
}
t.Logger.Debugf("communityToSubAgent: val=%v, current=%p", val, current)
t.priv.communityToSubAgent[val] = current
}
}
return nil
}
func (t *MasterAgent) findForSubAgent(community string) *SubAgent {
t.Logger.Infof("findForSubAgent(%s)", community)
if val, ok := t.priv.communityToSubAgent[community]; ok {
return val
} else {
return t.priv.defaultSubAgent
}
}
func DefaultAuthoritativeEngineID() SNMPEngineID {
// XXX:TODO: return random
val, _ := host.Info()
data := strings.Replace(val.HostID, "-", "", -1)
return SNMPEngineID{
EngineIDData: data,
}
}
func DefaultGetAuthoritativeEngineTime() uint32 {
val, err := host.Uptime()
if err != nil {
return uint32(time.Now().Unix())
}
return uint32(val)
}