-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1800 lines (1516 loc) · 73.4 KB
/
app.py
File metadata and controls
1800 lines (1516 loc) · 73.4 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 os
import logging
import sqlalchemy as sa
# Update declarative_base import for SQLAlchemy 2.0 compatibility
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy import func, extract, case
from flask import Flask, render_template, request, jsonify, redirect, url_for, json, send_file
from modules.nvdapi import NVDApi, fetch_all_nvd_data, determine_severity
from datetime import datetime
import threading
import calendar
from werkzeug.routing.exceptions import BuildError
from functools import lru_cache
import hashlib
import requests
import re
# Note: The 'RequestsDependencyWarning' suggests installing 'chardet' or 'charset_normalizer'
# for optimal character encoding detection by the requests library (likely used in nvdapi.py).
# Example: pip install chardet
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
Base = declarative_base()
# Define route constants - update to include all routes
class Routes:
INDEX = 'index'
SEARCH = 'search'
VIEW_ALL = 'view_all'
CVE_DETAILS = 'cve_details'
VENDOR_ANALYSIS = 'vendor_analysis'
SEVERITY_DISTRIBUTION = 'severity_distribution'
MONTHLY_SUMMARY = 'monthly_summary'
TOP_VENDORS = 'top_vendors'
UPDATE_DATABASE = 'update_database'
UPDATE_STATUS = 'check_update_status'
# ... other routes ...
# Create Flask application
app = Flask(__name__)
app.config['SECRET_KEY'] = 'NVD_CVE_Secret_Key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cve_database.db'
# Am Anfang der Datei, nach der app-Initialisierung:
app.config['TEMPLATES_AUTO_RELOAD'] = True
@app.after_request
def add_header(response):
"""
Sorge dafür, dass die Antworten nicht gecached werden während der Entwicklung
"""
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '-1'
return response
# Define the static folder explicitly to ensure CSS files are served correctly
app.static_folder = 'static'
# Add the current year to all templates
@app.context_processor
def inject_now():
return {'now': datetime.now}
# Add CVSS color helper function
@app.context_processor
def utility_functions():
def get_cvss_color(score):
if score is None:
return '#6c757d' # Default gray for unknown
score = float(score)
if score >= 9.0:
return '#ea4335' # Critical (red)
elif score >= 7.0:
return '#ff6d41' # High (orange)
elif score >= 4.0:
return '#fbbc04' # Medium (yellow)
else:
return '#34a853' # Low (green)
def get_cvss_bar_color(score):
return get_cvss_color(score) # Same function, different name for clarity
return dict(
get_cvss_color=get_cvss_color,
get_cvss_bar_color=get_cvss_bar_color
)
# Database setup
def create_local_cve_db():
"""
Create a SQLite database connection for storing CVE data.
"""
try:
db_path = os.path.join(os.path.dirname(__file__), 'cve_database.db')
engine = sa.create_engine(f'sqlite:///{db_path}', echo=False)
logging.info(f"Created database at {db_path}")
return engine
except Exception as e:
logging.error(f"Error creating database: {e}")
return None
# Ensure sessions are properly closed
def get_session(engine):
"""
Create a new SQLAlchemy session.
"""
Session = sessionmaker(bind=engine)
return Session()
def create_cve_table(engine):
"""Create the CVE table in the database with optimized indexes."""
try:
class CVE(Base):
__tablename__ = 'cves'
# Add extend_existing=True to handle multiple definitions
__table_args__ = {
'extend_existing': True,
# Add composite indexes for common queries
'sqlite_autoincrement': True,
'mysql_engine': 'InnoDB',
'mysql_charset': 'utf8mb4'
}
id = sa.Column(sa.Integer, primary_key=True)
cve_id = sa.Column(sa.String(20), unique=True, index=True)
published_date = sa.Column(sa.DateTime, index=True) # Add index
last_modified_date = sa.Column(sa.DateTime)
description = sa.Column(sa.Text)
cvss_v3_score = sa.Column(sa.Float, nullable=True)
cvss_v2_score = sa.Column(sa.Float, nullable=True)
severity = sa.Column(sa.String(20), nullable=True, index=True) # Add index
cpe_affected = sa.Column(sa.Text)
cwe_id = sa.Column(sa.String(50), nullable=True, index=True) # Add index
references = sa.Column(sa.Text)
Base.metadata.create_all(engine)
logging.info("CVE table created successfully")
return CVE
except Exception as e:
logging.error(f"Error creating CVE table: {e}")
return None
def parse_nvd_datetime(date_string):
"""
Parse NVD datetime format strings into Python datetime objects.
Args:
date_string: String date from NVD API (e.g. '2025-04-17T11:15Z')
Returns:
datetime object or None if parsing fails
"""
if not date_string:
return None
# Try different formats because NVD data might have variations
formats_to_try = [
'%Y-%m-%dT%H:%M:%SZ', # Format with seconds
'%Y-%m-%dT%H:%MZ', # Format without seconds
'%Y-%m-%dT%H:%M:%S', # Format without Z
'%Y-%m-%dT%H:%M' # Format without Z or seconds
]
for date_format in formats_to_try:
try:
# Remove trailing Z if present and not in format
if date_string.endswith('Z') and not date_format.endswith('Z'):
clean_date = date_string[:-1]
else:
clean_date = date_string
return datetime.strptime(clean_date, date_format)
except ValueError:
continue
# If all parsing attempts fail, log and return None
logging.warning(f"Could not parse date string: {date_string}")
return None
def import_cve_data_to_db(cve_list, engine, CVE):
"""
Import CVE data into the database.
Args:
cve_list: List of CVE data dicts from NVD
engine: SQLAlchemy engine object
CVE: CVE class for table operations
"""
try:
Session = sessionmaker(bind=engine)
session = Session()
# Count of new CVEs added to the database
new_cve_count = 0
for cve_item in cve_list:
cve_id = cve_item.get('cve', {}).get('CVE_data_meta', {}).get('ID')
if not cve_id:
continue
# Check if CVE already exists in database
existing_cve = session.query(CVE).filter_by(cve_id=cve_id).first()
if existing_cve:
continue
# Extract basic CVE information
published_date = parse_nvd_datetime(cve_item.get('publishedDate'))
last_modified_date = parse_nvd_datetime(cve_item.get('lastModifiedDate'))
# Extract description (use English if available)
descriptions = cve_item.get('cve', {}).get('description', {}).get('description_data', [])
description = next((item.get('value') for item in descriptions if item.get('lang') == 'en'), '')
# Extract CVSS scores if available
impact = cve_item.get('impact', {})
cvss_v3 = impact.get('baseMetricV3', {}).get('cvssV3', {}).get('baseScore')
cvss_v2 = impact.get('baseMetricV2', {}).get('cvssV2', {}).get('baseScore')
# Determine severity based on CVSS scores
severity = None
if cvss_v3 is not None:
severity = determine_severity(cvss_v3)
elif cvss_v2 is not None:
severity = determine_severity(cvss_v2)
else:
severity = "UNKNOWN"
# Extract CPE affected configurations
cpe_affected = []
nodes = cve_item.get('configurations', {}).get('nodes', [])
for node in nodes:
for cpe_match in node.get('cpe_match', []):
cpe_affected.append(cpe_match.get('cpe23Uri', ''))
# Extract CWE IDs if available
problem_type_data = cve_item.get('cve', {}).get('problemtype', {}).get('problemtype_data', [])
cwe_ids = []
for pt in problem_type_data:
for desc in pt.get('description', []):
if desc.get('value', '').startswith('CWE-'):
cwe_ids.append(desc.get('value'))
cwe_id = ', '.join(cwe_ids)
# Extract references
reference_data = cve_item.get('cve', {}).get('references', {}).get('reference_data', [])
references = [ref.get('url') for ref in reference_data]
# Create new CVE record
new_cve = CVE(
cve_id=cve_id,
published_date=published_date,
last_modified_date=last_modified_date,
description=description,
cvss_v3_score=cvss_v3,
cvss_v2_score=cvss_v2,
severity=severity,
cpe_affected=','.join(cpe_affected),
cwe_id=cwe_id,
references=','.join(references)
)
session.add(new_cve)
new_cve_count += 1
# Commit in batches to prevent memory issues
if new_cve_count % 1000 == 0:
session.commit()
logging.info(f"Committed {new_cve_count} records so far")
session.commit()
logging.info(f"Imported {new_cve_count} new CVEs to the database")
return new_cve_count
except Exception as e:
session.rollback()
logging.error(f"Error importing CVE data to database: {e}")
return 0
# Add caching for expensive operations
@lru_cache(maxsize=32)
def get_severity_distribution(cache_key=None):
"""Cached function to get severity distribution statistics"""
engine = create_local_cve_db()
session = get_session(engine)
try:
severity_query = session.query(
CVE_Model.severity, func.count(CVE_Model.id).label('count')
).group_by(CVE_Model.severity).all()
severity_map = {"CRITICAL": 0, "HIGH": 0, "MEDIUM": 0, "LOW": 0, "UNKNOWN": 0}
for severity, count in severity_query:
s_upper = (severity or 'UNKNOWN').upper()
if s_upper in severity_map:
severity_map[s_upper] = count
return severity_map, sum(severity_map.values())
finally:
session.close()
# Global variable to track database update status
db_update_status = {
'is_updating': False,
'progress': 0,
'total_years': 0,
'current_year': None,
'error': None,
'cves_added': 0
}
def update_database_task():
"""Background task for updating the database"""
global db_update_status
global CVE_Model
try:
db_update_status['is_updating'] = True
db_update_status['error'] = None
db_update_status['progress'] = 0
# Fetch all CVE data
logging.info("Starting comprehensive CVE database update...")
all_cve_items = fetch_all_nvd_data()
if not all_cve_items:
db_update_status['error'] = "Failed to fetch CVE data"
db_update_status['is_updating'] = False
return
# Create/update database
engine = create_local_cve_db()
CVE_Model = create_cve_table(engine)
# Import data
cves_added = import_cve_data_to_db(all_cve_items, engine, CVE_Model)
db_update_status['cves_added'] = cves_added
db_update_status['progress'] = 100
logging.info(f"Database update completed. Added {cves_added} new CVEs.")
except Exception as e:
db_update_status['error'] = str(e)
logging.error(f"Error in database update task: {e}")
finally:
db_update_status['is_updating'] = False
# Create a global reference to our CVE class
CVE_Model = None
# Flask routes
@app.route('/')
@app.route('/index')
def index():
"""Home page showing overview and search form"""
# Get cached severity counts
severity_counts, total_cve_count = get_severity_distribution()
# Force logo update on home page by adding a timestamp to prevent caching issues
logo_timestamp = int(datetime.now().timestamp())
results = []
search_term = request.args.get('search_term', '')
search_performed = request.args.get('search_performed', 'false').lower() == 'true'
exploitable_only = request.args.get('exploitable', 'false').lower() == 'true'
severity_filter = request.args.get('severity', '')
page = request.args.get('page', 1, type=int)
per_page = 100
# Lade Exploit-DB Statistiken
exploitdb_stats = None
try:
# API-Endpunkt abfragen für die Exploit-Statistiken
response = requests.get(f"http://localhost:{request.host.split(':')[1] if ':' in request.host else '8080'}/api/exploitdb/status")
if response.status_code == 200:
exploitdb_stats = response.json()
except Exception as e:
logging.warning(f"Fehler beim Laden der Exploit-DB Statistiken: {e}")
try:
engine = create_local_cve_db()
session = get_session(engine)
if CVE_Model is None:
return render_template('index.html', error_message="Database model not initialized. Please update the database first.", results=[], search_term=search_term, search_performed=search_performed, severity_counts={}, total_cve_count=0, exploitdb_stats=exploitdb_stats)
if request.method == 'POST':
search_performed = True
search_term = request.form.get('search_term', '').strip()
exploitable_only = request.form.get('exploitable') == 'on'
severity_filter = request.form.get('severity', '')
return redirect(url_for(Routes.INDEX, search_term=search_term, exploitable=exploitable_only, severity=severity_filter, search_performed=True))
if search_performed or search_term:
query = session.query(CVE_Model)
is_cve_pattern = search_term.upper().startswith('CVE-') and len(search_term.split('-')) == 3
if is_cve_pattern:
query = query.filter(CVE_Model.cve_id.ilike(search_term))
else:
keywords = search_term.split()
for keyword in keywords:
query = query.filter(CVE_Model.description.ilike(f"%{keyword}%"))
if severity_filter in ["CRITICAL", "HIGH", "MEDIUM", "LOW", "UNKNOWN"]:
query = query.filter(CVE_Model.severity == severity_filter)
if exploitable_only:
query = query.filter(CVE_Model.references.ilike('%exploit%'))
total_results = query.count()
query = query.order_by(CVE_Model.published_date.desc())
paginated_results = query.limit(per_page).offset((page - 1) * per_page).all()
results = paginated_results
total_pages = (total_results + per_page - 1) // per_page
if not results and is_cve_pattern:
nvd_api = NVDApi()
cve_api_details = nvd_api.get_cve(search_term)
if cve_api_details:
return render_template('cve_details.html', cve=cve_api_details, from_api=True)
else:
# Initialize these variables when no search is performed
total_results = 0
total_pages = 1
except Exception as e:
logging.error(f"Error during search or getting counts: {e}")
return render_template('index.html', error_message=f"Operation failed: {e}", results=[], search_term=search_term, search_performed=search_performed, severity_counts={}, total_cve_count=0, exploitdb_stats=exploitdb_stats)
finally:
session.close()
return render_template('index.html', results=results, search_term=search_term, search_performed=search_performed, severity=severity_filter, severity_counts=severity_counts, total_cve_count=total_cve_count, current_page=page, total_pages=total_pages, total_results=total_results, exploitable=exploitable_only, exploitdb_stats=exploitdb_stats)
@app.route('/search', methods=['GET', 'POST'])
def search():
"""
Dedicated search endpoint that redirects to index with search parameters.
This route exists to handle search references in templates.
"""
if request.method == 'POST':
search_term = request.form.get('search_term', '')
severity = request.form.get('severity', '')
exploitable = 'true' if request.form.get('exploitable') == 'on' else 'false'
else:
search_term = request.args.get('search_term', '')
severity = request.args.get('severity', '')
exploitable = request.args.get('exploitable', 'false')
# Redirect to index with search parameters
return redirect(url_for(Routes.INDEX,
search_term=search_term,
severity=severity,
exploitable=exploitable,
search_performed='true'))
@app.route('/view_all')
def view_all(): # Geändert von view_all_entries zu view_all
"""Display all CVEs in the database, with sorting options"""
sort_by = request.args.get('sort', 'published_desc')
page = request.args.get('page', 1, type=int)
per_page = 100
try:
engine = create_local_cve_db()
session = get_session(engine)
if CVE_Model is None:
return render_template('error.html', error="Database model not initialized. Please update the database first.")
severity_query = session.query(
CVE_Model.severity, func.count(CVE_Model.id)
).group_by(CVE_Model.severity).all()
severity_map = {"CRITICAL": 0, "HIGH": 0, "MEDIUM": 0, "LOW": 0, "UNKNOWN": 0}
for severity, count in severity_query:
s_upper = (severity or 'UNKNOWN').upper()
severity_map[s_upper] = count
severity_counts = severity_map
total_cve_count = sum(severity_counts.values())
query = session.query(CVE_Model)
severity_order = sa.case(
(CVE_Model.severity == 'CRITICAL', 5),
(CVE_Model.severity == 'HIGH', 4),
(CVE_Model.severity == 'MEDIUM', 3),
(CVE_Model.severity == 'LOW', 2),
else_=1
)
if sort_by == 'severity_asc':
query = query.order_by(severity_order.asc(), CVE_Model.published_date.desc())
elif sort_by == 'severity_desc':
query = query.order_by(severity_order.desc(), CVE_Model.published_date.desc())
elif sort_by == 'published_asc':
query = query.order_by(CVE_Model.published_date.asc())
else:
query = query.order_by(CVE_Model.published_date.desc())
total_results = query.count()
paginated_results = query.limit(per_page).offset((page - 1) * per_page).all()
total_pages = (total_results + per_page - 1) // per_page
return render_template('index.html', results=paginated_results, search_term='All Database Entries', search_performed=True, sort_by=sort_by, is_view_all=True, severity_counts=severity_counts, total_cve_count=total_cve_count, current_page=page, total_pages=total_pages, total_results=total_results)
except Exception as e:
logging.error(f"Error fetching all entries: {e}")
return render_template('error.html', error=str(e))
finally:
session.close()
@app.route('/cve/<cve_id>')
def cve_details(cve_id):
"""Show details for a specific CVE"""
try:
cve_data = None
from_api = False
exploits = []
# Try database first
if CVE_Model is not None:
engine = create_local_cve_db()
session = get_session(engine)
cve_data = session.query(CVE_Model).filter(CVE_Model.cve_id.ilike(cve_id)).first()
session.close()
# If not in DB, try API
if not cve_data:
return redirect(url_for(Routes.CVE_DETAILS, cve_id=cve_id))
# Exploits für diese CVE abrufen
if cve_data:
try:
from modules.additional_sources import ExploitDBAdapter
exploits = ExploitDBAdapter.get_exploits_for_cve(cve_id)
# Setzen Sie Exploit-Flags
if exploits:
cve_data.has_exploit = True
cve_data.exploit_data = json.dumps(exploits)
except Exception as e:
logging.error(f"Error fetching exploits for {cve_id}: {e}")
# Exploit-Fehler sollten nicht die gesamte Seite scheitern lassen
pass
return render_template('cve_details.html', cve=cve_data, from_api=from_api, exploits=exploits)
else:
return redirect(url_for(Routes.CVE_DETAILS, cve_id=cve_id))
except Exception as e:
logging.error(f"Error fetching CVE details for {cve_id}: {e}")
return render_template('error.html', error=f"An error occurred while fetching details for {cve_id}.")
@app.route('/api/exploit-code/<exploit_id>')
def get_exploit_code(exploit_id):
"""API endpoint to get exploit code for a specific exploit ID"""
try:
from modules.additional_sources import ExploitDBAdapter
# Versuche, den Exploit-Code abzurufen
exploit_code = ExploitDBAdapter.get_exploit_code_content(exploit_id)
if exploit_code:
return exploit_code, 200, {'Content-Type': 'text/plain'}
else:
return f"Exploit code not found for ID: {exploit_id}", 404, {'Content-Type': 'text/plain'}
except Exception as e:
logging.error(f"Error fetching exploit code for ID {exploit_id}: {e}")
return f"Error fetching exploit code: {str(e)}", 500, {'Content-Type': 'text/plain'}
@app.route('/api/cve/<cve_id>/exploits')
def get_cve_exploits(cve_id):
"""API endpoint to get exploits for a specific CVE ID"""
try:
from modules.additional_sources import ExploitDBAdapter
# Hole alle Exploits für diese CVE
exploits = ExploitDBAdapter.get_exploits_for_cve(cve_id)
# Wenn als Parameter angegeben, füge auch den Code hinzu
include_code = request.args.get('include_code') == 'true'
if include_code:
for exploit in exploits:
exploit_id = exploit.get('exploit_id')
if exploit_id:
code = ExploitDBAdapter.get_exploit_code_content(exploit_id)
if code:
exploit['code_content'] = code
return jsonify({
'status': 'success',
'cve_id': cve_id,
'count': len(exploits),
'exploits': exploits
})
except Exception as e:
logging.error(f"Error fetching exploits for CVE {cve_id}: {e}")
return jsonify({
'status': 'error',
'message': str(e),
'cve_id': cve_id
}), 500
@app.route('/update_exploitdb')
def update_exploitdb():
"""Update the exploit database with the latest entries from Exploit-DB"""
try:
from modules.additional_sources import ExploitDBAdapter
# Initialisiere die Exploit-Datenbank, falls sie noch nicht existiert
ExploitDBAdapter.init_exploit_db()
# Importiere die Metadaten
metadata_count = ExploitDBAdapter.import_all_exploit_metadata()
# Starte den Download-Prozess im Hintergrund
download_thread = threading.Thread(
target=ExploitDBAdapter.download_all_exploits,
kwargs={'limit': 1000, 'filter_cve_only': True}
)
download_thread.daemon = True
download_thread.start()
return render_template('update_status.html',
status={
'is_updating': True,
'type': 'exploit_db',
'message': f'Imported {metadata_count} exploit metadata entries. Downloading exploit code in the background.',
'progress': 50
})
except Exception as e:
logging.error(f"Error updating exploit database: {e}")
return render_template('error.html',
error_message=f"Failed to update exploit database: {str(e)}")
@app.route('/api/exploitdb/status')
def get_exploitdb_status():
"""Get status information about the exploit database"""
try:
from modules.additional_sources import ExploitDBAdapter
# Get counts of locally available exploits
local_exploits = ExploitDBAdapter.get_locally_available_exploits()
# Verbinde mit der Datenbank und hole Statistiken
import sqlite3
import os
db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'exploit_cache.db')
stats = {
'total_exploits': 0,
'with_cve': 0,
'downloaded': 0,
'recent_exploits': []
}
if os.path.exists(db_path):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Gesamtzahl der Exploits
cursor.execute("SELECT COUNT(*) FROM exploit_metadata")
stats['total_exploits'] = cursor.fetchone()[0]
# Anzahl der Exploits mit CVE-ID
cursor.execute("SELECT COUNT(*) FROM exploit_metadata WHERE cve_id != ''")
stats['with_cve'] = cursor.fetchone()[0]
# Anzahl der heruntergeladenen Exploits
cursor.execute("SELECT COUNT(*) FROM exploit_metadata WHERE download_status = 1")
stats['downloaded'] = cursor.fetchone()[0]
# Neueste Exploits (10 Einträge)
cursor.execute("""
SELECT id, description, date, cve_id FROM exploit_metadata
WHERE cve_id != ''
ORDER BY date DESC LIMIT 10
""")
stats['recent_exploits'] = [
{
'id': row[0],
'description': row[1],
'date': row[2],
'cve_id': row[3]
} for row in cursor.fetchall()
]
conn.close()
return jsonify({
'status': 'success',
'local_exploit_count': len(local_exploits),
'stats': stats
})
except Exception as e:
logging.error(f"Error getting exploit database status: {e}")
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@app.route('/verify_exploits')
def verify_exploits():
"""Verify the integrity of all downloaded exploits and repair if needed"""
try:
from modules.additional_sources import ExploitDBAdapter
# Run verification with auto-repair
verification_results = ExploitDBAdapter.verify_all_exploits(repair=True)
return render_template('exploits_verification.html',
results=verification_results,
status={
'success': f"Verification complete: {verification_results['valid']} valid, {verification_results['invalid']} invalid, {verification_results['repaired']} repaired"
})
except Exception as e:
logging.error(f"Error verifying exploits: {e}")
return render_template('error.html',
error_message=f"Failed to verify exploits: {str(e)}")
@app.route('/manage_exploits', methods=['GET', 'POST'])
def manage_exploits():
"""Route to manage the Exploit-DB database - import metadata and download exploits"""
try:
from modules.additional_sources import ExploitDBAdapter
# Stelle sicher, dass die Exploit-Datenbank initialisiert ist
ExploitDBAdapter.init_exploit_db()
status = {"success": None, "error": None}
stats = {
"metadata_count": 0,
"cve_exploits_count": 0,
"downloaded_count": 0,
"file_count": 0,
"recent_exploits": []
}
# Statistik aus der Datenbank holen
try:
import sqlite3
import os
db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'exploit_cache.db')
if os.path.exists(db_path):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Gesamtzahl der Exploits in der Datenbank
cursor.execute("SELECT COUNT(*) FROM exploit_metadata")
stats["metadata_count"] = cursor.fetchone()[0]
# Anzahl der Exploits mit CVE-IDs
cursor.execute("SELECT COUNT(*) FROM exploit_metadata WHERE cve_id != ''")
stats["cve_exploits_count"] = cursor.fetchone()[0]
# Anzahl der heruntergeladenen Exploits
cursor.execute("SELECT COUNT(*) FROM exploit_metadata WHERE download_status = 1")
stats["downloaded_count"] = cursor.fetchone()[0]
# Anzahl der tatsächlichen Exploit-Dateien
cursor.execute("SELECT COUNT(*) FROM exploit_code")
stats["file_count"] = cursor.fetchone()[0]
# Neueste Exploits (10 Einträge)
cursor.execute("""
SELECT id, description, date, cve_id, download_status
FROM exploit_metadata
ORDER BY date DESC LIMIT 10
""")
stats["recent_exploits"] = []
for row in cursor.fetchall():
has_file = row[4] == 1
stats["recent_exploits"].append({
"id": row[0],
"description": row[1],
"date": row[2],
"cve": row[3],
"has_file": has_file
})
conn.close()
except Exception as e:
logging.error(f"Fehler beim Abrufen der Exploit-Statistiken: {e}")
status["error"] = f"Fehler beim Abrufen der Statistiken: {str(e)}"
# POST-Anfragen verarbeiten
if request.method == 'POST':
action = request.form.get('action')
if action == 'import_metadata':
# Metadaten importieren
try:
metadata_count = ExploitDBAdapter.import_all_exploit_metadata()
status["success"] = f"Erfolgreich {metadata_count} Exploit-Metadaten importiert."
except Exception as e:
logging.error(f"Fehler beim Importieren der Exploit-Metadaten: {e}")
status["error"] = f"Fehler beim Importieren der Metadaten: {str(e)}"
elif action == 'download_exploits':
# Exploits herunterladen (im Hintergrund)
try:
limit = request.form.get('limit')
limit = int(limit) if limit else None
cve_only = request.form.get('cve_only') == 'on'
# Starte Download im Hintergrund
download_thread = threading.Thread(
target=ExploitDBAdapter.download_all_exploits,
kwargs={'limit': limit, 'filter_cve_only': cve_only}
)
download_thread.daemon = True
download_thread.start()
if limit:
status["success"] = f"Download von {limit} Exploits wurde im Hintergrund gestartet."
else:
status["success"] = "Download aller Exploits wurde im Hintergrund gestartet."
except Exception as e:
logging.error(f"Fehler beim Starten des Exploit-Downloads: {e}")
status["error"] = f"Fehler beim Starten des Downloads: {str(e)}"
elif action == 'download_exploit':
# Einzelnen Exploit herunterladen
try:
exploit_id = request.form.get('exploit_id')
if not exploit_id:
status["error"] = "Keine Exploit-ID angegeben."
else:
result = ExploitDBAdapter.download_and_store_exploit(exploit_id)
if result:
status["success"] = f"Exploit {exploit_id} erfolgreich heruntergeladen."
else:
status["error"] = f"Fehler beim Herunterladen des Exploits {exploit_id}."
except Exception as e:
logging.error(f"Fehler beim Herunterladen des einzelnen Exploits: {e}")
status["error"] = f"Fehler beim Herunterladen: {str(e)}"
# Aktualisierte Statistiken nach der Aktion abrufen
try:
if os.path.exists(db_path):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Aktualisierte Statistiken abrufen
cursor.execute("SELECT COUNT(*) FROM exploit_metadata")
stats["metadata_count"] = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM exploit_metadata WHERE cve_id != ''")
stats["cve_exploits_count"] = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM exploit_metadata WHERE download_status = 1")
stats["downloaded_count"] = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM exploit_code")
stats["file_count"] = cursor.fetchone()[0]
conn.close()
except Exception as e:
logging.error(f"Fehler beim Aktualisieren der Exploit-Statistiken: {e}")
return render_template('exploits_manager.html', status=status, stats=stats)
except Exception as e:
logging.error(f"Unerwarteter Fehler in manage_exploits Route: {e}")
return render_template('error.html', error_message=f"Unerwarteter Fehler: {str(e)}")
@app.route('/exploits')
def list_exploits():
"""Liste aller vorhandenen Exploits mit Filtermöglichkeiten anzeigen"""
try:
from modules.additional_sources import ExploitDBAdapter
# Paginierung und Filter
page = request.args.get('page', 1, type=int)
per_page = 20
search_term = request.args.get('search', '')
cve_filter = request.args.get('cve', '')
has_code = request.args.get('has_code') == 'true'
# Stelle sicher, dass die Datenbank existiert
ExploitDBAdapter.init_exploit_db()
# Verbindung zur Datenbank herstellen
import sqlite3
import os
db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'exploit_cache.db')
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row # Für Zugriff auf Spalten über Namen
cursor = conn.cursor()
# Basis-Abfrage
query = """
SELECT id, description, date, author, platform, type, cve_id, download_status
FROM exploit_metadata
WHERE 1=1
"""
params = []
# Filter hinzufügen
if search_term:
query += " AND (description LIKE ? OR author LIKE ?)"
params.extend([f'%{search_term}%', f'%{search_term}%'])
if cve_filter:
query += " AND cve_id LIKE ?"
params.append(f'%{cve_filter}%')
if has_code:
query += " AND download_status = 1"
# Gesamtanzahl ermitteln
count_query = f"SELECT COUNT(*) FROM ({query})"
cursor.execute(count_query, params)
total_results = cursor.fetchone()[0]
# Sortierung und Paginierung hinzufügen
query += " ORDER BY date DESC LIMIT ? OFFSET ?"
offset = (page - 1) * per_page
params.extend([per_page, offset])
# Abfrage ausführen
cursor.execute(query, params)
exploits = cursor.fetchall()
# Gesamtstatistik
cursor.execute("SELECT COUNT(*) FROM exploit_metadata")
total_exploits = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM exploit_metadata WHERE cve_id != ''")
cve_exploits = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM exploit_metadata WHERE download_status = 1")
downloaded_exploits = cursor.fetchone()[0]
conn.close()
# Seitenanzahl berechnen
total_pages = (total_results + per_page - 1) // per_page if total_results > 0 else 1
return render_template('exploits_list.html',
exploits=exploits,
search_term=search_term,
cve_filter=cve_filter,
has_code=has_code,
page=page,
total_pages=total_pages,
total_results=total_results,
total_exploits=total_exploits,
cve_exploits=cve_exploits,
downloaded_exploits=downloaded_exploits)
except Exception as e:
logging.error(f"Fehler beim Auflisten der Exploits: {e}")
return render_template('error.html', error_message=f"Fehler beim Auflisten der Exploits: {str(e)}")
@app.route('/exploits/<exploit_id>')
def view_exploit(exploit_id):
"""Einzelnen Exploit anzeigen mit detaillierten Informationen und Code"""
try:
from modules.additional_sources import ExploitDBAdapter
# Exploit-Metadaten aus der Datenbank holen
import sqlite3
import os
db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'exploit_cache.db')
if not os.path.exists(db_path):
return render_template('error.html', error_message="Exploit-Datenbank nicht gefunden.")
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("""
SELECT id, description, date, author, platform, type, cve_id, file_path, download_status
FROM exploit_metadata
WHERE id = ?
""", (exploit_id,))
exploit = cursor.fetchone()
if not exploit:
conn.close()
return render_template('error.html', error_message=f"Exploit mit ID {exploit_id} wurde nicht gefunden.")
# Prüfen ob Exploit-Code vorhanden ist
exploit_code = None
has_code = exploit['download_status'] == 1
if has_code:
# Versuche den Code zu laden