-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchecker.go
More file actions
1716 lines (1511 loc) · 54.3 KB
/
Copy pathchecker.go
File metadata and controls
1716 lines (1511 loc) · 54.3 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 proxy
import (
"context"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/ResistanceIsUseless/ProxyHawk/internal/errors"
"github.com/ResistanceIsUseless/ProxyHawk/internal/logging"
)
// NewChecker creates a new proxy checker
func NewChecker(config Config, debug bool, logger *logging.Logger) *Checker {
checker := &Checker{
config: config,
debug: debug,
logger: logger,
rateLimiter: make(map[string]time.Time),
}
// Validate and normalize retry configuration
checker.validateRetryConfig()
// Validate and normalize authentication configuration
checker.validateAuthConfig()
return checker
}
// Check validates a proxy and returns detailed information about its functionality
func (c *Checker) Check(proxyURL string) *ProxyResult {
result := &ProxyResult{
ProxyURL: proxyURL,
Type: ProxyTypeUnknown,
CheckResults: []CheckResult{},
SupportsHTTP: false,
SupportsHTTPS: false,
}
if c.debug {
result.DebugInfo += fmt.Sprintf("[PROXY CHECK] Starting check for: %s\n", proxyURL)
}
// Parse the proxy URL
parsedURL, err := url.Parse(proxyURL)
if err != nil {
result.Error = errors.NewProxyError(errors.ErrorProxyInvalidURL, "invalid proxy URL", proxyURL, err)
if c.debug {
result.DebugInfo += fmt.Sprintf("[ERROR] Failed to parse URL: %v\n", err)
}
return result
}
// Create a phased approach with clear stage markers in debug output
if c.debug {
result.DebugInfo += fmt.Sprintf("[PHASE 1/2] Detecting proxy type for %s\n", proxyURL)
}
// Determine proxy type
proxyType, client, err := c.determineProxyType(parsedURL, result)
if err != nil {
// Proxy doesn't work as a forward proxy, but it might still have vulnerabilities
// Try direct vulnerability scanning as fallback if advanced checks are enabled
if c.hasAdvancedChecks() {
if c.debug {
result.DebugInfo += fmt.Sprintf("[FALLBACK] Proxy connection failed, attempting direct vulnerability scan\n")
}
// Try to scan the target as a web server directly
if directResult := c.performDirectScan(parsedURL, result); directResult {
// Direct scan found something useful
if c.debug {
result.DebugInfo += fmt.Sprintf("[FALLBACK] Direct scan completed with findings\n")
}
return result
}
}
// Create a more concise error message
result.Error = errors.NewProxyError(errors.ErrorProxyNotWorking, "proxy check failed", proxyURL, err)
if c.debug {
result.DebugInfo += fmt.Sprintf("[RESULT] Proxy type detection failed and no vulnerabilities found: %v\n", err)
}
return result
}
if c.debug {
result.DebugInfo += fmt.Sprintf("[PHASE 1/2 COMPLETE] Successfully detected proxy type: %s\n", proxyType)
result.DebugInfo += fmt.Sprintf("[PHASE 2/2] Performing validation checks for %s proxy\n", proxyType)
}
result.Type = proxyType
// Perform checks using the determined client
if err := c.performChecks(client, result); err != nil {
result.Error = errors.NewProxyError(errors.ErrorProxyValidationFailed, "validation failed", proxyURL, err)
if c.debug {
result.DebugInfo += fmt.Sprintf("[RESULT] Validation checks failed: %v\n", err)
}
return result
}
if c.debug {
result.DebugInfo += fmt.Sprintf("[PHASE 2/2 COMPLETE] Validation successful\n")
}
// PHASE 3: Advanced Security Checks (if enabled)
if c.hasAdvancedChecks() {
if c.debug {
result.DebugInfo += fmt.Sprintf("[PHASE 3/3] Running advanced security checks\n")
}
if err := c.performAdvancedChecks(client, result); err != nil {
if c.debug {
result.DebugInfo += fmt.Sprintf("[PHASE 3/3] Advanced checks encountered error: %v\n", err)
}
// Don't fail the entire check if advanced checks fail
// Just log the error and continue
}
if c.debug {
result.DebugInfo += fmt.Sprintf("[PHASE 3/3 COMPLETE] Advanced security checks finished\n")
}
}
// PHASE 4: Anonymity Detection and Proxy Chain Detection
if c.debug {
result.DebugInfo += fmt.Sprintf("[PHASE 4/4] Checking proxy anonymity and chain detection\n")
}
anonymous, anonLevel, detectedIP, leakingHeaders, chainDetected, chainInfo, anonErr := c.checkAnonymity(client)
if anonErr == nil {
result.IsAnonymous = anonymous
result.AnonymityLevel = anonLevel
result.DetectedIP = detectedIP
result.LeakingHeaders = leakingHeaders
result.ProxyChainDetected = chainDetected
result.ProxyChainInfo = chainInfo
if c.debug {
result.DebugInfo += fmt.Sprintf("[PHASE 4/4 COMPLETE] Anonymity: %t, Level: %s\n", anonymous, anonLevel)
if chainDetected {
result.DebugInfo += fmt.Sprintf(" - Proxy Chain: YES (%s)\n", chainInfo)
}
if len(leakingHeaders) > 0 {
result.DebugInfo += fmt.Sprintf(" - Leaking Headers: %v\n", leakingHeaders)
}
}
} else if c.debug {
result.DebugInfo += fmt.Sprintf("[PHASE 4/4] Anonymity check failed: %v\n", anonErr)
}
// PHASE 5: Proxy Fingerprinting (if enabled)
if c.config.EnableFingerprint {
if c.debug {
result.DebugInfo += fmt.Sprintf("[PHASE 5/5] Fingerprinting proxy software\n")
}
fingerprint := c.FingerprintProxy(client, proxyURL)
result.Fingerprint = fingerprint
if c.debug {
result.DebugInfo += fmt.Sprintf("[PHASE 5/5 COMPLETE] Detected: %s (confidence: %.2f)\n", fingerprint.ProxySoftware, fingerprint.Confidence)
if fingerprint.Version != "" {
result.DebugInfo += fmt.Sprintf(" - Version: %s\n", fingerprint.Version)
}
}
}
if c.debug {
result.DebugInfo += fmt.Sprintf("[SUMMARY] Proxy check results for %s:\n", proxyURL)
result.DebugInfo += fmt.Sprintf(" - Type: %s\n", result.Type)
result.DebugInfo += fmt.Sprintf(" - Working: %t\n", result.Working)
result.DebugInfo += fmt.Sprintf(" - Speed: %v\n", result.Speed)
result.DebugInfo += fmt.Sprintf(" - Anonymous: %t (%s)\n", result.IsAnonymous, result.AnonymityLevel)
result.DebugInfo += fmt.Sprintf(" - Check Steps: %d\n", len(result.CheckResults))
if c.config.EnableFingerprint && result.Fingerprint != nil {
result.DebugInfo += fmt.Sprintf(" - Fingerprint: %s %s\n", result.Fingerprint.ProxySoftware, result.Fingerprint.Version)
}
}
return result
}
// determineProxyType attempts to determine the type of proxy by testing different protocols
func (c *Checker) determineProxyType(proxyURL *url.URL, result *ProxyResult) (ProxyType, *http.Client, error) {
var lastError string
// Use local validation URLs instead of mutating shared config
validationURLHTTP := "http://api.ipify.org?format=json"
validationURLHTTPS := "https://api.ipify.org?format=json"
// Save the original validation URL to restore after testing
origValidationURL := c.config.ValidationURL
defer func() {
c.config.ValidationURL = origValidationURL
}()
// First check if the proxy URL already specifies a scheme we can use
if proxyURL.Scheme != "" {
proxyType := ProxyTypeUnknown
scheme := proxyURL.Scheme
// Map URL scheme to ProxyType
switch strings.ToLower(scheme) {
case "http":
proxyType = ProxyTypeHTTP
case "https":
proxyType = ProxyTypeHTTPS
case "socks4":
proxyType = ProxyTypeSOCKS4
case "socks5":
proxyType = ProxyTypeSOCKS5
}
if proxyType != ProxyTypeUnknown {
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Using scheme from URL: %s\n", scheme)
}
// Try this scheme first
client, err := c.createClient(proxyURL, scheme, result)
if err == nil {
// Test with HTTP endpoint
c.config.ValidationURL = validationURLHTTP
httpSuccess, httpTestErr, httpCheckResult := c.testClientWithDetails(client, proxyType, result)
// Add the check result to our collection
if httpCheckResult != nil {
result.CheckResults = append(result.CheckResults, *httpCheckResult)
}
// Then test with HTTPS endpoint
c.config.ValidationURL = validationURLHTTPS
httpsSuccess, httpsTestErr, httpsCheckResult := c.testClientWithDetails(client, proxyType, result)
// Add the check result to our collection
if httpsCheckResult != nil {
result.CheckResults = append(result.CheckResults, *httpsCheckResult)
}
// Set protocol support based on results
if httpSuccess {
result.SupportsHTTP = true
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Success! %s proxy supports HTTP\n", proxyType)
}
}
if httpsSuccess {
result.SupportsHTTPS = true
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Success! %s proxy supports HTTPS\n", proxyType)
}
}
if httpSuccess || httpsSuccess {
if c.debug {
if httpSuccess && httpsSuccess {
result.DebugInfo += fmt.Sprintf("[TYPE] Using %s proxy with both HTTP and HTTPS support\n", proxyType)
} else if httpSuccess {
result.DebugInfo += fmt.Sprintf("[TYPE] Using %s proxy with HTTP support only\n", proxyType)
} else {
result.DebugInfo += fmt.Sprintf("[TYPE] Using %s proxy with HTTPS support only\n", proxyType)
}
}
return proxyType, client, nil
}
if c.debug && !httpSuccess && !httpsSuccess {
result.DebugInfo += fmt.Sprintf("[TYPE] Specified scheme %s failed: HTTP: %s, HTTPS: %s\n",
scheme, httpTestErr, httpsTestErr)
}
} else if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Failed to create client for specified scheme %s: %v\n",
scheme, err)
}
}
}
// If URL scheme detection failed, now try protocols in order: HTTP, HTTPS, SOCKS4, SOCKS5
// First try HTTP/HTTPS proxies
httpProxyCandidates := []struct {
proxyType ProxyType
scheme string
}{
{ProxyTypeHTTP, "http"},
{ProxyTypeHTTPS, "https"},
}
// Try HTTP/HTTPS proxy types first
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Testing as HTTP/HTTPS proxy: %s\n", proxyURL.Host)
}
type httpTestResult struct {
proxyType ProxyType
client *http.Client
success bool
protocol string // "http" or "https"
speed time.Duration
}
var httpResults []httpTestResult
for _, candidate := range httpProxyCandidates {
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Trying as %s proxy\n", candidate.proxyType)
}
client, err := c.createClient(proxyURL, candidate.scheme, result)
if err != nil {
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Failed to create client for %s: %v\n", candidate.proxyType, err)
}
lastError = fmt.Sprintf("client creation failed for %s: %v", candidate.proxyType, err)
continue
}
// Test with HTTP endpoint
c.config.ValidationURL = validationURLHTTP
httpSuccess, httpTestErr, httpCheckResult := c.testClientWithDetails(client, candidate.proxyType, result)
// Add the check result to our collection
if httpCheckResult != nil {
result.CheckResults = append(result.CheckResults, *httpCheckResult)
}
if httpSuccess {
httpResults = append(httpResults, httpTestResult{
proxyType: candidate.proxyType,
client: client,
success: true,
protocol: "http",
speed: httpCheckResult.Speed,
})
// Set HTTP support flag
result.SupportsHTTP = true
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Success! Working as %s proxy with HTTP endpoint\n", candidate.proxyType)
}
}
// Then test with HTTPS endpoint
c.config.ValidationURL = validationURLHTTPS
httpsSuccess, httpsTestErr, httpsCheckResult := c.testClientWithDetails(client, candidate.proxyType, result)
// Add the check result to our collection
if httpsCheckResult != nil {
result.CheckResults = append(result.CheckResults, *httpsCheckResult)
}
if httpsSuccess {
httpResults = append(httpResults, httpTestResult{
proxyType: candidate.proxyType,
client: client,
success: true,
protocol: "https",
speed: httpsCheckResult.Speed,
})
// Set HTTPS support flag
result.SupportsHTTPS = true
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Success! Working as %s proxy with HTTPS endpoint\n", candidate.proxyType)
}
}
// If both HTTP and HTTPS succeeded, return right away
if httpSuccess && httpsSuccess {
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] %s proxy supports both HTTP and HTTPS\n", candidate.proxyType)
}
return candidate.proxyType, client, nil
}
// If only HTTP succeeded, continue checking other proxy types
if httpSuccess && !httpsSuccess {
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] %s proxy supports HTTP but not HTTPS: %s\n",
candidate.proxyType, httpsTestErr)
}
// Don't return immediately - we'll store this as a fallback
}
// If neither succeeded, log errors
if !httpSuccess && !httpsSuccess {
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Failed as %s proxy: HTTP: %s, HTTPS: %s\n",
candidate.proxyType, httpTestErr, httpsTestErr)
}
lastError = fmt.Sprintf("HTTP: %s, HTTPS: %s", httpTestErr, httpsTestErr)
}
}
// If we found HTTP proxies but none supported HTTPS, still use the best HTTP proxy
if len(httpResults) > 0 {
// Try to find a proxy that supports HTTPS
for _, r := range httpResults {
if r.protocol == "https" {
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Selected %s proxy with HTTPS support\n", r.proxyType)
}
return r.proxyType, r.client, nil
}
}
// If none support HTTPS, use the first HTTP result
best := httpResults[0]
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Selected %s proxy with HTTP support only\n", best.proxyType)
}
return best.proxyType, best.client, nil
}
// If HTTP/HTTPS failed, try HTTP/2 and HTTP/3 if enabled
if c.config.EnableHTTP2 || c.config.EnableHTTP3 {
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Testing advanced HTTP protocols (HTTP/2, HTTP/3): %s\n", proxyURL.Host)
}
// Test HTTP/2 support if enabled
if c.config.EnableHTTP2 {
if success, client := c.detectHTTP2Protocol(proxyURL, result); success {
result.SupportsHTTP2 = true
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Selected HTTP/2 proxy\n")
}
return ProxyTypeHTTP2, client, nil
}
}
// Test HTTP/3 support if enabled
if c.config.EnableHTTP3 {
if success, client := c.detectHTTP3Protocol(proxyURL, result); success {
result.SupportsHTTP3 = true
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Selected HTTP/3 proxy\n")
}
return ProxyTypeHTTP3, client, nil
}
}
}
// If HTTP/HTTPS failed, try SOCKS proxies
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Testing as SOCKS proxy: %s\n", proxyURL.Host)
}
// Define SOCKS proxy candidates, testing SOCKS5 first
socksProxyCandidates := []struct {
proxyType ProxyType
scheme string
}{
{ProxyTypeSOCKS5, "socks5"},
{ProxyTypeSOCKS4, "socks4"},
}
type socksTestResult struct {
proxyType ProxyType
client *http.Client
success bool
protocol string // "http" or "https"
speed time.Duration
}
var socksResults []socksTestResult
for _, candidate := range socksProxyCandidates {
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Trying as %s proxy\n", candidate.proxyType)
}
client, err := c.createClient(proxyURL, candidate.scheme, result)
if err != nil {
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Failed to create client for %s: %v\n", candidate.proxyType, err)
}
lastError = fmt.Sprintf("client creation failed for %s: %v", candidate.proxyType, err)
continue
}
// Test with HTTP endpoint
c.config.ValidationURL = validationURLHTTP
httpSuccess, httpTestErr, httpCheckResult := c.testClientWithDetails(client, candidate.proxyType, result)
// Add the check result to our collection
if httpCheckResult != nil {
result.CheckResults = append(result.CheckResults, *httpCheckResult)
}
if httpSuccess {
socksResults = append(socksResults, socksTestResult{
proxyType: candidate.proxyType,
client: client,
success: true,
protocol: "http",
speed: httpCheckResult.Speed,
})
// Set HTTP support flag
result.SupportsHTTP = true
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Success! Working as %s proxy with HTTP endpoint\n", candidate.proxyType)
}
}
// Test with HTTPS endpoint
c.config.ValidationURL = validationURLHTTPS
httpsSuccess, httpsTestErr, httpsCheckResult := c.testClientWithDetails(client, candidate.proxyType, result)
// Add the check result to our collection
if httpsCheckResult != nil {
result.CheckResults = append(result.CheckResults, *httpsCheckResult)
}
if httpsSuccess {
socksResults = append(socksResults, socksTestResult{
proxyType: candidate.proxyType,
client: client,
success: true,
protocol: "https",
speed: httpsCheckResult.Speed,
})
// Set HTTPS support flag
result.SupportsHTTPS = true
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Success! Working as %s proxy with HTTPS endpoint\n", candidate.proxyType)
}
}
// If both HTTP and HTTPS succeeded, return right away (prefer SOCKS5 over SOCKS4)
if httpSuccess && httpsSuccess {
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] %s proxy supports both HTTP and HTTPS\n", candidate.proxyType)
}
return candidate.proxyType, client, nil
}
// If only one protocol succeeded, continue checking other proxy types
if (httpSuccess || httpsSuccess) && candidate.proxyType == ProxyTypeSOCKS5 {
// For SOCKS5, if either protocol works, we consider it a strong candidate
if c.debug {
if httpSuccess && !httpsSuccess {
result.DebugInfo += fmt.Sprintf("[TYPE] SOCKS5 proxy supports HTTP but not HTTPS: %s\n", httpsTestErr)
} else if !httpSuccess && httpsSuccess {
result.DebugInfo += fmt.Sprintf("[TYPE] SOCKS5 proxy supports HTTPS but not HTTP: %s\n", httpTestErr)
}
}
// We prefer SOCKS5 when possible, so return immediately
return candidate.proxyType, client, nil
}
// If neither succeeded, log errors
if !httpSuccess && !httpsSuccess {
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Failed as %s proxy: HTTP: %s, HTTPS: %s\n",
candidate.proxyType, httpTestErr, httpsTestErr)
}
lastError = fmt.Sprintf("HTTP: %s, HTTPS: %s", httpTestErr, httpsTestErr)
}
}
// If we have SOCKS results but didn't return earlier, select the best one
if len(socksResults) > 0 {
// First try to find a SOCKS5 proxy that supports HTTPS
for _, r := range socksResults {
if r.proxyType == ProxyTypeSOCKS5 && r.protocol == "https" {
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Selected SOCKS5 proxy with HTTPS support\n")
}
return r.proxyType, r.client, nil
}
}
// Then try a SOCKS5 proxy with HTTP only
for _, r := range socksResults {
if r.proxyType == ProxyTypeSOCKS5 && r.protocol == "http" {
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Selected SOCKS5 proxy with HTTP support only\n")
}
return r.proxyType, r.client, nil
}
}
// Then try a SOCKS4 proxy with HTTPS
for _, r := range socksResults {
if r.proxyType == ProxyTypeSOCKS4 && r.protocol == "https" {
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Selected SOCKS4 proxy with HTTPS support\n")
}
return r.proxyType, r.client, nil
}
}
// Finally, use any SOCKS proxy we found
best := socksResults[0]
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] Selected %s proxy with %s support\n",
best.proxyType, best.protocol)
}
return best.proxyType, best.client, nil
}
if c.debug {
result.DebugInfo += fmt.Sprintf("[TYPE] All proxy types failed for %s\n", proxyURL.Host)
}
if lastError == "" {
lastError = "all proxy types failed with unknown errors"
}
return ProxyTypeUnknown, nil, fmt.Errorf("could not determine proxy type: %s", lastError)
}
// performChecks runs all configured checks for the proxy
func (c *Checker) performChecks(client *http.Client, result *ProxyResult) error {
start := time.Now()
if c.debug {
result.DebugInfo += fmt.Sprintf("[VALIDATE] Running validation checks\n")
}
// Make the request to the validation URL (with retry logic if enabled)
resp, err := c.makeRequestWithRetry(client, c.config.ValidationURL, result)
if err != nil {
if c.debug {
result.DebugInfo += fmt.Sprintf("[VALIDATE] Request failed: %v\n", err)
}
return errors.NewHTTPError(errors.ErrorHTTPRequestFailed, "request failed", c.config.ValidationURL, err)
}
defer resp.Body.Close()
// Record the time taken
duration := time.Since(start)
result.Speed = duration
// Read response body
body, err := io.ReadAll(resp.Body)
if err != nil {
if c.debug {
result.DebugInfo += fmt.Sprintf("[VALIDATE] Failed to read response body: %v\n", err)
}
return fmt.Errorf("failed to read response body: %v", err)
}
// Create a check result for the validation
validationCheck := CheckResult{
URL: c.config.ValidationURL,
Success: true,
Speed: duration,
StatusCode: resp.StatusCode,
BodySize: int64(len(body)),
}
// Perform validation checks
if c.debug {
result.DebugInfo += fmt.Sprintf("[VALIDATE] Checking response status code: %d\n", resp.StatusCode)
}
// Check response status code
if c.config.RequireStatusCode > 0 && resp.StatusCode != c.config.RequireStatusCode {
validationCheck.Success = false
validationCheck.Error = fmt.Sprintf("unexpected status code: %d (expected: %d)",
resp.StatusCode, c.config.RequireStatusCode)
result.CheckResults = append(result.CheckResults, validationCheck)
if c.debug {
result.DebugInfo += fmt.Sprintf("[VALIDATE] Status code check failed: %s\n", validationCheck.Error)
}
return errors.NewHTTPError(errors.ErrorHTTPUnexpectedStatus, "unexpected status code", c.config.ValidationURL, nil).
WithDetail("status_code", resp.StatusCode).
WithDetail("expected_code", c.config.RequireStatusCode)
}
// Check response size
if c.debug {
result.DebugInfo += fmt.Sprintf("[VALIDATE] Checking response size: %d bytes\n", len(body))
}
if len(body) < c.config.MinResponseBytes {
validationCheck.Success = false
validationCheck.Error = fmt.Sprintf("response too small: %d bytes (min: %d)",
len(body), c.config.MinResponseBytes)
result.CheckResults = append(result.CheckResults, validationCheck)
if c.debug {
result.DebugInfo += fmt.Sprintf("[VALIDATE] Response size check failed: %s\n", validationCheck.Error)
}
return fmt.Errorf("response too small: %d bytes", len(body))
}
// Check for disallowed keywords
if c.debug && len(c.config.DisallowedKeywords) > 0 {
result.DebugInfo += fmt.Sprintf("[VALIDATE] Checking for disallowed keywords\n")
}
for _, keyword := range c.config.DisallowedKeywords {
if strings.Contains(string(body), keyword) {
validationCheck.Success = false
validationCheck.Error = fmt.Sprintf("response contains disallowed keyword: %s", keyword)
result.CheckResults = append(result.CheckResults, validationCheck)
if c.debug {
result.DebugInfo += fmt.Sprintf("[VALIDATE] Disallowed keyword found: %s\n", keyword)
}
return fmt.Errorf("response contains disallowed keyword: %s", keyword)
}
}
// Check for required content match
if c.config.RequireContentMatch != "" {
if c.debug {
result.DebugInfo += fmt.Sprintf("[VALIDATE] Checking for required content match: %s\n",
c.config.RequireContentMatch)
}
if !strings.Contains(string(body), c.config.RequireContentMatch) {
validationCheck.Success = false
validationCheck.Error = "response does not contain required content"
result.CheckResults = append(result.CheckResults, validationCheck)
if c.debug {
result.DebugInfo += fmt.Sprintf("[VALIDATE] Required content not found\n")
}
return fmt.Errorf("response does not contain required content")
}
}
// Check for required header fields
if c.debug && len(c.config.RequireHeaderFields) > 0 {
result.DebugInfo += fmt.Sprintf("[VALIDATE] Checking for required header fields\n")
}
for _, field := range c.config.RequireHeaderFields {
if resp.Header.Get(field) == "" {
validationCheck.Success = false
validationCheck.Error = fmt.Sprintf("response missing required header: %s", field)
result.CheckResults = append(result.CheckResults, validationCheck)
if c.debug {
result.DebugInfo += fmt.Sprintf("[VALIDATE] Missing required header: %s\n", field)
}
return fmt.Errorf("response missing required header: %s", field)
}
}
// All checks passed, add the successful validation result
result.CheckResults = append(result.CheckResults, validationCheck)
if c.debug {
result.DebugInfo += fmt.Sprintf("[VALIDATE] All validation checks passed\n")
}
// Mark the proxy as working
result.Working = true
return nil
}
// performSingleCheck performs a single URL check
func (c *Checker) performSingleCheck(client *http.Client, testURL string, result *ProxyResult) (*CheckResult, error) {
start := time.Now()
checkResult := &CheckResult{
URL: testURL,
}
if c.debug {
result.DebugInfo += fmt.Sprintf("[DEBUG] Testing URL: %s\n", testURL)
}
req, err := http.NewRequest("GET", testURL, nil)
if err != nil {
checkResult.Error = err.Error()
if c.debug {
result.DebugInfo += fmt.Sprintf("[DEBUG] Error creating request: %v\n", err)
}
return checkResult, err
}
// Add headers
req.Header.Set("User-Agent", c.config.UserAgent)
for key, value := range c.config.DefaultHeaders {
req.Header.Set(key, value)
}
// If rDNS lookup is enabled, try to use it for the Host header
if c.config.UseRDNS {
if host, err := lookupRDNS(req.URL.Hostname()); err == nil && host != "" {
if c.debug {
result.DebugInfo += fmt.Sprintf("[DEBUG] Using rDNS host: %s\n", host)
}
req.Host = host
}
}
if c.debug {
result.DebugInfo += fmt.Sprintf("[DEBUG] Sending request with headers: %v\n", req.Header)
}
resp, err := client.Do(req)
if err != nil {
checkResult.Error = err.Error()
if c.debug {
result.DebugInfo += fmt.Sprintf("[DEBUG] Request error: %v\n", err)
}
return checkResult, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
checkResult.Error = err.Error()
if c.debug {
result.DebugInfo += fmt.Sprintf("[DEBUG] Error reading response body: %v\n", err)
}
return checkResult, err
}
checkResult.StatusCode = resp.StatusCode
checkResult.BodySize = int64(len(body))
checkResult.Speed = time.Since(start)
checkResult.Success = c.validateResponse(resp, body)
if c.debug {
result.DebugInfo += fmt.Sprintf("[DEBUG] Response: status=%d, size=%d bytes, time=%v, success=%v\n",
checkResult.StatusCode, checkResult.BodySize, checkResult.Speed, checkResult.Success)
}
return checkResult, nil
}
// lookupRDNS performs a reverse DNS lookup on an IP address
func lookupRDNS(ip string) (string, error) {
names, err := net.LookupAddr(ip)
if err != nil {
return "", err
}
if len(names) == 0 {
return "", nil
}
// Remove trailing dot from PTR record
return strings.TrimSuffix(names[0], "."), nil
}
func (c *Checker) makeRequest(client *http.Client, urlStr string, result *ProxyResult) (*http.Response, error) {
// Create a context with the configured timeout
ctx, cancel := context.WithTimeout(context.Background(), c.config.Timeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", urlStr, nil)
if err != nil {
if c.debug {
result.DebugInfo += fmt.Sprintf("[DEBUG] Error creating request: %v\n", err)
}
return nil, err
}
// Apply rate limiting if enabled
if parsedURL, err := url.Parse(urlStr); err == nil {
c.applyRateLimit(parsedURL.Hostname(), result)
}
// Set headers
for key, value := range c.config.DefaultHeaders {
req.Header.Set(key, value)
}
req.Header.Set("User-Agent", c.config.UserAgent)
if c.debug {
result.DebugInfo += fmt.Sprintf("[DEBUG] Making request to: %s\n", urlStr)
// Get proxy information in a more readable format
proxyInfo := "direct connection"
if transport, ok := client.Transport.(*http.Transport); ok && transport.Proxy != nil {
// Try to get the proxy URL by making a test request
if proxyURL, err := transport.Proxy(req); err == nil && proxyURL != nil {
proxyInfo = proxyURL.String()
} else {
proxyInfo = "configured (address unavailable)"
}
}
result.DebugInfo += fmt.Sprintf("[DEBUG] Using proxy: %s\n", proxyInfo)
result.DebugInfo += fmt.Sprintf("[DEBUG] Full request:\n")
result.DebugInfo += fmt.Sprintf(" Method: %s\n", req.Method)
result.DebugInfo += fmt.Sprintf(" URL: %s\n", req.URL.String())
result.DebugInfo += fmt.Sprintf("[DEBUG] Headers:\n")
for key, values := range req.Header {
result.DebugInfo += fmt.Sprintf(" %s: %v\n", key, values)
}
}
start := time.Now()
resp, err := client.Do(req)
duration := time.Since(start)
if c.debug {
if err != nil {
result.DebugInfo += fmt.Sprintf("[DEBUG] Request error: %v\n", err)
} else if resp != nil {
result.DebugInfo += fmt.Sprintf("[DEBUG] Response received in %v:\n", duration)
result.DebugInfo += fmt.Sprintf(" Status: %s\n", resp.Status)
result.DebugInfo += fmt.Sprintf("[DEBUG] Headers:\n")
for key, values := range resp.Header {
result.DebugInfo += fmt.Sprintf(" %s: %v\n", key, values)
}
}
}
return resp, err
}
// performDirectScan attempts to scan the target directly as a web server when proxy connection fails
// This allows us to detect SSRF vulnerabilities, misconfigurations, and information leaks
// even when the target doesn't function as a forward proxy
func (c *Checker) performDirectScan(proxyURL *url.URL, result *ProxyResult) bool {
foundSomething := false
// Extract the target host and port
targetHost := proxyURL.Hostname()
targetPort := proxyURL.Port()
if targetPort == "" {
if proxyURL.Scheme == "https" || proxyURL.Scheme == "socks5" {
targetPort = "443"
} else {
targetPort = "80"
}
}
// Build the target URL
targetURL := fmt.Sprintf("http://%s:%s", targetHost, targetPort)
if c.debug {
result.DebugInfo += fmt.Sprintf("[DIRECT SCAN] Attempting direct vulnerability scan on %s\n", targetURL)
}
// Create a direct HTTP client (not using the target as a proxy)
directClient := &http.Client{
Timeout: c.config.Timeout,
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 10,
MaxConnsPerHost: 50,
IdleConnTimeout: 90 * time.Second,
DisableKeepAlives: false,
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse // Don't follow redirects
},
}
// Test 1: Try to access root path to see if it responds
req, err := http.NewRequest("GET", targetURL, nil)
if err != nil {
if c.debug {
result.DebugInfo += fmt.Sprintf("[DIRECT SCAN] Failed to create request: %v\n", err)
}
return false
}
req.Header.Set("User-Agent", c.config.UserAgent)
for key, value := range c.config.DefaultHeaders {
req.Header.Set(key, value)
}
resp, err := directClient.Do(req)
if err != nil {
if c.debug {
result.DebugInfo += fmt.Sprintf("[DIRECT SCAN] No response from target: %v\n", err)
}
return false
}
defer resp.Body.Close()
// Read response body
body, err := io.ReadAll(resp.Body)
if err != nil {
if c.debug {
result.DebugInfo += fmt.Sprintf("[DIRECT SCAN] Failed to read response: %v\n", err)
}
return false
}
if c.debug {
result.DebugInfo += fmt.Sprintf("[DIRECT SCAN] Received response: HTTP %d (%d bytes)\n", resp.StatusCode, len(body))
}
// Mark as not working as proxy, but note we got a response
result.Working = false
result.Type = ProxyTypeUnknown
// Check for information leaks in headers
leakedInfo := []string{}
// Check for server header
if serverHeader := resp.Header.Get("Server"); serverHeader != "" {
leakedInfo = append(leakedInfo, fmt.Sprintf("Server: %s", serverHeader))
foundSomething = true
}
// Check for internal IP leaks
internalHeaders := []string{
"X-Forwarded-For", "X-Real-IP", "X-Original-IP", "X-Client-IP",