-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprediction.py
More file actions
172 lines (143 loc) · 5.81 KB
/
prediction.py
File metadata and controls
172 lines (143 loc) · 5.81 KB
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
import pickle
import numpy as np
import sys
import os
import json
import re
class PredictionModel:
def __init__(self, model_path='obfuscation_model.pkl', encoder_path='label_encoder.pkl'):
try:
with open(model_path, 'rb') as f:
self.model = pickle.load(f)
with open(encoder_path, 'rb') as f:
self.label_encoder = pickle.load(f)
except:
print("[X] Model files not found. Please ensure the model has been installed")
sys.exit(1)
def predict(self, param1, param2, param3, param4 , param5 , param6 , param7 , param8):
try:
features = np.array([[float(param1), float(param2), float(param3), float(param4), float(param5), float(param6) , float(param7) , float(param8)]])
prediction = self.model.predict(features)
result = self.label_encoder.inverse_transform(prediction)[0]
confidence = self.model.predict_proba(features)[0]
return result, max(confidence)
except:
raise print("[X] Invalid input, all parameters must be numeric")
url_regex = re.compile(r"https?://[^\s/$.?#].[^\s]*", re.IGNORECASE)
windows_file_regex = re.compile(r"[a-zA-Z]:(\\[^\s<>:\"/\\|?*]+)+\\?")
unix_file_regex = re.compile(r"(/[^/\0]+)+/?")
def generate_parameters(line):
alnum_count = 0
quote_count = 0
slash_count = 0
word_count = 0
lower_case_letters = 0
upper_case_letters = 0
currently_word_active = False
url_present = 0
file_path_present = 0
non_ascii_count = 0
ascii_count = 0
if url_regex.search(line):
url_present = 1
if windows_file_regex.search(line) or unix_file_regex.search(line):
file_path_present = 1
for char in line:
if ord(char) > 127 or ord(char) < 0:
non_ascii_count = non_ascii_count + 1
else:
ascii_count = ascii_count + 1
if char.isalnum():
alnum_count = alnum_count + 1
if currently_word_active == False:
currently_word_active = True
word_count = word_count + 1
if char.islower():
lower_case_letters = lower_case_letters + 1
if char.isupper():
upper_case_letters = upper_case_letters + 1
else:
currently_word_active = False
if char == "'" or char == '"':
quote_count = quote_count + 1
if char == r"\\" or char == r"/":
slash_count = slash_count + 1
quote_alnum = quote_count/alnum_count
slash_alnum = slash_count/alnum_count
word_alnum = word_count/alnum_count
special_ratio = len(line)/alnum_count
lower_upper_ratio = ((lower_case_letters - upper_case_letters)**2)
ascii_ratio = non_ascii_count/ascii_count
return (quote_alnum,slash_alnum,word_alnum,special_ratio,lower_upper_ratio,url_present,file_path_present,ascii_ratio)
try:
predictor = PredictionModel()
result, confidence = predictor.predict(*sys.argv[1:5])
print(f"\nPrediction: {result}")
print(f"Confidence: {confidence:.2%}")
except Exception as e:
print(f"Error: {str(e)}")
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
print("Argfuscation Detector")
print("-------------------------------")
try:
predictor = PredictionModel()
except Exception as e:
print(f"Error initializing model: {str(e)}")
def menu():
print("\nOptions:")
print("1. Make prediction")
print("2. Batch prediction from file")
print("3. Clear screen")
print("4. Exit")
menu()
while True:
choice = input("\nEnter your choice (1-4): ").strip()
if choice == '4':
print("[*] Quitting")
quit()
elif choice == '1':
try:
command = input("[*] Input the command: ")
params = generate_parameters(command)
result, confidence = predictor.predict(params[0], params[1], params[2], params[3], params[4], params[5] , params[6] , params[7])
print("\n[!] Prediction Results:")
print(f"[!] Classification: {result}")
print(f"[!] Confidence: {confidence:.2%}")
except Exception as e:
print(f"\n[X] An error occurred: {str(e)}")
elif choice == '2':
try:
filename = input("[*] Enter the path to your input file: ").strip()
output_file = input("[*] Enter the path for results file: ").strip()
if os.path.isfile(filename):
with open(filename , "r") as f:
lines = f.readlines()
for line in lines:
line = line.strip()
if line:
params = generate_parameters(line)
result, confidence = predictor.predict(params[0], params[1], params[2], params[3], params[4])
result_json = {
"command":str(line),
"verdict":str(result),
"confidence":str(confidence)}
with open(output_file , "a") as ff:
ff.write(json.dumps(result_json))
ff.write("\n")
else:
print(f"[!] All results written to {output_file}")
else:
print("[X] Input file path specified does not exist")
except Exception as e:
print(f"[X] Error processing file: {str(e)}")
elif choice == '3':
menu()
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
else:
print("\nInvalid choice. Please enter 1, 2, 3 or 4.")