Repository navigation
Expand file tree
/
Copy pathcodec_encode_test.go
More file actions
770 lines (732 loc) · 34.4 KB
/
Copy pathcodec_encode_test.go
File metadata and controls
770 lines (732 loc) · 34.4 KB
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
// Copyright 2026 Netdata Inc. 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"
"fmt"
"math"
"slices"
"strconv"
"strings"
"testing"
"github.com/netdata/gosnmp/internal/ber"
"github.com/netdata/gosnmp/internal/usm"
)
// TestEncodeCharacterization pins the bytes MarshalMsg and SnmpEncodePacket
// produce for packets that cover every PDU layout, SNMPv3 security level,
// length form and OID edge case, or whether they fail or panic.
func TestEncodeCharacterization(t *testing.T) {
cases, wide := encodeCases(t)
results := make([]goldenCase, 0, len(cases))
for _, c := range cases {
gc := goldenCase{name: c.name, wide: wide[c.name]}
if !gc.skipped() {
usm.Salts.Set(0x0000000700000001) // the salt of an encrypted case
gc.dump = dumpEncode(c.encode)
}
results = append(results, gc)
}
codecGolden.check(t, "encode", results)
}
// TestMarshalLongOctetStringFields encodes communities and USM engine IDs
// longer than 127 bytes, and a user name of 32 bytes (the most RFC 3414
// section 2.4 allows), and decodes them back.
func TestMarshalLongOctetStringFields(t *testing.T) {
type fields struct {
community, engineID, userName string
}
long := func(n int) string { return strings.Repeat("x", n) }
tests := map[string]fields{
"community 128 bytes": {community: long(128)},
"community 256 bytes": {community: long(256)},
"community 300 bytes": {community: long(300)},
"engine ID 128 bytes": {engineID: long(128), userName: "user"},
"engine ID 300 bytes": {engineID: long(300), userName: "user"},
"user name 32 bytes": {engineID: "\x80\x00\x1f\x88\x04engine", userName: long(32)},
}
for name, want := range tests {
t.Run(name, func(t *testing.T) {
packet := &SnmpPacket{
Version: Version2c,
Community: want.community,
PDUType: GetRequest,
RequestID: 1,
Variables: []SnmpPDU{{Name: ".1.3.6.1.2.1.1.1.0", Type: Null}},
}
if want.community == "" {
packet.Version = Version3
packet.MsgFlags = NoAuthNoPriv
packet.SecurityModel = UserSecurityModel
packet.MsgID = 1
packet.SecurityParameters = &UsmSecurityParameters{AuthoritativeEngineID: want.engineID, UserName: want.userName}
}
msg, err := packet.MarshalMsg()
if err != nil {
t.Fatalf("MarshalMsg: %v", err)
}
decoded, err := (&GoSNMP{}).SnmpDecodePacket(msg)
if err != nil {
t.Fatalf("decoding the encoded message: %v\nmessage: %x", err, msg)
}
got := fields{community: decoded.Community}
if usm, ok := decoded.SecurityParameters.(*UsmSecurityParameters); ok {
got.engineID, got.userName = usm.AuthoritativeEngineID, usm.UserName
}
if got != want {
t.Errorf("decoded %+v, want %+v", got, want)
}
})
}
}
// TestMarshalUnencodableValues checks that MarshalMsg reports caller values
// it cannot encode as errors instead of panicking.
func TestMarshalUnencodableValues(t *testing.T) {
varbind := func(typ Asn1BER, value any) *SnmpPacket {
return &SnmpPacket{
Version: Version2c,
Community: "public",
PDUType: SetRequest,
RequestID: 1,
Variables: []SnmpPDU{{Name: ".1.3.6.1.2.1.1.5.0", Type: typ, Value: value}},
}
}
trap := func(agentAddress string) *SnmpPacket {
return &SnmpPacket{
Version: Version1,
Community: "public",
PDUType: Trap,
Enterprise: ".1.3.6.1.4.1.20372",
AgentAddress: agentAddress,
GenericTrap: 6,
}
}
tests := map[string]*SnmpPacket{
"Integer with a uint8 value": varbind(Integer, uint8(200)),
"ObjectIdentifier with an int value": varbind(ObjectIdentifier, 5),
"ObjectIdentifier with a []byte value": varbind(ObjectIdentifier, []byte(".1.3.6.1")),
"ObjectIdentifier with a nil value": varbind(ObjectIdentifier, nil),
"IPAddress with a string that is not an IP": varbind(IPAddress, "x"),
"v1 trap with an empty agent address": trap(""),
"v1 trap with an agent address not an IP": trap("x"),
}
for name, packet := range tests {
t.Run(name, func(t *testing.T) {
var err error
panicked, _ := observe(func() { _, err = packet.MarshalMsg() })
if panicked || err == nil {
t.Errorf("MarshalMsg panicked: %v, error: %v; want an error", panicked, err)
}
})
}
}
// TestEncodeValueTypesCharacterization pins, for every value tag, the value
// TLV that MarshalMsg writes for each Go value type, or whether it fails or
// panics. It records which Go types the encoder accepts.
func TestEncodeValueTypesCharacterization(t *testing.T) {
tags := []Asn1BER{
UnknownType, Boolean, Integer, BitString, OctetString, Null, ObjectIdentifier, ObjectDescription, IPAddress,
Counter32, Gauge32, TimeTicks, Opaque, NsapAddress, Counter64, Uinteger32, OpaqueFloat, OpaqueDouble,
NoSuchObject, NoSuchInstance, EndOfMibView,
}
values := []struct {
label string
value any
}{
{"nil", nil},
{"int(0)", 0},
{"int(-1)", -1},
{"int(MaxInt32)", math.MaxInt32},
{"int(MinInt32)", math.MinInt32},
{"int8(-1)", int8(-1)},
{"int32(-5)", int32(-5)},
{"int64(5)", int64(5)},
{"int64(MaxInt64)", int64(math.MaxInt64)},
{"uint(5)", uint(5)},
{"uint8(200)", uint8(200)},
{"uint32(MaxUint32)", uint32(math.MaxUint32)},
{"uint64(2^40)", uint64(1 << 40)},
{"uint64(MaxUint64)", uint64(math.MaxUint64)},
{"float32(1.5)", float32(1.5)},
{"float64(-2.25)", float64(-2.25)},
{`string("1.3.6.1")`, "1.3.6.1"},
{`string("192.0.2.1")`, "192.0.2.1"},
{`string("2001:db8::1")`, "2001:db8::1"},
{`string("::ffff:192.0.2.1")`, "::ffff:192.0.2.1"},
{`string("x")`, "x"},
{`[]byte("x")`, []byte("x")},
{"[]byte{}", []byte{}},
{"[]byte{192, 0, 2, 1}", []byte{192, 0, 2, 1}},
{"[]byte{1, 2, 3, 4, 5}", []byte{1, 2, 3, 4, 5}},
{"[]byte of 2001:db8::1", []byte{0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}},
}
results := make([]goldenCase, 0, len(tags))
for _, tag := range tags {
var d dumpWriter
for _, v := range values {
pkt := &SnmpPacket{
Version: Version2c,
Community: "public",
PDUType: SetRequest,
RequestID: 1,
Variables: []SnmpPDU{{Name: ".1.3.6.1.2.1.1.5.0", Type: tag, Value: v.value}},
}
d.linef("%s: %s", v.label, dumpVarbindValue(pkt))
}
results = append(results, goldenCase{name: fmt.Sprintf("0x%02x %s", byte(tag), tag), dump: d.String()})
}
codecGolden.check(t, "encode-value-types", results)
}
// TestEncodeReportableFlag checks the msgFlags octet of SNMPv3 messages: the
// security level, and the reportable flag set exactly for a PDU of the
// Confirmed Class (RFC 3412 section 6.4), whatever the packet's or client's
// flags hold besides the level, through MarshalMsg and SnmpEncodePacket.
func TestEncodeReportableFlag(t *testing.T) {
pduTypes := []PDUType{
GetRequest, GetNextRequest, GetBulkRequest, SetRequest, InformRequest, GetResponse, SNMPv2Trap, Report, Trap,
}
trap := SnmpTrap{Enterprise: ".1.3.6.1.4.1.20372", AgentAddress: "192.0.2.1", GenericTrap: 6}
vars := []SnmpPDU{{Name: ".1.3.6.1.2.1.1.1.0", Type: Null}}
for _, pdu := range pduTypes {
for _, level := range []SnmpV3MsgFlags{NoAuthNoPriv, AuthNoPriv} {
for _, flags := range []SnmpV3MsgFlags{level, level | Reportable} {
t.Run(fmt.Sprintf("MarshalMsg/%v/%v", pdu, flags), func(t *testing.T) {
msg, err := (&SnmpPacket{
Version: Version3, MsgFlags: flags, SecurityModel: UserSecurityModel,
SecurityParameters: codecUSM(t, levelAuth(level), NoPriv),
PDUType: pdu, MsgID: 1, RequestID: 1, SnmpTrap: trap, Variables: vars,
}).MarshalMsg()
if err != nil {
t.Fatalf("MarshalMsg: %v", err)
}
if got, want := wireFlags(t, msg), classFlags(level, pdu); got != want {
t.Errorf("msgFlags %v, want %v", got, want)
}
})
}
if pdu == Trap {
continue // SnmpEncodePacket has no SNMPv1 trap fields
}
t.Run(fmt.Sprintf("SnmpEncodePacket/%v/%v", pdu, level), func(t *testing.T) {
x := &GoSNMP{
Version: Version3, MsgFlags: level, SecurityModel: UserSecurityModel,
SecurityParameters: codecUSM(t, levelAuth(level), NoPriv),
}
msg, err := x.SnmpEncodePacket(pdu, vars, 0, 0)
if err != nil {
t.Fatalf("SnmpEncodePacket: %v", err)
}
if got, want := wireFlags(t, msg), classFlags(level, pdu); got != want {
t.Errorf("msgFlags %v, want %v", got, want)
}
})
}
}
}
// classFlags is the msgFlags octet of a message of level and pdu: Reportable
// for a PDU of the Confirmed Class.
func classFlags(level SnmpV3MsgFlags, pdu PDUType) SnmpV3MsgFlags {
if pdu.confirmed() {
return level | Reportable
}
return level
}
// TestValueKinds checks the value kinds: a type with a kind encodes and one
// without does not, and the decoder reads each kind's boundary values as the
// encoder writes them back to the same type and a value that encodes the same.
func TestValueKinds(t *testing.T) {
maxOID := ".2.4294967295" + strings.Repeat(".4294967295", 126) // 128 arcs, each the largest
samples := map[valueKind][]any{
kindNone: {nil},
kindNull: {nil},
kindInteger: {1, 0, math.MinInt32, math.MaxInt32},
kindUnsigned32: {uint32(1), uint32(0), uint32(math.MaxUint32), uint(math.MaxUint32)},
kindCounter64: {uint64(1), uint64(0), uint64(math.MaxUint64)},
kindOctets: {[]byte("x"), []byte{}, "text"},
kindOID: {".1.3.6.1", ".0.0", maxOID},
kindIPAddress: {"192.0.2.1", []byte{192, 0, 2, 1}, "2001:db8::1", make([]byte, 16)},
}
for tag := range 256 {
kind := valueKinds[tag]
values := samples[kind]
switch Asn1BER(tag) {
case OpaqueFloat:
values = []any{float32(1), float32(-0.5), float32(math.MaxFloat32)}
case OpaqueDouble:
values = []any{float64(1), math.MaxFloat64}
}
for _, value := range values {
out, err := appendValue(nil, Asn1BER(tag), value)
switch {
case kind == kindNone && err == nil:
t.Errorf("%v: encodes without a kind", Asn1BER(tag))
case kind != kindNone && err != nil:
t.Errorf("%v %#v: %v", Asn1BER(tag), value, err)
case err == nil:
r := ber.NewReader(out)
wireTag, content, err := r.Next()
if err != nil {
t.Fatalf("%v: %x: %v", Asn1BER(tag), out, err)
}
typ, decoded, err := decodeValue(Asn1BER(wireTag), content)
if err != nil {
t.Fatalf("%v: decoding %x: %v", Asn1BER(tag), out, err)
}
again, err := appendValue(nil, typ, decoded)
if typ != Asn1BER(tag) || err != nil || !bytes.Equal(again, out) {
t.Errorf("%v %#v: decodes as %v %#v, which encodes as %x (%v), not %x", Asn1BER(tag), value, typ, decoded, again, err, out)
}
}
}
}
}
// levelAuth is the authentication protocol codecUSM needs for level.
func levelAuth(level SnmpV3MsgFlags) SnmpV3AuthProtocol {
if level.authFlag() {
return SHA
}
return NoAuth
}
// wireFlags returns the msgFlags octet of the SNMPv3 message msg, read from
// msgGlobalData without parsing the rest.
func wireFlags(t *testing.T, msg []byte) SnmpV3MsgFlags {
t.Helper()
next := func(r *ber.Reader) []byte {
_, content, err := r.Next()
if err != nil {
t.Fatalf("reading msgFlags: %v\nmessage: %x", err, msg)
}
return content
}
r := ber.NewReader(msg)
m := ber.NewReader(next(&r))
next(&m) // msgVersion
g := ber.NewReader(next(&m))
next(&g) // msgID
next(&g) // msgMaxSize
flags := next(&g)
if len(flags) != 1 {
t.Fatalf("msgFlags of %d octets\nmessage: %x", len(flags), msg)
}
return SnmpV3MsgFlags(flags[0])
}
type encodeCase struct {
name string
encode func() ([]byte, error)
}
func dumpEncode(encode func() ([]byte, error)) string {
var out []byte
var err error
panicked, wroteStdout := observe(func() { out, err = encode() })
var d dumpWriter
switch {
case panicked:
d.line("encode: panic")
case err != nil:
d.line("encode: " + dumpError(err))
default:
d.line("encode: " + dumpBytes(out))
}
if wroteStdout {
d.line("stdout: written")
}
return d.String()
}
// dumpVarbindValue marshals a one-varbind v2c packet and returns the value TLV
// of its varbind, the whole message when it cannot be split, or the failure.
func dumpVarbindValue(pkt *SnmpPacket) string {
var out []byte
var err error
panicked, wroteStdout := observe(func() { out, err = pkt.MarshalMsg() })
var result string
switch {
case panicked:
result = "panic"
case err != nil:
result = dumpError(err)
default:
if value, ok := lastVarbindValue(out); ok {
result = fmt.Sprintf("% x", value)
} else {
result = "message " + dumpBytes(out)
}
}
if wroteStdout {
result += " (stdout written)"
}
return result
}
// lastVarbindValue returns the value TLV of the last varbind of a v1/v2c
// message, using a minimal BER reader that is independent of the codec.
func lastVarbindValue(msg []byte) ([]byte, bool) {
path := []int{2, 3, -1, 1} // message -> PDU -> varbind list -> last varbind -> value
cur := msg
for _, idx := range path {
children, ok := berChildren(cur)
if !ok || len(children) == 0 {
return nil, false
}
if idx < 0 {
idx = len(children) - 1
}
if idx >= len(children) {
return nil, false
}
cur = children[idx]
}
return cur, true
}
// berChildren splits the content of one constructed TLV into its child TLVs.
func berChildren(b []byte) ([][]byte, bool) {
content, rest, ok := berNext(b)
if !ok || len(rest) != 0 {
return nil, false
}
content = content[berHeaderLen(content):]
var children [][]byte
for len(content) > 0 {
child, next, ok := berNext(content)
if !ok {
return nil, false
}
children = append(children, child)
content = next
}
return children, true
}
// berNext returns the first TLV of b (header included) and the bytes after it.
func berNext(b []byte) (tlvBytes, rest []byte, ok bool) {
if len(b) < 2 {
return nil, nil, false
}
hdr := berHeaderLen(b)
if hdr == 0 || hdr > len(b) {
return nil, nil, false
}
n := 0
if b[1] < 0x80 {
n = int(b[1])
} else {
for _, c := range b[2:hdr] {
n = n<<8 | int(c)
}
}
if n > len(b)-hdr {
return nil, nil, false
}
return b[:hdr+n], b[hdr+n:], true
}
// berHeaderLen is the length of the tag and length octets of a definite-length TLV, or 0.
func berHeaderLen(b []byte) int {
if len(b) < 2 {
return 0
}
switch {
case b[1] < 0x80:
return 2
case b[1] == 0x80 || b[1] > 0x84:
return 0
default:
return 2 + int(b[1]&0x7f)
}
}
// codecUSM returns USM parameters for the synthetic codec-user with localized keys.
func codecUSM(t *testing.T, auth SnmpV3AuthProtocol, priv SnmpV3PrivProtocol) *UsmSecurityParameters {
t.Helper()
sp := &UsmSecurityParameters{
UserName: "codec-user",
AuthenticationProtocol: auth,
AuthenticationPassphrase: "codec-auth-pass",
PrivacyProtocol: priv,
PrivacyPassphrase: "codec-priv-pass",
AuthoritativeEngineID: "\x80\x00\x1f\x88\x04codec-engine",
AuthoritativeEngineBoots: 7,
AuthoritativeEngineTime: 1234,
}
if auth != NoAuth {
if err := sp.InitSecurityKeys(); err != nil {
t.Fatal(err)
}
}
return sp
}
// encodeCases returns the encode characterization cases and the names of those
// whose input needs a 64-bit int or uint (goldenCase.wide).
func encodeCases(t *testing.T) ([]encodeCase, map[string]bool) {
t.Helper()
wide := make(map[string]bool)
wideCase := func(name string, encode func() ([]byte, error)) encodeCase {
wide[name] = true
return encodeCase{name, encode}
}
nullVar := []SnmpPDU{{Name: ".1.3.6.1.2.1.1.1.0", Type: Null}}
mixedVars := []SnmpPDU{
{Name: ".1.3.6.1.2.1.1.7.0", Type: Integer, Value: 104},
{Name: ".1.3.6.1.2.1.1.4.0", Type: OctetString, Value: []byte("Administrator")},
{Name: ".1.3.6.1.2.1.1.2.0", Type: ObjectIdentifier, Value: ".1.3.6.1.4.1.8072.3.2.10"},
{Name: ".1.3.6.1.2.1.4.20.1.1.192.0.2.1", Type: IPAddress, Value: "192.0.2.1"},
{Name: ".1.3.6.1.2.1.2.2.1.10.1", Type: Counter32, Value: uint32(271070065)},
{Name: ".1.3.6.1.2.1.2.2.1.5.1", Type: Gauge32, Value: uint(100000000)},
{Name: ".1.3.6.1.2.1.1.3.0", Type: TimeTicks, Value: uint32(318870100)},
{Name: ".1.3.6.1.2.1.31.1.1.1.10.1", Type: Counter64, Value: uint64(1527943)},
{Name: ".1.3.6.1.4.1.2021.1", Type: Opaque, Value: []byte{0x9f, 0x78, 0x04, 0x41, 0x20, 0x00, 0x00}},
{Name: ".1.3.6.1.4.1.6574.4.2.12.1.0", Type: OpaqueFloat, Value: float32(10.0)},
{Name: ".1.3.6.1.4.1.6574.4.2.12.2.0", Type: OpaqueDouble, Value: float64(10.0)},
{Name: ".1.3.6.1.2.1.1.3.1", Type: Uinteger32, Value: uint32(7)},
{Name: ".1.3.6.1.2.1.1.9.0", Type: NoSuchObject},
{Name: ".1.3.6.1.2.1.1.9.1", Type: NoSuchInstance},
{Name: ".1.3.6.1.2.1.1.9.2", Type: EndOfMibView},
}
trap := SnmpTrap{
Enterprise: ".1.3.6.1.4.1.20372",
AgentAddress: "192.0.2.1",
GenericTrap: 6,
SpecificTrap: 42,
Timestamp: 256,
}
v2c := func(pduType PDUType, vars []SnmpPDU) *SnmpPacket {
return &SnmpPacket{Version: Version2c, Community: "public", PDUType: pduType, RequestID: 1, Variables: vars}
}
beyondInt32 := int64(math.MaxInt32) + 1
beyondUint32 := uint64(math.MaxUint32) + 1
// uintValue is a SetRequest of one varbind of typ holding the uint v.
uintValue := func(typ Asn1BER, v uint64) *SnmpPacket {
return v2c(SetRequest, []SnmpPDU{{Name: ".1.3.6.1.2.1.1.5.0", Type: typ, Value: uint(v)}})
}
v1Trap := func(edit func(*SnmpTrap)) *SnmpPacket {
tr := trap
edit(&tr)
return &SnmpPacket{Version: Version1, Community: "public", PDUType: Trap, SnmpTrap: tr, Variables: nullVar}
}
v3 := func(flags SnmpV3MsgFlags, pduType PDUType, sp *UsmSecurityParameters) *SnmpPacket {
return &SnmpPacket{
Version: Version3,
MsgFlags: flags,
SecurityModel: UserSecurityModel,
SecurityParameters: sp,
ContextEngineID: "\x80\x00\x1f\x88\x04codec-engine",
ContextName: "codec-context",
PDUType: pduType,
MsgID: 4242,
RequestID: 123456,
Variables: nullVar,
}
}
// hostVars are n OctetString varbinds; 4 make a v3 scoped PDU need a two-octet
// length, 20 a three-octet one.
hostVars := func(n int) []SnmpPDU {
vars := make([]SnmpPDU, n)
for i := range vars {
vars[i] = SnmpPDU{Name: ".1.3.6.1.2.1.1.5." + strconv.Itoa(i), Type: OctetString, Value: []byte("codec-host-" + strconv.Itoa(i))}
}
return vars
}
withVars := func(p *SnmpPacket, vars []SnmpPDU) *SnmpPacket { p.Variables = vars; return p }
oidName := func(name string) *SnmpPacket { return v2c(GetRequest, []SnmpPDU{{Name: name, Type: Null}}) }
// withPacketSalt gives the packet a salt of its own, unlike the drawn one:
// the encoder must neither send nor encrypt with it.
withPacketSalt := func(sp *UsmSecurityParameters) *UsmSecurityParameters {
sp.PrivacyParameters = []byte{0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee}
return sp
}
// 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 *GoSNMP) *GoSNMP {
x.SetRequestID(0)
x.SetMsgID(0)
return x
}
marshal := func(p *SnmpPacket) func() ([]byte, error) { return p.MarshalMsg }
edit := func(p *SnmpPacket, f func(*SnmpPacket)) *SnmpPacket { f(p); return p }
return []encodeCase{
// v1 and v2c PDUs.
{"v1/get-request", marshal(&SnmpPacket{Version: Version1, Community: "public", PDUType: GetRequest, RequestID: 1, Variables: nullVar})},
{"v2c/get-request", marshal(v2c(GetRequest, nullVar))},
{"v2c/get-request/no-varbinds", marshal(v2c(GetRequest, nil))},
{"v2c/get-next-request", marshal(v2c(GetNextRequest, nullVar))},
{"v2c/getbulk-request", marshal(edit(v2c(GetBulkRequest, slices.Concat(nullVar, nullVar)), func(p *SnmpPacket) { p.NonRepeaters, p.MaxRepetitions = 1, 10 }))},
{"v2c/getbulk-request/max-repetitions-2^31", marshal(edit(v2c(GetBulkRequest, nullVar), func(p *SnmpPacket) { p.MaxRepetitions = 1 << 31 }))},
{"v2c/getbulk-request/max-repetitions-max-uint32", marshal(edit(v2c(GetBulkRequest, nullVar), func(p *SnmpPacket) { p.MaxRepetitions = math.MaxUint32 }))},
{"v2c/getbulk-request/non-repeaters-200", marshal(edit(v2c(GetBulkRequest, nullVar), func(p *SnmpPacket) { p.NonRepeaters = 200 }))},
{"v2c/getbulk-request/request-id-2^31", marshal(edit(v2c(GetBulkRequest, nullVar), func(p *SnmpPacket) { p.RequestID = 1 << 31 }))},
{"v2c/set-request/mixed-types", marshal(v2c(SetRequest, mixedVars))},
{"v2c/get-response/error", marshal(edit(v2c(GetResponse, nullVar), func(p *SnmpPacket) { p.Error, p.ErrorIndex = GenErr, 2 }))},
{"v2c/get-response/error-index-255", marshal(edit(v2c(GetResponse, nullVar), func(p *SnmpPacket) { p.Error, p.ErrorIndex = TooBig, 255 }))},
{"v2c/snmpv2-trap", marshal(v2c(SNMPv2Trap, mixedVars[:3]))},
{"v2c/inform-request", marshal(v2c(InformRequest, nullVar))},
{"v2c/inform-request/is-inform-flag", marshal(edit(v2c(SNMPv2Trap, nullVar), func(p *SnmpPacket) { p.IsInform = true }))},
{"v2c/report", marshal(v2c(Report, nullVar))},
{"v2c/unknown-pdu-type", marshal(v2c(PDUType(0xa9), nullVar))},
{"v2c/request-id-0", marshal(edit(v2c(GetRequest, nullVar), func(p *SnmpPacket) { p.RequestID = 0 }))},
{"v2c/request-id-2^31", marshal(edit(v2c(GetRequest, nullVar), func(p *SnmpPacket) { p.RequestID = 1 << 31 }))},
{"v2c/request-id-max-uint32", marshal(edit(v2c(GetRequest, nullVar), func(p *SnmpPacket) { p.RequestID = math.MaxUint32 }))},
{"v2c/version-2", marshal(edit(v2c(GetRequest, nullVar), func(p *SnmpPacket) { p.Version = 2 }))},
wideCase("v2c/set-request/counter32-uint-2^32", marshal(uintValue(Counter32, beyondUint32))),
wideCase("v2c/set-request/gauge32-uint-2^32", marshal(uintValue(Gauge32, beyondUint32))),
wideCase("v2c/set-request/timeticks-uint-2^32", marshal(uintValue(TimeTicks, beyondUint32))),
wideCase("v2c/set-request/uinteger32-uint-2^32", marshal(uintValue(Uinteger32, beyondUint32))),
// Lengths.
{"v2c/community-empty", marshal(edit(v2c(GetRequest, nullVar), func(p *SnmpPacket) { p.Community = "" }))},
{"v2c/community-127", marshal(edit(v2c(GetRequest, nullVar), func(p *SnmpPacket) { p.Community = strings.Repeat("c", 127) }))},
{"v2c/community-128", marshal(edit(v2c(GetRequest, nullVar), func(p *SnmpPacket) { p.Community = strings.Repeat("c", 128) }))},
{"v2c/community-256", marshal(edit(v2c(GetRequest, nullVar), func(p *SnmpPacket) { p.Community = strings.Repeat("c", 256) }))},
{"v2c/octet-string-127", marshal(v2c(SetRequest, []SnmpPDU{{Name: ".1.3.6.1.2.1.1.5.0", Type: OctetString, Value: []byte(strings.Repeat("o", 127))}}))},
// 116 value octets make the varbind content exactly 128 bytes, the first long-form length.
{"v2c/varbind-content-128", marshal(v2c(SetRequest, []SnmpPDU{{Name: ".1.3.6.1.2.1.1.5.0", Type: OctetString, Value: []byte(strings.Repeat("o", 116))}}))},
{"v2c/octet-string-200", marshal(v2c(SetRequest, []SnmpPDU{{Name: ".1.3.6.1.2.1.1.5.0", Type: OctetString, Value: []byte(strings.Repeat("o", 200))}}))},
{"v2c/octet-string-300", marshal(v2c(SetRequest, []SnmpPDU{{Name: ".1.3.6.1.2.1.1.5.0", Type: OctetString, Value: []byte(strings.Repeat("o", 300))}}))},
{"v2c/octet-string-70000", marshal(v2c(SetRequest, []SnmpPDU{{Name: ".1.3.6.1.2.1.1.5.0", Type: OctetString, Value: []byte(strings.Repeat("o", 70000))}}))},
{"v2c/100-varbinds", marshal(v2c(GetRequest, slices.Repeat(nullVar, 100)))},
// Varbind names.
{"oid/no-leading-dot", marshal(oidName("1.3.6.1.2.1.1.5.0"))},
{"oid/empty", marshal(oidName(""))},
{"oid/single-arc", marshal(oidName(".1"))},
{"oid/two-arcs", marshal(oidName(".1.3"))},
{"oid/first-arc-2", marshal(oidName(".2.999.1"))},
{"oid/first-arc-3", marshal(oidName(".3.1"))},
{"oid/second-arc-40", marshal(oidName(".1.40"))},
{"oid/arc-max-uint32", marshal(oidName(".1.3.6.1.4.1.4294967295"))},
{"oid/arc-2^32", marshal(oidName(".1.3.6.1.4.1.4294967296"))},
{"oid/empty-arc", marshal(oidName(".1..3.6"))},
{"oid/trailing-dot", marshal(oidName(".1.3.6."))},
{"oid/letters", marshal(oidName(".1.3.abc"))},
{"oid/negative-arc", marshal(oidName(".1.3.-6"))},
{"oid/130-arcs", marshal(oidName(".1.3" + strings.Repeat(".129", 128)))},
{"oid/128-arcs", marshal(oidName(".1.3" + strings.Repeat(".1", 126)))},
{"oid/129-arcs", marshal(oidName(".1.3" + strings.Repeat(".1", 127)))},
{"oid/content-128", marshal(oidName(".1.3" + strings.Repeat(".129", 63) + ".1"))},
{"oid/first-packed-value-max-uint32", marshal(oidName(".2.4294967215"))},
{"oid/first-packed-value-over-uint32", marshal(oidName(".2.4294967216"))},
{"oid/second-arc-max-uint32", marshal(oidName(".2.4294967295"))},
{"oid/second-arc-over-uint32", marshal(oidName(".2.4294967296"))},
// v1 Trap.
{"v1-trap/basic", marshal(v1Trap(func(*SnmpTrap) {}))},
{"v1-trap/agent-address-empty", marshal(v1Trap(func(tr *SnmpTrap) { tr.AgentAddress = "" }))},
{"v1-trap/agent-address-ipv4-mapped", marshal(v1Trap(func(tr *SnmpTrap) { tr.AgentAddress = "::ffff:192.0.2.1" }))},
{"v1-trap/agent-address-ipv6", marshal(v1Trap(func(tr *SnmpTrap) { tr.AgentAddress = "2001:db8::1" }))},
{"v1-trap/agent-address-invalid", marshal(v1Trap(func(tr *SnmpTrap) { tr.AgentAddress = "not-an-ip" }))},
{"v1-trap/enterprise-empty", marshal(v1Trap(func(tr *SnmpTrap) { tr.Enterprise = "" }))},
{"v1-trap/generic-negative", marshal(v1Trap(func(tr *SnmpTrap) { tr.GenericTrap = -1 }))},
{"v1-trap/specific-max-int32", marshal(v1Trap(func(tr *SnmpTrap) { tr.SpecificTrap = math.MaxInt32 }))},
wideCase("v1-trap/generic-2^31", marshal(v1Trap(func(tr *SnmpTrap) { tr.GenericTrap = int(beyondInt32) }))),
wideCase("v1-trap/specific-2^31", marshal(v1Trap(func(tr *SnmpTrap) { tr.SpecificTrap = int(beyondInt32) }))),
{"v1-trap/timestamp-max-uint32", marshal(v1Trap(func(tr *SnmpTrap) { tr.Timestamp = math.MaxUint32 }))},
wideCase("v1-trap/timestamp-2^32", marshal(v1Trap(func(tr *SnmpTrap) { tr.Timestamp = uint(beyondUint32) }))),
{"v1-trap/in-v2c-message", marshal(edit(v1Trap(func(*SnmpTrap) {}), func(p *SnmpPacket) { p.Version = Version2c }))},
// SNMPv3.
{"v3/no-auth-no-priv/discovery", marshal(edit(v3(Reportable|NoAuthNoPriv, GetRequest, &UsmSecurityParameters{}), func(p *SnmpPacket) {
p.ContextEngineID, p.ContextName, p.Variables = "", "", nil
}))},
{"v3/no-auth-no-priv/get-request", marshal(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)))},
{"v3/no-auth-no-priv/msg-id-2^31", marshal(edit(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) { p.MsgID = 1 << 31 }))},
{"v3/no-auth-no-priv/engine-id-200", marshal(edit(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) {
p.SecurityParameters.(*UsmSecurityParameters).AuthoritativeEngineID = strings.Repeat("e", 200)
}))},
{"v3/no-auth-no-priv/user-name-200", marshal(edit(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) {
p.SecurityParameters.(*UsmSecurityParameters).UserName = strings.Repeat("u", 200)
}))},
{"v3/no-auth-no-priv/user-name-32", marshal(edit(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) {
p.SecurityParameters.(*UsmSecurityParameters).UserName = strings.Repeat("u", 32)
}))},
{"v3/no-auth-no-priv/user-name-33", marshal(edit(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) {
p.SecurityParameters.(*UsmSecurityParameters).UserName = strings.Repeat("u", 33)
}))},
{"v3/no-auth-no-priv/max-size-483", marshal(edit(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) { p.MsgMaxSize = 483 }))},
{"v3/no-auth-no-priv/max-size-484", marshal(edit(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) { p.MsgMaxSize = 484 }))},
{"v3/no-auth-no-priv/msg-id-max-int32", marshal(edit(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) { p.MsgID = math.MaxInt32 }))},
{"v3/no-auth-no-priv/reserved-flags", marshal(v3(NoAuthNoPriv|0xf8, GetRequest, codecUSM(t, NoAuth, NoPriv)))},
{"v3/no-auth-no-priv/v1-trap-pdu", marshal(edit(v3(NoAuthNoPriv, Trap, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) { p.SnmpTrap = trap }))},
{"v3/no-auth-no-priv/engine-boots-2^31", marshal(edit(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) {
p.SecurityParameters.(*UsmSecurityParameters).AuthoritativeEngineBoots = 1 << 31
}))},
{"v3/no-auth-no-priv/engine-time-2^31", marshal(edit(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) {
p.SecurityParameters.(*UsmSecurityParameters).AuthoritativeEngineTime = 1 << 31
}))},
{"v3/no-auth-no-priv/engine-boots-and-time-max-int32", marshal(edit(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) {
sp := p.SecurityParameters.(*UsmSecurityParameters)
sp.AuthoritativeEngineBoots, sp.AuthoritativeEngineTime = math.MaxInt32, math.MaxInt32
}))},
{"v3/no-auth-no-priv/max-size-1500", marshal(edit(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) { p.MsgMaxSize = 1500 }))},
{"v3/no-auth-no-priv/max-size-max-int32", marshal(edit(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) { p.MsgMaxSize = math.MaxInt32 }))},
{"v3/no-auth-no-priv/max-size-2^31", marshal(edit(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) { p.MsgMaxSize = 1 << 31 }))},
{"v3/no-auth-no-priv/security-model-200", marshal(edit(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) { p.SecurityModel = 200 }))},
{"v3/no-auth-no-priv/engine-boots-and-time-2^31", marshal(edit(v3(NoAuthNoPriv, GetRequest, codecUSM(t, NoAuth, NoPriv)), func(p *SnmpPacket) {
sp := p.SecurityParameters.(*UsmSecurityParameters)
sp.AuthoritativeEngineBoots, sp.AuthoritativeEngineTime = 1<<31, 1<<31+1
}))},
{"v3/no-auth-no-priv/report", marshal(v3(NoAuthNoPriv, Report, codecUSM(t, NoAuth, NoPriv)))},
{"v3/no-auth-no-priv/nil-security-parameters", marshal(v3(NoAuthNoPriv, GetRequest, nil))},
{"v3/auth-no-priv/md5", marshal(v3(AuthNoPriv, GetRequest, codecUSM(t, MD5, NoPriv)))},
{"v3/auth-no-priv/sha", marshal(v3(AuthNoPriv, GetRequest, codecUSM(t, SHA, NoPriv)))},
{"v3/auth-no-priv/sha224", marshal(v3(AuthNoPriv, GetRequest, codecUSM(t, SHA224, NoPriv)))},
{"v3/auth-no-priv/sha256", marshal(v3(AuthNoPriv, GetRequest, codecUSM(t, SHA256, NoPriv)))},
{"v3/auth-no-priv/sha384", marshal(v3(AuthNoPriv, GetRequest, codecUSM(t, SHA384, NoPriv)))},
{"v3/auth-no-priv/sha512", marshal(v3(AuthNoPriv, GetRequest, codecUSM(t, SHA512, NoPriv)))},
// Authentication keys of 80 octets, longer than the hash and the 64-octet
// HMAC block: refused, as any key of another size than the hash's.
{"v3/auth-no-priv/md5/key-80", marshal(edit(v3(AuthNoPriv, GetRequest, codecUSM(t, MD5, NoPriv)), func(p *SnmpPacket) {
p.SecurityParameters.(*UsmSecurityParameters).SecretKey = []byte(strings.Repeat("k", 80))
}))},
{"v3/auth-no-priv/sha/key-80", marshal(edit(v3(AuthNoPriv, GetRequest, codecUSM(t, SHA, NoPriv)), func(p *SnmpPacket) {
p.SecurityParameters.(*UsmSecurityParameters).SecretKey = []byte(strings.Repeat("k", 80))
}))},
{"v3/auth-no-priv/sha256/key-80", marshal(edit(v3(AuthNoPriv, GetRequest, codecUSM(t, SHA256, NoPriv)), func(p *SnmpPacket) {
p.SecurityParameters.(*UsmSecurityParameters).SecretKey = []byte(strings.Repeat("k", 80))
}))},
// A user name or engine ID that holds the octets of the zero
// placeholder keeps them: the digest goes into the field.
{"v3/auth-no-priv/md5/placeholder-in-user-name", marshal(edit(v3(AuthNoPriv, GetRequest, codecUSM(t, MD5, NoPriv)), func(p *SnmpPacket) {
p.SecurityParameters.(*UsmSecurityParameters).UserName = "\x04\x0c" + strings.Repeat("\x00", 12)
}))},
{"v3/auth-no-priv/md5/placeholder-in-engine-id", marshal(edit(v3(AuthNoPriv, GetRequest, codecUSM(t, MD5, NoPriv)), func(p *SnmpPacket) {
p.SecurityParameters.(*UsmSecurityParameters).AuthoritativeEngineID = "\x80\x00\x1f\x88\x04\x04\x0c" + strings.Repeat("\x00", 12)
}))},
{"v3/auth-no-priv/flags-without-keys", marshal(v3(AuthNoPriv, GetRequest, &UsmSecurityParameters{UserName: "codec-user"}))},
{"v3/auth-priv/sha-aes", marshal(v3(AuthPriv, GetRequest, withPacketSalt(codecUSM(t, SHA, AES))))},
{"v3/auth-priv/sha-aes192", marshal(v3(AuthPriv, GetRequest, withPacketSalt(codecUSM(t, SHA, AES192))))},
{"v3/auth-priv/sha-aes256c", marshal(v3(AuthPriv, GetRequest, withPacketSalt(codecUSM(t, SHA, AES256C))))},
{"v3/auth-priv/md5-des", marshal(v3(AuthPriv, GetRequest, withPacketSalt(codecUSM(t, MD5, DES))))},
{"v3/priv-without-auth/sha-aes", marshal(v3(AuthPriv&^AuthNoPriv, GetRequest, withPacketSalt(codecUSM(t, SHA, AES))))},
{"v3/auth-priv/sha-aes/without-salt", marshal(v3(AuthPriv, GetRequest, codecUSM(t, SHA, AES)))},
{"v3/no-auth-no-priv/20-varbinds", marshal(withVars(v3(NoAuthNoPriv, GetResponse, codecUSM(t, NoAuth, NoPriv)), hostVars(20)))},
{"v3/auth-no-priv/sha/20-varbinds", marshal(withVars(v3(AuthNoPriv, GetResponse, codecUSM(t, SHA, NoPriv)), hostVars(20)))},
{"v3/auth-priv/sha-aes/4-varbinds", marshal(withVars(v3(AuthPriv, GetResponse, withPacketSalt(codecUSM(t, SHA, AES))), hostVars(4)))},
{"v3/auth-priv/sha-aes/20-varbinds", marshal(withVars(v3(AuthPriv, GetResponse, withPacketSalt(codecUSM(t, SHA, AES))), hostVars(20)))},
{"v3/auth-priv/md5-des/4-varbinds", marshal(withVars(v3(AuthPriv, GetResponse, withPacketSalt(codecUSM(t, MD5, DES))), hostVars(4)))},
{"v3/auth-priv/md5-des/20-varbinds", marshal(withVars(v3(AuthPriv, GetResponse, withPacketSalt(codecUSM(t, MD5, DES))), hostVars(20)))},
{"v3/auth-priv/md5-des/without-salt", marshal(v3(AuthPriv, GetRequest, codecUSM(t, MD5, DES)))},
// SnmpEncodePacket builds the packet from the GoSNMP configuration.
{"encode-packet/v1/get-request", func() ([]byte, error) {
x := fixedIDs(&GoSNMP{Version: Version1, Community: "public"})
return x.SnmpEncodePacket(GetRequest, nullVar, 0, 0)
}},
{"encode-packet/v2c/getbulk-request", func() ([]byte, error) {
x := fixedIDs(&GoSNMP{Version: Version2c, Community: "public"})
return x.SnmpEncodePacket(GetBulkRequest, nullVar, 1, 10)
}},
{"encode-packet/v2c/getbulk-request/max-repetitions-max-uint32", func() ([]byte, error) {
x := fixedIDs(&GoSNMP{Version: Version2c, Community: "public"})
return x.SnmpEncodePacket(GetBulkRequest, nullVar, 0, math.MaxUint32)
}},
{"encode-packet/v3/auth-no-priv/sha", func() ([]byte, error) {
x := fixedIDs(&GoSNMP{
Version: Version3,
MsgFlags: AuthNoPriv,
SecurityModel: UserSecurityModel,
SecurityParameters: codecUSM(t, SHA, NoPriv),
ContextName: "codec-context",
})
return x.SnmpEncodePacket(GetRequest, nullVar, 0, 0)
}},
{"encode-packet/v3/auth-priv/sha-aes", func() ([]byte, error) {
x := fixedIDs(&GoSNMP{
Version: Version3,
MsgFlags: AuthPriv,
SecurityModel: UserSecurityModel,
SecurityParameters: codecUSM(t, SHA, AES),
ContextName: "codec-context",
})
return x.SnmpEncodePacket(GetRequest, nullVar, 0, 0)
}},
}, wide
}