-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.go
1637 lines (1500 loc) · 45.9 KB
/
models.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
package tlsmodel
import (
"bytes"
"crypto/dsa"
"crypto/ecdsa"
"crypto/rsa"
"crypto/tls"
cryptotls "crypto/tls"
"crypto/x509"
"encoding/gob"
"encoding/json"
"fmt"
"log"
"math/big"
"sort"
"strconv"
"strings"
"time"
tlsdefs "github.com/adedayo/tls-definitions"
)
var (
//tls13KeyExchange is a constant to identify a key exchange or MAC/PRF in a TLS3 cipher
tls13KeyExchange = "TLSv1.3"
//NkxErrorMessage error message
NkxErrorMessage = "Not a key exchange message"
)
//CipherConfig extracts the important elements of a Ciphersuit based on its name
type CipherConfig struct {
CipherID uint16
Cipher string
KeyExchange string
Authentication string
IsExport bool
SupportsForwardSecrecy bool
Encryption string
MACPRF string //MAC (TLS <=1.1) or PseudoRandomFunction (TLS >= 1.2)
}
//IsAuthenticated returns whether the cipher supports authentication
func (cc *CipherConfig) IsAuthenticated() bool {
return !(cc.Authentication == "NULL" || cc.Authentication == "anon")
}
func rsaPerformanceMultiplier(keyLength int) int {
switch keyLength {
case 1024:
return 2
case 2048:
return 4
case 3072:
return 8
default:
return 10
}
}
func dhPerformanceMultiplier(keyLength int) int {
switch keyLength {
case 1024:
return 1
case 2048:
return 2
case 3072:
return 3
default:
return 10
}
}
func (cc *CipherConfig) getKXPerfMultiplier(config CipherConfigParameters) int {
if cc.usesRSAKeyExchange() {
return rsaPerformanceMultiplier(config.RSABitLength)
}
if cc.usesDHKeyExchange() {
return dhPerformanceMultiplier(config.SupportedGroupStrength)
}
return 10
}
func (cc *CipherConfig) getKXPerf(config CipherConfigParameters) int {
switch cc.KeyExchange {
case "NULL":
return 1
case "ECDH":
return 2 * cc.getKXPerfMultiplier(config)
case "ECDHE":
return 3 * cc.getKXPerfMultiplier(config)
case "RSA":
return 4 * cc.getKXPerfMultiplier(config)
case "DH":
return 5 * cc.getKXPerfMultiplier(config)
case "DHE":
return 6 * cc.getKXPerfMultiplier(config)
case "KRB5": //from here is arbitrary - don't care
return 100
case "PSK":
return 100
case "ECCPWD":
return 100
case "SRP":
return 100
}
if strings.Contains(cc.Cipher, "SCSV") {
//these are signalling ciphers just return a large multiplier
return 100
}
return -1
}
func (cc *CipherConfig) getAuthPerf() int {
switch cc.Authentication {
case "anon":
return 1
case "NULL":
return 1
case "ECDSA":
return 2
case "SHA":
return 3
case "RSA":
return 4
case "DHE":
return 5
case "DSS": //from here is arbitrary - don't care
return 10
case "PSK":
return 10
case "KRB5":
return 10
case "ECCPWD":
return 10
case "SRP":
return 10
}
if strings.Contains(cc.Cipher, "SCSV") {
//these are signalling ciphers just return a large multiplier
return 10
}
return -1
}
func (cc *CipherConfig) getMACPRFPerf() int {
switch cc.MACPRF {
case "NULL":
return 1
case "MD5":
return 2
case "SHA":
return 3
case "SHA256":
return 4
case "SHA384":
return 5
}
if strings.Contains(cc.Cipher, "SCSV") {
//these are signalling ciphers just return a large multiplier
return 10
}
return -1
}
func (cc *CipherConfig) getEncAlg() string {
alg := strings.Split(cc.Encryption, "_")
switch alg[0] {
case "NULL":
return "NULL"
case "AES":
return "AES"
case "CAMELLIA":
return "CAMELLIA"
case "DES":
return "DES"
case "CHACHA20":
return "CHACHA20"
case "DES40":
return "DES40"
case "IDEA":
return "IDEA"
case "ARIA":
return "ARIA"
case "RC4":
return "RC4"
case "RC2":
return "RC2"
case "SEED":
return "SEED"
case "3DES":
if len(alg) > 1 && alg[1] == "EDE" {
return "3DES_EDE"
}
return "NA"
}
if strings.Contains(cc.Cipher, "SCSV") {
//these are signalling ciphers just return a large multiplier
return "NA"
}
return "NA"
}
func (cc *CipherConfig) getEncAlgPerf() int {
switch cc.getEncAlg() {
case "NULL":
return 1
case "AES":
return 2
case "RC2":
return 3
case "RC4":
return 3
case "CAMELLIA":
return 4
case "CHACHA20":
return 4
case "SEED":
return 5
case "DES40":
return 6
case "DES":
return 6
case "3DES_EDE":
return 7
case "ARIA": //from here is arbitrary - don't care
return 10
case "IDEA":
return 10
}
if strings.Contains(cc.Cipher, "SCSV") {
//these are signalling ciphers just return a large multiplier
return 10
}
return -1
}
func (cc *CipherConfig) getEncKeyPerf() int {
switch cc.GetEncryptionKeyLength() {
case 0:
return 1
case 40:
return 2
case 56:
return 3
case 112:
return 4
case 128:
return 5
case 256:
return 6
}
if strings.Contains(cc.Cipher, "SCSV") {
//these are signalling ciphers just return a large multiplier
return 10
}
return -1
}
func (cc *CipherConfig) getEncMode() string {
if strings.Contains(cc.Encryption, "CBC") {
return "CBC"
}
if strings.Contains(cc.Encryption, "CCM_8") {
return "CCM_8"
}
if strings.Contains(cc.Encryption, "RC4") {
return "RC4"
}
mode := strings.Split(cc.Encryption, "_")
switch mode[len(mode)-1] {
case "GCM":
return "GCM"
case "CBC":
return "CBC"
case "CCM":
return "CCM"
case "MD5":
return "MD5"
case "NULL":
return "NULL"
case "POLY1305":
return "POLY1305"
}
return mode[len(mode)-1]
}
func (cc *CipherConfig) getEncModePerf() int {
switch cc.getEncMode() {
case "NULL":
return 1
case "GCM":
return 2
case "MD5":
return 3
case "RC4":
return 3
case "POLY1305":
return 4
case "CCM":
return 4
case "CCM_8":
return 4
case "CBC":
return 5
}
if strings.Contains(cc.Cipher, "SCSV") {
//these are signalling ciphers just return a large multiplier
return 10
}
return -1
}
//GetEncryptionKeyLength returns the effective key lengths of encryption algorithms used in the cipher
//See https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r4.pdf for details
func (cc *CipherConfig) GetEncryptionKeyLength() int {
kl := -1 //key length
enc := cc.Encryption
switch {
case enc == "NULL" || cc.Cipher == "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" || cc.Cipher == "TLS_FALLBACK_SCSV":
kl = 0
case strings.Contains(enc, "3DES"):
kl = 112
case strings.Contains(enc, "DES40") || strings.Contains(enc, "CBC_40"):
kl = 40
case enc == "DES_CBC":
kl = 56
case enc == "SEED_CBC" || enc == "IDEA_CBC": //see https://tools.ietf.org/html/rfc4269 for SEED.
kl = 128
case enc == "CHACHA20_POLY1305": //see https://tools.ietf.org/html/rfc7539#section-4
kl = 256
case len(strings.Split(enc, "_")) >= 2:
k := strings.Split(enc, "_")[1]
kk, err := strconv.Atoi(k)
if err != nil {
kl = -1
} else {
kl = kk
}
}
return kl
}
//GetKeyExchangeKeyLength returns the key length indicated by the cipher
func (cc *CipherConfig) GetKeyExchangeKeyLength(cipher, protocol uint16, scan ScanResult) int {
kl := -1
kx := cc.KeyExchange
switch {
case kx == "NULL":
kl = 0
case cc.Authentication == "anon":
kl = 0
case kx == "RSA" || (cc.Authentication == "RSA" && strings.Contains(kx, "DH") && func() bool {
//deal with DH ciphers that use RSA for key exchange
ex, ok := scan.KeyExchangeByProtocolByCipher[protocol]
if ok {
if _, ok2 := ex[cipher]; !ok2 { //ensure that the cipher does not actually exchange keys
return true
}
}
return false
}()):
if c, ok := scan.CertificatesPerProtocol[protocol]; ok {
certs, err := c.GetCertificates()
if err == nil && len(certs) > 0 && certs[0].PublicKeyAlgorithm.String() == "RSA" {
if pub, ok := certs[0].PublicKey.(*rsa.PublicKey); ok {
kl = pub.N.BitLen()
}
}
}
case cc.Authentication == "RSA" && strings.HasPrefix(kx, "DH"):
if ex, ok := scan.KeyExchangeByProtocolByCipher[protocol]; ok {
if kex, ok2 := ex[cipher]; ok2 { // there is a key exchange data
if key := kex.Key; len(key) > 1 {
length := int(key[0])<<8 | int(key[1])
kxch := key[2 : 2+length]
Public := new(big.Int).SetBytes(kxch)
return Public.BitLen()
}
}
}
case strings.Contains(kx, "ECDH"): // see https://www.ietf.org/rfc/rfc5480.txt and pp 133 https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar3.pdf for comparable strength
if ex, ok := scan.KeyExchangeByProtocolByCipher[protocol]; ok {
if kex, ok := ex[cipher]; ok {
if key := kex.Key; len(key) > 2 {
cid := uint16(key[1])<<8 | uint16(key[2])
if k, ok := tlsdefs.SupportedGroupStrength[cid]; ok {
kl = k
}
}
}
}
case strings.Contains(kx, tls13KeyExchange):
if ex, ok := scan.KeyExchangeByProtocolByCipher[protocol]; ok {
if kex, ok := ex[cipher]; ok {
if cid := uint16(kex.Group); cid != 0 {
if k, ok := tlsdefs.SupportedGroupStrength[cid]; ok {
kl = k
}
}
}
}
}
return kl
}
//getContextFreeKeyExchangeKeyLength returns the key length indicated by the cipher and key exchange config
func (cc *CipherConfig) getContextFreeKeyExchangeKeyLength(config CipherConfigParameters) int {
if cc.KeyExchange == "NULL" {
return 0
}
if cc.usesRSAKeyExchange() {
return config.RSABitLength
}
if cc.usesDHKeyExchange() {
return config.SupportedGroupStrength
}
return -1
}
func (cc *CipherConfig) usesRSAKeyExchange() bool {
kx := cc.KeyExchange
if kx == "RSA" || (cc.Authentication == "RSA" && strings.Contains(kx, "DH")) {
return true
}
return false
}
func (cc *CipherConfig) usesDHKeyExchange() bool {
if cc.Authentication != "RSA" && strings.Contains(cc.KeyExchange, "DH") {
return true
}
return false
}
//ComputeContextFreeMetric calculates interesting metrics about the cipher
func (cc *CipherConfig) ComputeContextFreeMetric(config CipherConfigParameters) (metric CipherMetrics) {
metric.KeyExchangeStrength = mapKeyExchangeKeylengthToScore(cc.getContextFreeKeyExchangeKeyLength(config))
metric.EncryptionKeyStrength = mapEncKeyLengthToScore(cc.GetEncryptionKeyLength())
if cc.IsAuthenticated() {
metric.Authentication = 100
}
metric.MacPRF = cc.GetMACPRFStrength()
metric.Performance = cc.getPerformanceMetric(config)
if cc.SupportsForwardSecrecy {
metric.ForwardSecrecy = 100
}
metric.ConfigParams = config
metric.CipherConfig = *cc
metric.OverallScore = (10*metric.Authentication + 30*metric.ForwardSecrecy + 10*metric.KeyExchangeStrength +
40*metric.EncryptionKeyStrength + 10*metric.MacPRF) / 100
return
}
func (cc *CipherConfig) getPerformanceMetric(config CipherConfigParameters) int {
return ((cc.getKXPerf(config)) * cc.getAuthPerf() * cc.getEncAlgPerf() * cc.getEncKeyPerf() *
cc.getEncModePerf() * cc.getMACPRFPerf())
}
//GetMACPRFStrength returns the relative strength of the MAC/PRF algorithm
func (cc *CipherConfig) GetMACPRFStrength() int {
if strings.Contains(cc.Cipher, "SCSV") {
return 0
}
strength := -1
switch cc.MACPRF {
case "SHA384":
strength = 100
case "SHA256":
strength = 90
case "SHA":
strength = 50
case "MD5":
strength = 20
case "NULL":
strength = 0
default:
strength = -1
}
return strength
}
//EnumerateCipherMetrics enumerates metrics for ciphers along multiple config axes
func EnumerateCipherMetrics() (metrics []CipherMetrics) {
strengthToSupportedGroups := make(map[int][]string)
for nc, kx := range tlsdefs.SupportedGroupStrength {
if kx >= 0 && kx == 3072 {
if ncs, present := strengthToSupportedGroups[kx]; present {
strengthToSupportedGroups[kx] = append(ncs, tlsdefs.SupportedGroups[nc])
} else {
strengthToSupportedGroups[kx] = []string{tlsdefs.SupportedGroups[nc]}
}
}
}
// RSALengths := []int{1024, 2048, 3072}
RSALengths := []int{2048}
rsaParams := []CipherConfigParameters{}
for _, rsa := range RSALengths {
rsaParams = append(rsaParams, CipherConfigParameters{
RSABitLength: rsa,
})
}
dheParams := []CipherConfigParameters{}
for kx := range strengthToSupportedGroups {
dheParams = append(dheParams, CipherConfigParameters{
SupportedGroupStrength: kx,
SupportedGroups: strengthToSupportedGroups[kx],
})
}
ccs := []CipherConfig{}
dummyConfig := CipherConfigParameters{}
for c := range tlsdefs.CipherSuiteMap {
if cc, err := GetCipherConfig(c); err == nil {
ccs = append(ccs, cc)
}
}
for _, cc := range ccs {
if cc.usesRSAKeyExchange() {
for _, param := range rsaParams {
m := cc.ComputeContextFreeMetric(param)
metrics = append(metrics, m)
}
continue
}
if cc.usesDHKeyExchange() {
for _, param := range dheParams {
m := cc.ComputeContextFreeMetric(param)
metrics = append(metrics, m)
}
continue
}
m := cc.ComputeContextFreeMetric(dummyConfig)
metrics = append(metrics, m)
}
sort.Sort(CipherMetricsSorter(metrics))
return
}
//CipherConfigParameters contains information about Parameters for determining the key length of key exchange algorithms and other cipher parameters
type CipherConfigParameters struct {
RSABitLength int //The RSA key from the certificate
SupportedGroupStrength int
SupportedGroups []string //The Supported Groups that have the indicated strength
}
//CipherMetrics are various metrics of interest to compare ciphers as the bases for various desirable property ordering such as security and performance
type CipherMetrics struct {
Authentication int
KeyExchangeStrength int
ForwardSecrecy int
EncryptionKeyStrength int
MacPRF int
Performance int
OverallScore int
ConfigParams CipherConfigParameters
CipherConfig CipherConfig
}
func isTLS13Cipher(cipher uint16) bool {
for _, x := range tlsdefs.TLS13Ciphers {
if x == cipher {
return true
}
}
return false
}
func getCipherConfig13(cipher uint16) (config CipherConfig, err error) {
if cipherName, exists := tlsdefs.CipherSuiteMap[cipher]; exists {
config.CipherID = cipher
config.Cipher = cipherName
config.KeyExchange = tls13KeyExchange
config.Authentication = tls13KeyExchange
cipherName = strings.TrimPrefix(cipherName, "TLS_")
//set these values temporarily
config.MACPRF = tls13KeyExchange
config.Encryption = cipherName
if strings.Contains(cipherName, "SHA256") {
config.MACPRF = "SHA256"
config.Encryption = strings.TrimSuffix(cipherName, "_SHA256")
} else if strings.Contains(cipherName, "SHA384") {
config.MACPRF = "SHA384"
config.Encryption = strings.TrimSuffix(cipherName, "_SHA384")
}
return
}
return config, fmt.Errorf("The cipher id 0x%x is not recognised", cipher)
}
//GetCipherConfig extracts a `CipherConfig` using the Cipher's IANA string name
// Details here https://www.iana.org/assignments/tls-parameters/tls-parameters.txt
func GetCipherConfig(cipher uint16) (config CipherConfig, err error) {
if cipherName, exists := tlsdefs.CipherSuiteMap[cipher]; exists {
config.CipherID = cipher
config.Cipher = cipherName
if cipherName == "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" || cipherName == "TLS_FALLBACK_SCSV" {
return
}
if isTLS13Cipher(cipher) {
return getCipherConfig13(cipher)
}
cipherName = strings.TrimPrefix(cipherName, "TLS_")
cs := strings.Split(cipherName, "_WITH_")
if len(cs) != 2 {
return config, fmt.Errorf("Expects a cipher name that contains _WITH_ but got %s", config.Cipher)
}
kxAuth, encMAC := cs[0], cs[1]
config.IsExport = strings.Contains(kxAuth, "EXPORT")
ka := strings.Split(kxAuth, "_")
if len(ka) == 1 {
config.KeyExchange = ka[0]
config.Authentication = ka[0]
}
if len(ka) >= 2 {
if ka[1] == "EXPORT" {
config.KeyExchange = ka[0]
config.Authentication = ka[0]
} else {
config.KeyExchange = ka[0]
config.Authentication = ka[1]
}
}
if strings.Contains(config.KeyExchange, "DHE") {
config.SupportsForwardSecrecy = true
}
em := strings.Split(encMAC, "_")
m := em[len(em)-1]
if strings.Contains(m, "SHA") || strings.Contains(m, "MD5") || m == "NULL" {
config.MACPRF = m
config.Encryption = strings.Join(em[:len(em)-1], "_")
} else if strings.Contains(encMAC, "CCM") {
config.MACPRF = "SHA256" // see https://tools.ietf.org/html/rfc6655#section-4
config.Encryption = encMAC
} else {
config.Encryption = encMAC
}
return
}
return config, fmt.Errorf("The cipher id 0x%x is not recognised", cipher)
}
//ScanData is the Human-readable result of a given scan
type ScanData struct {
ScanRequest AdvancedScanRequest
Results map[int][]HumanScanResult //ScanGroup index (in the ASR) -> human scan results
}
//ScanGroup is a grouping of CIDR ranges to be scanned with descriptions, useful for reporting
type ScanGroup struct {
Description string `yaml:"description"` //Freeform text used in reporting
CIDRRanges []string `yaml:"cidrRanges"`
}
//AdvancedScanRequest is a model to describe a given TLS Audit scan
type AdvancedScanRequest struct {
Config ScanConfig
//Next two fields will be automatically set once scan starts
Day string //Date the scan was run in the format yyyy-mm-dd
ScanID string //Non-empty ScanID means this is a ScanRequest to resume an existing, possibly incomplete, scan
ScanGroups []ScanGroup
}
//GroupedHost exploded hosts from an associated ScanGroup
type GroupedHost struct {
ScanGroup ScanGroup
Hosts []string
}
//PersistedScanRequest persisted version of ScanRequest
type PersistedScanRequest struct {
Request AdvancedScanRequest
GroupedHosts []GroupedHost
ScanStart time.Time
ScanEnd time.Time
Progress int
HostCount int
}
// //ServerResultSummary is a mini report of scan result
// type ServerResultSummary struct {
// Server string
// HostName string
// Port string
// Grade string
// }
//ScanResultSummary is the summary of a scan result session
type ScanResultSummary struct {
Request AdvancedScanRequest
ScanStart time.Time
ScanEnd time.Time
Progress int
HostCount int
PortCount int
BestGrade string
WorstGrade string
HostGrades map[string]string
GradeToHostPorts map[string][]string
}
//Marshall scan request
func (psr PersistedScanRequest) Marshall() []byte {
result := bytes.Buffer{}
gob.Register(PersistedScanRequest{})
err := gob.NewEncoder(&result).Encode(&psr)
if err != nil {
log.Print(err)
}
return result.Bytes()
}
//UnmasharlPersistedScanRequest builds PersistedScanRequest from bytes
func UnmasharlPersistedScanRequest(data []byte) (PersistedScanRequest, error) {
psr := PersistedScanRequest{}
gob.Register(psr)
buf := bytes.NewBuffer(data)
err := gob.NewDecoder(buf).Decode(&psr)
if err != nil {
return psr, err
}
return psr, nil
}
//ScanProgress contains partial scam results with an indication of progress
type ScanProgress struct {
ScanID string
Progress float32
ScanResults []HumanScanResult // this is the latest scan results delta, at the end of scan all cummulative scans are sent
Narrative string //freeflow text
}
//ScanConfig describes details of how the TLS scan should be carried out
type ScanConfig struct {
ProtocolsOnly bool
Timeout int
//Number of Packets per Second to send out during underlying port scan
PacketsPerSecond int
//Suppress certificate output
HideCerts bool
//Suppress output of TLS status of closed ports or ports with no TLS
HideNoTLS bool
//control whether to produce a running commentary of scan progress or stay quiet till the end
Quiet bool
ServicePort int
}
//SecurityScore contains the overall grading of a TLS/SSL port
type SecurityScore struct {
ProtocolScore int
KeyExchangeScore int
CipherEncryptionScore int
CertificateScore int
Grade string
Warnings []string
}
//OrderGrade allows a simple numeric ordering of TLS grades. Actual values don't matter
func (SecurityScore) OrderGrade(grade string) int {
switch grade {
case "A+":
return 120
case "A":
return 118
case "B":
return 116
case "C":
return 114
case "D":
return 112
case "E":
return 110
case "F":
return 108
case "T":
return 106
case "TA+":
return 20
case "TA":
return 18
case "TB":
return 16
case "TC":
return 14
case "TD":
return 12
case "TE":
return 10
case "TF":
return 8
case "U":
return 6
case "Worst": // used to indicate worst case before data
return 200
case "Best": //used to indicate best case before data
return -200
case "":
return 200
default:
return -200
}
}
// KeyExchangeAlgorithm says what it is
type KeyExchangeAlgorithm int
//HostAndPort is a model representing a hostname and a given port
type HostAndPort struct {
Hostname string
Port string
}
// ServerHelloMessage is the TLS server hello message
type ServerHelloMessage struct {
Raw []byte
Vers uint16
Random []byte
SessionId []byte
CipherSuite uint16
CompressionMethod uint8
NextProtoNeg bool
NextProtos []string
OcspStapling bool
Scts [][]byte
TicketSupported bool
SecureRenegotiation []byte
SecureRenegotiationSupported bool
AlpnProtocol string
SupportedVersion uint16
ServerShare KeyShare
SelectedIdentityPresent bool
SelectedIdentity uint16
// HelloRetryRequest extensions
cookie []byte
selectedGroup CurveID
}
// CurveID is the type of a TLS identifier for an elliptic curve. See
// https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8.
//
// In TLS 1.3, this type is called NamedGroup, but at this time this library
// only supports Elliptic Curve based groups. See RFC 8446, Section 4.2.7.
type CurveID uint16
//KeyShare TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
type KeyShare struct {
Group CurveID
Data []byte
}
// ServerKeyExchangeMsg is the key exchange message
type ServerKeyExchangeMsg struct {
// Raw []byte
Key []byte
Group CurveID // for TLS v1.3
}
// HelloAndKey bundles server hello and ServerKeyExchange messages
type HelloAndKey struct {
Hello ServerHelloMessage
Key ServerKeyExchangeMsg
HasKey bool
}
// CertificateMessage simply exporting the internal certificateMsg
type CertificateMessage struct {
// Raw []byte
Certificates [][]byte
Certs []*x509.Certificate
}
//GetCertificates returns the list of certificates in a TLS certificate message
func (cert *CertificateMessage) GetCertificates() (certs []*x509.Certificate, e error) {
if cert.Certs == nil {
for _, c := range cert.Certificates {
cc, err := x509.ParseCertificate(c)
if err != nil {
return certs, err
}
certs = append(certs, cc)
}
cert.Certs = certs
} else {
certs = cert.Certs
}
return
}
// ScanResult is the scan result of a server TLS settings
type ScanResult struct {
Server string //IP address
HostName string
Port string
SupportedProtocols []uint16
HasCipherPreferenceOrderByProtocol map[uint16]bool
CipherPreferenceOrderByProtocol map[uint16][]uint16
OcspStaplingByProtocol map[uint16]bool
SelectedCipherByProtocol map[uint16]uint16
ALPNByProtocol map[uint16]string
SecureRenegotiationSupportedByProtocol map[uint16]bool
CipherSuiteByProtocol map[uint16][]uint16
ServerHelloMessageByProtocolByCipher map[uint16]map[uint16]ServerHelloMessage
CertificatesPerProtocol map[uint16]CertificateMessage
KeyExchangeByProtocolByCipher map[uint16]map[uint16]ServerKeyExchangeMsg
IsSTARTLS bool
IsSSH bool
SupportsTLSFallbackSCSV bool
GroupID int //ScanRequest Host Group index
}
//UnmarsharlScanResult builds ScanResults from bytes
func UnmarsharlScanResult(data []byte) ([]ScanResult, error) {
sr := []ScanResult{}
gob.Register(sr)
buf := bytes.NewBuffer(data)
err := gob.NewDecoder(buf).Decode(&sr)
if err != nil {
return sr, err
}
return sr, nil
}
//HumanScanResult is a Stringified version of ScanResult
type HumanScanResult struct {
Server string
HostName string
Port string
SupportsTLS bool
SupportedProtocols []string
HasCipherPreferenceOrderByProtocol map[string]bool
CipherPreferenceOrderByProtocol map[string][]string
OcspStaplingByProtocol map[string]bool
SelectedCipherByProtocol map[string]string
ALPNByProtocol map[string]string
SecureRenegotiationSupportedByProtocol map[string]bool
CipherSuiteByProtocol map[string][]string
// ServerHelloMessageByProtocolByCipher map[string]map[string]ServerHelloMessage
CertificatesPerProtocol map[string][]HumanCertificate
// KeyExchangeByProtocolByCipher map[string]map[string]ServerKeyExchangeMsg
IsSTARTLS bool
IsSSH bool
SupportsTLSFallbackSCSV bool
Score SecurityScore
GroupID int //ScanRequest Host Group index
}
//HumanCertificate is a "string" representation of various attributes of a certificate
type HumanCertificate struct {
Subject string
SubjectSerialNo string
SubjectCN string
SubjectAN string
SerialNumber string
Issuer string
PublicKeyAlgorithm string
ValidFrom string
ValidUntil string
Key string
SignatureAlgorithm string
Signature string
OcspStapling bool
RevocationDetail string
}
func getCurve(protocol, cipher uint16, scan ScanResult) string {
curveID := ""
if c, ok := scan.KeyExchangeByProtocolByCipher[protocol]; ok {
if ex, ok := c[cipher]; ok {
if cid := uint16(ex.Group); cid != 0 { // we would have set the CurveID group in TLS v1.3 and above
curveID = fmt.Sprintf(" (Supported Group: %s)", tlsdefs.SupportedGroups[cid])
} else {
key := ex.Key
if len(key) > 4 && key[0] == 3 {
//Supported Group
cid := uint16(key[1])<<8 | uint16(key[2])