# -*- coding: utf-8 -*- # ============================================================================== # PROXY MULTIFILAMENTADO PROFESIONAL - VERSIÓN ULTRA-ROBUSTA (PYTHON 3) # ============================================================================== #screen -dmS badvpn2 /bin/badvpn-udpgw --listen-addr 127.0.0.1:7300 --max-clients 1000 --max-connections-for-client 100 #screen -dmS pydic-80 python3 /root/Pythonv1.py 8080 import socket import threading import select import sys import time import logging import logging.handlers import itertools # --- CONFIGURACIÓN DE RED --- IPV4_ADDR = '0.0.0.0' IPV6_ADDR = '::' LISTENING_PORT = int(sys.argv[1]) if sys.argv[1:] else 8080 DEFAULT_HOST = '127.0.0.1:223' # --- CONFIGURACIÓN DE SEGURIDAD AVANZADA --- MAX_CONNECTIONS = 1000 CONNECTION_COOLDOWN = 0.5 TIMEOUT = 60 BUFLEN = 16384 # 🛡️ LISTA BLANCA DE IPs (Si está vacía, permite todas) # Ejemplo: ALLOWED_IPS = ['127.0.0.1', '192.168.1.50'] ALLOWED_IPS = [] # 🚫 LISTA NEGRA DE DOMINIOS (Bloquea conexiones a estos hosts) BLOCKED_HOSTS = ['sitio-prohibido.com', 'anuncios.malware.net'] # 📑 ENCABEZADOS A INYECTAR (Se añaden a la comunicación con el destino) CUSTOM_HEADERS = { "X-Proxy-Agent": "Gemini-Ultra-Robust-v3", "X-Forwarded-For-Proxy": "True" } # --- MENSAJES ROTATIVOS --- MENSAJES = [ "Pfsense", "OPNsense", "VyOS", "Claro", "Windows Server", "BSD Free", "VyOS", "Altice", "Viva", "Google", "VyOS", "TNSR" ] mensaje_cycle = itertools.cycle(MENSAJES) cycle_lock = threading.Lock() # --- SISTEMA DE LOGS --- LOG_FILE = 'proxy_avanzado.log' def setup_logger(): logger = logging.getLogger("ProxyAvanzado") logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=10*1024*1024, backupCount=5) handler.setFormatter(formatter) console = logging.StreamHandler() console.setFormatter(formatter) logger.addHandler(handler) logger.addHandler(console) return logger log = setup_logger() conn_limit = threading.Semaphore(MAX_CONNECTIONS) ip_history = {} ip_lock = threading.Lock() class ConnectionHandler(threading.Thread): def __init__(self, client_socket, addr): super().__init__(daemon=True) self.client = client_socket self.addr = addr self.target = None self.log_id = "{}:{}".format(addr[0], addr[1]) def finish(self): for s in [self.client, self.target]: if s: try: s.close() except: pass conn_limit.release() def is_ip_allowed(self, ip): if not ALLOWED_IPS: return True return ip in ALLOWED_IPS def is_host_blocked(self, target_str): host = target_str.split(':')[0].lower() return host in BLOCKED_HOSTS def run(self): try: # Validar IP en lista blanca if not self.is_ip_allowed(self.addr[0]): log.warning("[{}] IP no autorizada. Cerrando.".format(self.log_id)) return data = self.client.recv(BUFLEN) if not data: return headers_text = data.decode('latin-1', errors='ignore') target_info = self.extract_header(headers_text, 'X-Real-Host') or DEFAULT_HOST # Validar dominio bloqueado if self.is_host_blocked(target_info): log.warning("[{}] Intento de acceso a host bloqueado: {}".format(self.log_id, target_info)) self.client.sendall(b"HTTP/1.1 403 Forbidden\r\n\r\n") return with cycle_lock: msg = next(mensaje_cycle) if not self.connect_to_target(target_info): log.error("[{}] Error conectando a {}".format(self.log_id, target_info)) return # Respuesta al cliente resp = "HTTP/1.1 101 {}\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n".format(msg).encode('utf-8') self.client.sendall(resp) log.info("[{}] OK -> {} | Msg: {}".format(self.log_id, target_info, msg)) self.bridge() except Exception as e: log.error("[{}] Error: {}".format(self.log_id, e)) finally: self.finish() def extract_header(self, text, header_name): for line in text.split('\r\n'): if line.lower().startswith(header_name.lower() + ":"): return line.split(':', 1)[1].strip() return None def connect_to_target(self, target_str): try: host, port = (target_str.split(':') + [22])[:2] port = int(port) infos = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM) for res in infos: af, socktype, proto, _, sa = res try: self.target = socket.socket(af, socktype, proto) self.target.settimeout(10) self.target.connect(sa) return True except: if self.target: self.target.close() continue return False except: return False def bridge(self): sockets = [self.client, self.target] while True: try: readable, _, error = select.select(sockets, [], sockets, TIMEOUT) if error or not readable: break for s in readable: other = self.target if s is self.client else self.client chunk = s.recv(BUFLEN) if not chunk: return other.sendall(chunk) except: break def main(): listeners = [] for af, addr in [(socket.AF_INET, IPV4_ADDR), (socket.AF_INET6, IPV6_ADDR)]: try: s = socket.socket(af, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if af == socket.AF_INET6: try: s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) except: pass s.bind((addr, LISTENING_PORT)) s.listen(128) listeners.append(s) log.info("Escuchando en {}:{}".format(addr, LISTENING_PORT)) except Exception as e: log.debug("Interfaz {} ocupada: {}".format(addr, e)) if not listeners: log.critical("No se pudo iniciar ningun listener.") return try: while True: r, _, _ = select.select(listeners, [], []) for s in r: client, addr = s.accept() ip = addr[0] with ip_lock: now = time.time() if now - ip_history.get(ip, 0) < CONNECTION_COOLDOWN: client.close() continue ip_history[ip] = now if not conn_limit.acquire(blocking=False): client.close() continue ConnectionHandler(client, addr).start() except KeyboardInterrupt: log.info("Servidor detenido.") finally: for s in listeners: s.close() if __name__ == "__main__": main()