-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvulnscanner.py
1956 lines (1675 loc) · 72 KB
/
vulnscanner.py
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
#!/usr/bin/env python3
"""
AI-Powered Vulnerability Scanner
Developed by RZ1 (https://github.com/THE-RZ1-x)
Repository: https://github.com/THE-RZ1-x/Ai_Vuln_Scanner
A sophisticated vulnerability scanner that uses AI to analyze and detect security vulnerabilities
in network services and systems.
"""
# -*- coding: utf-8 -*-
# Author: cbk914
import os
import sys
import nmap
import json
import time
import socket
import shodan
import logging
import vulners
import argparse
import requests
import ipaddress
import traceback
from tqdm import tqdm
import google.generativeai as genai
from datetime import datetime
from dotenv import load_dotenv
from bs4 import BeautifulSoup
from typing import Dict, List, Union
from requests.exceptions import RequestException
import re
import vulners
import shodan
from jinja2 import Template
from dotenv import load_dotenv
from bs4 import BeautifulSoup
from typing import Dict, List, Union
from requests.exceptions import RequestException
import re
import requests
import json
import time
import logging
import ipaddress
from tqdm import tqdm
from jinja2 import Template
from dotenv import load_dotenv
from bs4 import BeautifulSoup
from typing import Dict, List, Union
from requests.exceptions import RequestException
import re
import vulners
import shodan
import aiohttp
import asyncio
from web_scanner import WebScanner, WebVulnerability
from report_generator import ReportGenerator, ReportData
from container_scanner import ContainerScanner, ContainerScanResult
from cloud_scanner import CloudScanner, CloudScanResult
# Parse command line arguments
parser = argparse.ArgumentParser(description='AI-powered vulnerability scanner')
parser.add_argument('-t', '--target', required=True, help='Target IP address, hostname, container image, or cloud provider')
parser.add_argument('-s', '--scan-type', choices=['basic', 'comprehensive', 'container', 'cloud'], default='basic',
help='Type of scan to perform')
parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose output')
parser.add_argument('-o', '--output', help='Output file name (without extension)')
parser.add_argument('--container', action='store_true', help='Treat target as a container image')
parser.add_argument('--cloud-providers', nargs='+', choices=['aws', 'azure', 'gcp'],
help='Cloud providers to scan when using cloud scan type')
args = parser.parse_args()
# Configure logging based on verbosity
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Load environment variables
load_dotenv()
# Initialize global scanner
scanner = None
ai_analyzer = None
def init_scanner():
"""Initialize the global scanner instance."""
global scanner
if scanner is None:
scanner = VulnerabilityScanner()
return scanner
def init_ai_analyzer():
"""Initialize the global AI analyzer instance."""
global ai_analyzer
if ai_analyzer is None:
ai_analyzer = AISecurityAnalyzer()
return ai_analyzer
class VulnerabilityScanner:
def __init__(self):
"""Initialize the scanner with necessary APIs."""
self.vulners_api = None
self.shodan_api = None
self.web_scanner = WebScanner()
self.container_scanner = ContainerScanner()
self.cloud_scanner = CloudScanner()
self.report_generator = ReportGenerator()
self.initialize_apis()
def initialize_apis(self):
"""Initialize various security APIs."""
try:
# Initialize Vulners API
self.vulners_api = init_vulners_api()
if self.vulners_api:
print("✓ Vulners API initialized")
# Initialize Shodan API if needed
shodan_api_key = os.getenv('SHODAN_API_KEY')
if shodan_api_key:
try:
import shodan
self.shodan_api = shodan.Shodan(shodan_api_key)
print("✓ Shodan API initialized")
except Exception as e:
print(f"✗ Error initializing Shodan API: {str(e)}")
except Exception as e:
print(f"✗ Error initializing APIs: {str(e)}")
async def analyze_service(self, service_info: dict) -> dict:
"""Analyze a service and its vulnerabilities."""
try:
# Get AI analysis
analyzer = init_ai_analyzer()
ai_analysis = await analyzer.analyze_attack_surface(service_info)
# Get vulnerability information if Vulners API is available
vulns = []
if self.vulners_api and service_info.get('product') and service_info.get('version'):
try:
vulns_result = self.vulners_api.softwareVulnerabilities(
service_info['product'],
service_info['version']
)
if vulns_result.get('vulnerabilities'):
vulns = vulns_result['vulnerabilities']
except Exception as e:
print(f"✗ Error getting vulnerabilities: {str(e)}")
return {
'vulnerabilities': vulns,
'ai_analysis': ai_analysis,
'recommendations': ai_analysis.get('mitigation_steps', []) if ai_analysis else []
}
except Exception as e:
print(f"✗ Error analyzing service: {str(e)}")
return {
'vulnerabilities': [],
'ai_analysis': {},
'recommendations': []
}
async def scan(self, target: str, scan_type: str = 'basic') -> dict:
"""
Perform vulnerability scan based on target type.
Args:
target: IP address, hostname, container image, or cloud provider
scan_type: Type of scan to perform
Returns:
dict: Scan results including vulnerabilities and analysis
"""
start_time = time.time()
try:
# Check scan type
if scan_type == 'cloud':
return await self._scan_cloud_infrastructure(target)
elif scan_type == 'container' or self._is_container_target(target):
return await self._scan_container(target)
else:
return await self._scan_network_target(target, scan_type)
except Exception as e:
logger.error(f"Error during scan: {str(e)}")
raise
def _is_container_target(self, target: str) -> bool:
"""Determine if the target is a container image."""
return ('/' in target or ':' in target) and not any(char in target for char in ['http://', 'https://', '*'])
async def _scan_container(self, target: str) -> dict:
"""Perform container security scan."""
try:
print(f"Starting container security scan for {target}...")
# Scan container
container_results = await self.container_scanner.scan_container(target)
# Calculate risk score based on findings
risk_score = self._calculate_container_risk_score(container_results)
# Prepare report data
report_data = ReportData(
target=target,
scan_type='container',
timestamp=datetime.now().strftime("%Y-%m-%d_%H-%M-%S"),
vulnerabilities=self._convert_container_vulns(container_results.vulnerabilities),
system_info={'type': 'container', 'image': target},
web_vulnerabilities=[],
network_services=[],
risk_score=risk_score,
scan_duration=time.time() - start_time
)
# Generate report
report_path = self.report_generator.generate_report(
report_data,
output_dir="reports"
)
print(f"✓ Container scan complete. Report generated: {report_path}")
return {
'container_results': container_results,
'risk_score': risk_score,
'report_path': report_path
}
except Exception as e:
logger.error(f"Error scanning container: {str(e)}")
raise
def _calculate_container_risk_score(self, results: ContainerScanResult) -> float:
"""Calculate risk score for container scan results."""
score = 0.0
# Vulnerability severity weights
severity_weights = {
'Critical': 10.0,
'High': 8.0,
'Medium': 5.0,
'Low': 2.0,
'Unknown': 1.0
}
# Calculate vulnerability score
vuln_count = len(results.vulnerabilities)
if vuln_count > 0:
severity_scores = [severity_weights.get(v.severity, 1.0) for v in results.vulnerabilities]
score += sum(severity_scores) / vuln_count
# Add points for misconfigurations
score += len(results.misconfigurations) * 2.0
# Add points for exposed secrets
score += len(results.secrets) * 3.0
# Add points for compliance issues
score += len(results.compliance_issues) * 1.5
# Normalize score to 0-10 range
score = min(score, 10.0)
return score
def _convert_container_vulns(self, container_vulns: List[ContainerVulnerability]) -> List[Dict]:
"""Convert container vulnerabilities to standard format."""
return [{
'type': 'Container',
'id': vuln.id,
'severity': vuln.severity,
'description': vuln.description,
'package': vuln.package,
'current_version': vuln.version,
'fixed_version': vuln.fixed_version,
'cve_id': vuln.cve_id,
'remediation': vuln.remediation
} for vuln in container_vulns]
async def _scan_network_target(self, target: str, scan_type: str) -> dict:
"""Perform network and web application scan."""
# Validate target
if not validate_target(target):
raise ValueError(f"Invalid target: {target}")
# Initialize components
network_mapper = NetworkMapper()
ai_analyzer = init_ai_analyzer()
# Perform network scan
print(f"Running network scan on {target}...")
scan_results = await network_mapper.scan_target(target, scan_type)
# Perform web vulnerability scan if HTTP/HTTPS services are found
web_vulns = []
if any(service['name'] in ['http', 'https'] for service in scan_results.get('services', [])):
print("Detected web services, performing web vulnerability scan...")
web_vulns = await self.web_scanner.scan_web_application(f"http://{target}")
# Analyze results
analysis_results = await analyze_vulnerabilities(scan_results)
# Calculate risk score
risk_score = calculate_risk_level(target)
# Prepare report data
report_data = ReportData(
target=target,
scan_type=scan_type,
timestamp=datetime.now().strftime("%Y-%m-%d_%H-%M-%S"),
vulnerabilities=analysis_results.get('vulnerabilities', []),
system_info=scan_results.get('system_info', {}),
web_vulnerabilities=web_vulns,
network_services=scan_results.get('services', []),
risk_score=risk_score,
scan_duration=time.time() - start_time
)
# Generate report
report_path = self.report_generator.generate_report(
report_data,
output_dir="reports"
)
print(f"✓ Network scan complete. Report generated: {report_path}")
return {
'scan_results': scan_results,
'analysis': analysis_results,
'web_vulnerabilities': web_vulns,
'risk_score': risk_score,
'report_path': report_path
}
async def _scan_cloud_infrastructure(self, target: str) -> dict:
"""Perform cloud infrastructure security scan."""
try:
print("Starting cloud infrastructure security scan...")
# Determine cloud providers to scan
providers = []
if args.cloud_providers:
providers = args.cloud_providers
elif target.lower() in ['aws', 'azure', 'gcp']:
providers = [target.lower()]
else:
providers = ['aws', 'azure', 'gcp'] # Scan all by default
# Scan cloud infrastructure
cloud_results = await self.cloud_scanner.scan_cloud_infrastructure(providers)
# Calculate overall risk score
risk_score = self._calculate_cloud_risk_score(cloud_results)
# Prepare report data
report_data = ReportData(
target=f"Cloud Infrastructure ({', '.join(providers)})",
scan_type='cloud',
timestamp=datetime.now().strftime("%Y-%m-%d_%H-%M-%S"),
vulnerabilities=self._convert_cloud_vulns(cloud_results),
system_info={'providers': providers},
web_vulnerabilities=[],
network_services=[],
risk_score=risk_score,
scan_duration=time.time() - start_time,
cloud_findings=cloud_results
)
# Generate report
report_path = self.report_generator.generate_report(
report_data,
output_dir="reports"
)
print(f"✓ Cloud infrastructure scan complete. Report generated: {report_path}")
return {
'cloud_results': cloud_results,
'risk_score': risk_score,
'report_path': report_path
}
except Exception as e:
logger.error(f"Error scanning cloud infrastructure: {str(e)}")
raise
def _calculate_cloud_risk_score(self, results: Dict[str, CloudScanResult]) -> float:
"""Calculate overall cloud infrastructure risk score."""
if not results:
return 0.0
total_score = 0.0
weights = {
'Critical': 10.0,
'High': 8.0,
'Medium': 5.0,
'Low': 2.0,
'Unknown': 1.0
}
for provider_results in results.values():
# Vulnerability score
vuln_score = sum(weights.get(v.severity, 1.0) for v in provider_results.vulnerabilities)
# Misconfiguration score
misconfig_score = len(provider_results.misconfigurations) * 2.0
# IAM issues score
iam_score = len(provider_results.iam_issues) * 3.0
# Network findings score
network_score = len(provider_results.network_findings) * 2.5
# Add to total
total_score += (vuln_score + misconfig_score + iam_score + network_score)
# Normalize to 0-10 range
return min(total_score / len(results), 10.0)
def _convert_cloud_vulns(self, results: Dict[str, CloudScanResult]) -> List[Dict]:
"""Convert cloud vulnerabilities to standard format."""
vulns = []
for provider, result in results.items():
for vuln in result.vulnerabilities:
vulns.append({
'type': 'Cloud',
'provider': provider,
'resource_id': vuln.resource_id,
'severity': vuln.severity,
'description': vuln.description,
'recommendation': vuln.recommendation,
'compliance_standards': vuln.compliance_standards,
'risk_score': vuln.risk_score
})
return vulns
class VulnerabilityDatabase:
def __init__(self):
self.nvd_api_key = os.getenv('NVD_API_KEY')
self.base_url = "https://services.nvd.nist.gov/rest/json/cves/2.0"
self.cache_file = "vuln_cache.json"
self.cache = self._load_cache()
self.vulners_api = scanner.vulners_api
self.shodan_api = scanner.shodan_api
def _load_cache(self):
try:
if os.path.exists(self.cache_file):
with open(self.cache_file, 'r') as f:
return json.load(f)
return {}
except Exception as e:
logger.error(f"Error loading vulnerability cache: {e}")
return {}
def _save_cache(self):
try:
with open(self.cache_file, 'w') as f:
json.dump(self.cache, f)
except Exception as e:
logger.error(f"Error saving vulnerability cache: {e}")
def search_vulnerabilities(self, product: str, version: str = None) -> list:
"""Search for vulnerabilities using multiple sources."""
cache_key = f"{product}:{version}"
if cache_key in self.cache:
return self.cache[cache_key]
vulns = []
# Try Vulners API first
if self.vulners_api:
try:
search_query = f"{product}"
if version:
search_query += f" {version}"
vulners_results = self.vulners_api.search(search_query, limit=100)
for vuln in vulners_results:
vuln_info = {
'id': vuln.get('id'),
'title': vuln.get('title'),
'description': vuln.get('description'),
'severity': float(vuln.get('cvss', {}).get('score', 0)),
'published': vuln.get('published'),
'references': vuln.get('references', []),
'source': 'vulners'
}
vulns.append(vuln_info)
except Exception as e:
logger.error(f"Error searching Vulners: {str(e)}")
# Try NVD API as backup
try:
params = {
'keywordSearch': product,
'resultsPerPage': 100
}
if version:
params['versionStart'] = version
params['versionStartType'] = 'including'
headers = {'apiKey': self.nvd_api_key} if self.nvd_api_key else {}
response = requests.get(
self.base_url,
params=params,
headers=headers,
timeout=10
)
if response.status_code == 200:
data = response.json()
for vuln in data.get('vulnerabilities', []):
cve = vuln.get('cve', {})
vuln_info = {
'id': cve.get('id'),
'description': cve.get('descriptions', [{}])[0].get('value', ''),
'severity': cve.get('metrics', {}).get('cvssMetricV31', [{}])[0].get('cvssData', {}).get('baseScore', 0),
'published': cve.get('published'),
'references': [ref.get('url') for ref in cve.get('references', [])],
'source': 'nvd'
}
vulns.append(vuln_info)
except Exception as e:
logger.error(f"Error searching NVD: {str(e)}")
# Add Shodan data if available
try:
if self.shodan_api:
api = self.shodan_api
results = api.search(f"product:{product}")
for result in results['matches'][:5]:
if 'vulns' in result:
for cve_id, vuln_info in result['vulns'].items():
vulns.append({
'id': cve_id,
'severity': float(vuln_info.get('cvss', 0)),
'description': vuln_info.get('summary', ''),
'source': 'shodan'
})
except Exception as e:
logger.error(f"Error searching Shodan: {str(e)}")
# Remove duplicates based on ID
unique_vulns = {v['id']: v for v in vulns if v['id']}.values()
vulns = sorted(unique_vulns, key=lambda x: float(x.get('severity', 0)), reverse=True)
self.cache[cache_key] = vulns
self._save_cache()
return vulns
class ExploitFinder:
def __init__(self):
self.exploit_db_url = "https://www.exploit-db.com/search?q="
self.metasploit_url = "https://www.rapid7.com/db/?q="
self.cache = {}
def find_exploits(self, cve_id: str) -> dict:
"""Find available exploits for a CVE."""
if cve_id in self.cache:
return self.cache[cve_id]
exploits = {
'exploit_db': [],
'metasploit': [],
'github': []
}
try:
# Search ExploitDB
response = requests.get(f"{self.exploit_db_url}{cve_id}")
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
for link in soup.find_all('a', href=True):
if '/exploits/' in link['href']:
exploits['exploit_db'].append({
'title': link.text.strip(),
'url': f"https://www.exploit-db.com{link['href']}"
})
# Search GitHub
gh_response = requests.get(
f"https://api.github.com/search/repositories?q={cve_id}+in:readme+in:description"
)
if gh_response.status_code == 200:
for repo in gh_response.json().get('items', [])[:5]:
exploits['github'].append({
'title': repo['full_name'],
'url': repo['html_url'],
'description': repo['description']
})
self.cache[cve_id] = exploits
return exploits
except Exception as e:
logger.error(f"Error finding exploits: {e}")
return exploits
class AISecurityAnalyzer:
def __init__(self):
"""Initialize the AI Security Analyzer with multiple AI models."""
self.models = {
'gemini': init_gemini(),
'openai': init_openai(),
'local_ml': init_local_ml_model()
}
self.active_model = 'gemini' # Default model
self.cache = {}
self.last_api_call = 0
self.min_delay = 2
self.autonomous_mode = True
self.security_apis = SecurityAPIIntegration()
async def analyze_attack_surface(self, service_data: dict) -> dict:
"""Enhanced AI-powered attack surface analysis using multiple models."""
try:
# Try primary model first
result = await self._analyze_with_model(self.active_model, service_data)
# If confidence is low, try other models
if result.get('confidence', 1.0) < 0.7:
all_results = await asyncio.gather(*[
self._analyze_with_model(model, service_data)
for model in self.models.keys()
if model != self.active_model
])
# Combine results using ensemble approach
result = self._ensemble_results([result] + all_results)
# Add false positive reduction
result = await self._reduce_false_positives(result)
return result
except Exception as e:
logger.error(f"AI analysis failed: {str(e)}")
return await self.get_fallback_analysis(service_data)
async def _analyze_with_model(self, model_name: str, service_data: dict) -> dict:
"""Analyze using a specific AI model."""
model = self.models[model_name]
# Format prompt based on model type
if model_name == 'gemini':
prompt = self._format_gemini_prompt(service_data)
elif model_name == 'openai':
prompt = self._format_openai_prompt(service_data)
else:
prompt = self._format_generic_prompt(service_data)
# Rate limiting
await self._respect_rate_limit(model_name)
try:
response = await self._get_model_response(model, prompt)
return self.parse_ai_response(response)
except Exception as e:
logger.error(f"Error with {model_name}: {str(e)}")
return {}
async def _reduce_false_positives(self, result: dict) -> dict:
"""Reduce false positives using historical data and verification."""
if not result.get('vulnerabilities'):
return result
verified_vulns = []
for vuln in result['vulnerabilities']:
# Verify using additional sources
verification_score = await self._verify_vulnerability(vuln)
if verification_score >= 0.7: # High confidence threshold
verified_vulns.append(vuln)
result['vulnerabilities'] = verified_vulns
return result
def _ensemble_results(self, results: List[dict]) -> dict:
"""Combine results from multiple models using weighted voting."""
if not results:
return {}
# Weight results based on model confidence and historical accuracy
weighted_results = []
for result in results:
if result:
weight = result.get('confidence', 0.5) * self._get_model_accuracy(result.get('model', 'unknown'))
weighted_results.append((result, weight))
# Combine vulnerabilities with weights
final_vulns = {}
for result, weight in weighted_results:
for vuln in result.get('vulnerabilities', []):
vuln_id = vuln.get('id')
if vuln_id in final_vulns:
final_vulns[vuln_id]['weight'] += weight
else:
vuln['weight'] = weight
final_vulns[vuln_id] = vuln
# Filter final vulnerabilities based on weighted consensus
consensus_threshold = 0.6
final_result = {
'vulnerabilities': [v for v in final_vulns.values() if v['weight'] > consensus_threshold],
'confidence': sum(wr[1] for wr in weighted_results) / len(weighted_results),
'model': 'ensemble'
}
return final_result
def _get_model_accuracy(self, model_name: str) -> float:
"""Get historical accuracy score for a model."""
# TODO: Implement model accuracy tracking
return {
'gemini': 0.85,
'openai': 0.82,
'local_ml': 0.75
}.get(model_name, 0.5)
def parse_ai_response(self, response_text: str) -> dict:
"""Parse the AI response into a structured format."""
try:
# Split response into sections
sections = response_text.split('\n\n')
analysis = {
'findings': [],
'mitigation_steps': [],
'technical_details': [],
'risk_assessment': []
}
current_section = None
for line in response_text.split('\n'):
line = line.strip()
if not line:
continue
# Identify sections
if 'vulnerability' in line.lower() or 'finding' in line.lower():
current_section = 'findings'
elif 'mitigation' in line.lower() or 'recommendation' in line.lower():
current_section = 'mitigation_steps'
elif 'technical' in line.lower() or 'detail' in line.lower():
current_section = 'technical_details'
elif 'risk' in line.lower() or 'impact' in line.lower():
current_section = 'risk_assessment'
elif current_section and line.startswith(('-', '*', '•')):
analysis[current_section].append(line.lstrip('-* •').strip())
return analysis
except Exception as e:
print(f"✗ Error parsing AI response: {str(e)}")
return {
'findings': [],
'mitigation_steps': [],
'technical_details': [],
'risk_assessment': []
}
async def _verify_vulnerability(self, vuln: dict) -> float:
"""Verify a vulnerability using additional sources."""
# TODO: Implement vulnerability verification
return 0.8
async def _respect_rate_limit(self, model_name: str):
"""Respect rate limits for AI models."""
# TODO: Implement rate limiting
pass
async def _get_model_response(self, model, prompt: str) -> str:
"""Get the response from an AI model."""
# TODO: Implement model response handling
return ""
def _format_gemini_prompt(self, service_data: dict) -> str:
"""Format prompt for Gemini AI model."""
# TODO: Implement prompt formatting for Gemini
return ""
def _format_openai_prompt(self, service_data: dict) -> str:
"""Format prompt for OpenAI model."""
# TODO: Implement prompt formatting for OpenAI
return ""
def _format_generic_prompt(self, service_data: dict) -> str:
"""Format prompt for generic AI model."""
# TODO: Implement prompt formatting for generic model
return ""
async def get_fallback_analysis(self, service_data: dict) -> dict:
"""Get fallback analysis when AI analysis fails."""
service_type = service_data.get('name', '').lower()
print(f"Using fallback analysis for {service_type}")
# Get default recommendations based on service type
if 'http' in service_type:
recommendations = [
"Enable HTTPS and redirect HTTP to HTTPS",
"Implement security headers (HSTS, CSP, etc.)",
"Use WAF for additional protection",
"Regular security patching",
"Enable logging and monitoring"
]
elif 'ssh' in service_type:
recommendations = [
"Use strong SSH key authentication",
"Disable password authentication",
"Change default port",
"Implement fail2ban",
"Regular security updates"
]
else:
recommendations = [
"Keep service updated",
"Implement access controls",
"Enable logging",
"Regular security audits",
"Monitor for suspicious activity"
]
return {
'findings': [f"Service {service_type} may have security vulnerabilities"],
'mitigation_steps': recommendations,
'technical_details': [],
'risk_assessment': ['Potential security risk - manual assessment recommended']
}
class SecurityAPIIntegration:
"""Integration with various security APIs"""
def __init__(self):
self.cache = {}
self.cache_duration = 3600 # 1 hour cache
async def get_cve_mitre(self, cve_id: str) -> dict:
"""Get CVE details from MITRE (Free API)"""
url = f"https://cve.circl.lu/api/cve/{cve_id}"
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
return await response.json()
return None
except Exception as e:
logger.error(f"Error fetching CVE from MITRE: {str(e)}")
return None
async def check_virus_total(self, domain: str) -> dict:
"""Query VirusTotal API (Free tier - 500 requests/day)"""
api_key = os.getenv('VIRUSTOTAL_API_KEY')
if not api_key:
return None
url = f"https://www.virustotal.com/vtapi/v2/domain/report"
params = {'apikey': api_key, 'domain': domain}
try:
async with aiohttp.ClientSession() as session:
async with session.get(url, params=params) as response:
if response.status == 200:
return await response.json()
return None
except Exception as e:
logger.error(f"Error checking VirusTotal: {str(e)}")
return None
async def query_abuse_ipdb(self, ip: str) -> dict:
"""Query AbuseIPDB (Free tier - 1000 requests/day)"""
api_key = os.getenv('ABUSEIPDB_API_KEY')
if not api_key:
return None
url = "https://api.abuseipdb.com/api/v2/check"
headers = {
'Accept': 'application/json',
'Key': api_key
}
params = {
'ipAddress': ip,
'maxAgeInDays': 90
}
try:
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, params=params) as response:
if response.status == 200:
return await response.json()
return None
except Exception as e:
logger.error(f"Error checking AbuseIPDB: {str(e)}")
return None
async def check_greynoise(self, ip: str) -> dict:
"""Query GreyNoise (Free Community API)"""
api_key = os.getenv('GREYNOISE_API_KEY')
if not api_key:
return None
url = f"https://api.greynoise.io/v3/community/{ip}"
headers = {'key': api_key}
try:
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as response:
if response.status == 200:
return await response.json()
return None
except Exception as e:
logger.error(f"Error checking GreyNoise: {str(e)}")
return None
async def check_urlscan(self, domain: str) -> dict:
"""Query URLScan.io (Free API)"""
api_key = os.getenv('URLSCAN_API_KEY')
if not api_key:
return None
url = "https://urlscan.io/api/v1/scan/"
headers = {
'API-Key': api_key,
'Content-Type': 'application/json'
}
data = {'url': domain, 'visibility': 'public'}
try:
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers, json=data) as response:
if response.status == 200:
return await response.json()
return None
except Exception as e:
logger.error(f"Error submitting to URLScan: {str(e)}")
return None
class NetworkMapper:
def __init__(self):
self.vuln_db = VulnerabilityDatabase()
self.exploit_finder = ExploitFinder()
self.scan_results = {}
def analyze_service(self, service: dict) -> dict:
"""Analyze a single service for vulnerabilities."""
product = service.get('product', '')
version = service.get('version', '')
vulnerabilities = self.vuln_db.search_vulnerabilities(product, version)
high_risk_vulns = []
for vuln in vulnerabilities:
if vuln['severity'] >= 7.0: # CVSS score >= 7.0 is high
exploits = self.exploit_finder.find_exploits(vuln['id'])
if any(exploits.values()): # If any exploits found
vuln['exploits'] = exploits
high_risk_vulns.append(vuln)
return {
'service_info': service,
'vulnerabilities': vulnerabilities,
'high_risk': high_risk_vulns
}
def get_service_recommendations(self, service_analysis: dict) -> list:
"""Generate security recommendations based on service analysis."""
recommendations = []
service = service_analysis['service_info']
# Basic service hardening
if service.get('name') == 'ssh':
recommendations.extend([
"Disable root login via SSH",
"Use key-based authentication instead of passwords",
"Change default SSH port",
"Implement fail2ban for brute force protection"
])
elif service.get('name') == 'http' or service.get('name') == 'https':
recommendations.extend([
"Enable HTTPS and redirect HTTP to HTTPS",
"Implement security headers (HSTS, CSP, etc.)",
"Use WAF for additional protection",
"Disable unnecessary HTTP methods",
"Implement rate limiting"
])
# Version-specific recommendations
if service.get('version'):
recommendations.append(f"Update {service.get('product')} to the latest version")
# Vulnerability-specific recommendations
for vuln in service_analysis['high_risk']:
recommendations.append(f"Critical: Patch {vuln['id']} - {vuln['description'][:100]}...")
return recommendations
def analyze_vulnerabilities(scan_data: dict) -> str: