proxy_dual.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. * =====================================================================================
  3. * PROXY VPN DUAL (TCP + TLS) - ULTIMATE BARE-METAL EDITION V9
  4. * Correcciones:
  5. * 1. Bugfix de OpenSSL Internal Buffer (SSL_pending) para NetMod.
  6. * 2. Anti-Flood calibrado para evitar auto-baneos por hilos múltiples de VPN.
  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. // --- CONFIGURACIÓN BASE ---
  23. #define DEFAULT_PORT_TCP 80
  24. #define DEFAULT_PORT_TLS 443
  25. #define SSH_HOST "127.0.0.1"
  26. #define SSH_PORT 22
  27. #define BUFLEN 16384
  28. #define MAX_CONNECTIONS 500
  29. #define LOG_FILE "/root/proxy-dual.log"
  30. #define CERT_FILE "/root/cert.pem"
  31. #define KEY_FILE "/root/key.pem"
  32. // --- CONFIGURACIÓN DE SEGURIDAD (ANTI-FLOOD & BAN) ---
  33. #define MAX_TRACKED_IPS 200
  34. #define AUTO_BAN_STRIKES 15 // Aumentado a 15 para soportar los hilos de NetMod
  35. #define BAN_TIME 3600 // 1 Hora
  36. #define COOLDOWN_SEC 1 // Ventana de 1 segundo
  37. typedef struct {
  38. char ip[INET6_ADDRSTRLEN];
  39. time_t last_connect;
  40. int strikes;
  41. time_t ban_until;
  42. } ip_record_t;
  43. ip_record_t ip_database[MAX_TRACKED_IPS];
  44. pthread_mutex_t ip_db_mutex = PTHREAD_MUTEX_INITIALIZER;
  45. // --- RESPUESTAS FAKE WEB ---
  46. const char *FAKE_WEB_TCP = "HTTP/1.1 400 Bad Request\r\nServer: nginx/1.24.0\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n<html><body><center><h1>400 Bad Request</h1></center><hr><center>nginx/1.24.0</center></body></html>\r\n";
  47. const char *FAKE_WEB_TLS = "HTTP/1.1 400 OK\r\nServer: nginx/1.21.0\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n<html><body><center><h1>400 Bad Request</h1></center></body></html>\r\n";
  48. // --- MENSAJES ROTATIVOS ---
  49. const char *MENSAJES[] = {"🚀 CONEXION ESTABLECIDA", "🛡️ CIFRADO MILITAR ACTIVO", "🔋 MODO SIGILO SSL OK", "Pfsense", "OPNsense", "VyOS", "Claro", "Google", "TNSR", "🌐 BYPASS OK"};
  50. #define NUM_MENSAJES (sizeof(MENSAJES) / sizeof(MENSAJES[0]))
  51. int mensaje_idx = 0;
  52. pthread_mutex_t msg_mutex = PTHREAD_MUTEX_INITIALIZER;
  53. int active_connections = 0;
  54. pthread_mutex_t conn_mutex = PTHREAD_MUTEX_INITIALIZER;
  55. pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;
  56. typedef struct {
  57. int client_fd;
  58. struct sockaddr_storage addr;
  59. int is_tls;
  60. SSL_CTX *ssl_ctx;
  61. } client_data_t;
  62. // --- FUNCIONES DE SOPORTE ---
  63. void write_log(const char *ip, const char *proto, const char *msg) {
  64. pthread_mutex_lock(&log_mutex);
  65. FILE *f = fopen(LOG_FILE, "a");
  66. if (f) {
  67. time_t now = time(NULL);
  68. struct tm *t = localtime(&now);
  69. char ts[64];
  70. strftime(ts, sizeof(ts), "%Y-%m-%d %H:%M:%S", t);
  71. fprintf(f, "[%s] [%s] [%s] %s\n", ts, proto, ip ? ip : "SISTEMA", msg);
  72. printf("[%s] [%s] [%s] %s\n", ts, proto, ip ? ip : "SISTEMA", msg);
  73. fclose(f);
  74. }
  75. pthread_mutex_unlock(&log_mutex);
  76. }
  77. // --- MOTOR DE SEGURIDAD ---
  78. int check_and_update_ip(const char *ip) {
  79. pthread_mutex_lock(&ip_db_mutex);
  80. time_t now = time(NULL);
  81. int empty_slot = -1;
  82. int found = 0;
  83. for (int i = 0; i < MAX_TRACKED_IPS; i++) {
  84. if (ip_database[i].ip[0] == '\0' && empty_slot == -1) empty_slot = i;
  85. else if (strcmp(ip_database[i].ip, ip) == 0) {
  86. found = 1;
  87. if (ip_database[i].ban_until > now) {
  88. pthread_mutex_unlock(&ip_db_mutex);
  89. return 0; // Sigue baneado
  90. }
  91. if (now - ip_database[i].last_connect <= COOLDOWN_SEC) {
  92. ip_database[i].strikes++;
  93. ip_database[i].last_connect = now;
  94. if (ip_database[i].strikes >= AUTO_BAN_STRIKES) {
  95. ip_database[i].ban_until = now + BAN_TIME;
  96. pthread_mutex_unlock(&ip_db_mutex);
  97. return -1; // Acaba de ser baneado
  98. }
  99. } else {
  100. ip_database[i].strikes = 1;
  101. ip_database[i].last_connect = now;
  102. }
  103. break;
  104. }
  105. }
  106. if (!found && empty_slot != -1) {
  107. strcpy(ip_database[empty_slot].ip, ip);
  108. ip_database[empty_slot].last_connect = now;
  109. ip_database[empty_slot].strikes = 1;
  110. ip_database[empty_slot].ban_until = 0;
  111. }
  112. pthread_mutex_unlock(&ip_db_mutex);
  113. return 1;
  114. }
  115. SSL_CTX *create_ssl_context() {
  116. SSL_load_error_strings();
  117. OpenSSL_add_ssl_algorithms();
  118. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  119. if (!ctx) exit(1);
  120. SSL_CTX_use_certificate_file(ctx, CERT_FILE, SSL_FILETYPE_PEM);
  121. SSL_CTX_use_PrivateKey_file(ctx, KEY_FILE, SSL_FILETYPE_PEM);
  122. return ctx;
  123. }
  124. int create_server_socket(int port) {
  125. int s_sock = socket(AF_INET6, SOCK_STREAM, 0);
  126. if (s_sock < 0) return -1;
  127. int opt = 1; setsockopt(s_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  128. int no = 0; setsockopt(s_sock, IPPROTO_IPV6, IPV6_V6ONLY, &no, sizeof(no));
  129. struct sockaddr_in6 addr;
  130. memset(&addr, 0, sizeof(addr));
  131. addr.sin6_family = AF_INET6;
  132. addr.sin6_addr = in6addr_any;
  133. addr.sin6_port = htons(port);
  134. if (bind(s_sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) return -1;
  135. listen(s_sock, 600);
  136. return s_sock;
  137. }
  138. void *connection_handler(void *arg) {
  139. client_data_t *data = (client_data_t *)arg;
  140. int client_sock = data->client_fd;
  141. int is_tls = data->is_tls;
  142. SSL_CTX *ctx = data->ssl_ctx;
  143. char client_ip[INET6_ADDRSTRLEN];
  144. if (data->addr.ss_family == AF_INET) {
  145. struct sockaddr_in *s = (struct sockaddr_in *)&data->addr;
  146. inet_ntop(AF_INET, &s->sin_addr, client_ip, sizeof(client_ip));
  147. } else {
  148. struct sockaddr_in6 *s = (struct sockaddr_in6 *)&data->addr;
  149. inet_ntop(AF_INET6, &s->sin6_addr, client_ip, sizeof(client_ip));
  150. }
  151. free(data);
  152. const char *proto_name = is_tls ? "TLS" : "TCP";
  153. // --- FILTRO DE SEGURIDAD ---
  154. int sec_status = check_and_update_ip(client_ip);
  155. if (sec_status == 0) {
  156. close(client_sock);
  157. pthread_mutex_lock(&conn_mutex); active_connections--; pthread_mutex_unlock(&conn_mutex);
  158. pthread_exit(NULL);
  159. } else if (sec_status == -1) {
  160. write_log(client_ip, proto_name, "⛔ IP Baneada (Flood/Spam detectado)");
  161. close(client_sock);
  162. pthread_mutex_lock(&conn_mutex); active_connections--; pthread_mutex_unlock(&conn_mutex);
  163. pthread_exit(NULL);
  164. }
  165. SSL *ssl = NULL;
  166. if (is_tls) {
  167. ssl = SSL_new(ctx);
  168. SSL_set_fd(ssl, client_sock);
  169. if (SSL_accept(ssl) <= 0) {
  170. SSL_free(ssl); close(client_sock);
  171. pthread_mutex_lock(&conn_mutex); active_connections--; pthread_mutex_unlock(&conn_mutex);
  172. pthread_exit(NULL);
  173. }
  174. }
  175. // =========================================================================
  176. // BUGFIX: REVISAR LA MEMORIA INTERNA DE OPENSSL ANTES DE ESPERAR EN EL CABLE
  177. // =========================================================================
  178. fd_set init_fds; FD_ZERO(&init_fds); FD_SET(client_sock, &init_fds);
  179. struct timeval init_tv = {3, 0};
  180. char buffer[BUFLEN];
  181. int bytes_read = 0;
  182. int ssl_has_data = is_tls ? SSL_pending(ssl) : 0;
  183. // Si SSL ya secuestró el paquete, lo leemos de inmediato. Si no, esperamos 3 seg.
  184. if (ssl_has_data > 0 || select(client_sock + 1, &init_fds, NULL, NULL, &init_tv) > 0) {
  185. if (is_tls) bytes_read = SSL_read(ssl, buffer, sizeof(buffer)-1);
  186. else bytes_read = recv(client_sock, buffer, sizeof(buffer)-1, 0);
  187. }
  188. int target_sock = -1;
  189. long tx_bytes = 0, rx_bytes = 0;
  190. if (bytes_read > 0) {
  191. buffer[bytes_read] = '\0';
  192. struct sockaddr_in t_addr;
  193. target_sock = socket(AF_INET, SOCK_STREAM, 0);
  194. t_addr.sin_family = AF_INET;
  195. t_addr.sin_port = htons(SSH_PORT);
  196. inet_pton(AF_INET, SSH_HOST, &t_addr.sin_addr);
  197. if (connect(target_sock, (struct sockaddr *)&t_addr, sizeof(t_addr)) < 0) goto cleanup;
  198. if (strncmp(buffer, "SSH-", 4) == 0) {
  199. send(target_sock, buffer, bytes_read, 0);
  200. } else if (strstr(buffer, "HTTP/") != NULL && strstr(buffer, "Upgrade: websocket") == NULL) {
  201. write_log(client_ip, proto_name, "🕵️ Escáner detectado. Fake Web (400 OK).");
  202. if (is_tls) SSL_write(ssl, FAKE_WEB_TLS, strlen(FAKE_WEB_TLS));
  203. else send(client_sock, FAKE_WEB_TCP, strlen(FAKE_WEB_TCP), 0);
  204. goto cleanup;
  205. } else {
  206. // --- ENCABEZADOS EXTENDIDOS RECUPERADOS ---
  207. pthread_mutex_lock(&msg_mutex);
  208. const char *status_msg = MENSAJES[mensaje_idx];
  209. mensaje_idx = (mensaje_idx + 1) % NUM_MENSAJES;
  210. pthread_mutex_unlock(&msg_mutex);
  211. char response[1024];
  212. snprintf(response, sizeof(response),
  213. "HTTP/1.1 101 %s\r\n"
  214. "Server: nginx/1.24.0\r\n"
  215. "X-Forwarded-For: 127.0.0.1\r\n"
  216. "Content-Type: text/html; charset=UTF-8\r\n"
  217. "Proxy-Connection: keep-alive\r\n"
  218. "Cache-Control: no-cache\r\n"
  219. "X-Proxy-Agent: Gemini-Ultra-Dual-C\r\n"
  220. "Connection: Upgrade\r\n"
  221. "Upgrade: websocket\r\n\r\n", status_msg);
  222. if (is_tls) SSL_write(ssl, response, strlen(response));
  223. else send(client_sock, response, strlen(response), 0);
  224. write_log(client_ip, proto_name, "✅ Túnel Inyectado OK");
  225. }
  226. } else {
  227. struct sockaddr_in t_addr;
  228. target_sock = socket(AF_INET, SOCK_STREAM, 0);
  229. t_addr.sin_family = AF_INET;
  230. t_addr.sin_port = htons(SSH_PORT);
  231. inet_pton(AF_INET, SSH_HOST, &t_addr.sin_addr);
  232. if (connect(target_sock, (struct sockaddr *)&t_addr, sizeof(t_addr)) != 0) goto cleanup;
  233. write_log(client_ip, proto_name, "✅ Túnel Modo Silencioso");
  234. }
  235. int max_fd = (client_sock > target_sock) ? client_sock : target_sock;
  236. while (1) {
  237. fd_set readfds; FD_ZERO(&readfds); FD_SET(client_sock, &readfds); FD_SET(target_sock, &readfds);
  238. struct timeval select_tv = {300, 0};
  239. int pending = is_tls ? SSL_pending(ssl) : 0;
  240. if (pending == 0) {
  241. if (select(max_fd + 1, &readfds, NULL, NULL, &select_tv) <= 0) break;
  242. }
  243. if (pending > 0 || FD_ISSET(client_sock, &readfds)) {
  244. int b = is_tls ? SSL_read(ssl, buffer, BUFLEN) : recv(client_sock, buffer, BUFLEN, 0);
  245. if (b <= 0) break;
  246. send(target_sock, buffer, b, 0);
  247. rx_bytes += b;
  248. }
  249. if (FD_ISSET(target_sock, &readfds)) {
  250. int b = recv(target_sock, buffer, BUFLEN, 0);
  251. if (b <= 0) break;
  252. if (is_tls) SSL_write(ssl, buffer, b);
  253. else send(client_sock, buffer, b, 0);
  254. tx_bytes += b;
  255. }
  256. }
  257. cleanup:
  258. if (target_sock != -1) close(target_sock);
  259. if (is_tls) { SSL_shutdown(ssl); SSL_free(ssl); }
  260. close(client_sock);
  261. pthread_mutex_lock(&conn_mutex); active_connections--; pthread_mutex_unlock(&conn_mutex);
  262. pthread_exit(NULL);
  263. }
  264. int main(int argc, char **argv) {
  265. int port_tcp = DEFAULT_PORT_TCP, port_tls = DEFAULT_PORT_TLS;
  266. if (argc >= 3) { port_tcp = atoi(argv[1]); port_tls = atoi(argv[2]); }
  267. // Limpiar base de datos de IPs al inicio
  268. memset(ip_database, 0, sizeof(ip_database));
  269. signal(SIGPIPE, SIG_IGN);
  270. SSL_CTX *ctx = create_ssl_context();
  271. int server_tcp = create_server_socket(port_tcp);
  272. int server_tls = create_server_socket(port_tls);
  273. if (server_tcp < 0 || server_tls < 0) exit(1);
  274. write_log(NULL, "SISTEMA", "🚀 PROXY DUAL BARE-METAL INICIADO (Ultimate Edition V9)");
  275. write_log(NULL, "SISTEMA", "🛡️ Módulos cargados: Anti-Flood (15/s), Auto-Ban, SSL_pending Fix, Full Headers");
  276. int max_server_fd = (server_tcp > server_tls) ? server_tcp : server_tls;
  277. while (1) {
  278. fd_set master_fds; FD_ZERO(&master_fds); FD_SET(server_tcp, &master_fds); FD_SET(server_tls, &master_fds);
  279. if (select(max_server_fd + 1, &master_fds, NULL, NULL, NULL) < 0) continue;
  280. int active_sock = -1, is_tls = 0;
  281. if (FD_ISSET(server_tcp, &master_fds)) { active_sock = server_tcp; is_tls = 0; }
  282. else if (FD_ISSET(server_tls, &master_fds)) { active_sock = server_tls; is_tls = 1; }
  283. struct sockaddr_storage c_addr;
  284. socklen_t c_len = sizeof(c_addr);
  285. int client_sock = accept(active_sock, (struct sockaddr *)&c_addr, &c_len);
  286. if (client_sock < 0) continue;
  287. pthread_mutex_lock(&conn_mutex);
  288. if (active_connections >= MAX_CONNECTIONS) { pthread_mutex_unlock(&conn_mutex); close(client_sock); continue; }
  289. active_connections++; pthread_mutex_unlock(&conn_mutex);
  290. client_data_t *d = malloc(sizeof(client_data_t));
  291. d->client_fd = client_sock; d->addr = c_addr; d->is_tls = is_tls; d->ssl_ctx = ctx;
  292. pthread_t tid; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  293. if (pthread_create(&tid, &attr, connection_handler, d) != 0) {
  294. close(client_sock); free(d);
  295. pthread_mutex_lock(&conn_mutex); active_connections--; pthread_mutex_unlock(&conn_mutex);
  296. }
  297. pthread_attr_destroy(&attr);
  298. }
  299. return 0;
  300. }