wasmdashai commited on
Commit
62dcfec
·
1 Parent(s): 9c3d10b

model push

Browse files
ASG.API/AModelScenoariotree.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Fri Mar 10 23:13:18 2023
4
+
5
+ @author:
6
+ """
7
+ from ModelTEC import *
8
+ from MScenoariotree import *
9
+ from MCheakscenario import Cheakscenario
10
+
11
+
12
+
13
+ class ModelScenoariotree:
14
+
15
+ def __init__(self,obTECSoft=None,obTEC=None,obG=None,Base=None,isForm=False):
16
+
17
+
18
+ self.cks=Cheakscenario(ob=obTECSoft)
19
+ # obTEC.nlp=Base.nlp
20
+ # obTECSoft.nlp=Base.nlp
21
+ self.Base=Base
22
+ self.obGroup=obG
23
+ self.Base.setModels(ObTEC=obTEC,ObTECSodft=obTECSoft,obchk=self.cks,isForm=isForm)
24
+
25
+
26
+ def search(self,inputstate=[''],rateerror=0,PrintFuri=True,type_search='Max',ThresholdTechnique=0.0,istrans=False):
27
+
28
+ Cheakscenario.PrintFuri=PrintFuri
29
+ Cheakscenario.rateerror=rateerror
30
+
31
+ self.Base.Predict(Description=inputstate,WF=type_search,ThresholdTechnique=ThresholdTechnique,istrans=istrans)
32
+ print ('all scenario : end')
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
ASG.API/ASGModels.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ModelTEC import *
2
+
3
+ import pickle
4
+ from TypeModels import TypeModel
5
+ from BasePath import BASEPATH
6
+ from threading import Thread
7
+ from MScenoariotree import *
8
+ from AModelScenoariotree import ModelScenoariotree
9
+
10
+ from MCheakscenario import Cheakscenario
11
+ class ASG:
12
+ def readobsoft(self):
13
+ self.Soft=TEC(typemodel="svmL",model_setting=TypeModel['software'])
14
+ self.Soft.loadmodel()
15
+ self.Index+=1
16
+
17
+ def readobgroup(self):
18
+ self.Group=TEC(typemodel="svmL",model_setting=TypeModel['group'])
19
+ self.Group.loadmodel()
20
+ self.Index+=1
21
+
22
+ def readobtec(self):
23
+ self.Tec=TEC(typemodel="svmL",model_setting=TypeModel['technique'])
24
+ self.Tec.loadmodel()
25
+ self.Index+=1
26
+
27
+ def readmstree(self):
28
+ self.SGT=Scenoariotree('TTs.pkl','tecbyTectics.pkl')
29
+ self.SGT.Fit()
30
+ self.Index+=1
31
+ def __init__(self):
32
+ self.Index=0
33
+ self.SGT=None
34
+ # Thread(target=self.readmstree).start()
35
+ # Thread(target=self.readobsoft).start()
36
+ # Thread(target=self.readobtec).start()
37
+ # Thread(target=self.readobgroup).start()
38
+ self.readmstree()
39
+ self.readobsoft()
40
+ self.readobtec()
41
+ self.readobgroup()
42
+
43
+
44
+ self.Soft.setPipeline(model=self.Tec)
45
+ self.Group.setPipeline(model=self.Soft)
46
+ self.cks=Cheakscenario(ob=self.Soft)
47
+ self.MST=ModelScenoariotree(obTECSoft=self.Soft,obTEC=self.Tec,obG=self.Group,Base=self.SGT,isForm=True)
48
+ self.Tec.obMP
49
+ self.SGT.setModels(ObTEC=self.Tec,ObTECSodft=self.Soft,obchk=self.cks,isForm=False)
50
+
51
+
52
+
53
+ def search(self,inputstate=[''],rateerror=0,PrintFuri=True,type_search='Max',ThresholdTechnique=0.5,istrans=False,numstop=-1):
54
+
55
+ Cheakscenario.PrintFuri=PrintFuri
56
+ Cheakscenario.rateerror=rateerror
57
+
58
+ outputs=self.SGT.Predict(Description=inputstate,WF=type_search,ThresholdTechnique=ThresholdTechnique,istrans=istrans,numstop=numstop)
59
+ print ('all scenario : end')
60
+ return outputs
61
+
ASG.API/BasePath.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import sys
2
+ path="/home/asgmodel/django-rest-api/DjangoRestApi/tutorials/ASG"
3
+ BASEPATH=path+'/'
4
+ sys.path.insert(0, path)
ASG.API/MCheakscenario.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Sun Dec 18 21:43:54 2022
4
+
5
+ @author: amaer
6
+ """
7
+ import numpy as np
8
+
9
+ from ModelTEC import *
10
+
11
+
12
+ class Cheakscenario:
13
+ rateerror=0
14
+ PrintFuri=True
15
+
16
+ def __init__(self,ob=None,sequensed=None):
17
+ self.obTECSoft=ob
18
+ self.lensoft=len(ob.obMP.Classes)
19
+ self.inintlist()
20
+ self.onsequens=sequensed
21
+
22
+
23
+ def inintlist(self):
24
+ self.listsoftware=np.zeros((self.lensoft,5))
25
+ self.Counter=0
26
+
27
+
28
+
29
+ def createtable(self,row,stat,index=0):
30
+ st='<table border="1" style="" ><tr style="background-color:'+stat[0]+'; color:#fff"><th style="text-align:center" >Tactic Name</th><th style="text-align:center" >Technique Name</th></tr>'
31
+
32
+
33
+
34
+ for ob in row:
35
+ st+='<tr><td style="text-align:center" >'+ob[0]+'</td><td style="text-align:center" >'+ob[1]+'</td></tr>'
36
+
37
+ st+='<tr style="background-color:'+stat[0]+'; color:#fff"><td colspan = "2" style="text-align:center" >attack scenario status ('
38
+
39
+ st+=''+ stat[1] +' ) </td></tr>'
40
+ return st+'</table>'
41
+
42
+
43
+
44
+
45
+ def getScenario(self,itmes,k=0,index=0):
46
+ stat=self.getAStatescenario(k,index)
47
+ if Cheakscenario.PrintFuri==False and stat[1]=='Failure':return None
48
+ rowd=[]
49
+ for ob in itmes:
50
+ if ob.strip() !='':
51
+
52
+ itms=ob.split("*->")
53
+ rowd.append([itms[0],itms[1]])
54
+ return rowd,stat,k
55
+
56
+
57
+
58
+
59
+ def process(self,path,cinput,isclean=True):
60
+ itmes=path.split("=> ")
61
+
62
+ pathT=self.getpathTech(itmes)
63
+ if isclean:
64
+ da=self.obTECSoft.clean_dataT([pathT+' ' +cinput+" use "])
65
+ else:
66
+ da=[cinput]
67
+
68
+
69
+
70
+ # print(pathT,da)
71
+ if(len(da)>0):
72
+ try:
73
+ feat=self.obTECSoft.obMP.obVec.transform(da)
74
+ pyd=self.obTECSoft.Model.predict_proba(feat)
75
+ self.listsoftware[:,4]+=np.array(pyd[0])
76
+ #for i in range(self.lensoft):
77
+ # self.listsoftware[i,4]=pyd[0][i]
78
+ index=np.argmax(pyd)
79
+ k=pyd[0][index]*100+Cheakscenario.rateerror
80
+
81
+ row=self.getScenario(itmes,k,index)
82
+ if row is not None and len(row[0])>0:
83
+ self.Counter+=1
84
+ if self.onsequens is not None:
85
+ self.onsequens((row,pyd[0]))
86
+
87
+
88
+ return row,pyd[0]
89
+
90
+
91
+ except: pass
92
+
93
+ return None
94
+
95
+ def print_table(self,path,cinput):
96
+ # self.obTECSoft.ChangeModel(ob='svmL')
97
+ rows=self.process(path, cinput)
98
+
99
+ if rows is not None :
100
+ row,pa=rows
101
+ td=self.createtable(row[0],row[1],self.Counter)
102
+ print('---------------------------scenario (',self.Counter,')------------------------------')
103
+ # display(HTML(td))
104
+
105
+ return rows
106
+
107
+
108
+ def getAStatescenario(self,k,index):
109
+ if k>=70:
110
+ self.listsoftware[index][0]+=1
111
+ return ('#04AA6D','Success')
112
+ if k>=60:
113
+ self.listsoftware[index][1]+=1
114
+ return ('#1ec7c3','close to success')
115
+
116
+ if k>=30:
117
+ self.listsoftware[index][2]+=1
118
+ return ('#fb4bd1','Initi')
119
+ self.listsoftware[index][3]+=1
120
+ return ('#e91c07','Failure')
121
+ def getpathTech(self,items):
122
+ path=' use '
123
+ for ob in items:
124
+ if ob.strip() !='':
125
+
126
+ itms=ob.split("*->")
127
+ path+=' '+itms[1]
128
+ return path
129
+
130
+
131
+
132
+
133
+
134
+
ASG.API/MScenoariotree.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Tue Dec 6 22:13:12 2022
4
+
5
+ @author: amaer
6
+ """
7
+
8
+ import numpy as np
9
+
10
+
11
+
12
+ import copy
13
+ from ModelTEC import *
14
+
15
+ import pickle
16
+
17
+ from threading import Thread
18
+ class Graph:
19
+
20
+ def __init__(self,root,name=None,idtactic=0):
21
+ self.Root=root
22
+ self.Name=name
23
+ self.Idtactic=idtactic
24
+
25
+ self.Tactics=[]
26
+ #........................
27
+
28
+ def Filter(self):
29
+ for i in range(self.Idtactic,len(Scenoariotree.Basetree)):
30
+ self.Tactics.append(copy.deepcopy(Scenoariotree.Basetree[i]))
31
+
32
+ #........................
33
+
34
+ def Run(self,path="",state=" ",Cinput="",listAttackGod=[],numstop=-1):
35
+
36
+ self.Filter()
37
+ for tactic in self.Tactics:
38
+ tactic.Run(self.Root,path=path+"=> "+tactic.Name,state=state,Cinput=Cinput,listAttackGod=listAttackGod,numstop=numstop)
39
+ # thread=Thread(target = tactic.Run, args = (self.Root,path+"->"+tactic.Name))
40
+ # thread.start()
41
+ # thread.join()
42
+
43
+
44
+ #........................
45
+
46
+
47
+ class Technique:
48
+
49
+ PreprocessingFunc=None
50
+ ExtractFeaturesFunc=None
51
+ objFile=None
52
+ Counter=0
53
+ Cinput=' '
54
+ listAttackGod=[]
55
+ PrintScenoario=print
56
+
57
+
58
+
59
+ def __init__(self,name,description,weight=None):
60
+
61
+ self.Name=name
62
+ self.Description=description
63
+ self.Weight=weight
64
+ self.CleanDescription=None
65
+ self.FeaturesDescription=None
66
+ self.Graph=None
67
+
68
+ #........................................
69
+
70
+ def Preprocessing(self):
71
+ if Technique.PreprocessingFunc:
72
+ return Technique.PreprocessingFunc([self.Description])
73
+ return self.Description
74
+
75
+ #........................................
76
+
77
+ def ExtractFeatures(self):
78
+ if Technique.ExtractFeaturesFunc:
79
+ return Technique.ExtractFeaturesFunc(self.CleanDescription if self.CleanDescription else self.Description)
80
+ return np.zeros((1,10))
81
+
82
+ #........................................
83
+
84
+ def Fit(self):
85
+ self.CleanDescription=self.Preprocessing()
86
+ #self.FeaturesDescription=self.ExtractFeatures()
87
+
88
+ #........................................
89
+
90
+ def Run(self,id,path="",state=" ",Cinput="",listAttackGod=[],numstop=-1):
91
+
92
+ if (numstop ==-1 or len(listAttackGod)<numstop):
93
+ if id<len(Scenoariotree.Basetree) :
94
+ # Technique.objFile.write("=")
95
+
96
+ # print('=',end='')
97
+
98
+ path=path+" *-> "+self.Name+" "
99
+ row=Technique.PrintScenoario(path,Cinput)
100
+ if row is not None:
101
+ listAttackGod.append(row)
102
+
103
+ self.Graph=Graph(root=self,name=self.Name,idtactic=id+1)
104
+ self.Graph.Run(path=path,state=state,Cinput=Cinput,listAttackGod=listAttackGod,numstop=numstop)
105
+ else :
106
+ try:
107
+ row=Technique.PrintScenoario(path,Cinput)
108
+ if row is not None:
109
+ listAttackGod.append(row)
110
+
111
+ except:
112
+ pass
113
+
114
+
115
+ #........................................
116
+
117
+ def __str__(self):
118
+ return f"(Name: {self.Name} , Weights: {self.Weight})"
119
+
120
+
121
+
122
+ class Tactic():
123
+ dataMS=None
124
+ WF="thrshold"
125
+
126
+
127
+
128
+ def __init__(self,name,id=0,description=None,weight=None,techniques=None,wfilter="thrshold"):
129
+ self.Name=name
130
+ self.Id=id
131
+ self.Weight=weight
132
+ self.Techniques=techniques if techniques else []
133
+
134
+
135
+ #........................................
136
+
137
+ def Filter1(self,root,path=""):
138
+ i=0
139
+ while i<len(self.Techniques):
140
+
141
+ sim=Tactic.dataMS[root.Name][self.Techniques[i].Name]
142
+
143
+ if sim>=Scenoariotree.ThresholdTechnique:
144
+ self.Techniques[i].Weight=sim
145
+
146
+
147
+ else:
148
+
149
+ # row=Technique.PrintScenoario(path,Technique.Cinput)
150
+ # if row is not None:
151
+ # Technique.listAttackGod.append(row)
152
+ # Technique.Counter+=1
153
+ self.Techniques.remove(self.Techniques[i])
154
+ i-=1
155
+
156
+
157
+
158
+ i+=1
159
+
160
+ #........................................
161
+ def Filter2(self,root,path=""):
162
+
163
+ listd=[]
164
+ max=0
165
+ for i in range(len(self.Techniques)):
166
+ sim=Tactic.dataMS[root.Name][self.Techniques[i].Name]
167
+ if sim>max and sim>=Scenoariotree.ThresholdTechnique:
168
+ listd=[self.Techniques[i]]
169
+ max=sim
170
+ # Scenoariotree.CurrentSoft.predict()
171
+
172
+
173
+ self.Techniques=listd
174
+
175
+ #........................................
176
+ def Filter(self,root,path=""):
177
+ if Tactic.WF=="thrshold":
178
+ self.Filter1(root,path)
179
+ else:
180
+ self.Filter2(root,path)
181
+
182
+
183
+ def Run(self,root,path="",state="",Cinput="",listAttackGod=[],numstop=-1):
184
+
185
+ self.Filter(root,path)
186
+
187
+ for technique in self.Techniques:
188
+ technique.Run(self.Id,path=path,state=state,Cinput=Cinput,listAttackGod=listAttackGod,numstop=numstop)
189
+ # thread=Thread(target=technique.Run,args=(self.Id,path))
190
+ # thread.start()
191
+ # thread.join()
192
+
193
+ #........................................
194
+
195
+ def __str__(self):
196
+ return f"(Name: {self.Name}, Weight: {self.Weight})"
197
+
198
+
199
+
200
+ from BasePath import BASEPATH
201
+
202
+ class Scenoariotree:
203
+
204
+ obTEC=None
205
+ obTECSodft=None
206
+ ThresholdTechnique=0.3
207
+ ThresholdTactic=0.3
208
+ Basetree=None
209
+ CurrentSoft=None
210
+ indecisT={}
211
+ CurrentInput=''
212
+
213
+
214
+ #....................................................
215
+
216
+
217
+
218
+
219
+
220
+
221
+
222
+ #....................................................
223
+
224
+
225
+ def __init__(self,file1,file2,Ntactics=None):
226
+
227
+ self.TacticsOrder=pickle.load(open(BASEPATH+file1,'rb'))
228
+ self.indecisT=pickle.load(open(BASEPATH+file2,'rb'))
229
+ self.Ntactics=len(self.TacticsOrder)
230
+ self.nlp=None#spacy.load('en_core_web_lg')
231
+ """
232
+
233
+ """
234
+
235
+ def setModels(self,ObTEC=None,ObTECSodft=None,obchk=None,isForm=False):
236
+ self.obTEC=ObTEC
237
+ self.obTECSodft=ObTECSodft
238
+ self.obTEC.ChangeModel(ob="svmK")
239
+ self.obTECSodft.ChangeModel(ob="svmK")
240
+ self.obchk=obchk
241
+ Technique.PrintScenoario=obchk.print_table if isForm==False else obchk.process
242
+
243
+ #....................................................
244
+
245
+ def InitBasetree(self):
246
+ tree=[]
247
+ i=0
248
+ for key in self.TacticsOrder:
249
+ tactic=key
250
+ tree.append(Tactic(name=tactic,id=i))
251
+ group=self.TacticsOrder[key]
252
+ i+=1
253
+ for j in range(len(group)):
254
+ tree[-1].Techniques.append(Technique(name=group[j],
255
+ description=" ",
256
+ ))
257
+
258
+
259
+ return tree
260
+
261
+ #..............................................
262
+
263
+ def getordertactics(self):
264
+ return ''
265
+ def Fit(self,file="dataSM.pkl",wtype='ALL'):
266
+
267
+
268
+
269
+
270
+
271
+ Tactic.dataMS=pickle.load(open(BASEPATH+file,'rb'))
272
+ Scenoariotree.Basetree=self.InitBasetree()
273
+
274
+
275
+ # Scenoariotree.Basetree[6].Techniques.append(Technique(name="Exploitation of Remote Services",description="Exploitation of Remote Services")
276
+
277
+
278
+
279
+ #..............................................
280
+
281
+ def Predict(self,Description,ThresholdTechnique=0.5,ThresholdTactic=0.0,WF="thrshold",istrans=False,numstop=-1):
282
+ Technique.Counter=0
283
+ Technique.listAttackGod=[]
284
+ self.obchk.inintlist()
285
+ Tactic.WF=WF
286
+ Scenoariotree.ThresholdTechnique=ThresholdTechnique
287
+ Scenoariotree.ThresholdTactic=ThresholdTactic
288
+ if istrans:
289
+ Description=[self.obTEC.to_tran(Description)]
290
+
291
+ tech=self.obTEC.predict(Description)
292
+
293
+ if tech!="No":
294
+ print('-------------------------------------------')
295
+ print('Technique : ', tech)
296
+ tact=self.indecisT[tech]
297
+
298
+ print(' Tactic :',tact)
299
+ self.obTECSodft.ChangeModel(ob="svmK")
300
+ CurrentSoft=self.obTECSodft.predict(Description+[" "+tech])
301
+
302
+ print('input same as Software is : ',CurrentSoft)
303
+ self.obTECSodft.ChangeModel(ob="svmL")
304
+ print('-------------------------------------------')
305
+ print('---------------------senarios----------------------')
306
+ listofs=[]
307
+
308
+ self.Root=Technique(name=tech,description=Description)
309
+
310
+ idt=-1
311
+ for key in self.TacticsOrder:
312
+ if key==tact:
313
+ break
314
+ idt+=1
315
+
316
+ self.Root.Run(id=idt+1,path="=> "+tact,state="",Cinput=Description[0],listAttackGod=listofs,numstop=numstop)
317
+ if idt==self.Ntactics-1:
318
+ self.obchk.process(tact+" *-> "+ tech,Description[0],isclean=False)
319
+
320
+
321
+
322
+
323
+
324
+
325
+
326
+
327
+ else :
328
+ print( "no found any thing........")
329
+
330
+ return listofs
331
+ #..............................................
332
+
333
+
334
+
335
+
ASG.API/ModelTEC.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Sat Dec 17 11:27:28 2022
4
+
5
+ @author: amaer
6
+ """
7
+
8
+ import pickle
9
+ import numpy as np
10
+
11
+
12
+ from sklearn.feature_extraction.text import TfidfVectorizer
13
+ import regex as re
14
+ # import spacy
15
+ # from spacy import displacy
16
+ from sklearn.model_selection import train_test_split
17
+
18
+ from sklearn.metrics import confusion_matrix, classification_report, accuracy_score,f1_score, precision_score, recall_score
19
+
20
+ from googletrans import Translator
21
+
22
+ from django.urls import ModelPums
23
+ import requests
24
+
25
+ class TEC:
26
+ __Outs={'svmL':None,'svmK':None,'logstick':None,'target':None}
27
+
28
+ def createOuts():
29
+ ob=TEC.__Outs.copy()
30
+ for key in ob:
31
+ ob[key]=[]
32
+ return ob
33
+ def __init__(self,typemodel="svmL",model_setting=None,spt=0.3,nlp=None):
34
+
35
+ self.model_setting=model_setting
36
+ self.isLoad=False
37
+ self.nlp=nlp
38
+
39
+
40
+ def toclean(self,txt):
41
+ try:
42
+ url="https://ansaltwyl256.pythonanywhere.com/api/nlp/"+txt
43
+ response = requests.get(url)
44
+
45
+ return response.json()['description']
46
+ except:
47
+ return "$"
48
+ def loadmodel(self):
49
+ mm=ModelPums()
50
+ matrck=pickle.load(open(self.model_setting.path_model,'rb'))
51
+ self.DES=pickle.load(open(self.model_setting.path_Qwords,'rb'))
52
+ mm.obData=matrck['obData']
53
+ mm.obVec=matrck['obVec']
54
+ mm.obSVML=matrck['obSVML']
55
+ mm.obSVMK=matrck['obSVMK']
56
+ mm.oblogict=matrck['oblogict']
57
+ mm.X=matrck['X']
58
+ mm.Y=matrck['Y']
59
+ mm.Classes=matrck['Classes']
60
+ self.obMP=mm
61
+ if self.model_setting.path_Qwords!="":
62
+ self.Qwords={}#pickle.load(open(model_setting.path_Qwords,'rb'))
63
+ else:
64
+ self.Qwords={}
65
+ self.detector = Translator()
66
+ # self.Splits(spt)
67
+ self.Model=self.obMP.obSVML
68
+
69
+ self.name=self.model_setting.name
70
+ self.pipeline= None
71
+ self.isLoad=True
72
+
73
+ def getLables(self):
74
+ return self.obMP.Classes
75
+
76
+ def is_found(self,words,ob):
77
+ sms=[]
78
+
79
+ ob=ob.lower().strip()
80
+ for w in words:
81
+ if w==ob:
82
+ return 1,w
83
+ sms.append(self.similarity(w,ob))
84
+ index=np.argmax(sms)
85
+ if sms[index]>0.7:
86
+ return 2, list(words)[index]
87
+
88
+ return 0,''
89
+
90
+ def is_found_K(self,words,ob):
91
+
92
+ ob=ob.lower().strip()
93
+ for w in words:
94
+ if w==ob:
95
+ return 1,w
96
+
97
+ return -1,''
98
+
99
+
100
+ def Training(self):
101
+ self.obMP.obSVMK.fit(self.obMP.X,self.obMP.Y)
102
+
103
+
104
+ def clean_dataT(self,data,typw='',is_input=False):
105
+ d,_=self.clean_dataAPI(data)
106
+ return d
107
+ datac=data
108
+ dock=[]
109
+ is_found= self.is_found if is_input==True else self.is_found_K
110
+
111
+ reg=r"([0-9])|(@\[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)|^rt|http.+?"
112
+ for datac in data:
113
+ strr=str(datac)
114
+ strr=re.sub(reg, "", strr)
115
+ doc=self.nlp(strr)
116
+ disc=""
117
+ for token in doc:
118
+ if not token.is_punct and not token.is_stop and not token.is_space and token.is_alpha:
119
+ if token.pos_=='ADJ' or token.pos_=='NOUN' or token.pos_=='VERB':#token.pos_== typw:
120
+ qk,key=is_found(self.Qwords,token.lemma_)
121
+ if qk==1:
122
+ disc=disc+self.Qwords[token.lemma_]+" "
123
+ elif qk==2:
124
+ disc=disc+self.Qwords[key]+" "
125
+ elif qk==-1:
126
+ disc=disc+token.lemma_+" "
127
+
128
+ disc=disc.lower().strip()
129
+ if len(disc)>0:
130
+ dock.append(disc)
131
+
132
+ return dock
133
+
134
+ def similarity(self,ob1,ob2):
135
+ ob1=ob1
136
+ ob2=ob2
137
+ nob1=self.nlp(ob1)
138
+ return nob1.similarity(self.nlp(ob2))
139
+
140
+ #-----------------#
141
+ def clean_data(self,data,typw='',is_input=False):
142
+ return self.clean_dataAPI(data)
143
+ datac=data
144
+ dock=[]
145
+ labels=[]
146
+ is_found= self.is_found if is_input==True else self.is_found_K
147
+ reg=r"([0-9])|(@\[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)|^rt|http.+?"
148
+ for (datac,label) in data:
149
+ strr=str(datac)
150
+
151
+ strr=re.sub(reg, "", strr)
152
+ doc=self.nlp(strr)
153
+ disc=""
154
+ for token in doc:
155
+ if not token.is_punct and not token.is_stop and not token.is_space and token.is_alpha:
156
+ if True: # token.pos_=='ADJ' or token.pos_=='NOUN' or token.pos_=='VERB' :
157
+ # disc=disc+token.lemma_+" "
158
+ qk,key=is_found(self.Qwords,token.lemma_)
159
+ # print(qk,key)
160
+ if qk==1:
161
+ disc=disc+self.Qwords[key]+" "
162
+ elif qk==2:
163
+ disc=disc+self.Qwords[key]+" "
164
+ elif qk==-1:
165
+ disc=disc+token.lemma_+" "
166
+
167
+ if len(disc)>2:
168
+ dock.append(disc.strip())
169
+ labels.append(label)
170
+ return dock,labels
171
+ #-----------------#
172
+ def clean_dataAPI(self,data,typw='',is_input=False):
173
+ txt=self.toclean(data)
174
+ if txt !="$":
175
+ return [txt],6
176
+
177
+
178
+ reg=r"([0-9])|(@\[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)|^rt|http.+?"
179
+
180
+ strr=str(data)
181
+
182
+ strr=re.sub(reg, "", strr)
183
+ return [strr],6
184
+ def setPipeline(self,model=None):
185
+ self.pipeline=model
186
+ def to_tran(self,text,dest='en'):
187
+ ff=True
188
+ c=0
189
+
190
+ while ff:
191
+
192
+
193
+ try:
194
+ t=self.detector.translate(str(text),dest=dest)
195
+ ff=False
196
+ text=t.text
197
+ except:
198
+ c+=1
199
+ if c==20:
200
+ ff=False
201
+ print(' no connenet Tr')
202
+
203
+ return text
204
+
205
+ def Predict_ALL(self,description,istrans=False):
206
+ if istrans:
207
+ description=self.to_tran(description)
208
+
209
+
210
+ if self.pipeline is not None:
211
+ text_output,_,outs=self.pipeline.Predict_ALL(description)
212
+ for key in outs:
213
+ text_output=text_output+'--'+ outs[key]
214
+ else:
215
+ text_output=''
216
+
217
+
218
+
219
+
220
+ mx,outs=self.get_ptedict_proba(description+' '+text_output)
221
+
222
+ return text_output,mx,outs
223
+
224
+
225
+ def predictAPI(self,description,is_input=False,istrans=False):
226
+ if istrans:
227
+ description=self.to_tran(description)
228
+
229
+ clean_description,_=self.clean_dataAPI(description,'',is_input=is_input)
230
+
231
+ try:
232
+ features=self.obMP.obVec.transform(clean_description)
233
+ yp=self.Model.predict(features)
234
+ txttec=self.obMP.Classes[yp[0]]
235
+ dis=self.DES[txttec]
236
+ except:
237
+ txttec='No'
238
+ dis=" ....."
239
+ return txttec,dis
240
+ def predict(self,description,is_input=False,istrans=False):
241
+ if istrans:
242
+ description=self.to_tran(description)
243
+
244
+ clean_description,_=self.clean_data([(description,' ')],'',is_input=is_input)
245
+
246
+ try:
247
+ features=self.obMP.obVec.transform(clean_description)
248
+ yp=self.Model.predict(features)
249
+ txttec=self.obMP.Classes[yp[0]]
250
+ except:
251
+ txttec='No'
252
+ return txttec
253
+
254
+ def ptedict_proba(self,description,mx=[],is_input=False,istrans=False):
255
+ if istrans:
256
+ description=self.to_tran(description)
257
+
258
+ clean_description,_=self.clean_data([(description,' ')],'',is_input=is_input)
259
+ try:
260
+ features=self.obMP.obVec.transform(clean_description)
261
+ mx=self.Model.predict_proba(features)
262
+ print(np.int16(mx*100))
263
+ yp=np.argmax(mx)
264
+ print(yp)
265
+
266
+ txttec='Technique : '+ self.obMP.Classes[yp]
267
+ except:
268
+ txttec='No Found technique ...! (^_^)'
269
+ return txttec
270
+
271
+
272
+
273
+ def get_ptedict_proba(self,description,mx=[]):
274
+ clean_description,_=self.clean_data([(description,' ')],'')
275
+
276
+ try:
277
+ features=self.obMP.obVec.transform(clean_description)
278
+ mx=self.obMP.obSVML.predict_proba(features)
279
+ yk=self.obMP.obSVMK.predict(features)
280
+
281
+
282
+ # yp=np.argmax(mx)
283
+
284
+
285
+ outputs={'svmK':self.obMP.Classes[yk[0]]}
286
+ except:
287
+ txttec='No Found technique ...! (^_^)'
288
+ outputs={}
289
+ return mx,outputs
290
+
291
+ def get_ptedict_threemodel(self,description):
292
+ clean_description,_=self.clean_data([(description,' ')],'')
293
+
294
+ try:
295
+ features=self.obMP.obVec.transform(clean_description)
296
+ yl=self.obMP.obSVML.predict(features)
297
+ yk=self.obMP.obSVMK.predict(features)
298
+ ym=self.obMP.oblogict.predict(features)
299
+
300
+
301
+ outputs={'svmL':self.obMP.Classes[yl[0]],
302
+ 'svmK':self.obMP.Classes[yk[0]],
303
+ 'logstick':self.obMP.Classes[ym[0]]
304
+ }
305
+ except:
306
+ print('No Found technique ...! (^_^)' )
307
+ outputs={}
308
+ return outputs
309
+
310
+
311
+ def verification(self,inputs=[],outputs=[]):
312
+ out_prodect=TEC.createOuts()
313
+ unprocess=0
314
+ meta={"tf":TEC.createOuts(),"num":TEC.createOuts()}
315
+ names=list(self.obMP.Classes)
316
+ for i in range(len(outputs)):
317
+ try:
318
+ outs=self.get_ptedict_threemodel(inputs[i])
319
+ target=outputs[i].strip()
320
+ names.index(target)
321
+ outs['target']=target
322
+
323
+
324
+ for key in outs:
325
+
326
+ out_prodect[key].append(outs[key])
327
+ meta['tf'][key].append(int(outs[key]==target))
328
+ meta['num'][key].append(names.index(outs[key]))
329
+
330
+
331
+
332
+
333
+ except :
334
+ unprocess+=1
335
+
336
+ scores={}
337
+ for key in meta['num']:
338
+ if key!='target':
339
+ scores[key]=self.valmodel(meta['num']['target'],meta['num'][key],' model '+key)
340
+
341
+
342
+ return out_prodect,meta,scores
343
+ def valmodel(self,y,yp,titel=" "):
344
+ print('---------------'+titel+'------------------------' )
345
+ cr=classification_report(y, yp)
346
+ print(cr)
347
+ scores={}
348
+ scores['accuracy']=accuracy_score(y, yp)
349
+ scores['f1_score']=f1_score(y, yp, average="macro")
350
+ scores['precision']=precision_score(y, yp, average="macro")
351
+ scores['recall']=recall_score(y, yp, average="macro")
352
+ return {'smmray':cr,'scores':scores}
353
+ #----------------------
354
+ def ChangeModel(self,ob=None):
355
+ if ob==None:return
356
+ if type(ob) is not str:
357
+ self.Model=ob
358
+ else :
359
+ if ob=='svmL':
360
+ self.Model=self.obMP.obSVML
361
+ elif ob=='svmK':
362
+ self.Model=self.obMP.obSVMK
363
+ else:
364
+ self.Model=self.obMP.oblogict
365
+
366
+ #------------------------------
367
+
368
+ def Search(self):
369
+ txt=input('Enter any text :')
370
+ print('Technique:'+ self.predict(txt))
371
+
372
+
373
+ def Info_Models(self):
374
+ print('Number Data is ',self.obMP.X.shape)
375
+ print('Number of classes :',len(self.obMP.Classes))
376
+ print ('---------simples -------------------')
377
+ n=len(self.obMP.Classes)
378
+ f=n%2
379
+ n=n-f
380
+ for i in range(0,n,2):
381
+ print( (self.obMP.Classes[i], np.sum(np.int16(self.obMP.Y==i))),'------------------',(self.obMP.Classes[i+1], np.sum(np.int16(self.obMP.Y==i+1))))
382
+
383
+ if f==1: print( (self.obMP.Classes[i+2], np.sum(np.int16(self.obMP.Y==i+2))))
384
+
385
+ def DlistModel(self):
386
+ print ('SVC(kernel=\'linear\')-> svmL')
387
+ print('LinearSVC(C=1.0) -> svmK ')
388
+ print('LogisticRegression() -> logic')
ASG.API/ModelsObs.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from ModelTEC import *
2
+
3
+ import pickle
4
+ from TypeModels import TypeModel
5
+ from BasePath import BASEPATH
6
+
7
+
8
+ MST=TEC(typemodel="svmL",model_setting=TypeModel['technique'])
ASG.API/TTs.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e6d068bd7128bf11f9d539266ecf0510582bef0a1f4a1c79e8be750765454359
3
+ size 2075
ASG.API/TecModel_API.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:38cc340c52bdad72ec621acfee3dbc7e0dd9c276f19be4c8837c8d582225320a
3
+ size 22410842
ASG.API/TypeModels.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class ModelSetting:
2
+ def __init__(self,name="",path_model="",path_Qwords=""):
3
+ self.name=name
4
+ self.path_model=path_model
5
+ self.path_Qwords=path_Qwords
6
+
7
+ from BasePath import BASEPATH
8
+
9
+ TypeModel={
10
+ 'group':ModelSetting(name='Group',path_model=BASEPATH+"groupModel_API.pkl",path_Qwords=BASEPATH+"listdesgroupModel_API.pkl"),
11
+ 'technique':ModelSetting(name='Technique',path_model=BASEPATH+"TecModel_API.pkl",path_Qwords=BASEPATH+"listdesTecModel_API.pkl"),
12
+ 'software':ModelSetting(name='Software',path_model=BASEPATH+"sofwareModel_API.pkl",path_Qwords=BASEPATH+"listdessofwareModel_API.pkl")
13
+ }
14
+
15
+
16
+
17
+ FormModels={TypeModel['group'].name:
18
+ {'name':'FormGroupS',
19
+ 'coldata' : [
20
+ {"text": "num", "stretch": False,"width":50},
21
+
22
+ "Tactic Name"
23
+ ,
24
+ "Technique Name",
25
+ "Group Name",
26
+ "Score "
27
+ ]
28
+ ,
29
+ 'msgs':['''• Refers to the search for the highest technique similar to the nature of the specific input.''',
30
+ '''• Determining the threshold, which is a value between 0 and 1 that allows the width of more than one technique that can be similar to the nature of the input. ''',
31
+ ''' Techniques can be searched in two ways''',
32
+ '''The table shows each technique with the tactic to which it belongs and the score that determines the good prediction probability value in percentage. ''',
33
+ '''The interface allows the user to enter a description of a technique or a group of techniques that serve the same purpose. The user can also enter the program that uses the technique and predicts the most appropriate technique.'''
34
+ ]
35
+ ,'placeholder':' , softwares and groups '
36
+ },
37
+ #2
38
+ TypeModel['technique'].name:
39
+ {'name':'FormTechniqueS',
40
+ 'coldata' : [
41
+ {"text": "num", "stretch": False,"width":50},
42
+
43
+ "Tactic Name"
44
+ ,
45
+ "Technique Name",
46
+
47
+ "Score "
48
+ ]
49
+ ,
50
+ 'msgs':['''• Refers to the search for the highest technique similar to the nature of the specific input.''',
51
+ '''• Determining the threshold, which is a value between 0 and 1 that allows the width of more than one technique that can be similar to the nature of the input. ''',
52
+ ''' Techniques can be searched in two ways''',
53
+ '''The table shows each technique with the tactic to which it belongs and the score that determines the good prediction probability value in percentage. ''',
54
+ '''The interface allows the user to enter a description of a technique or a group of techniques that serve the same purpose. The user can also enter the program that uses the technique and predicts the most appropriate technique.'''
55
+ ]
56
+ ,'placeholder':'.'
57
+ }
58
+
59
+
60
+
61
+ #3
62
+ ,TypeModel['software'].name:
63
+ {'name':'FormTechniqueS',
64
+ 'coldata' : [
65
+ {"text": "num", "stretch": False,"width":50},
66
+ "Software Name"
67
+ ,
68
+ "Score "
69
+ ]
70
+ ,
71
+ 'msgs':['''• Refers to the search for the highest program similar to the nature of the selected input text.''',
72
+ '''• Setting the threshold, which is a value between 0 and 1 that allows the display of more than one program that can be similar to the nature of the text entered. ''',
73
+ '''The program can be searched in two ways ''',
74
+ '''The table shows the name of the program and the score that determines the probability value of a good forecast, which is a percentage value''',
75
+ '''The interface allows the user to enter a description of a program or a group of programs within the MITER ATT & CK that serves the same purpose. The user can also enter techniques that may be within the series of program scenarios.''']
76
+
77
+ ,'placeholder':' and softwares'
78
+ },
79
+
80
+ }
ASG.API/__pycache__/AModelScenoariotree.cpython-39.pyc ADDED
Binary file (1.17 kB). View file
 
