proxy_dual.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. /*
  2. * =====================================================================================
  3. * PROXY VPN DUAL ULTIMATE - EDICIÓN BARE-METAL V11 (FINAL)
  4. * Arquitectura: Dual-Stack (IPv4/IPv6) con Multiplexación de Puertos (80/443).
  5. * Seguridad: Anti-Flood dinámico, Auto-Ban en RAM, Evasión Capa 7 (Fake Web).
  6. * Optimización: C Nativo (POSIX) con Multihilos Detached y OpenSSL.
  7. * Compilación: gcc -O3 -o proxy_dual proxy_dual.c -lssl -lcrypto -lpthread
  8. * =====================================================================================
  9. */
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <unistd.h>
  14. #include <arpa/inet.h>
  15. #include <sys/socket.h>
  16. #include <sys/select.h>
  17. #include <pthread.h>
  18. #include <signal.h>
  19. #include <time.h>
  20. #include <openssl/ssl.h>
  21. #include <openssl/err.h>
  22. #include <errno.h>
  23. // --- CONFIGURACIÓN DE RED ---
  24. #define PORT_TCP 80
  25. #define PORT_TLS 443
  26. #define SSH_HOST "127.0.0.1"
  27. #define SSH_PORT 22
  28. #define BUFLEN 16384
  29. #define MAX_CONNECTIONS 1000
  30. // --- RUTAS DE SISTEMA ---
  31. #define CERT_FILE "/root/cert.pem"
  32. #define KEY_FILE "/root/key.pem"
  33. #define LOG_FILE "/root/proxy-dual-c.log"
  34. // --- CONFIGURACIÓN DE SEGURIDAD (ANTI-FLOOD) ---
  35. #define MAX_TRACKED_IPS 500
  36. #define AUTO_BAN_STRIKES 25 // Conexiones permitidas por segundo
  37. #define BAN_TIME 3600 // 1 Hora de bloqueo
  38. typedef struct {
  39. char ip[INET6_ADDRSTRLEN];
  40. time_t last_connect;
  41. int strikes;
  42. time_t ban_until;
  43. } ip_record_t;
  44. ip_record_t ip_database[MAX_TRACKED_IPS];
  45. pthread_mutex_t ip_db_mutex = PTHREAD_MUTEX_INITIALIZER;
  46. // --- RESPUESTAS FAKE WEB (CAMUFLAJE) ---
  47. const char *FAKE_WEB_TCP =
  48. "HTTP/1.1 400 Bad Request\r\n"
  49. "Server: nginx/1.24.0\r\n"
  50. "Content-Type: text/html\r\n"
  51. "Content-Length: 157\r\n"
  52. "Connection: close\r\n\r\n"
  53. "<html>\r\n<head><title>400 Bad Request</title></head>\r\n"
  54. "<body>\r\n<center><h1>400 Bad Request</h1></center>\r\n"
  55. "<hr><center>nginx/1.24.0</center>\r\n</body>\r\n</html>\r\n";
  56. const char *FAKE_WEB_TLS =
  57. "HTTP/1.1 400 OK\r\n"
  58. "Server: nginx/1.21.0\r\n"
  59. "Content-Type: text/html\r\n"
  60. "Connection: close\r\n\r\n"
  61. "<html><body><center><h1>400 Bad Request</h1></center></body></html>\r\n";
  62. // --- MENSAJES ROTATIVOS ---
  63. const char *MENSAJES[] = {
  64. "🚀 CONEXION ESTABLECIDA", "🛡️ CIFRADO MILITAR ACTIVO", "🔋 MODO SIGILO SSL OK",
  65. "Pfsense", "OPNsense", "VyOS", "Claro", "Altice", "Viva", "Google", "TNSR",
  66. "🌐 BYPASS FIREWALL OK", "💎 PREMIUM VIP", "⚡ VELOCIDAD MAXIMA"
  67. };
  68. #define NUM_MENSAJES (sizeof(MENSAJES) / sizeof(MENSAJES[0]))
  69. int mensaje_idx = 0;
  70. pthread_mutex_t msg_mutex = PTHREAD_MUTEX_INITIALIZER;
  71. // --- ESTADO GLOBAL ---
  72. int active_connections = 0;
  73. pthread_mutex_t conn_mutex = PTHREAD_MUTEX_INITIALIZER;
  74. pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;
  75. typedef struct {
  76. int client_fd;
  77. struct sockaddr_storage addr;
  78. int is_tls;
  79. SSL_CTX *ssl_ctx;
  80. } client_data_t;
  81. // --- REGISTRO DE EVENTOS (THREAD-SAFE) ---
  82. void write_log(const char *ip, const char *proto, const char *msg) {
  83. pthread_mutex_lock(&log_mutex);
  84. FILE *f = fopen(LOG_FILE, "a");
  85. if (f) {
  86. time_t now = time(NULL);
  87. struct tm *t = localtime(&now);
  88. char ts[64];
  89. strftime(ts, sizeof(ts), "%Y-%m-%d %H:%M:%S", t);
  90. char clean_ip[INET6_ADDRSTRLEN];
  91. if (ip && strncmp(ip, "::ffff:", 7) == 0) strcpy(clean_ip, ip + 7);
  92. else if (ip) strcpy(clean_ip, ip);
  93. else strcpy(clean_ip, "SISTEMA");
  94. fprintf(f, "[%s] [%s] [%s] %s\n", ts, proto, clean_ip, msg);
  95. printf("[%s] [%s] [%s] %s\n", ts, proto, clean_ip, msg);
  96. fclose(f);
  97. }
  98. pthread_mutex_unlock(&log_mutex);
  99. }
  100. // --- MOTOR DE SEGURIDAD ANTI-FLOOD ---
  101. int check_ip_security(const char *ip) {
  102. pthread_mutex_lock(&ip_db_mutex);
  103. time_t now = time(NULL);
  104. int empty_slot = -1;
  105. for (int i = 0; i < MAX_TRACKED_IPS; i++) {
  106. if (ip_database[i].ip[0] == '\0') {
  107. if (empty_slot == -1) empty_slot = i;
  108. continue;
  109. }
  110. if (strcmp(ip_database[i].ip, ip) == 0) {
  111. if (ip_database[i].ban_until > now) {
  112. pthread_mutex_unlock(&ip_db_mutex);
  113. return 0; // Baneado
  114. }
  115. if (ip_database[i].last_connect == now) {
  116. ip_database[i].strikes++;
  117. if (ip_database[i].strikes > AUTO_BAN_STRIKES) {
  118. ip_database[i].ban_until = now + BAN_TIME;
  119. pthread_mutex_unlock(&ip_db_mutex);
  120. return -1; // Nuevo Ban
  121. }
  122. } else {
  123. ip_database[i].strikes = 1;
  124. ip_database[i].last_connect = now;
  125. }
  126. pthread_mutex_unlock(&ip_db_mutex);
  127. return 1;
  128. }
  129. }
  130. if (empty_slot != -1) {
  131. strcpy(ip_database[empty_slot].ip, ip);
  132. ip_database[empty_slot].last_connect = now;
  133. ip_database[empty_slot].strikes = 1;
  134. ip_database[empty_slot].ban_until = 0;
  135. }
  136. pthread_mutex_unlock(&ip_db_mutex);
  137. return 1;
  138. }
  139. // --- CONFIGURACIÓN OPENSSL ---
  140. SSL_CTX *init_ssl_context() {
  141. SSL_library_init();
  142. SSL_load_error_strings();
  143. OpenSSL_add_all_algorithms();
  144. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  145. if (!ctx) return NULL;
  146. if (SSL_CTX_use_certificate_file(ctx, CERT_FILE, SSL_FILETYPE_PEM) <= 0 ||
  147. SSL_CTX_use_PrivateKey_file(ctx, KEY_FILE, SSL_FILETYPE_PEM) <= 0) {
  148. return NULL;
  149. }
  150. return ctx;
  151. }
  152. // --- CREACIÓN DE SOCKET DUAL-STACK (IPv4/IPv6) ---
  153. int create_dual_socket(int port) {
  154. int s = socket(AF_INET6, SOCK_STREAM, 0);
  155. if (s < 0) return -1;
  156. int opt = 1;
  157. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  158. // Desactivar IPV6_V6ONLY para escuchar IPv4 simultáneamente
  159. int no = 0;
  160. setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &no, sizeof(no));
  161. struct sockaddr_in6 addr;
  162. memset(&addr, 0, sizeof(addr));
  163. addr.sin6_family = AF_INET6;
  164. addr.sin6_addr = in6addr_any;
  165. addr.sin6_port = htons(port);
  166. if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
  167. close(s); return -1;
  168. }
  169. listen(s, 512);
  170. return s;
  171. }
  172. // --- MANEJADOR DE CONEXIÓN (HILO TRABAJADOR) ---
  173. void *connection_worker(void *arg) {
  174. client_data_t *data = (client_data_t *)arg;
  175. int client_fd = data->client_fd;
  176. int is_tls = data->is_tls;
  177. SSL_CTX *ssl_ctx = data->ssl_ctx;
  178. char ip_str[INET6_ADDRSTRLEN];
  179. if (data->addr.ss_family == AF_INET) {
  180. struct sockaddr_in *s = (struct sockaddr_in *)&data->addr;
  181. inet_ntop(AF_INET, &s->sin_addr, ip_str, sizeof(ip_str));
  182. } else {
  183. struct sockaddr_in6 *s = (struct sockaddr_in6 *)&data->addr;
  184. inet_ntop(AF_INET6, &s->sin6_addr, ip_str, sizeof(ip_str));
  185. }
  186. free(data);
  187. const char *proto = is_tls ? "TLS" : "TCP";
  188. // 1. Seguridad Anti-Flood
  189. int sec = check_ip_security(ip_str);
  190. if (sec <= 0) {
  191. if (sec == -1) write_log(ip_str, proto, "⛔ IP Bloqueada por Flood.");
  192. close(client_fd);
  193. pthread_mutex_lock(&conn_mutex); active_connections--; pthread_mutex_unlock(&conn_mutex);
  194. return NULL;
  195. }
  196. SSL *ssl = NULL;
  197. if (is_tls) {
  198. ssl = SSL_new(ssl_ctx);
  199. SSL_set_fd(ssl, client_fd);
  200. if (SSL_accept(ssl) <= 0) {
  201. SSL_free(ssl); close(client_fd);
  202. pthread_mutex_lock(&conn_mutex); active_connections--; pthread_mutex_unlock(&conn_mutex);
  203. return NULL;
  204. }
  205. }
  206. // 2. Lectura con protección para NetMod (SSL_pending + select)
  207. char buffer[BUFLEN];
  208. int bytes = 0;
  209. fd_set rset; FD_ZERO(&rset); FD_SET(client_fd, &rset);
  210. struct timeval tv = {3, 0};
  211. int has_ssl_data = (is_tls) ? SSL_pending(ssl) : 0;
  212. if (has_ssl_data > 0 || select(client_fd + 1, &rset, NULL, NULL, &tv) > 0) {
  213. if (is_tls) bytes = SSL_read(ssl, buffer, sizeof(buffer) - 1);
  214. else bytes = recv(client_fd, buffer, sizeof(buffer) - 1, 0);
  215. }
  216. int target_fd = -1;
  217. long tx = 0, rx = 0;
  218. if (bytes > 0) {
  219. buffer[bytes] = '\0';
  220. // Conectar al SSH local
  221. struct sockaddr_in ssh_addr;
  222. target_fd = socket(AF_INET, SOCK_STREAM, 0);
  223. ssh_addr.sin_family = AF_INET;
  224. ssh_addr.sin_port = htons(SSH_PORT);
  225. inet_pton(AF_INET, SSH_HOST, &ssh_addr.sin_addr);
  226. if (connect(target_fd, (struct sockaddr *)&ssh_addr, sizeof(ssh_addr)) < 0) goto end;
  227. // Lógica de Enrutamiento L7
  228. if (strncmp(buffer, "SSH-", 4) == 0) {
  229. write_log(ip_str, proto, "✅ SSH Directo Detectado");
  230. send(target_fd, buffer, bytes, 0);
  231. } else if (strstr(buffer, "HTTP/") && !strstr(buffer, "Upgrade: websocket")) {
  232. write_log(ip_str, proto, "🕵️ Escáner HTTP. Fake Web enviada.");
  233. if (is_tls) SSL_write(ssl, FAKE_WEB_TLS, strlen(FAKE_WEB_TLS));
  234. else send(client_fd, FAKE_WEB_TCP, strlen(FAKE_WEB_TCP), 0);
  235. goto end;
  236. } else {
  237. // Inyector VPN (WebSocket)
  238. pthread_mutex_lock(&msg_mutex);
  239. const char *msg_rot = MENSAJES[mensaje_idx];
  240. mensaje_idx = (mensaje_idx + 1) % NUM_MENSAJES;
  241. pthread_mutex_unlock(&msg_mutex);
  242. char resp[2048];
  243. snprintf(resp, sizeof(resp),
  244. "HTTP/1.1 101 %s\r\n"
  245. "Server: nginx/1.24.0\r\n"
  246. "X-Forwarded-For: 127.0.0.1\r\n"
  247. "Content-Type: text/html; charset=UTF-8\r\n"
  248. "Proxy-Connection: keep-alive\r\n"
  249. "Cache-Control: no-cache\r\n"
  250. "X-Proxy-Agent: Gemini-Ultra-Dual-C-V11\r\n"
  251. "Connection: Upgrade\r\n"
  252. "Upgrade: websocket\r\n\r\n", msg_rot);
  253. if (is_tls) SSL_write(ssl, resp, strlen(resp));
  254. else send(client_fd, resp, strlen(resp), 0);
  255. write_log(ip_str, proto, "✅ Túnel Inyectado OK");
  256. }
  257. } else {
  258. // NetMod Silencioso
  259. struct sockaddr_in ssh_addr;
  260. target_fd = socket(AF_INET, SOCK_STREAM, 0);
  261. ssh_addr.sin_family = AF_INET;
  262. ssh_addr.sin_port = htons(SSH_PORT);
  263. inet_pton(AF_INET, SSH_HOST, &ssh_addr.sin_addr);
  264. if (connect(target_fd, (struct sockaddr *)&ssh_addr, sizeof(ssh_addr)) == 0) {
  265. write_log(ip_str, proto, "✅ Túnel Silencioso (Stunnel) OK");
  266. } else goto end;
  267. }
  268. // 3. Puente de Datos (Tunneling)
  269. int max_fd = (client_fd > target_fd) ? client_fd : target_fd;
  270. while (1) {
  271. fd_set fds; FD_ZERO(&fds); FD_SET(client_fd, &fds); FD_SET(target_fd, &fds);
  272. struct timeval sel_tv = {300, 0};
  273. int pending = (is_tls) ? SSL_pending(ssl) : 0;
  274. if (pending == 0) {
  275. if (select(max_fd + 1, &fds, NULL, NULL, &sel_tv) <= 0) break;
  276. }
  277. if (pending > 0 || FD_ISSET(client_fd, &fds)) {
  278. int r = (is_tls) ? SSL_read(ssl, buffer, BUFLEN) : recv(client_fd, buffer, BUFLEN, 0);
  279. if (r <= 0) break;
  280. send(target_fd, buffer, r, 0);
  281. rx += r;
  282. }
  283. if (FD_ISSET(target_fd, &fds)) {
  284. int r = recv(target_fd, buffer, BUFLEN, 0);
  285. if (r <= 0) break;
  286. if (is_tls) SSL_write(ssl, buffer, r);
  287. else send(client_fd, buffer, r, 0);
  288. tx += r;
  289. }
  290. }
  291. end:
  292. if (target_fd != -1) close(target_fd);
  293. if (is_tls) { SSL_shutdown(ssl); SSL_free(ssl); }
  294. close(client_fd);
  295. double mb = (double)(tx + rx) / (1024.0 * 1024.0);
  296. if (mb > 0.05) {
  297. char stat[128]; snprintf(stat, sizeof(stat), "[*] Cierre Sesión. Tráfico: %.2f MB", mb);
  298. write_log(ip_str, proto, stat);
  299. }
  300. pthread_mutex_lock(&conn_mutex); active_connections--; pthread_mutex_unlock(&conn_mutex);
  301. return NULL;
  302. }
  303. // --- HILO MAESTRO ---
  304. int main(int argc, char **argv) {
  305. // Ignorar SIGPIPE para evitar crasheos por desconexiones bruscas
  306. signal(SIGPIPE, SIG_IGN);
  307. memset(ip_database, 0, sizeof(ip_database));
  308. SSL_CTX *ssl_ctx = init_ssl_context();
  309. int s_tcp = create_dual_socket(PORT_TCP);
  310. int s_tls = create_dual_socket(PORT_TLS);
  311. if (s_tcp < 0 || s_tls < 0) {
  312. fprintf(stderr, "Error al abrir los puertos. Revisa que no estén usados.\n");
  313. exit(1);
  314. }
  315. write_log(NULL, "SISTEMA", "=========================================================");
  316. write_log(NULL, "SISTEMA", "🚀 PROXY DUAL ULTIMATE V11 (C) - BARE-METAL");
  317. write_log(NULL, "SISTEMA", "🛡️ Dual-Stack (v4/v6) | Anti-Flood (25/s) | OpenSSL Fix");
  318. write_log(NULL, "SISTEMA", "=========================================================");
  319. int max_fd = (s_tcp > s_tls) ? s_tcp : s_tls;
  320. while (1) {
  321. fd_set master; FD_ZERO(&master); FD_SET(s_tcp, &master); FD_SET(s_tls, &master);
  322. if (select(max_fd + 1, &master, NULL, NULL, NULL) < 0) continue;
  323. int active_s = FD_ISSET(s_tcp, &master) ? s_tcp : s_tls;
  324. int is_tls = (active_s == s_tls);
  325. struct sockaddr_storage client_addr;
  326. socklen_t addr_len = sizeof(client_addr);
  327. int client_fd = accept(active_s, (struct sockaddr *)&client_addr, &addr_len);
  328. if (client_fd < 0) continue;
  329. pthread_mutex_lock(&conn_mutex);
  330. if (active_connections >= MAX_CONNECTIONS) {
  331. pthread_mutex_unlock(&conn_mutex); close(client_fd); continue;
  332. }
  333. active_connections++;
  334. pthread_mutex_unlock(&conn_mutex);
  335. client_data_t *d = malloc(sizeof(client_data_t));
  336. d->client_fd = client_fd; d->addr = client_addr; d->is_tls = is_tls; d->ssl_ctx = ssl_ctx;
  337. pthread_t tid;
  338. pthread_attr_t attr; pthread_attr_init(&attr);
  339. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  340. if (pthread_create(&tid, &attr, connection_worker, d) != 0) {
  341. close(client_fd); free(d);
  342. pthread_mutex_lock(&conn_mutex); active_connections--; pthread_mutex_unlock(&conn_mutex);
  343. }
  344. pthread_attr_destroy(&attr);
  345. }
  346. return 0;
  347. }