-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1327 lines (1103 loc) · 47.1 KB
/
app.py
File metadata and controls
1327 lines (1103 loc) · 47.1 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
import requests
import sqlite3
import json
from datetime import datetime, timedelta, timezone
from flask import Flask, render_template, jsonify, request, send_from_directory
import threading
import time
from dataclasses import dataclass
from typing import List, Optional
import os
import re
from packaging import version
import difflib
from dotenv import load_dotenv
from concurrent.futures import ThreadPoolExecutor
import bcrypt
from flask_jwt_extended import create_access_token, get_jwt_identity, jwt_required, JWTManager
# Load environment variables from .env file
load_dotenv()
# Configuration
app = Flask(__name__, static_folder='static/dist')
app.config["JWT_SECRET_KEY"] = os.environ.get('JWT_SECRET_KEY', 'super-secret-key-for-dev')
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1)
jwt = JWTManager(app)
NVD_API_URL = "https://services.nvd.nist.gov/rest/json/cves/2.0"
# Environment variables are loaded from .env or the system environment
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
os.makedirs(DATA_DIR, exist_ok=True)
DB_NAME = os.path.join(DATA_DIR, 'cve_database.db')
UPDATE_INTERVAL = int(os.environ.get('UPDATE_INTERVAL', 3600)) # Default to 1 hour
# NVD API key should be set in your .env file for better request rates.
# It can be used without a key, but with very low rate limits.
NVD_API_KEY = os.environ.get('NVD_API_KEY')
@dataclass
class CVE:
id: str
description: str
published_date: str
last_modified: str
severity: str
cvss_score: Optional[float]
references: List[str]
class CVEMonitor:
def __init__(self):
self.init_db()
self.create_default_user()
self.create_indexes()
self.api_key = NVD_API_KEY
def init_db(self):
"""Initializes the SQLite database"""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS cves (
id TEXT PRIMARY KEY,
description TEXT,
published_date TEXT,
last_modified TEXT,
severity TEXT,
cvss_score REAL,
reference_urls TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Table to track fetching progress
cursor.execute('''
CREATE TABLE IF NOT EXISTS sync_status (
id INTEGER PRIMARY KEY,
last_full_sync TEXT,
last_update TEXT,
total_cves INTEGER,
status TEXT
)
''')
# Table for users
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
conn.commit()
conn.close()
def create_indexes(self):
"""Create indexes to optimize queries"""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
# Index for searching and sorting
cursor.execute('CREATE INDEX IF NOT EXISTS idx_published_date ON cves(published_date DESC)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_severity ON cves(severity)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_cvss_score ON cves(cvss_score DESC)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_cve_id ON cves(id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_search ON cves(id, description)')
conn.commit()
conn.close()
def create_default_user(self):
"""Creates a default admin user if no users exist."""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM users")
user_count = cursor.fetchone()[0]
if user_count == 0:
username = os.environ.get('ADMIN_USER', 'admin')
password = os.environ.get('ADMIN_PASSWORD', 'password')
if not username or not password or password == 'password':
print("WARNING: ADMIN_USER and ADMIN_PASSWORD environment variables are not set or are default. Cannot create default user.")
conn.close()
return
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
cursor.execute("INSERT INTO users (username, password_hash) VALUES (?, ?)", (username, hashed_password.decode('utf-8')))
conn.commit()
print(f"✅ Created default admin user: {username}")
conn.close()
def fetch_cves_with_api_key(self, params):
"""Performs a request with the API key"""
headers = {}
if self.api_key and self.api_key != 'YOUR_API_KEY_HERE':
headers['apiKey'] = self.api_key
try:
response = requests.get(NVD_API_URL, params=params, headers=headers, timeout=60)
if response.status_code == 403:
print("⚠️ Rate limit reached. Pausing for 30 seconds...")
time.sleep(30)
return None
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error during fetch: {e}")
return None
def fetch_all_cves_historical(self):
"""Fetches ALL historical CVEs progressively"""
print("="*60)
print("🚀 Starting complete CVE fetch")
print("="*60)
# Mettre à jour le statut
self.update_sync_status('running', 'Fetching in progress...')
current_year = datetime.now().year
total_processed = 0
# If we have an API key, we can make larger requests
if self.api_key and self.api_key != 'YOUR_API_KEY_HERE':
print("✅ API key detected - Optimized fetching")
results_per_page = 2000
sleep_time = 0.7 # With API key: up to 50 requests/30s
else:
print("⚠️ No API key - Slow fetching")
results_per_page = 1000
sleep_time = 6 # Without API key: 5 requests/30s
# Fetch year by year, month by month
for year in range(current_year, 1998, -1): # CVEs since 1999
print(f"\n📅 Processing year {year}...")
year_count = 0
for month in range(12, 0, -1):
# For the current year, do not go past the current month
if year == current_year and month > datetime.now().month:
continue
start_date = datetime(year, month, 1)
# Calculate the last day of the month
if month == 12:
end_date = datetime(year, 12, 31, 23, 59, 59)
else:
end_date = datetime(year, month + 1, 1) - timedelta(seconds=1)
# Handle pagination
start_index = 0
month_total = 0
while True:
params = {
'pubStartDate': start_date.strftime('%Y-%m-%dT00:00:00.000'),
'pubEndDate': end_date.strftime('%Y-%m-%dT23:59:59.999'),
'startIndex': start_index,
'resultsPerPage': results_per_page
}
data = self.fetch_cves_with_api_key(params)
if not data:
print(f" ❌ Error for {year}/{month:02d}")
break
vulnerabilities = data.get('vulnerabilities', [])
total_results = data.get('totalResults', 0)
# Save CVEs
for vuln in vulnerabilities:
try:
cve = self.parse_cve_data(vuln)
self.save_cve(cve)
month_total += 1
except Exception as e:
print(f" Error parsing CVE: {e}")
print(f" 📊 {year}/{month:02d}: {month_total}/{total_results} CVEs saved", end='\r')
# Check if there are more results
start_index += results_per_page
if start_index >= total_results:
print(f" ✅ {year}/{month:02d}: {month_total} CVEs saved in total")
break
# Pause between requests
time.sleep(sleep_time)
year_count += month_total
total_processed += month_total
# Update status periodically
if month % 3 == 0:
self.update_sync_status('running', f'Year {year} - {total_processed} CVEs processed')
print(f"📊 Year {year} finished: {year_count} CVEs fetched")
# Final status update
self.update_sync_status('completed', f'Fetch complete - {total_processed} CVEs')
print(f"\n{'='*60}")
print(f"\n{'='*60}\n✅ Full fetch complete!\n📊 Total: {total_processed} CVEs fetched\n{'='*60}\n")
print(f"{'='*60}\n")
return total_processed
def fetch_recent_cves(self, hours_back=2):
"""Fetches CVEs from the last X hours (for updates)"""
end_date = datetime.now()
start_date = end_date - timedelta(hours=hours_back)
params = {
'lastModStartDate': start_date.strftime('%Y-%m-%dT%H:%M:%S.000'),
'lastModEndDate': end_date.strftime('%Y-%m-%dT%H:%M:%S.999'),
'resultsPerPage': 2000
}
return self.fetch_cves_with_api_key(params)
def update_recent_cves(self):
"""Updates with recent CVEs (called hourly)"""
print(f"\n🔄 Hourly update - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
# Fetch CVEs modified in the last 2 hours
data = self.fetch_recent_cves(hours_back=2)
if data and 'vulnerabilities' in data:
count = 0
for item in data['vulnerabilities']:
try:
cve = self.parse_cve_data(item)
self.save_cve(cve)
count += 1
except Exception as e:
print(f"Error processing CVE: {e}")
print(f"✅ {count} CVEs updated")
self.update_sync_status('active', f'Last update: {datetime.now().isoformat()}')
else:
print("ℹ️ No updates available")
def parse_cve_data(self, cve_item):
"""Parses CVE data from the API response"""
cve_id = cve_item['cve']['id']
# Description
descriptions = cve_item['cve'].get('descriptions', [])
description = descriptions[0]['value'] if descriptions else 'No description'
# Dates
published = cve_item['cve']['published']
modified = cve_item['cve']['lastModified']
# CVSS Score and severity
cvss_score = None
severity = 'UNKNOWN'
metrics = cve_item['cve'].get('metrics', {})
if 'cvssMetricV31' in metrics and metrics['cvssMetricV31']:
cvss_data = metrics['cvssMetricV31'][0]['cvssData']
cvss_score = cvss_data['baseScore']
severity = cvss_data['baseSeverity']
elif 'cvssMetricV2' in metrics and metrics['cvssMetricV2']:
cvss_data = metrics['cvssMetricV2'][0]['cvssData']
cvss_score = cvss_data['baseScore']
severity = self.score_to_severity(cvss_score)
# References
references = []
for ref in cve_item['cve'].get('references', []):
references.append(ref['url'])
return CVE(
id=cve_id,
description=description,
published_date=published,
last_modified=modified,
severity=severity,
cvss_score=cvss_score,
references=references
)
def score_to_severity(self, score):
"""Converts a CVSS score to a severity level"""
if score >= 9.0:
return 'CRITICAL'
elif score >= 7.0:
return 'HIGH'
elif score >= 4.0:
return 'MEDIUM'
elif score >= 0.1:
return 'LOW'
return 'NONE'
def save_cve(self, cve: CVE):
"""Saves a CVE to the database"""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO cves
(id, description, published_date, last_modified, severity, cvss_score, reference_urls)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (
cve.id,
cve.description,
cve.published_date,
cve.last_modified,
cve.severity,
cve.cvss_score,
json.dumps(cve.references)
))
conn.commit()
conn.close()
def update_sync_status(self, status, message):
"""Updates the synchronization status"""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM cves')
total_cves = cursor.fetchone()[0]
cursor.execute('''
INSERT OR REPLACE INTO sync_status (id, last_full_sync, last_update, total_cves, status)
VALUES (1, ?, ?, ?, ?)
''', (
datetime.now().isoformat() if status == 'completed' else None,
datetime.now().isoformat(),
total_cves,
message
))
conn.commit()
conn.close()
def get_sync_status(self):
"""Gets the synchronization status"""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute('SELECT * FROM sync_status WHERE id = 1')
row = cursor.fetchone()
if row:
return {
'last_full_sync': row[1],
'last_update': row[2],
'total_cves': row[3],
'status': row[4]
}
return None
def get_recent_cves(self, limit=50, offset=0, search_term=None, sort_by='published_date', sort_order='DESC'):
"""Gets CVEs with pagination and sorting"""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
# Allowed columns for sorting (security)
allowed_sort_columns = {
'id': 'id',
'description': 'description',
'severity': 'severity',
'cvss_score': 'cvss_score',
'published_date': 'published_date'
}
# Validate sort column
if sort_by not in allowed_sort_columns:
sort_by = 'published_date'
# Validate sort order
if sort_order.upper() not in ['ASC', 'DESC']:
sort_order = 'DESC'
# Build query with search
base_query = "FROM cves"
where_clause = ""
params = []
if search_term:
where_clause = " WHERE id LIKE ? OR description LIKE ? OR severity LIKE ?"
params = [f'%{search_term}%', f'%{search_term}%', f'%{search_term}%']
# Count total for pagination
count_query = f"SELECT COUNT(*) {base_query}{where_clause}"
cursor.execute(count_query, params)
total_count = cursor.fetchone()[0]
# Main query with sorting and pagination
if sort_by == 'severity':
order_clause = f"""
ORDER BY
CASE severity
WHEN 'CRITICAL' THEN 1
WHEN 'HIGH' THEN 2
WHEN 'MEDIUM' THEN 3
WHEN 'LOW' THEN 4
ELSE 5
END {sort_order},
published_date DESC
"""
else:
order_clause = f" ORDER BY {allowed_sort_columns[sort_by]} {sort_order}"
select_query = f"""
SELECT * {base_query}{where_clause}
{order_clause}
LIMIT ? OFFSET ?
"""
params.extend([limit, offset])
cursor.execute(select_query, params)
cves = []
for row in cursor.fetchall():
cves.append({
'id': row[0],
'description': row[1],
'published_date': row[2],
'last_modified': row[3],
'severity': row[4],
'cvss_score': row[5],
'references': json.loads(row[6]) if row[6] else []
})
conn.close()
return {
'cves': cves,
'total': total_count,
'page': offset // limit + 1,
'pages': (total_count + limit - 1) // limit,
'limit': limit
}
def get_cve_details(self, cve_id):
"""Fetches full details for a single CVE, including PoCs and Nuclei status."""
print(f"DEBUG: get_cve_details called with cve_id: '{cve_id}'")
conn = sqlite3.connect(DB_NAME)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("SELECT * FROM cves WHERE id = ?", (cve_id,))
cve_row = cursor.fetchone()
if not cve_row:
print(f"DEBUG: CVE with id '{cve_id}' not found in database.")
conn.close()
return None
print(f"DEBUG: Found CVE '{cve_id}' in database.")
cve_data = dict(cve_row)
cve_data['references'] = json.loads(cve_data.get('reference_urls', '[]'))
# Asynchronously fetch PoCs and Nuclei status
with ThreadPoolExecutor(max_workers=2) as executor:
future_pocs = executor.submit(self.search_github_poc, cve_id)
future_nuclei = executor.submit(self.has_nuclei_template_online, cve_id)
pocs_result = future_pocs.result()
nuclei_result = future_nuclei.result()
cve_data['pocs'] = pocs_result.get('items', [])
cve_data['nuclei_template'] = nuclei_result
# Ensure cvss_vector is present, even if null
if 'cvss_vector' not in cve_data:
cve_data['cvss_vector'] = None
conn.close()
return cve_data
def search_specific_cve(self, cve_id):
"""Searches for a specific CVE in the NVD API"""
params = {'cveId': cve_id}
data = self.fetch_cves_with_api_key(params)
if data and 'vulnerabilities' in data and len(data['vulnerabilities']) > 0:
cve = self.parse_cve_data(data['vulnerabilities'][0])
self.save_cve(cve)
return cve
return None
def search_github_poc(self, cve_id):
"""Searches for PoCs on GitHub via the API"""
try:
headers = {
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'CVE-Monitor'
}
# Optional GitHub token to increase rate limit
github_token = os.environ.get('GITHUB_TOKEN', '')
if github_token:
headers['Authorization'] = f'token {github_token}'
# Search for the CVE in repos
search_query = f"{cve_id} in:name,description,readme"
url = f"https://api.github.com/search/repositories?q={search_query}&sort=stars&order=desc&per_page=10"
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 200:
data = response.json()
repos = []
for repo in data.get('items', []):
repos.append({
'name': repo['full_name'],
'url': repo['html_url'],
'description': repo.get('description', ''),
'stars': repo['stargazers_count'],
'language': repo.get('language', 'Unknown'),
'updated': repo['updated_at']
})
# Also search in code
code_url = f"https://api.github.com/search/code?q={cve_id}+extension:py+extension:sh+extension:c+extension:cpp&per_page=5"
code_response = requests.get(code_url, headers=headers, timeout=10)
code_results = []
if code_response.status_code == 200:
code_data = code_response.json()
for item in code_data.get('items', []):
code_results.append({
'filename': item['name'],
'path': item['path'],
'repo': item['repository']['full_name'],
'url': item['html_url']
})
return {
'repos': repos,
'code': code_results,
'total_repos': data.get('total_count', 0)
}
else:
return {'repos': [], 'code': [], 'error': f'GitHub API: {response.status_code}'}
except Exception as e:
print(f"Erreur recherche GitHub: {e}")
return {'repos': [], 'code': [], 'error': str(e)}
def has_nuclei_template_online(self, cve_id: str) -> bool:
"""Vérifie si un template Nuclei existe pour un CVE sur GitHub"""
url = f"https://api.github.com/search/code?q={cve_id}+repo:projectdiscovery/nuclei-templates"
headers = {
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'CVE-Monitor'
}
token = os.environ.get('GITHUB_TOKEN')
if token:
headers['Authorization'] = f'token {token}'
try:
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 200:
data = response.json()
return data.get('total_count', 0) > 0
else:
print(f"[GitHub] Erreur {response.status_code} pour {cve_id}")
except Exception as e:
print(f"[GitHub] Exception lors de la recherche Nuclei : {e}")
return False
def get_statistics(self):
"""Calcule les statistiques sur les CVE"""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
# Total des CVE
cursor.execute('SELECT COUNT(*) FROM cves')
total = cursor.fetchone()[0]
# CVE par sévérité
cursor.execute('''
SELECT severity, COUNT(*)
FROM cves
GROUP BY severity
''')
severity_stats = dict(cursor.fetchall())
# CVE des 30 derniers jours
thirty_days_ago = (datetime.now() - timedelta(days=30)).isoformat()
cursor.execute('''
SELECT COUNT(*)
FROM cves
WHERE published_date >= ?
''', (thirty_days_ago,))
recent_30 = cursor.fetchone()[0]
# CVE des 7 derniers jours
seven_days_ago = (datetime.now() - timedelta(days=7)).isoformat()
cursor.execute('''
SELECT COUNT(*)
FROM cves
WHERE published_date >= ?
''', (seven_days_ago,))
recent_7 = cursor.fetchone()[0]
conn.close()
return {
'total': total,
'severity': severity_stats,
'recent_30days': recent_30,
'recent_7days': recent_7,
'critical': severity_stats.get('CRITICAL', 0),
'high': severity_stats.get('HIGH', 0)
}
# === MÉTHODES POUR LA RECHERCHE INVERSÉE ===
def search_by_product_version(self, product_name, product_version=None):
"""Recherche inversée : trouve tous les CVE pour un produit/version spécifique"""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
# Normaliser le nom du produit
normalized_product = self._normalize_product_name(product_name)
# Recherche de base par nom de produit
query = """
SELECT * FROM cves
WHERE LOWER(description) LIKE ?
ORDER BY published_date DESC
"""
cursor.execute(query, (f'%{normalized_product}%',))
all_results = cursor.fetchall()
# Convertir en dictionnaires
cves = []
for row in all_results:
cve_dict = {
'id': row[0],
'description': row[1],
'published_date': row[2],
'last_modified': row[3],
'severity': row[4],
'cvss_score': row[5],
'references': json.loads(row[6]) if row[6] else [],
'affected_versions': []
}
# Extraire les versions affectées de la description
if product_version:
versions = self._extract_versions_from_description(cve_dict['description'], normalized_product)
cve_dict['affected_versions'] = versions
# Vérifier si la version spécifiée est affectée
if self._is_version_affected(product_version, versions, cve_dict['description']):
cve_dict['version_match'] = True
cves.append(cve_dict)
else:
# Si pas de version spécifiée, retourner tous les CVE du produit
versions = self._extract_versions_from_description(cve_dict['description'], normalized_product)
cve_dict['affected_versions'] = versions
cves.append(cve_dict)
conn.close()
# Analyser et enrichir les résultats
return self._enrich_search_results(cves, product_name, product_version)
def _normalize_product_name(self, product_name):
"""Normalise le nom du produit pour la recherche"""
# Dictionnaire de correspondances communes
aliases = {
'httpd': 'apache',
'apache httpd': 'apache',
'apache http server': 'apache',
'nginx server': 'nginx',
'mariadb': 'mysql',
'postgresql': 'postgres',
'ms windows': 'windows',
'microsoft windows': 'windows',
'rhel': 'red hat',
'centos': 'red hat',
'ubuntu linux': 'ubuntu',
'k8s': 'kubernetes'
}
normalized = product_name.lower().strip()
# Vérifier les alias
for alias, canonical in aliases.items():
if alias in normalized:
normalized = normalized.replace(alias, canonical)
return normalized
def _extract_versions_from_description(self, description, product_name):
"""Extrait les versions mentionnées dans la description"""
versions = []
desc_lower = description.lower()
# Patterns pour détecter les versions
version_patterns = [
# Pattern "product version X.Y.Z"
rf'{product_name}\s+(?:version\s+)?(\d+(?:\.\d+)*(?:\.\w+)?)',
# Pattern "product < X.Y.Z" ou "> X.Y.Z"
rf'{product_name}\s*[<>]=?\s*(\d+(?:\.\d+)*)',
# Pattern "versions X.Y through X.Y"
rf'versions?\s+(\d+(?:\.\d+)*)\s+through\s+(\d+(?:\.\d+)*)',
# Pattern "before version X.Y.Z"
rf'before\s+(?:version\s+)?(\d+(?:\.\d+)*)',
# Pattern "prior to X.Y.Z"
rf'prior\s+to\s+(\d+(?:\.\d+)*)',
# Pattern générique pour version avec préfixe 'v'
rf'{product_name}.*?v(\d+(?:\.\d+)*)'
]
for pattern in version_patterns:
matches = re.finditer(pattern, desc_lower)
for match in matches:
if match.groups():
for group in match.groups():
if group:
versions.append(group)
# Recherche de plages de versions
range_match = re.search(r'(\d+(?:\.\d+)*)\s*(?:to|-|through)\s*(\d+(?:\.\d+)*)', desc_lower)
if range_match:
versions.append(f"{range_match.group(1)}-{range_match.group(2)}")
return list(set(versions)) # Supprimer les doublons
def _is_version_affected(self, user_version, affected_versions, description):
"""Vérifie si la version de l'utilisateur est affectée"""
desc_lower = description.lower()
# Gestion des cas spéciaux
if 'all versions' in desc_lower:
return True
try:
user_ver = version.parse(user_version)
except:
# Si la version n'est pas parsable, faire une comparaison de chaînes
return any(user_version in v for v in affected_versions)
for affected in affected_versions:
# Gestion des plages de versions
if '-' in affected:
start, end = affected.split('-')
try:
if version.parse(start) <= user_ver <= version.parse(end):
return True
except:
pass
# Vérifier les mentions "before", "prior to", etc.
if re.search(rf'before\s+(?:version\s+)?{re.escape(affected)}', desc_lower):
try:
if user_ver < version.parse(affected):
return True
except:
pass
# Vérifier les mentions "through"
if re.search(rf'through\s+{re.escape(affected)}', desc_lower):
try:
if user_ver <= version.parse(affected):
return True
except:
pass
# Comparaison exacte
try:
if user_ver == version.parse(affected):
return True
except:
if user_version == affected:
return True
return False
def _enrich_search_results(self, cves, product_name, product_version):
"""Enrichit les résultats avec des métadonnées supplémentaires"""
results = {
'product': product_name,
'version': product_version,
'total_cves': len(cves),
'cves': cves,
'statistics': {
'critical': sum(1 for c in cves if c['severity'] == 'CRITICAL'),
'high': sum(1 for c in cves if c['severity'] == 'HIGH'),
'medium': sum(1 for c in cves if c['severity'] == 'MEDIUM'),
'low': sum(1 for c in cves if c['severity'] == 'LOW')
}
}
# Si une version est spécifiée, ajouter des recommandations
if product_version:
results['recommendations'] = self._generate_recommendations(cves, product_name, product_version)
return results
def _generate_recommendations(self, cves, product_name, product_version):
"""Génère des recommandations basées sur les CVE trouvés"""
recommendations = []
if not cves:
recommendations.append({
'type': 'info',
'message': f"Aucune vulnérabilité connue pour {product_name} {product_version}"
})
return recommendations
# Analyser la sévérité
critical_count = sum(1 for c in cves if c['severity'] == 'CRITICAL')
high_count = sum(1 for c in cves if c['severity'] == 'HIGH')
if critical_count > 0:
recommendations.append({
'type': 'critical',
'message': f"{critical_count} vulnérabilité(s) CRITIQUE(S) détectée(s) ! Mise à jour urgente recommandée."
})
if high_count > 0:
recommendations.append({
'type': 'warning',
'message': f"{high_count} vulnérabilité(s) de sévérité HAUTE. Planifier une mise à jour rapidement."
})
# Vérifier l'âge des CVE
recent_cves = [c for c in cves if self._is_recent_cve(c['published_date'], days=30)]
if recent_cves:
recommendations.append({
'type': 'info',
'message': f"{len(recent_cves)} vulnérabilité(s) découverte(s) dans les 30 derniers jours."
})
# Suggérer la dernière version sûre connue
safe_version = self._find_safe_version(cves, product_name, product_version)
if safe_version:
recommendations.append({
'type': 'success',
'message': f"Version recommandée : {safe_version} ou supérieure"
})
return recommendations
def _is_recent_cve(self, published_date, days=30):
"""Vérifie si un CVE est récent"""
try:
pub_date = datetime.fromisoformat(published_date.replace('Z', '+00:00'))
return (datetime.now(timezone.utc) - pub_date).days <= days
except:
return False
def _find_safe_version(self, cves, product_name, current_version):
"""Essaie de déterminer une version sûre basée sur les CVE"""
# Cette fonction pourrait être améliorée avec une base de données
# de versions ou une API externe
all_affected_versions = []
for cve in cves:
all_affected_versions.extend(cve.get('affected_versions', []))
# Logique simplifiée : suggérer la dernière version majeure + 1
try:
curr_ver = version.parse(current_version)
if hasattr(curr_ver, 'major'):
return f"{curr_ver.major + 1}.0.0"
except:
pass
return None
monitor = CVEMonitor()
# =================================================================
# API Routes
# =================================================================
# Auth routes
@app.route('/api/register', methods=['POST'])
def register():
"""Registers a new user."""
username = request.json.get('username', None)
password = request.json.get('password', None)
if not username or not password:
return jsonify({"msg": "Missing username or password"}), 400
if len(password) < 8:
return jsonify({"msg": "Password must be at least 8 characters"}), 400
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute("SELECT id FROM users WHERE username = ?", (username,))
if cursor.fetchone():
conn.close()
return jsonify({"msg": "Username already exists"}), 409
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
cursor.execute("INSERT INTO users (username, password_hash) VALUES (?, ?)",
(username, hashed_password.decode('utf-8')))
conn.commit()
conn.close()
return jsonify({"msg": "User created successfully"}), 201
@app.route('/api/login', methods=['POST'])
def login():
"""Authenticates a user and returns a JWT."""
username = request.json.get('username', None)
password = request.json.get('password', None)
if not username or not password:
return jsonify({"msg": "Missing username or password"}), 400
conn = sqlite3.connect(DB_NAME)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("SELECT password_hash FROM users WHERE username = ?", (username,))
user_row = cursor.fetchone()
conn.close()
if user_row and bcrypt.checkpw(password.encode('utf-8'), user_row['password_hash'].encode('utf-8')):
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token)
return jsonify({"msg": "Bad username or password"}), 401
@app.route("/api/profile")
@jwt_required()
def profile():
"""Returns the current user's identity and details."""
current_user_username = get_jwt_identity()
conn = sqlite3.connect(DB_NAME)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("SELECT id, username, created_at FROM users WHERE username = ?", (current_user_username,))
user_row = cursor.fetchone()
conn.close()
if not user_row:
return jsonify({"msg": "User not found"}), 404
return jsonify({