-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanager.go
More file actions
543 lines (457 loc) · 14.6 KB
/
Copy pathmanager.go
File metadata and controls
543 lines (457 loc) · 14.6 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
package discovery
import (
"fmt"
"sort"
"strings"
"time"
"github.com/ResistanceIsUseless/ProxyHawk/internal/config"
"github.com/ResistanceIsUseless/ProxyHawk/internal/errors"
"github.com/ResistanceIsUseless/ProxyHawk/internal/logging"
)
// Manager coordinates proxy discovery across multiple sources
type Manager struct {
config config.DiscoveryConfig
discoverers map[string]Discoverer
logger *logging.Logger
filters FilterOptions
scoring ScoringWeights
honeypotDetector *HoneypotDetector
enableHoneypotFilter bool
}
// NewManager creates a new discovery manager
func NewManager(discoveryConfig config.DiscoveryConfig, logger *logging.Logger) *Manager {
m := &Manager{
config: discoveryConfig,
discoverers: make(map[string]Discoverer),
logger: logger,
filters: DefaultFilterOptions(),
scoring: DefaultScoringWeights(),
honeypotDetector: NewHoneypotDetector(),
enableHoneypotFilter: discoveryConfig.EnableHoneypotFilter,
}
// Initialize discoverers based on configuration
if discoveryConfig.ShodanAPIKey != "" {
m.discoverers["shodan"] = NewShodanDiscoverer(discoveryConfig.ShodanAPIKey)
}
// Initialize Censys discoverer if configured
if discoveryConfig.CensysAPIKey != "" && discoveryConfig.CensysSecret != "" {
m.discoverers["censys"] = NewCensysDiscoverer(discoveryConfig.CensysAPIKey, discoveryConfig.CensysSecret)
}
// Initialize free lists discoverer (always available)
m.discoverers["freelists"] = NewFreeListsDiscoverer()
// Initialize web scraper discoverer (always available)
m.discoverers["webscraper"] = NewWebScraperDiscoverer()
return m
}
// SetHoneypotFilterEnabled enables or disables honeypot filtering
func (m *Manager) SetHoneypotFilterEnabled(enabled bool) {
m.enableHoneypotFilter = enabled
}
// DefaultFilterOptions returns sensible default filter options
func DefaultFilterOptions() FilterOptions {
return FilterOptions{
MinConfidence: 0.3,
MaxAge: 24 * time.Hour,
Countries: []string{}, // Empty means all countries
ExcludeCountries: []string{"CN", "RU", "KP", "IR"}, // Common exclusions
Protocols: []string{"http", "https", "socks4", "socks5"},
MinPort: 1,
MaxPort: 65535,
RequireAuth: nil, // Don't care about auth
ExcludeMalicious: true,
MaxResults: 1000,
}
}
// SetFilters updates the filter options
func (m *Manager) SetFilters(filters FilterOptions) {
m.filters = filters
}
// SetScoring updates the scoring weights
func (m *Manager) SetScoring(scoring ScoringWeights) {
m.scoring = scoring
}
// GetAvailableSources returns the names of configured discoverers
func (m *Manager) GetAvailableSources() []string {
var sources []string
for name, discoverer := range m.discoverers {
if discoverer.IsConfigured() {
sources = append(sources, name)
}
}
sort.Strings(sources)
return sources
}
// SearchAll searches for proxy candidates across all configured sources
func (m *Manager) SearchAll(query string, maxResults int) (*DiscoveryResult, error) {
if len(m.discoverers) == 0 {
return nil, errors.NewConfigError(errors.ErrorConfigNotFound, "no discovery sources configured", nil)
}
sources := m.GetAvailableSources()
if len(sources) == 0 {
return nil, errors.NewConfigError(errors.ErrorConfigNotFound, "no discovery sources available", nil)
}
m.logger.Info("Starting proxy discovery across all sources",
"query", query,
"max_results", maxResults,
"sources", sources)
start := time.Now()
allCandidates := make([]ProxyCandidate, 0, maxResults)
allErrors := make([]string, 0)
metadata := make(map[string]interface{})
// Search each source
for _, sourceName := range sources {
discoverer := m.discoverers[sourceName]
m.logger.Info("Searching source", "source", sourceName)
result, err := discoverer.Search(query, maxResults)
if err != nil {
errMsg := fmt.Sprintf("%s: %v", sourceName, err)
allErrors = append(allErrors, errMsg)
m.logger.Warn("Source search failed", "source", sourceName, "error", err)
continue
}
m.logger.Info("Source search completed",
"source", sourceName,
"candidates", len(result.Candidates),
"total", result.Total,
"duration", result.Duration)
allCandidates = append(allCandidates, result.Candidates...)
metadata[sourceName+"_results"] = len(result.Candidates)
metadata[sourceName+"_total"] = result.Total
metadata[sourceName+"_duration"] = result.Duration.String()
}
// Deduplicate candidates
if m.config.Deduplicate {
allCandidates = m.deduplicateCandidates(allCandidates)
m.logger.Info("Deduplicated candidates", "count", len(allCandidates))
}
// Filter candidates
filtered := m.filterCandidates(allCandidates)
m.logger.Info("Basic filtering completed", "before", len(allCandidates), "after", len(filtered))
// Apply honeypot filtering if enabled
var honeypotFiltered []ProxyCandidate
var suspiciousCandidates []ProxyCandidate
if m.enableHoneypotFilter {
honeypotFiltered, suspiciousCandidates = m.honeypotDetector.FilterHoneypots(filtered, 0.4)
if len(suspiciousCandidates) > 0 {
m.logger.Warn("Honeypot detection filtered suspicious candidates",
"original", len(filtered),
"clean", len(honeypotFiltered),
"suspicious", len(suspiciousCandidates))
}
filtered = honeypotFiltered
} else {
honeypotFiltered = filtered
}
m.logger.Info("All filtering completed", "before", len(allCandidates), "after", len(filtered))
// Score and sort candidates
scored := m.scoreCandidates(filtered)
sort.Slice(scored, func(i, j int) bool {
return scored[i].Confidence > scored[j].Confidence
})
// Limit results
if len(scored) > maxResults {
scored = scored[:maxResults]
}
duration := time.Since(start)
m.logger.Info("Discovery completed",
"total_found", len(allCandidates),
"after_filtering", len(filtered),
"final_results", len(scored),
"duration", duration,
"sources_used", len(sources))
return &DiscoveryResult{
Query: query,
Source: "all",
Timestamp: start,
Duration: duration,
Total: len(allCandidates),
Filtered: len(scored),
Candidates: scored,
Errors: allErrors,
Metadata: metadata,
}, nil
}
// SearchSource searches a specific discovery source
func (m *Manager) SearchSource(sourceName, query string, maxResults int) (*DiscoveryResult, error) {
discoverer, exists := m.discoverers[sourceName]
if !exists {
return nil, fmt.Errorf("discovery source '%s' not available", sourceName)
}
if !discoverer.IsConfigured() {
return nil, fmt.Errorf("discovery source '%s' not configured", sourceName)
}
m.logger.Info("Searching specific source",
"source", sourceName,
"query", query,
"max_results", maxResults)
result, err := discoverer.Search(query, maxResults)
if err != nil {
return nil, fmt.Errorf("search failed for source %s: %w", sourceName, err)
}
// Apply filtering and scoring
filtered := m.filterCandidates(result.Candidates)
// Apply honeypot filtering if enabled
if m.enableHoneypotFilter {
honeypotFiltered, suspiciousCandidates := m.honeypotDetector.FilterHoneypots(filtered, 0.4)
if len(suspiciousCandidates) > 0 {
m.logger.Warn("Honeypot detection filtered suspicious candidates from single source",
"source", sourceName,
"original", len(filtered),
"clean", len(honeypotFiltered),
"suspicious", len(suspiciousCandidates))
}
filtered = honeypotFiltered
}
scored := m.scoreCandidates(filtered)
// Sort by confidence
sort.Slice(scored, func(i, j int) bool {
return scored[i].Confidence > scored[j].Confidence
})
// Update result
result.Candidates = scored
result.Filtered = len(scored)
m.logger.Info("Source search completed",
"source", sourceName,
"original", len(result.Candidates),
"filtered", len(scored),
"duration", result.Duration)
return result, nil
}
// GetHostDetails gets detailed information about a specific host
func (m *Manager) GetHostDetails(sourceName, ip string) (*ProxyCandidate, error) {
discoverer, exists := m.discoverers[sourceName]
if !exists {
return nil, fmt.Errorf("discovery source '%s' not available", sourceName)
}
if !discoverer.IsConfigured() {
return nil, fmt.Errorf("discovery source '%s' not configured", sourceName)
}
m.logger.Info("Getting host details", "source", sourceName, "ip", ip)
candidate, err := discoverer.GetDetails(ip)
if err != nil {
return nil, fmt.Errorf("failed to get details for %s from %s: %w", ip, sourceName, err)
}
// Apply scoring
scored := m.scoreCandidates([]ProxyCandidate{*candidate})
if len(scored) > 0 {
return &scored[0], nil
}
return candidate, nil
}
// GetPresetQueries returns preset search queries for different proxy types
func (m *Manager) GetPresetQueries() map[string][]string {
queries := make(map[string][]string)
// Add Shodan queries if available
if _, exists := m.discoverers["shodan"]; exists {
queries["shodan"] = ShodanProxyQueries
}
// Add Censys queries if available
if _, exists := m.discoverers["censys"]; exists {
queries["censys"] = CensysProxyQueries
}
// Add free lists queries if available
if _, exists := m.discoverers["freelists"]; exists {
queries["freelists"] = FreeListProxyQueries
}
// Add web scraper queries if available
if _, exists := m.discoverers["webscraper"]; exists {
queries["webscraper"] = WebScraperProxyQueries
}
// Add general queries
queries["general"] = []string{
"proxy server",
"squid proxy",
"nginx proxy",
"apache proxy",
"socks proxy",
"http proxy",
"https proxy",
"anonymous proxy",
"elite proxy",
"transparent proxy",
}
return queries
}
// deduplicateCandidates removes duplicate candidates based on IP and port
func (m *Manager) deduplicateCandidates(candidates []ProxyCandidate) []ProxyCandidate {
seen := make(map[string]*ProxyCandidate)
for i := range candidates {
candidate := &candidates[i]
key := fmt.Sprintf("%s:%d", candidate.IP, candidate.Port)
existing, exists := seen[key]
if !exists {
seen[key] = candidate
continue
}
// Keep the candidate with higher confidence
if candidate.Confidence > existing.Confidence {
seen[key] = candidate
} else if candidate.Confidence == existing.Confidence {
// If confidence is equal, prefer more recent discovery
if candidate.LastSeen.After(existing.LastSeen) {
seen[key] = candidate
}
}
}
// Convert back to slice
result := make([]ProxyCandidate, 0, len(seen))
for _, candidate := range seen {
result = append(result, *candidate)
}
return result
}
// filterCandidates applies filtering rules to candidates
func (m *Manager) filterCandidates(candidates []ProxyCandidate) []ProxyCandidate {
filtered := make([]ProxyCandidate, 0, len(candidates))
for _, candidate := range candidates {
if m.shouldKeepCandidate(candidate) {
filtered = append(filtered, candidate)
}
}
return filtered
}
// shouldKeepCandidate determines if a candidate passes filtering rules
func (m *Manager) shouldKeepCandidate(candidate ProxyCandidate) bool {
// Check confidence threshold
if candidate.Confidence < m.filters.MinConfidence {
return false
}
// Check age
if m.filters.MaxAge > 0 && time.Since(candidate.LastSeen) > m.filters.MaxAge {
return false
}
// Check country inclusion
if len(m.filters.Countries) > 0 {
found := false
for _, country := range m.filters.Countries {
if strings.EqualFold(candidate.Country, country) {
found = true
break
}
}
if !found {
return false
}
}
// Check country exclusion
for _, excludeCountry := range m.filters.ExcludeCountries {
if strings.EqualFold(candidate.Country, excludeCountry) {
return false
}
}
// Check protocol
if len(m.filters.Protocols) > 0 {
found := false
for _, protocol := range m.filters.Protocols {
if strings.EqualFold(candidate.Protocol, protocol) {
found = true
break
}
}
if !found {
return false
}
}
// Check port range
if candidate.Port < m.filters.MinPort || candidate.Port > m.filters.MaxPort {
return false
}
// Check auth requirement
if m.filters.RequireAuth != nil {
if *m.filters.RequireAuth != candidate.AuthRequired {
return false
}
}
// Check malicious exclusion
if m.filters.ExcludeMalicious && candidate.IsMalicious {
return false
}
return true
}
// scoreCandidates applies scoring to candidates based on various factors
func (m *Manager) scoreCandidates(candidates []ProxyCandidate) []ProxyCandidate {
scored := make([]ProxyCandidate, len(candidates))
copy(scored, candidates)
for i := range scored {
// Calculate base score
scored[i].Confidence = m.calculateScore(&scored[i])
// Apply honeypot penalty to confidence score
if m.enableHoneypotFilter {
m.honeypotDetector.UpdateCandidateConfidence(&scored[i])
}
}
return scored
}
// calculateScore calculates a comprehensive score for a proxy candidate
func (m *Manager) calculateScore(candidate *ProxyCandidate) float64 {
_ = candidate.Confidence // Original confidence (unused in final calculation)
// Source reliability scoring
sourceScore := 0.0
switch candidate.Source {
case "shodan":
sourceScore = 0.9 // Shodan is highly reliable
case "censys":
sourceScore = 0.8
case "free-lists":
sourceScore = 0.3 // Free lists are less reliable
default:
sourceScore = 0.5
}
// Location desirability scoring
locationScore := 0.5 // Default neutral
desirableCountries := []string{"US", "GB", "DE", "NL", "FR", "CA", "AU", "SE", "NO", "DK"}
for _, country := range desirableCountries {
if strings.EqualFold(candidate.Country, country) {
locationScore = 0.8
break
}
}
// Technical indicators scoring
techScore := 0.0
if len(candidate.ProxyHeaders) > 0 {
techScore += 0.3
}
if candidate.ProxyType != "unknown" && candidate.ProxyType != "" {
techScore += 0.2
}
if candidate.ServerHeader != "" {
techScore += 0.1
}
if candidate.TLSEnabled {
techScore += 0.1
}
// Freshness scoring
freshnessScore := 1.0
age := time.Since(candidate.LastSeen)
if age > 24*time.Hour {
freshnessScore = 0.8
}
if age > 7*24*time.Hour {
freshnessScore = 0.6
}
if age > 30*24*time.Hour {
freshnessScore = 0.3
}
// Network quality scoring (simplified)
networkScore := 0.5
if candidate.ASN != "" {
networkScore += 0.2
}
if candidate.ISP != "" {
networkScore += 0.1
}
// Apply weights and combine scores
finalScore := (sourceScore * m.scoring.SourceReliability) +
(locationScore * m.scoring.LocationDesirability) +
(techScore * m.scoring.TechnicalIndicators) +
(freshnessScore * m.scoring.Freshness) +
(networkScore * m.scoring.NetworkQuality)
// Ensure score is between 0 and 1
if finalScore > 1.0 {
finalScore = 1.0
}
if finalScore < 0.0 {
finalScore = 0.0
}
return finalScore
}