1
0

VPN.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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 # Puerto de SSH local
  14. LOG_FILE = "/root/proxy-ssl.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 = 200
  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 400 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>Error<</title></head>\n"
  36. b"<body style='text-align:center; padding:50px; font-family:sans-serif;'>\n"
  37. b"<h1>Hola</h1>\n<p>400 Bad Request</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-v6-TLS",
  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. print(log_entry.strip())
  79. except: pass
  80. active_connections = 0
  81. conn_lock = threading.Lock()
  82. class ConnectionHandler(threading.Thread):
  83. def __init__(self, client_socket, addr):
  84. super().__init__(daemon=True)
  85. self.client = client_socket
  86. self.addr = addr
  87. self.target = None
  88. self.tx_bytes = 0
  89. self.rx_bytes = 0
  90. def build_http_response(self, status_msg):
  91. headers_str = "".join([f"{k}: {v}\r\n" for k, v in CUSTOM_HEADERS.items()])
  92. return (f"HTTP/1.1 101 {status_msg}\r\n{headers_str}Connection: Upgrade\r\nUpgrade: websocket\r\n\r\n").encode('utf-8')
  93. def run(self):
  94. global active_connections
  95. client_ip = self.addr[0]
  96. try:
  97. if client_ip in banned_ips_memory:
  98. if time.time() > banned_ips_memory[client_ip]:
  99. del banned_ips_memory[client_ip]
  100. if client_ip in ip_strikes: del ip_strikes[client_ip]
  101. else: return
  102. now = time.time()
  103. if client_ip in ip_strikes and (now - ip_strikes.get('last_time', 0)) < CONNECTION_COOLDOWN:
  104. ip_strikes[client_ip] = ip_strikes.get(client_ip, 0) + 1
  105. if ip_strikes[client_ip] >= AUTO_BAN_STRIKES:
  106. banned_ips_memory[client_ip] = time.time() + BAN_TIME
  107. log(f"⛔ IP Baneada (Flood/Spam)", self.addr)
  108. return
  109. ip_strikes['last_time'] = now
  110. ip_strikes[client_ip] = 0
  111. self.client.settimeout(2.0)
  112. payload = b""
  113. try:
  114. payload = self.client.recv(BUFLEN)
  115. except socket.timeout:
  116. pass # NetMod en silencio (Modo Stunnel)
  117. except Exception:
  118. return
  119. try:
  120. self.target = socket.create_connection((SSH_HOST, SSH_PORT), timeout=10)
  121. except Exception as e:
  122. log(f"❌ Error interno destino: {e}", self.addr)
  123. return
  124. if payload:
  125. if payload.startswith(b"SSH-"):
  126. log(f"✅ Túnel cifrado (Modo SSH Directo)", self.addr)
  127. self.target.sendall(payload)
  128. elif b"HTTP/" in payload and b"Upgrade: websocket" not in payload:
  129. # 🛡️ ACTIVE PROBING EVASION ACTIVADO
  130. log(f"🕵️ Active Probing detectado (Navegador/Escáner). Respondiendo 200 OK Fake Web.", self.addr)
  131. self.client.sendall(FAKE_WEB_RESPONSE)
  132. return # Cierra conexión. El firewall queda engañado.
  133. else:
  134. with cycle_lock: current_status = next(mensaje_cycle)
  135. self.client.sendall(self.build_http_response(current_status))
  136. log(f"✅ Túnel cifrado (Modo WebSocket HTTP): {current_status}", self.addr)
  137. else:
  138. log(f"✅ Túnel cifrado (Modo Stunnel Silencioso)", self.addr)
  139. self.tunnel()
  140. except Exception as e: log(f"❌ Error: {e}", self.addr)
  141. finally:
  142. with conn_lock: active_connections -= 1
  143. self.cleanup()
  144. def tunnel(self):
  145. self.client.settimeout(None)
  146. self.target.settimeout(None)
  147. sockets = [self.client, self.target]
  148. while True:
  149. readable, _, error = select.select(sockets, [], sockets, 300)
  150. if error or not readable: break
  151. for s in readable:
  152. try:
  153. data = s.recv(BUFLEN)
  154. if not data: return
  155. if s is self.client:
  156. self.target.sendall(data)
  157. self.tx_bytes += len(data)
  158. else:
  159. self.client.sendall(data)
  160. self.rx_bytes += len(data)
  161. except: return
  162. def cleanup(self):
  163. total_mb = (self.tx_bytes + self.rx_bytes) / (1024 * 1024)
  164. if total_mb > 0.01: log(f"[*] Conexión finalizada. Tráfico consumido: {total_mb:.2f} MB", self.addr)
  165. for s in [self.client, self.target]:
  166. if s:
  167. try: s.close()
  168. except: pass
  169. def main():
  170. global active_connections
  171. ssl_context = None
  172. if USE_SSL:
  173. try:
  174. ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  175. ssl_context.load_cert_chain(certfile=CERT_FILE, keyfile=KEY_FILE)
  176. except Exception as e:
  177. log(f"❌ Error crítico cargando certificados SSL: {e}")
  178. sys.exit(1)
  179. try:
  180. addr_info = socket.getaddrinfo(None, LISTENING_PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
  181. addr_info.sort(key=lambda x: x[0] == socket.AF_INET6, reverse=True)
  182. af, socktype, proto, canonname, sa = addr_info[0]
  183. server = socket.socket(af, socktype, proto)
  184. server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  185. if af == socket.AF_INET6:
  186. try: server.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
  187. except: pass
  188. server.bind(sa)
  189. server.listen(600)
  190. log(f"=====================================================")
  191. log(f"🔥 Servidor Robusto Iniciado en Puerto {LISTENING_PORT}")
  192. log(f"🛡️ Motor SSL/TLS & Anti-Active Probing: ACTIVADO")
  193. log(f"🎯 Destino Interno: {SSH_HOST}:{SSH_PORT}")
  194. log(f"=====================================================")
  195. while True:
  196. client, addr = server.accept()
  197. if USE_SSL:
  198. try:
  199. client = ssl_context.wrap_socket(client, server_side=True)
  200. except Exception:
  201. client.close()
  202. continue
  203. with conn_lock:
  204. if active_connections >= MAX_CONNECTIONS:
  205. client.close()
  206. continue
  207. active_connections += 1
  208. ConnectionHandler(client, addr).start()
  209. except Exception as e: log(f"❌ Error crítico en servidor: {e}")
  210. finally: server.close()
  211. if __name__ == "__main__":
  212. main()