Proxy-ssl.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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.5
  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. "🌐 BYPASS DE FIREWALL OK"
  55. ]
  56. mensaje_cycle = itertools.cycle(MENSAJES)
  57. cycle_lock = threading.Lock()
  58. def log(msg, addr=None):
  59. try:
  60. if os.path.exists(LOG_FILE) and os.path.getsize(LOG_FILE) > MAX_LOG_SIZE:
  61. with open(LOG_FILE, 'w') as f: f.write(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] LOG REINICIADO\n")
  62. timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
  63. client_info = f" [{addr[0]}]" if addr else ""
  64. log_entry = f"[{timestamp}]{client_info} {msg}\n"
  65. with open(LOG_FILE, 'a') as f: f.write(log_entry)
  66. except: pass
  67. active_connections = 0
  68. conn_lock = threading.Lock()
  69. class ConnectionHandler(threading.Thread):
  70. def __init__(self, client_socket, addr):
  71. super().__init__(daemon=True)
  72. self.client = client_socket
  73. self.addr = addr
  74. self.target = None
  75. self.tx_bytes = 0
  76. self.rx_bytes = 0
  77. def build_http_response(self, status_msg):
  78. headers_str = "".join([f"{k}: {v}\r\n" for k, v in CUSTOM_HEADERS.items()])
  79. return (f"HTTP/1.1 101 {status_msg}\r\n{headers_str}Connection: Upgrade\r\nUpgrade: websocket\r\n\r\n").encode('utf-8')
  80. def run(self):
  81. global active_connections
  82. client_ip = self.addr[0]
  83. try:
  84. if client_ip in banned_ips_memory:
  85. if time.time() > banned_ips_memory[client_ip]:
  86. del banned_ips_memory[client_ip]
  87. if client_ip in ip_strikes: del ip_strikes[client_ip]
  88. else: return
  89. now = time.time()
  90. if client_ip in ip_strikes and (now - ip_strikes.get('last_time', 0)) < CONNECTION_COOLDOWN:
  91. ip_strikes[client_ip] = ip_strikes.get(client_ip, 0) + 1
  92. if ip_strikes[client_ip] >= AUTO_BAN_STRIKES:
  93. banned_ips_memory[client_ip] = time.time() + BAN_TIME
  94. log(f"⛔ IP Baneada por Flood/Escaneo: {client_ip}", self.addr)
  95. return
  96. ip_strikes['last_time'] = now
  97. ip_strikes[client_ip] = 0
  98. self.client.settimeout(2.0)
  99. payload = b""
  100. try:
  101. payload = self.client.recv(BUFLEN)
  102. except socket.timeout:
  103. pass # NetMod en silencio
  104. except Exception:
  105. return
  106. try:
  107. self.target = socket.create_connection((SSH_HOST, SSH_PORT), timeout=10)
  108. except Exception as e:
  109. log(f"❌ Error interno destino SSH: {e}", self.addr)
  110. return
  111. if payload:
  112. if payload.startswith(b"SSH-"):
  113. self.target.sendall(payload)
  114. elif b"HTTP/" in payload and b"Upgrade: websocket" not in payload:
  115. log(f"🕵️ Escáner detectado. Respondiendo Fake Web.", self.addr)
  116. self.client.sendall(FAKE_WEB_RESPONSE)
  117. return
  118. else:
  119. with cycle_lock: current_status = next(mensaje_cycle)
  120. self.client.sendall(self.build_http_response(current_status))
  121. self.tunnel()
  122. except Exception as e: pass
  123. finally:
  124. with conn_lock: active_connections -= 1
  125. self.cleanup()
  126. def tunnel(self):
  127. self.client.settimeout(None)
  128. self.target.settimeout(None)
  129. sockets = [self.client, self.target]
  130. while True:
  131. readable, _, error = select.select(sockets, [], sockets, 300)
  132. if error or not readable: break
  133. for s in readable:
  134. try:
  135. data = s.recv(BUFLEN)
  136. if not data: return
  137. if s is self.client:
  138. self.target.sendall(data)
  139. self.tx_bytes += len(data)
  140. else:
  141. self.client.sendall(data)
  142. self.rx_bytes += len(data)
  143. except: return
  144. def cleanup(self):
  145. total_mb = (self.tx_bytes + self.rx_bytes) / (1024 * 1024)
  146. if total_mb > 0.05: log(f"[*] Tráfico finalizado: {total_mb:.2f} MB", self.addr)
  147. for s in [self.client, self.target]:
  148. if s:
  149. try: s.close()
  150. except: pass
  151. def main():
  152. global active_connections
  153. ssl_context = None
  154. if USE_SSL:
  155. try:
  156. ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  157. ssl_context.load_cert_chain(certfile=CERT_FILE, keyfile=KEY_FILE)
  158. except Exception as e:
  159. print(f"Error crítico cargando certificados SSL: {e}")
  160. sys.exit(1)
  161. try:
  162. addr_info = socket.getaddrinfo(None, LISTENING_PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
  163. addr_info.sort(key=lambda x: x[0] == socket.AF_INET6, reverse=True)
  164. af, socktype, proto, canonname, sa = addr_info[0]
  165. server = socket.socket(af, socktype, proto)
  166. server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  167. if af == socket.AF_INET6:
  168. try: server.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
  169. except: pass
  170. server.bind(sa)
  171. server.listen(500) # Aumentado el backlog para soportar ráfagas de bots
  172. print(f"=====================================================")
  173. print(f"🔥 Servidor Robusto INMORTAL Iniciado - Puerto {LISTENING_PORT}")
  174. print(f"🛡️ Motor SSL/TLS & Anti-Crash: ACTIVADO")
  175. print(f"=====================================================")
  176. # EL BUCLE PRINCIPAL AHORA ES BLINDADO
  177. while True:
  178. try:
  179. client, addr = server.accept()
  180. if USE_SSL:
  181. try:
  182. client = ssl_context.wrap_socket(client, server_side=True)
  183. except Exception:
  184. # Si el bot manda basura en lugar de un handshake SSL, se cierra y se ignora silenciosamente.
  185. client.close()
  186. continue
  187. with conn_lock:
  188. if active_connections >= MAX_CONNECTIONS:
  189. client.close()
  190. continue
  191. active_connections += 1
  192. ConnectionHandler(client, addr).start()
  193. except socket.error as e:
  194. # Si Linux se queda sin recursos por 1 segundo por un ataque DDoS,
  195. # esperamos 50ms y volvemos a intentarlo en lugar de apagar el script.
  196. time.sleep(0.05)
  197. continue
  198. except Exception as e:
  199. time.sleep(1)
  200. continue
  201. except Exception as e:
  202. print(f"Error fatal: {e}")
  203. finally:
  204. server.close()
  205. if __name__ == "__main__":
  206. main()