-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathapp.py
2089 lines (1794 loc) · 74.1 KB
/
app.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
from __future__ import with_statement
from contextlib import closing
from flask import Flask, render_template, url_for, request, redirect, jsonify, config, make_response
from flask import Response
from flask import flash
from flask_bootstrap import Bootstrap
from flask_login import LoginManager,login_user,logout_user,login_required,current_user
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Boolean, Column , ForeignKey
from sqlalchemy import DateTime, Integer, String, Text, Float
from flask import g
import os
from os import path
import re
import logging,sys
import datetime
from datetime import timedelta
import json
import sqlite3
from forms import LoginForm
from flask_wtf import FlaskForm
from wtforms import SelectField,StringField,validators
from sqlite3 import Error
from webargs import flaskparser, fields
from errors import InternalServerError
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
import login
import latch
import json
# import db_migrate as migration
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_DATABASE_DIR
from config import SQLALCHEMY_DATABASE_VERSION
from config import CONSOLE_VERSION
from config import CONSOLE_PATH
from config import CONSOLE_VERSION
from config import APP_VERSION
# from models imp
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
Bootstrap(app)
app.config['SECRET_KEY'] = 'secret'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# app.config.from_object(flaskcode.default_config)
# app.config['FLASKCODE_RESOURCE_BASEPATH'] = 'functions/'
# app.register_blueprint(flaskcode.blueprint, url_prefix='/flaskcode')
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
import models
import db_create as create_db
import db_upgrade as upgrade_db
import data as ins_records
# migrate = Migrate(app, db)
# manager = Manager(app)
# manager.add_command('db', MigrateCommand)
import configparser
config = configparser.ConfigParser()
config.sections()
config.read('conf.ini')
config.sections()
latchAppId = config['Latch']['appId']
latchSecret = config['Latch']['secret']
@login_manager.user_loader
def load_user(user_id):
return db.session.query(models.Users_DB).get(int(user_id))
# validations
def validation_message (Tabla,Filtro):
Numregistros = 0
Numregistros = db.session.query(Tabla).filter_by(**Filtro).count()
if Numregistros == 0:
message = "No matches found in the table "+ Tabla.__tablename__
else:
message = ""
return message
def validation_messageWihoutFilter (Tabla):
Numregistros = 0
Numregistros = db.session.query(Tabla).count()
if Numregistros == 0:
message = "No matches found in the table "+ Tabla.__tablename__
else:
message = ""
return message
# classes
class Form_validations(FlaskForm):
# StringField('Username', [validators.Length(min=4, max=25)])
ThreatName = StringField('ThreatName', [validators.Length(min=2, max=25)])
ThreatDesc = StringField('ThreatDesc', [validators.Length(min=1, max=25)])
class Form(FlaskForm):
tactic = SelectField('tactic', choices=[])
intel = SelectField('intel', choices=[])
threat = SelectField('threat', choices=[])
plan = SelectField('plan', choices=[])
class Form_task(FlaskForm):
warrior = SelectField('warrior', choices=[])
# class Warrior:
# def __init__(self,idw,os,arch,name,pid,timestamp,ip):
# self.IDWarrior = idw
# self.os = os
# self.arch = arch
# self.name = name
# self.pid = pid
# self.lastseen = timestamp
# self.ip = ip
# class Threat:
# def __init__(self,id,name,description):
# self.id = id
# self.name = name
# self.description = description
# class technique:
# def __init__(self,IDTech,URL_Mitre,Name,IDMitre):
# self.IDTech = IDTech
# self.URL_Mitre = URL_Mitre
# self.Name = Name
# self.IDMitre = IDMitre
# class Tactic:
# def __init__(self,IDtactic,URL_Mitre,Name,Description,IDMitre):
# self.IDtactic = IDtactic
# self.URL_Mitre = URL_Mitre
# self.Name = Name
# self.Description = Description
# self.IDMitre = IDMitre
# class Result:
# def __init__(self,idw,idp,data):
# self.id = idw
# self.plan = idp
# self.resultado = data
# funciones asociadas con la base de datos
# Threat's inserts
def insertar_Amenaza(amenaza):
# for amenaza in amenazas:
Numregistros = 0
Numregistros = db.session.query(models.Threat_DB).filter_by(Name = amenaza['Name'] ).count()
if Numregistros == 0:
registro = models.Threat_DB(
# IDthreat =amenaza['IDthreat'],
Created=amenaza['Created'],
Modified=amenaza['Modified'],
Name=amenaza['Name'],
Description=amenaza['Description'],
Windows=amenaza['Windows'],
MacOS=amenaza['MacOS'],
Linux=amenaza['Linux']
)
db.session.add(registro)
db.session.commit()
logging.debug('Amenaza insertada...')
return (registro.IDthreat)
else:
Threat = db.session.query(models.Threat_DB).filter_by(Name = amenaza['Name'] ).first()
return (Threat.IDthreat)
# plan's inserts
def insertar_Plan(plan,Threat):
Numregistros = 0
Numregistros = db.session.query(models.Plan_DB).filter_by(Name = plan['Name'] ).count()
if Numregistros == 0:
registro = models.Plan_DB(
# IDPlan =plan['IDPlan'],
IDThreat=Threat,
Name=plan['Name'],
Description=plan['Description']
)
db.session.add(registro)
db.session.commit()
logging.debug('plan insertado...')
return (registro.IDPlan)
else:
IDPlan = AvailablePlanName (plan, Threat)
return (IDPlan)
def AvailablePlanName(plan, Threat):
Numregistros = 0
loop = 0
planName = plan['Name']
notFound = False
while notFound == False:
loop = loop + 1
planName = plan['Name'] + "_"+str(loop)
Numregistros = db.session.query(models.Plan_DB).filter_by(Name = planName ).count()
if Numregistros == 0:
notFound = True
registro = models.Plan_DB(
# IDPlan =plan['IDPlan'],
IDThreat=Threat,
Name=planName,
Description=plan['Description']
)
db.session.add(registro)
db.session.commit()
return (registro.IDPlan)
# tech's inserts
def insertar_Tecnica(tecnica):
Insert_Tecnicas = []
Numregistros = 0
Numregistros = db.session.query(models.Technique_DB).filter_by(IDMitre = tecnica['IDMitre'] ).count()
if Numregistros == 0:
registro = models.Technique_DB(
# IDTech =tecnica['IDTech'],
URL_Mitre=tecnica['URL_Mitre'],
Name=tecnica['Name'],
IDMitre=tecnica['IDMitre']
)
db.session.add(registro)
db.session.commit()
logging.debug('Técnica insertada...')
return (registro.IDTech)
else:
tech = db.session.query(models.Technique_DB).filter_by(IDMitre = tecnica['IDMitre'] ).first()
return(tech.IDTech)
# tactic's inserts
def insertar_Tactica(tactica):
Numregistros = 0
Numregistros = db.session.query(models.Tactic_DB).filter_by(IDMitre = tactica['IDMitre'] ).count()
if Numregistros == 0:
registro = models.Tactic_DB(
# IDTactic =tactica['IDTactic'],
URL_Mitre=tactica['URL_Mitre'],
Name=tactica['Name'],
Description=tactica['Description'],
IDMitre=tactica['IDMitre']
)
db.session.add(registro)
db.session.commit()
logging.debug('Tácticas insertadas...')
return (registro.IDTactic)
else:
tactic = db.session.query(models.Tactic_DB).filter_by(IDMitre = tactica['IDMitre'] ).first()
return(tactic.IDTactic)
# intel's inserts
def insertar_Inteligencia(inteligencia):
Numregistros = 0
Numregistros = db.session.query(models.Inteligence_DB).filter_by(IDTech = inteligencia['IDTech'],IDTactic = inteligencia['IDTactic'], Function = inteligencia['Name'] ).count()
if Numregistros == 0:
if not os.path.isfile("functions/"+inteligencia['Name']):
fileName = "functions/"+inteligencia['Name']
data = json.loads(inteligencia['Content'])
with open(fileName, 'w') as f:
for item in data:
f.write("%s\n" % item)
f.close()
registro = models.Inteligence_DB(
# IDIntel =inteligencia['IDIntel'],
IDTech=inteligencia['IDTech'],
IDTactic=inteligencia['IDTactic'],
Function=inteligencia['Name'],
Terminated=inteligencia['Terminated']
)
db.session.add(registro)
db.session.commit()
logging.debug('Inteligencia insertada...')
return (registro.IDIntel)
else:
intel = models.Inteligence_DB.query.filter_by(IDTech = inteligencia['IDTech'],IDTactic = inteligencia['IDTactic'],Function = inteligencia['Name'] ).first()
fileName = "functions/"+inteligencia['Name']
data = json.loads(inteligencia['Content'])
with open(fileName, 'w') as f: # file would be created if not exists
try:
for item in data:
f.write("%s\n" % item)
except:
return render_template("error.html",message = "an error occurred while was saving file "+ fileName)
return (intel.IDIntel)
# task's inserts
def insertar_Tarea(tarea,IDPlan,IDIntel):
Numregistros = 0
Numregistros = db.session.query(models.Task_DB).filter_by(IDPlan = IDPlan,IDIntel = IDIntel,Orden = tarea['Orden'] ).count()
if Numregistros == 0:
registro = models.Task_DB(
# IDTask =tarea['IDTask'],
IDPlan= IDPlan,
IDIntel=IDIntel,
Orden=tarea['Orden']
)
db.session.add(registro)
db.session.commit()
logging.debug('Tarea insertada...')
def InsertarDatos_BD(objetos):
Threats = objetos["Threat"]
for Threat in Threats :
IDthreat = insertar_Amenaza(Threat)
plan = objetos["Plan"]
IDPlan = insertar_Plan(plan[0],IDthreat)
inteligencias = objetos["Inteligence"]
tecnicas = objetos["Technique"]
tacticas = objetos["Tactic"]
tareas = objetos["Task"]
for i, inteligencia in enumerate(inteligencias):
IDTech = insertar_Tecnica(tecnicas[i])
IDTactic = insertar_Tactica(tacticas[i])
IDIntel = insertar_Inteligencia(inteligencias[i])
insertar_Tarea(tareas[i],IDPlan,IDIntel)
# elimina un plan pasado por post
@app.route('/deletePlan',methods=['GET', 'POST'])
def deletePlan():
from login import is_login
if is_login() == False :
return redirect(url_for("login"))
respuesta = request.json
IDPlan = respuesta['plan']
plan = db.session.query(models.Plan_DB).filter_by(IDPlan = IDPlan).first()
for tarea in db.session.query(models.Task_DB).filter_by(IDPlan = IDPlan).all():
Filtro = {'IDTask': tarea.IDTask }
message = validation_message(models.Directive_DB,Filtro)
if len(message) == 0:
for Directive in db.session.query(models.Directive_DB).filter_by(IDTask = tarea.IDTask).all():
db.session.delete(Directive)
Filtro = {'IDWarrior': Directive.IDWarrior }
message = validation_message(models.Warrior_DB,Filtro)
if len(message) == 0:
Warrior = db.session.query(models.Warrior_DB).filter_by(IDWarrior = Directive.IDWarrior).first()
for data in db.session.query(models.DataStore_DB).filter_by(IDWarrior = Directive.IDWarrior).all():
db.session.delete(data)
db.session.delete(Warrior)
db.session.delete(tarea)
db.session.delete(plan)
db.session.commit()
return redirect(url_for("plan"))
# elimina un plan pasado por post
@app.route('/implementation',methods=['GET', 'POST'])
def Implementation():
from login import is_login
if is_login() == False :
return redirect(url_for("login"))
inteligenceList = []
techniqueList = []
for inteligences in db.session.query(models.Inteligence_DB).filter_by(IDTactic = 'TA0001'):
if inteligences.Function != None:
for techniques in db.session.query(models.Technique_DB).filter_by(IDMitre = inteligences.IDTech):
techniqueObj = {}
techniqueObj['IDMitre'] = techniques.IDMitre
techniqueObj['Name'] = techniques.Name
techniqueObj['Function'] = inteligences.Function
techniqueList.append(techniqueObj)
inteligenceObj = {}
inteligenceObj['IDIntel'] = inteligences.IDIntel
inteligenceObj['Function'] = inteligences.Function
inteligenceList.append(inteligenceObj)
tacticList = []
for tactic in db.session.query(models.Tactic_DB).all():
tacticObj = {}
tacticObj['IDMitre'] = tactic.IDMitre
tacticObj['Name'] = tactic.Name
tacticList.append(tacticObj)
return render_template("implementation.html",tacticList = tacticList,techniqueList = techniqueList )
@app.route('/login',methods=['GET', 'POST'])
def login():
from models import Users_DB
from login import login_user
form = LoginForm()
if form.validate_on_submit():
user = Users_DB.query.filter_by(username=form.username.data).first()
if user is not None and user.verify_password(form.password.data):
#if latch accountID exists
if user.latchAccountId is not None:
#if latch status is on, login
if(getLatchStatus(user)):
login_user(user)
flash("Latch is unlocked", "success")
return redirect(url_for('index'))
else:
flash("Your Latch seems to be locked","danger")
return redirect(url_for('login'))
else:
login_user(user)
return redirect(url_for('index'))
form.username.errors.append("Wrong password")
return render_template('login.html', form=form)
@app.route('/users',methods=['GET', 'POST'])
def users():
from login import is_login
if is_login() == False :
return redirect(url_for("login"))
if request.method == 'GET':
datalist = []
for user in db.session.query(models.Users_DB).all():
userObject = {}
userObject['id'] = user.id
userObject['username'] = user.username
userObject['admin'] = user.admin
userObject['latchAccountId'] = user.latchAccountId
datalist.append(userObject)
import configparser
config = configparser.ConfigParser()
config.sections()
config.read('conf.ini')
config.sections()
appid = config['Latch']['appid']
secret = config['Latch']['secret']
return render_template("users.html", datalist=datalist, appid = appid, secret = secret )
return render_template("users.html")
@app.route('/addUser',methods=['GET','POST'])
def addUser():
from login import is_login
if is_login() == False :
return redirect(url_for("login"))
if request.method == 'POST':
Nombre = request.form['nombre']
Password = request.form['password']
if request.form.get('isAdmin'):
Admin = 1
else:
Admin = 0
registro = models.Users_DB()
registro.password = Password
registro.username = Nombre
registro.admin = Admin
flash('User added successfully', 'success')
db.session.add(registro)
db.session.commit()
return redirect(url_for("users"))
@app.route('/deleteUser', methods=['GET','POST'])
def deleteUser():
from login import is_login
if is_login() == False :
return redirect(url_for("login"))
if request.method == 'POST':
data = request.json
userID = data["IDUser"]
registro = db.session.query(models.Users_DB).filter_by(id = userID).first()
registro.username = 'borrar'
db.session.delete(registro)
db.session.commit()
flash('User deleted successfully', 'success')
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
@app.route('/updateLatchConfig', methods=['POST'])
def updateLatchConfig():
import configparser
import sys
appId = request.form['latchAppId']
secret = request.form['latchSecret']
#update
config = configparser.SafeConfigParser()
config.read('conf.ini')
config.set('Latch','appId', appId)
config.set('Latch', 'secret', secret)
with open('conf.ini', 'w') as configfile:
config.write(configfile)
##
config = configparser.ConfigParser()
config.sections()
config.read('conf.ini')
config.sections()
latchAppId = config['Latch']['appId']
latchSecret = config['Latch']['secret']
return redirect(url_for("users"))
@app.route('/latchUnpair',methods=['POST'])
def unpairLatch():
from flask import session
import configparser
import sys
config = configparser.ConfigParser()
config.sections()
config.read('conf.ini')
config.sections()
latchAppId = config['Latch']['appId']
latchSecret = config['Latch']['secret']
accountID= session["latchAccountId"]
#UNPAIR
api = latch.Latch(latchAppId, latchSecret)
response = api.unpair(accountID)
if(response != None):
#REMOVE ACCID FROM DB
userID = session["id"]
user = db.session.query(models.Users_DB).filter_by(id = userID).first()
user.latchAccountId = None
db.session.commit()
#REMOVE FROM SESSION
session["latchAccountId"]=None
flash("Unpaired","success")
else:
flash("Something went wrong","danger")
return redirect(url_for("users"))
@app.route("/unPairSelectedUser", methods=['POST'])
def unPairSelectedUser():
import configparser
import sys
config = configparser.ConfigParser()
config.sections()
config.read('conf.ini')
config.sections()
latchAppId = config['Latch']['appId']
latchSecret = config['Latch']['secret']
data = request.json
appIDUser = data["appIDUser"]
from flask import session
if(session["latchAccountId"]== appIDUser):
session["latchAccountId"]=None
#UNPAIR
api = latch.Latch(latchAppId, latchSecret)
response = api.unpair(appIDUser)
if(response != None):
registro = db.session.query(models.Users_DB).filter_by(latchAccountId = appIDUser).first()
registro.latchAccountId = None
db.session.commit()
flash('User: '+ registro.username +' unpaired successfully', 'success')
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
else:
flash('Something went wrong', 'danger')
return json.dumps({'success':False}), 200, {'ContentType':'application/json'}
@app.route('/latchPairing', methods=['POST'])
def latchPairing():
#retrieve values from form
token = request.form['latchToken']
import configparser
import sys
config = configparser.ConfigParser()
config.sections()
config.read('conf.ini')
config.sections()
latchAppId = config['Latch']['appId']
latchSecret = config['Latch']['secret']
#create api object with appId and secret
api = latch.Latch(latchAppId, latchSecret)
#Latch pairing
try:
response = api.pair(token)
responseData = response.get_data()
data_string=json.dumps(responseData)
decoded=json.loads(data_string)
accountId = decoded["accountId"]
except:
flash("Something went wrong, checkout the fields you have entered", "danger")
return redirect(url_for("users"))
#Status check
response = api.status(accountId)
responseData = response.get_data()
data_string=json.dumps(responseData)
decoded=json.loads(data_string)
operations = decoded["operations"]
status = operations[latchAppId]["status"]
if status == 'on' or status == 'off':
#UPDATE ACCOUNTID AT DB
from flask import session
userID = session["id"]
#query db for the user.id
user = db.session.query(models.Users_DB).filter_by(id = userID).first()
user.latchAccountId = accountId
db.session.commit()
flash("ATTPwn has been paired with Latch", "success")
#UPDATE SESSION
session["latchAccountId"] = accountId
return redirect(url_for("users"))
else:
flash("Latch appId or secret are wrong", "danger")
return redirect(url_for("users"))
return redirect(url_for("users"))
def getLatchStatus(user):
import configparser
import sys
config = configparser.ConfigParser()
config.sections()
config.read('conf.ini')
config.sections()
latchAppId = config['Latch']['appId']
latchSecret = config['Latch']['secret']
appid = latchAppId
secret = latchSecret
api = latch.Latch(appid, secret)
#Status check
response = api.status(user.latchAccountId)
responseData = response.get_data()
data_string=json.dumps(responseData)
decoded=json.loads(data_string)
operations = decoded["operations"]
status = operations[appid]["status"]
if status == 'on':
return True
else:
return False
@app.route("/logout")
def logout():
from login import logout_user
logout_user()
return redirect(url_for('login'))
@app.route('/add_Implementation',methods=['GET', 'POST'])
def add_Implementation():
from login import is_login
if is_login() == False :
return redirect(url_for("login"))
inteligenceList = []
techniqueList = []
for inteligences in db.session.query(models.Inteligence_DB).filter_by(IDTactic = 'TA0001'):
for techniques in db.session.query(models.Technique_DB).filter_by(IDMitre = inteligences.IDTech):
techniqueObj = {}
techniqueObj['IDMitre'] = techniques.IDMitre
techniqueObj['Name'] = techniques.Name
# techniqueObj['Function'] = inteligences.Function
techniqueList.append(techniqueObj)
inteligenceObj = {}
inteligenceObj['IDIntel'] = inteligences.IDIntel
# inteligenceObj['Function'] = inteligences.Function
inteligenceList.append(inteligenceObj)
tacticList = []
for tactic in db.session.query(models.Tactic_DB).all():
tacticObj = {}
tacticObj['IDMitre'] = tactic.IDMitre
tacticObj['Name'] = tactic.Name
tacticList.append(tacticObj)
return render_template("add_Implementation.html",tacticList = tacticList,techniqueList = techniqueList )
# elimina un warrior pasado en la url
@app.route('/delWarrior/<IDWarrior>',methods=['GET', 'POST'])
def delWarrior(IDWarrior):
from login import is_login
if is_login() == False :
return redirect(url_for("login"))
for Directive in db.session.query(models.Directive_DB).filter_by(IDWarrior = IDWarrior).all():
db.session.delete(Directive)
db.session.commit()
for data in db.session.query(models.DataStore_DB).filter_by(IDWarrior = IDWarrior).all():
db.session.delete(data)
warrior = db.session.query(models.Warrior_DB).filter_by(IDWarrior = IDWarrior).first()
db.session.delete(warrior)
db.session.commit()
# return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
flash('Warrior removed successfully', 'success')
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
#vistas principales
@app.route('/',methods=['GET', 'POST'])
def index():
if create_db.create_database() == True:
flash('database create successfully', 'success')
database = db.session.query(models.Version_DB).filter_by(repository_id = "database repository").first()
version = database.version
if database.version < SQLALCHEMY_DATABASE_VERSION:
message = upgrade_db.upgrade_version()
try:
while version <= SQLALCHEMY_DATABASE_VERSION:
ins_records.upgrade_database(version)
version += 1
flash(message, 'success')
except:
flash("an error ocurred while database updating", 'danger')
from login import is_login
if is_login() == False :
return redirect(url_for("login"))
Estado = "Alive"
if request.method == "POST":
Estado = request.form['State']
#Recuperamos los warriors
warriorlist = []
datalist = {}
#obtenemos la fecha y hora actuales y restamos 3 min para ver si los warrior estan entre esos dos valores
now = datetime.datetime.now() - timedelta(minutes= 60 )
Filtro = {'State': 'Alive'}
Numregistros = 0
Numregistros = db.session.query(models.Warrior_DB).filter_by(**Filtro).count()
if Numregistros == 0:
message = validation_message(models.Warrior_DB,Filtro)
logging.debug(message+ ' -- Filtro: '+ str(Filtro))
else:
for warrior in db.session.query(models.Warrior_DB).filter_by(State = "Alive").all():
if str(warrior.Lastseen) < str(now):
warrior.State = "Dead"
db.session.commit()
i = 0
# state filter
if Estado == "":
message = validation_messageWihoutFilter(models.Warrior_DB )
if len(message) == 0:
for warrior in db.session.query(models.Warrior_DB).all():
warriorlist.append(warrior)
for directiva in db.session.query(models.Directive_DB).filter_by(Done= "true" , IDWarrior = warrior.IDWarrior).all() :
tarea = db.session.query(models.Task_DB).filter_by(IDTask = directiva.IDTask).first()
plan = db.session.query(models.Plan_DB).filter_by(IDPlan = tarea.IDPlan).first()
inteligencia = db.session.query(models.Inteligence_DB).filter_by(IDIntel = tarea.IDIntel).first()
tecnica = db.session.query(models.Technique_DB).filter_by(IDMitre = inteligencia.IDTech).first()
i += 1
if not warrior.IDWarrior in datalist:
datalist[warrior.IDWarrior] = plan.Name + " ---> "+ tecnica.Name + " - " +str(inteligencia.Function)
else:
datalist[warrior.IDWarrior] += ' | ' + tecnica.Name + " - " +str(inteligencia.Function)
else:
for warrior in db.session.query(models.Warrior_DB).filter_by(State = Estado).all():
warriorlist.append(warrior)
for directiva in db.session.query(models.Directive_DB).filter_by(Done= "true" , IDWarrior = warrior.IDWarrior).all() :
tarea = db.session.query(models.Task_DB).filter_by(IDTask = directiva.IDTask).first()
plan = db.session.query(models.Plan_DB).filter_by(IDPlan = tarea.IDPlan).first()
inteligencia = db.session.query(models.Inteligence_DB).filter_by(IDIntel = tarea.IDIntel).first()
tecnica = db.session.query(models.Technique_DB).filter_by(IDMitre = inteligencia.IDTech).first()
i += 1
if not warrior.IDWarrior in datalist:
datalist[warrior.IDWarrior] = plan.Name + " ---> "+ tecnica.Name + " - " +str(inteligencia.Function)
else:
datalist[warrior.IDWarrior] += ' | ' + tecnica.Name + " - " +str(inteligencia.Function)
form = FlaskForm()
return render_template("index.html",warriorlist=warriorlist,datalist=datalist, Estado=Estado)
@app.route('/plan',methods=['GET', 'POST'])
def plan():
from login import is_login
if is_login() == False :
return redirect(url_for("login"))
form = Form()
planList = []
for plan in db.session.query(models.Plan_DB).all():
planObj = {}
planObj['IDPlan'] = plan.IDPlan
planObj['Name'] = plan.Name
planList.append(planObj)
return render_template("plan.html", form = form, planList=planList)
# elimina un warrior pasado en la url
@app.route('/about',methods=['GET', 'POST'])
def about():
from login import is_login
if is_login() == False :
return redirect(url_for("login"))
database = db.session.query(models.Version_DB).filter_by(repository_id = "database repository").first()
databaseVersion = database.version
consoleVersion = CONSOLE_VERSION
appVersion = APP_VERSION
return render_template("about.html",consoleVersion = consoleVersion,databaseVersion = databaseVersion, appVersion=appVersion)
@app.route('/results',methods=['GET', 'POST'])
def results():
from login import is_login
if is_login() == False :
return redirect(url_for("login"))
#Recuperamos los agents y los resultados
warriorlist = []
datalist = {}
listaDirectivasWarrior = {}
showView = False
sinDirectivas = False
message = ""
i = 0
plan = None
for warrior in db.session.query(models.Warrior_DB).all():
DirectivesArray = []
warriorlist.append(warrior)
Filtro = {'IDWarrior': warrior.IDWarrior}
Numregistros = 0
Numregistros = db.session.query(models.Directive_DB).filter_by(**Filtro).count()
if Numregistros == 0:
message = validation_message(models.Directive_DB,Filtro)
logging.debug(message+ ' -- Filtro: '+ str(Filtro))
# message = "no hay directivas para los warrior"
sinDirectivas = True
else:
for directiva in db.session.query(models.Directive_DB).filter_by( IDWarrior = warrior.IDWarrior).all() :
DirectivasObj = {}
tarea = db.session.query(models.Task_DB).filter_by(IDTask = directiva.IDTask).first()
if plan == None:
plan = db.session.query(models.Plan_DB).filter_by(IDPlan = tarea.IDPlan).first()
inteligencia = db.session.query(models.Inteligence_DB).filter_by(IDIntel = tarea.IDIntel).first()
tecnica = db.session.query(models.Technique_DB).filter_by(IDMitre = inteligencia.IDTech).first()
DirectivasObj['techName'] = tecnica.IDMitre+" - "+ tecnica.Name
DirectivasObj['function'] = str(inteligencia.Function)
DirectivasObj['done'] = directiva.Done
if (str(directiva.Good) == '0'):
DirectivasObj['good'] = 'Success'
else:
if directiva.Done == "true":
DirectivasObj['good'] = 'Error'
else:
DirectivasObj['good'] = 'Pending'
DirectivesArray.append(DirectivasObj)
showView = True
sinDirectivas = False
if plan == None:
listaDirectivasWarrior[warrior.IDWarrior] = "",DirectivesArray
else:
listaDirectivasWarrior[warrior.IDWarrior] = plan.Name,DirectivesArray
# if showView :
# if listaDirectivasWarrior == None:
# return render_template("resultados.html",warriorlist=warriorlist)
# else:
return render_template("results.html",warriorlist=warriorlist,listaDirectivasWarrior = listaDirectivasWarrior)
# else:
# return render_template("error.html",message = message)
@app.route('/updateDataStore',methods=['POST'])
def updateDataStore():
from login import is_login
if is_login() == False :
return redirect(url_for("login"))
data = request.json
IDData = data["IDData"]
User = data["User"]
if User == "" or User == "-":
User = None
Password = data["Password"]
if Password == "" or Password == "-":
Password = None
NTLM = data["NTLM"]
if NTLM == "" or NTLM == "-":
NTLM = None
LM = data["LM"]
if LM == "" or LM == "-":
LM = None
IP = data["IP"]
if IP == "" or IP == "-":
IP = None
Port = data["Port"]
if Port == "" or Port == "-":
Port = None
DataStore = db.session.query(models.DataStore_DB).filter_by(IDData = IDData).first()
DataStore.User = User
DataStore.Password = Password
DataStore.NTLM = NTLM
DataStore.LM = LM
DataStore.IP = IP
DataStore.Port = Port
db.session.commit()
flash('DataStore updated successfully', 'success')
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
@app.route('/dataStore/<warriorAlias>',methods=['GET', 'POST'])
def dataStore(warriorAlias):
from login import is_login
if is_login() == False :
return redirect(url_for("login"))
Filtro = {'Alias': warriorAlias }
message = validation_message(models.Warrior_DB,Filtro)
if len(message) != 0:
print (message)
logging.debug(message+ ' -- Filtro: '+ str(Filtro))
return render_template("error.html",message = message)
else:
warrior = db.session.query(models.Warrior_DB).filter_by(Alias = warriorAlias).first()
IDWarrior = warrior.IDWarrior
dataStoreArray = []
for data in db.session.query(models.DataStore_DB).filter_by(IDWarrior=IDWarrior).all():
dataStoreObj = {}
if data.User == None:
dataStoreObj['User'] = "-"
else:
dataStoreObj['User'] = data.User
if data.IP == None:
dataStoreObj['IP'] = "-"
else:
dataStoreObj['IP'] = data.IP
if data.Password == None:
dataStoreObj['Password'] = "-"
else:
dataStoreObj['Password'] = data.Password
if data.NTLM == None:
dataStoreObj['NTLM'] = "-"
else:
dataStoreObj['NTLM'] = data.NTLM
if data.LM == None:
dataStoreObj['LM'] = "-"
else: