forked from gosnmp/gosnmp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
v3_usm.go
1026 lines (890 loc) · 29 KB
/
v3_usm.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.
// 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"
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/des" //nolint:gosec
"crypto/hmac"
"crypto/md5" //nolint:gosec
crand "crypto/rand"
"crypto/sha1" //nolint:gosec
_ "crypto/sha256" // Register hash function #4 (SHA224), #5 (SHA256)
_ "crypto/sha512" // Register hash function #6 (SHA384), #7 (SHA512)
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"hash"
"strings"
"sync"
"sync/atomic"
)
// SnmpV3AuthProtocol describes the authentication protocol in use by an authenticated SnmpV3 connection.
type SnmpV3AuthProtocol uint8
// NoAuth, MD5, and SHA are implemented
const (
NoAuth SnmpV3AuthProtocol = 1
MD5 SnmpV3AuthProtocol = 2
SHA SnmpV3AuthProtocol = 3
SHA224 SnmpV3AuthProtocol = 4
SHA256 SnmpV3AuthProtocol = 5
SHA384 SnmpV3AuthProtocol = 6
SHA512 SnmpV3AuthProtocol = 7
)
//go:generate stringer -type=SnmpV3AuthProtocol
// HashType maps the AuthProtocol's hash type to an actual crypto.Hash object.
func (authProtocol SnmpV3AuthProtocol) HashType() crypto.Hash {
switch authProtocol {
default:
return crypto.MD5
case SHA:
return crypto.SHA1
case SHA224:
return crypto.SHA224
case SHA256:
return crypto.SHA256
case SHA384:
return crypto.SHA384
case SHA512:
return crypto.SHA512
}
}
//nolint:gochecknoglobals
var macVarbinds = [][]byte{
{},
{byte(OctetString), 0},
{byte(OctetString), 12,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0},
{byte(OctetString), 12,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0},
{byte(OctetString), 16,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0},
{byte(OctetString), 24,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0},
{byte(OctetString), 32,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0},
{byte(OctetString), 48,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0}}
// SnmpV3PrivProtocol is the privacy protocol in use by an private SnmpV3 connection.
type SnmpV3PrivProtocol uint8
// NoPriv, DES implemented, AES planned
// Changed: AES192, AES256, AES192C, AES256C added
const (
NoPriv SnmpV3PrivProtocol = 1
DES SnmpV3PrivProtocol = 2
AES SnmpV3PrivProtocol = 3
AES192 SnmpV3PrivProtocol = 4 // Blumenthal-AES192
AES256 SnmpV3PrivProtocol = 5 // Blumenthal-AES256
AES192C SnmpV3PrivProtocol = 6 // Reeder-AES192
AES256C SnmpV3PrivProtocol = 7 // Reeder-AES256
)
//go:generate stringer -type=SnmpV3PrivProtocol
// UsmSecurityParameters is an implementation of SnmpV3SecurityParameters for the UserSecurityModel
type UsmSecurityParameters struct {
mu sync.Mutex
// localAESSalt must be 64bit aligned to use with atomic operations.
localAESSalt uint64
localDESSalt uint32
AuthoritativeEngineID string
AuthoritativeEngineBoots uint32
AuthoritativeEngineTime uint32
UserName string
AuthenticationParameters string
PrivacyParameters []byte
AuthenticationProtocol SnmpV3AuthProtocol
PrivacyProtocol SnmpV3PrivProtocol
AuthenticationPassphrase string
PrivacyPassphrase string
SecretKey []byte
PrivacyKey []byte
Logger Logger
}
// Description logs authentication paramater information to the provided GoSNMP Logger
func (sp *UsmSecurityParameters) Description() string {
var sb strings.Builder
sb.WriteString("user=")
sb.WriteString(sp.UserName)
sb.WriteString(",engine=(")
sb.WriteString(hex.EncodeToString([]byte(sp.AuthoritativeEngineID)))
// sb.WriteString(sp.AuthoritativeEngineID)
sb.WriteString(")")
switch sp.AuthenticationProtocol {
case NoAuth:
sb.WriteString(",auth=noauth")
case MD5:
sb.WriteString(",auth=md5")
case SHA:
sb.WriteString(",auth=sha")
case SHA224:
sb.WriteString(",auth=sha224")
case SHA256:
sb.WriteString(",auth=sha256")
case SHA384:
sb.WriteString(",auth=sha384")
case SHA512:
sb.WriteString(",auth=sha512")
}
sb.WriteString(",authPass=")
sb.WriteString(sp.AuthenticationPassphrase)
switch sp.PrivacyProtocol {
case NoPriv:
sb.WriteString(",priv=NoPriv")
case DES:
sb.WriteString(",priv=DES")
case AES:
sb.WriteString(",priv=AES")
case AES192:
sb.WriteString(",priv=AES192")
case AES256:
sb.WriteString(",priv=AES256")
case AES192C:
sb.WriteString(",priv=AES192C")
case AES256C:
sb.WriteString(",priv=AES256C")
}
sb.WriteString(",privPass=")
sb.WriteString(sp.PrivacyPassphrase)
return sb.String()
}
// SafeString returns a logging safe (no secrets) string of the UsmSecurityParameters
func (sp *UsmSecurityParameters) SafeString() string {
return fmt.Sprintf("AuthoritativeEngineID:%s, AuthoritativeEngineBoots:%d, AuthoritativeEngineTimes:%d, UserName:%s, AuthenticationParameters:%s, PrivacyParameters:%v, AuthenticationProtocol:%s, PrivacyProtocol:%s",
sp.AuthoritativeEngineID,
sp.AuthoritativeEngineBoots,
sp.AuthoritativeEngineTime,
sp.UserName,
sp.AuthenticationParameters,
sp.PrivacyParameters,
sp.AuthenticationProtocol,
sp.PrivacyProtocol,
)
}
// Log logs security paramater information to the provided GoSNMP Logger
func (sp *UsmSecurityParameters) Log() {
sp.mu.Lock()
defer sp.mu.Unlock()
sp.Logger.Printf("SECURITY PARAMETERS:%s", sp.SafeString())
}
// Copy method for UsmSecurityParameters used to copy a SnmpV3SecurityParameters without knowing it's implementation
func (sp *UsmSecurityParameters) Copy() SnmpV3SecurityParameters {
sp.mu.Lock()
defer sp.mu.Unlock()
return &UsmSecurityParameters{AuthoritativeEngineID: sp.AuthoritativeEngineID,
AuthoritativeEngineBoots: sp.AuthoritativeEngineBoots,
AuthoritativeEngineTime: sp.AuthoritativeEngineTime,
UserName: sp.UserName,
AuthenticationParameters: sp.AuthenticationParameters,
PrivacyParameters: sp.PrivacyParameters,
AuthenticationProtocol: sp.AuthenticationProtocol,
PrivacyProtocol: sp.PrivacyProtocol,
AuthenticationPassphrase: sp.AuthenticationPassphrase,
PrivacyPassphrase: sp.PrivacyPassphrase,
SecretKey: sp.SecretKey,
PrivacyKey: sp.PrivacyKey,
localDESSalt: sp.localDESSalt,
localAESSalt: sp.localAESSalt,
Logger: sp.Logger,
}
}
func (sp *UsmSecurityParameters) getDefaultContextEngineID() string {
return sp.AuthoritativeEngineID
}
func (sp *UsmSecurityParameters) initSecurityKeys() error {
sp.mu.Lock()
defer sp.mu.Unlock()
return sp.initSecurityKeysNoLock()
}
func (sp *UsmSecurityParameters) initSecurityKeysNoLock() error {
var err error
if sp.AuthenticationProtocol > NoAuth && len(sp.SecretKey) == 0 {
sp.SecretKey, err = genlocalkey(sp.AuthenticationProtocol,
sp.AuthenticationPassphrase,
sp.AuthoritativeEngineID)
if err != nil {
return err
}
}
if sp.PrivacyProtocol > NoPriv && len(sp.PrivacyKey) == 0 {
switch sp.PrivacyProtocol {
// Changed: The Output of SHA1 is a 20 octets array, therefore for AES128 (16 octets) either key extension algorithm can be used.
case AES, AES192, AES256, AES192C, AES256C:
// Use abstract AES key localization algorithms.
sp.PrivacyKey, err = genlocalPrivKey(sp.PrivacyProtocol, sp.AuthenticationProtocol,
sp.PrivacyPassphrase,
sp.AuthoritativeEngineID)
if err != nil {
return err
}
default:
sp.PrivacyKey, err = genlocalkey(sp.AuthenticationProtocol,
sp.PrivacyPassphrase,
sp.AuthoritativeEngineID)
if err != nil {
return err
}
}
}
return nil
}
func (sp *UsmSecurityParameters) setSecurityParameters(in SnmpV3SecurityParameters) error {
var insp *UsmSecurityParameters
var err error
sp.mu.Lock()
defer sp.mu.Unlock()
if insp, err = castUsmSecParams(in); err != nil {
return err
}
if sp.AuthoritativeEngineID != insp.AuthoritativeEngineID {
sp.AuthoritativeEngineID = insp.AuthoritativeEngineID
sp.SecretKey = nil
sp.PrivacyKey = nil
err = sp.initSecurityKeysNoLock()
if err != nil {
return err
}
}
sp.AuthoritativeEngineBoots = insp.AuthoritativeEngineBoots
sp.AuthoritativeEngineTime = insp.AuthoritativeEngineTime
return nil
}
func (sp *UsmSecurityParameters) validate(flags SnmpV3MsgFlags) error {
securityLevel := flags & AuthPriv // isolate flags that determine security level
switch securityLevel {
case AuthPriv:
if sp.PrivacyProtocol <= NoPriv {
return fmt.Errorf("securityParameters.PrivacyProtocol is required")
}
fallthrough
case AuthNoPriv:
if sp.AuthenticationProtocol <= NoAuth {
return fmt.Errorf("securityParameters.AuthenticationProtocol is required")
}
fallthrough
case NoAuthNoPriv:
if sp.UserName == "" {
return fmt.Errorf("securityParameters.UserName is required")
}
default:
return fmt.Errorf("validate: MsgFlags must be populated with an appropriate security level")
}
if sp.PrivacyProtocol > NoPriv && len(sp.PrivacyKey) == 0 {
if sp.PrivacyPassphrase == "" {
return fmt.Errorf("securityParameters.PrivacyPassphrase is required when a privacy protocol is specified")
}
}
if sp.AuthenticationProtocol > NoAuth && len(sp.SecretKey) == 0 {
if sp.AuthenticationPassphrase == "" {
return fmt.Errorf("securityParameters.AuthenticationPassphrase is required when an authentication protocol is specified")
}
}
return nil
}
func (sp *UsmSecurityParameters) init(log Logger) error {
var err error
sp.Logger = log
switch sp.PrivacyProtocol {
case AES, AES192, AES256, AES192C, AES256C:
salt := make([]byte, 8)
_, err = crand.Read(salt)
if err != nil {
return fmt.Errorf("error creating a cryptographically secure salt: %w", err)
}
sp.localAESSalt = binary.BigEndian.Uint64(salt)
case DES:
salt := make([]byte, 4)
_, err = crand.Read(salt)
if err != nil {
return fmt.Errorf("error creating a cryptographically secure salt: %w", err)
}
sp.localDESSalt = binary.BigEndian.Uint32(salt)
}
return nil
}
func castUsmSecParams(secParams SnmpV3SecurityParameters) (*UsmSecurityParameters, error) {
s, ok := secParams.(*UsmSecurityParameters)
if !ok || s == nil {
return nil, fmt.Errorf("param SnmpV3SecurityParameters is not of type *UsmSecurityParameters")
}
return s, nil
}
var (
passwordKeyHashCache = make(map[string][]byte) //nolint:gochecknoglobals
passwordKeyHashMutex sync.RWMutex //nolint:gochecknoglobals
)
func hashPassword(hash hash.Hash, password string) ([]byte, error) {
if len(password) == 0 {
return []byte{}, errors.New("hashPassword: password is empty")
}
var pi int // password index
for i := 0; i < 1048576; i += 64 {
var chunk []byte
for e := 0; e < 64; e++ {
chunk = append(chunk, password[pi%len(password)])
pi++
}
if _, err := hash.Write(chunk); err != nil {
return []byte{}, err
}
}
hashed := hash.Sum(nil)
return hashed, nil
}
// Common passwordToKey algorithm, "caches" the result to avoid extra computation each reuse
func cachedPasswordToKey(hash hash.Hash, cacheKey string, password string) ([]byte, error) {
passwordKeyHashMutex.RLock()
value := passwordKeyHashCache[cacheKey]
passwordKeyHashMutex.RUnlock()
if value != nil {
return value, nil
}
hashed, err := hashPassword(hash, password)
if err != nil {
return nil, err
}
passwordKeyHashMutex.Lock()
passwordKeyHashCache[cacheKey] = hashed
passwordKeyHashMutex.Unlock()
return hashed, nil
}
func hMAC(hash crypto.Hash, cacheKey string, password string, engineID string) ([]byte, error) {
hashed, err := cachedPasswordToKey(hash.New(), cacheKey, password)
if err != nil {
return []byte{}, nil
}
local := hash.New()
_, err = local.Write(hashed)
if err != nil {
return []byte{}, err
}
_, err = local.Write([]byte(engineID))
if err != nil {
return []byte{}, err
}
_, err = local.Write(hashed)
if err != nil {
return []byte{}, err
}
final := local.Sum(nil)
return final, nil
}
func cacheKey(authProtocol SnmpV3AuthProtocol, passphrase string) string {
var cacheKey = make([]byte, 1+len(passphrase))
cacheKey = append(cacheKey, 'h'+byte(authProtocol))
cacheKey = append(cacheKey, []byte(passphrase)...)
return string(cacheKey)
}
// Extending the localized privacy key according to Reeder Key extension algorithm:
// https://tools.ietf.org/html/draft-reeder-snmpv3-usm-3dese
// Many vendors, including Cisco, use the 3DES key extension algorithm to extend the privacy keys that are too short when using AES,AES192 and AES256.
// Previously implemented in net-snmp and pysnmp libraries.
// Tested for AES128 and AES256
func extendKeyReeder(authProtocol SnmpV3AuthProtocol, password string, engineID string) ([]byte, error) {
var key []byte
var err error
key, err = hMAC(authProtocol.HashType(), cacheKey(authProtocol, password), password, engineID)
if err != nil {
return nil, err
}
newkey, err := hMAC(authProtocol.HashType(), cacheKey(authProtocol, string(key)), string(key), engineID)
return append(key, newkey...), err
}
// Extending the localized privacy key according to Blumenthal key extension algorithm:
// https://tools.ietf.org/html/draft-blumenthal-aes-usm-04#page-7
// Not many vendors use this algorithm.
// Previously implemented in the net-snmp and pysnmp libraries.
// TODO: Not tested
func extendKeyBlumenthal(authProtocol SnmpV3AuthProtocol, password string, engineID string) ([]byte, error) {
var key []byte
var err error
key, err = hMAC(authProtocol.HashType(), cacheKey(authProtocol, password), password, engineID)
if err != nil {
return nil, err
}
newkey := authProtocol.HashType().New()
_, _ = newkey.Write(key)
return append(key, newkey.Sum(nil)...), err
}
// Changed: New function to calculate the Privacy Key for abstract AES
func genlocalPrivKey(privProtocol SnmpV3PrivProtocol, authProtocol SnmpV3AuthProtocol, password string, engineID string) ([]byte, error) {
var keylen int
var localPrivKey []byte
var err error
switch privProtocol {
case AES, DES:
keylen = 16
case AES192, AES192C:
keylen = 24
case AES256, AES256C:
keylen = 32
}
switch privProtocol {
case AES, AES192C, AES256C:
localPrivKey, err = extendKeyReeder(authProtocol, password, engineID)
case AES192, AES256:
localPrivKey, err = extendKeyBlumenthal(authProtocol, password, engineID)
default:
localPrivKey, err = genlocalkey(authProtocol, password, engineID)
}
if err != nil {
return nil, err
}
if len(localPrivKey) < keylen {
return []byte{}, fmt.Errorf("genlocalPrivKey: privProtocol: %v len(localPrivKey): %d, keylen: %d",
privProtocol, len(localPrivKey), keylen)
}
return localPrivKey[:keylen], nil
}
func genlocalkey(authProtocol SnmpV3AuthProtocol, passphrase string, engineID string) ([]byte, error) {
var secretKey []byte
var err error
secretKey, err = hMAC(authProtocol.HashType(), cacheKey(authProtocol, passphrase), passphrase, engineID)
if err != nil {
return []byte{}, err
}
return secretKey, nil
}
// http://tools.ietf.org/html/rfc2574#section-8.1.1.1
// localDESSalt needs to be incremented on every packet.
func (sp *UsmSecurityParameters) usmAllocateNewSalt() interface{} {
sp.mu.Lock()
defer sp.mu.Unlock()
var newSalt interface{}
switch sp.PrivacyProtocol {
case AES, AES192, AES256, AES192C, AES256C:
newSalt = atomic.AddUint64(&(sp.localAESSalt), 1)
default:
newSalt = atomic.AddUint32(&(sp.localDESSalt), 1)
}
return newSalt
}
func (sp *UsmSecurityParameters) usmSetSalt(newSalt interface{}) error {
sp.mu.Lock()
defer sp.mu.Unlock()
switch sp.PrivacyProtocol {
case AES, AES192, AES256, AES192C, AES256C:
aesSalt, ok := newSalt.(uint64)
if !ok {
return fmt.Errorf("salt provided to usmSetSalt is not the correct type for the AES privacy protocol")
}
var salt = make([]byte, 8)
binary.BigEndian.PutUint64(salt, aesSalt)
sp.PrivacyParameters = salt
default:
desSalt, ok := newSalt.(uint32)
if !ok {
return fmt.Errorf("salt provided to usmSetSalt is not the correct type for the DES privacy protocol")
}
var salt = make([]byte, 8)
binary.BigEndian.PutUint32(salt, sp.AuthoritativeEngineBoots)
binary.BigEndian.PutUint32(salt[4:], desSalt)
sp.PrivacyParameters = salt
}
return nil
}
func (sp *UsmSecurityParameters) initPacket(packet *SnmpPacket) error {
// http://tools.ietf.org/html/rfc2574#section-8.1.1.1
// localDESSalt needs to be incremented on every packet.
newSalt := sp.usmAllocateNewSalt()
if packet.MsgFlags&AuthPriv > AuthNoPriv {
s, err := castUsmSecParams(packet.SecurityParameters)
if err != nil {
return err
}
return s.usmSetSalt(newSalt)
}
return nil
}
func (sp *UsmSecurityParameters) discoveryRequired() *SnmpPacket {
if sp.AuthoritativeEngineID == "" {
var emptyPdus []SnmpPDU
// send blank packet to discover authoriative engine ID/boots/time
blankPacket := &SnmpPacket{
Version: Version3,
MsgFlags: Reportable | NoAuthNoPriv,
SecurityModel: UserSecurityModel,
SecurityParameters: &UsmSecurityParameters{Logger: sp.Logger},
PDUType: GetRequest,
Logger: sp.Logger,
Variables: emptyPdus,
}
return blankPacket
}
return nil
}
func (sp *UsmSecurityParameters) calcPacketDigest(packet []byte) ([]byte, error) {
return calcPacketDigest(packet, sp)
}
// calcPacketDigest calculate authenticate digest for incoming messages (TRAP or
// INFORM).
// Support MD5, SHA1, SHA224, SHA256, SHA384, SHA512 protocols
func calcPacketDigest(packetBytes []byte, secParams *UsmSecurityParameters) ([]byte, error) {
var digest []byte
var err error
switch secParams.AuthenticationProtocol {
case MD5, SHA:
digest, err = digestRFC3414(
secParams.AuthenticationProtocol,
packetBytes,
secParams.SecretKey)
case SHA224, SHA256, SHA384, SHA512:
digest, err = digestRFC7860(
secParams.AuthenticationProtocol,
packetBytes,
secParams.SecretKey)
}
return digest, err
}
// digestRFC7860 calculate digest for incoming messages using HMAC-SHA2 protcols
// according to RFC7860 4.2.2
func digestRFC7860(h SnmpV3AuthProtocol, packet []byte, authKey []byte) ([]byte, error) {
mac := hmac.New(h.HashType().New, authKey)
_, err := mac.Write(packet)
if err != nil {
return []byte{}, err
}
msgDigest := mac.Sum(nil)
return msgDigest, nil
}
// digestRFC3414 calculate digest for incoming messages using MD5 or SHA1
// according to RFC3414 6.3.2 and 7.3.2
func digestRFC3414(h SnmpV3AuthProtocol, packet []byte, authKey []byte) ([]byte, error) {
var extkey [64]byte
var err error
var k1, k2 [64]byte
var h1, h2 hash.Hash
copy(extkey[:], authKey)
switch h {
case MD5:
h1 = md5.New() //nolint:gosec
h2 = md5.New() //nolint:gosec
case SHA:
h1 = sha1.New() //nolint:gosec
h2 = sha1.New() //nolint:gosec
}
for i := 0; i < 64; i++ {
k1[i] = extkey[i] ^ 0x36
k2[i] = extkey[i] ^ 0x5c
}
_, err = h1.Write(k1[:])
if err != nil {
return []byte{}, err
}
_, err = h1.Write(packet)
if err != nil {
return []byte{}, err
}
d1 := h1.Sum(nil)
_, err = h2.Write(k2[:])
if err != nil {
return []byte{}, err
}
_, err = h2.Write(d1)
if err != nil {
return []byte{}, err
}
return h2.Sum(nil)[:12], nil
}
func (sp *UsmSecurityParameters) authenticate(packet []byte) error {
var msgDigest []byte
var err error
if msgDigest, err = sp.calcPacketDigest(packet); err != nil {
return err
}
idx := bytes.Index(packet, macVarbinds[sp.AuthenticationProtocol])
if idx < 0 {
return fmt.Errorf("unable to locate the position in packet to write authentication key")
}
copy(packet[idx+2:idx+len(macVarbinds[sp.AuthenticationProtocol])], msgDigest)
return nil
}
// determine whether a message is authentic
func (sp *UsmSecurityParameters) isAuthentic(packetBytes []byte, packet *SnmpPacket) (bool, error) {
var msgDigest []byte
var packetSecParams *UsmSecurityParameters
var err error
if packetSecParams, err = castUsmSecParams(packet.SecurityParameters); err != nil {
return false, err
}
// TODO: investigate call chain to determine if this is really the best spot for this
if msgDigest, err = calcPacketDigest(packetBytes, packetSecParams); err != nil {
return false, err
}
for k, v := range []byte(packetSecParams.AuthenticationParameters) {
if msgDigest[k] != v {
return false, nil
}
}
return true, nil
}
func (sp *UsmSecurityParameters) encryptPacket(scopedPdu []byte) ([]byte, error) {
var b []byte
switch sp.PrivacyProtocol {
case AES, AES192, AES256, AES192C, AES256C:
var iv [16]byte
binary.BigEndian.PutUint32(iv[:], sp.AuthoritativeEngineBoots)
binary.BigEndian.PutUint32(iv[4:], sp.AuthoritativeEngineTime)
copy(iv[8:], sp.PrivacyParameters)
// aes.NewCipher(sp.PrivacyKey[:16]) changed to aes.NewCipher(sp.PrivacyKey)
block, err := aes.NewCipher(sp.PrivacyKey)
if err != nil {
return nil, err
}
stream := cipher.NewCFBEncrypter(block, iv[:])
ciphertext := make([]byte, len(scopedPdu))
stream.XORKeyStream(ciphertext, scopedPdu)
pduLen, err := marshalLength(len(ciphertext))
if err != nil {
return nil, err
}
b = append([]byte{byte(OctetString)}, pduLen...)
scopedPdu = append(b, ciphertext...) //nolint:gocritic
default:
preiv := sp.PrivacyKey[8:]
var iv [8]byte
for i := 0; i < len(iv); i++ {
iv[i] = preiv[i] ^ sp.PrivacyParameters[i]
}
block, err := des.NewCipher(sp.PrivacyKey[:8]) //nolint:gosec
if err != nil {
return nil, err
}
mode := cipher.NewCBCEncrypter(block, iv[:])
pad := make([]byte, des.BlockSize-len(scopedPdu)%des.BlockSize)
scopedPdu = append(scopedPdu, pad...)
ciphertext := make([]byte, len(scopedPdu))
mode.CryptBlocks(ciphertext, scopedPdu)
pduLen, err := marshalLength(len(ciphertext))
if err != nil {
return nil, err
}
b = append([]byte{byte(OctetString)}, pduLen...)
scopedPdu = append(b, ciphertext...) //nolint:gocritic
}
return scopedPdu, nil
}
func (sp *UsmSecurityParameters) decryptPacket(packet []byte, cursor int) ([]byte, error) {
_, cursorTmp, err := parseLength(packet[cursor:])
if err != nil {
return nil, err
}
cursorTmp += cursor
if cursorTmp > len(packet) {
return nil, errors.New("error decrypting ScopedPDU: truncated packet")
}
switch sp.PrivacyProtocol {
case AES, AES192, AES256, AES192C, AES256C:
var iv [16]byte
binary.BigEndian.PutUint32(iv[:], sp.AuthoritativeEngineBoots)
binary.BigEndian.PutUint32(iv[4:], sp.AuthoritativeEngineTime)
copy(iv[8:], sp.PrivacyParameters)
block, err := aes.NewCipher(sp.PrivacyKey)
if err != nil {
return nil, err
}
stream := cipher.NewCFBDecrypter(block, iv[:])
plaintext := make([]byte, len(packet[cursorTmp:]))
stream.XORKeyStream(plaintext, packet[cursorTmp:])
copy(packet[cursor:], plaintext)
packet = packet[:cursor+len(plaintext)]
default:
if len(packet[cursorTmp:])%des.BlockSize != 0 {
return nil, errors.New("error decrypting ScopedPDU: not multiple of des block size")
}
preiv := sp.PrivacyKey[8:]
var iv [8]byte
for i := 0; i < len(iv); i++ {
iv[i] = preiv[i] ^ sp.PrivacyParameters[i]
}
block, err := des.NewCipher(sp.PrivacyKey[:8]) //nolint:gosec
if err != nil {
return nil, err
}
mode := cipher.NewCBCDecrypter(block, iv[:])
plaintext := make([]byte, len(packet[cursorTmp:]))
mode.CryptBlocks(plaintext, packet[cursorTmp:])
copy(packet[cursor:], plaintext)
// truncate packet to remove extra space caused by the
// octetstring/length header that was just replaced
packet = packet[:cursor+len(plaintext)]
}
return packet, nil
}
// marshal a snmp version 3 security parameters field for the User Security Model
func (sp *UsmSecurityParameters) marshal(flags SnmpV3MsgFlags) ([]byte, error) {
var buf bytes.Buffer
var err error
// msgAuthoritativeEngineID
buf.Write([]byte{byte(OctetString), byte(len(sp.AuthoritativeEngineID))})
buf.WriteString(sp.AuthoritativeEngineID)
// msgAuthoritativeEngineBoots
msgAuthoritativeEngineBoots, err := marshalUint32(sp.AuthoritativeEngineBoots)
if err != nil {
return nil, err
}
buf.Write([]byte{byte(Integer), byte(len(msgAuthoritativeEngineBoots))})
buf.Write(msgAuthoritativeEngineBoots)
// msgAuthoritativeEngineTime
msgAuthoritativeEngineTime, err := marshalUint32(sp.AuthoritativeEngineTime)
if err != nil {
return nil, err
}
buf.Write([]byte{byte(Integer), byte(len(msgAuthoritativeEngineTime))})
buf.Write(msgAuthoritativeEngineTime)
// msgUserName
buf.Write([]byte{byte(OctetString), byte(len(sp.UserName))})
buf.WriteString(sp.UserName)
// msgAuthenticationParameters
if flags&AuthNoPriv > 0 {
buf.Write(macVarbinds[sp.AuthenticationProtocol])
} else {
buf.Write([]byte{byte(OctetString), 0})
}
// msgPrivacyParameters
if flags&AuthPriv > AuthNoPriv {
privlen, err2 := marshalLength(len(sp.PrivacyParameters))
if err2 != nil {
return nil, err2
}
buf.Write([]byte{byte(OctetString)})
buf.Write(privlen)
buf.Write(sp.PrivacyParameters)
} else {
buf.Write([]byte{byte(OctetString), 0})
}
// wrap security parameters in a sequence
paramLen, err := marshalLength(buf.Len())
if err != nil {
return nil, err
}
tmpseq := append([]byte{byte(Sequence)}, paramLen...)
tmpseq = append(tmpseq, buf.Bytes()...)
return tmpseq, nil
}
func (sp *UsmSecurityParameters) unmarshal(flags SnmpV3MsgFlags, packet []byte, cursor int) (int, error) {
var err error
if PDUType(packet[cursor]) != Sequence {
return 0, errors.New("error parsing SNMPV3 User Security Model parameters")
}
_, cursorTmp, err := parseLength(packet[cursor:])
if err != nil {
return 0, err
}
cursor += cursorTmp
if cursorTmp > len(packet) {
return 0, errors.New("error parsing SNMPV3 User Security Model parameters: truncated packet")
}
rawMsgAuthoritativeEngineID, count, err := parseRawField(sp.Logger, packet[cursor:], "msgAuthoritativeEngineID")
if err != nil {
return 0, fmt.Errorf("error parsing SNMPV3 User Security Model msgAuthoritativeEngineID: %w", err)
}
cursor += count
if AuthoritativeEngineID, ok := rawMsgAuthoritativeEngineID.(string); ok {
if sp.AuthoritativeEngineID != AuthoritativeEngineID {
sp.AuthoritativeEngineID = AuthoritativeEngineID
sp.SecretKey = nil
sp.PrivacyKey = nil
sp.Logger.Printf("Parsed authoritativeEngineID %0x", []byte(AuthoritativeEngineID))
err = sp.initSecurityKeysNoLock()
if err != nil {
return 0, err
}
}
}
rawMsgAuthoritativeEngineBoots, count, err := parseRawField(sp.Logger, packet[cursor:], "msgAuthoritativeEngineBoots")
if err != nil {
return 0, fmt.Errorf("error parsing SNMPV3 User Security Model msgAuthoritativeEngineBoots: %w", err)
}
cursor += count
if AuthoritativeEngineBoots, ok := rawMsgAuthoritativeEngineBoots.(int); ok {
sp.AuthoritativeEngineBoots = uint32(AuthoritativeEngineBoots)
sp.Logger.Printf("Parsed authoritativeEngineBoots %d", AuthoritativeEngineBoots)
}
rawMsgAuthoritativeEngineTime, count, err := parseRawField(sp.Logger, packet[cursor:], "msgAuthoritativeEngineTime")
if err != nil {
return 0, fmt.Errorf("error parsing SNMPV3 User Security Model msgAuthoritativeEngineTime: %w", err)
}
cursor += count
if AuthoritativeEngineTime, ok := rawMsgAuthoritativeEngineTime.(int); ok {
sp.AuthoritativeEngineTime = uint32(AuthoritativeEngineTime)
sp.Logger.Printf("Parsed authoritativeEngineTime %d", AuthoritativeEngineTime)
}
rawMsgUserName, count, err := parseRawField(sp.Logger, packet[cursor:], "msgUserName")
if err != nil {
return 0, fmt.Errorf("error parsing SNMPV3 User Security Model msgUserName: %w", err)
}
cursor += count
if msgUserName, ok := rawMsgUserName.(string); ok {
sp.UserName = msgUserName
sp.Logger.Printf("Parsed userName %s", msgUserName)
}
rawMsgAuthParameters, count, err := parseRawField(sp.Logger, packet[cursor:], "msgAuthenticationParameters")
if err != nil {
return 0, fmt.Errorf("error parsing SNMPV3 User Security Model msgAuthenticationParameters: %w", err)
}
if msgAuthenticationParameters, ok := rawMsgAuthParameters.(string); ok {
sp.AuthenticationParameters = msgAuthenticationParameters
sp.Logger.Printf("Parsed authenticationParameters %s", msgAuthenticationParameters)
}
// blank msgAuthenticationParameters to prepare for authentication check later
if flags&AuthNoPriv > 0 {