-
Notifications
You must be signed in to change notification settings - Fork 16
/
Halberd.py
2188 lines (1921 loc) · 91.2 KB
/
Halberd.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
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
#!/usr/bin/env python3
import json
import dash
import datetime
import time
import os
import boto3
import uuid
import threading
import dash_bootstrap_components as dbc
from dash import dcc, html, ALL, callback_context, no_update, MATCH, ctx
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
import dash_daq as daq
from dash_iconify import DashIconify
import pandas as pd
from core.entra.entra_token_manager import EntraTokenManager
from core.azure.azure_access import AzureAccess
from pages.dashboard.entity_map import GenerateEntityMappingGraph
from core.Functions import generate_technique_info, run_initialization_check, AddNewSchedule, GetAllPlaybooks, ParseTechniqueResponse, playbook_viz_generator, generate_attack_technique_options, generate_attack_tactics_options, generate_attack_technique_config, generate_entra_access_info, generate_aws_access_info, generate_azure_access_info, parse_app_log_file, group_app_log_events, create_app_log_event_summary, get_playbook_stats, parse_execution_report
from core.playbook.playbook import Playbook
from core.playbook.playbook_step import PlaybookStep
from core.playbook.playbook_error import PlaybookError
from core.Constants import *
from core.aws.aws_session_manager import SessionManager
from attack_techniques.technique_registry import *
from core.logging.logger import setup_logger,StructuredAppLog
from core.logging.report import read_log_file, analyze_log, generate_html_report
from core.output_manager.output_manager import OutputManager
from pages.attack_analyse import process_attack_data, create_metric_card, create_df_from_attack_logs, create_bar_chart, create_pie_chart, create_timeline_graph
from pages.automator import create_playbook_item, create_playbook_manager_layout, schedule_pb_div, export_pb_div, generate_playbook_creator_offcanvas, generate_step_form, playbook_editor_create_parameter_inputs, create_step_progress_card
# Create Application
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.LUX, dbc.icons.BOOTSTRAP],title='Halberd', update_title='Loading...', suppress_callback_exceptions=True)
# Navigation bar layout
navbar = dbc.NavbarSimple(
id = "halberd-main-navbar",
children=[
dbc.NavItem(dbc.NavLink("Attack", href="/attack")),
dbc.NavItem(dbc.NavLink("Recon", href="/recon")),
dbc.NavItem(dbc.NavLink("Automator", href="/automator")),
dbc.NavItem(dbc.NavLink("Analyse", href="/attack-analyse"))
],
brand= html.Div([
dbc.Row(
[
dbc.Col(html.Img(src="/assets/favicon.ico", height="30px")),
dbc.Col(html.Div("Halberd", className="text-danger", style={'font-family':'horizon'})),
],
),
]),
brand_href="/home",
color="dark",
dark=True,
sticky= "top",
)
# App layout
app.layout = html.Div([
dcc.Interval(id='interval-to-trigger-initialization-check',interval=60000,n_intervals=0),
html.Div(id='hidden-div', style={'display':'none'}),
dcc.Location(id='url', refresh=False),
navbar,
html.Div(id='page-content',className="bg-dark", style={'overflow': 'auto'}),
dbc.Toast(
children = "Hello!",
id="app-welcome-notification",
header="Welcome to Halberd",
is_open=True,
dismissable=True,
duration=3000,
color="primary",
style={"position": "fixed", "top": 92, "right": 10, "width": 350},
),
dbc.Toast(
children = "",
id="app-notification",
header="Notification",
is_open=False,
dismissable=True,
duration=5000,
color="primary",
style={"position": "fixed", "top": 92, "right": 10, "width": 350},
),
dcc.Download(id="app-download-sink"),
dbc.Modal(
[
dbc.ModalHeader(dbc.ModalTitle("Technique Details")),
dbc.ModalBody(id = "app-technique-info-display-modal-body"),
dbc.ModalFooter(
dbc.Button("Close", id="close-app-technique-info-display-modal", className="ml-auto")
),
],
id="app-technique-info-display-modal",
size="lg",
scrollable=True,
),
# Error modal -> use this to display an error pop up message
dbc.Modal(
[
dbc.ModalHeader("Error", style={"background-color": "#dc3545", "color": "white"}),
dbc.ModalBody(id="app-error-display-modal-body"),
dbc.ModalFooter(
dbc.Button("Close", id="close-app-error-display-modal", className="ml-auto")
),
],
id="app-error-display-modal",
is_open=False,
),
# Success modal -> use this to display a success pop up message
dbc.Modal(
[
dbc.ModalHeader("Success", style={"background-color": "#28a745", "color": "white"}),
dbc.ModalBody(id="app-success-display-modal-body"),
dbc.ModalFooter(
dbc.Button("Close", id="close-app-success-display-modal", className="ml-auto")
),
],
id="app-success-display-modal",
is_open=False,
)
])
'''C001 - Callback to update the page content based on the URL'''
@app.callback(Output('page-content', 'children'), [Input('url', 'pathname')])
def display_page_from_url_callback(pathname):
if pathname == '/home':
from pages.home import page_layout
return page_layout
elif pathname == '/attack':
from pages.attack import page_layout
return page_layout
elif pathname == '/recon':
from pages.recon import page_layout
return page_layout
elif pathname == '/automator':
return create_playbook_manager_layout()
elif pathname == '/schedules':
from pages.schedules import generate_automator_schedules_view
return generate_automator_schedules_view()
elif pathname == '/attack-history':
from pages.attack_history import generate_attack_history_page
return generate_attack_history_page()
elif pathname == '/attack-analyse':
from pages.attack_analyse import create_layout
return create_layout()
else:
from pages.home import page_layout
return page_layout
'''C002 - Callback to generate tactic dropdown options in Attack view'''
@app.callback(
Output(component_id = "tactic-dropdown", component_property = "options"),
Output(component_id = "tactic-dropdown", component_property = "value"),
Input(component_id = "attack-surface-tabs", component_property = "active_tab")
)
def generate_tactic_dropdown_callback(tab):
tactic_dropdown_option = generate_attack_tactics_options(tab)
return tactic_dropdown_option, tactic_dropdown_option[0]["value"]
'''C003 - Callback to generate techniques radio options in Attack page'''
@app.callback(
Output(component_id = "attack-techniques-options-div", component_property = "children"),
Input(component_id = "attack-surface-tabs", component_property = "active_tab"),
Input(component_id = "tactic-dropdown", component_property = "value")
)
def generate_attack_technique_options_callback(tab, tactic):
technique_options = generate_attack_technique_options(tab, tactic)
return technique_options
'''C004 - Callback to display technique config'''
@app.callback(
Output(component_id = "attack-config-div", component_property = "children"),
Input(component_id = "attack-options-radio", component_property = "value"),
prevent_initial_call=True
)
def display_attack_technique_config_callback(technique):
technique_config = generate_attack_technique_config(technique)
return technique_config
'''C005 - Callback to execute a technqiue'''
@app.callback(
Output(component_id = "execution-output-div", component_property = "children"),
Output(component_id = "app-notification", component_property = "is_open", allow_duplicate=True),
Output(component_id = "app-notification", component_property = "children", allow_duplicate=True),
Input(component_id= "technique-execute-button", component_property= "n_clicks"),
State(component_id = "tactic-dropdown", component_property = "value"),
State(component_id = "attack-options-radio", component_property = "value"),
State({"type": "technique-config-display", "index": ALL}, "value"),
State({"type": "technique-config-display-boolean-switch", "index": ALL}, "on"),
State({"type": "technique-config-display-file-upload", "index": ALL}, "contents"),
prevent_initial_call = True
)
def execute_technique_callback(n_clicks, tactic, t_id, values, bool_on, file_content):
'''The input callback can handle text inputs, boolean flags and file upload content'''
if n_clicks == 0:
raise PreventUpdate
technique = TechniqueRegistry.get_technique(t_id)
technique_params = (technique().get_parameters())
# Technique attack surface / category
attack_surface = TechniqueRegistry.get_technique_category(t_id)
# Active entity / Source
active_entity = "Unknown"
if attack_surface in ["m365","entra_id"]:
manager = EntraTokenManager()
access_token = manager.get_active_token()
if access_token:
try:
access_info = manager.decode_jwt_token(access_token)
active_entity = access_info['Entity']
except Exception as e:
active_entity = "Unknown"
else:
active_entity = "Unknown"
if attack_surface == "aws":
try:
manager = SessionManager()
# set default session
sts_client = boto3.client('sts')
session_info = sts_client.get_caller_identity()
active_entity = session_info['UserId']
except:
active_entity = "Unknown"
if attack_surface == "azure":
try:
current_access = AzureAccess().get_current_subscription_info()
active_entity = current_access['user']['name']
except:
active_entity = "Unknown"
# Create technique input
technique_input = {}
file_input = {}
bool_input = {}
i=0
for param in technique_params:
if technique_params[param]['input_field_type'] not in ["bool", "upload"]:
technique_input[param] = [*values][i]
i+=1
elif technique_params[param]['input_field_type'] == "upload":
file_input[param] = technique_params[param]
elif technique_params[param]['input_field_type'] == "bool":
bool_input[param] = technique_params[param]
if file_content:
i = 0
for param in file_input:
technique_input[param] = [*file_content][i]
i+=1
if bool_on:
i = 0
for param in bool_input:
technique_input[param] = [*bool_on][i]
i+=1
# Log technique execution start
event_id = str(uuid.uuid4()) #Generate unique event_id for the execution
logger.info(StructuredAppLog("Technique Execution",
event_id = event_id,
source = active_entity,
status = "started",
technique = t_id,
tactic=tactic,
timestamp=datetime.datetime.now().isoformat())
)
# Execute technique
output = technique().execute(**technique_input)
# check if technique output is in the expected tuple format (success, response)
if isinstance(output, tuple) and len(output) == 2:
result, response = output
# Initialize output manager
output_manager = OutputManager()
if result.value == "success":
# Log technique execution success
logger.info(StructuredAppLog("Technique Execution",
event_id = event_id,
source = active_entity,
status = "completed",
result = "success",
technique = t_id,
target = None,
tactic=tactic,
timestamp=datetime.datetime.now().isoformat())
)
# Save output to file
output_manager.store_technique_output(
data=response['value'],
technique_name=t_id,
event_id=event_id
)
# Return results
return ParseTechniqueResponse(response['value']), True, "Technique Execution Successful"
# Log technique execution failure
logger.info(StructuredAppLog("Technique Execution",
event_id = event_id,
source = active_entity,
status = "completed",
result = "failed",
technique = t_id,
target = None,
tactic=tactic,
timestamp=datetime.datetime.now().isoformat())
)
# Save output to file
output_manager.store_technique_output(
data=response['error'],
technique_name=t_id,
event_id=event_id
)
# Return results
return ParseTechniqueResponse(response['error']), True, "Technique Execution Failed"
# Unexpected technique output
return ParseTechniqueResponse(""), True, "Technique Execution Failed"
'''C006 - Entity Map - Generate Map'''
@app.callback(
Output(component_id = "entity-map-display-div", component_property = "children", allow_duplicate=True),
Input(component_id = "generate-entity-map-button", component_property = "n_clicks"),
Input(component_id = "map-layout-select", component_property = "value"),
Input(component_id = "filter-select", component_property = "value"),
prevent_initial_call=True
)
def update_entity_map(n_clicks, map_layout, filter_category):
if not n_clicks:
return html.Div("Click 'Generate Entity Map' to view the map.")
if filter_category == 'all':
filter_category = None
return GenerateEntityMappingGraph(map_layout, filter_category)
'''C007 - Callback to display selected technique info in Attack view'''
@app.callback(
Output(component_id = "attack-technique-info-div", component_property = "children", allow_duplicate=True),
Input(component_id = "attack-options-radio", component_property = "value"),
prevent_initial_call=True
)
def display_attack_technique_info_callback(t_id):
if t_id is None:
raise PreventUpdate
# Get technique details
technique_details = generate_technique_info(t_id)
return technique_details
'''C008 - Callback to generate trace report'''
@app.callback(
Output(component_id = "app-download-sink", component_property = "data", allow_duplicate=True),
Input(component_id= "download-halberd-report-button", component_property= "n_clicks"),
prevent_initial_call = True
)
def generate_trace_report_callback(n_clicks):
if n_clicks == 0:
raise PreventUpdate
try:
log_lines = read_log_file(APP_LOG_FILE)
analysis_results = analyze_log(log_lines)
html_report = generate_html_report(analysis_results)
# Save the HTML report
with open(f'{REPORT_DIR}/halberd_security_report.html', 'w', encoding='utf-8') as report_file:
report_file.write(html_report)
return dcc.send_file(f'{REPORT_DIR}/halberd_security_report.html')
except FileNotFoundError:
return (f"Error: The file '{APP_LOG_FILE}' was not found. Ensure the log file exists and the path is correct.")
except Exception:
raise PreventUpdate
'''C009 - Callback to download trace logs'''
@app.callback(
Output("app-download-sink", "data"),
Input("download-trace-logs-button", "n_clicks"),
prevent_initial_call=True,
)
def download_trace_logs_callback(n_clicks):
if n_clicks == 0:
raise PreventUpdate
# Parse log file and create summary
events = parse_app_log_file(APP_LOG_FILE)
grouped_events = group_app_log_events(events)
summary = create_app_log_event_summary(grouped_events)
# Create DataFrame
df = pd.DataFrame(summary)
return dcc.send_data_frame(df.to_csv, "attack_trace.csv", index=False)
'''C010 - Callback to set AWS active/default session and populate AWS access info dynamically based on selected session'''
@app.callback(
Output(component_id = "aws-access-info-div", component_property = "children"),
Input(component_id = "interval-to-trigger-initialization-check", component_property = "n_intervals"),
Input(component_id = "aws-session-selector-dropdown", component_property = "value"))
def generate_aws_access_info_callback(n_interval, session_name):
return generate_aws_access_info(session_name)
'''C011 - Callback to populate EntraID access info'''
@app.callback(
Output(component_id = "access-info-div", component_property = "children"),
Input(component_id = "interval-to-trigger-initialization-check", component_property = "n_intervals"))
def generate_entra_access_info_callback(n_intervals):
return generate_entra_access_info("active")
'''C012 - Callback to set active Entra ID access token'''
@app.callback(
Output(component_id = "access-info-div", component_property = "children", allow_duplicate=True),
Input(component_id = "token-selector-dropdown", component_property = "value"),
prevent_initial_call=True)
def set_entra_active_token_callback(value):
manager = EntraTokenManager()
# Retrieve the actual token from tokens file
selected_token = json.loads(value)
selected_token_entity = list(selected_token.keys())[0]
selected_token_exp = list(selected_token.values())[0]
for token in manager.get_all_tokens():
token_info = manager.decode_jwt_token(token)
if token_info != None:
if token_info['Entity'] == selected_token_entity and token_info['Access Exp'] == selected_token_exp:
access_token = token
break
else:
pass
# Set selected token as active
manager.set_active_token(access_token)
# Update access info div with selected token info
return generate_entra_access_info(access_token=access_token)
'''C013 - Callback to generate Entra ID token options in Access dropdown'''
@app.callback(
Output(component_id = "token-selector-dropdown", component_property = "options"),
Input(component_id = "token-selector-dropdown", component_property = "title"))
def generate_entra_token_dropdown_callback(title):
manager = EntraTokenManager()
if title == None:
all_tokens = []
for token in manager.get_all_tokens():
token_info = manager.decode_jwt_token(token)
if token_info != None:
selected_value = {token_info.get('Entity') : token_info.get('Access Exp')}
all_tokens.append(
{
'label': html.Div(f"{token_info['Entity']}-{token_info.get('Access Exp')}", className="text-dark"), 'value': json.dumps(selected_value)
}
)
return all_tokens
'''C014 - Recon page tab switcher'''
@app.callback(
Output("recon-content-div", "children"),
Input("recon-target-tabs", "active_tab"))
def generate_content_from_recon_tab_callback(tab):
if tab == "tab-recon-entity-map":
from pages.dashboard.entity_map import page_layout
return page_layout
if tab == "tab-recon-roles":
from pages.dashboard.recon_roles import page_layout
return page_layout
if tab == "tab-recon-users":
from pages.dashboard.recon_users import page_layout
return page_layout
else:
from pages.dashboard.entity_map import page_layout
return page_layout
'''C015 - Callback to generate data in role recon dashboard'''
@app.callback(
Output(component_id = "role-name-recon-div", component_property = "children"),
Output(component_id = "role-template-id-recon-div", component_property = "children"),
Output(component_id = "role-id-recon-div", component_property = "children"),
Output(component_id = "role-member-count-recon-div", component_property = "children"),
Output(component_id = "role-member-recon-div", component_property = "children"),
Output(component_id = "role-description-recon-div", component_property = "children"),
Input(component_id= "role-recon-start-button", component_property= "n_clicks"),
Input(component_id = "role-recon-input", component_property = "value"))
def execute_recon_callback(n_clicks, role_name):
if n_clicks == 0:
raise PreventUpdate
# Input validation
if role_name in ["",None]:
response = "N/A"
return response, response, response, response, response, response
# Import recon functions
from pages.dashboard.recon_roles import FindRole, ReconRoleMembers
# Execute recon
role_name, role_id, role_template_id, role_description = FindRole(role_name)
member_count, role_members = ReconRoleMembers(role_template_id)
return role_name, role_template_id, role_id, member_count, role_members, role_description
'''C016 - Callback to generate data in user recon dashboard'''
@app.callback(Output(
component_id = "user-displayname-recon-div", component_property = "children"),
Output(component_id = "user-id-recon-div", component_property = "children"),
Output(component_id = "user-upn-recon-div", component_property = "children"),
Output(component_id = "user-mail-recon-div", component_property = "children"),
Output(component_id = "user-job-title-recon-div", component_property = "children"),
Output(component_id = "user-location-recon-div", component_property = "children"),
Output(component_id = "user-phone-recon-div", component_property = "children"),
Output(component_id = "user-group-count-recon-div", component_property = "children"),
Output(component_id = "user-role-count-recon-div", component_property = "children"),
Output(component_id = "user-groups-recon-div", component_property = "children"),
Output(component_id = "user-roles-recon-div", component_property = "children"),
Output(component_id = "user-app-count-recon-div", component_property = "children"),
Output(component_id = "user-app-recon-div", component_property = "children"),
Input(component_id= "user-recon-start-button", component_property= "n_clicks"),
Input(component_id = "user-recon-input", component_property = "value"))
def execute_user_recon_dashboard_callback(n_clicks, user_string):
if n_clicks == 0:
raise PreventUpdate
# Input validation
if user_string in ["",None]:
response = "N/A"
return response, response, response, response, response, response, response, response, response, response, response, response, response
# Import recon functions
from pages.dashboard.recon_users import FindUser, ReconUserMemberships, ReconUserAssignedApps
# Execute recon
user_id, user_upn, user_display_name, user_mail, user_job_title, user_off_location, user_phone = FindUser(user_string)
groups_count, role_count, group_membership, role_assigned = ReconUserMemberships(user_id)
app_assigned_count, user_app_assignments = ReconUserAssignedApps(user_id)
return user_display_name, user_id, user_upn, user_mail, user_job_title, user_off_location, user_phone, groups_count, role_count, group_membership, role_assigned, app_assigned_count, user_app_assignments
'''C017 - Callback to populate Azure access info dynamically based on selected subscription'''
@app.callback(
Output(component_id = "azure-access-info-div", component_property = "children"),
Input(component_id = "interval-to-trigger-initialization-check", component_property = "n_intervals"),
Input(component_id = "azure-subscription-selector-dropdown", component_property = "value"))
def generate_azure_access_info_callback(n_intervals, value):
return generate_azure_access_info(value)
'''C018 - Callback to generate Azure subscription options in Access dropdown'''
@app.callback(
Output(component_id = "azure-subscription-selector-dropdown", component_property = "options"),
Input(component_id = "azure-subscription-selector-dropdown", component_property = "title"))
def generate_azure_sub_dropdown_callback(title):
if title == None:
all_subscriptions = []
for subs in AzureAccess().get_account_available_subscriptions():
selected_value = subs.get("id")
all_subscriptions.append(
{
'label': html.Div(subs.get("name"), className="text-dark"), 'value': selected_value
}
)
return all_subscriptions
'''C019 - Callback to generate attack sequence visualization in Automator'''
@app.callback(
Output("playbook-visualization-container", "children"),
[Input({"type": "playbook-card-click", "index": ALL}, "n_clicks")],
prevent_initial_call=True
)
def update_visualization(n_clicks):
"""Update the visualization when a playbook is selected"""
if not callback_context.triggered:
raise PreventUpdate
# Get the triggered component's ID
triggered = callback_context.triggered[0]
prop_id = json.loads(triggered['prop_id'].rsplit('.',1)[0])
if triggered['value'] is None: # No clicks yet
raise PreventUpdate
playbook_id = prop_id['index']
try:
pb_config = Playbook(playbook_id)
# Return both the visualization and some playbook info
return html.Div([
html.H4(f"Playbook: {pb_config.name}", className="mb-3 text-light"),
html.Div(playbook_viz_generator(pb_config.name), className="mb-3"),
dbc.Card([
dbc.CardBody([
html.H5("Playbook Details", className="card-title"),
html.P(f"Author: {pb_config.author}", className="mb-2"),
html.P(f"Created: {pb_config.creation_date}", className="mb-2"),
html.P(f"Total Steps: {pb_config.steps}", className="mb-2"),
html.P(f"Description: {pb_config.description}", className="mb-0")
])
], className="bg-dark text-light border-secondary")
])
except Exception as e:
return html.Div([
html.H4("Error Loading Visualization", className="text-danger"),
html.P(str(e), className="text-muted")
], className="p-3")
'''C020 - Callback to execute attack sequence in automator view'''
@app.callback(
Output("execution-progress-offcanvas", "is_open", allow_duplicate=True),
Output("app-notification", "is_open", allow_duplicate=True),
Output("app-notification", "children", allow_duplicate=True),
Output("app-error-display-modal", "is_open", allow_duplicate=True),
Output("app-error-display-modal-body", "children", allow_duplicate=True),
Output("selected-playbook-data", "data", allow_duplicate=True),
Output("execution-interval", "disabled", allow_duplicate=True),
Input({'type': 'execute-playbook-button', 'index': ALL}, 'n_clicks'),
prevent_initial_call=True
)
def execute_playbook_callback(n_clicks):
"""Execute playbook and initialize progress tracking"""
if not any(n_clicks):
raise PreventUpdate
ctx = callback_context
if not ctx.triggered:
raise PreventUpdate
# Get clicked playbook
button_id = ctx.triggered[0]['prop_id'].rsplit('.',1)[0]
playbook_file = eval(button_id)['index']
try:
# Execute playbook in background thread
def execute_playbook():
playbook = Playbook(playbook_file)
playbook.execute()
execution_thread = threading.Thread(target=execute_playbook)
execution_thread.daemon = True
execution_thread.start()
return True, True, "Playbook Execution Started", False, "", playbook_file, False
except PlaybookError as e:
error_msg = f"Playbook Execution Failed: {str(e.message)}"
return False, False, "", True, error_msg, None, True
except Exception as e:
error_msg = f"Unexpected Error: {str(e)}"
return False, False, "", True, error_msg, None, True
'''C021 - Callback to open attack scheduler off canvas'''
@app.callback(
Output(component_id = "automator-offcanvas", component_property = "is_open", allow_duplicate= True),
Output(component_id = "automator-offcanvas", component_property = "title", allow_duplicate= True),
Output(component_id = "automator-offcanvas", component_property = "children", allow_duplicate= True),
Output(component_id="selected-playbook-data", component_property="data", allow_duplicate= True),
Input({'type': 'open-schedule-win-playbook-button', 'index': ALL}, 'n_clicks'),
prevent_initial_call=True
)
def toggle_pb_schedule_canvas_callback(n_clicks):
if not any(n_clicks):
raise PreventUpdate
# Find which button was clicked
ctx = callback_context
if not ctx.triggered:
raise PreventUpdate
# Extract playbook name from context
button_id = ctx.triggered[0]['prop_id'].rsplit('.',1)[0]
selected_pb_name = eval(button_id)['index']
return True, html.H3(["Schedule Playbook"]), schedule_pb_div, selected_pb_name
'''C022 - Callback to create new automator schedule'''
@app.callback(
Output(component_id = "app-notification", component_property = "is_open", allow_duplicate=True),
Output(component_id = "app-notification", component_property = "children", allow_duplicate=True),
Output(component_id = "automator-offcanvas", component_property = "is_open", allow_duplicate=True),
State(component_id="selected-playbook-data", component_property="data"),
State(component_id = "set-time-input", component_property = "value"),
State(component_id = "automator-date-range-picker", component_property = "start_date"),
State(component_id = "automator-date-range-picker", component_property = "end_date"),
State(component_id = "schedule-repeat-boolean", component_property = "on"),
State(component_id = "repeat-options-dropdown", component_property = "value"),
State(component_id = "schedule-name-input", component_property = "value"),
Input(component_id = "schedule-playbook-button", component_property = "n_clicks"),
prevent_initial_call=True)
def create_new_schedule_callback(selected_pb_data, execution_time, start_date, end_date, repeat_flag, repeat_frequency, schedule_name, n_clicks):
if n_clicks == 0:
raise PreventUpdate
if selected_pb_data == None:
raise PreventUpdate
playbook_id = selected_pb_data
# Create new schedule
AddNewSchedule(schedule_name, playbook_id, start_date, end_date, execution_time, repeat_flag, repeat_frequency)
# Send notification after new schedule is created and close scheduler off canvas
return True, "Playbook Scheduled", False
'''C023 - Callback to export playbook'''
@app.callback(
Output(component_id = "app-download-sink", component_property = "data", allow_duplicate = True),
Output(component_id = "app-notification", component_property = "is_open", allow_duplicate=True),
Output(component_id = "app-notification", component_property = "children", allow_duplicate=True),
Output(component_id = "app-error-display-modal", component_property = "is_open", allow_duplicate=True),
Output(component_id = "app-error-display-modal-body", component_property = "children", allow_duplicate=True),
State(component_id="selected-playbook-data", component_property="data"),
State(component_id = "export-playbook-mask-param-boolean", component_property = "on"),
State(component_id = "export-playbook-filename-text-input", component_property = "value"),
Input(component_id = "export-playbook-button", component_property = "n_clicks"),
prevent_initial_call=True)
def export_playbook_callback(selected_pb_data, mask_param, export_file_name, n_clicks):
if n_clicks == 0:
raise PreventUpdate
playbook_file = selected_pb_data
playbook = Playbook(playbook_file)
if not export_file_name:
export_file_base_name = "Halberd_Playbook" # Set default file name
export_file_name = export_file_base_name+"-"+(playbook.name).replace(" ", "_")+".yml"
# Export playbook
playbook_export_file_path = playbook.export(export_file = export_file_name, include_params=not(mask_param))
# Download playbook and send app notification
return dcc.send_file(playbook_export_file_path), True, "Playbook Exported", False, ""
'''C024 - Callback to import playbook'''
@app.callback(
Output(component_id = "app-notification", component_property = "is_open", allow_duplicate=True),
Output(component_id = "app-notification", component_property = "children", allow_duplicate=True),
Output(component_id = "app-error-display-modal", component_property = "is_open", allow_duplicate=True),
Output(component_id = "app-error-display-modal-body", component_property = "children", allow_duplicate=True),
Output('playbook-list-container', 'children', allow_duplicate=True),
Output("playbook-stats", "children", allow_duplicate=True),
Input(component_id = 'import-pb-button', component_property = 'n_clicks'),
Input(component_id = 'upload-playbook', component_property = 'contents'),
prevent_initial_call=True)
def import_playbook_callback(n_clicks, file_contents):
if n_clicks == 0:
raise PreventUpdate
if file_contents:
try:
# Import playbook
Playbook.import_playbook(file_contents)
# Refresh the playbook list
playbooks = GetAllPlaybooks()
playbook_items = []
for pb_file in playbooks:
try:
pb_config = Playbook(pb_file)
# Apply search filter if query exists
playbook_items.append(create_playbook_item(pb_config))
except Exception as e:
print(f"Error loading playbook {pb_file}: {str(e)}")
# Generate stats
stats = get_playbook_stats()
stats_text = (f"{stats['total_playbooks']} playbooks loaded • "
f"Last sync: {stats['last_sync'].strftime('%I:%M %p') if stats['last_sync'] else 'never'}")
# Import success - display notification and update playbook list
return True, "Playbook Imported", False, "", playbook_items, stats_text
except Exception as e:
# Display error in modal pop up
return False, "", True, str(e), no_update, no_update
else:
raise PreventUpdate
'''C025 - Callback to add technique as step to playbook'''
@app.callback(
Output(component_id = "app-notification", component_property = "is_open", allow_duplicate=True),
Output(component_id = "app-notification", component_property = "children", allow_duplicate=True),
Output(component_id = "app-error-display-modal", component_property = "is_open", allow_duplicate=True),
Output(component_id = "app-error-display-modal-body", component_property = "children", allow_duplicate=True),
Input(component_id = "confirm-add-to-playbook-modal-button", component_property = "n_clicks"),
Input(component_id = "att-pb-selector-dropdown", component_property = "value"),
State(component_id = "pb-add-step-number-input", component_property = "value"),
State(component_id = "pb-add-step-wait-input", component_property = "value"),
State(component_id = "attack-options-radio", component_property = "value"),
State(component_id = {"type": "technique-config-display", "index": ALL}, component_property = "value"),
State(component_id = {"type": "technique-config-display-boolean-switch", "index": ALL}, component_property = "on"),
State(component_id = {"type": "technique-config-display-file-upload", "index": ALL}, component_property = "contents"),
prevent_initial_call=True
)
def add_technique_to_pb_callback(n_clicks, selected_pb, step_no, wait, t_id, values, bool_on, file_content):
if n_clicks == 0:
raise PreventUpdate
# If config has file as input
if selected_pb:
if file_content:
for pb in GetAllPlaybooks():
pb_config = Playbook(pb)
if pb_config.name == selected_pb:
break
technique_input.append(file_content)
else:
for pb in GetAllPlaybooks():
pb_config = Playbook(pb)
if pb_config.name == selected_pb:
break
# Create technique input
technique = TechniqueRegistry.get_technique(t_id)
technique_params = (technique().get_parameters())
technique_input = {}
file_input = {}
bool_input = {}
i=0
for param in technique_params:
if technique_params[param]['input_field_type'] not in ["bool", "upload"]:
technique_input[param] = [*values][i]
i+=1
elif technique_params[param]['input_field_type'] == "upload":
file_input[param] = technique_params[param]
elif technique_params[param]['input_field_type'] == "bool":
bool_input[param] = technique_params[param]
if file_content:
i = 0
for param in file_input:
technique_input[param] = [*file_content][i]
i+=1
if bool_on:
i = 0
for param in bool_input:
technique_input[param] = [*bool_on][i]
i+=1
# Create playbook step
try:
new_step = PlaybookStep(module=t_id, params=technique_input, wait=wait)
# Add technique to playbook
pb_config.add_step(new_step=new_step, step_no=step_no)
# Save and update with new playbook config
pb_config.save()
return True, "Added to Playbook", False, ""
except Exception as e:
# Display error in error pop-up
return False, "", True, str(e)
else:
# Display error in error pop-up
return False, "", True, "Cannot Add Step : No Playbook Selected"
'''C026 - Callback to open playbook creator off canvas'''
@app.callback(
Output(component_id = "automator-offcanvas", component_property = "is_open", allow_duplicate= True),
Output(component_id = "automator-offcanvas", component_property = "title", allow_duplicate= True),
Output(component_id = "automator-offcanvas", component_property = "children", allow_duplicate= True),
Input(component_id = 'open-creator-win-playbook-button', component_property= 'n_clicks'),
prevent_initial_call=True
)
def toggle_pb_creator_canvas_callback(n_clicks):
if n_clicks:
return True, [html.H3("Create New Playbook")], generate_playbook_creator_offcanvas()
raise PreventUpdate
'''C027 - Callback to create new playbook'''
@app.callback(
Output(component_id = "playbook-creator-modal", component_property = "is_open", allow_duplicate=True),
Output(component_id = "app-notification", component_property = "is_open", allow_duplicate=True),
Output(component_id = "app-notification", component_property = "children", allow_duplicate=True),
Output(component_id = "app-error-display-modal", component_property = "is_open", allow_duplicate=True),
Output(component_id = "app-error-display-modal-body", component_property = "children", allow_duplicate=True),
State(component_id = "pb-name-input", component_property = "value"),
State(component_id = "pb-desc-input", component_property = "value"),
State(component_id = "pb-author-input", component_property = "value"),
State(component_id = "pb-refs-input", component_property = "value"),
Input(component_id = "create-playbook-button", component_property = "n_clicks"), prevent_initial_call=True
)
def create_new_pb_callback(pb_name, pb_desc, pb_author, pb_references, n_clicks):
if n_clicks == 0:
raise PreventUpdate
try:
new_playbook = Playbook.create_new(
name= pb_name,
author= pb_author,
description= pb_desc,
references=[pb_references]
)
return False, True, f"New Playbook Created : {new_playbook.name}", False, ""
except Exception as e:
return True, False, "", True, str(e)
'''C028 - Callback to display technique info from playbook node in modal'''
@app.callback(
Output(component_id = "app-technique-info-display-modal-body", component_property = "children"),
Output(component_id = "app-technique-info-display-modal", component_property = "is_open"),
Input(component_id = "auto-attack-sequence-cytoscape-nodes", component_property = "tapNodeData"),
[State(component_id = "app-technique-info-display-modal", component_property = "is_open")],
prevent_initial_call=True
)
def toggle_t_info_modal_callback(data, is_open):
if data:
# Extract module_id from node label
if data['label'] != "None":
info = data['info']
else:
raise PreventUpdate
if info == "time":
# Display time gap
wait_time = data['label']
return [html.B(f"Time Gap : {wait_time} seconds")], True
else:
# Display module info
pb_step_info = data['info']
step_data = next(iter(pb_step_info.items()))
module_id = step_data[1]['Module']
return generate_technique_info(module_id), not is_open
else:
raise PreventUpdate
'''C029 - Callback to display playbook node data on hover (deprecated)'''
'''C030 - Callback to open/close add to playbook modal on Attack page'''
@app.callback(
Output(component_id = "add-to-playbook-modal", component_property = "is_open"),
[
Input(component_id = "open-add-to-playbook-modal-button", component_property = "n_clicks"),
Input(component_id = "close-add-to-playbook-modal-button", component_property = "n_clicks"),
Input(component_id = "confirm-add-to-playbook-modal-button", component_property = "n_clicks")
],
[State(component_id = "add-to-playbook-modal", component_property = "is_open")],
prevent_initial_call=True
)
def toggle_add_to_pb_modal_callback(n1, n2, n3, is_open):
if n1 or n2 or n3:
return not is_open
return is_open
'''C031 - [Automator] Callback to generate/update playbook list in automator'''
@app.callback(
Output("playbook-list-container", "children"),
Output("playbook-stats", "children"),
Input("playbook-search", "value"),
)
def update_playbook_list_callback(search_query):
"""Update the playbook list and stats based on search query"""
# Get all available playbooks on system
playbooks = GetAllPlaybooks()
# Generate stats
stats = get_playbook_stats()
stats_text = (f"{stats['total_playbooks']} playbooks loaded • "f"Last sync: {stats['last_sync'].strftime('%I:%M %p') if stats['last_sync'] else 'never'}")
# If no playbooks found on system
if not playbooks:
empty_playbook_list_div = html.Div(
children=[
html.Div([
DashIconify(
icon="mdi:information-outline", #Information icon
width=48,
height=48,
className="text-muted mb-3"
),
html.P("Create or Import a playbook", # Default message when no playbook is selected
className="text-muted")
], className="text-center")
],
className="d-flex justify-content-center align-items-center",
style={'padding':'20px'}
)
return empty_playbook_list_div, stats_text
# Initialize list to store playbook items
playbook_items = []
for pb_file in playbooks:
try: