-
Notifications
You must be signed in to change notification settings - Fork 0
/
reportlab_generator.py
592 lines (541 loc) · 20.1 KB
/
reportlab_generator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
"""Generate a TPT report using a passed data dictionary."""
# Standard Python Libraries
from hashlib import sha256
import os
import pandas as pd
# Third-Party Libraries
import numpy as np
from reportlab.lib import utils
from reportlab.lib.colors import HexColor
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import inch
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import (
HRFlowable,
Image,
KeepTogether,
# ListFlowable,
# ListItem,
PageBreak,
Paragraph,
Spacer,
Table,
TableStyle,
)
from reportlab.platypus.doctemplate import (
BaseDocTemplate,
# NextPageTemplate,
PageTemplate,
)
from reportlab.platypus.frames import Frame
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
EXAMPLE_TABLE1 = {
"id": [12],
"Finding": ["Spear Phishing Weakness"],
"Severity": ["High"],
"Service": ["Phishing Assessment (Infrastructure Only)"],
"Location": ["Phishing"]
}
# Set fonts that you will use in the pdf.
pdfmetrics.registerFont(
TTFont("Franklin_Gothic_Book", BASE_DIR + "/fonts/FranklinGothicBook.ttf")
)
pdfmetrics.registerFont(
TTFont(
"Franklin_Gothic_Medium_Regular",
BASE_DIR + "/fonts/FranklinGothicMediumRegular.ttf",
)
)
# Set your page size
defaultPageSize = letter
PAGE_HEIGHT = defaultPageSize[1]
PAGE_WIDTH = defaultPageSize[0]
class MyDocTemplate(BaseDocTemplate):
"""Extend the BaseDocTemplate to adjust Template."""
def __init__(self, filename, **kw):
"""Initialize MyDocTemplate."""
self.allowSplitting = 0
BaseDocTemplate.__init__(self, filename, **kw)
self.pagesize = defaultPageSize
class ConditionalSpacer(Spacer):
"""Create a Conditional Spacer class."""
def wrap(self, availWidth, availHeight):
"""Create a spacer if there is space on the page to do so."""
height = min(self.height, availHeight - 1e-8)
return (availWidth, height)
def get_image(path, width=1 * inch):
"""Read in an image and scale it based on the width argument."""
img = utils.ImageReader(path)
iw, ih = img.getSize()
aspect = ih / float(iw)
return Image(path, width=width, height=(width * aspect))
def format_table(
df, header_style, column_widths, column_style_list, remove_symbols=False
):
"""Read in a dataframe and convert it to a table and format it with a provided style list."""
header_row = [
[Paragraph(str(cell), header_style) for cell in row] for row in [df.columns]
]
data = []
for row in np.array(df).tolist():
current_cell = 0
current_row = []
for cell in row:
if column_style_list[current_cell] is not None:
# Remove emojis from content because the report generator can't display them
cell = Paragraph(
str(cell), column_style_list[current_cell]
)
current_row.append(cell)
current_cell += 1
data.append(current_row)
data = header_row + data
table = Table(
data,
colWidths=column_widths,
rowHeights=None,
style=None,
splitByRow=1,
repeatRows=1,
repeatCols=0,
rowSplitRange=(2, -1),
spaceBefore=None,
spaceAfter=None,
cornerRadii=None,
)
style = TableStyle(
[
("VALIGN", (0, 0), (-1, 0), "MIDDLE"),
("ALIGN", (0, 0), (-1, -1), "CENTER"),
("VALIGN", (0, 1), (-1, -1), "MIDDLE"),
("INNERGRID", (0, 0), (-1, -1), 1, "white"),
("TEXTFONT", (0, 1), (-1, -1), "Franklin_Gothic_Book"),
("FONTSIZE", (0, 1), (-1, -1), 12),
(
"ROWBACKGROUNDS",
(0, 1),
(-1, -1),
[HexColor("#FFFFFF"), HexColor("#DEEBF7")],
),
("BACKGROUND", (0, 0), (-1, 0), HexColor("#1d5288")),
("LINEBELOW", (0, -1), (-1, -1), 1.5, HexColor("#1d5288")),
]
)
table.setStyle(style)
if len(df) == 0:
label = Paragraph(
"No Data to Report",
ParagraphStyle(
name="centered",
fontName="Franklin_Gothic_Medium_Regular",
textColor=HexColor("#a7a7a6"),
fontSize=16,
leading=16,
alignment=1,
spaceAfter=10,
spaceBefore=10,
),
)
table = KeepTogether([table, label])
return table
def report_gen(data_dict):
"""Generate a TPT report with data passed in the data dictionry."""
"""Build the 'templates' for the static pages."""
def doHeading(text, sty):
"""Add a bookmark to heading element to allow linking from the table of contents."""
# this will add a bookmark to a header allowing it to be linked from the table of contents
# create bookmarkname
bn = sha256((text + sty.name).encode("utf8")).hexdigest()
# modify paragraph text to include an anchor point with name bn
h = Paragraph(text + '<a name="%s"/>' % bn, sty)
# store the bookmark name on the flowable so afterFlowable can see this
h._bookmarkName = bn
return h
def titlePage(canvas, doc):
"""Build static elements of the cover page."""
canvas.saveState()
# Add the background image to the top
# canvas.drawImage(BASE_DIR + "/assets/TitlePage.png", 0, 0, width=None, height=None)
# canvas.drawInlineImage(
# BASE_DIR + "/assets/cisa.png", 45, 705, width=65, height=65
# )
# Story.append(get_image(BASE_DIR + "/assets/TitlePage.png", width=6 * inch))
# # set the font
canvas.setFont("Franklin_Gothic_Medium_Regular", 32)
# # Write the title to page and add some dynamic content to complete the tile page later
# canvas.drawString(50, 660, "TPT Report")
# canvas.restoreState()
def summaryPage(canvas, doc):
"""Build static elements of the summary page."""
# canvas.saveState()
# # Set the font
# canvas.setFont("Franklin_Gothic_Book", 13)
# # add a background image
# # canvas.drawImage(
# # BASE_DIR + "/assets/summary-background.png",
# # 0,
# # 0,
# # width=PAGE_WIDTH,
# # height=PAGE_HEIGHT,
# # )
# # Change the color that will be used in the rectangle we add
# canvas.setFillColor(HexColor("#1d5288"))
# canvas.setStrokeColor("#1d5288")
# canvas.rect(inch, 210, 3.5 * inch, 5.7 * inch, fill=1)
# canvas.restoreState()
# # Add header/footer
# canvas.setStrokeColor("#a7a7a6")
# canvas.setFillColor("#a7a7a6")
# canvas.drawInlineImage(
# BASE_DIR + "/assets/cisa.png", 45, 705, width=65, height=65
# )
# canvas.drawString(130, 745, "TPT Report")
# canvas.drawString(130, 725, "Reporting Period: " + data_dict["dateRange"])
# canvas.line(130, 710, PAGE_WIDTH - inch, 710)
# canvas.drawRightString(
# PAGE_WIDTH - inch, 0.75 * inch, "P&E Report | Page %d" % (doc.page)
# )
# canvas.drawString(inch, 0.75 * inch, data_dict["endDate"])
# canvas.setFont("Franklin_Gothic_Medium_Regular", 12)
# ***Document Structures***#
"""Build frames for different page structures."""
# Load the doc
doc = MyDocTemplate(data_dict["filename"])
# Create the frames that will be dynamically filled later on
# frame: x, y, width, height
# title_frame = Frame(45, 390, 530, 250, id=None, showBoundary=0)
frameT = Frame(
doc.leftMargin - (0.5 * inch),
doc.bottomMargin,
PAGE_WIDTH - (1 * inch),
PAGE_HEIGHT - (2.4 * inch),
id="normal",
showBoundary=0,
)
# Add different Page templates for dynamic filling
doc.addPageTemplates(
[
PageTemplate(id="TitlePage", frames=frameT, onPage=titlePage),
PageTemplate(id="SummaryPage", frames=frameT, onPage=summaryPage),
]
)
# Generate the list that we will fill with all of our dynamic content that will stream through the report
Story = []
"""Create font and formatting styles."""
PS = ParagraphStyle
centered = PS(
name="centered",
fontName="Franklin_Gothic_Medium_Regular",
fontSize=20,
leading=16,
alignment=1,
spaceAfter=10,
spaceBefore=10,
)
indented = PS(
name="indented",
fontName="Franklin_Gothic_Book",
fontSize=12,
leading=14,
leftIndent=30,
spaceAfter=20,
)
h1 = PS(
fontName="Franklin_Gothic_Medium_Regular",
name="Heading1",
fontSize=16,
leading=18,
textColor=HexColor("#003e67"),
)
h2 = PS(
name="Heading2",
fontName="Franklin_Gothic_Medium_Regular",
fontSize=14,
leading=10,
textColor=HexColor("#003e67"),
spaceAfter=12,
)
h3 = PS(
name="Heading3",
fontName="Franklin_Gothic_Medium_Regular",
fontSize=14,
leading=10,
textColor=HexColor("#003e67"),
spaceAfter=10,
)
body = PS(
name="body",
leading=14,
fontName="Franklin_Gothic_Book",
fontSize=12,
)
json_excel = PS(
name="json_excel",
fontName="Franklin_Gothic_Medium_Regular",
fontSize=10,
alignment=1,
)
figure = PS(
name="figure",
fontName="Franklin_Gothic_Medium_Regular",
fontSize=12,
leading=16,
alignment=1,
)
table = PS(
name="table",
fontName="Franklin_Gothic_Medium_Regular",
fontSize=12,
leading=16,
alignment=1,
spaceAfter=12,
)
table_header = PS(
name="table_header",
fontName="Franklin_Gothic_Medium_Regular",
fontSize=12,
leading=20,
alignment=1,
spaceAfter=30,
textColor=HexColor("#FFFFFF"),
)
title_data = PS(
fontName="Franklin_Gothic_Medium_Regular", name="Title", fontSize=18, leading=20
)
"""Stream all the dynamic content to the report."""
# *************************#
# Create repeated elements
# Create random elements we will use throughout the report. i.ee horizontal lines and spacers
point12_spacer = ConditionalSpacer(1, 12)
horizontal_line = HRFlowable(
width="100%",
thickness=1.5,
lineCap="round",
color=HexColor("#003e67"),
spaceBefore=0,
spaceAfter=1,
hAlign="LEFT",
vAlign="TOP",
dash=None,
)
# ***Title Page***#
#The default template will be the first in the list we create above i.e. TitlePage
#These will start at the beginning of the frame we added to that template page
# Story.append(point12_spacer)
# Story.append(point12_spacer)
Story.append(get_image(BASE_DIR + "/assets/TitlePage.png", width=7.3 * inch))
Story.append(point12_spacer)
Story.append(point12_spacer)
Story.append(doHeading("TPT Report", h1))
Story.append(PageBreak())
# Story.append(Spacer(1, 55))
Story.append(
format_table(
data_dict["intro_table"],
table_header,
[1.5 * inch, 2.3 * inch, 2* inch, 1.5 * inch],
[None, body, None, None],
)
)
Story.append(Spacer(1, 55))
Story.append(
format_table(
data_dict["reference_table"],
table_header,
[5.8 * inch, 1.5 * inch],
[body, None],
)
)
# Story.append(Spacer(1, 40))
# Story.append(Paragraph("Phishing Results", h1))
# Story.append(Spacer(1, 10))
# Story.append(
# Paragraph("""The phishing test evaluated the performance of security controls at the border and host. During a phishing attack (Figure 5), an attacker sends an email that must successfully pass through any protections presented by both the network border and the host system that receives the email.""", body)
# )
Story.append(PageBreak())
Story.append(horizontal_line)
Story.append(point12_spacer)
Story.append(doHeading("Phishing Results", h2))
Story.append(
Paragraph(
"""The phishing test evaluated the performance of security controls
at the border and host. During a phishing attack (Figure 5), an
attacker sends an email that must successfully pass through any
protections presented by both the network border and the host system
that receives the email.""",
body,
)
)
Story.append(point12_spacer)
Story.append(get_image(BASE_DIR + "/assets/Picture1.png", width=4 * inch))
Story.append(point12_spacer)
Story.append(get_image(BASE_DIR + "/assets/Picture2.png", width=4 * inch))
Story.append(point12_spacer)
Story.append(
Paragraph(
"""A simulated phishing attack scenario was performed with the Example Organization (EXPL) complicit user, Alisia Romo, during which, the CISA team attempted to execute a variety of simulated malicious payloads on the POC’s workstation. This simulated attack scenario was meant to test EXPL’s security controls in their ability to identify, alert, and prevent such attack vectors. """,
body,
)
)
Story.append(point12_spacer)
Story.append(
Paragraph(
"""The initial email containing a link to the malicious payloads was able to circumvent border protections and reach the complicit user’s inbox (in spam). Of the twenty-five (25) different payloads tested, zero (0) payloads successfully executed and connected to the CISA team’s command-and-control (C2) server. From the attached payload test, one (1) of the eight (8) emails containing malicious attachments was able to circumvent through border protections and reach the POC’s inbox. This payload was unable to successfully execute.""",
body,
)
)
# Story.append(point12_spacer)
# Story.append(point12_spacer)
Story.append(PageBreak())
Story.append(horizontal_line)
Story.append(point12_spacer)
Story.append(doHeading("Noted System Strengths", h2))
Story.append(
Paragraph(
"""The internal and email infrastructure incorporated several security features that reduced the effectiveness of phishing payloads. The environment’s firewall (Fortinet) prohibited users from accessing the testing team’s malicious web during the phishing assessment. This reduces the likelihood of users obtaining malicious software from known malicious sites and domains. The environment utilized an effective antivirus solution (Trend Micro), which prevented the execution of most malicious payloads during the phishing assessment.""",
body,
)
)
Story.append(point12_spacer)
Story.append(
Paragraph(
"""The environment utilized Albert real-time monitoring, which alerted security staff upon the detection of malicious code within the environment. The alert notifications were received within minutes of initiating the phishing assessment.""",
body,
)
)
Story.append(point12_spacer)
Story.append(
format_table(
pd.DataFrame.from_dict(EXAMPLE_TABLE1),
table_header,
[.5 * inch, 1.5 * inch, inch, 2.5 * inch, inch],
[None, body, None, body, None],
)
)
Story.append(point12_spacer)
Story.append(point12_spacer)
Story.append(doHeading("Affected Systems", h2))
Story.append(
Paragraph(
"""@example.org workstations""",
body,
)
)
Story.append(point12_spacer)
Story.append(point12_spacer)
Story.append(doHeading("Description", h2))
Story.append(
Paragraph(
"""Successful spear phishing requires an attacker’s email to pass through the network border and execute on the local host with the aid of a user performing some action. Most common phishing attacks can be rebuffed by good border and host-level automated protections. Inadequate protections allow the execution of malicious payloads. """,
body,
)
)
Story.append(point12_spacer)
Story.append(point12_spacer)
Story.append(doHeading("Recommended Mitigation", h2))
Story.append(
Paragraph(
"""Regularly analyze border and host-level protections, including spam-filtering capabilities, to ensure their continued effectiveness in blocking the delivery and execution of malware. """,
body,
)
)
Story.append(PageBreak())
Story.append(horizontal_line)
Story.append(point12_spacer)
Story.append(doHeading("Payload Testing Results", h2))
Story.append(
Paragraph(
"""
Payload Testing Results
""",
table,
)
)
# Generate a table using ad atabframe passed to my format_table function
Story.append(
format_table(
data_dict["breach_table"],
table_header,
[2.5 * inch, inch, inch, inch, inch],
[body, None, None, None, None],
)
)
Story.append(point12_spacer)
Story.append(PageBreak())
Story.append(horizontal_line)
Story.append(point12_spacer)
Story.append(doHeading("Payload Testing Results", h2))
Story.append(
Paragraph(
"""The initial email containing a link to the malicious payloads was able to circumvent border protections and reach the complicit user’s inbox (in spam). Of the twenty-five (25) different payloads tested, no payloads successfully executed and connected to the CISA team’s C2 server. From the attached payload test, one (1) of the eight (8) emails containing malicious attachments were able to circumvent through border protections and reach the POC’s inbox. This payload was unable to successfully execute. """,
body,
)
)
Story.append(point12_spacer)
Story.append(point12_spacer)
Story.append(doHeading("Conclusions/Recommendations", h2))
Story.append(
Paragraph(
"""Regularly analyze border and host-level protections, including spam-filtering capabilities, to ensure their continued effectiveness in blocking the delivery and execution of malware. """,
body,
)
)
# Story.append(horizontal_line)
# Story.append(point12_spacer)
# Preloaded templates to use on the next page
# Story.append(point12_spacer)
# Story.append(point12_spacer)
# Story.append(
# Paragraph(
# """
# Payload Testing Results
# """,
# table,
# )
# )
# # Generate a table using ad atabframe passed to my format_table function
# Story.append(
# format_table(
# data_dict["breach_table"],
# table_header,
# [2.5 * inch, inch, inch, inch, inch],
# [body, None, None, None, None],
# )
# )
# Story.append(point12_spacer)
# Story.append(PageBreak())
doc.multiBuild(Story)
return 1
# Temporary list data
data_dict = {
'dateRange': "Test date",
'startDate': 'start_date',
'endDate': 'end_date',
'filename': 'testrun.pdf',
'intro_table': pd.DataFrame.from_dict(
{
'Report Date': ['dd/mm/yy'],
'Stakeholder Name': ['Test stakeholder'],
'Test Conducted': ['Type of Assessment'],
'Assessment ID': ['######']
}
),
'reference_table': pd.DataFrame.from_dict(
{
'Security Reference (FCRM, NIST, ETC.)': ['NIST ### - ## - Revision # - The subject matter listed', '', ''],
'Date': ['dd/mm/yy', '', ''],
}
),
'breach_table': pd.DataFrame.from_dict(
{
'Payload Description': ['0', '1', '2', '3'],
'C2 Protocol': ['a', 'b', 'c', 'd'],
'Border Protection': ['1', 'b', '3', 'd'],
'Host Protection': ['ab', 'bc', 'cd', 'de'],
'Notes': ['w', 'x', 'y', 'z']
}
)
}
report_gen(data_dict)