-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcvehawk.py
More file actions
2827 lines (2510 loc) · 126 KB
/
cvehawk.py
File metadata and controls
2827 lines (2510 loc) · 126 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
"""
CVEHawk - Advanced CVE Lookup Tool v2.1
A multi-threaded command-line tool for CVE information gathering
Enhanced with better POC search and multi-platform support
"""
import argparse
import requests
import json
import sys
import time
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Dict, List, Optional, Tuple
import re
from urllib.parse import quote, urlencode
import os
from datetime import datetime
import tempfile
import csv
from pathlib import Path
import html
try:
import yaml
YAML_AVAILABLE = True
except ImportError:
YAML_AVAILABLE = False
print("Warning: PyYAML not installed. Configuration files not supported.")
class Colors:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
class RateLimiter:
"""Handle API rate limiting with automatic cooldown and resume"""
def __init__(self):
self.github_requests = 0
self.github_reset_time = None
self.github_limit = 60 # Default for unauthenticated
self.github_remaining = 60
self.nvd_last_request = time.time()
self.nvd_min_interval = 0.6 # Minimum seconds between NVD requests
def check_github_limit(self, headers):
"""Update GitHub rate limit info from response headers"""
if 'X-RateLimit-Limit' in headers:
self.github_limit = int(headers['X-RateLimit-Limit'])
if 'X-RateLimit-Remaining' in headers:
self.github_remaining = int(headers['X-RateLimit-Remaining'])
if 'X-RateLimit-Reset' in headers:
self.github_reset_time = int(headers['X-RateLimit-Reset'])
def wait_if_needed(self, api_type='github'):
"""Wait if rate limit is close or exceeded"""
if api_type == 'github':
if self.github_remaining <= 2 and self.github_reset_time:
wait_time = self.github_reset_time - time.time()
if wait_time > 0:
print(f"{Colors.YELLOW}[RATE LIMIT]{Colors.RESET} GitHub API limit reached. Cooling down for {wait_time:.0f} seconds...")
print(f"{Colors.BLUE}[INFO]{Colors.RESET} Will resume automatically after cooldown period.")
for i in range(int(wait_time)):
time.sleep(1)
remaining = int(wait_time - i - 1)
if remaining % 10 == 0 and remaining > 0:
print(f"{Colors.YELLOW}[COOLDOWN]{Colors.RESET} {remaining} seconds remaining...")
print(f"{Colors.GREEN}[RESUMED]{Colors.RESET} Continuing with API requests...")
self.github_remaining = self.github_limit # Reset after cooldown
return True
elif api_type == 'nvd':
elapsed = time.time() - self.nvd_last_request
if elapsed < self.nvd_min_interval:
time.sleep(self.nvd_min_interval - elapsed)
self.nvd_last_request = time.time()
return False
def print_banner():
"""Enhanced ASCII art banner with better visual appeal"""
banner = f"""{Colors.CYAN}
╔══════════════════════════════════════════════════════════════════╗
║ ██████╗██╗ ██╗███████╗██╗ ██╗ █████╗ ██╗ ██╗██╗ ██╗ ║
║ ██╔════╝██║ ██║██╔════╝██║ ██║██╔══██╗██║ ██║██║ ██╔╝ ║
║ ██║ ██║ ██║█████╗ ███████║███████║██║ █╗ ██║█████╔╝ ║
║ ██║ ╚██╗ ██╔╝██╔══╝ ██╔══██║██╔══██║██║███╗██║██╔═██╗ ║
║ ╚██████╗ ╚████╔╝ ███████╗██║ ██║██║ ██║╚███╔███╔╝██║ ██╗ ║
║ ╚═════╝ ╚═══╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚══╝╚══╝ ╚═╝ ╚═╝ ║
╚══════════════════════════════════════════════════════════════════╝
{Colors.RESET}
{Colors.BOLD}{Colors.WHITE} Advanced CVE Lookup Tool v2.1 Enhanced{Colors.RESET}
{Colors.MAGENTA} Created by @alsh4rfi{Colors.RESET}
{Colors.CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{Colors.RESET}
{Colors.GREEN} Enhanced Features: Multi-Platform POC Search | Smart Ranking | Export+{Colors.RESET}
"""
print(banner)
class CVELookup:
def __init__(self, config_file: Optional[str] = None):
self.session = requests.Session()
self.session.headers.update({
'User-Agent': 'CVEHawk/2.1 (Security Research Tool)',
'Accept': 'application/json'
})
self.lock = threading.Lock()
self.config = self.load_config(config_file)
self.rate_limiter = RateLimiter() # Add rate limiter
self.mitre_api = "https://services.nvd.nist.gov/rest/json/cves/2.0"
self.github_api = "https://api.github.com/search/repositories"
self.github_code_api = "https://api.github.com/search/code"
self.epss_api = "https://api.first.org/data/v1/epss"
self.exploit_db_search = "https://www.exploit-db.com/search"
self.packetstorm_search = "https://packetstormsecurity.com/search"
if self.config.get('api_keys', {}).get('github'):
self.session.headers['Authorization'] = f"token {self.config['api_keys']['github']}"
self.rate_limiter.github_limit = 5000 # Authenticated limit
self.rate_limiter.github_remaining = 5000
else:
self.rate_limiter.github_limit = 60
self.rate_limiter.github_remaining = 60
def display_rate_limit_status(self):
"""Display current rate limit status"""
print(f"\n{Colors.BOLD}API Rate Limit Status:{Colors.RESET}")
print(f" • GitHub: {Colors.CYAN}{self.rate_limiter.github_remaining}/{self.rate_limiter.github_limit}{Colors.RESET} requests remaining")
if self.rate_limiter.github_reset_time:
reset_in = self.rate_limiter.github_reset_time - time.time()
if reset_in > 0:
print(f" • Reset in: {Colors.YELLOW}{reset_in/60:.1f} minutes{Colors.RESET}")
if self.rate_limiter.github_remaining < 10:
print(f" {Colors.YELLOW}⚠ Warning: Running low on API requests. Consider adding a GitHub token.{Colors.RESET}")
def load_config(self, config_file: Optional[str]) -> Dict:
"""Load configuration from YAML file"""
default_config = {
'api_keys': {},
'output': {
'format': 'detailed',
'colors': True
},
'filters': {
'min_severity': 'none'
},
'export': {
'directory': './cvehawk_reports'
}
}
if config_file and os.path.exists(config_file) and YAML_AVAILABLE:
try:
with open(config_file, 'r') as f:
user_config = yaml.safe_load(f) or {}
default_config.update(user_config)
except Exception as e:
print(f"{Colors.YELLOW}[WARNING]{Colors.RESET} Error loading config: {e}")
return default_config
def get_severity_color(self, severity: str) -> str:
"""Get color based on CVSS severity"""
severity = severity.upper()
colors = {
'CRITICAL': Colors.RED + Colors.BOLD,
'HIGH': Colors.RED,
'MEDIUM': Colors.YELLOW,
'LOW': Colors.GREEN,
'NONE': Colors.BLUE,
'UNKNOWN': Colors.WHITE
}
return colors.get(severity, Colors.WHITE)
def normalize_cve_id(self, cve_id: str) -> str:
"""Normalize CVE ID by replacing various dash characters with standard hyphen"""
normalized = cve_id.replace('–', '-').replace('—', '-').replace('−', '-')
return normalized.upper().strip()
def validate_cve_format(self, cve_id: str) -> bool:
"""Validate CVE ID format"""
normalized = self.normalize_cve_id(cve_id)
pattern = r'^CVE-\d{4}-\d{4,7}$'
return bool(re.match(pattern, normalized))
def fetch_cve_details(self, cve_id: str) -> Optional[Dict]:
"""Fetch CVE details from NVD API"""
try:
self.rate_limiter.wait_if_needed('nvd')
normalized_cve = self.normalize_cve_id(cve_id)
if not self.validate_cve_format(normalized_cve):
raise ValueError(f"Invalid CVE format: {cve_id} (normalized: {normalized_cve})")
url = f"{self.mitre_api}?cveId={normalized_cve}"
with self.lock:
print(f"{Colors.BLUE}[INFO]{Colors.RESET} Fetching data for {normalized_cve}...")
response = self.session.get(url, timeout=30)
if response.status_code == 404:
with self.lock:
print(f"{Colors.YELLOW}[WARNING]{Colors.RESET} CVE {normalized_cve} not found in NVD database")
print(f"{Colors.YELLOW}[INFO]{Colors.RESET} This could be because:")
print(f" • The CVE is very recent and not yet published")
print(f" • The CVE is from a future year")
print(f" • The CVE ID doesn't exist")
return None
elif response.status_code == 403:
with self.lock:
print(f"{Colors.RED}[ERROR]{Colors.RESET} Access denied (403) - API rate limit or authentication issue")
return None
response.raise_for_status()
data = response.json()
if data.get('totalResults', 0) == 0:
with self.lock:
print(f"{Colors.YELLOW}[WARNING]{Colors.RESET} No results found for {normalized_cve}")
print(f"{Colors.YELLOW}[INFO]{Colors.RESET} Trying alternative search methods...")
return self.try_alternative_search(normalized_cve)
return data['vulnerabilities'][0]['cve']
except requests.exceptions.RequestException as e:
with self.lock:
print(f"{Colors.RED}[ERROR]{Colors.RESET} Network error for {normalized_cve}: {e}")
return None
except ValueError as e:
with self.lock:
print(f"{Colors.RED}[ERROR]{Colors.RESET} {e}")
return None
except Exception as e:
with self.lock:
print(f"{Colors.RED}[ERROR]{Colors.RESET} Unexpected error for {normalized_cve}: {e}")
return None
def try_alternative_search(self, cve_id: str) -> Optional[Dict]:
"""Try alternative search methods when primary lookup fails"""
try:
alt_url = f"https://services.nvd.nist.gov/rest/json/cve/1.0/{cve_id}"
with self.lock:
print(f"{Colors.BLUE}[INFO]{Colors.RESET} Trying alternative API for {cve_id}...")
response = self.session.get(alt_url, timeout=30)
if response.status_code == 200:
data = response.json()
if 'result' in data and 'CVE_Items' in data['result']:
cve_items = data['result']['CVE_Items']
if cve_items:
old_cve = cve_items[0]['cve']
return self.convert_old_format_to_new(old_cve)
with self.lock:
print(f"{Colors.YELLOW}[WARNING]{Colors.RESET} {cve_id} not found in any available database")
except Exception as e:
with self.lock:
print(f"{Colors.YELLOW}[WARNING]{Colors.RESET} Alternative search failed for {cve_id}: {e}")
return None
def convert_old_format_to_new(self, old_cve_data: Dict) -> Dict:
"""Convert old API format to new format for compatibility"""
try:
converted = {
'id': old_cve_data.get('CVE_data_meta', {}).get('ID', ''),
'descriptions': [],
'published': old_cve_data.get('publishedDate', ''),
'lastModified': old_cve_data.get('lastModifiedDate', ''),
'references': [],
'metrics': {}
}
if 'description' in old_cve_data:
for desc in old_cve_data['description']['description_data']:
converted['descriptions'].append({
'lang': desc.get('lang', 'en'),
'value': desc.get('value', '')
})
if 'references' in old_cve_data:
for ref in old_cve_data['references']['reference_data']:
converted['references'].append({
'url': ref.get('url', ''),
'tags': ref.get('tags', [])
})
return converted
except Exception as e:
print(f"{Colors.YELLOW}[WARNING]{Colors.RESET} Error converting old format: {e}")
return old_cve_data
def fetch_epss_score(self, cve_id: str) -> Optional[Dict]:
"""Fetch EPSS (Exploit Prediction Scoring System) data"""
try:
normalized_cve = self.normalize_cve_id(cve_id)
url = f"{self.epss_api}?cve={normalized_cve}"
response = self.session.get(url, timeout=15)
response.raise_for_status()
data = response.json()
if data.get('status') == 'OK' and data.get('data'):
epss_data = data['data'][0]
return {
'epss_score': float(epss_data.get('epss', 0)),
'epss_percentile': float(epss_data.get('percentile', 0)),
'date': epss_data.get('date', '')
}
except Exception as e:
with self.lock:
print(f"{Colors.YELLOW}[WARNING]{Colors.RESET} EPSS lookup failed for {cve_id}: {e}")
return None
def search_github_repositories(self, cve_id: str) -> List[Dict]:
"""Enhanced GitHub repository search with rate limiting"""
try:
normalized_cve = self.normalize_cve_id(cve_id)
cve_parts = normalized_cve.split('-')
cve_year = cve_parts[1] if len(cve_parts) > 1 else ""
cve_number = cve_parts[2] if len(cve_parts) > 2 else ""
search_queries = [
f'"{normalized_cve}" AND (exploit OR poc OR "proof of concept")',
f'"{normalized_cve}" vulnerability',
f'"CVE-{cve_year}-{cve_number}" exploit',
f'CVE {cve_year} {cve_number} exploit',
f'{normalized_cve} language:python exploit',
f'{normalized_cve} language:c exploit',
f'intitle:"{normalized_cve}" exploit',
]
all_results = []
seen_urls = set()
for i, query in enumerate(search_queries[:7]):
try:
self.rate_limiter.wait_if_needed('github')
sort_strategies = ["stars", "updated", "best-match", "forks"]
sort_param = sort_strategies[i % len(sort_strategies)]
url = f"{self.github_api}?q={quote(query)}&sort={sort_param}&order=desc&per_page=20"
response = self.session.get(url, timeout=25)
self.rate_limiter.check_github_limit(response.headers)
if response.status_code == 403:
rate_limit_reset = response.headers.get('X-RateLimit-Reset')
if rate_limit_reset:
wait_time = int(rate_limit_reset) - time.time()
if wait_time > 0:
with self.lock:
print(f"{Colors.YELLOW}[RATE LIMIT]{Colors.RESET} GitHub API limit hit. Auto-cooling down for {wait_time:.0f}s...")
for countdown in range(int(wait_time), 0, -1):
if countdown % 30 == 0:
print(f"{Colors.BLUE}[COOLDOWN]{Colors.RESET} {countdown} seconds remaining...")
time.sleep(1)
print(f"{Colors.GREEN}[RESUMED]{Colors.RESET} Retrying request...")
response = self.session.get(url, timeout=25)
if response.status_code == 403:
break # Still limited, stop trying
else:
with self.lock:
print(f"{Colors.YELLOW}[WARNING]{Colors.RESET} GitHub API rate limited. Consider adding API key.")
break
elif response.status_code == 422:
continue
if response.status_code != 200:
continue
data = response.json()
for item in data.get('items', [])[:15]:
repo_url = item.get('html_url', '')
if repo_url and repo_url not in seen_urls:
seen_urls.add(repo_url)
if self.is_likely_poc_enhanced(item, normalized_cve):
try:
created = item.get('created_at', '')
pushed = item.get('pushed_at', '')
if created and pushed:
from datetime import datetime
created_date = datetime.fromisoformat(created.replace('Z', '+00:00'))
pushed_date = datetime.fromisoformat(pushed.replace('Z', '+00:00'))
days_active = (pushed_date - created_date).days
item['estimated_commits'] = max(1, min(days_active * 7, 10000))
else:
item['estimated_commits'] = item.get('size', 0) // 10
except:
item['estimated_commits'] = 0
item['search_query'] = query
item['search_rank'] = i
item['relevance_score'] = self.calculate_relevance_score(item, normalized_cve)
all_results.append(item)
if self.rate_limiter.github_remaining > 30:
time.sleep(0.2) # Fast when we have quota
elif self.rate_limiter.github_remaining > 10:
time.sleep(0.5) # Slower when getting low
else:
time.sleep(1.0) # Very slow when almost out
except requests.exceptions.RequestException:
continue
all_results.sort(key=lambda x: (
x.get('stargazers_count', 0) * 1000 +
x.get('forks_count', 0) * 100 +
x.get('estimated_commits', 0) * 0.1
), reverse=True)
with self.lock:
if all_results:
print(f"{Colors.GREEN}[INFO]{Colors.RESET} Found {len(all_results)} POCs (GitHub API: {self.rate_limiter.github_remaining}/{self.rate_limiter.github_limit} requests remaining)")
return all_results[:15]
except Exception as e:
with self.lock:
print(f"{Colors.YELLOW}[WARNING]{Colors.RESET} GitHub repository search error: {e}")
return []
def search_github_code(self, cve_id: str) -> List[Dict]:
"""Search for code mentioning the CVE with rate limiting"""
try:
normalized_cve = self.normalize_cve_id(cve_id)
search_queries = [
f'"{normalized_cve}" exploit',
f'"{normalized_cve}" poc',
f'"{normalized_cve}" vulnerability'
]
all_results = []
seen_repos = set()
for query in search_queries[:2]:
try:
self.rate_limiter.wait_if_needed('github')
url = f"{self.github_code_api}?q={quote(query)}&sort=indexed&per_page=10"
response = self.session.get(url, timeout=15)
self.rate_limiter.check_github_limit(response.headers)
if response.status_code == 403:
rate_limit_reset = response.headers.get('X-RateLimit-Reset')
if rate_limit_reset:
wait_time = int(rate_limit_reset) - time.time()
if wait_time > 0 and wait_time < 300: # Wait up to 5 minutes
with self.lock:
print(f"{Colors.YELLOW}[RATE LIMIT]{Colors.RESET} Code search limit hit. Cooling down...")
time.sleep(wait_time + 1)
response = self.session.get(url, timeout=15)
if response.status_code == 403:
break
else:
break
elif response.status_code != 200:
continue
data = response.json()
for item in data.get('items', [])[:5]:
repo = item.get('repository', {})
repo_url = repo.get('html_url', '')
if repo_url and repo_url not in seen_repos:
seen_repos.add(repo_url)
repo_item = {
'html_url': repo_url,
'full_name': repo.get('full_name', ''),
'description': repo.get('description', ''),
'stargazers_count': repo.get('stargazers_count', 0),
'forks_count': repo.get('forks_count', 0),
'language': repo.get('language', ''),
'updated_at': repo.get('updated_at', ''),
'size': repo.get('size', 0),
'open_issues_count': repo.get('open_issues_count', 0),
'source': 'github_code_search',
'code_file': item.get('name', ''),
'code_path': item.get('path', ''),
'relevance_score': self.calculate_relevance_score(repo, normalized_cve)
}
all_results.append(repo_item)
if self.rate_limiter.github_remaining > 10:
time.sleep(0.3)
else:
time.sleep(1.0)
except requests.exceptions.RequestException:
continue
return all_results
except Exception as e:
with self.lock:
print(f"{Colors.YELLOW}[WARNING]{Colors.RESET} GitHub code search error: {e}")
return []
def is_likely_poc_enhanced(self, repo: Dict, cve_id: str) -> bool:
"""Enhanced POC detection with better filtering and regex matching"""
repo_name = repo.get('full_name', '').lower()
description = (repo.get('description') or '').lower()
cve_lower = cve_id.lower()
cve_parts = cve_lower.split('-')
cve_year = cve_parts[1] if len(cve_parts) > 1 else ""
cve_number = cve_parts[2] if len(cve_parts) > 2 else ""
cve_patterns = [
cve_lower, # Exact match
cve_lower.replace('-', '_'), # Underscore variant
cve_lower.replace('-', ' '), # Space variant
cve_lower.replace('-', ''), # No separator
f"cve{cve_year}{cve_number}", # Compact format
f"{cve_year}_{cve_number}", # Year_number format
]
cve_mentioned = any(pattern in repo_name or pattern in description
for pattern in cve_patterns)
strong_indicators = {
'exploit': 3,
'poc': 3,
'proof': 2,
'concept': 2,
'vulnerability': 2,
'cve': 2,
'security': 1,
'pentest': 2,
'hack': 1,
'attack': 1,
'payload': 2,
'rce': 2, # Remote code execution
'bypass': 2,
'0day': 3,
'zero-day': 3,
}
indicator_score = sum(weight for keyword, weight in strong_indicators.items()
if keyword in repo_name or keyword in description)
stars = repo.get('stargazers_count', 0)
size = repo.get('size', 0)
forks = repo.get('forks_count', 0)
if size < 5 and stars == 0 and forks == 0:
return False
exclude_keywords = [
'awesome', 'list', 'collection', 'tutorial', 'learning',
'book', 'course', 'guide', 'reference', 'documentation',
'template', 'boilerplate', 'framework', 'library',
'dashboard', 'monitoring', 'scanner', 'checker', 'notes',
'cheatsheet', 'resources', 'bookmark', 'archive'
]
exclude_score = sum(1 for keyword in exclude_keywords
if keyword in repo_name or keyword in description)
if cve_mentioned:
return exclude_score < 3 and (indicator_score >= 1 or stars >= 2)
elif indicator_score >= 4:
return exclude_score < 2
elif indicator_score >= 2:
return exclude_score < 2 and (stars >= 5 or forks >= 2)
else:
return False
def calculate_relevance_score(self, repo: Dict, cve_id: str) -> float:
"""Enhanced relevance score calculation with better GitHub metrics"""
score = 0.0
repo_name = (repo.get('full_name') or '').lower()
description = (repo.get('description') or '').lower()
if cve_id.lower() in repo_name:
score += 60 # Increased from 50
if cve_id.lower() in description:
score += 40 # Increased from 30
poc_keywords = {
'exploit': 30, # Increased
'poc': 30, # Increased
'proof of concept': 30,
'vulnerability': 20, # Increased
'cve': 20, # Increased
'security': 12, # Slightly increased
'pentest': 15, # New
'hack': 10, # New
'attack': 8 # New
}
for keyword, points in poc_keywords.items():
if keyword in repo_name:
score += points
if keyword in description:
score += points * 0.8 # Slightly higher multiplier
stars = repo.get('stargazers_count', 0)
forks = repo.get('forks_count', 0)
if stars > 0:
import math
if stars >= 1000:
score += 40
elif stars >= 500:
score += 35
elif stars >= 100:
score += 30
elif stars >= 50:
score += 25
elif stars >= 20:
score += 20
elif stars >= 10:
score += 15
elif stars >= 5:
score += 10
else:
score += min(8, math.log10(stars + 1) * 3)
if forks > 0:
if forks >= 100:
score += 25
elif forks >= 50:
score += 20
elif forks >= 20:
score += 15
elif forks >= 10:
score += 12
elif forks >= 5:
score += 8
else:
score += min(5, forks)
try:
updated_at = repo.get('updated_at', '')
if updated_at:
from datetime import datetime
import re
date_clean = re.sub(r'[TZ].*$', '', updated_at)
updated_date = datetime.fromisoformat(date_clean)
days_old = (datetime.now() - updated_date).days
if days_old <= 30:
score += 25
elif days_old <= 90:
score += 20
elif days_old <= 180:
score += 15
elif days_old <= 365:
score += 10
elif days_old <= 730:
score += 5
except Exception:
pass # Skip if date parsing fails
size = repo.get('size', 0)
if 50 <= size <= 50000: # Sweet spot for POC repos
score += 15
elif 10 <= size <= 100000:
score += 10
elif size > 0:
score += 5
language = (repo.get('language') or '').lower()
language_scores = {
'python': 15, # Most common for security tools
'c': 12, # Common for exploits
'c++': 12,
'go': 10, # Growing in security space
'rust': 10,
'java': 8,
'javascript': 8, # Web exploits
'shell': 12, # Exploit scripts
'powershell': 10, # Windows exploits
'bash': 8,
'php': 6,
'ruby': 6
}
score += language_scores.get(language, 0)
open_issues = repo.get('open_issues_count', 0)
if open_issues == 0:
score += 5 # Well-maintained
elif open_issues <= 5:
score += 3
elif open_issues > 20:
score -= 5 # Potentially abandoned
exploit_patterns = ['exploit', 'poc', 'cve', 'vuln', 'security', 'pentest']
pattern_matches = sum(1 for pattern in exploit_patterns if pattern in repo_name)
score += pattern_matches * 5
return score
def search_alternative_platforms(self, cve_id: str) -> List[Dict]:
"""Search alternative platforms for POCs and exploits"""
alternative_results = []
try:
platforms = [
self.search_exploit_db(cve_id),
self.search_packetstorm(cve_id),
self.search_rapid7_db(cve_id)
]
for platform_results in platforms:
if platform_results:
alternative_results.extend(platform_results)
except Exception as e:
with self.lock:
print(f"{Colors.YELLOW}[WARNING]{Colors.RESET} Alternative platform search error: {e}")
return alternative_results
def search_exploit_db(self, cve_id: str) -> List[Dict]:
"""Search Exploit-DB for exploits (web scraping approach)"""
try:
normalized_cve = self.normalize_cve_id(cve_id)
return [{
'platform': 'Exploit-DB',
'title': f'Search results for {normalized_cve}',
'url': f'https://www.exploit-db.com/search?cve={normalized_cve}',
'description': 'Manual verification required',
'type': 'search_link'
}]
except Exception:
return []
def search_packetstorm(self, cve_id: str) -> List[Dict]:
"""Search PacketStorm Security"""
try:
normalized_cve = self.normalize_cve_id(cve_id)
return [{
'platform': 'PacketStorm',
'title': f'Search results for {normalized_cve}',
'url': f'https://packetstormsecurity.com/search/?q={normalized_cve}',
'description': 'Manual verification required',
'type': 'search_link'
}]
except Exception:
return []
def search_rapid7_db(self, cve_id: str) -> List[Dict]:
"""Search Rapid7 Vulnerability Database"""
try:
normalized_cve = self.normalize_cve_id(cve_id)
return [{
'platform': 'Rapid7',
'title': f'Vulnerability details for {normalized_cve}',
'url': f'https://www.rapid7.com/db/?q={normalized_cve}',
'description': 'Comprehensive vulnerability details',
'type': 'search_link'
}]
except Exception:
return []
def search_poc_comprehensive(self, cve_id: str) -> List[Dict]:
"""Comprehensive POC search across multiple platforms"""
all_pocs = []
with self.lock:
print(f"{Colors.BLUE}[INFO]{Colors.RESET} Searching for POCs across multiple platforms...")
github_repos = self.search_github_repositories(cve_id)
if github_repos:
all_pocs.extend(github_repos)
github_code = self.search_github_code(cve_id)
if github_code:
all_pocs.extend(github_code)
alt_platforms = self.search_alternative_platforms(cve_id)
if alt_platforms:
all_pocs.extend(alt_platforms)
seen_urls = set()
unique_pocs = []
for poc in all_pocs:
url = poc.get('html_url') or poc.get('url', '')
if url and url not in seen_urls:
seen_urls.add(url)
unique_pocs.append(poc)
unique_pocs.sort(key=lambda x: x.get('relevance_score', 0), reverse=True)
return unique_pocs
def analyze_poc_quality(self, poc_results: List[Dict]) -> List[Dict]:
"""Analyze POC quality and add intelligence"""
analyzed_pocs = []
for poc in poc_results:
try:
if poc.get('type') == 'search_link':
poc['analysis'] = {
'quality_score': 50, # Neutral score for manual verification
'quality_level': 'MANUAL_CHECK',
'platform': poc.get('platform', 'Unknown'),
'requires_verification': True
}
analyzed_pocs.append(poc)
continue
stars = poc.get('stargazers_count', 0)
forks = poc.get('forks_count', 0)
issues = poc.get('open_issues_count', 0)
updated = poc.get('updated_at', '')
language = poc.get('language', 'Unknown')
size = poc.get('size', 0)
quality_score = 0
if stars >= 100: quality_score += 30
elif stars >= 50: quality_score += 25
elif stars >= 20: quality_score += 20
elif stars >= 10: quality_score += 15
elif stars >= 5: quality_score += 10
elif stars >= 1: quality_score += 5
if forks >= 50: quality_score += 20
elif forks >= 20: quality_score += 15
elif forks >= 10: quality_score += 10
elif forks >= 5: quality_score += 5
try:
if updated:
from datetime import datetime
updated_date = datetime.fromisoformat(updated.replace('Z', '+00:00'))
days_old = (datetime.now().astimezone() - updated_date).days
if days_old <= 30: quality_score += 20
elif days_old <= 90: quality_score += 15
elif days_old <= 365: quality_score += 10
elif days_old <= 730: quality_score += 5
except:
pass
reliable_languages = ['Python', 'C', 'C++', 'Java', 'Go', 'Rust']
if language in reliable_languages:
quality_score += 15
elif language in ['JavaScript', 'PHP', 'Ruby', 'Perl']:
quality_score += 10
elif language:
quality_score += 5
if 100 <= size <= 10000: quality_score += 10
elif 10 <= size <= 100000: quality_score += 5
if issues < 10: quality_score += 5
relevance_bonus = min(20, poc.get('relevance_score', 0) * 0.2)
quality_score += relevance_bonus
if quality_score >= 80: quality_level = "EXCELLENT"
elif quality_score >= 60: quality_level = "GOOD"
elif quality_score >= 40: quality_level = "FAIR"
elif quality_score >= 20: quality_level = "POOR"
else: quality_level = "VERY_POOR"
poc['analysis'] = {
'quality_score': quality_score,
'quality_level': quality_level,
'language': language,
'last_updated': updated,
'stars': stars,
'forks': forks,
'size_kb': round(size / 1024, 2) if size > 0 else 0,
'source': poc.get('source', 'github_repo_search')
}
analyzed_pocs.append(poc)
except Exception as e:
poc['analysis'] = {
'quality_score': 0,
'quality_level': 'UNKNOWN',
'error': str(e)
}
analyzed_pocs.append(poc)
return analyzed_pocs
def export_results(self, cve_data_list: List[Dict], format_type: str, filename: Optional[str] = None) -> str:
"""Enhanced export with reference URLs in CSV and better error handling"""
try:
export_dir = Path(self.config.get('export', {}).get('directory', './cvehawk_reports'))
export_dir.mkdir(exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
if not filename:
filename = f"cvehawk_report_{timestamp}"
if format_type.lower() == 'json':
filepath = export_dir / f"{filename}.json"
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(cve_data_list, f, indent=2, default=str, ensure_ascii=False)
elif format_type.lower() == 'html':
filepath = export_dir / f"{filename}.html"
html_content = self.generate_html_report(cve_data_list)
with open(filepath, 'w', encoding='utf-8') as f:
f.write(html_content)
elif format_type.lower() == 'csv':
filepath = export_dir / f"{filename}.csv"
with open(filepath, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
headers = [
'CVE_ID', 'Severity', 'CVSS_Score', 'EPSS_Score', 'EPSS_Percentile',
'Description', 'Published', 'Last_Modified', 'Reference_URLs',
'POC_Count', 'Top_POC_URL', 'Top_POC_Stars', 'Top_POC_Quality'
]
writer.writerow(headers)
for cve_data in cve_data_list:
try:
cve_info = cve_data.get('cve_info', {})
cve_id = cve_data.get('cve_id', 'Unknown')
severity = cve_data.get('severity', 'unknown')
cvss_score = cve_data.get('cvss_score', 'N/A')
epss_score = cve_data.get('epss_score', '')
epss_percentile = cve_data.get('epss_percentile', '')
descriptions = cve_info.get('descriptions', [])
description = ''
if descriptions and len(descriptions) > 0:
description = descriptions[0].get('value', '')[:300] # Limit length
published = cve_info.get('published', '')[:10] if cve_info.get('published') else ''
last_modified = cve_info.get('lastModified', '')[:10] if cve_info.get('lastModified') else ''
reference_urls = cve_data.get('reference_urls', [])
ref_urls_str = '; '.join(reference_urls[:5]) # Limit to 5 URLs
poc_results = cve_data.get('poc_results', [])
poc_count = len(poc_results)
top_poc_url = ''
top_poc_stars = ''
top_poc_quality = ''
if poc_results:
github_pocs = [p for p in poc_results if p.get('html_url') and 'github.com' in p.get('html_url', '')]
if github_pocs:
top_poc = github_pocs[0] # Already sorted by relevance
top_poc_url = top_poc.get('html_url', '')
top_poc_stars = str(top_poc.get('stargazers_count', 0))
analysis = top_poc.get('analysis', {})
top_poc_quality = f"{analysis.get('quality_level', 'UNKNOWN')} ({analysis.get('quality_score', 0):.0f}/100)"
row = [
cve_id, severity, cvss_score, epss_score, epss_percentile,
description, published, last_modified, ref_urls_str,
poc_count, top_poc_url, top_poc_stars, top_poc_quality
]
writer.writerow(row)
except Exception as row_error:
error_row = [
cve_data.get('cve_id', 'Unknown'), 'ERROR', '', '', '',
f'Export error: {str(row_error)}', '', '', '', '', '', '', ''
]
writer.writerow(error_row)
else:
raise ValueError(f"Unsupported export format: {format_type}")
return str(filepath)
except Exception as e:
print(f"{Colors.RED}[ERROR]{Colors.RESET} Export failed: {e}")
return ""
def generate_html_report(self, cve_data_list: List[Dict]) -> str:
"""Generate professional HTML report with modern design"""
def safe_html_text(text):
"""Safely encode text for HTML"""
if not text:
return ''
text = str(text).replace('🦅', '🦅').replace('🔥', '🔥').replace('⚠️', '⚠').replace('📊', '📊').replace('✅', '✅').replace('🎯', '🎯').replace('🔍', '🔍').replace('⭐', '⭐').replace('👑', '👑').replace('🥇', '🥇').replace('🥈', '🥈').replace('📌', '📌')
return html.escape(text)
total_cves = len(cve_data_list)
cves_with_pocs = sum(1 for cve in cve_data_list if cve.get('poc_results'))
total_pocs = sum(len(cve.get('poc_results', [])) for cve in cve_data_list)
critical_high = sum(1 for cve in cve_data_list if cve.get('severity', '').lower() in ['critical', 'high'])
html_content = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CVEHawk Security Report - Professional Edition</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<style>
* {{
margin: 0;
padding: 0;
box-sizing: border-box;
}}
:root {{
--primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
--danger-gradient: linear-gradient(135deg, #f93b1d 0%, #ea1e63 100%);
--success-gradient: linear-gradient(135deg, #00b09b 0%, #96c93d 100%);
--warning-gradient: linear-gradient(135deg, #f7971e 0%, #ffd200 100%);
--dark-bg: #0a0a0f;
--card-bg: #13131a;
--card-border: rgba(255, 255, 255, 0.08);
--text-primary: #ffffff;
--text-secondary: #a8a8b3;
--text-muted: #6b6b7b;
}}
body {{
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background: var(--dark-bg);
color: var(--text-primary);