ASG.API/__pycache__/ASGModels.cpython-39.pyc ADDED
Binary file (2.36 kB). View file
 
ASG.API/__pycache__/BasePath.cpython-39.pyc ADDED
Binary file (295 Bytes). View file
 
ASG.API/__pycache__/MCheakscenario.cpython-39.pyc ADDED
Binary file (3.66 kB). View file
 
ASG.API/__pycache__/MScenoariotree.cpython-39.pyc ADDED
Binary file (7.24 kB). View file
 
ASG.API/__pycache__/ModelTEC.cpython-39.pyc ADDED
Binary file (9.94 kB). View file
 
ASG.API/__pycache__/ModelsObs.cpython-39.pyc ADDED
Binary file (363 Bytes). View file
 
ASG.API/__pycache__/TypeModels.cpython-39.pyc ADDED
Binary file (2.67 kB). View file
 
ASG.API/dataSM.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a4bd82ccd036a2882a34ab3f15b0d946c552968d424993b76c91290d9758280d
3
+ size 133931
ASG.API/groupModel_API.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:62fdd85ebbf478200e5b62e6d4d0d14b0e277d4246529fcb1000e570f6da8d80
3
+ size 661391
ASG.API/listdesTecModel_API.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d922166eea668091cece614ed1d70ccd76de977bbe36e4631def93c11746b617
3
+ size 81302
ASG.API/listdesgroupModel_API.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f83dd8e6e08e1a184113379461dc9fe9f9b9b2071e8165c03435ef1d27d0e1e
3
+ size 10576
ASG.API/listdessofwareModel_API.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33ec00988f89fa6d4a76ea2e08fa580daf2230f2c4d61a21e06f7c1c64ed38a2
3
+ size 9525
ASG.API/sofwareModel_API.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df5fa4fa7d4879c0c6bc3effb79e7231749f550203a2242bf00218e50181bc78
3
+ size 1199576
ASG.API/tecbyTectics.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1eef0005b2f4ad1c2053c1a1052353b25ed20e358821e2ca474791f189655f72
3
+ size 2160