forked from gosnmp/gosnmp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
v3.go
504 lines (430 loc) · 14.5 KB
/
v3.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
// Copyright 2012 The GoSNMP Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gosnmp
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"runtime"
)
// SnmpV3MsgFlags contains various message flags to describe Authentication, Privacy, and whether a report PDU must be sent.
type SnmpV3MsgFlags uint8
// Possible values of SnmpV3MsgFlags
const (
NoAuthNoPriv SnmpV3MsgFlags = 0x0 // No authentication, and no privacy
AuthNoPriv SnmpV3MsgFlags = 0x1 // Authentication and no privacy
AuthPriv SnmpV3MsgFlags = 0x3 // Authentication and privacy
Reportable SnmpV3MsgFlags = 0x4 // Report PDU must be sent.
)
//go:generate stringer -type=SnmpV3MsgFlags
// SnmpV3SecurityModel describes the security model used by a SnmpV3 connection
type SnmpV3SecurityModel uint8
// UserSecurityModel is the only SnmpV3SecurityModel currently implemented.
const (
UserSecurityModel SnmpV3SecurityModel = 3
)
//go:generate stringer -type=SnmpV3SecurityModel
// SnmpV3SecurityParameters is a generic interface type to contain various implementations of SnmpV3SecurityParameters
type SnmpV3SecurityParameters interface {
Log()
Copy() SnmpV3SecurityParameters
Description() string
SafeString() string
InitPacket(packet *SnmpPacket) error
InitSecurityKeys() error
validate(flags SnmpV3MsgFlags) error
init(log Logger) error
discoveryRequired() *SnmpPacket
getDefaultContextEngineID() string
setSecurityParameters(in SnmpV3SecurityParameters) error
marshal(flags SnmpV3MsgFlags) ([]byte, error)
unmarshal(flags SnmpV3MsgFlags, packet []byte, cursor int) (int, error)
authenticate(packet []byte) error
isAuthentic(packetBytes []byte, packet *SnmpPacket) (bool, error)
encryptPacket(scopedPdu []byte) ([]byte, error)
decryptPacket(packet []byte, cursor int) ([]byte, error)
}
func (x *GoSNMP) validateParametersV3() error {
// update following code if you implement a new security model
if x.SecurityModel != UserSecurityModel {
return errors.New("the SNMPV3 User Security Model is the only SNMPV3 security model currently implemented")
}
if x.SecurityParameters == nil {
return errors.New("SNMPV3 SecurityParameters must be set")
}
return x.SecurityParameters.validate(x.MsgFlags)
}
// authenticate the marshalled result of a snmp version 3 packet
func (packet *SnmpPacket) authenticate(msg []byte) ([]byte, error) {
defer func() {
if e := recover(); e != nil {
var buf = make([]byte, 8192)
runtime.Stack(buf, true)
fmt.Printf("[v3::authenticate]recover: %v. Stack=%v\n", e, string(buf))
}
}()
if packet.Version != Version3 {
return msg, nil
}
if packet.MsgFlags&AuthNoPriv > 0 {
err := packet.SecurityParameters.authenticate(msg)
if err != nil {
return nil, err
}
}
return msg, nil
}
func (x *GoSNMP) testAuthentication(packet []byte, result *SnmpPacket, useResponseSecurityParameters bool) error {
if x.Version != Version3 {
return fmt.Errorf("testAuthentication called with non Version3 connection")
}
msgFlags := x.MsgFlags
if useResponseSecurityParameters {
msgFlags = result.MsgFlags
}
if msgFlags&AuthNoPriv > 0 {
var authentic bool
var err error
if useResponseSecurityParameters {
authentic, err = result.SecurityParameters.isAuthentic(packet, result)
} else {
authentic, err = x.SecurityParameters.isAuthentic(packet, result)
}
if err != nil {
return err
}
if !authentic {
return fmt.Errorf("incoming packet is not authentic, discarding")
}
}
return nil
}
func (x *GoSNMP) initPacket(packetOut *SnmpPacket) error {
if x.MsgFlags&AuthPriv > AuthNoPriv {
return x.SecurityParameters.InitPacket(packetOut)
}
return nil
}
// http://tools.ietf.org/html/rfc2574#section-2.2.3 This code does not
// check if the last message received was more than 150 seconds ago The
// snmpds that this code was tested on emit an 'out of time window'
// error with the new time and this code will retransmit when that is
// received.
func (x *GoSNMP) negotiateInitialSecurityParameters(packetOut *SnmpPacket) error {
if x.Version != Version3 || packetOut.Version != Version3 {
return fmt.Errorf("negotiateInitialSecurityParameters called with non Version3 connection or packet")
}
if x.SecurityModel != packetOut.SecurityModel {
return fmt.Errorf("connection security model does not match security model defined in packet")
}
if discoveryPacket := packetOut.SecurityParameters.discoveryRequired(); discoveryPacket != nil {
discoveryPacket.ContextName = x.ContextName
result, err := x.sendOneRequest(discoveryPacket, true)
if err != nil {
return err
}
err = x.storeSecurityParameters(result)
if err != nil {
return err
}
err = x.updatePktSecurityParameters(packetOut)
if err != nil {
return err
}
} else {
err := packetOut.SecurityParameters.InitSecurityKeys()
if err == nil {
return err
}
}
return nil
}
// save the connection security parameters after a request/response
func (x *GoSNMP) storeSecurityParameters(result *SnmpPacket) error {
if x.Version != Version3 || result.Version != Version3 {
return fmt.Errorf("storeParameters called with non Version3 connection or packet")
}
if x.SecurityModel != result.SecurityModel {
return fmt.Errorf("connection security model does not match security model extracted from packet")
}
if x.ContextEngineID == "" {
x.ContextEngineID = result.SecurityParameters.getDefaultContextEngineID()
}
return x.SecurityParameters.setSecurityParameters(result.SecurityParameters)
}
// update packet security parameters to match connection security parameters
func (x *GoSNMP) updatePktSecurityParameters(packetOut *SnmpPacket) error {
if x.Version != Version3 || packetOut.Version != Version3 {
return fmt.Errorf("updatePktSecurityParameters called with non Version3 connection or packet")
}
if x.SecurityModel != packetOut.SecurityModel {
return fmt.Errorf("connection security model does not match security model extracted from packet")
}
err := packetOut.SecurityParameters.setSecurityParameters(x.SecurityParameters)
if err != nil {
return err
}
if packetOut.ContextEngineID == "" {
packetOut.ContextEngineID = x.ContextEngineID
}
return nil
}
func (packet *SnmpPacket) marshalV3(buf *bytes.Buffer) (*bytes.Buffer, error) { //nolint:interfacer
emptyBuffer := new(bytes.Buffer) // used when returning errors
header, err := packet.marshalV3Header()
if err != nil {
return emptyBuffer, err
}
buf.Write([]byte{byte(Sequence), byte(len(header))})
packet.Logger.Printf("Marshal V3 Header len=%d. Eaten Last 4 Bytes=%v", len(header), header[len(header)-4:])
buf.Write(header)
var securityParameters []byte
securityParameters, err = packet.SecurityParameters.marshal(packet.MsgFlags)
if err != nil {
return emptyBuffer, err
}
packet.Logger.Printf("Marshal V3 SecurityParameters len=%d. Eaten Last 4 Bytes=%v",
len(securityParameters), securityParameters[len(securityParameters)-4:])
buf.Write([]byte{byte(OctetString)})
secParamLen, err := marshalLength(len(securityParameters))
if err != nil {
return emptyBuffer, err
}
buf.Write(secParamLen)
buf.Write(securityParameters)
scopedPdu, err := packet.marshalV3ScopedPDU()
if err != nil {
return emptyBuffer, err
}
buf.Write(scopedPdu)
return buf, nil
}
// marshal a snmp version 3 packet header
func (packet *SnmpPacket) marshalV3Header() ([]byte, error) {
buf := new(bytes.Buffer)
// msg id
buf.Write([]byte{byte(Integer), 4})
err := binary.Write(buf, binary.BigEndian, packet.MsgID)
if err != nil {
return nil, err
}
oldLen := 0
packet.Logger.Printf("MarshalV3Header msgID len=%v", buf.Len()-oldLen)
oldLen = buf.Len()
// maximum response msg size
var maxBufSize uint32 = rxBufSize
if packet.MsgMaxSize != 0 {
maxBufSize = packet.MsgMaxSize
}
maxmsgsize, err := marshalUint32(maxBufSize)
if err != nil {
return nil, err
}
buf.Write([]byte{byte(Integer), byte(len(maxmsgsize))})
buf.Write(maxmsgsize)
packet.Logger.Printf("MarshalV3Header maxmsgsize len=%v", buf.Len()-oldLen)
oldLen = buf.Len()
// msg flags
buf.Write([]byte{byte(OctetString), 1, byte(packet.MsgFlags)})
packet.Logger.Printf("MarshalV3Header msg flags len=%v", buf.Len()-oldLen)
oldLen = buf.Len()
// msg security model
buf.Write([]byte{byte(Integer), 1, byte(packet.SecurityModel)})
packet.Logger.Printf("MarshalV3Header msg security model len=%v", buf.Len()-oldLen)
return buf.Bytes(), nil
}
// marshal and encrypt (if necessary) a snmp version 3 Scoped PDU
func (packet *SnmpPacket) marshalV3ScopedPDU() ([]byte, error) {
var b []byte
scopedPdu, err := packet.prepareV3ScopedPDU()
if err != nil {
return nil, err
}
pduLen, err := marshalLength(len(scopedPdu))
if err != nil {
return nil, err
}
b = append([]byte{byte(Sequence)}, pduLen...)
scopedPdu = append(b, scopedPdu...)
if packet.MsgFlags&AuthPriv > AuthNoPriv {
scopedPdu, err = packet.SecurityParameters.encryptPacket(scopedPdu)
if err != nil {
return nil, err
}
}
return scopedPdu, nil
}
// prepare the plain text of a snmp version 3 Scoped PDU
func (packet *SnmpPacket) prepareV3ScopedPDU() ([]byte, error) {
var buf bytes.Buffer
// ContextEngineID
idlen, err := marshalLength(len(packet.ContextEngineID))
if err != nil {
return nil, err
}
buf.Write(append([]byte{byte(OctetString)}, idlen...))
buf.WriteString(packet.ContextEngineID)
// ContextName
namelen, err := marshalLength(len(packet.ContextName))
if err != nil {
return nil, err
}
buf.Write(append([]byte{byte(OctetString)}, namelen...))
buf.WriteString(packet.ContextName)
data, err := packet.marshalPDU()
if err != nil {
return nil, err
}
buf.Write(data)
return buf.Bytes(), nil
}
func (x *GoSNMP) unmarshalV3Header(packet []byte,
cursor int,
response *SnmpPacket) (int, error) {
if PDUType(packet[cursor]) != Sequence {
return 0, fmt.Errorf("invalid SNMPV3 Header")
}
_, cursorTmp, err := parseLength(packet[cursor:])
if err != nil {
return 0, err
}
cursor += cursorTmp
if cursor > len(packet) {
return 0, errors.New("error parsing SNMPV3 message ID: truncted packet")
}
rawMsgID, count, err := parseRawField(x.Logger, packet[cursor:], "msgID")
if err != nil {
return 0, fmt.Errorf("error parsing SNMPV3 message ID: %w", err)
}
cursor += count
if cursor > len(packet) {
return 0, errors.New("error parsing SNMPV3 message ID: truncted packet")
}
if MsgID, ok := rawMsgID.(int); ok {
response.MsgID = uint32(MsgID)
x.Logger.Printf("Parsed message ID %d", MsgID)
}
rawMsgMaxSize, count, err := parseRawField(x.Logger, packet[cursor:], "msgMaxSize")
if err != nil {
return 0, fmt.Errorf("error parsing SNMPV3 msgMaxSize: %w", err)
}
cursor += count
if cursor > len(packet) {
return 0, errors.New("error parsing SNMPV3 message ID: truncted packet")
}
if MsgMaxSize, ok := rawMsgMaxSize.(int); ok {
response.MsgMaxSize = uint32(MsgMaxSize)
x.Logger.Printf("Parsed message max size %d", MsgMaxSize)
}
rawMsgFlags, count, err := parseRawField(x.Logger, packet[cursor:], "msgFlags")
if err != nil {
return 0, fmt.Errorf("error parsing SNMPV3 msgFlags: %w", err)
}
cursor += count
if cursor > len(packet) {
return 0, errors.New("error parsing SNMPV3 message ID: truncted packet")
}
if MsgFlags, ok := rawMsgFlags.(string); ok && len(MsgFlags) > 0 {
response.MsgFlags = SnmpV3MsgFlags(MsgFlags[0])
x.Logger.Printf("parsed msg flags %s", MsgFlags)
}
rawSecModel, count, err := parseRawField(x.Logger, packet[cursor:], "msgSecurityModel")
if err != nil {
return 0, fmt.Errorf("error parsing SNMPV3 msgSecModel: %w", err)
}
cursor += count
if cursor >= len(packet) {
return 0, errors.New("error parsing SNMPV3 message ID: truncted packet")
}
if SecModel, ok := rawSecModel.(int); ok {
response.SecurityModel = SnmpV3SecurityModel(SecModel)
x.Logger.Printf("Parsed security model %d", SecModel)
}
if PDUType(packet[cursor]) != PDUType(OctetString) {
return 0, errors.New("invalid SNMPV3 Security Parameters")
}
_, cursorTmp, err = parseLength(packet[cursor:])
if err != nil {
return 0, err
}
cursor += cursorTmp
if cursor > len(packet) {
return 0, errors.New("error parsing SNMPV3 message ID: truncted packet")
}
if response.SecurityParameters == nil {
response.SecurityParameters = &UsmSecurityParameters{Logger: x.Logger}
}
cursor, err = response.SecurityParameters.unmarshal(response.MsgFlags, packet, cursor)
if err != nil {
return 0, err
}
x.Logger.Printf("Parsed Security Parameters. now offset=%v,", cursor)
return cursor, nil
}
func (x *GoSNMP) decryptPacket(packet []byte, cursor int, response *SnmpPacket) ([]byte, int, error) {
var err error
var decrypted = false
if cursor >= len(packet) {
return nil, 0, errors.New("error parsing SNMPV3: truncated packet")
}
switch PDUType(packet[cursor]) {
case PDUType(OctetString):
// pdu is encrypted
packet, err = response.SecurityParameters.decryptPacket(packet, cursor)
if err != nil {
return nil, 0, err
}
decrypted = true
fallthrough
case Sequence:
// pdu is plaintext or has been decrypted
tlength, cursorTmp, err := parseLength(packet[cursor:])
if err != nil {
return nil, 0, err
}
if decrypted {
// truncate padding that might have been included with
// the encrypted PDU
if cursor+tlength > len(packet) {
return nil, 0, errors.New("error parsing SNMPV3: truncated packet")
}
packet = packet[:cursor+tlength]
}
cursor += cursorTmp
if cursor > len(packet) {
return nil, 0, errors.New("error parsing SNMPV3: truncated packet")
}
rawContextEngineID, count, err := parseRawField(x.Logger, packet[cursor:], "contextEngineID")
if err != nil {
return nil, 0, fmt.Errorf("error parsing SNMPV3 contextEngineID: %w", err)
}
cursor += count
if cursor > len(packet) {
return nil, 0, errors.New("error parsing SNMPV3: truncated packet")
}
if contextEngineID, ok := rawContextEngineID.(string); ok {
response.ContextEngineID = contextEngineID
x.Logger.Printf("Parsed contextEngineID %s", contextEngineID)
}
rawContextName, count, err := parseRawField(x.Logger, packet[cursor:], "contextName")
if err != nil {
return nil, 0, fmt.Errorf("error parsing SNMPV3 contextName: %w", err)
}
cursor += count
if cursor > len(packet) {
return nil, 0, errors.New("error parsing SNMPV3: truncated packet")
}
if contextName, ok := rawContextName.(string); ok {
response.ContextName = contextName
x.Logger.Printf("Parsed contextName %s", contextName)
}
default:
return nil, 0, errors.New("error parsing SNMPV3 scoped PDU")
}
return packet, cursor, nil
}