-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvuln_detection.py
262 lines (230 loc) · 8.55 KB
/
vuln_detection.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
import os
# Directory and file structure
structure = {
"malware_detection_project": {
"config": {
"api_config.json": '''{
"cve_api_url": "https://cve.circl.lu/api/cve/",
"virustotal_api_key": "your_virustotal_api_key",
"exploit_db_api_url": "https://www.exploit-db.com/",
"network_analysis_tool": "nmap",
"apk_analysis_tool": "apktool"
}''',
"model_config.json": '''{
"model_type": "RandomForest",
"n_estimators": 100,
"test_size": 0.2,
"random_state": 42
}'''
},
"data": {
"cve_data.json": '''{
"CVE-2024-1234": {
"score": 9.8,
"description": "Critical vulnerability in XYZ",
"exploitability": 10
},
"CVE-2024-5678": {
"score": 6.5,
"description": "Moderate vulnerability in ABC",
"exploitability": 6
}
}''',
"exploit_data.json": '''{
"CVE-2024-1234": {
"exploit_available": true
},
"CVE-2024-5678": {
"exploit_available": false
}
}''',
"virustotal_data.json": '''{
"hash_1": {
"malicious": 1,
"harmless": 0,
"suspicious": 0
},
"hash_2": {
"malicious": 0,
"harmless": 1,
"suspicious": 0
}
}''',
"network_data.json": '''{
"192.168.1.1": {
"open_ports": 3,
"vulnerable_services": 1,
"traffic_pattern": "anomalous"
},
"192.168.1.2": {
"open_ports": 2,
"vulnerable_services": 0,
"traffic_pattern": "normal"
}
}''',
"apk_data.json": '''{
"apk_1": {
"permissions": 5,
"malicious_activity": 1,
"obfuscation_level": 7
},
"apk_2": {
"permissions": 3,
"malicious_activity": 0,
"obfuscation_level": 4
}
}'''
},
"src": {
"logger.py": '''import logging
def setup_logger():
logger = logging.getLogger('MalwareDetectionLogger')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler('malware_detection.log')
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
logger = setup_logger()
''',
"data_fetcher.py": '''import json
from .logger import logger
def load_data(file_path):
logger.info(f"Loading data from {file_path}")
try:
with open(file_path, 'r') as file:
data = json.load(file)
return data
except FileNotFoundError:
logger.error(f"File not found: {file_path}")
return {}
except json.JSONDecodeError:
logger.error(f"Error decoding JSON from {file_path}")
return {}
def fetch_cve_data():
return load_data('data/cve_data.json')
def fetch_exploit_data():
return load_data('data/exploit_data.json')
def fetch_virustotal_data():
return load_data('data/virustotal_data.json')
def fetch_network_data():
return load_data('data/network_data.json')
def fetch_apk_data():
return load_data('data/apk_data.json')
''',
"feature_engineering.py": '''import pandas as pd
from .logger import logger
def create_feature_set(cve_data, exploit_data, vt_data, network_data, apk_data):
logger.info("Creating feature set from the raw data")
records = []
for cve_id, cve_details in cve_data.items():
vt_record = vt_data.get('hash_1', {})
exploit_record = exploit_data.get(cve_id, {})
network_record = network_data.get('192.168.1.1', {})
apk_record = apk_data.get('apk_1', {})
record = {
'cve_score': cve_details.get('score', 0),
'exploitability': cve_details.get('exploitability', 0),
'exploit_available': int(exploit_record.get('exploit_available', False)),
'malicious': vt_record.get('malicious', 0),
'harmless': vt_record.get('harmless', 0),
'suspicious': vt_record.get('suspicious', 0),
'open_ports': network_record.get('open_ports', 0),
'vulnerable_services': network_record.get('vulnerable_services', 0),
'traffic_pattern_anomalous': 1 if network_record.get('traffic_pattern') == 'anomalous' else 0,
'permissions': apk_record.get('permissions', 0),
'malicious_activity': apk_record.get('malicious_activity', 0),
'obfuscation_level': apk_record.get('obfuscation_level', 0),
'is_vulnerable': 1 if cve_details.get('score', 0) > 7 else 0
}
records.append(record)
df = pd.DataFrame(records)
logger.info(f"Feature set created with {df.shape[0]} records")
return df
''',
"model_trainer.py": '''from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from .logger import logger
import json
def load_model_config():
logger.info("Loading model configuration")
with open('config/model_config.json', 'r') as file:
return json.load(file)
def train_model(df):
logger.info("Starting model training")
config = load_model_config()
X = df.drop('is_vulnerable', axis=1)
y = df['is_vulnerable']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=config['test_size'], random_state=config['random_state'])
model = RandomForestClassifier(n_estimators=config['n_estimators'], random_state=config['random_state'])
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
logger.info(f"Model training completed with accuracy: {accuracy * 100:.2f}%")
return model
''',
"predictor.py": '''import pandas as pd
from .logger import logger
def predict_vulnerability(model, cve_data, exploit_data, vt_data, network_data, apk_data):
logger.info("Starting prediction on new data")
input_data = pd.DataFrame([{
'cve_score': cve_data.get('score', 0),
'exploitability': cve_data.get('exploitability', 0),
'exploit_available': int(exploit_data.get('exploit_available', False)),
'malicious': vt_data.get('malicious', 0),
'harmless': vt_data.get('harmless', 0),
'suspicious': vt_data.get('suspicious', 0),
'open_ports': network_data.get('open_ports', 0),
'vulnerable_services': network_data.get('vulnerable_services', 0),
'traffic_pattern_anomalous': 1 if network_data.get('traffic_pattern') == 'anomalous' else 0,
'permissions': apk_data.get('permissions', 0),
'malicious_activity': apk_data.get('malicious_activity', 0),
'obfuscation_level': apk_data.get('obfuscation_level', 0)
}])
prediction = model.predict(input_data)
logger.info(f"Prediction result: {'Vulnerable' if prediction[0] == 1 else 'Not Vulnerable'}")
return prediction[0]
'''
},
"main.py": '''from src.data_fetcher import fetch_cve_data, fetch_exploit_data, fetch_virustotal_data, fetch_network_data, fetch_apk_data
from src.feature_engineering import create_feature_set
from src.model_trainer import train_model
from src.predictor import predict_vulnerability
from src.logger import logger
if __name__ == '__main__':
logger.info("Starting Malware Detection Project")
# Fetch data
cve_data = fetch_cve_data()
exploit_data = fetch_exploit_data()
vt_data = fetch_virustotal_data()
network_data = fetch_network_data()
apk_data = fetch_apk_data()
# Create features
features_df = create_feature_set(cve_data, exploit_data, vt_data, network_data, apk_data)
# Train model
model = train_model(features_df)
# Predict on a new example (using first entry in cve_data for illustration)
if cve_data:
first_cve = next(iter(cve_data.values()))
prediction = predict_vulnerability(model, first_cve, exploit_data.get('CVE-2024-1234', {}), vt_data.get('hash_1', {}), network_data.get('192.168.1.1', {}), apk_data.get('apk_1', {}))
logger.info(f"Prediction for first CVE: {'Vulnerable' if prediction == 1 else 'Not Vulnerable'}")
else:
logger.warning("No CVE data available for prediction")
'''
}
}
# Create directories and files
def create_structure(base_path, structure):
for name, content in structure.items():
path = os.path.join(base_path, name)
if isinstance(content, dict):
os.makedirs(path, exist_ok=True)
create_structure(path, content)
else:
with open(path, 'w') as file:
file.write(content)
# Usage
base_path = "malware_detection_project"
create_structure(base_path, structure)