forked from gosnmp/gosnmp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
marshal.go
1292 lines (1128 loc) · 36.9 KB
/
marshal.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
package gosnmp
import (
"bytes"
"context"
"encoding/asn1"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"runtime"
"strings"
"sync/atomic"
"time"
)
//
// Remaining globals and definitions located here.
// See http://www.rane.com/note161.html for a succint description of the SNMP
// protocol.
//
// SnmpVersion 1, 2c and 3 implemented
type SnmpVersion uint8
// SnmpVersion 1, 2c and 3 implemented
const (
Version1 SnmpVersion = 0x0
Version2c SnmpVersion = 0x1
Version3 SnmpVersion = 0x3
)
// SnmpPacket struct represents the entire SNMP Message or Sequence at the
// application layer.
type SnmpPacket struct {
Version SnmpVersion
MsgFlags SnmpV3MsgFlags
SecurityModel SnmpV3SecurityModel
SecurityParameters SnmpV3SecurityParameters // interface
ContextEngineID string
ContextName string
Community string
PDUType PDUType
MsgID uint32
RequestID uint32
MsgMaxSize uint32
Error SNMPError
ErrorIndex uint8
NonRepeaters uint8
MaxRepetitions uint32
Variables []SnmpPDU
Logger Logger // interface
// v1 traps have a very different format from v2c and v3 traps.
//
// These fields are set via the SnmpTrap parameter to SendTrap().
SnmpTrap
}
// SnmpTrap is used to define a SNMP trap, and is passed into SendTrap
type SnmpTrap struct {
Variables []SnmpPDU
// If true, the trap is an InformRequest, not a trap. This has no effect on
// v1 traps, as Inform is not part of the v1 protocol.
IsInform bool
// These fields are required for SNMPV1 Trap Headers
Enterprise string
AgentAddress string
GenericTrap int
SpecificTrap int
Timestamp uint
}
// VarBind struct represents an SNMP Varbind.
type VarBind struct {
Name asn1.ObjectIdentifier
Value asn1.RawValue
}
// PDUType describes which SNMP Protocol Data Unit is being sent.
type PDUType byte
// The currently supported PDUType's
const (
Sequence PDUType = 0x30
GetRequest PDUType = 0xa0
GetNextRequest PDUType = 0xa1
GetResponse PDUType = 0xa2
SetRequest PDUType = 0xa3
Trap PDUType = 0xa4 // v1
GetBulkRequest PDUType = 0xa5
InformRequest PDUType = 0xa6
SNMPv2Trap PDUType = 0xa7 // v2c, v3
Report PDUType = 0xa8 // v3
)
// SNMPv3: User-based Security Model Report PDUs and
// error types as per https://tools.ietf.org/html/rfc3414
const (
usmStatsUnsupportedSecLevels = ".1.3.6.1.6.3.15.1.1.1.0"
usmStatsNotInTimeWindows = ".1.3.6.1.6.3.15.1.1.2.0"
usmStatsUnknownUserNames = ".1.3.6.1.6.3.15.1.1.3.0"
usmStatsUnknownEngineIDs = ".1.3.6.1.6.3.15.1.1.4.0"
usmStatsWrongDigests = ".1.3.6.1.6.3.15.1.1.5.0"
usmStatsDecryptionErrors = ".1.3.6.1.6.3.15.1.1.6.0"
)
var (
ErrDecryption = errors.New("decryption error")
ErrNotInTimeWindow = errors.New("not in time window")
ErrUnknownEngineID = errors.New("unknown engine id")
ErrUnknownReportPDU = errors.New("unknown report pdu")
ErrUnknownSecurityLevel = errors.New("unknown security level")
ErrUnknownUsername = errors.New("unknown username")
ErrWrongDigest = errors.New("wrong digest")
)
const rxBufSize = 65535 // max size of IPv4 & IPv6 packet
// Logger is an interface used for debugging. Both Print and
// Printf have the same interfaces as Package Log in the std library. The
// Logger interface is small to give you flexibility in how you do
// your debugging.
//
// For verbose logging to stdout:
//
// gosnmp_logger = log.New(os.Stdout, "", 0)
type Logger interface {
Print(v ...interface{})
Printf(format string, v ...interface{})
}
func (x *GoSNMP) logPrint(v ...interface{}) {
if x.loggingEnabled {
x.Logger.Print(v...)
}
}
func (x *GoSNMP) logPrintf(format string, v ...interface{}) {
if x.loggingEnabled {
x.Logger.Printf(format, v...)
}
}
// send/receive one snmp request
func (x *GoSNMP) sendOneRequest(packetOut *SnmpPacket,
wait bool) (result *SnmpPacket, err error) {
allReqIDs := make([]uint32, 0, x.Retries+1)
// allMsgIDs := make([]uint32, 0, x.Retries+1) // unused
timeout := x.Timeout
withContextDeadline := false
for retries := 0; ; retries++ {
if retries > 0 {
if x.OnRetry != nil {
x.OnRetry(x)
}
x.logPrintf("Retry number %d. Last error was: %v", retries, err)
if withContextDeadline && strings.Contains(err.Error(), "timeout") {
err = context.DeadlineExceeded
break
}
if retries > x.Retries {
if strings.Contains(err.Error(), "timeout") {
err = fmt.Errorf("request timeout (after %d retries)", retries-1)
}
break
}
if x.ExponentialTimeout {
// https://www.webnms.com/snmp/help/snmpapi/snmpv3/v1/timeout.html
timeout *= 2
}
withContextDeadline = false
}
err = nil
if x.Context.Err() != nil {
return nil, x.Context.Err()
}
reqDeadline := time.Now().Add(timeout)
if contextDeadline, ok := x.Context.Deadline(); ok {
if contextDeadline.Before(reqDeadline) {
reqDeadline = contextDeadline
withContextDeadline = true
}
}
err = x.Conn.SetDeadline(reqDeadline)
if err != nil {
return nil, err
}
// Request ID is an atomic counter that wraps to 0 at max int32.
reqID := (atomic.AddUint32(&(x.requestID), 1) & 0x7FFFFFFF)
allReqIDs = append(allReqIDs, reqID)
packetOut.RequestID = reqID
if x.Version == Version3 {
msgID := (atomic.AddUint32(&(x.msgID), 1) & 0x7FFFFFFF)
// allMsgIDs = append(allMsgIDs, msgID) // unused
packetOut.MsgID = msgID
err = x.initPacket(packetOut)
if err != nil {
break
}
}
if x.loggingEnabled && x.Version == Version3 {
packetOut.SecurityParameters.Log()
}
var outBuf []byte
outBuf, err = packetOut.marshalMsg()
if err != nil {
// Don't retry - not going to get any better!
err = fmt.Errorf("marshal: %w", err)
break
}
if x.PreSend != nil {
x.PreSend(x)
}
x.logPrintf("SENDING PACKET: %#+v", *packetOut)
// If using UDP and unconnected socket, send packet directly to stored address.
if uconn, ok := x.Conn.(net.PacketConn); ok && x.uaddr != nil {
_, err = uconn.WriteTo(outBuf, x.uaddr)
} else {
_, err = x.Conn.Write(outBuf)
}
if err != nil {
continue
}
if x.OnSent != nil {
x.OnSent(x)
}
// all sends wait for the return packet, except for SNMPv2Trap
if !wait {
return &SnmpPacket{}, nil
}
waitingResponse:
for {
x.logPrint("WAITING RESPONSE...")
// Receive response and try receiving again on any decoding error.
// Let the deadline abort us if we don't receive a valid response.
var resp []byte
resp, err = x.receive()
if err == io.EOF && strings.HasPrefix(x.Transport, "tcp") {
// EOF on TCP: reconnect and retry. Do not count
// as retry as socket was broken
x.logPrintf("ERROR: EOF. Performing reconnect")
err = x.netConnect()
if err != nil {
return nil, err
}
retries--
break
} else if err != nil {
// receive error. retrying won't help. abort
break
}
if x.OnRecv != nil {
x.OnRecv(x)
}
x.logPrintf("GET RESPONSE OK: %+v", resp)
result = new(SnmpPacket)
result.Logger = x.Logger
result.MsgFlags = packetOut.MsgFlags
if packetOut.SecurityParameters != nil {
result.SecurityParameters = packetOut.SecurityParameters.Copy()
}
var cursor int
cursor, err = x.unmarshalHeader(resp, result)
if err != nil {
x.logPrintf("ERROR on unmarshall header: %s", err)
break
}
if x.Version == Version3 {
useResponseSecurityParameters := false
if usp, ok := x.SecurityParameters.(*UsmSecurityParameters); ok {
if usp.AuthoritativeEngineID == "" {
useResponseSecurityParameters = true
}
}
err = x.testAuthentication(resp, result, useResponseSecurityParameters)
if err != nil {
x.logPrintf("ERROR on Test Authentication on v3: %s", err)
break
}
resp, cursor, err = x.decryptPacket(resp, cursor, result)
if err != nil {
x.logPrintf("ERROR on decryptPacket on v3: %s", err)
break
}
}
err = x.unmarshalPayload(resp, cursor, result)
if err != nil {
x.logPrintf("ERROR on UnmarshalPayload on v3: %s", err)
break
}
if result.Error == NoError && len(result.Variables) < 1 {
x.logPrintf("ERROR on UnmarshalPayload on v3: Empty result")
break
}
// While Report PDU was defined by RFC 1905 as part of SNMPv2, it was never
// used until SNMPv3. Report PDU's allow a SNMP engine to tell another SNMP
// engine that an error was detected while processing an SNMP message.
//
// The format for a Report PDU is
// -----------------------------------
// | 0xA8 | reqid | 0 | 0 | varbinds |
// -----------------------------------
// where:
// - PDU type 0xA8 indicates a Report PDU.
// - reqid is either:
// The request identifier of the message that triggered the report
// or zero if the request identifier cannot be extracted.
// - The variable bindings will contain a single object identifier and its value
//
// usmStatsNotInTimeWindows and usmStatsUnknownEngineIDs are recoverable errors
// and will be retransmitted, for others we return the result with an error.
if result.Version == Version3 && result.PDUType == Report && len(result.Variables) == 1 {
switch result.Variables[0].Name {
case usmStatsUnsupportedSecLevels:
return result, ErrUnknownSecurityLevel
case usmStatsNotInTimeWindows:
break waitingResponse
case usmStatsUnknownUserNames:
return result, ErrUnknownUsername
case usmStatsUnknownEngineIDs:
break waitingResponse
case usmStatsWrongDigests:
return result, ErrWrongDigest
case usmStatsDecryptionErrors:
return result, ErrDecryption
default:
return result, ErrUnknownReportPDU
}
}
validID := false
for _, id := range allReqIDs {
if id == result.RequestID {
validID = true
}
}
if result.RequestID == 0 {
validID = true
}
if !validID {
x.logPrint("ERROR out of order")
continue
}
break
}
if err != nil {
continue
}
if x.OnFinish != nil {
x.OnFinish(x)
}
// Success!
return result, nil
}
// Return last error
return nil, err
}
// generic "sender" that negotiate any version of snmp request
//
// all sends wait for the return packet, except for SNMPv2Trap
func (x *GoSNMP) send(packetOut *SnmpPacket, wait bool) (result *SnmpPacket, err error) {
defer func() {
if e := recover(); e != nil {
var buf = make([]byte, 8192)
runtime.Stack(buf, true)
err = fmt.Errorf("recover: %v Stack:%v", e, string(buf))
}
}()
if x.Conn == nil {
return nil, fmt.Errorf("&GoSNMP.Conn is missing. Provide a connection or use Connect()")
}
if x.Retries < 0 {
x.Retries = 0
}
x.logPrint("SEND INIT")
if packetOut.Version == Version3 {
x.logPrint("SEND INIT NEGOTIATE SECURITY PARAMS")
if err = x.negotiateInitialSecurityParameters(packetOut); err != nil {
return &SnmpPacket{}, err
}
x.logPrint("SEND END NEGOTIATE SECURITY PARAMS")
}
// perform request
result, err = x.sendOneRequest(packetOut, wait)
if err != nil {
x.logPrintf("SEND Error on the first Request Error: %s", err)
return result, err
}
if result.Version == Version3 {
x.logPrintf("SEND STORE SECURITY PARAMS from result: %+v", result)
err = x.storeSecurityParameters(result)
if result.PDUType == Report && len(result.Variables) == 1 {
switch result.Variables[0].Name {
case usmStatsNotInTimeWindows:
x.logPrint("WARNING detected out-of-time-window ERROR")
if err = x.updatePktSecurityParameters(packetOut); err != nil {
x.logPrintf("ERROR updatePktSecurityParameters error: %s", err)
return nil, err
}
// retransmit with updated auth engine params
result, err = x.sendOneRequest(packetOut, wait)
if err != nil {
x.logPrintf("ERROR out-of-time-window retransmit error: %s", err)
return result, ErrNotInTimeWindow
}
case usmStatsUnknownEngineIDs:
x.logPrint("WARNING detected unknown engine id ERROR")
if err = x.updatePktSecurityParameters(packetOut); err != nil {
x.logPrintf("ERROR updatePktSecurityParameters error: %s", err)
return nil, err
}
// retransmit with updated engine id
result, err = x.sendOneRequest(packetOut, wait)
if err != nil {
x.logPrintf("ERROR unknown engine id retransmit error: %s", err)
return result, ErrUnknownEngineID
}
}
}
}
return result, err
}
func (packet *SnmpPacket) logPrintf(format string, v ...interface{}) {
if packet.Logger != nil {
packet.Logger.Printf(format, v...)
}
}
// -- Marshalling Logic --------------------------------------------------------
// MarshalMsg marshalls a snmp packet, ready for sending across the wire
func (packet *SnmpPacket) MarshalMsg() ([]byte, error) {
return packet.marshalMsg()
}
// marshal an SNMP message
func (packet *SnmpPacket) marshalMsg() ([]byte, error) {
var err error
buf := new(bytes.Buffer)
// version
buf.Write([]byte{2, 1, byte(packet.Version)})
if packet.Version == Version3 {
buf, err = packet.marshalV3(buf)
if err != nil {
return nil, err
}
} else {
// community
buf.Write([]byte{4, uint8(len(packet.Community))})
buf.WriteString(packet.Community)
// pdu
pdu, err2 := packet.marshalPDU()
if err2 != nil {
return nil, err2
}
buf.Write(pdu)
}
// build up resulting msg - sequence, length then the tail (buf)
msg := new(bytes.Buffer)
msg.WriteByte(byte(Sequence))
bufLengthBytes, err2 := marshalLength(buf.Len())
if err2 != nil {
return nil, err2
}
msg.Write(bufLengthBytes)
_, err = buf.WriteTo(msg)
if err != nil {
return nil, err
}
authenticatedMessage, err := packet.authenticate(msg.Bytes())
if err != nil {
return nil, err
}
return authenticatedMessage, nil
}
func (packet *SnmpPacket) marshalSNMPV1TrapHeader() ([]byte, error) {
buf := new(bytes.Buffer)
// marshal OID
oidBytes, err := marshalOID(packet.Enterprise)
if err != nil {
return nil, fmt.Errorf("unable to marshal OID: %w", err)
}
buf.Write([]byte{byte(ObjectIdentifier), byte(len(oidBytes))})
buf.Write(oidBytes)
// marshal AgentAddress (ip address)
ip := net.ParseIP(packet.AgentAddress)
ipAddressBytes := ipv4toBytes(ip)
buf.Write([]byte{byte(IPAddress), byte(len(ipAddressBytes))})
buf.Write(ipAddressBytes)
// marshal GenericTrap. Could just cast GenericTrap to a single byte as IDs greater than 6 are unknown,
// but do it properly. See issue 182.
var genericTrapBytes []byte
genericTrapBytes, err = marshalInt32(packet.GenericTrap)
if err != nil {
return nil, fmt.Errorf("unable to marshal SNMPv1 GenericTrap: %w", err)
}
buf.Write([]byte{byte(Integer), byte(len(genericTrapBytes))})
buf.Write(genericTrapBytes)
// marshal SpecificTrap
var specificTrapBytes []byte
specificTrapBytes, err = marshalInt32(packet.SpecificTrap)
if err != nil {
return nil, fmt.Errorf("unable to marshal SNMPv1 SpecificTrap: %w", err)
}
buf.Write([]byte{byte(Integer), byte(len(specificTrapBytes))})
buf.Write(specificTrapBytes)
// marshal timeTicks
timeTickBytes, err := marshalUint32(uint32(packet.Timestamp))
if err != nil {
return nil, fmt.Errorf("unable to Timestamp: %w", err)
}
buf.Write([]byte{byte(TimeTicks), byte(len(timeTickBytes))})
buf.Write(timeTickBytes)
return buf.Bytes(), nil
}
// marshal a PDU
func (packet *SnmpPacket) marshalPDU() ([]byte, error) {
buf := new(bytes.Buffer)
switch packet.PDUType {
case GetBulkRequest:
// requestid
buf.Write([]byte{2, 4})
err := binary.Write(buf, binary.BigEndian, packet.RequestID)
if err != nil {
return nil, err
}
// non repeaters
nonRepeaters, err := marshalUint32(packet.NonRepeaters)
if err != nil {
return nil, fmt.Errorf("marshalPDU: unable to marshal NonRepeaters to uint32: %w", err)
}
buf.Write([]byte{2, byte(len(nonRepeaters))})
if err = binary.Write(buf, binary.BigEndian, nonRepeaters); err != nil {
return nil, fmt.Errorf("marshalPDU: unable to marshal NonRepeaters: %w", err)
}
// max repetitions
maxRepetitions, err := marshalUint32(packet.MaxRepetitions)
if err != nil {
return nil, fmt.Errorf("marshalPDU: unable to marshal maxRepetitions to uint32: %w", err)
}
buf.Write([]byte{2, byte(len(maxRepetitions))})
if err = binary.Write(buf, binary.BigEndian, maxRepetitions); err != nil {
return nil, fmt.Errorf("marshalPDU: unable to marshal maxRepetitions: %w", err)
}
case Trap:
// write SNMP V1 Trap Header fields
snmpV1TrapHeader, err := packet.marshalSNMPV1TrapHeader()
if err != nil {
return nil, err
}
buf.Write(snmpV1TrapHeader)
default:
// requestid
buf.Write([]byte{2, 4})
err := binary.Write(buf, binary.BigEndian, packet.RequestID)
if err != nil {
return nil, fmt.Errorf("unable to marshal OID: %w", err)
}
// error status
errorStatus, err := marshalUint32(uint8(packet.Error))
if err != nil {
return nil, fmt.Errorf("marshalPDU: unable to marshal errorStatus to uint32: %w", err)
}
buf.Write([]byte{2, byte(len(errorStatus))})
if err = binary.Write(buf, binary.BigEndian, errorStatus); err != nil {
return nil, fmt.Errorf("marshalPDU: unable to marshal errorStatus: %w", err)
}
// error index
errorIndex, err := marshalUint32(packet.ErrorIndex)
if err != nil {
return nil, fmt.Errorf("marshalPDU: unable to marshal errorIndex to uint32: %w", err)
}
buf.Write([]byte{2, byte(len(errorIndex))})
if err = binary.Write(buf, binary.BigEndian, errorIndex); err != nil {
return nil, fmt.Errorf("marshalPDU: unable to marshal errorIndex: %w", err)
}
}
// build varbind list
vbl, err := packet.marshalVBL()
if err != nil {
return nil, fmt.Errorf("marshalPDU: unable to marshal varbind list: %w", err)
}
buf.Write(vbl)
// build up resulting pdu
pdu := new(bytes.Buffer)
// calculate pdu length
bufLengthBytes, err := marshalLength(buf.Len())
if err != nil {
return nil, fmt.Errorf("marshalPDU: unable to marshal pdu length: %w", err)
}
// write request type
pdu.WriteByte(byte(packet.PDUType))
// write pdu length
pdu.Write(bufLengthBytes)
// write the tail (buf)
if _, err = buf.WriteTo(pdu); err != nil {
return nil, fmt.Errorf("marshalPDU: unable to marshal pdu: %w", err)
}
return pdu.Bytes(), nil
}
// marshal a varbind list
func (packet *SnmpPacket) marshalVBL() ([]byte, error) {
vblBuf := new(bytes.Buffer)
for _, pdu := range packet.Variables {
pdu := pdu
vb, err := marshalVarbind(&pdu)
if err != nil {
return nil, err
}
vblBuf.Write(vb)
}
vblBytes := vblBuf.Bytes()
vblLengthBytes, err := marshalLength(len(vblBytes))
if err != nil {
return nil, err
}
// FIX does bytes.Buffer give better performance than byte slices?
result := []byte{byte(Sequence)}
result = append(result, vblLengthBytes...)
result = append(result, vblBytes...)
return result, nil
}
// marshal a varbind
func marshalVarbind(pdu *SnmpPDU) ([]byte, error) {
oid, err := marshalOID(pdu.Name)
if err != nil {
return nil, err
}
pduBuf := new(bytes.Buffer)
tmpBuf := new(bytes.Buffer)
// Marshal the PDU type into the appropriate BER
switch pdu.Type {
case Null:
ltmp, err2 := marshalLength(len(oid))
if err2 != nil {
return nil, err2
}
tmpBuf.Write([]byte{byte(ObjectIdentifier)})
tmpBuf.Write(ltmp)
tmpBuf.Write(oid)
tmpBuf.Write([]byte{byte(Null), byte(EndOfContents)})
ltmp, err2 = marshalLength(tmpBuf.Len())
if err2 != nil {
return nil, err2
}
pduBuf.Write([]byte{byte(Sequence)})
pduBuf.Write(ltmp)
_, err2 = tmpBuf.WriteTo(pduBuf)
if err2 != nil {
return nil, err2
}
case Integer:
// Oid
tmpBuf.Write([]byte{byte(ObjectIdentifier), byte(len(oid))})
tmpBuf.Write(oid)
// Number
var intBytes []byte
switch value := pdu.Value.(type) {
case byte:
intBytes = []byte{byte(pdu.Value.(int))}
case int:
if intBytes, err = marshalInt32(value); err != nil {
return nil, fmt.Errorf("error mashalling PDU Integer: %w", err)
}
default:
return nil, fmt.Errorf("unable to marshal PDU Integer; not byte or int")
}
tmpBuf.Write([]byte{byte(Integer), byte(len(intBytes))})
tmpBuf.Write(intBytes)
// Sequence, length of oid + integer, then oid/integer data
pduBuf.WriteByte(byte(Sequence))
pduBuf.WriteByte(byte(len(oid) + len(intBytes) + 4))
pduBuf.Write(tmpBuf.Bytes())
case Counter32, Gauge32, TimeTicks, Uinteger32:
// Oid
tmpBuf.Write([]byte{byte(ObjectIdentifier), byte(len(oid))})
tmpBuf.Write(oid)
// Number
var intBytes []byte
switch value := pdu.Value.(type) {
case uint32:
if intBytes, err = marshalUint32(value); err != nil {
return nil, fmt.Errorf("error marshalling PDU Uinteger32 type from uint32: %w", err)
}
case uint:
if intBytes, err = marshalUint32(uint32(value)); err != nil {
return nil, fmt.Errorf("error marshalling PDU Uinteger32 type from uint: %w", err)
}
default:
return nil, fmt.Errorf("unable to marshal pdu.Type %v; unknown pdu.Value %v[type=%T]", pdu.Type, pdu.Value, pdu.Value)
}
tmpBuf.Write([]byte{byte(pdu.Type), byte(len(intBytes))})
tmpBuf.Write(intBytes)
// Sequence, length of oid + integer, then oid/integer data
pduBuf.WriteByte(byte(Sequence))
pduBuf.WriteByte(byte(len(oid) + len(intBytes) + 4))
pduBuf.Write(tmpBuf.Bytes())
case OctetString, BitString:
// Oid
tmpBuf.Write([]byte{byte(ObjectIdentifier), byte(len(oid))})
tmpBuf.Write(oid)
// OctetString
var octetStringBytes []byte
switch value := pdu.Value.(type) {
case []byte:
octetStringBytes = value
case string:
octetStringBytes = []byte(value)
default:
return nil, fmt.Errorf("unable to marshal PDU OctetString; not []byte or string")
}
var length []byte
length, err = marshalLength(len(octetStringBytes))
if err != nil {
return nil, fmt.Errorf("unable to marshal PDU length: %w", err)
}
tmpBuf.WriteByte(byte(pdu.Type))
tmpBuf.Write(length)
tmpBuf.Write(octetStringBytes)
tmpBytes := tmpBuf.Bytes()
length, err = marshalLength(len(tmpBytes))
if err != nil {
return nil, fmt.Errorf("unable to marshal PDU data length: %w", err)
}
// Sequence, length of oid + octetstring, then oid/octetstring data
pduBuf.WriteByte(byte(Sequence))
pduBuf.Write(length)
pduBuf.Write(tmpBytes)
case ObjectIdentifier:
// Oid
tmpBuf.Write([]byte{byte(ObjectIdentifier), byte(len(oid))})
tmpBuf.Write(oid)
value := pdu.Value.(string)
oidBytes, err := marshalOID(value)
if err != nil {
return nil, fmt.Errorf("error marshalling ObjectIdentifier: %w", err)
}
// Oid data
var length []byte
length, err = marshalLength(len(oidBytes))
if err != nil {
return nil, fmt.Errorf("error marshalling ObjectIdentifier length: %w", err)
}
tmpBuf.WriteByte(byte(pdu.Type))
tmpBuf.Write(length)
tmpBuf.Write(oidBytes)
tmpBytes := tmpBuf.Bytes()
length, err = marshalLength(len(tmpBytes))
if err != nil {
return nil, fmt.Errorf("error marshalling ObjectIdentifier data length: %w", err)
}
// Sequence, length of oid + oid, then oid/oid data
pduBuf.WriteByte(byte(Sequence))
pduBuf.Write(length)
pduBuf.Write(tmpBytes)
case IPAddress:
// Oid
tmpBuf.Write([]byte{byte(ObjectIdentifier), byte(len(oid))})
tmpBuf.Write(oid)
// OctetString
var ipAddressBytes []byte
switch value := pdu.Value.(type) {
case []byte:
ipAddressBytes = value
case string:
ip := net.ParseIP(value)
ipAddressBytes = ipv4toBytes(ip)
default:
return nil, fmt.Errorf("unable to marshal PDU IPAddress; not []byte or string")
}
tmpBuf.Write([]byte{byte(IPAddress), byte(len(ipAddressBytes))})
tmpBuf.Write(ipAddressBytes)
// Sequence, length of oid + octetstring, then oid/octetstring data
pduBuf.WriteByte(byte(Sequence))
pduBuf.WriteByte(byte(len(oid) + len(ipAddressBytes) + 4))
pduBuf.Write(tmpBuf.Bytes())
case Counter64, OpaqueFloat, OpaqueDouble:
converters := map[Asn1BER]func(interface{}) ([]byte, error){
Counter64: marshalUint64,
OpaqueFloat: marshalFloat32,
OpaqueDouble: marshalFloat64,
}
tmpBuf.Write([]byte{byte(ObjectIdentifier), byte(len(oid))})
tmpBuf.Write(oid)
tmpBuf.WriteByte(byte(pdu.Type))
intBytes, err := converters[pdu.Type](pdu.Value)
if err != nil {
return nil, fmt.Errorf("error converting PDU value type %v to %v: %w", pdu.Value, pdu.Type, err)
}
tmpBuf.WriteByte(byte(len(intBytes)))
tmpBuf.Write(intBytes)
tmpBytes := tmpBuf.Bytes()
length, err := marshalLength(len(tmpBytes))
if err != nil {
return nil, fmt.Errorf("error marshalling Float type length: %w", err)
}
// Sequence, length of oid + oid, then oid/oid data
pduBuf.WriteByte(byte(Sequence))
pduBuf.Write(length)
pduBuf.Write(tmpBytes)
case NoSuchInstance, NoSuchObject, EndOfMibView:
tmpBuf.Write([]byte{byte(ObjectIdentifier), byte(len(oid))})
tmpBuf.Write(oid)
tmpBuf.WriteByte(byte(pdu.Type))
tmpBuf.WriteByte(byte(EndOfContents))
tmpBytes := tmpBuf.Bytes()
length, err := marshalLength(len(tmpBytes))
if err != nil {
return nil, fmt.Errorf("error marshalling Null type data length: %w", err)
}
// Sequence, length of oid + oid, then oid/oid data
pduBuf.WriteByte(byte(Sequence))
pduBuf.Write(length)
pduBuf.Write(tmpBytes)
default:
return nil, fmt.Errorf("unable to marshal PDU: unknown BER type %q", pdu.Type)
}
return pduBuf.Bytes(), nil
}
// -- Unmarshalling Logic ------------------------------------------------------
func (x *GoSNMP) unmarshalHeader(packet []byte, response *SnmpPacket) (int, error) {
if len(packet) < 2 {
return 0, fmt.Errorf("cannot unmarshal empty packet")
}
if response == nil {
return 0, fmt.Errorf("cannot unmarshal response into nil packet reference")
}
response.Variables = make([]SnmpPDU, 0, 5)
// Start parsing the packet
cursor := 0
// First bytes should be 0x30
if PDUType(packet[0]) != Sequence {
return 0, fmt.Errorf("invalid packet header")
}
length, cursor := parseLength(packet)
if len(packet) != length {
return 0, fmt.Errorf("error verifying packet sanity: Got %d Expected: %d", len(packet), length)
}
x.logPrintf("Packet sanity verified, we got all the bytes (%d)", length)
// Parse SNMP Version
rawVersion, count, err := parseRawField(x.Logger, packet[cursor:], "version")
if err != nil {
return 0, fmt.Errorf("error parsing SNMP packet version: %w", err)
}
cursor += count
if cursor > len(packet) {
return 0, fmt.Errorf("error parsing SNMP packet, packet length %d cursor %d", len(packet), cursor)
}
if version, ok := rawVersion.(int); ok {
response.Version = SnmpVersion(version)
x.logPrintf("Parsed version %d", version)
}
if response.Version == Version3 {
oldcursor := cursor
cursor, err = x.unmarshalV3Header(packet, cursor, response)
if err != nil {
return 0, err
}
x.logPrintf("UnmarshalV3Header done. [with SecurityParameters]. Header Size %d. Last 4 Bytes=[%v]", cursor-oldcursor, packet[cursor-4:cursor])
} else {
// Parse community
rawCommunity, count, err := parseRawField(x.Logger, packet[cursor:], "community")
if err != nil {
return 0, fmt.Errorf("error parsing community string: %w", err)
}
cursor += count
if cursor > len(packet) {
return 0, fmt.Errorf("error parsing SNMP packet, packet length %d cursor %d", len(packet), cursor)
}
if community, ok := rawCommunity.(string); ok {
response.Community = community
x.logPrintf("Parsed community %s", community)
}
}
return cursor, nil
}
func (x *GoSNMP) unmarshalPayload(packet []byte, cursor int, response *SnmpPacket) error {
if len(packet) == 0 {
return errors.New("cannot unmarshal nil or empty payload packet")
}
if cursor > len(packet) {
return fmt.Errorf("cannot unmarshal payload, packet length %d cursor %d", len(packet), cursor)
}
if response == nil {
return errors.New("cannot unmarshal payload response into nil packet reference")
}
// Parse SNMP packet type
requestType := PDUType(packet[cursor])
x.logPrintf("UnmarshalPayload Meet PDUType %#x. Offset %v", requestType, cursor)
switch requestType {
// known, supported types
case GetResponse, GetNextRequest, GetBulkRequest, Report, SNMPv2Trap, GetRequest, SetRequest, InformRequest:
response.PDUType = requestType
if err := x.unmarshalResponse(packet[cursor:], response); err != nil {