ptunnel.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. /*
  2. * ptunnel.c
  3. * ptunnel is licensed under the BSD license:
  4. *
  5. * Copyright (c) 2004-2011, Daniel Stoedle <daniels@cs.uit.no>,
  6. * Yellow Lemon Software. All rights reserved.
  7. *
  8. * Copyright (c) 2017-2019, Toni Uhlig <matzeton@googlemail.com>
  9. *
  10. * Redistribution and use in source and binary forms, with or without
  11. * modification, are permitted provided that the following conditions are met:
  12. *
  13. * - Redistributions of source code must retain the above copyright notice,
  14. * this list of conditions and the following disclaimer.
  15. *
  16. * - Redistributions in binary form must reproduce the above copyright notice,
  17. * this list of conditions and the following disclaimer in the documentation
  18. * and/or other materials provided with the distribution.
  19. *
  20. * - Neither the name of the Yellow Lemon Software nor the names of its
  21. * contributors may be used to endorse or promote products derived from this
  22. * software without specific prior written permission.
  23. *
  24. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  25. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  26. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  27. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  28. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  29. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  30. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  31. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  32. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  33. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  34. * POSSIBILITY OF SUCH DAMAGE.
  35. *
  36. * Contacting the author:
  37. * You can get in touch with me, Daniel Stødle (that's the Norwegian letter oe,
  38. * in case your text editor didn't realize), here: <daniels@cs.uit.no>
  39. *
  40. * The official ptunnel website is here:
  41. * <http://www.cs.uit.no/~daniels/PingTunnel/>
  42. *
  43. * Note that the source code is best viewed with tabs set to 4 spaces.
  44. */
  45. #ifdef HAVE_CONFIG_H
  46. #include "config.h"
  47. #endif
  48. #include "ptunnel.h"
  49. #include "options.h"
  50. #include "utils.h"
  51. #include "md5.h"
  52. #ifdef HAVE_SELINUX
  53. #include <selinux/selinux.h>
  54. #endif
  55. #ifdef WIN32
  56. #include <winsock2.h>
  57. /* Map errno (which Winsock doesn't use) to GetLastError; include the code in the strerror */
  58. #ifdef errno
  59. #undef errno
  60. #endif /* errno */
  61. #define errno GetLastError()
  62. /** Local error string storage */
  63. static char errorstr[255];
  64. static char * print_last_windows_error() {
  65. char last_errorstr[255];
  66. DWORD last_error = GetLastError();
  67. memset(last_errorstr, 0, sizeof(last_errorstr));
  68. FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
  69. NULL, last_error, 0, last_errorstr, sizeof(last_errorstr), NULL);
  70. snprintf(errorstr, sizeof(errorstr), "%s (%lu)", last_errorstr, last_error);
  71. return errorstr;
  72. }
  73. #define strerror(x) print_last_windows_error()
  74. #endif /* WIN32 */
  75. /* globals */
  76. /** Lock protecting the chain of connections */
  77. pthread_mutex_t chain_lock;
  78. /** Lock protecting the num_threads variable */
  79. pthread_mutex_t num_threads_lock;
  80. /** Current thread count */
  81. int num_threads = 0;
  82. /** Current tunnel count */
  83. uint32_t num_tunnels = 0;
  84. /** Table indicating when a connection ID is allowable (used by proxy) */
  85. uint32_t *seq_expiry_tbl = NULL;
  86. /* Some buffer constants */
  87. const int tcp_receive_buf_len = kDefault_buf_size;
  88. const int icmp_receive_buf_len = kDefault_buf_size + kIP_header_size +
  89. kICMP_header_size + sizeof(ping_tunnel_pkt_t);
  90. const int pcap_buf_size = (kDefault_buf_size + kIP_header_size +
  91. kICMP_header_size + sizeof(ping_tunnel_pkt_t)+64)*64;
  92. /** (icmp[icmptype] = icmp-echo || icmp[icmptype] = icmp-echoreply) */
  93. char pcap_filter_program[] = "icmp";
  94. /** The chain of client/proxy connections */
  95. proxy_desc_t *chain = 0;
  96. const char *state_name[kNum_proto_types] = { "start", "ack", "data",
  97. "close", "authenticate" };
  98. /* Let the fun begin! */
  99. int main(int argc, char *argv[]) {
  100. #ifndef WIN32
  101. pid_t pid;
  102. #endif
  103. #ifdef WIN32
  104. WORD wVersionRequested;
  105. WSADATA wsaData;
  106. int err;
  107. wVersionRequested = MAKEWORD(2, 2);
  108. err = WSAStartup( wVersionRequested, &wsaData );
  109. if ( err != 0 ) {
  110. return -1;
  111. }
  112. if (LOBYTE( wsaData.wVersion ) != 2 ||
  113. HIBYTE( wsaData.wVersion ) != 2)
  114. {
  115. WSACleanup();
  116. return -1;
  117. }
  118. #endif /* WIN32 */
  119. memset(opts.password_digest, 0, kMD5_digest_size);
  120. /* The seq_expiry_tbl is used to prevent the remote ends from prematurely
  121. * re-using a sequence number.
  122. */
  123. seq_expiry_tbl = (uint32_t *) calloc(65536, sizeof(uint32_t));
  124. /* Parse options */
  125. if (parse_options(argc, argv))
  126. return -1;
  127. #ifdef HAVE_PCAP
  128. if (opts.pcap && opts.udp) {
  129. pt_log(kLog_error, "Packet capture is not supported (or needed) when using UDP for transport.\n");
  130. opts.pcap = 0;
  131. }
  132. #ifdef WIN32
  133. if (!opts.pcap && !opts.udp) {
  134. pt_log(kLog_info, "WARNING: Running ptunnel-ng on Windows in ICMP mode without WinPcap enabled is not supported and may not work!\n");
  135. }
  136. #endif
  137. #endif
  138. pt_log(kLog_info, "Starting %s.\n", PACKAGE_STRING);
  139. pt_log(kLog_info, "(c) 2004-2011 Daniel Stoedle, <daniels@cs.uit.no>\n");
  140. pt_log(kLog_info, "(c) 2017-2019 Toni Uhlig, <matzeton@googlemail.com>\n");
  141. #ifdef WIN32
  142. pt_log(kLog_info, "Windows version by Mike Miller, <mike@mikeage.net>\n");
  143. #else
  144. pt_log(kLog_info, "Security features by Sebastien Raveau, <sebastien.raveau@epita.fr>\n");
  145. #endif
  146. pt_log(kLog_info, "%s.\n", (opts.mode == kMode_forward ? "Relaying packets from incoming TCP streams" :
  147. "Forwarding incoming ping packets over TCP"));
  148. if (opts.udp)
  149. pt_log(kLog_info, "UDP transport enabled.\n");
  150. pt_log(kLog_debug, "Destination at %s:%u\n", opts.given_dst_hostname, opts.given_dst_port);
  151. /* TODO: Maybe give the user the opportunity to bind to certain addresses e.g. 127.0.0.1 ? */
  152. if (opts.mode == kMode_forward)
  153. pt_log(kLog_debug, "Listen for incoming connections at 0.0.0.0:%u\n", opts.tcp_listen_port);
  154. #ifndef WIN32
  155. signal(SIGPIPE, SIG_IGN);
  156. if (opts.use_syslog) {
  157. if (opts.log_file != stdout) {
  158. pt_log(kLog_error, "Logging using syslog overrides the use of a specified logfile (using -f).\n");
  159. fclose(opts.log_file);
  160. opts.log_file = stdout;
  161. }
  162. openlog("ptunnel", LOG_PID, LOG_USER);
  163. }
  164. if (opts.chroot) {
  165. pt_log(kLog_info, "Restricting file access to %s\n", opts.root_dir);
  166. if (-1 == chdir(opts.root_dir) || -1 == chroot(opts.root_dir)) {
  167. pt_log(kLog_error, "chdir/chroot `%s': %s\n", opts.root_dir, strerror(errno));
  168. exit(1);
  169. }
  170. }
  171. if (opts.daemonize) {
  172. pt_log(kLog_info, "Going to the background.\n");
  173. if (0 < (pid = fork()))
  174. exit(0);
  175. if (0 > pid)
  176. pt_log(kLog_error, "fork: %s\n", strerror(errno));
  177. else
  178. if (-1 == setsid())
  179. pt_log(kLog_error, "setsid: %s\n", strerror(errno));
  180. else {
  181. if (0 < (pid = fork()))
  182. exit(0);
  183. if (0 > pid)
  184. pt_log(kLog_error, "fork: %s\n", strerror(errno));
  185. else {
  186. if (NULL != opts.pid_file) {
  187. fprintf(opts.pid_file, "%d\n", getpid());
  188. fclose(opts.pid_file);
  189. }
  190. if (! freopen("/dev/null", "r", stdin) ||
  191. ! freopen("/dev/null", "w", stdout) ||
  192. ! freopen("/dev/null", "w", stderr))
  193. pt_log(kLog_error, "freopen `%s': %s\n", "/dev/null", strerror(errno));
  194. }
  195. }
  196. }
  197. #endif /* !WIN32 */
  198. pthread_mutex_init(&chain_lock, 0);
  199. pthread_mutex_init(&num_threads_lock, 0);
  200. // Check mode, validate arguments and start either client or proxy.
  201. if (opts.mode == kMode_forward) {
  202. if (!opts.given_proxy_ip || !opts.given_dst_ip || !opts.given_dst_port || !opts.tcp_listen_port) {
  203. printf("One of the options are missing or invalid.\n");
  204. print_usage(argv[0]);
  205. return -1;
  206. }
  207. pt_forwarder();
  208. }
  209. else
  210. pt_proxy(0);
  211. #ifdef WIN32
  212. WSACleanup();
  213. #else
  214. if (opts.root_dir)
  215. free(opts.root_dir);
  216. #ifdef HAVE_SELINUX
  217. if (NULL != opts.selinux_context)
  218. free(opts.selinux_context);
  219. #endif
  220. #endif /* WIN32 */
  221. pt_log(kLog_info, "ptunnel is exiting.\n");
  222. return 0;
  223. }
  224. /** pt_forwarder:
  225. * Sets up a listening TCP socket, and forwards incoming connections
  226. * over ping packets.
  227. */
  228. void pt_forwarder(void) {
  229. int server_sock, new_sock, sock, yes = 1;
  230. fd_set set;
  231. struct timeval time;
  232. struct sockaddr_in addr, dest_addr;
  233. socklen_t addr_len;
  234. pthread_t pid;
  235. uint16_t rand_id;
  236. struct in_addr in_addr;
  237. pt_log(kLog_debug, "Starting forwarder..\n");
  238. /** Open our listening socket */
  239. sock = socket(AF_INET, SOCK_STREAM, 0);
  240. if (sock < 0) {
  241. pt_log(kLog_error, "Failed to create socket: %s\n", strerror(errno));
  242. return;
  243. }
  244. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const void *) &yes, sizeof(int)) == -1) {
  245. pt_log(kLog_error, "Failed to set SO_REUSEADDR option on listening socket: %s\n", strerror(errno));
  246. close(sock);
  247. return;
  248. }
  249. addr.sin_family = AF_INET;
  250. addr.sin_port = htons(opts.tcp_listen_port);
  251. addr.sin_addr.s_addr = INADDR_ANY;
  252. memset(&(addr.sin_zero), 0, 8);
  253. if (bind(sock, (struct sockaddr*)&addr, sizeof(struct sockaddr)) == -1) {
  254. pt_log(kLog_error, "Failed to bind listening socket to port %u: %s\n", opts.tcp_listen_port, strerror(errno));
  255. close(sock);
  256. return;
  257. }
  258. server_sock = sock;
  259. /* Fill out address structure */
  260. memset(&dest_addr, 0, sizeof(struct sockaddr_in));
  261. dest_addr.sin_family = AF_INET;
  262. if (opts.udp)
  263. dest_addr.sin_port = htons(kDNS_port /* dns port.. */);
  264. else
  265. dest_addr.sin_port = 0;
  266. in_addr.s_addr = opts.given_proxy_ip;
  267. dest_addr.sin_addr.s_addr = opts.given_proxy_ip;
  268. pt_log(kLog_verbose, "Proxy IP address: %s\n", inet_ntoa(in_addr));
  269. listen(server_sock, 10);
  270. while (1) {
  271. FD_ZERO(&set);
  272. FD_SET(server_sock, &set);
  273. time.tv_sec = 1;
  274. time.tv_usec = 0;
  275. if (select(server_sock+1, &set, 0, 0, &time) > 0) {
  276. pt_log(kLog_info, "Incoming connection.\n");
  277. addr_len = sizeof(struct sockaddr_in);
  278. new_sock = accept(server_sock, (struct sockaddr*)&addr, &addr_len);
  279. if (new_sock < 0) {
  280. pt_log(kLog_error, "Accepting incoming connection failed.\n");
  281. continue;
  282. }
  283. pthread_mutex_lock(&num_threads_lock);
  284. if (num_threads <= 0) {
  285. pt_log(kLog_event, "No running proxy thread - starting it.\n");
  286. #ifndef WIN32
  287. if (pthread_create(&pid, 0, pt_proxy, 0) != 0)
  288. #else
  289. if (0 == (pid = _beginthreadex(0, 0, (unsigned int (__stdcall *)(void *))pt_proxy, 0, 0, 0)))
  290. #endif
  291. {
  292. pt_log(kLog_error, "Couldn't create thread! Dropping incoming connection.\n");
  293. close(new_sock);
  294. pthread_mutex_unlock(&num_threads_lock);
  295. continue;
  296. }
  297. }
  298. addr = dest_addr;
  299. rand_id = (uint16_t) pt_random();
  300. create_and_insert_proxy_desc(rand_id, rand_id, new_sock, &addr, opts.given_dst_ip, opts.given_dst_port, kProxy_start, kUser_flag);
  301. pthread_mutex_unlock(&num_threads_lock);
  302. }
  303. }
  304. }
  305. int pt_create_udp_socket(int port) {
  306. struct sockaddr_in addr;
  307. int sock, yes = 1;
  308. sock = socket(AF_INET, SOCK_DGRAM, 0);
  309. if (sock < 0) {
  310. pt_log(kLog_error, "Failed to set create UDP socket..\n");
  311. return 0;
  312. }
  313. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const void*)&yes, sizeof(int)) < 0) {
  314. pt_log(kLog_error, "Failed to set UDP REUSEADDR socket option. (Not fatal, hopefully.)\n");
  315. close(sock);
  316. return 0;
  317. }
  318. #ifdef SO_REUSEPORT
  319. yes = 1;
  320. if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (const void*)&yes, sizeof(int)) < 0)
  321. pt_log(kLog_error, "Failed to set UDP REUSEPORT socket option. (Not fatal, hopefully.)\n");
  322. #endif /* SO_REUSEPORT */
  323. memset(&addr, 0, sizeof(struct sockaddr_in));
  324. addr.sin_family = AF_INET;
  325. addr.sin_addr.s_addr = htonl(INADDR_ANY);
  326. addr.sin_port = htons(port);
  327. if (bind(sock, (struct sockaddr*) &addr, sizeof(struct sockaddr_in)) < 0) {
  328. pt_log(kLog_error, "Failed to bind UDP socket to port %d (try running as root).\n", port);
  329. close(sock);
  330. return 0;
  331. }
  332. return sock;
  333. }
  334. /* pt_proxy: This function does all the client and proxy stuff.
  335. */
  336. void* pt_proxy(void *args) {
  337. fd_set set;
  338. struct timeval timeout;
  339. int bytes;
  340. struct sockaddr_in addr;
  341. socklen_t addr_len;
  342. int fwd_sock = 0,
  343. max_sock = 0,
  344. idx;
  345. char *buf;
  346. double now, last_status_update = 0.0;
  347. proxy_desc_t *cur, *prev, *tmp;
  348. #ifdef HAVE_PCAP
  349. pcap_info_t pc;
  350. pcap_if_t *alldevs = 0, *pdev;
  351. #endif
  352. xfer_stats_t xfer;
  353. #ifdef HAVE_PCAP
  354. ip_packet_t *pkt;
  355. uint32_t ip;
  356. in_addr_t *adr;
  357. #endif
  358. struct in_addr in_addr;
  359. #ifdef HAVE_ICMPFILTER
  360. struct icmp_filter filt;
  361. #endif
  362. /* Start the thread, initialize protocol and ring states. */
  363. pt_log(kLog_debug, "Starting ping proxy..\n");
  364. if (opts.udp) {
  365. pt_log(kLog_debug, "Creating UDP socket..\n");
  366. if (opts.mode == kMode_proxy)
  367. fwd_sock = pt_create_udp_socket(kDNS_port);
  368. else
  369. fwd_sock = pt_create_udp_socket(0);
  370. if (!fwd_sock) {
  371. pt_log(kLog_error, "Failed to create UDP socket.\n");
  372. return 0;
  373. }
  374. }
  375. else {
  376. if (opts.unprivileged)
  377. {
  378. pt_log(kLog_debug, "Attempting to create unprivileged ICMP datagram socket..\n");
  379. fwd_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP);
  380. } else {
  381. pt_log(kLog_debug, "Attempting to create privileged ICMP raw socket..\n");
  382. fwd_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
  383. #ifdef HAVE_ICMPFILTER
  384. if (opts.mode == kMode_forward)
  385. filt.data = ~(1<<ICMP_ECHOREPLY);
  386. else
  387. filt.data = ~(1<<ICMP_ECHO);
  388. if (fwd_sock >= 0 &&
  389. setsockopt(fwd_sock, SOL_RAW, ICMP_FILTER, &filt, sizeof filt) == -1)
  390. {
  391. pt_log(kLog_error, "setockopt for ICMP_FILTER: %s\n", strerror(errno));
  392. }
  393. #endif
  394. }
  395. if (fwd_sock < 0) {
  396. pt_log(kLog_error, "Couldn't create %s socket: %s\n",
  397. (opts.unprivileged ? "unprivileged datagram" :
  398. "privileged raw"), strerror(errno));
  399. return 0;
  400. }
  401. }
  402. max_sock = fwd_sock+1;
  403. #ifdef HAVE_PCAP
  404. if (opts.pcap) {
  405. if (opts.udp) {
  406. pt_log(kLog_error, "Packet capture is not useful with UDP [should not get here!]!\n");
  407. close(fwd_sock);
  408. return 0;
  409. }
  410. if (!opts.unprivileged) {
  411. memset(&pc, 0, sizeof(pc));
  412. pt_log(kLog_info, "Initializing pcap.\n");
  413. pc.pcap_err_buf = (char *) malloc(PCAP_ERRBUF_SIZE);
  414. pc.pcap_data_buf = (char *) malloc(pcap_buf_size);
  415. pc.pcap_desc = pcap_open_live(opts.pcap_device,
  416. pcap_buf_size, 0 /* promiscous */,
  417. 50 /* ms */, pc.pcap_err_buf);
  418. if (pc.pcap_desc) {
  419. if (pcap_lookupnet(opts.pcap_device, &pc.netp,
  420. &pc.netmask, pc.pcap_err_buf) == -1)
  421. {
  422. pt_log(kLog_error, "pcap error: %s\n", pc.pcap_err_buf);
  423. opts.pcap = 0;
  424. }
  425. in_addr.s_addr = pc.netp;
  426. pt_log(kLog_verbose, "Network: %s\n", inet_ntoa(in_addr));
  427. in_addr.s_addr = pc.netmask;
  428. pt_log(kLog_verbose, "Netmask: %s\n", inet_ntoa(in_addr));
  429. if (pcap_compile(pc.pcap_desc, &pc.fp, pcap_filter_program, 0, pc.netp) == -1) {
  430. pt_log(kLog_error, "Failed to compile pcap filter program.\n");
  431. pcap_close(pc.pcap_desc);
  432. opts.pcap = 0;
  433. }
  434. else if (pcap_setfilter(pc.pcap_desc, &pc.fp) == -1) {
  435. pt_log(kLog_error, "Failed to set pcap filter program.\n");
  436. pcap_close(pc.pcap_desc);
  437. opts.pcap = 0;
  438. }
  439. }
  440. else {
  441. pt_log(kLog_error, "pcap error: %s\n", pc.pcap_err_buf);
  442. opts.pcap = 0;
  443. if (pcap_findalldevs(&alldevs, pc.pcap_err_buf) == 0) {
  444. idx = 0;
  445. pt_log(kLog_error, "Available pcap devices:\n");
  446. for (pdev = alldevs; pdev != NULL; pdev = pdev->next) {
  447. pt_log(kLog_error, "[%d] \"%s\": \"%s\"\n", ++idx,
  448. pdev->name, (pdev->description ? pdev->description : "UNKNOWN"));
  449. }
  450. pcap_freealldevs(alldevs);
  451. }
  452. }
  453. pc.pkt_q.head = 0;
  454. pc.pkt_q.tail = 0;
  455. pc.pkt_q.elems = 0;
  456. /* Check if we have succeeded, and free stuff if not */
  457. if (!opts.pcap) {
  458. pt_log(kLog_error, "There were errors enabling pcap - pcap has been disabled.\n");
  459. free(pc.pcap_err_buf);
  460. free(pc.pcap_data_buf);
  461. return 0;
  462. }
  463. }
  464. else
  465. pt_log(kLog_info, "pcap disabled since we're running in unprivileged mode.\n");
  466. }
  467. #endif
  468. pthread_mutex_lock(&num_threads_lock);
  469. num_threads++;
  470. pthread_mutex_unlock(&num_threads_lock);
  471. /* Allocate icmp receive buffer */
  472. buf = (char *) malloc(icmp_receive_buf_len);
  473. /* Start forwarding :) */
  474. pt_log(kLog_info, "Ping proxy is listening in %s mode.\n",
  475. (opts.unprivileged ? "unprivileged" : "privileged"));
  476. #ifndef WIN32
  477. #ifdef HAVE_SELINUX
  478. if (opts.uid || opts.gid || opts.selinux_context)
  479. #else
  480. if (opts.uid || opts.gid)
  481. #endif
  482. pt_log(kLog_info, "Dropping privileges now.\n");
  483. if (opts.gid && -1 == setgid(opts.gid))
  484. pt_log(kLog_error, "setgid(%d): %s\n", opts.gid, strerror(errno));
  485. if (opts.uid && -1 == setuid(opts.uid))
  486. pt_log(kLog_error, "setuid(%d): %s\n", opts.uid, strerror(errno));
  487. #ifdef HAVE_SELINUX
  488. if (opts.selinux) {
  489. if (NULL != opts.selinux_context && -1 == setcon(opts.selinux_context))
  490. pt_log(kLog_error, "setcon(%s) failed: %s\n", opts.selinux_context, strerror(errno));
  491. }
  492. #endif
  493. #endif
  494. while (1) {
  495. FD_ZERO(&set);
  496. FD_SET(fwd_sock, &set);
  497. max_sock = fwd_sock+1;
  498. pthread_mutex_lock(&chain_lock);
  499. for (cur = chain; cur; cur = cur->next) {
  500. if (cur->sock) {
  501. FD_SET(cur->sock, &set);
  502. if (cur->sock >= max_sock)
  503. max_sock = cur->sock+1;
  504. }
  505. }
  506. pthread_mutex_unlock(&chain_lock);
  507. timeout.tv_sec = 0;
  508. timeout.tv_usec = 10000;
  509. /* Don't care about return val, since we need to check for new states anyway.. */
  510. select(max_sock, &set, 0, 0, &timeout);
  511. pthread_mutex_lock(&chain_lock);
  512. for (prev = 0, cur = chain; cur && cur->sock; cur = tmp) {
  513. /* Client: If we're starting up, send a message to the remote end saying so,
  514. * causing him to connect to our desired endpoint.
  515. */
  516. if (cur->state == kProxy_start) {
  517. pt_log(kLog_verbose, "Sending proxy request.\n");
  518. cur->last_ack = time_as_double();
  519. queue_packet(fwd_sock, cur->pkt_type, 0, 0, cur->id_no, cur->id_no,
  520. &cur->my_seq, cur->send_ring, &cur->send_idx, &cur->send_wait_ack,
  521. cur->dst_ip, cur->dst_port, cur->state | cur->type_flag,
  522. &cur->dest_addr, cur->next_remote_seq, &cur->send_first_ack, &cur->ping_seq);
  523. cur->xfer.icmp_out++;
  524. cur->state = kProto_data;
  525. }
  526. if (cur->should_remove) {
  527. pt_log(kLog_info, "\nSession statistics:\n");
  528. print_statistics(&cur->xfer, 0);
  529. pt_log(kLog_info, "\n");
  530. tmp = cur->next;
  531. remove_proxy_desc(cur, prev);
  532. continue;
  533. }
  534. /* Only handle traffic if there is traffic on the socket, we have
  535. * room in our send window AND we either don't use a password, or
  536. * have been authenticated.
  537. */
  538. if (FD_ISSET(cur->sock, &set) && cur->send_wait_ack < kPing_window_size &&
  539. (!opts.password || cur->authenticated))
  540. {
  541. bytes = recv(cur->sock, cur->buf, tcp_receive_buf_len, 0);
  542. if (bytes <= 0) {
  543. pt_log(kLog_info, "Connection closed or lost.\n");
  544. tmp = cur->next;
  545. send_termination_msg(cur, fwd_sock);
  546. pt_log(kLog_info, "Session statistics:\n");
  547. print_statistics(&cur->xfer, 0);
  548. remove_proxy_desc(cur, prev);
  549. /* No need to update prev */
  550. continue;
  551. }
  552. cur->xfer.bytes_out += bytes;
  553. cur->xfer.icmp_out++;
  554. queue_packet(fwd_sock, cur->pkt_type, cur->buf, bytes, cur->id_no,
  555. cur->icmp_id, &cur->my_seq, cur->send_ring, &cur->send_idx,
  556. &cur->send_wait_ack, 0, 0, cur->state | cur->type_flag,
  557. &cur->dest_addr, cur->next_remote_seq, &cur->send_first_ack, &cur->ping_seq);
  558. }
  559. prev = cur;
  560. tmp = cur->next;
  561. }
  562. pthread_mutex_unlock(&chain_lock);
  563. if (FD_ISSET(fwd_sock, &set)) {
  564. /* Handle ping traffic */
  565. addr_len = sizeof(struct sockaddr);
  566. bytes = recvfrom(fwd_sock, buf, icmp_receive_buf_len, 0, (struct sockaddr*)&addr, &addr_len);
  567. if (bytes < 0) {
  568. pt_log(kLog_error, "Error receiving packet on ICMP socket: %s\n", strerror(errno));
  569. break;
  570. }
  571. handle_packet(buf, bytes, 0, &addr, fwd_sock);
  572. }
  573. /* Check for packets needing resend, and figure out if any connections
  574. * should be closed down due to inactivity.
  575. */
  576. pthread_mutex_lock(&chain_lock);
  577. now = time_as_double();
  578. for (cur = chain; cur; cur = cur->next) {
  579. in_addr.s_addr = cur->dst_ip;
  580. if (cur->last_activity + kAutomatic_close_timeout < now) {
  581. pt_log(kLog_info, "Dropping tunnel to %s:%d due to inactivity.\n", inet_ntoa(in_addr), cur->dst_port, cur->id_no);
  582. cur->should_remove = 1;
  583. continue;
  584. }
  585. if (cur->recv_wait_send && cur->sock)
  586. cur->xfer.bytes_in += send_packets(cur->recv_ring, &cur->recv_xfer_idx, &cur->recv_wait_send, &cur->sock);
  587. /* Check for any icmp packets requiring resend, and resend _only_ the first packet. */
  588. idx = cur->send_first_ack;
  589. if (cur->send_ring[idx].pkt && cur->send_ring[idx].last_resend+kResend_interval < now) {
  590. pt_log(kLog_debug, "Resending packet with seq-no %d.\n", cur->send_ring[idx].seq_no);
  591. cur->send_ring[idx].last_resend = now;
  592. cur->send_ring[idx].pkt->seq = htons(cur->ping_seq);
  593. cur->ping_seq++;
  594. cur->send_ring[idx].pkt->checksum = 0;
  595. cur->send_ring[idx].pkt->checksum = htons(calc_icmp_checksum((uint16_t*)cur->send_ring[idx].pkt, cur->send_ring[idx].pkt_len));
  596. /* printf("ID: %d\n", htons(cur->send_ring[idx].pkt->identifier)); */
  597. sendto(fwd_sock, (const void*)cur->send_ring[idx].pkt, cur->send_ring[idx].pkt_len,
  598. 0, (struct sockaddr*)&cur->dest_addr, sizeof(struct sockaddr));
  599. cur->xfer.icmp_resent++;
  600. }
  601. /* Figure out if it's time to send an explicit acknowledgement */
  602. if (cur->last_ack+1.0 < now && cur->send_wait_ack < kPing_window_size &&
  603. cur->remote_ack_val+1 != cur->next_remote_seq)
  604. {
  605. cur->last_ack = now;
  606. queue_packet(fwd_sock, cur->pkt_type, 0, 0, cur->id_no, cur->icmp_id,
  607. &cur->my_seq, cur->send_ring, &cur->send_idx, &cur->send_wait_ack,
  608. cur->dst_ip, cur->dst_port, kProto_ack | cur->type_flag,
  609. &cur->dest_addr, cur->next_remote_seq, &cur->send_first_ack, &cur->ping_seq);
  610. cur->xfer.icmp_ack_out++;
  611. }
  612. }
  613. pthread_mutex_unlock(&chain_lock);
  614. #ifdef HAVE_PCAP
  615. if (opts.pcap) {
  616. if (pcap_dispatch(pc.pcap_desc, 32, pcap_packet_handler, (u_char*)&pc.pkt_q) > 0) {
  617. pqueue_elem_t *cur;
  618. pt_log(kLog_verbose, "pcap captured %d packets - handling them..\n", pc.pkt_q.elems);
  619. while (pc.pkt_q.head) {
  620. cur = pc.pkt_q.head;
  621. memset(&addr, 0, sizeof(struct sockaddr));
  622. addr.sin_family = AF_INET;
  623. pkt = (ip_packet_t*)&cur->data[0];
  624. ip = pkt->src_ip;
  625. adr = (in_addr_t*)&ip;
  626. addr.sin_addr.s_addr = *adr;
  627. handle_packet(cur->data, cur->bytes, 1, &addr, fwd_sock);
  628. pc.pkt_q.head = cur->next;
  629. free(cur);
  630. pc.pkt_q.elems--;
  631. }
  632. pc.pkt_q.tail = 0;
  633. pc.pkt_q.head = 0;
  634. }
  635. }
  636. #endif
  637. /* Update running statistics, if requested (only once every second) */
  638. if (opts.print_stats && opts.mode == kMode_forward && now > last_status_update+1) {
  639. pthread_mutex_lock(&chain_lock);
  640. memset(&xfer, 0, sizeof(xfer_stats_t));
  641. for (cur = chain; cur; cur = cur->next) {
  642. xfer.bytes_in += cur->xfer.bytes_in;
  643. xfer.bytes_out += cur->xfer.bytes_out;
  644. xfer.icmp_in += cur->xfer.icmp_in;
  645. xfer.icmp_out += cur->xfer.icmp_out;
  646. xfer.icmp_resent += cur->xfer.icmp_resent;
  647. }
  648. pthread_mutex_unlock(&chain_lock);
  649. print_statistics(&xfer, (opts.log_level >= kLog_verbose ? 0 : 1));
  650. last_status_update = now;
  651. }
  652. }
  653. pt_log(kLog_debug, "Proxy exiting..\n");
  654. if (fwd_sock)
  655. close(fwd_sock);
  656. /* TODO: Clean up the other descs. Not really a priority since there's no
  657. * real way to quit ptunnel in the first place..
  658. */
  659. free(buf);
  660. pt_log(kLog_debug, "Ping proxy done\n");
  661. return 0;
  662. }
  663. /* print_statistics: Prints transfer statistics for the given xfer block. The
  664. * is_continuous variable controls the output mode, either printing a new line
  665. * or overwriting the old line.
  666. */
  667. void print_statistics(xfer_stats_t *xfer, int is_continuous) {
  668. const double mb = 1024.0*1024.0;
  669. double loss = 0.0;
  670. if (xfer->icmp_out > 0)
  671. loss = (double)xfer->icmp_resent/(double)xfer->icmp_out;
  672. if (is_continuous)
  673. printf("\r");
  674. printf("[inf]: I/O: %6.2f/%6.2f mb ICMP I/O/R: %8u/%8u/%8u Loss: %4.1f%%",
  675. xfer->bytes_in/mb, xfer->bytes_out/mb, xfer->icmp_in, xfer->icmp_out, xfer->icmp_resent, loss);
  676. if (!is_continuous)
  677. printf("\n");
  678. else
  679. fflush(stdout);
  680. }
  681. #ifdef HAVE_PCAP
  682. /* pcap_packet_handler:
  683. * This is our callback function handling captured packets. We already know that the packets
  684. * are ICMP echo or echo-reply messages, so all we need to do is strip off the ethernet header
  685. * and append it to the queue descriptor (the refcon argument).
  686. *
  687. * Ok, the above isn't entirely correct (we can get other ICMP types as well). This function
  688. * also has problems when it captures packets on the loopback interface. The moral of the
  689. * story: Don't do ping forwarding over the loopback interface.
  690. *
  691. * Also, we currently don't support anything else than ethernet when in pcap mode. The reason
  692. * is that I haven't read up on yet on how to remove the frame header from the packet..
  693. */
  694. void pcap_packet_handler(u_char *refcon, const struct pcap_pkthdr *hdr, const u_char* pkt) {
  695. pqueue_t *q;
  696. pqueue_elem_t *elem;
  697. ip_packet_t *ip;
  698. /* pt_log(kLog_verbose, "Packet handler: %d =? %d\n", hdr->caplen, hdr->len); */
  699. q = (pqueue_t*)refcon;
  700. elem = (pqueue_elem_t *) malloc(sizeof(pqueue_elem_t)+hdr->caplen-sizeof(struct ether_header));
  701. memcpy(elem->data, pkt+sizeof(struct ether_header), hdr->caplen-sizeof(struct ether_header));
  702. ip = (ip_packet_t*)elem->data;
  703. /* TODO: Add fragment support */
  704. elem->bytes = ntohs(ip->pkt_len);
  705. if (elem->bytes > hdr->caplen-sizeof(struct ether_header)) {
  706. pt_log(kLog_error, "Received fragmented packet - unable to reconstruct!\n");
  707. pt_log(kLog_error, "This error usually occurs because pcap is used on "
  708. "devices that are not wlan or ethernet.\n");
  709. free(elem);
  710. return;
  711. }
  712. /* elem->bytes = hdr->caplen-sizeof(struct ether_header); */
  713. elem->next = 0;
  714. if (q->tail) {
  715. q->tail->next = elem;
  716. q->tail = elem;
  717. }
  718. else {
  719. q->head = elem;
  720. q->tail = elem;
  721. }
  722. q->elems++;
  723. }
  724. #endif
  725. uint16_t calc_icmp_checksum(uint16_t *data, int bytes) {
  726. uint32_t sum;
  727. int i;
  728. sum = 0;
  729. for (i = 0; i < bytes / 2; i++) {
  730. /* WARNING; this might be a bug, but might explain why I occasionally
  731. * see buggy checksums.. (added htons, that might be the correct behaviour)
  732. */
  733. sum += data[i];
  734. }
  735. sum = (sum & 0xFFFF) + (sum >> 16);
  736. sum = htons(0xFFFF - sum);
  737. return sum;
  738. }
  739. /* send_termination_msg: Sends two packets to the remote end, informing it that
  740. * the tunnel is being closed down.
  741. */
  742. void send_termination_msg(proxy_desc_t *cur, int icmp_sock) {
  743. /* Send packet twice, hoping at least one of them makes it through.. */
  744. queue_packet(icmp_sock, cur->pkt_type, 0, 0, cur->id_no, cur->icmp_id, &cur->my_seq,
  745. cur->send_ring, &cur->send_idx, &cur->send_wait_ack, 0, 0,
  746. kProto_close | cur->type_flag, &cur->dest_addr, cur->next_remote_seq,
  747. &cur->send_first_ack, &cur->ping_seq);
  748. queue_packet(icmp_sock, cur->pkt_type, 0, 0, cur->id_no, cur->icmp_id, &cur->my_seq,
  749. cur->send_ring, &cur->send_idx, &cur->send_wait_ack, 0, 0,
  750. kProto_close | cur->type_flag, &cur->dest_addr, cur->next_remote_seq,
  751. &cur->send_first_ack, &cur->ping_seq);
  752. cur->xfer.icmp_out += 2;
  753. }