-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
466 lines (363 loc) · 14.5 KB
/
app.py
File metadata and controls
466 lines (363 loc) · 14.5 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
import io
import webbrowser
from flask import Flask, request, render_template, send_file, session
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.lib.units import inch
from reportlab.lib.enums import TA_LEFT
from reportlab.lib.styles import ParagraphStyle
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
from docx.shared import RGBColor
# Custom imports
from scraper import scrape_nvd, scrape_cveorg, scrape_cvedetails, scrape_exploitdb
from helpers import is_valid_cve
# App initialization
app = Flask(__name__)
app.secret_key = "your_secret_key"
@app.route("/")
def home():
"""
RS
Route for the home page of the web application.
This function handles requests to the root URL ("/") and returns the
rendered 'index.html' template, which serves as the home page of the site.
"""
return render_template("index.html")
@app.route("/cve", methods=["POST"])
def cve_checker():
"""
AA
Route for the CVE checker page of the web application.
This function handles POST requests to the "/cve" URL and renders the
'searchresult.html' template with the scraped data from NVD, CVE.org,
CVE Details and ExploitDB. If the CVE ID is not valid, it renders the
same template with an error message.
Args:
request.form["cve_id"]: The CVE ID to be searched.
Returns:
Rendered 'searchresult.html' template with scraped data or an error
message if the CVE ID is not valid.
"""
# AA. Get the CVE ID from the form and make it uppercase
cve_id = request.form["cve_id"].upper()
# AA. Check if the CVE ID is valid
cve_passed_regex = is_valid_cve(cve_id)
# AA. If the CVE ID is valid, scrape the data from the scrapers otherwise render the same template with an error message
if cve_passed_regex:
nvd_data = scrape_nvd(cve_id)
cveorg_data = scrape_cveorg(cve_id)
cvedetails_data = scrape_cvedetails(cve_id)
exploits = scrape_exploitdb(cve_id)
# AA. Combine the scraped data into a single dictionary
cve_data = {**nvd_data, **cveorg_data, **cvedetails_data}
# RS, SA. Store the scraped data in the session
session["cve_data"] = cve_data
# AA. Open the CVE website in the default web browser
websites = [
"https://nvd.nist.gov/vuln/detail/"+cve_id,
"https://www.cve.org/CVERecord?id="+cve_id,
"https://www.cvedetails.com/cve/"+cve_id,
"https://cve.mitre.org/cgi-bin/cvename.cgi?name="+cve_id,
"https://www.tenable.com/cve/"+cve_id,
]
# AA. Open the websites in the default web browser
for url in websites:
webbrowser.open(url)
# AA. Render the 'searchresult.html' template with the scraped data
return render_template(
"searchresult.html", cve_data=cve_data, exploits=exploits
)
else:
# AA. If the CVE ID is not valid, render the same template with an error message
return render_template(
"searchresult.html", cve_data={"error": "CVE not found or wrong CVE format"}
)
@app.route("/download/pdf")
def download_pdf():
"""
RS
Download CVE report as PDF.
This function generates a PDF report based on the stored CVE data in the
session and sends it as a downloadable file. If no CVE data is available in
the session, it returns an error message.
Returns:
A PDF file containing the CVE report, or an error message if no CVE
data is available in the session.
"""
# RS, SA.Get the CVE data from the session
cve_data = session.get("cve_data")
# If no CVE data is available in the session, return an error message
if not cve_data:
return "No CVE data available to generate the PDF.", 400
# Generate the PDF report
pdf_buffer = io.BytesIO()
generate_pdf(cve_data, pdf_buffer)
pdf_buffer.seek(0)
# Send the PDF file as a downloadable file
return send_file(
pdf_buffer,
as_attachment=True,
download_name="cve_report.pdf",
mimetype="application/pdf",
)
def generate_pdf(cve_data, buffer):
"""
RS
Generate a PDF report from the given CVE data and write it to the given file-like object.
Args:
cve_data (dict): A dictionary containing the CVE data to be included in the report.
buffer (file-like object): A file-like object to which the generated PDF report will be written.
Returns:
None
"""
# Create the PDF document
doc = SimpleDocTemplate(buffer, pagesize=letter)
# Define the elements to be included in the report
elements = []
# Add a title
styles = getSampleStyleSheet()
title = Paragraph("CVE Report", styles["Title"])
elements.append(title)
# Define a custom paragraph style for table content
custom_style = ParagraphStyle(
name="Custom",
fontSize=10,
leading=12,
alignment=TA_LEFT,
wordWrap="CJK", # Enables text wrapping
)
# Prepare data for the table
table_data = [["Key", "Value"]] # Table header
# Iterate over the cve_data dictionary
for key, value in cve_data.items():
if key in ["cvss_color", "status_color"]:
continue # Skip these fields
# Format the key: uppercase and replace underscores with spaces
formatted_key = key.upper().replace("_", " ")
# Check if value needs to be a Paragraph
if isinstance(value, str):
if len(value) > 50: # Adjust threshold as needed
value = Paragraph(value, custom_style)
else:
value = Paragraph(value, custom_style)
elif isinstance(value, dict):
# Debugging: Print out the type of value if it's a dictionary
print(f"Debug: Value for key '{key}' is a dictionary: {value}")
value = Paragraph(
str(value), custom_style
) # Convert dict to string and then to Paragraph
else:
# Handle other types of values if needed
print(f"Debug: Value for key '{key}' is of type {type(value)}")
value = Paragraph(str(value), custom_style)
table_data.append([formatted_key, value])
# Create a table with style
table = Table(
table_data, colWidths=[2.5 * inch, 4.5 * inch]
) # Adjust column widths as needed
table.setStyle(
TableStyle(
[
("BACKGROUND", (0, 0), (-1, 0), colors.grey),
("TEXTCOLOR", (0, 0), (-1, 0), colors.whitesmoke),
("ALIGN", (0, 0), (-1, -1), "CENTER"),
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
("FONTSIZE", (0, 0), (-1, 0), 14),
("BOTTOMPADDING", (0, 0), (-1, 0), 12),
("BACKGROUND", (0, 1), (-1, -1), colors.beige),
("GRID", (0, 0), (-1, -1), 1, colors.black),
("ALIGN", (0, 1), (-1, -1), "LEFT"),
]
)
)
# Add the table to the elements
elements.append(table)
# Build the PDF document
doc.build(elements)
@app.route("/download/word")
def download_word():
"""
RS
Download CVE report as a Word document.
This function generates a Word document based on the stored CVE data in the
session and sends it as a downloadable file. If no CVE data is available in
the session, it returns an error message.
Returns:
A Word file containing the CVE report, or an error message if no CVE
data is available in the session.
"""
cve_data = session.get("cve_data")
# Check if CVE data exists
if not cve_data:
return "No CVE data available to generate the Word document.", 400
# Create an in-memory buffer
word_buffer = io.BytesIO()
# Generate the Word document and write it to the buffer
generate_word(cve_data, word_buffer)
# Move the pointer to the beginning of the buffer
word_buffer.seek(0)
# Send the buffer as a downloadable Word file
return send_file(
word_buffer,
as_attachment=True,
download_name="cve_report.docx",
mimetype="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
)
def generate_word(cve_data, buffer):
"""
RS
Generate a Word document from the given CVE data and write it to the given file-like object.
Args:
cve_data (dict): A dictionary containing the CVE data to be included in the report.
buffer (file-like object): A file-like object to which the generated Word document will be written.
Returns:
None
"""
# Create a new Word document
doc = Document()
# Add a title with styling
title = doc.add_heading("CVE Report", level=1)
title_format = title.paragraph_format
title_format.space_after = Pt(12)
# Style for key headings (formatted key names)
key_style = doc.styles.add_style("KeyStyle", 1)
key_font = key_style.font
key_font.bold = True
key_font.size = Pt(12)
key_font.color.rgb = RGBColor(0, 102, 204) # Dark blue color
# Style for values
value_style = doc.styles.add_style("ValueStyle", 1)
value_font = value_style.font
value_font.size = Pt(11)
# Add key-value pairs to the Word document with formatting
for key, value in cve_data.items():
if key in ["cvss_color", "status_color"]:
continue # Skip these fields
# Format the key: uppercase and replace underscores with spaces
formatted_key = key.upper().replace("_", " ")
# Add the key with the custom style
key_paragraph = doc.add_paragraph(f"{formatted_key}:", style="KeyStyle")
# Add the value with the custom style
value_paragraph = doc.add_paragraph(str(value), style="ValueStyle")
# Add space after each entry for better readability
key_paragraph.paragraph_format.space_after = Pt(4)
value_paragraph.paragraph_format.space_after = Pt(8)
# Alternate background color for better readability
if len(doc.paragraphs) % 2 == 0:
shading_elm = parse_xml(r'<w:shd {} w:fill="F2F2F2"/>'.format(nsdecls("w")))
key_paragraph._p.get_or_add_pPr().append(shading_elm)
value_paragraph._p.get_or_add_pPr().append(shading_elm)
# Save the document to the buffer
doc.save(buffer)
@app.route("/download/md")
def download_md():
"""
SA
Download CVE report as Markdown.
This function generates a Markdown report based on the stored CVE data in the
session and sends it as a downloadable file. If no CVE data is available in
the session, it returns an error message.
Returns:
A Markdown file containing the CVE report, or an error message if no CVE
data is available in the session.
"""
cve_data = session.get("cve_data")
# Check if CVE data exists
if not cve_data:
return "No CVE data available to generate the Markdown report.", 400
# Create an in-memory buffer for Markdown
md_buffer = io.BytesIO()
# Generate the Markdown content and write it to the buffer
generate_md(cve_data, md_buffer)
# Move the pointer to the beginning of the buffer
md_buffer.seek(0)
# Send the buffer as a downloadable Markdown file
return send_file(
md_buffer,
as_attachment=True,
download_name="cve_report.md",
mimetype="text/markdown",
)
def generate_md(cve_data, buffer):
"""
SA
Generate a Markdown report from the given CVE data and write it to the given file-like object.
Args:
cve_data (dict): A dictionary containing the CVE data to be included in the report.
buffer (file-like object): A file-like object to which the generated Markdown report will be written.
Returns:
None
"""
report_lines = ["# CVE Report\n\n"]
# Add key-value pairs to the report
for key, value in cve_data.items():
if key in ["cvss_color", "status_color"]:
continue
formatted_key = key.upper().replace("_", " ")
report_lines.append(f"## {formatted_key}\n")
report_lines.append(f"{value}\n\n")
# Join the list into a string and write to the buffer
report_content = "".join(report_lines)
buffer.write(report_content.encode("utf-8"))
@app.route("/download/html")
def download_html():
"""
SA
Download CVE report as HTML.
This function generates an HTML report based on the stored CVE data in the
session and sends it as a downloadable file. If no CVE data is available in
the session, it returns an error message.
Returns:
An HTML file containing the CVE report, or an error message if no CVE
data is available in the session.
"""
cve_data = session.get("cve_data")
# Check if CVE data exists
if not cve_data:
return "No CVE data available to generate the HTML report.", 400
# Create an in-memory buffer for HTML
html_buffer = io.BytesIO()
# Generate the HTML content and write it to the buffer
generate_html(cve_data, html_buffer)
# Move the pointer to the beginning of the buffer
html_buffer.seek(0)
# Send the buffer as a downloadable HTML file
return send_file(
html_buffer,
as_attachment=True,
download_name="cve_report.html",
mimetype="text/html",
)
def generate_html(cve_data, buffer):
"""
SA
Generate an HTML report from the given CVE data and write it to the given file-like object.
Args:
cve_data (dict): A dictionary containing the CVE data to be included in the report.
buffer (file-like object): A file-like object to which the generated HTML report will be written.
Returns:
None
"""
# Generate the HTML content
html_lines = ["<html><head><title>CVE Report</title></head><body>"]
html_lines.append("<h1>CVE Report</h1>")
# Add key-value pairs to the report
for key, value in cve_data.items():
if key in ["cvss_color", "status_color"]:
continue
formatted_key = key.upper().replace("_", " ")
html_lines.append(f"<h2>{formatted_key}</h2>")
html_lines.append(f"<p>{value}</p>")
# Close the HTML body
html_lines.append("</body></html>")
# Join the list into a string and write to the buffer
html_content = "".join(html_lines)
buffer.write(html_content.encode("utf-8"))
# RS. Run the Flask app
if __name__ == "__main__":
app.run(debug=True)