-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathddv-c.py
3080 lines (2932 loc) · 168 KB
/
ddv-c.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
# Install Mac Dependancies
# python3 -m pip install flask
# python3 -m pip install pandas
# python3 -m pip install networkx
# python3 -m pip install plotly
# python3 -m pip install paramiko
# python3 -m pip install scp
# sudo pip3 install -r requirements.txt
#!/usr/bin/env python3
from flask import Flask, request, jsonify, session, g, redirect, url_for, abort, render_template, flash, make_response, Markup, Response, stream_with_context
from datetime import datetime
import pandas as pd
import time, sys, json, requests, pprint, ast, ddv_c_sl_api, random, paramiko, math, difflib, ddv_c_cfg
import networkx as nx
import numpy as np
import matplotlib as plt
import plotly.graph_objects as go
import vtpy as vps
from decimal import Decimal
from scp import SCPClient
from collections import deque, OrderedDict
from ddv_c_cfg import out_list_filename, eut_list_filename, agents_list_filename, tg_v_tasks_list_filename, tg_a_tasks_list_filename # required due to globals() breaking with cfg import
plt.use('agg') # needed to allow flask to keep running while producing images
pp = pprint.PrettyPrinter(indent=5)
app = Flask(__name__)
app.config.from_object(__name__)
app.config.update(dict(SECRET_KEY='development key', USERNAME='admin', PASSWORD='ddv'))
if ddv_c_cfg.vps_apikey != 'NONE':
vps.s.headers.update({"API-Key": ddv_c_cfg.vps_apikey})
else:
print(
'VULTRAPI environment variable not set. Some functions will not work and return error 403.'
)
tg_a_vectors = [
'icmp-flood',
'udp-flood-dst-port-80',
'udp-flood-dst-port-53',
'tcp-syn-flood-dst-port-80',
'ipv4-proto-0',
'chargen-ra-flood-dst-port-80',
'dns-ra-flood-dst-port-80'
]
tg_v_protos = [
'icmp',
'http',
'https',
'dns'
]
@app.route('/ddv_c_settings', methods=['GET', 'POST'])
def ddv_c_settings():
try:
import ddv_c_cfg
if request.method == 'GET':
f_current = open('ddv_c_cfg.py', 'r') # read in config file
f_old = open('ddv_c_cfg_old.py', 'w+')
cfgDict = OrderedDict() # normal dict does not preserve order
for line in f_current:
f_old.write(line) # Create a backup of cfg file
listedline = line.strip().split(' = ') # split around the = sign for Key and Value
if len(listedline) > 1: # we have the = sign in there
commentline = listedline[1].strip().split(' # ') # split around the # sign for Detail (Comments)
cfgDict[listedline[0]] = [commentline[0], commentline[1]] # add Key, Value and Comments to Dict
f_current.close()
f_old.close()
if request.method == 'POST':
cfgDict = OrderedDict() # normal dict does not preserve order
newDict = request.form.to_dict(flat=False) # change from ImmutableMultiDict to Dict
#print(newDict)
for n in range(len(newDict['Key'])): #The POST returns each Table Data Column at a time, need to join them back into Dict again
cfgDict[newDict['Key'][n]] = [newDict['Value'][n], newDict['Description'][n]] # add Key, Value and Comments back to Dict
f_new = open('ddv_c_cfg_new.py', 'w') # write out new config file
for k, v in cfgDict.items():
f_new.write(str(k) + ' = '+ str(v[0]) + ' # ' + str(v[1]) + '\n')
f_new.close()
# record all config setting changes to ddv_c_cfg_changes.txt
diff = difflib.ndiff(open('ddv_c_cfg_new.py').readlines(),open('ddv_c_cfg_old.py').readlines())
f_changes = open('ddv_c_cfg_changes.txt', 'a+')
f_changes.write(datetime.now().strftime("%Y-%m-%d %H:%M:%S") + '\n' + ''.join(diff))
#print ''.join(diff),
f_changes.close()
try: # do error checks on the ddv_c_cfg_new file
import ddv_c_cfg_new # check if there are syntax issues with new ddv_c_cfg_new file, before writing it out to ddv_c_cfg.py
f_new = open('ddv_c_cfg_new.py', 'r') # read in config file
f_current = open('ddv_c_cfg.py', 'w+')
for line in f_new:
f_current.write(line)
except:
flash('There is a syntax error with your updates to the ddv_c_cfg file, recent changes to ddv_c_cfg has NOT been saved', 'flash_red')
return render_template(
"ddv_c_settings.html",
data = {}
)
return render_template(
"ddv_c_settings.html",
data = cfgDict.items()
)
except:
flash('There is a syntax error with the ddv_c_cfg file, please remediate', 'flash_red')
return render_template(
"ddv_c_settings.html",
data = {}
)
@app.route('/ddv_tg_settings', methods=['GET', 'POST'])
def ddv_tg_settings():
try:
my_public_ip = requests.get("https://api.ipify.org/?format=json").json()['ip']
except:
my_public_ip = '255.255.255.255'
try:
if request.method == 'GET':
f_current = open('./ddv-tg-x/ddv_tg_cfg.py', 'r') # read in config file
f_old = open('./ddv-tg-x/ddv_tg_cfg_old.py', 'w+')
cfgDict = OrderedDict() # normal dict does not preserve order
for line in f_current:
f_old.write(line) # Create a backup of cfg file
listedline = line.strip().split(' = ') # split around the = sign for Key and Value
if len(listedline) > 1: # we have the = sign in there
commentline = listedline[1].strip().split(' # ') # split around the # sign for Detail (Comments)
cfgDict[listedline[0]] = [commentline[0], commentline[1]] # add Key, Value and Comments to Dict
f_current.close()
f_old.close()
if request.method == 'POST':
cfgDict = OrderedDict() # normal dict does not preserve order
newDict = request.form.to_dict(flat=False) # change from ImmutableMultiDict to Dict
#print(newDict)
for n in range(len(newDict['Key'])): #The POST returns each Table Data Column at a time, need to join them back into Dict again
cfgDict[newDict['Key'][n]] = [newDict['Value'][n], newDict['Description'][n]] # add Key, Value and Comments back to Dict
f_new = open('./ddv-tg-x/ddv_tg_cfg_new.py', 'w') # write out new config file
for k, v in cfgDict.items():
f_new.write(str(k) + ' = '+ str(v[0]) + ' # ' + str(v[1]) + '\n')
f_new.close()
# record all config setting changes to ddv_tg_cfg_changes.txt
diff = difflib.ndiff(open('./ddv-tg-x/ddv_tg_cfg_new.py').readlines(),open('./ddv-tg-x/ddv_tg_cfg_old.py').readlines())
f_changes = open('./ddv-tg-x/ddv_tg_cfg_changes.txt', 'a+')
f_changes.write(datetime.now().strftime("%Y-%m-%d %H:%M:%S") + '\n' + ''.join(diff))
#print ''.join(diff),
f_changes.close()
try: # do error checks on the ddv_tg_cfg_new file
f_new = open('./ddv-tg-x/ddv_tg_cfg_new.py', 'r') # read in config file
f_current = open('./ddv-tg-x/ddv_tg_cfg.py', 'w+')
for line in f_new:
f_current.write(line)
except:
flash('There is a syntax error with your updates to the ddv_tg_cfg file, recent changes to ddv_tg_cfg has NOT been saved', 'flash_red')
return render_template(
"ddv_tg_settings.html",
data = {}
)
return render_template(
"ddv_tg_settings.html",
data = cfgDict.items(),
my_public_ip = my_public_ip
)
except:
flash('There is a syntax error with the ddv_tg_cfg file, please remediate', 'flash_red')
return render_template(
"ddv_tg_settings.html",
data = {}
)
def get_out():
try:
out_list_df = pd.read_csv(ddv_c_cfg.out_list_filename, names=[
'out_enrollment_id',
'out_companyname',
'out_contactname',
'out_contactemail',
'out_contactnumber',
'out_industry',
'out_sl_ip',
'out_sl_api',
'out_enrollment_date'
], dtype={'out_contactnumber': str}, header=None)
out_list_df.set_index('out_enrollment_id', inplace=True)
return out_list_df
except:
out_list_df = pd.DataFrame([['empty']], index=['error'], columns=['out_companyname'])
return out_list_df
def get_eut():
try:
eut_list_df = pd.read_csv(ddv_c_cfg.eut_list_filename, names=[
'eut_enrollment_id',
'eut_shortname',
'eut_dst_ip',
'eut_companyname',
'eut_companyname_id',
'eut_enrollment_date'
], dtype={'eut_companyname_id': str}, header=None)
eut_list_df.set_index('eut_enrollment_id', inplace=True)
return eut_list_df
except:
eut_list_df = pd.DataFrame([['empty']], index=['error'], columns=['eut_shortname'])
return eut_list_df
def get_agents():
try:
agent_list_df = pd.read_csv(ddv_c_cfg.agents_list_filename, names=[
'agent_enrollment_id',
'agent_hostname',
'agent_ip',
'agent_port',
'agent_location',
'agent_description',
'agent_role',
'agent_local_api_key',
'agent_remote_api_key',
'agent_enrollment_date'
], dtype={'agent_local_api_key': str,'agent_remote_api_key': str}, header=None)
agent_list_df.set_index('agent_enrollment_id', inplace=True)
return agent_list_df
except:
agent_list_df = pd.DataFrame([['empty']], index=['error'], columns=['agent_role'])
return agent_list_df
def get_tg_v_tasks():
try:
tg_v_list_df = pd.read_csv(ddv_c_cfg.tg_v_tasks_list_filename, names=[
'tg_v_enrollment_id',
'tg_v_eut',
'tg_v_eut_id',
'tg_v_host',
'tg_v_host_id',
'tg_v_src_ip',
'tg_v_dst_ip',
'tg_v_dst_proto',
'tg_v_pps',
'tg_v_dur',
'tg_v_p_cnt',
'tg_v_p_int',
'tg_v_description',
'tg_v_enrollment_date',
'tg_v_status'
], dtype={'tg_v_host_id': str,'tg_v_p_cnt': str}, header=None)
tg_v_list_df.set_index('tg_v_enrollment_id', inplace=True)
return tg_v_list_df
except:
tg_v_list_df = pd.DataFrame([['empty']], index=['error'], columns=['error'])
return tg_v_list_df
def get_tg_a_tasks():
try:
tg_a_list_df = pd.read_csv(ddv_c_cfg.tg_a_tasks_list_filename, names=[
'tg_a_enrollment_id',
'tg_a_eut',
'tg_a_eut_id',
'tg_a_host',
'tg_a_host_id',
'tg_a_src_ip',
'tg_a_dst_ip',
'tg_a_dst_vector',
'tg_a_pps',
'tg_a_dur',
'tg_a_p_cnt',
'tg_a_p_int',
'tg_a_description',
'tg_a_enrollment_date',
'tg_a_status'
], dtype={'tg_a_host_id': str,'tg_a_p_cnt': str}, header=None)
tg_a_list_df.set_index('tg_a_enrollment_id', inplace=True)
return tg_a_list_df
except:
tg_a_list_df = pd.DataFrame([['empty']], index=['error'], columns=['error'])
return tg_a_list_df
def get_alert_mit_details():
try:
amd_list_df = pd.read_csv(ddv_c_sl_api.sl_ddv_mo_alert_list_filename, names=[
'alert_gid',
'mo_gid',
'mo_name',
'alert_class',
'alert_type',
'alert_importance',
'alert_ongoing',
'start_time',
'host_address',
'impact_bps',
'impact_pps',
'misuse_types',
'mitigation_data',
'source_prefixes'
], header=None)
amd_list_df.set_index('alert_gid', inplace=True)
return amd_list_df
except:
amd_list_df = pd.DataFrame([['empty']], index=['error'], columns=['out_companyname'])
return amd_list_df
def edit_df(ddv_df, row_indexer, col_indexer, new_value):
# ddv_df can be out, eut, agents, tg_v_tasks, tg_a_tasks
df = globals()['get_' + ddv_df]() # construct the function to run from var input, and get df
df.loc[row_indexer, col_indexer] = new_value # change value in df
df.to_csv(globals()[ddv_df + '_list_filename'], mode='w', header=False) # overwrite new df to old csv
@app.route('/', methods=['GET'])
def ddv_landing_page():
return render_template('index.html')
@app.route('/alert_lookup/<mo_gid>', methods=['GET'])
def alert_lookup(mo_gid):
ddv_c_sl_api.sl_dos_alert_search(mo_gid)
@app.route('/agents_status', methods=['GET'])
def agents_status():
try:
agent_list_df = get_agents()
agents_status = []
for uuid in agent_list_df.index:
agent_enrollment_id = uuid
agent_hostname = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_hostname'].values[0])
agent_ip = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_ip'].values[0])
agent_port = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_port'].values[0])
agent_location = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_location'].values[0])
agent_description = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_description'].values[0])
agent_role = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_role'].values[0])
agent_enrollment_date = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_enrollment_date'].values[0])
url = 'https://' + str(agent_ip) + ':' + str(agent_port)+ '/ddv_tg_x_keepalive'
#print url
try:
task_resp = requests.get(url, verify=False, timeout=ddv_c_cfg.agent_timeout)
if task_resp.ok:
#return task_resp.json()
#print task_resp.json()
if task_resp.json().get('action') == 'success':
agent_health_response = task_resp.json().get('health')
agent_tasks_response = task_resp.json().get('tasks')
try:
if agent_tasks_response[0]['index'] == 'error':
agent_tasks_response = []
else:
pass
except:
pass
session['remote_agent_alive'] = True
#flash('DDV-C: ' + str(agent_hostname) + ': ' + str(task_resp.json().get('health')), 'flash_green') # success message from remote agent
else:
pass
else:
agent_health_response = 'offline'
agent_tasks_response = []
except:
flash('DDV-C: There was a problem connecting to the Remote Agent: ' + str(agent_hostname), 'flash_red')
session['remote_agent_alive'] = False
agent_health_response = 'offline'
agent_tasks_response = []
agents_status_entry = {
#'agent_enrollment_id': agent_enrollment_id,
'agent_hostname': agent_hostname,
'agent_ip': agent_ip,
'agent_port': agent_port,
'agent_location': agent_location,
'agent_description': agent_description,
'agent_role': agent_role,
'agent_enrollment_date': agent_enrollment_date,
'agent_health': str(agent_health_response) + ' (' + str(len(agent_tasks_response)) + ' tasks)',
'edit': agent_enrollment_id,
'delete': agent_enrollment_id,
'push': agent_enrollment_id
}
agents_status.append(agents_status_entry)
#print agents_status
agents_status_df = pd.DataFrame.from_dict(agents_status)
# Reorder columns back to original ordering
agents_status_df = agents_status_df[[
#'agent_enrollment_id',
'agent_hostname',
'agent_ip',
'agent_port',
'agent_location',
'agent_description',
'agent_role',
'agent_enrollment_date',
'agent_health',
'edit',
'delete',
'push'
]]
return render_template(
"list_agents_status.html",
column_names=agents_status_df.columns.values,
row_data=list(agents_status_df.values.tolist()),
edit_link_column="edit",
delete_link_column="delete",
push_link_column="push",
zip=zip
)
except:
flash('No DDV-TG-x Agents Configured as yet. Please Configure Agents...', 'flash_red')
return redirect(url_for('enroll_agents'))
@app.route('/agent_lookup/<uuid>', methods=['GET'])
def agent_lookup(uuid):
try:
agent_list_df = get_agents()
agent_enrollment_id = uuid
agent_hostname = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_hostname'].values[0])
agent_ip = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_ip'].values[0])
agent_port = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_port'].values[0])
agent_location = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_location'].values[0])
agent_description = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_description'].values[0])
agent_role = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_role'].values[0])
agent_enrollment_date = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_enrollment_date'].values[0])
return {
'agent_enrollment_id': agent_enrollment_id,
'agent_hostname': agent_hostname,
'agent_ip': agent_ip,
'agent_port': agent_port,
'agent_location': agent_location,
'agent_description': agent_description,
'agent_role': agent_role,
'agent_enrollment_date': agent_enrollment_date
}
except:
return {
'error': 'invalid uuid',
'agent_enrollment_id': 0
}
@app.route('/remote_agent_enroll_push', methods=['GET', 'POST'])
def remote_agent_enroll_push():
agent_list_df = get_agents()
error = None
try:
agent_names = agent_list_df.agent_hostname
except:
return redirect(url_for('enroll_agents'))
if request.method == 'POST':
uuid = agent_list_df[agent_list_df['agent_hostname'] == request.form['agent_hostname']].index.values[0]
if request.method == 'GET':
try: #Landing directly in push page, with GET, results in no uuid, hence needs exception
uuid = int(request.args.get('push_agent_uuid'))
except:
pass
try:
agent_enrollment_id = uuid
agent_hostname = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_hostname'].values[0])
agent_ip = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_ip'].values[0])
agent_port = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_port'].values[0])
agent_location = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_location'].values[0])
agent_description = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_description'].values[0])
agent_role = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_role'].values[0])
agent_local_api_key = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_local_api_key'].values[0])
agent_remote_api_key = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_remote_api_key'].values[0])
agent_enrollment_date = str(agent_list_df[agent_list_df.index == int(uuid)]['agent_enrollment_date'].values[0])
enroll_data = {
'agent_enrollment_id': agent_enrollment_id,
'agent_hostname': agent_hostname,
'agent_ip': agent_ip,
'agent_port': agent_port,
'agent_location': agent_location,
'agent_description': agent_description,
'agent_role': agent_role,
'agent_local_api_key': agent_local_api_key,
'agent_remote_api_key': agent_remote_api_key,
'agent_enrollment_date': agent_enrollment_date
}
enroll_agent_entry(enroll_data)
except:
pass
agent_list_df = get_agents()
agent_names = agent_list_df.agent_hostname
return render_template('remote_agent_enroll_push.html', error=error, agent_names=agent_names, data=agent_list_df.to_html())
@app.route('/remote_tg_v_task_push', methods=['GET', 'POST'])
def remote_tg_v_task_push():
tg_v_tasks_entries = get_tg_v_tasks()
tg_v_names = tg_v_tasks_entries.reset_index().to_dict('records') # pass whole dataframe as 'list of dicts' to render template select list
agent_entries = get_agents()
error = None
if request.method == 'POST':
try:
uuid = int(request.form['tg_v_enrollment_id'])
except:
return redirect(url_for('enroll_tg_v_tasks'))
if request.method == 'GET':
try: #Landing directly in push page, with GET, results in no uuid, hence needs exception
uuid = int(request.args.get('push_tg_v_task_uuid'))
except:
pass
try:
tg_v_enrollment_id = uuid
tg_v_eut = str(tg_v_tasks_entries[tg_v_tasks_entries.index == int(uuid)]['tg_v_eut'].values[0])
tg_v_eut_id = str(tg_v_tasks_entries[tg_v_tasks_entries.index == int(uuid)]['tg_v_eut_id'].values[0])
tg_v_host = str(tg_v_tasks_entries[tg_v_tasks_entries.index == int(uuid)]['tg_v_host'].values[0])
tg_v_host_id = str(tg_v_tasks_entries[tg_v_tasks_entries.index == int(uuid)]['tg_v_host_id'].values[0])
tg_v_host_ip = str(agent_entries[agent_entries.index == int(tg_v_host_id)]['agent_ip'].values[0])
tg_v_host_port = str(agent_entries[agent_entries.index == int(tg_v_host_id)]['agent_port'].values[0])
tg_v_src_ip = str(tg_v_tasks_entries[tg_v_tasks_entries.index == int(uuid)]['tg_v_src_ip'].values[0])
tg_v_dst_ip = str(tg_v_tasks_entries[tg_v_tasks_entries.index == int(uuid)]['tg_v_dst_ip'].values[0])
tg_v_dst_proto = str(tg_v_tasks_entries[tg_v_tasks_entries.index == int(uuid)]['tg_v_dst_proto'].values[0])
tg_v_pps = str(tg_v_tasks_entries[tg_v_tasks_entries.index == int(uuid)]['tg_v_pps'].values[0])
tg_v_dur = str(tg_v_tasks_entries[tg_v_tasks_entries.index == int(uuid)]['tg_v_dur'].values[0])
tg_v_p_cnt = str(tg_v_tasks_entries[tg_v_tasks_entries.index == int(uuid)]['tg_v_p_cnt'].values[0])
tg_v_p_int = str(tg_v_tasks_entries[tg_v_tasks_entries.index == int(uuid)]['tg_v_p_int'].values[0])
tg_v_description = str(tg_v_tasks_entries[tg_v_tasks_entries.index == int(uuid)]['tg_v_description'].values[0])
tg_v_enrollment_date = str(tg_v_tasks_entries[tg_v_tasks_entries.index == int(uuid)]['tg_v_enrollment_date'].values[0])
tg_v_status = str(tg_v_tasks_entries[tg_v_tasks_entries.index == int(uuid)]['tg_v_status'].values[0])
task_data = {
'tg_v_enrollment_id': tg_v_enrollment_id,
'tg_v_eut': tg_v_eut,
'tg_v_eut_id': tg_v_eut_id,
'tg_v_host': tg_v_host,
'tg_v_host_id': tg_v_host_id,
'tg_v_host_ip': tg_v_host_ip,
'tg_v_src_ip': tg_v_src_ip,
'tg_v_dst_ip': tg_v_dst_ip,
'tg_v_dst_proto': tg_v_dst_proto,
'tg_v_pps': tg_v_pps,
'tg_v_dur': tg_v_dur,
'tg_v_p_cnt': tg_v_p_cnt,
'tg_v_p_int': tg_v_p_int,
'tg_v_description': tg_v_description,
'tg_v_enrollment_date': tg_v_enrollment_date,
'tg_v_status': tg_v_status
}
#task_data = json.dumps(task_data)
#header = {
# "X-DDV-APIToken":tg_v_local_api_key,
# "Content-Type": "application/json"
#}
#print task_data
url = 'https://' + str(tg_v_host_ip) + ':' + str(tg_v_host_port)+ '/remote_tg_v_task_push/' + str(tg_v_enrollment_id)
#print url
try:
task_resp = requests.post(url, verify=False, json=task_data)
if task_resp.ok:
#return task_resp.json()
#print task_resp.json()
if task_resp.json().get('enrollment') == 'failed':
flash(task_resp.json().get('error'), 'flash_red')
session['remote_task_enrolled'] = False
elif task_resp.json().get('enrollment') == 'success':
session['remote_task_enrolled'] = True
flash(task_resp.json().get('message'), 'flash_green')
else:
pass
else:
pass
except:
flash('DDV-C: There was a problem connecting to the Remote Agent', 'flash_red')
tg_v_tasks_entries = get_tg_v_tasks()
tg_v_names = tg_v_tasks_entries.reset_index().to_dict('records')
except:
pass
return render_template('remote_tg_v_task_push.html',
error=error,
tg_v_names=tg_v_names,
data=tg_v_tasks_entries.to_html())
@app.route('/remote_tg_a_task_push', methods=['GET', 'POST'])
def remote_tg_a_task_push():
tg_a_tasks_entries = get_tg_a_tasks()
tg_a_names = tg_a_tasks_entries.reset_index().to_dict('records') # pass whole dataframe as 'list of dicts' to render template select list
agent_entries = get_agents()
error = None
if request.method == 'POST':
try:
uuid = int(request.form['tg_a_enrollment_id'])
except:
return redirect(url_for('enroll_tg_a_tasks'))
if request.method == 'GET':
try: #Landing directly in push page, with GET, results in no uuid, hence needs exception
uuid = int(request.args.get('push_tg_a_task_uuid'))
except:
pass
try:
tg_a_enrollment_id = uuid
tg_a_eut = str(tg_a_tasks_entries[tg_a_tasks_entries.index == int(uuid)]['tg_a_eut'].values[0])
tg_a_eut_id = str(tg_a_tasks_entries[tg_a_tasks_entries.index == int(uuid)]['tg_a_eut_id'].values[0])
tg_a_host = str(tg_a_tasks_entries[tg_a_tasks_entries.index == int(uuid)]['tg_a_host'].values[0])
tg_a_host_id = str(tg_a_tasks_entries[tg_a_tasks_entries.index == int(uuid)]['tg_a_host_id'].values[0])
try:
tg_a_host_ip = str(agent_entries[agent_entries.index == int(tg_a_host_id)]['agent_ip'].values[0])
tg_a_host_port = str(agent_entries[agent_entries.index == int(tg_a_host_id)]['agent_port'].values[0])
except:
error = 'DDV-C: Remote Agent, ' + str(tg_a_host) + ', no longer exists'
return render_template('remote_tg_a_task_push.html',
error=error,
tg_a_names=tg_a_names,
data=tg_a_tasks_entries.to_html())
tg_a_src_ip = str(tg_a_tasks_entries[tg_a_tasks_entries.index == int(uuid)]['tg_a_src_ip'].values[0])
tg_a_dst_ip = str(tg_a_tasks_entries[tg_a_tasks_entries.index == int(uuid)]['tg_a_dst_ip'].values[0])
tg_a_dst_vector = str(tg_a_tasks_entries[tg_a_tasks_entries.index == int(uuid)]['tg_a_dst_vector'].values[0])
tg_a_pps = str(tg_a_tasks_entries[tg_a_tasks_entries.index == int(uuid)]['tg_a_pps'].values[0])
tg_a_dur = str(tg_a_tasks_entries[tg_a_tasks_entries.index == int(uuid)]['tg_a_dur'].values[0])
tg_a_p_cnt = str(tg_a_tasks_entries[tg_a_tasks_entries.index == int(uuid)]['tg_a_p_cnt'].values[0])
tg_a_p_int = str(tg_a_tasks_entries[tg_a_tasks_entries.index == int(uuid)]['tg_a_p_int'].values[0])
tg_a_description = str(tg_a_tasks_entries[tg_a_tasks_entries.index == int(uuid)]['tg_a_description'].values[0])
tg_a_enrollment_date = str(tg_a_tasks_entries[tg_a_tasks_entries.index == int(uuid)]['tg_a_enrollment_date'].values[0])
tg_a_status = str(tg_a_tasks_entries[tg_a_tasks_entries.index == int(uuid)]['tg_a_status'].values[0])
task_data = {
'tg_a_enrollment_id': tg_a_enrollment_id,
'tg_a_eut': tg_a_eut,
'tg_a_eut_id': tg_a_eut_id,
'tg_a_host': tg_a_host,
'tg_a_host_id': tg_a_host_id,
'tg_a_host_ip': tg_a_host_ip,
'tg_a_src_ip': tg_a_src_ip,
'tg_a_dst_ip': tg_a_dst_ip,
'tg_a_dst_vector': tg_a_dst_vector,
'tg_a_pps': tg_a_pps,
'tg_a_dur': tg_a_dur,
'tg_a_p_cnt': tg_a_p_cnt,
'tg_a_p_int': tg_a_p_int,
'tg_a_description': tg_a_description,
'tg_a_enrollment_date': tg_a_enrollment_date,
'tg_a_status': tg_a_status
}
#task_data = json.dumps(task_data)
#header = {
# "X-DDV-APIToken":tg_a_local_api_key,
# "Content-Type": "application/json"
#}
#print task_data
url = 'https://' + str(tg_a_host_ip) + ':' + str(tg_a_host_port)+ '/remote_tg_a_task_push/' + str(tg_a_enrollment_id)
#print url
try:
task_resp = requests.post(url, verify=False, json=task_data)
if task_resp.ok:
#return task_resp.json()
#print task_resp.json()
if task_resp.json().get('enrollment') == 'failed':
flash(task_resp.json().get('error'), 'flash_red')
session['remote_task_enrolled'] = False
elif task_resp.json().get('enrollment') == 'success':
session['remote_task_enrolled'] = True
flash(task_resp.json().get('message'), 'flash_green')
else:
pass
else:
pass
except:
flash('DDV-C: There was a problem connecting to the Remote Agent, ' + str(tg_a_host), 'flash_red')
tg_a_tasks_entries = get_tg_a_tasks()
tg_a_names = tg_a_tasks_entries.reset_index().to_dict('records')
except:
pass
return render_template('remote_tg_a_task_push.html',
error=error,
tg_a_names=tg_a_names,
data=tg_a_tasks_entries.to_html())
@app.route('/device_keepalive', methods=['POST'])
def device_keepalive():
try:
content = request.json
ka_uuid = content['unique_id']
ka_enroll_id = content['enroll_id']
device_list_df = pd.read_csv(device_list_filename, names=['enroll_id', 'uuid', 'device_info', 'first_seen', 'last_seen'], header=None)
device_list_df.set_index('enroll_id', inplace=True)
device_list_df.ix[device_list_df[device_list_df['uuid'] == ka_uuid].index[0], 'last_seen'] = datetime.now()
#print device_list_df
device_list_df.to_csv(device_list_filename, mode='w', header=False, columns=['uuid', 'device_info', 'first_seen', 'last_seen'])
return jsonify(
{'ka_enroll_id': ka_enroll_id,
'ka_uuid': ka_uuid
}
)
except:
return 0
@app.route('/stream_content')
def stream_content():
def file_reader(filename):
previous_file = 0
while True:
try:
time.sleep(1)
current_file = len(open(filename).readlines( ))
#print(previous_file, current_file, (int(current_file) - int(previous_file)))
for entry in deque(open(filename), (int(current_file) - int(previous_file))):
yield str(entry) + '<br/>\n'
previous_file = current_file
except:
pass
return Response(stream_with_context(file_reader('scroller_log')), mimetype='text/html')
@app.route('/stream')
def stream():
return render_template('scroller.html')
def stream_logger(line):
f = open('scroller_log', 'a+')
f.write(line + '\n')
f.close()
def stream_logger_clear():
f = open('scroller_log', 'w+')
f.close()
@app.route('/stream_test')
def stream_test():
f = open('scroller_log', 'w+')
f.close()
for i in range(10):
j = math.sqrt(i)
time.sleep(1)
# this value should be inserted into file
stream_logger(str(i))
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('You were logged in', 'flash_blue')
return redirect(url_for('out_status'))
return render_template('login.html', error=error)
@app.route('/manage_vps_agents', methods=['GET', 'POST'])
def manage_vps_agents():
error = None
try:
vps_servers = dict(vps.serverlist())
except:
error = 'DDV-C: VPS API or Connection not configured'
vps_servers = {}
if request.method == 'POST':
try:
if int(request.form['vps_qty']) > 0:
#print(request.form['vps_qty'])
new_vps_list = vps_tg_x_provision(int(request.form['vps_qty']))
vps_tg_x_configure(new_vps_list)
vps_servers = dict(vps.serverlist()) # get fresh list of servers after provisioning
except:
pass
try:
if request.form['vps_destroy'] == 'Yes':
#print(request.form['vps_destroy'])
vps_tg_x_kill_all()
vps_servers = dict(vps.serverlist()) # get fresh list of servers after deletion
else:
#print(request.form['vps_destroy'])
pass
except:
pass
if request.method == 'GET':
try:
vps_servers = dict(vps.serverlist())
except:
error = 'DDV-C: VULTR VPS API not configured correctly. Generate API Key from www.vultr.com'
return render_template('manage_vps_agents.html', error=error, data=vps_servers.values())
@app.route('/list_agents', methods=['GET'])
def list_agents():
agent_entries = get_agents()
return render_template('list_agents.html', data=agent_entries.to_html())
# return render_template('list_agents.html', tables=[agent_entries.to_html(classes='agents')],
# titles = ['Configured Agents'])
@app.route('/enroll_agents', methods=['GET', 'POST'])
def enroll_agents():
port_role_map = { 'V' : ddv_c_cfg.ddv_tg_v_port, 'A' : ddv_c_cfg.ddv_tg_a_port}
agent_entries = get_agents()
error = None
if request.method == 'POST':
# if request.form['username'] != app.config['USERNAME']:
# error = 'Invalid username'
# elif request.form['password'] != app.config['PASSWORD']:
# error = 'Invalid password'
# else:
agent_list_entry = {
'agent_enrollment_id': int(time.time()),
'agent_hostname': request.form['agent_hostname'],
'agent_ip': request.form['agent_ip'],
'agent_port': port_role_map[request.form['agent_role']],
'agent_location': request.form['agent_location'],
'agent_description': request.form['agent_description'],
'agent_role': request.form['agent_role'],
'agent_local_api_key': request.form['agent_local_api_key'],
'agent_remote_api_key': request.form['agent_remote_api_key'],
'agent_enrollment_date': str(datetime.now())
}
#print agent_list_entry
enroll_agent_entry(agent_list_entry)
agent_entries = get_agents()
return render_template('enroll_agents.html', error=error, data=agent_entries.to_html())
def enroll_vps_agents(vps_list):
port_role_map = { 'V' : ddv_c_cfg.ddv_tg_v_port, 'A' : ddv_c_cfg.ddv_tg_a_port}
for vps_server in vps_list:
agent_list_entry_a = {
'agent_enrollment_id': '99' + str(vps_server['SUBID']) + '99', # if int(uuid) starts and ends with 99, it's an A
'agent_hostname': str('VPS-' + str(vps_server['location']) + '-' + str(vps_server['SUBID']) + '-A'),
'agent_ip': str(vps_server['main_ip']),
'agent_port': port_role_map['A'],
'agent_location': str(vps_server['location']),
'agent_description': str(vps_server['tag']),
'agent_role': 'A',
'agent_local_api_key': '',
'agent_remote_api_key': '',
'agent_enrollment_date': str(datetime.now())
}
agent_list_entry_v = {
'agent_enrollment_id': '88' + str(vps_server['SUBID']) + '88', # if int(uuid) starts and ends with 88, it's a V
'agent_hostname': str('VPS-' + str(vps_server['location']) + '-' + str(vps_server['SUBID']) + '-V'),
'agent_ip': str(vps_server['main_ip']),
'agent_port': port_role_map['V'],
'agent_location': str(vps_server['location']),
'agent_description': str(vps_server['tag']),
'agent_role': 'V',
'agent_local_api_key': '',
'agent_remote_api_key': '',
'agent_enrollment_date': str(datetime.now())
}
# Add new VPS server as Attacker Role
enroll_agent_entry(agent_list_entry_a)
# Add new VPS server as Verifier Role
enroll_agent_entry(agent_list_entry_v)
def enroll_agent_entry(agent_list_entry):
agent_list = []
agent_list.append(agent_list_entry)
agent_list_df = pd.DataFrame.from_dict(agent_list)
agent_list_df.set_index('agent_enrollment_id', inplace=True)
#print agent_lookup(agent_list_entry['agent_enrollment_id'])
try: # if the entry exists already, don't append a new entry (which will result in duplicates)
if int(agent_lookup(agent_list_entry['agent_enrollment_id'])['agent_enrollment_id']) == 0:
agent_list_df.to_csv(ddv_c_cfg.agents_list_filename, mode='a', header=False, columns=[
#'agent_enrollment_id',
'agent_hostname',
'agent_ip',
'agent_port',
'agent_location',
'agent_description',
'agent_role',
'agent_local_api_key',
'agent_remote_api_key',
'agent_enrollment_date'
])
else:
pass
except:
pass
session['new_agent_enrolled'] = True
flash('DDV-C: New Agent Enrolled', 'flash_green')
# Once new Agent is Enrolled, try and enroll remote agent
header = {
"X-DDV-APIToken": agent_list_df['agent_local_api_key'],
"Content-Type": "application/json"
}
# Connect to Remote Agent and Configure it
url = 'https://' + str(agent_list_entry['agent_ip']) + ':' + str(agent_list_entry['agent_port'])+ '/remote_agent_enroll/' + str(agent_list_entry['agent_enrollment_id'])
#print url
try:
enroll_resp = requests.post(url, verify=False, json=agent_list_entry, timeout=ddv_c_cfg.agent_timeout)
if enroll_resp.ok:
#return enroll_resp.json()
#print enroll_resp.json()
if enroll_resp.json().get('enrollment') == 'failed':
flash(enroll_resp.json().get('error'), 'flash_red')
session['remote_agent_enrolled'] = False
elif enroll_resp.json().get('enrollment') == 'success':
session['remote_agent_enrolled'] = True
flash('DDV-C: ' + str(enroll_resp.json().get('agent_hostname')) + ' successfully enrolled', 'flash_green')
else:
pass
else:
pass
except:
flash('DDV-C: Connection to Remote Agent Timed-Out', 'flash_red')
def delete_vps_agents(vps_uuids):
for vps_id in vps_uuids:
# Delete both the Attacker and Verifier roles in one go
try:
agent_entries = get_agents()
del_agent_ip = agent_entries[agent_entries.index == vps_id]['agent_ip'].values[0]
del_agent_port = agent_entries[agent_entries.index == vps_id]['agent_port'].values[0]
delete_agent_entry(agent_entries, vps_id, del_agent_ip, del_agent_port)
except:
pass
@app.route('/delete_agents', methods=['GET', 'POST'])
def delete_agents():
error = None
agent_entries = get_agents()
try:
agent_names = agent_entries.agent_hostname
except:
return redirect(url_for('enroll_agents'))
if request.method == 'GET':
try:
uuid = int(request.args.get('delete_agent_uuid')) # https://127.0.0.1:2020/delete_agents?delete_agent_uuid=1594133309
if (int(str(uuid)[:2]) and int(str(uuid)[-2:]) == 99 or int(str(uuid)[:2]) and int(str(uuid)[-2:]) == 88): #VPS Specific tasks
vps_subid = int(str(uuid)[2:][:-2]) # find id between the 99 or 88 identifiers
vps_uuids = [int('99' + str(vps_subid) + '99'), int('88' + str(vps_subid) + '88')]
delete_vps_agents(vps_uuids)
# Destroy VPS next
vps.kill([str(vps_subid)])
flash('DDV-C: VPS server, ' + str(vps_subid) + ' destroyed', 'flash_green')
agent_entries = get_agents()
agent_names = agent_entries.agent_hostname
else:
del_agent_ip = agent_entries[agent_entries.index == uuid]['agent_ip'].values[0]
del_agent_port = agent_entries[agent_entries.index == uuid]['agent_port'].values[0]
delete_agent_entry(agent_entries, uuid, del_agent_ip, del_agent_port)
agent_entries = get_agents()
agent_names = agent_entries.agent_hostname
return render_template('delete_agents.html', error=error, agent_names=agent_names, data=agent_entries.to_html())
except:
pass
if request.method == 'POST':
uuid = agent_entries[agent_entries['agent_hostname'] == request.form['agent_hostname']].index.values[0]
if (int(str(uuid)[:2]) and int(str(uuid)[-2:]) == 99 or int(str(uuid)[:2]) and int(str(uuid)[-2:]) == 88): #VPS Specific tasks
vps_subid = int(str(uuid)[2:][:-2]) # find id between the 99 or 88 identifiers
vps_uuids = [int('99' + str(vps_subid) + '99'), int('88' + str(vps_subid) + '88')]
delete_vps_agents(vps_uuids)
# Destroy VPS next
vps.kill([str(vps_subid)])
flash('DDV-C: VPS server, ' + str(vps_subid) + ' destroyed', 'flash_green')
agent_entries = get_agents()
agent_names = agent_entries.agent_hostname
else:
del_agent_ip = agent_entries[agent_entries.index == uuid]['agent_ip'].values[0]
del_agent_port = agent_entries[agent_entries.index == uuid]['agent_port'].values[0]
delete_agent_entry(agent_entries, uuid, del_agent_ip, del_agent_port)
agent_entries = get_agents()
agent_names = agent_entries.agent_hostname
return render_template('delete_agents.html', error=error, agent_names=agent_names, data=agent_entries.to_html())
def delete_agent_entry(agent_entries, uuid, del_agent_ip, del_agent_port):
# 1. Before removing the agent, find and delete all associated agent tasks
# 1a. Find and delete all Attack Tasks
tg_a_task_entries = get_tg_a_tasks()
for task_entry in tg_a_task_entries[tg_a_task_entries['tg_a_host_id'] == str(uuid)].index.values:
try:
tg_a_task_entries = get_tg_a_tasks() # get fresh task list after each recursive deletion of task
if delete_tg_a_task_entry(task_entry) == 'success':
pass
else:
pass
#flash('DDV-C: ' + str(uuid) + ' task could not be deleted', 'flash_red')
except:
flash('DDV-C: No more tasks to be deleted', 'flash_red')
# 1b. Find and delete all Verifier Tasks
tg_v_task_entries = get_tg_v_tasks()
for task_entry in tg_v_task_entries[tg_v_task_entries['tg_v_host_id'] == str(uuid)].index.values:
try:
tg_v_task_entries = get_tg_v_tasks() # get fresh task list after each recursive deletion of task
if delete_tg_v_task_entry(task_entry) == 'success':
pass
else:
pass
#flash('DDV-C: ' + str(uuid) + ' task could not be deleted', 'flash_red')
except:
flash('DDV-C: No more tasks to be deleted', 'flash_red')
# 2. Delete agent after deleting all associated tasks
agent_entries.drop(index=int(uuid)).to_csv(ddv_c_cfg.agents_list_filename, mode='w', header=False, columns=[
#'agent_enrollment_id',
'agent_hostname',
'agent_ip',
'agent_port',
'agent_location',
'agent_description',
'agent_role',
'agent_local_api_key',
'agent_remote_api_key',
'agent_enrollment_date'
])
session['agent_deleted'] = True