-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
1065 lines (975 loc) · 31.7 KB
/
Copy pathmain.go
File metadata and controls
1065 lines (975 loc) · 31.7 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
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 main
import (
"context"
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"net"
"os"
"regexp"
"strings"
"sync"
"sync/atomic"
"time"
"gopkg.in/yaml.v3"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/reflection/grpc_reflection_v1alpha"
"google.golang.org/grpc/status"
)
const (
banner = `
⢀⡀ ⣏⡱ ⣏⡱ ⡎⠑ ⡇ ⡀⢀ ⣀⣀ ⢀⡀ ⡀⣀
⣑⡺ ⠇⠱ ⠇ ⠣⠔ ⠣ ⣑⡺ ⠴⠥ ⠣⠭ ⠏
- - - - - - - - - - - - - - - - - - -
A gRPC Discovery & Security Scanner
© 2025 Owais Shaikh
github.com/0x4f53 • owais@0x4f.in
`
)
// ============================================================================
// CONFIGURATION & SIGNATURE STRUCTURES
// ============================================================================
type SignatureConfig struct {
Tokens []string `yaml:"tokens"`
SensitiveServices []PatternSig `yaml:"sensitive_services"`
DangerousMethods []PatternSig `yaml:"dangerous_methods"`
Wordlists Wordlists `yaml:"wordlists"`
Config GeneralConfig `yaml:"configuration"` // New section
}
type GeneralConfig struct {
HealthChecks []string `yaml:"health_checks"`
IgnoredServices []string `yaml:"ignored_services"`
Crypto CryptoPolicy `yaml:"crypto"`
}
type CryptoPolicy struct {
MinKeySize int `yaml:"min_key_size"`
WeakSigAlgos []string `yaml:"weak_signature_algos"`
}
type PatternSig struct {
Pattern string `yaml:"pattern"`
Severity string `yaml:"severity"`
Reason string `yaml:"reason"`
}
type Wordlists struct {
Services []string `yaml:"services"`
Methods []string `yaml:"methods"`
}
// LoadSignatures loads the YAML configuration from a file
func LoadSignatures(path string) (*SignatureConfig, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var config SignatureConfig
if err := yaml.Unmarshal(data, &config); err != nil {
return nil, err
}
return &config, nil
}
// ============================================================================
// WEAK TLS CIPHER SUITES - (Kept in code as they map to Go constants)
// ============================================================================
var weakCipherSuites = map[uint16]string{
tls.TLS_RSA_WITH_RC4_128_SHA: "RC4-SHA (INSECURE)",
tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA: "3DES-CBC-SHA (WEAK)",
tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA: "ECDHE-RC4-SHA (INSECURE)",
tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: "ECDHE-ECDSA-RC4-SHA (INSECURE)",
tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: "ECDHE-3DES-CBC-SHA (WEAK)",
tls.TLS_RSA_WITH_AES_128_CBC_SHA: "AES128-CBC-SHA (CBC mode)",
tls.TLS_RSA_WITH_AES_256_CBC_SHA: "AES256-CBC-SHA (CBC mode)",
tls.TLS_RSA_WITH_AES_128_CBC_SHA256: "AES128-CBC-SHA256 (No PFS)",
tls.TLS_RSA_WITH_AES_128_GCM_SHA256: "AES128-GCM-SHA256 (No PFS)",
tls.TLS_RSA_WITH_AES_256_GCM_SHA384: "AES256-GCM-SHA384 (No PFS)",
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: "ECDHE-ECDSA-AES128-CBC-SHA (CBC)",
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: "ECDHE-ECDSA-AES256-CBC-SHA (CBC)",
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: "ECDHE-RSA-AES128-CBC-SHA (CBC)",
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: "ECDHE-RSA-AES256-CBC-SHA (CBC)",
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: "ECDHE-RSA-AES128-CBC-SHA256 (CBC)",
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: "ECDHE-ECDSA-AES128-CBC-SHA256 (CBC)",
}
// ScanResult holds the results of scanning a single target
type ScanResult struct {
Target string `json:"target"`
Port int `json:"port"`
IsGRPC bool `json:"is_grpc"`
TLSEnabled bool `json:"tls_enabled"`
TLSVersion string `json:"tls_version,omitempty"`
TLSCipherSuite string `json:"tls_cipher_suite,omitempty"`
CertInfo *CertInfo `json:"cert_info,omitempty"`
ReflectionEnabled bool `json:"reflection_enabled"`
Services []ServiceInfo `json:"services,omitempty"`
BlindServices []string `json:"blind_services,omitempty"`
AuthRequired bool `json:"auth_required"`
AuthType string `json:"auth_type,omitempty"`
AuthBypassTokens []string `json:"auth_bypass_tokens,omitempty"`
Error string `json:"error,omitempty"`
ScanTime time.Duration `json:"scan_time_ms"`
Findings []Finding `json:"findings,omitempty"`
MethodAuthResults []MethodAuthRes `json:"method_auth_results,omitempty"`
}
type MethodAuthRes struct {
Method string `json:"method"`
NoAuthResult string `json:"no_auth_result"`
AuthRequired bool `json:"auth_required"`
}
type CertInfo struct {
Subject string `json:"subject"`
Issuer string `json:"issuer"`
NotBefore time.Time `json:"not_before"`
NotAfter time.Time `json:"not_after"`
DNSNames []string `json:"dns_names,omitempty"`
SelfSigned bool `json:"self_signed"`
Expired bool `json:"expired"`
ExpiresSoon bool `json:"expires_soon"`
KeySize int `json:"key_size,omitempty"`
SignatureAlgo string `json:"signature_algo,omitempty"`
WeakSignature bool `json:"weak_signature"`
SerialNumber string `json:"serial_number,omitempty"`
}
type Finding struct {
Severity string `json:"severity"`
Title string `json:"title"`
Description string `json:"description"`
Remediation string `json:"remediation,omitempty"`
Reference string `json:"reference,omitempty"`
CVSS string `json:"cvss,omitempty"`
}
type ServiceInfo struct {
Name string `json:"name"`
Methods []MethodInfo `json:"methods"`
}
type MethodInfo struct {
Name string `json:"name"`
ClientStreaming bool `json:"client_streaming"`
ServerStreaming bool `json:"server_streaming"`
InputType string `json:"input_type"`
OutputType string `json:"output_type"`
}
// Scanner performs gRPC reconnaissance
type Scanner struct {
timeout time.Duration
concurrency int
verbose bool
tryTLS bool
tryPlain bool
blindEnum bool
authTest bool
signatures *SignatureConfig
}
// NewScanner creates a new Scanner instance
func NewScanner(timeout time.Duration, concurrency int, verbose, tryTLS, tryPlain, blindEnum, authTest bool, sigs *SignatureConfig) *Scanner {
return &Scanner{
timeout: timeout,
concurrency: concurrency,
verbose: verbose,
tryTLS: tryTLS,
tryPlain: tryPlain,
blindEnum: blindEnum,
authTest: authTest,
signatures: sigs,
}
}
// generateServicePatterns generates common service name patterns
func generateServicePatterns(base string) []string {
patterns := []string{
base,
base + "Service",
base + "Svc",
base + "API",
strings.ToLower(base) + "." + base + "Service",
"api." + base,
"api." + base + "Service",
base + ".v1." + base + "Service",
base + ".v2." + base + "Service",
"proto." + base + "Service",
"grpc." + base + "Service",
"internal." + base + "Service",
"public." + base + "Service",
"com.example." + strings.ToLower(base) + "." + base + "Service",
}
return patterns
}
func (s *Scanner) ScanTarget(ctx context.Context, host string, port int) ScanResult {
start := time.Now()
target := fmt.Sprintf("%s:%d", host, port)
result := ScanResult{Target: host, Port: port}
if !s.isPortOpen(target) {
result.Error = "port closed or filtered"
result.ScanTime = time.Since(start)
return result
}
var conn *grpc.ClientConn
var err error
var tlsState *tls.ConnectionState
// Try TLS
if s.tryTLS {
if s.verbose {
fmt.Printf("[*] Trying TLS connection to %s\n", target)
}
conn, result.TLSVersion, result.CertInfo, tlsState, err = s.connectWithTLS(ctx, target)
if err == nil {
result.IsGRPC = true
result.TLSEnabled = true
if tlsState != nil {
result.TLSCipherSuite = tls.CipherSuiteName(tlsState.CipherSuite)
s.checkWeakCipher(tlsState, &result)
s.checkTLSVersion(tlsState, &result)
}
s.enumerateServices(ctx, conn, &result)
if !result.ReflectionEnabled && s.blindEnum {
s.blindEnumerate(ctx, conn, &result)
}
s.performDeepSecurityChecks(ctx, conn, target, &result)
conn.Close()
s.analyzeFindings(&result)
result.ScanTime = time.Since(start)
return result
}
}
// Try Plaintext
if s.tryPlain {
if s.verbose {
fmt.Printf("[*] Trying plaintext connection to %s\n", target)
}
conn, err = s.connectPlaintext(ctx, target)
if err == nil {
result.IsGRPC = true
result.TLSEnabled = false
s.enumerateServices(ctx, conn, &result)
if !result.ReflectionEnabled && s.blindEnum {
s.blindEnumerate(ctx, conn, &result)
}
s.performDeepSecurityChecks(ctx, conn, target, &result)
conn.Close()
s.analyzeFindings(&result)
result.ScanTime = time.Since(start)
return result
}
result.Error = fmt.Sprintf("connection failed: %v", err)
}
result.ScanTime = time.Since(start)
return result
}
func (s *Scanner) performDeepSecurityChecks(ctx context.Context, conn *grpc.ClientConn, target string, result *ScanResult) {
if s.verbose {
fmt.Printf("[*] Running deep security checks on %s...\n", target)
}
if s.authTest {
s.testHardcodedTokens(ctx, conn, result)
}
if len(result.Services) > 0 {
s.testMethodAuth(ctx, conn, result)
}
s.checkStreamingAbuse(result)
s.analyzeServicePatterns(result)
s.analyzeMethodPatterns(result)
}
func (s *Scanner) testHardcodedTokens(ctx context.Context, conn *grpc.ClientConn, result *ScanResult) {
if s.verbose {
fmt.Printf("[*] Testing for hardcoded/default authentication tokens...\n")
}
baselineCode := s.testAuthWithToken(ctx, conn, "", result)
if baselineCode == codes.OK {
return
}
// Use tokens from Signatures
for _, token := range s.signatures.Tokens {
testCtx := metadata.AppendToOutgoingContext(ctx, "authorization", token)
code := s.testAuthWithToken(testCtx, conn, token, result)
if code == codes.OK || code == codes.InvalidArgument || code == codes.Internal {
result.AuthBypassTokens = append(result.AuthBypassTokens, token)
result.Findings = append(result.Findings, Finding{
Severity: "CRITICAL",
Title: "Hardcoded Authentication Token Accepted",
Description: fmt.Sprintf("The server accepted the hardcoded token '%s' for authentication.", token),
Remediation: "Remove hardcoded tokens and implement proper authentication.",
CVSS: "9.8 (Critical)",
})
if s.verbose {
fmt.Printf("[!] CRITICAL: Hardcoded token '%s' accepted!\n", token)
}
}
bearerToken := "Bearer " + token
testCtx = metadata.AppendToOutgoingContext(ctx, "authorization", bearerToken)
code = s.testAuthWithToken(testCtx, conn, bearerToken, result)
if code == codes.OK || code == codes.InvalidArgument || code == codes.Internal {
if !contains(result.AuthBypassTokens, bearerToken) {
result.AuthBypassTokens = append(result.AuthBypassTokens, bearerToken)
result.Findings = append(result.Findings, Finding{
Severity: "CRITICAL",
Title: "Hardcoded Bearer Token Accepted",
Description: fmt.Sprintf("The server accepted 'Bearer %s' for authentication.", token),
Remediation: "Implement proper JWT validation with signature verification.",
CVSS: "9.8 (Critical)",
})
}
}
}
}
func (s *Scanner) testAuthWithToken(ctx context.Context, conn *grpc.ClientConn, token string, result *ScanResult) codes.Code {
if len(result.Services) > 0 {
svc := result.Services[0]
if len(svc.Methods) > 0 {
method := fmt.Sprintf("/%s/%s", svc.Name, svc.Methods[0].Name)
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
err := conn.Invoke(ctx, method, nil, nil)
if err != nil {
st, ok := status.FromError(err)
if ok {
return st.Code()
}
}
return codes.OK
}
}
client := grpc_reflection_v1alpha.NewServerReflectionClient(conn)
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
stream, err := client.ServerReflectionInfo(ctx)
if err != nil {
st, ok := status.FromError(err)
if ok {
return st.Code()
}
return codes.Unknown
}
stream.CloseSend()
return codes.OK
}
func (s *Scanner) isHealthCheckMethod(name string) bool {
// Default fallback if config is empty
checks := []string{"Health", "Check", "Ping", "Status", "Ready", "Live", "Version", "Info"}
// Use YAML config if available
if len(s.signatures.Config.HealthChecks) > 0 {
checks = s.signatures.Config.HealthChecks
}
nameLower := strings.ToLower(name)
for _, h := range checks {
if strings.Contains(nameLower, strings.ToLower(h)) {
return true
}
}
return false
}
func (s *Scanner) testMethodAuth(ctx context.Context, conn *grpc.ClientConn, result *ScanResult) {
if s.verbose {
fmt.Printf("[*] Testing method-level authentication...\n")
}
for _, svc := range result.Services {
for _, method := range svc.Methods {
fullMethod := fmt.Sprintf("/%s/%s", svc.Name, method.Name)
testCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
err := conn.Invoke(testCtx, fullMethod, nil, nil)
cancel()
authRes := MethodAuthRes{Method: fullMethod}
if err != nil {
st, ok := status.FromError(err)
if ok {
authRes.NoAuthResult = st.Code().String()
switch st.Code() {
case codes.Unauthenticated, codes.PermissionDenied:
authRes.AuthRequired = true
case codes.OK, codes.InvalidArgument, codes.Internal:
authRes.AuthRequired = false
if !s.isHealthCheckMethod(method.Name) {
result.Findings = append(result.Findings, Finding{
Severity: "MEDIUM",
Title: "Method Accessible Without Authentication",
Description: fmt.Sprintf("Method %s is accessible without authentication (returned %s).", fullMethod, st.Code().String()),
})
}
default:
authRes.AuthRequired = false
}
} else {
authRes.NoAuthResult = err.Error()
}
} else {
authRes.NoAuthResult = "OK"
authRes.AuthRequired = false
}
result.MethodAuthResults = append(result.MethodAuthResults, authRes)
}
}
}
func (s *Scanner) checkStreamingAbuse(result *ScanResult) {
for _, svc := range result.Services {
for _, method := range svc.Methods {
if method.ClientStreaming || method.ServerStreaming {
streamType := "server streaming"
if method.ClientStreaming && method.ServerStreaming {
streamType = "bidirectional streaming"
} else if method.ClientStreaming {
streamType = "client streaming"
}
result.Findings = append(result.Findings, Finding{
Severity: "LOW",
Title: "Streaming Method Detected",
Description: fmt.Sprintf("Method %s/%s uses %s. Verify rate limiting.", svc.Name, method.Name, streamType),
})
}
}
}
}
func (s *Scanner) analyzeServicePatterns(result *ScanResult) {
allServices := make([]string, 0)
for _, svc := range result.Services {
allServices = append(allServices, svc.Name)
}
allServices = append(allServices, result.BlindServices...)
// Use Loaded Signatures
for _, svcName := range allServices {
for _, pattern := range s.signatures.SensitiveServices {
matched, _ := regexp.MatchString(pattern.Pattern, svcName)
if matched {
alreadyReported := false
for _, f := range result.Findings {
if strings.Contains(f.Description, svcName) && strings.Contains(f.Title, "Sensitive") {
alreadyReported = true
break
}
}
if !alreadyReported {
result.Findings = append(result.Findings, Finding{
Severity: pattern.Severity,
Title: "Sensitive Service Exposed: " + svcName,
Description: pattern.Reason,
Remediation: "Restrict access via auth/network segmentation.",
})
}
break
}
}
}
}
func (s *Scanner) analyzeMethodPatterns(result *ScanResult) {
for _, svc := range result.Services {
for _, method := range svc.Methods {
for _, pattern := range s.signatures.DangerousMethods {
matched, _ := regexp.MatchString(pattern.Pattern, method.Name)
if matched {
result.Findings = append(result.Findings, Finding{
Severity: pattern.Severity,
Title: fmt.Sprintf("Dangerous Method Pattern: %s/%s", svc.Name, method.Name),
Description: pattern.Reason,
Remediation: "Ensure proper auth and input validation.",
})
break
}
}
}
}
}
func (s *Scanner) checkWeakCipher(state *tls.ConnectionState, result *ScanResult) {
if desc, weak := weakCipherSuites[state.CipherSuite]; weak {
result.Findings = append(result.Findings, Finding{
Severity: "MEDIUM",
Title: "Weak TLS Cipher Suite",
Description: fmt.Sprintf("Server uses weak cipher: %s (%s)", desc, tls.CipherSuiteName(state.CipherSuite)),
})
}
}
func (s *Scanner) checkTLSVersion(state *tls.ConnectionState, result *ScanResult) {
var versionName string
var severity string
switch state.Version {
case tls.VersionSSL30:
versionName = "SSL 3.0"
severity = "CRITICAL"
case tls.VersionTLS10:
versionName = "TLS 1.0"
severity = "HIGH"
case tls.VersionTLS11:
versionName = "TLS 1.1"
severity = "HIGH"
case tls.VersionTLS12:
result.TLSVersion = "TLS 1.2"
return
case tls.VersionTLS13:
result.TLSVersion = "TLS 1.3"
return
default:
return
}
result.TLSVersion = versionName
result.Findings = append(result.Findings, Finding{
Severity: severity,
Title: "Deprecated TLS Version",
Description: fmt.Sprintf("Server supports deprecated %s.", versionName),
})
}
func (s *Scanner) isPortOpen(target string) bool {
conn, err := net.DialTimeout("tcp", target, s.timeout)
if err != nil {
return false
}
conn.Close()
return true
}
func (s *Scanner) connectWithTLS(ctx context.Context, target string) (*grpc.ClientConn, string, *CertInfo, *tls.ConnectionState, error) {
var certInfo *CertInfo
var tlsState *tls.ConnectionState
tlsConfig := &tls.Config{
InsecureSkipVerify: true,
VerifyConnection: func(cs tls.ConnectionState) error {
tlsState = &cs
if len(cs.PeerCertificates) > 0 {
cert := cs.PeerCertificates[0]
certInfo = &CertInfo{
Subject: cert.Subject.String(),
Issuer: cert.Issuer.String(),
NotBefore: cert.NotBefore,
NotAfter: cert.NotAfter,
DNSNames: cert.DNSNames,
SelfSigned: cert.Subject.String() == cert.Issuer.String(),
Expired: time.Now().After(cert.NotAfter),
ExpiresSoon: time.Now().Add(30 * 24 * time.Hour).After(cert.NotAfter),
SignatureAlgo: cert.SignatureAlgorithm.String(),
SerialNumber: cert.SerialNumber.String(),
}
// Check for weak signature algorithms
weakAlgos := s.signatures.Config.Crypto.WeakSigAlgos
for _, weak := range weakAlgos {
if strings.Contains(strings.ToUpper(cert.SignatureAlgorithm.String()), weak) {
certInfo.WeakSignature = true
break
}
}
// Get key size
switch pub := cert.PublicKey.(type) {
case interface{ Size() int }:
certInfo.KeySize = pub.Size() * 8
}
}
return nil
},
}
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
// FIX: Capture the connection and error separately
conn, err := grpc.DialContext(ctx, target,
grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
grpc.WithBlock(),
)
if err != nil {
return nil, "", nil, nil, err
}
// Return all 5 required values
return conn, "TLS 1.2+", certInfo, tlsState, nil
}
func (s *Scanner) connectPlaintext(ctx context.Context, target string) (*grpc.ClientConn, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
return grpc.DialContext(ctx, target, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock())
}
func (s *Scanner) enumerateServices(ctx context.Context, conn *grpc.ClientConn, result *ScanResult) {
client := grpc_reflection_v1alpha.NewServerReflectionClient(conn)
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
stream, err := client.ServerReflectionInfo(ctx)
if err != nil {
if st, ok := status.FromError(err); ok {
switch st.Code() {
case codes.Unauthenticated:
result.AuthRequired = true
result.AuthType = "unknown (unauthenticated error)"
return
case codes.PermissionDenied:
result.AuthRequired = true
result.AuthType = "unknown (permission denied)"
return
case codes.Unimplemented:
result.ReflectionEnabled = false
return
}
}
result.Error = fmt.Sprintf("reflection error: %v", err)
return
}
result.ReflectionEnabled = true
if err := stream.Send(&grpc_reflection_v1alpha.ServerReflectionRequest{
MessageRequest: &grpc_reflection_v1alpha.ServerReflectionRequest_ListServices{ListServices: "*"},
}); err != nil {
result.Error = fmt.Sprintf("failed to list services: %v", err)
return
}
resp, err := stream.Recv()
if err != nil {
result.Error = fmt.Sprintf("failed to receive service list: %v", err)
return
}
listResp := resp.GetListServicesResponse()
if listResp == nil {
return
}
// Inside enumerateServices loop...
for _, svc := range listResp.Service {
shouldIgnore := false
// Check against ignored list in YAML
ignores := s.signatures.Config.IgnoredServices
if len(ignores) == 0 {
ignores = []string{"grpc.reflection"} // Fallback
}
for _, ignore := range ignores {
if strings.Contains(svc.Name, ignore) {
shouldIgnore = true
break
}
}
if shouldIgnore {
continue
}
// ... (rest of the logic)
}
}
func (s *Scanner) blindEnumerate(ctx context.Context, conn *grpc.ClientConn, result *ScanResult) {
if s.verbose {
fmt.Printf("[*] Reflection disabled, attempting blind enumeration...\n")
}
var foundServices []string
var mu sync.Mutex
var wg sync.WaitGroup
sem := make(chan struct{}, s.concurrency)
var checked int64
var found int64
// Use wordlist from Signatures
wordlist := s.signatures.Wordlists.Services
totalPatterns := 0
for _, base := range wordlist {
totalPatterns += len(generateServicePatterns(base))
}
for _, base := range wordlist {
patterns := generateServicePatterns(base)
for _, serviceName := range patterns {
wg.Add(1)
sem <- struct{}{}
go func(svc string) {
defer wg.Done()
defer func() { <-sem }()
exists, _ := s.probeService(ctx, conn, svc)
atomic.AddInt64(&checked, 1)
if exists {
atomic.AddInt64(&found, 1)
mu.Lock()
foundServices = append(foundServices, svc)
mu.Unlock()
if s.verbose {
fmt.Printf("[+] Found service: %s\n", svc)
}
}
if s.verbose && atomic.LoadInt64(&checked)%100 == 0 {
fmt.Printf("[*] Progress: %d/%d checked | Found: %d\n", atomic.LoadInt64(&checked), totalPatterns, atomic.LoadInt64(&found))
}
}(serviceName)
}
}
wg.Wait()
result.BlindServices = foundServices
}
func (s *Scanner) probeService(ctx context.Context, conn *grpc.ClientConn, serviceName string) (bool, error) {
// Use method wordlist from Signatures to probe
probeMethods := s.signatures.Wordlists.Methods
if len(probeMethods) == 0 {
probeMethods = []string{"Get", "List", "Check", "Health", "Ping"}
}
for _, method := range probeMethods {
fullMethod := fmt.Sprintf("/%s/%s", serviceName, method)
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
err := conn.Invoke(ctx, fullMethod, nil, nil)
cancel()
if err != nil {
st, ok := status.FromError(err)
if !ok {
continue
}
switch st.Code() {
case codes.Unimplemented:
desc := st.Message()
if strings.Contains(desc, "unknown service") {
return false, nil
}
if strings.Contains(desc, "unknown method") {
return true, nil
}
return false, nil
case codes.Unauthenticated, codes.PermissionDenied, codes.InvalidArgument, codes.Internal, codes.Unavailable:
return true, nil
}
}
}
return false, nil
}
func (s *Scanner) CallMethod(ctx context.Context, target, method string) (codes.Code, string, error) {
var conn *grpc.ClientConn
var err error
if s.tryTLS {
conn, _, _, _, err = s.connectWithTLS(ctx, target)
}
if err != nil && s.tryPlain {
conn, err = s.connectPlaintext(ctx, target)
}
if err != nil {
return codes.Unknown, "", fmt.Errorf("connection failed: %v", err)
}
defer conn.Close()
if !strings.HasPrefix(method, "/") {
method = "/" + method
}
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
err = conn.Invoke(ctx, method, nil, nil)
if err != nil {
st, ok := status.FromError(err)
if ok {
return st.Code(), st.Message(), nil
}
return codes.Unknown, err.Error(), nil
}
return codes.OK, "success", nil
}
func getServiceName(fqn string) string {
parts := strings.Split(fqn, ".")
return parts[len(parts)-1]
}
func (s *Scanner) analyzeFindings(result *ScanResult) {
minSize := s.signatures.Config.Crypto.MinKeySize
if minSize == 0 {
minSize = 2048 // Fallback
}
if result.ReflectionEnabled {
result.Findings = append(result.Findings, Finding{
Severity: "MEDIUM",
Title: "Server Reflection Enabled",
Description: "gRPC reflection allows full service enumeration.",
})
}
if result.IsGRPC && !result.TLSEnabled {
result.Findings = append(result.Findings, Finding{
Severity: "HIGH",
Title: "Plaintext gRPC (No TLS)",
Description: "Service accessible over plaintext.",
CVSS: "7.5 (High)",
})
}
if result.CertInfo != nil {
if result.CertInfo.SelfSigned {
result.Findings = append(result.Findings, Finding{
Severity: "MEDIUM", Title: "Self-Signed TLS Certificate",
Description: "Certificate is self-signed.",
})
}
if result.CertInfo.Expired {
result.Findings = append(result.Findings, Finding{
Severity: "HIGH", Title: "Expired TLS Certificate",
Description: "Certificate has expired.",
})
}
if result.CertInfo.WeakSignature {
result.Findings = append(result.Findings, Finding{
Severity: "HIGH", Title: "Weak Certificate Signature",
Description: "Weak signature algorithm detected.",
})
}
minSize := s.signatures.Config.Crypto.MinKeySize
if minSize == 0 {
minSize = 2048 // Fallback
}
if result.CertInfo.KeySize > 0 && result.CertInfo.KeySize < minSize {
result.Findings = append(result.Findings, Finding{
Severity: "HIGH",
Title: "Weak Certificate Key Size",
Description: fmt.Sprintf("Certificate uses %d-bit key. Policy requires %d bits.", result.CertInfo.KeySize, minSize),
})
}
}
if !result.AuthRequired && (len(result.Services) > 0 || len(result.BlindServices) > 0 || result.ReflectionEnabled) {
result.Findings = append(result.Findings, Finding{
Severity: "INFO", // Or HIGH, depending on your risk model
Title: "No Authentication Detected",
Description: "Services (or reflection) are accessible without authentication. Disabling reflection is NOT enough; you must implement auth interceptors.",
Remediation: "Implement gRPC interceptors to validate tokens (JWT, OAuth) for every request.",
})
}
severityOrder := map[string]int{"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3, "INFO": 4}
for i := 0; i < len(result.Findings); i++ {
for j := i + 1; j < len(result.Findings); j++ {
if severityOrder[result.Findings[i].Severity] > severityOrder[result.Findings[j].Severity] {
result.Findings[i], result.Findings[j] = result.Findings[j], result.Findings[i]
}
}
}
}
func (s *Scanner) ScanTargets(ctx context.Context, targets []string, ports []int) []ScanResult {
var results []ScanResult
var mu sync.Mutex
var wg sync.WaitGroup
sem := make(chan struct{}, s.concurrency)
for _, target := range targets {
for _, port := range ports {
wg.Add(1)
sem <- struct{}{}
go func(t string, p int) {
defer wg.Done()
defer func() { <-sem }()
result := s.ScanTarget(ctx, t, p)
mu.Lock()
results = append(results, result)
mu.Unlock()
if result.IsGRPC {
s.printResult(result)
}
}(target, port)
}
}
wg.Wait()
return results
}
func (s *Scanner) printResult(result ScanResult) {
fmt.Printf("\n[+] gRPC Service Found: %s:%d\n", result.Target, result.Port)
fmt.Printf(" TLS: %v\n", result.TLSEnabled)
if result.ReflectionEnabled && len(result.Services) > 0 {
fmt.Printf(" Services (%d):\n", len(result.Services))
for _, svc := range result.Services {
fmt.Printf(" - %s\n", svc.Name)
}
}
if len(result.BlindServices) > 0 {
fmt.Printf(" Blind-Enumerated Services (%d):\n", len(result.BlindServices))
for _, svc := range result.BlindServices {
fmt.Printf(" - %s\n", svc)
}
}
if len(result.AuthBypassTokens) > 0 {
fmt.Printf(" [!!!] AUTH BYPASS TOKENS FOUND:\n")
for _, token := range result.AuthBypassTokens {
fmt.Printf(" - %q\n", token)
}
}
if len(result.Findings) > 0 {
fmt.Printf(" Security Findings (%d):\n", len(result.Findings))
for _, f := range result.Findings {
fmt.Printf(" [%s] %s\n", f.Severity, f.Title)
}
}
}
func contains(slice []string, str string) bool {
for _, s := range slice {
if s == str {
return true
}
}
return false
}
func main() {
var (
targets string
targetFile string
ports string
timeout int
concurrency int
outputJSON string
verbose bool
noTLS bool
noPlain bool
blindEnum bool
callMethod string
sigFile string
)
flag.StringVar(&targets, "t", "", "Target host(s)")
flag.StringVar(&targetFile, "T", "", "File containing targets")
flag.StringVar(&ports, "p", "50051,9090,443,8443,9000", "Ports to scan")
flag.IntVar(&timeout, "timeout", 5, "Connection timeout")
flag.IntVar(&concurrency, "c", 10, "Concurrency")
flag.StringVar(&outputJSON, "o", "", "Output JSON file")
flag.BoolVar(&verbose, "v", false, "Verbose output")
flag.BoolVar(&noTLS, "no-tls", false, "Skip TLS")
flag.BoolVar(&noPlain, "no-plain", false, "Skip Plaintext")
flag.BoolVar(&blindEnum, "blind", false, "Enable blind enumeration")
flag.StringVar(&callMethod, "call", "", "Call method (Service/Method)")
flag.StringVar(&sigFile, "sigs", "signatures.yaml", "Path to signatures YAML file")
flag.Parse()
fmt.Println(banner)
// 1. Load Signatures
sigs, err := LoadSignatures(sigFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading signatures from %s: %v\n", sigFile, err)
fmt.Fprintf(os.Stderr, "Please ensure the YAML file exists or specify one with -sigs\n")
os.Exit(1)
}
if verbose {
fmt.Printf("[*] Loaded signatures: %d tokens, %d service patterns\n",
len(sigs.Tokens), len(sigs.SensitiveServices))
}
// 2. Setup Scanner
scanner := NewScanner(
time.Duration(timeout)*time.Second,
concurrency,
verbose,
!noTLS,
!noPlain,
blindEnum,
true,