Proxy_VPN.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. # -*- coding: utf-8 -*-
  2. import socket
  3. import threading
  4. import select
  5. import sys
  6. import time
  7. import itertools
  8. import os
  9. import ssl
  10. # --- CONFIGURACIÓN BASE ---
  11. LISTENING_PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 443
  12. SSH_HOST = '127.0.0.1'
  13. SSH_PORT = 22 # Asegúrate de que este es tu puerto SSH/Dropbear
  14. LOG_FILE = "/root/proxy.log"
  15. MAX_LOG_SIZE = 10 * 1024 * 1024
  16. # --- CONFIGURACIÓN SSL/TLS ---
  17. USE_SSL = True
  18. CERT_FILE = "/root/cert.pem"
  19. KEY_FILE = "/root/key.pem"
  20. # --- CONFIGURACIÓN DE SEGURIDAD AVANZADA ---
  21. MAX_CONNECTIONS = 150 # Ligeramente aumentado
  22. CONNECTION_COOLDOWN = 0.7
  23. BUFLEN = 16384
  24. AUTO_BAN_STRIKES = 3
  25. BAN_TIME = 3600
  26. banned_ips_memory = {}
  27. ip_strikes = {}
  28. ALLOWED_IPS = []
  29. # --- RESPUESTA FAKE WEB (ANTI ACTIVE PROBING) ---
  30. FAKE_WEB_RESPONSE = (
  31. b"HTTP/1.1 200 OK\r\n"
  32. b"Server: nginx/1.21.0\r\n"
  33. b"Content-Type: text/html; charset=UTF-8\r\n"
  34. b"Connection: close\r\n\r\n"
  35. b"<!DOCTYPE html>\n<html>\n<head><title>Bienvenido</title></head>\n"
  36. b"<body style='text-align:center; padding:50px; font-family:sans-serif;'>\n"
  37. b"<h1>Hola</h1>\n<p>Servicio en funcionamiento.</p>\n"
  38. b"</body>\n</html>\n"
  39. )
  40. # --- CUSTOM HEADERS PARA VPN ---
  41. CUSTOM_HEADERS = {
  42. "Server": "nginx/1.21.0",
  43. "X-Forwarded-For": "127.0.0.1",
  44. "Content-Type": "text/html; charset=UTF-8",
  45. "Proxy-Connection": "keep-alive",
  46. "Cache-Control": "no-cache",
  47. "X-Proxy-Agent": "Gemini-Ultra-Robust-v7-HA",
  48. "X-Forwarded-For-Proxy": "True"
  49. }
  50. MENSAJES = [
  51. "🚀 CONEXION TLS ESTABLECIDA",
  52. "🛡️ CIFRADO MILITAR ACTIVO",
  53. "🔋 MODO SIGILO SSL OK",
  54. "Pfsense",
  55. "OPNsense",
  56. "VyOS",
  57. "Claro",
  58. "Windows Server",
  59. "BSD Free",
  60. "VyOS",
  61. "Altice",
  62. "Viva",
  63. "Google",
  64. "VyOS",
  65. "TNSR",
  66. "🌐 BYPASS DE FIREWALL OK"
  67. ]
  68. mensaje_cycle = itertools.cycle(MENSAJES)
  69. cycle_lock = threading.Lock()
  70. def log(msg, addr=None):
  71. try:
  72. if os.path.exists(LOG_FILE) and os.path.getsize(LOG_FILE) > MAX_LOG_SIZE:
  73. with open(LOG_FILE, 'w') as f: f.write(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] LOG REINICIADO\n")
  74. timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
  75. client_info = f" [{addr[0]}]" if addr else ""
  76. log_entry = f"[{timestamp}]{client_info} {msg}\n"
  77. with open(LOG_FILE, 'a') as f: f.write(log_entry)
  78. except: pass
  79. active_connections = 0
  80. conn_lock = threading.Lock()
  81. class ConnectionHandler(threading.Thread):
  82. def __init__(self, client_socket, addr):
  83. super().__init__(daemon=True)
  84. self.client = client_socket
  85. self.addr = addr
  86. self.target = None
  87. self.tx_bytes = 0
  88. self.rx_bytes = 0
  89. def build_http_response(self, status_msg):
  90. headers_str = "".join([f"{k}: {v}\r\n" for k, v in CUSTOM_HEADERS.items()])
  91. return (f"HTTP/1.1 101 {status_msg}\r\n{headers_str}Connection: Upgrade\r\nUpgrade: websocket\r\n\r\n").encode('utf-8')
  92. def run(self):
  93. global active_connections
  94. client_ip = self.addr[0]
  95. try:
  96. if client_ip in banned_ips_memory:
  97. if time.time() > banned_ips_memory[client_ip]:
  98. del banned_ips_memory[client_ip]
  99. if client_ip in ip_strikes: del ip_strikes[client_ip]
  100. else: return
  101. now = time.time()
  102. if client_ip in ip_strikes and (now - ip_strikes.get('last_time', 0)) < CONNECTION_COOLDOWN:
  103. ip_strikes[client_ip] = ip_strikes.get(client_ip, 0) + 1
  104. if ip_strikes[client_ip] >= AUTO_BAN_STRIKES:
  105. banned_ips_memory[client_ip] = time.time() + BAN_TIME
  106. log(f"⛔ IP Baneada por Flood/Escaneo: {client_ip}", self.addr)
  107. return
  108. ip_strikes['last_time'] = now
  109. ip_strikes[client_ip] = 0
  110. self.client.settimeout(2.0)
  111. payload = b""
  112. try:
  113. payload = self.client.recv(BUFLEN)
  114. except socket.timeout:
  115. pass # NetMod en silencio
  116. except Exception:
  117. return
  118. try:
  119. self.target = socket.create_connection((SSH_HOST, SSH_PORT), timeout=10)
  120. except Exception as e:
  121. log(f"❌ Error interno destino SSH: {e}", self.addr)
  122. return
  123. if payload:
  124. if payload.startswith(b"SSH-"):
  125. self.target.sendall(payload)
  126. elif b"HTTP/" in payload and b"Upgrade: websocket" not in payload:
  127. log(f"🕵️ Escáner detectado. Respondiendo Fake Web.", self.addr)
  128. self.client.sendall(FAKE_WEB_RESPONSE)
  129. return
  130. else:
  131. with cycle_lock: current_status = next(mensaje_cycle)
  132. self.client.sendall(self.build_http_response(current_status))
  133. self.tunnel()
  134. except Exception as e: pass
  135. finally:
  136. with conn_lock: active_connections -= 1
  137. self.cleanup()
  138. def tunnel(self):
  139. self.client.settimeout(None)
  140. self.target.settimeout(None)
  141. sockets = [self.client, self.target]
  142. while True:
  143. readable, _, error = select.select(sockets, [], sockets, 300)
  144. if error or not readable: break
  145. for s in readable:
  146. try:
  147. data = s.recv(BUFLEN)
  148. if not data: return
  149. if s is self.client:
  150. self.target.sendall(data)
  151. self.tx_bytes += len(data)
  152. else:
  153. self.client.sendall(data)
  154. self.rx_bytes += len(data)
  155. except: return
  156. def cleanup(self):
  157. total_mb = (self.tx_bytes + self.rx_bytes) / (1024 * 1024)
  158. if total_mb > 0.05: log(f"[*] Tráfico finalizado: {total_mb:.2f} MB", self.addr)
  159. for s in [self.client, self.target]:
  160. if s:
  161. try: s.close()
  162. except: pass
  163. def main():
  164. global active_connections
  165. ssl_context = None
  166. if USE_SSL:
  167. try:
  168. ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  169. ssl_context.load_cert_chain(certfile=CERT_FILE, keyfile=KEY_FILE)
  170. except Exception as e:
  171. print(f"Error crítico cargando certificados SSL: {e}")
  172. sys.exit(1)
  173. try:
  174. addr_info = socket.getaddrinfo(None, LISTENING_PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
  175. addr_info.sort(key=lambda x: x[0] == socket.AF_INET6, reverse=True)
  176. af, socktype, proto, canonname, sa = addr_info[0]
  177. server = socket.socket(af, socktype, proto)
  178. server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  179. if af == socket.AF_INET6:
  180. try: server.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
  181. except: pass
  182. server.bind(sa)
  183. server.listen(500) # Aumentado el backlog para soportar ráfagas de bots
  184. print(f"=====================================================")
  185. print(f"🔥 Servidor Robusto INMORTAL Iniciado - Puerto {LISTENING_PORT}")
  186. print(f"🛡️ Motor SSL/TLS & Anti-Crash: ACTIVADO")
  187. print(f"=====================================================")
  188. # EL BUCLE PRINCIPAL AHORA ES BLINDADO
  189. while True:
  190. try:
  191. client, addr = server.accept()
  192. if USE_SSL:
  193. try:
  194. client = ssl_context.wrap_socket(client, server_side=True)
  195. except Exception:
  196. # Si el bot manda basura en lugar de un handshake SSL, se cierra y se ignora silenciosamente.
  197. client.close()
  198. continue
  199. with conn_lock:
  200. if active_connections >= MAX_CONNECTIONS:
  201. client.close()
  202. continue
  203. active_connections += 1
  204. ConnectionHandler(client, addr).start()
  205. except socket.error as e:
  206. # Si Linux se queda sin recursos por 1 segundo por un ataque DDoS,
  207. # esperamos 50ms y volvemos a intentarlo en lugar de apagar el script.
  208. time.sleep(0.05)
  209. continue
  210. except Exception as e:
  211. time.sleep(1)
  212. continue
  213. except Exception as e:
  214. print(f"Error fatal: {e}")
  215. finally:
  216. server.close()
  217. if __name__ == "__main__":
  218. main()