PageRenderTime 75ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/ncat/ncat_listen.c

https://gitlab.com/g10h4ck/nmap-gsoc2015
C | 1149 lines | 733 code | 156 blank | 260 comment | 231 complexity | ee552f3358e4189cc507ee0509a53f86 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, Apache-2.0, LGPL-2.0, LGPL-2.1, MIT
  1. /***************************************************************************
  2. * ncat_listen.c -- --listen mode. *
  3. ***********************IMPORTANT NMAP LICENSE TERMS************************
  4. * *
  5. * The Nmap Security Scanner is (C) 1996-2015 Insecure.Com LLC. Nmap is *
  6. * also a registered trademark of Insecure.Com LLC. This program is free *
  7. * software; you may redistribute and/or modify it under the terms of the *
  8. * GNU General Public License as published by the Free Software *
  9. * Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE CLARIFICATIONS *
  10. * AND EXCEPTIONS DESCRIBED HEREIN. This guarantees your right to use, *
  11. * modify, and redistribute this software under certain conditions. If *
  12. * you wish to embed Nmap technology into proprietary software, we sell *
  13. * alternative licenses (contact sales@nmap.com). Dozens of software *
  14. * vendors already license Nmap technology such as host discovery, port *
  15. * scanning, OS detection, version detection, and the Nmap Scripting *
  16. * Engine. *
  17. * *
  18. * Note that the GPL places important restrictions on "derivative works", *
  19. * yet it does not provide a detailed definition of that term. To avoid *
  20. * misunderstandings, we interpret that term as broadly as copyright law *
  21. * allows. For example, we consider an application to constitute a *
  22. * derivative work for the purpose of this license if it does any of the *
  23. * following with any software or content covered by this license *
  24. * ("Covered Software"): *
  25. * *
  26. * o Integrates source code from Covered Software. *
  27. * *
  28. * o Reads or includes copyrighted data files, such as Nmap's nmap-os-db *
  29. * or nmap-service-probes. *
  30. * *
  31. * o Is designed specifically to execute Covered Software and parse the *
  32. * results (as opposed to typical shell or execution-menu apps, which will *
  33. * execute anything you tell them to). *
  34. * *
  35. * o Includes Covered Software in a proprietary executable installer. The *
  36. * installers produced by InstallShield are an example of this. Including *
  37. * Nmap with other software in compressed or archival form does not *
  38. * trigger this provision, provided appropriate open source decompression *
  39. * or de-archiving software is widely available for no charge. For the *
  40. * purposes of this license, an installer is considered to include Covered *
  41. * Software even if it actually retrieves a copy of Covered Software from *
  42. * another source during runtime (such as by downloading it from the *
  43. * Internet). *
  44. * *
  45. * o Links (statically or dynamically) to a library which does any of the *
  46. * above. *
  47. * *
  48. * o Executes a helper program, module, or script to do any of the above. *
  49. * *
  50. * This list is not exclusive, but is meant to clarify our interpretation *
  51. * of derived works with some common examples. Other people may interpret *
  52. * the plain GPL differently, so we consider this a special exception to *
  53. * the GPL that we apply to Covered Software. Works which meet any of *
  54. * these conditions must conform to all of the terms of this license, *
  55. * particularly including the GPL Section 3 requirements of providing *
  56. * source code and allowing free redistribution of the work as a whole. *
  57. * *
  58. * As another special exception to the GPL terms, Insecure.Com LLC grants *
  59. * permission to link the code of this program with any version of the *
  60. * OpenSSL library which is distributed under a license identical to that *
  61. * listed in the included docs/licenses/OpenSSL.txt file, and distribute *
  62. * linked combinations including the two. *
  63. * *
  64. * Any redistribution of Covered Software, including any derived works, *
  65. * must obey and carry forward all of the terms of this license, including *
  66. * obeying all GPL rules and restrictions. For example, source code of *
  67. * the whole work must be provided and free redistribution must be *
  68. * allowed. All GPL references to "this License", are to be treated as *
  69. * including the terms and conditions of this license text as well. *
  70. * *
  71. * Because this license imposes special exceptions to the GPL, Covered *
  72. * Work may not be combined (even as part of a larger work) with plain GPL *
  73. * software. The terms, conditions, and exceptions of this license must *
  74. * be included as well. This license is incompatible with some other open *
  75. * source licenses as well. In some cases we can relicense portions of *
  76. * Nmap or grant special permissions to use it in other open source *
  77. * software. Please contact fyodor@nmap.org with any such requests. *
  78. * Similarly, we don't incorporate incompatible open source software into *
  79. * Covered Software without special permission from the copyright holders. *
  80. * *
  81. * If you have any questions about the licensing restrictions on using *
  82. * Nmap in other works, are happy to help. As mentioned above, we also *
  83. * offer alternative license to integrate Nmap into proprietary *
  84. * applications and appliances. These contracts have been sold to dozens *
  85. * of software vendors, and generally include a perpetual license as well *
  86. * as providing for priority support and updates. They also fund the *
  87. * continued development of Nmap. Please email sales@nmap.com for further *
  88. * information. *
  89. * *
  90. * If you have received a written license agreement or contract for *
  91. * Covered Software stating terms other than these, you may choose to use *
  92. * and redistribute Covered Software under those terms instead of these. *
  93. * *
  94. * Source is provided to this software because we believe users have a *
  95. * right to know exactly what a program is going to do before they run it. *
  96. * This also allows you to audit the software for security holes. *
  97. * *
  98. * Source code also allows you to port Nmap to new platforms, fix bugs, *
  99. * and add new features. You are highly encouraged to send your changes *
  100. * to the dev@nmap.org mailing list for possible incorporation into the *
  101. * main distribution. By sending these changes to Fyodor or one of the *
  102. * Insecure.Org development mailing lists, or checking them into the Nmap *
  103. * source code repository, it is understood (unless you specify otherwise) *
  104. * that you are offering the Nmap Project (Insecure.Com LLC) the *
  105. * unlimited, non-exclusive right to reuse, modify, and relicense the *
  106. * code. Nmap will always be available Open Source, but this is important *
  107. * because the inability to relicense code has caused devastating problems *
  108. * for other Free Software projects (such as KDE and NASM). We also *
  109. * occasionally relicense the code to third parties as discussed above. *
  110. * If you wish to specify special license conditions of your *
  111. * contributions, just say so when you send them. *
  112. * *
  113. * This program is distributed in the hope that it will be useful, but *
  114. * WITHOUT ANY WARRANTY; without even the implied warranty of *
  115. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Nmap *
  116. * license file for more details (it's in a COPYING file included with *
  117. * Nmap, and also available from https://svn.nmap.org/nmap/COPYING) *
  118. * *
  119. ***************************************************************************/
  120. /* $Id$ */
  121. #include "ncat.h"
  122. #include <errno.h>
  123. #include <signal.h>
  124. #include <stdio.h>
  125. #include <stdlib.h>
  126. #include <string.h>
  127. #include <sys/types.h>
  128. #include <limits.h>
  129. #ifndef WIN32
  130. #include <unistd.h>
  131. #include <sys/socket.h>
  132. #include <netinet/in.h>
  133. #include <arpa/inet.h>
  134. #include <sys/wait.h>
  135. #else
  136. #include <fcntl.h>
  137. #endif
  138. #if HAVE_SYS_UN_H
  139. #include <sys/un.h>
  140. #endif
  141. #ifdef HAVE_OPENSSL
  142. #include <openssl/ssl.h>
  143. #include <openssl/err.h>
  144. #endif
  145. #ifdef WIN32
  146. /* Define missing constant for shutdown(2).
  147. * See:
  148. * http://msdn.microsoft.com/en-us/library/windows/desktop/ms740481%28v=vs.85%29.aspx
  149. */
  150. #define SHUT_WR SD_SEND
  151. #endif
  152. /* read_fds is the clients we are accepting data from. broadcast_fds is the
  153. clients were are sending data to. broadcast_fds doesn't include the listening
  154. socket and stdin. Network clients are not added to read_fds when --send-only
  155. is used, because they would be always selected without having data read.
  156. write_fds is the list of clients that are waiting for some kind of response
  157. from us, like a pending ssl negotiation. */
  158. static fd_set master_readfds, master_writefds, master_broadcastfds;
  159. #ifdef HAVE_OPENSSL
  160. /* sslpending_fds contains the list of ssl sockets that are waiting to complete
  161. the ssl handshake */
  162. static fd_set sslpending_fds;
  163. #endif
  164. /* These are bookkeeping data structures that are parallel to read_fds and
  165. broadcast_fds. */
  166. static fd_list_t client_fdlist, broadcast_fdlist;
  167. static int listen_socket[NUM_LISTEN_ADDRS];
  168. /* Has stdin seen EOF? */
  169. static int stdin_eof = 0;
  170. static int crlf_state = 0;
  171. static void handle_connection(int socket_accept);
  172. static int read_stdin(void);
  173. static int read_socket(int recv_fd);
  174. static void post_handle_connection(struct fdinfo sinfo);
  175. static void read_and_broadcast(int recv_socket);
  176. static void shutdown_sockets(int how);
  177. static int chat_announce_connect(int fd, const union sockaddr_u *su);
  178. static int chat_announce_disconnect(int fd);
  179. static char *chat_filter(char *buf, size_t size, int fd, int *nwritten);
  180. /* The number of connected clients is the difference of conn_inc and conn_dec.
  181. It is split up into two variables for signal safety. conn_dec is modified
  182. (asynchronously) only in signal handlers and conn_inc is modified
  183. (synchronously) only in the main program. get_conn_count loops while conn_dec
  184. is being modified. */
  185. static unsigned int conn_inc = 0;
  186. static volatile unsigned int conn_dec = 0;
  187. static volatile sig_atomic_t conn_dec_changed;
  188. static void decrease_conn_count(void)
  189. {
  190. conn_dec_changed = 1;
  191. conn_dec++;
  192. }
  193. static int get_conn_count(void)
  194. {
  195. unsigned int count;
  196. /* conn_dec is modified in a signal handler, so loop until it stops
  197. changing. */
  198. do {
  199. conn_dec_changed = 0;
  200. count = conn_inc - conn_dec;
  201. } while (conn_dec_changed);
  202. ncat_assert(count <= INT_MAX);
  203. return count;
  204. }
  205. #ifndef WIN32
  206. static void sigchld_handler(int signum)
  207. {
  208. while (waitpid(-1, NULL, WNOHANG) > 0)
  209. decrease_conn_count();
  210. }
  211. #endif
  212. static int ncat_listen_stream(int proto)
  213. {
  214. int rc, i, fds_ready;
  215. fd_set listen_fds;
  216. struct timeval tv;
  217. struct timeval *tvp = NULL;
  218. unsigned int num_sockets;
  219. /* clear out structs */
  220. FD_ZERO(&master_readfds);
  221. FD_ZERO(&master_writefds);
  222. FD_ZERO(&master_broadcastfds);
  223. FD_ZERO(&listen_fds);
  224. #ifdef HAVE_OPENSSL
  225. FD_ZERO(&sslpending_fds);
  226. #endif
  227. zmem(&client_fdlist, sizeof(client_fdlist));
  228. zmem(&broadcast_fdlist, sizeof(broadcast_fdlist));
  229. #ifdef WIN32
  230. set_pseudo_sigchld_handler(decrease_conn_count);
  231. #else
  232. /* Reap on SIGCHLD */
  233. Signal(SIGCHLD, sigchld_handler);
  234. /* Ignore the SIGPIPE that occurs when a client disconnects suddenly and we
  235. send data to it before noticing. */
  236. Signal(SIGPIPE, SIG_IGN);
  237. #endif
  238. #ifdef HAVE_OPENSSL
  239. if (o.ssl)
  240. setup_ssl_listen();
  241. #endif
  242. /* We need a list of fds to keep current fdmax. The second parameter is a
  243. number added to the supplied connection limit, that will compensate
  244. maxfds for the added by default listen and stdin sockets. */
  245. init_fdlist(&client_fdlist, sadd(o.conn_limit, num_listenaddrs + 1));
  246. for (i = 0; i < NUM_LISTEN_ADDRS; i++)
  247. listen_socket[i] = -1;
  248. num_sockets = 0;
  249. for (i = 0; i < num_listenaddrs; i++) {
  250. /* setup the main listening socket */
  251. listen_socket[num_sockets] = do_listen(SOCK_STREAM, proto, &listenaddrs[i]);
  252. if (listen_socket[num_sockets] == -1) {
  253. if (o.debug > 0)
  254. logdebug("do_listen(\"%s\"): %s\n", inet_ntop_ez(&listenaddrs[i].storage, sizeof(listenaddrs[i].storage)), socket_strerror(socket_errno()));
  255. continue;
  256. }
  257. /* Make our listening socket non-blocking because there are timing issues
  258. * which could cause us to block on accept() even though select() says it's
  259. * readable. See UNPv1 2nd ed, p422 for more.
  260. */
  261. unblock_socket(listen_socket[num_sockets]);
  262. /* setup select sets and max fd */
  263. FD_SET(listen_socket[num_sockets], &master_readfds);
  264. add_fd(&client_fdlist, listen_socket[num_sockets]);
  265. FD_SET(listen_socket[num_sockets], &listen_fds);
  266. num_sockets++;
  267. }
  268. if (num_sockets == 0) {
  269. if (num_listenaddrs == 1)
  270. bye("Unable to open listening socket on %s: %s", inet_ntop_ez(&listenaddrs[0].storage, sizeof(listenaddrs[0].storage)), socket_strerror(socket_errno()));
  271. else
  272. bye("Unable to open any listening sockets.");
  273. }
  274. add_fd(&client_fdlist, STDIN_FILENO);
  275. init_fdlist(&broadcast_fdlist, o.conn_limit);
  276. if (o.idletimeout > 0)
  277. tvp = &tv;
  278. while (1) {
  279. /* We pass these temporary descriptor sets to fselect, since fselect
  280. modifies the sets it receives. */
  281. fd_set readfds = master_readfds, writefds = master_writefds;
  282. struct fdinfo *fdi = NULL;
  283. if (o.debug > 1)
  284. logdebug("selecting, fdmax %d\n", client_fdlist.fdmax);
  285. if (o.debug > 1 && o.broker)
  286. logdebug("Broker connection count is %d\n", get_conn_count());
  287. if (o.idletimeout > 0)
  288. ms_to_timeval(tvp, o.idletimeout);
  289. fds_ready = fselect(client_fdlist.fdmax + 1, &readfds, &writefds, NULL, tvp);
  290. if (o.debug > 1)
  291. logdebug("select returned %d fds ready\n", fds_ready);
  292. if (fds_ready == 0)
  293. bye("Idle timeout expired (%d ms).", o.idletimeout);
  294. /*
  295. * FIXME: optimize this loop to look only at the fds in the fd list,
  296. * doing it this way means that if you have one descriptor that is very
  297. * large, say 500, and none close to it, that you'll loop many times for
  298. * nothing.
  299. */
  300. for (i = 0; i <= client_fdlist.fdmax && fds_ready > 0; i++) {
  301. /* Loop through descriptors until there's something to read */
  302. if (!FD_ISSET(i, &readfds) && !FD_ISSET(i, &writefds))
  303. continue;
  304. if (o.debug > 1)
  305. logdebug("fd %d is ready\n", i);
  306. #ifdef HAVE_OPENSSL
  307. /* Is this an ssl socket pending a handshake? If so handle it. */
  308. if (o.ssl && FD_ISSET(i, &sslpending_fds)) {
  309. FD_CLR(i, &master_readfds);
  310. FD_CLR(i, &master_writefds);
  311. fdi = get_fdinfo(&client_fdlist, i);
  312. ncat_assert(fdi != NULL);
  313. switch (ssl_handshake(fdi)) {
  314. case NCAT_SSL_HANDSHAKE_COMPLETED:
  315. /* Clear from sslpending_fds once ssl is established */
  316. FD_CLR(i, &sslpending_fds);
  317. post_handle_connection(*fdi);
  318. break;
  319. case NCAT_SSL_HANDSHAKE_PENDING_WRITE:
  320. FD_SET(i, &master_writefds);
  321. break;
  322. case NCAT_SSL_HANDSHAKE_PENDING_READ:
  323. FD_SET(i, &master_readfds);
  324. break;
  325. case NCAT_SSL_HANDSHAKE_FAILED:
  326. default:
  327. SSL_free(fdi->ssl);
  328. Close(fdi->fd);
  329. FD_CLR(i, &sslpending_fds);
  330. FD_CLR(i, &master_readfds);
  331. rm_fd(&client_fdlist, i);
  332. /* Are we in single listening mode(without -k)? If so
  333. then we should quit also. */
  334. if (!o.keepopen && !o.broker)
  335. return 1;
  336. --conn_inc;
  337. break;
  338. }
  339. } else
  340. #endif
  341. if (FD_ISSET(i, &listen_fds)) {
  342. /* we have a new connection request */
  343. handle_connection(i);
  344. } else if (i == STDIN_FILENO) {
  345. if (o.broker) {
  346. read_and_broadcast(i);
  347. } else {
  348. /* Read from stdin and write to all clients. */
  349. rc = read_stdin();
  350. if (rc == 0) {
  351. if (o.proto != IPPROTO_TCP || (o.proto == IPPROTO_TCP && o.sendonly)) {
  352. /* There will be nothing more to send. If we're not
  353. receiving anything, we can quit here. */
  354. return 0;
  355. }
  356. shutdown_sockets(SHUT_WR);
  357. }
  358. if (rc < 0)
  359. return 1;
  360. }
  361. } else if (!o.sendonly) {
  362. if (o.broker) {
  363. read_and_broadcast(i);
  364. } else {
  365. /* Read from a client and write to stdout. */
  366. rc = read_socket(i);
  367. if (rc <= 0 && !o.keepopen)
  368. return rc == 0 ? 0 : 1;
  369. }
  370. }
  371. fds_ready--;
  372. }
  373. }
  374. return 0;
  375. }
  376. /* Accept a connection on a listening socket. Allow or deny the connection.
  377. Fork a command if o.cmdexec is set. Otherwise, add the new socket to the
  378. watch set. */
  379. static void handle_connection(int socket_accept)
  380. {
  381. union sockaddr_u remoteaddr;
  382. socklen_t ss_len;
  383. struct fdinfo s = { 0 };
  384. int conn_count;
  385. zmem(&s, sizeof(s));
  386. zmem(&remoteaddr, sizeof(remoteaddr.storage));
  387. ss_len = sizeof(remoteaddr.storage);
  388. errno = 0;
  389. s.fd = accept(socket_accept, &remoteaddr.sockaddr, &ss_len);
  390. if (s.fd < 0) {
  391. if (o.debug)
  392. logdebug("Error in accept: %s\n", strerror(errno));
  393. close(s.fd);
  394. return;
  395. }
  396. if (o.verbose) {
  397. #if HAVE_SYS_UN_H
  398. if (remoteaddr.sockaddr.sa_family == AF_UNIX)
  399. loguser("Connection from a client on Unix domain socket.\n");
  400. else
  401. #endif
  402. if (o.chat)
  403. loguser("Connection from %s on file descriptor %d.\n", inet_socktop(&remoteaddr), s.fd);
  404. else
  405. loguser("Connection from %s.\n", inet_socktop(&remoteaddr));
  406. }
  407. if (!o.keepopen && !o.broker) {
  408. int i;
  409. for (i = 0; i < num_listenaddrs; i++) {
  410. Close(listen_socket[i]);
  411. FD_CLR(listen_socket[i], &master_readfds);
  412. rm_fd(&client_fdlist, listen_socket[i]);
  413. }
  414. }
  415. if (o.verbose) {
  416. #if HAVE_SYS_UN_H
  417. if (remoteaddr.sockaddr.sa_family == AF_UNIX)
  418. loguser("Connection from %s.\n", remoteaddr.un.sun_path);
  419. else
  420. #endif
  421. loguser("Connection from %s:%hu.\n", inet_socktop(&remoteaddr), inet_port(&remoteaddr));
  422. }
  423. /* Check conditions that might cause us to deny the connection. */
  424. conn_count = get_conn_count();
  425. if (conn_count >= o.conn_limit) {
  426. if (o.verbose)
  427. loguser("New connection denied: connection limit reached (%d)\n", conn_count);
  428. Close(s.fd);
  429. return;
  430. }
  431. if (!allow_access(&remoteaddr)) {
  432. if (o.verbose)
  433. loguser("New connection denied: not allowed\n");
  434. Close(s.fd);
  435. return;
  436. }
  437. s.remoteaddr = remoteaddr;
  438. conn_inc++;
  439. unblock_socket(s.fd);
  440. #ifdef HAVE_OPENSSL
  441. if (o.ssl) {
  442. /* Add the socket to the necessary descriptor lists. */
  443. FD_SET(s.fd, &sslpending_fds);
  444. FD_SET(s.fd, &master_readfds);
  445. FD_SET(s.fd, &master_writefds);
  446. /* Add it to our list of fds too for maintaining maxfd. */
  447. if (add_fdinfo(&client_fdlist, &s) < 0)
  448. bye("add_fdinfo() failed.");
  449. } else
  450. #endif
  451. post_handle_connection(s);
  452. }
  453. /* This function handles the post connection specific actions that are needed
  454. * after a socket has been initialized(normal socket or ssl socket). */
  455. static void post_handle_connection(struct fdinfo sinfo)
  456. {
  457. /*
  458. * Are we executing a command? If so then don't add this guy
  459. * to our descriptor list or set.
  460. */
  461. if (o.cmdexec) {
  462. if (o.keepopen)
  463. netrun(&sinfo, o.cmdexec);
  464. else
  465. netexec(&sinfo, o.cmdexec);
  466. } else {
  467. /* Now that a client is connected, pay attention to stdin. */
  468. if (!stdin_eof)
  469. FD_SET(STDIN_FILENO, &master_readfds);
  470. if (!o.sendonly) {
  471. /* add to our lists */
  472. FD_SET(sinfo.fd, &master_readfds);
  473. /* add it to our list of fds for maintaining maxfd */
  474. #ifdef HAVE_OPENSSL
  475. /* Don't add it twice (see handle_connection above) */
  476. if (!o.ssl)
  477. #endif
  478. if (add_fdinfo(&client_fdlist, &sinfo) < 0)
  479. bye("add_fdinfo() failed.");
  480. }
  481. FD_SET(sinfo.fd, &master_broadcastfds);
  482. if (add_fdinfo(&broadcast_fdlist, &sinfo) < 0)
  483. bye("add_fdinfo() failed.");
  484. if (o.chat)
  485. chat_announce_connect(sinfo.fd, &sinfo.remoteaddr);
  486. }
  487. }
  488. /* Read from stdin and broadcast to all client sockets. Return the number of
  489. bytes read, or -1 on error. */
  490. int read_stdin(void)
  491. {
  492. int nbytes;
  493. char buf[DEFAULT_TCP_BUF_LEN];
  494. char *tempbuf = NULL;
  495. nbytes = read(STDIN_FILENO, buf, sizeof(buf));
  496. if (nbytes <= 0) {
  497. if (nbytes < 0 && o.verbose)
  498. logdebug("Error reading from stdin: %s\n", strerror(errno));
  499. if (nbytes == 0 && o.debug)
  500. logdebug("EOF on stdin\n");
  501. /* Don't close the file because that allows a socket to be fd 0. */
  502. FD_CLR(STDIN_FILENO, &master_readfds);
  503. /* Buf mark that we've seen EOF so it doesn't get re-added to the
  504. select list. */
  505. stdin_eof = 1;
  506. return nbytes;
  507. }
  508. if (o.crlf)
  509. fix_line_endings((char *) buf, &nbytes, &tempbuf, &crlf_state);
  510. if (o.linedelay)
  511. ncat_delay_timer(o.linedelay);
  512. /* Write to everything in the broadcast set. */
  513. if (tempbuf != NULL) {
  514. ncat_broadcast(&master_broadcastfds, &broadcast_fdlist, tempbuf, nbytes);
  515. free(tempbuf);
  516. tempbuf = NULL;
  517. } else {
  518. ncat_broadcast(&master_broadcastfds, &broadcast_fdlist, buf, nbytes);
  519. }
  520. return nbytes;
  521. }
  522. /* Read from a client socket and write to stdout. Return the number of bytes
  523. read from the socket, or -1 on error. */
  524. int read_socket(int recv_fd)
  525. {
  526. char buf[DEFAULT_TCP_BUF_LEN];
  527. struct fdinfo *fdn;
  528. int nbytes, pending;
  529. fdn = get_fdinfo(&client_fdlist, recv_fd);
  530. ncat_assert(fdn != NULL);
  531. nbytes = 0;
  532. do {
  533. int n;
  534. n = ncat_recv(fdn, buf, sizeof(buf), &pending);
  535. if (n <= 0) {
  536. if (o.debug)
  537. logdebug("Closing connection.\n");
  538. #ifdef HAVE_OPENSSL
  539. if (o.ssl && fdn->ssl) {
  540. if (nbytes == 0)
  541. SSL_shutdown(fdn->ssl);
  542. SSL_free(fdn->ssl);
  543. }
  544. #endif
  545. close(recv_fd);
  546. FD_CLR(recv_fd, &master_readfds);
  547. rm_fd(&client_fdlist, recv_fd);
  548. FD_CLR(recv_fd, &master_broadcastfds);
  549. rm_fd(&broadcast_fdlist, recv_fd);
  550. conn_inc--;
  551. if (get_conn_count() == 0)
  552. FD_CLR(STDIN_FILENO, &master_readfds);
  553. return n;
  554. }
  555. Write(STDOUT_FILENO, buf, n);
  556. nbytes += n;
  557. } while (pending);
  558. return nbytes;
  559. }
  560. /* This is sufficiently different from the TCP code (wrt SSL, etc) that it
  561. * resides in its own simpler function
  562. */
  563. static int ncat_listen_dgram(int proto)
  564. {
  565. struct {
  566. int fd;
  567. union sockaddr_u addr;
  568. } sockfd[NUM_LISTEN_ADDRS];
  569. int i, fdn = -1;
  570. int fdmax, nbytes, n, fds_ready;
  571. char buf[DEFAULT_UDP_BUF_LEN] = { 0 };
  572. char *tempbuf = NULL;
  573. fd_set read_fds;
  574. union sockaddr_u remotess;
  575. socklen_t sslen = sizeof(remotess.storage);
  576. struct timeval tv;
  577. struct timeval *tvp = NULL;
  578. unsigned int num_sockets;
  579. for (i = 0; i < NUM_LISTEN_ADDRS; i++) {
  580. sockfd[i].fd = -1;
  581. sockfd[i].addr.storage.ss_family = AF_UNSPEC;
  582. }
  583. FD_ZERO(&read_fds);
  584. /* Initialize remotess struct so recvfrom() doesn't hit the fan.. */
  585. zmem(&remotess.storage, sizeof(remotess.storage));
  586. remotess.storage.ss_family = o.af;
  587. #ifdef WIN32
  588. set_pseudo_sigchld_handler(decrease_conn_count);
  589. #else
  590. /* Reap on SIGCHLD */
  591. Signal(SIGCHLD, sigchld_handler);
  592. /* Ignore the SIGPIPE that occurs when a client disconnects suddenly and we
  593. send data to it before noticing. */
  594. Signal(SIGPIPE, SIG_IGN);
  595. #endif
  596. /* set for selecting udp listening sockets */
  597. fd_set listen_fds;
  598. fd_list_t listen_fdlist;
  599. FD_ZERO(&listen_fds);
  600. init_fdlist(&listen_fdlist, num_listenaddrs);
  601. num_sockets = 0;
  602. for (i = 0; i < num_listenaddrs; i++) {
  603. /* create the UDP listen sockets */
  604. sockfd[num_sockets].fd = do_listen(SOCK_DGRAM, proto, &listenaddrs[i]);
  605. if (sockfd[num_sockets].fd == -1) {
  606. if (o.debug > 0)
  607. logdebug("do_listen(\"%s\"): %s\n", inet_ntop_ez(&listenaddrs[i].storage, sizeof(listenaddrs[i].storage)), socket_strerror(socket_errno()));
  608. continue;
  609. }
  610. FD_SET(sockfd[num_sockets].fd, &listen_fds);
  611. add_fd(&listen_fdlist, sockfd[num_sockets].fd);
  612. sockfd[num_sockets].addr = listenaddrs[i];
  613. num_sockets++;
  614. }
  615. if (num_sockets == 0) {
  616. if (num_listenaddrs == 1)
  617. bye("Unable to open listening socket on %s: %s", inet_ntop_ez(&listenaddrs[0].storage, sizeof(listenaddrs[0].storage)), socket_strerror(socket_errno()));
  618. else
  619. bye("Unable to open any listening sockets.");
  620. }
  621. if (o.idletimeout > 0)
  622. tvp = &tv;
  623. while (1) {
  624. int i, j, conn_count, socket_n;
  625. if (fdn != -1) {
  626. /*remove socket descriptor which is burnt */
  627. FD_CLR(sockfd[fdn].fd, &listen_fds);
  628. rm_fd(&listen_fdlist, sockfd[fdn].fd);
  629. /* Rebuild the udp socket which got burnt */
  630. sockfd[fdn].fd = do_listen(SOCK_DGRAM, proto, &sockfd[fdn].addr);
  631. if (sockfd[fdn].fd == -1)
  632. bye("do_listen: %s", socket_strerror(socket_errno()));
  633. FD_SET(sockfd[fdn].fd, &listen_fds);
  634. add_fd(&listen_fdlist, sockfd[fdn].fd);
  635. }
  636. fdn = -1;
  637. socket_n = -1;
  638. fd_set fds;
  639. FD_ZERO(&fds);
  640. while (1) {
  641. /*
  642. * We just select to get a list of sockets which we can talk to
  643. */
  644. if (o.debug > 1)
  645. logdebug("selecting, fdmax %d\n", listen_fdlist.fdmax);
  646. fds = listen_fds;
  647. if (o.idletimeout > 0)
  648. ms_to_timeval(tvp, o.idletimeout);
  649. fds_ready = fselect(listen_fdlist.fdmax + 1, &fds, NULL, NULL, tvp);
  650. if (o.debug > 1)
  651. logdebug("select returned %d fds ready\n", fds_ready);
  652. if (fds_ready == 0)
  653. bye("Idle timeout expired (%d ms).", o.idletimeout);
  654. /*
  655. * Figure out which listening socket got a connection. This loop should
  656. * really call a function for each ready socket instead of breaking on
  657. * the first one.
  658. */
  659. for (i = 0; i <= listen_fdlist.fdmax && fds_ready > 0; i++) {
  660. /* Loop through descriptors until there is something ready */
  661. if (!FD_ISSET(i, &fds))
  662. continue;
  663. /* Check each listening socket */
  664. for (j = 0; j < num_sockets; j++) {
  665. if (i == sockfd[j].fd) {
  666. if (o.debug > 1)
  667. logdebug("Valid descriptor %d \n", i);
  668. fdn = j;
  669. socket_n = i;
  670. break;
  671. }
  672. }
  673. /* if we found a valid socket break */
  674. if (fdn != -1) {
  675. fds_ready--;
  676. break;
  677. }
  678. }
  679. /* Make sure someone connected */
  680. if (fdn == -1)
  681. continue;
  682. /*
  683. * We just peek so we can get the client connection details without
  684. * removing anything from the queue. Sigh.
  685. */
  686. nbytes = recvfrom(socket_n, buf, sizeof(buf), MSG_PEEK,
  687. &remotess.sockaddr, &sslen);
  688. if (nbytes < 0) {
  689. loguser("%s.\n", socket_strerror(socket_errno()));
  690. close(socket_n);
  691. return 1;
  692. }
  693. /* Check conditions that might cause us to deny the connection. */
  694. conn_count = get_conn_count();
  695. if (conn_count >= o.conn_limit) {
  696. if (o.verbose)
  697. loguser("New connection denied: connection limit reached (%d)\n", conn_count);
  698. } else if (!allow_access(&remotess)) {
  699. if (o.verbose)
  700. loguser("New connection denied: not allowed\n");
  701. } else {
  702. /* Good to go. */
  703. break;
  704. }
  705. /* Dump the current datagram */
  706. nbytes = recv(socket_n, buf, sizeof(buf), 0);
  707. if (nbytes < 0) {
  708. loguser("%s.\n", socket_strerror(socket_errno()));
  709. close(socket_n);
  710. return 1;
  711. }
  712. ncat_log_recv(buf, nbytes);
  713. }
  714. if (o.debug > 1)
  715. logdebug("Valid Connection from %d\n", socket_n);
  716. conn_inc++;
  717. /*
  718. * We're using connected udp. This has the down side of only
  719. * being able to handle one udp client at a time
  720. */
  721. Connect(socket_n, &remotess.sockaddr, sslen);
  722. /* clean slate for buf */
  723. zmem(buf, sizeof(buf));
  724. /* are we executing a command? then do it */
  725. if (o.cmdexec) {
  726. struct fdinfo info = { 0 };
  727. info.fd = socket_n;
  728. if (o.keepopen)
  729. netrun(&info, o.cmdexec);
  730. else
  731. netexec(&info, o.cmdexec);
  732. continue;
  733. }
  734. FD_SET(socket_n, &read_fds);
  735. FD_SET(STDIN_FILENO, &read_fds);
  736. fdmax = socket_n;
  737. /* stdin -> socket and socket -> stdout */
  738. while (1) {
  739. fd_set fds;
  740. fds = read_fds;
  741. if (o.debug > 1)
  742. logdebug("udp select'ing\n");
  743. if (o.idletimeout > 0)
  744. ms_to_timeval(tvp, o.idletimeout);
  745. fds_ready = fselect(fdmax + 1, &fds, NULL, NULL, tvp);
  746. if (fds_ready == 0)
  747. bye("Idle timeout expired (%d ms).", o.idletimeout);
  748. if (FD_ISSET(STDIN_FILENO, &fds)) {
  749. nbytes = Read(STDIN_FILENO, buf, sizeof(buf));
  750. if (nbytes < 0) {
  751. loguser("%s.\n", strerror(errno));
  752. return 1;
  753. } else if (nbytes == 0) {
  754. return 0;
  755. }
  756. if (o.crlf)
  757. fix_line_endings((char *) buf, &nbytes, &tempbuf, &crlf_state);
  758. if (!o.recvonly) {
  759. if (tempbuf != NULL)
  760. n = send(socket_n, tempbuf, nbytes, 0);
  761. else
  762. n = send(socket_n, buf, nbytes, 0);
  763. if (n < nbytes) {
  764. loguser("%s.\n", socket_strerror(socket_errno()));
  765. close(socket_n);
  766. return 1;
  767. }
  768. ncat_log_send(buf, nbytes);
  769. }
  770. if (tempbuf != NULL) {
  771. free(tempbuf);
  772. tempbuf = NULL;
  773. }
  774. }
  775. if (FD_ISSET(socket_n, &fds)) {
  776. nbytes = recv(socket_n, buf, sizeof(buf), 0);
  777. if (nbytes < 0) {
  778. loguser("%s.\n", socket_strerror(socket_errno()));
  779. close(socket_n);
  780. return 1;
  781. }
  782. ncat_log_recv(buf, nbytes);
  783. if (!o.sendonly)
  784. Write(STDOUT_FILENO, buf, nbytes);
  785. }
  786. zmem(buf, sizeof(buf));
  787. }
  788. }
  789. return 0;
  790. }
  791. int ncat_listen()
  792. {
  793. #if HAVE_SYS_UN_H
  794. if (o.af == AF_UNIX)
  795. if (o.proto == IPPROTO_UDP)
  796. return ncat_listen_dgram(0);
  797. else
  798. return ncat_listen_stream(0);
  799. else
  800. #endif
  801. if (o.httpserver)
  802. return ncat_http_server();
  803. else if (o.proto == IPPROTO_UDP)
  804. return ncat_listen_dgram(o.proto);
  805. else if (o.proto == IPPROTO_SCTP)
  806. return ncat_listen_stream(o.proto);
  807. else if (o.proto == IPPROTO_TCP)
  808. return ncat_listen_stream(o.proto);
  809. else
  810. bye("Unknown o.proto %d\n", o.proto);
  811. /* unreached */
  812. return 1;
  813. }
  814. //---------------
  815. /* Read from recv_fd and broadcast whatever is read to all other descriptors in
  816. read_fds, with the exception of stdin, listen_socket, and recv_fd itself.
  817. Handles EOL translation and chat mode. On read error or end of stream,
  818. closes the socket and removes it from the read_fds list. */
  819. static void read_and_broadcast(int recv_fd)
  820. {
  821. struct fdinfo *fdn;
  822. int pending;
  823. fdn = get_fdinfo(&client_fdlist, recv_fd);
  824. ncat_assert(fdn != NULL);
  825. /* Loop while ncat_recv indicates data is pending. */
  826. do {
  827. char buf[DEFAULT_TCP_BUF_LEN];
  828. char *chatbuf, *outbuf;
  829. char *tempbuf = NULL;
  830. fd_set broadcastfds;
  831. int n;
  832. /* Behavior differs depending on whether this is stdin or a socket. */
  833. if (recv_fd == STDIN_FILENO) {
  834. n = read(recv_fd, buf, sizeof(buf));
  835. if (n <= 0) {
  836. if (n < 0 && o.verbose)
  837. logdebug("Error reading from stdin: %s\n", strerror(errno));
  838. if (n == 0 && o.debug)
  839. logdebug("EOF on stdin\n");
  840. /* Don't close the file because that allows a socket to be
  841. fd 0. */
  842. FD_CLR(recv_fd, &master_readfds);
  843. /* But mark that we've seen EOF so it doesn't get re-added to
  844. the select list. */
  845. stdin_eof = 1;
  846. return;
  847. }
  848. if (o.crlf)
  849. fix_line_endings((char *) buf, &n, &tempbuf, &crlf_state);
  850. pending = 0;
  851. } else {
  852. /* From a connected socket, not stdin. */
  853. n = ncat_recv(fdn, buf, sizeof(buf), &pending);
  854. if (n <= 0) {
  855. if (o.debug)
  856. logdebug("Closing connection.\n");
  857. #ifdef HAVE_OPENSSL
  858. if (o.ssl && fdn->ssl) {
  859. if (n == 0)
  860. SSL_shutdown(fdn->ssl);
  861. SSL_free(fdn->ssl);
  862. }
  863. #endif
  864. close(recv_fd);
  865. FD_CLR(recv_fd, &master_readfds);
  866. rm_fd(&client_fdlist, recv_fd);
  867. FD_CLR(recv_fd, &master_broadcastfds);
  868. rm_fd(&broadcast_fdlist, recv_fd);
  869. conn_inc--;
  870. if (conn_inc == 0)
  871. FD_CLR(STDIN_FILENO, &master_readfds);
  872. if (o.chat)
  873. chat_announce_disconnect(recv_fd);
  874. return;
  875. }
  876. }
  877. if (o.debug > 1)
  878. logdebug("Handling data from client %d.\n", recv_fd);
  879. chatbuf = NULL;
  880. /* tempbuf is in use if we read from STDIN and fixed EOL */
  881. if (tempbuf == NULL)
  882. outbuf = buf;
  883. else
  884. outbuf = tempbuf;
  885. if (o.chat) {
  886. chatbuf = chat_filter(outbuf, n, recv_fd, &n);
  887. if (chatbuf == NULL) {
  888. if (o.verbose)
  889. logdebug("Error formatting chat message from fd %d\n", recv_fd);
  890. } else {
  891. outbuf = chatbuf;
  892. }
  893. }
  894. /* Send to everyone except the one who sent this message. */
  895. broadcastfds = master_broadcastfds;
  896. FD_CLR(recv_fd, &broadcastfds);
  897. ncat_broadcast(&broadcastfds, &broadcast_fdlist, outbuf, n);
  898. free(chatbuf);
  899. free(tempbuf);
  900. tempbuf = NULL;
  901. } while (pending);
  902. }
  903. static void shutdown_sockets(int how)
  904. {
  905. struct fdinfo *fdn;
  906. int i;
  907. for (i = 0; i <= broadcast_fdlist.fdmax; i++) {
  908. if (!FD_ISSET(i, &master_broadcastfds))
  909. continue;
  910. fdn = get_fdinfo(&broadcast_fdlist, i);
  911. ncat_assert(fdn != NULL);
  912. shutdown(fdn->fd, how);
  913. }
  914. }
  915. /* Announce the new connection and who is already connected. */
  916. static int chat_announce_connect(int fd, const union sockaddr_u *su)
  917. {
  918. char *buf = NULL;
  919. size_t size = 0, offset = 0;
  920. int i, count, ret;
  921. strbuf_sprintf(&buf, &size, &offset,
  922. "<announce> %s is connected as <user%d>.\n", inet_socktop(su), fd);
  923. strbuf_sprintf(&buf, &size, &offset, "<announce> already connected: ");
  924. count = 0;
  925. for (i = 0; i < client_fdlist.fdmax; i++) {
  926. union sockaddr_u su;
  927. socklen_t len = sizeof(su.storage);
  928. if (i == fd || !FD_ISSET(i, &master_broadcastfds))
  929. continue;
  930. if (getpeername(i, &su.sockaddr, &len) == -1)
  931. bye("getpeername for sd %d failed: %s.", i, strerror(errno));
  932. if (count > 0)
  933. strbuf_sprintf(&buf, &size, &offset, ", ");
  934. strbuf_sprintf(&buf, &size, &offset, "%s as <user%d>", inet_socktop(&su), i);
  935. count++;
  936. }
  937. if (count == 0)
  938. strbuf_sprintf(&buf, &size, &offset, "nobody");
  939. strbuf_sprintf(&buf, &size, &offset, ".\n");
  940. ret = ncat_broadcast(&master_broadcastfds, &broadcast_fdlist, buf, offset);
  941. free(buf);
  942. return ret;
  943. }
  944. static int chat_announce_disconnect(int fd)
  945. {
  946. char buf[128];
  947. int n;
  948. n = Snprintf(buf, sizeof(buf),
  949. "<announce> <user%d> is disconnected.\n", fd);
  950. if (n >= sizeof(buf) || n < 0)
  951. return -1;
  952. return ncat_broadcast(&master_broadcastfds, &broadcast_fdlist, buf, n);
  953. }
  954. /*
  955. * This is stupid. But it's just a bit of fun.
  956. *
  957. * The file descriptor of the sender is prepended to the
  958. * message sent to clients, so you can distinguish
  959. * each other with a degree of sanity. This gives a
  960. * similar effect to an IRC session. But stupider.
  961. */
  962. static char *chat_filter(char *buf, size_t size, int fd, int *nwritten)
  963. {
  964. char *result = NULL;
  965. size_t n = 0;
  966. const char *p;
  967. int i;
  968. n = 32;
  969. result = (char *) safe_malloc(n);
  970. i = Snprintf(result, n, "<user%d> ", fd);
  971. /* Escape control characters. */
  972. for (p = buf; p - buf < size; p++) {
  973. char repl[32];
  974. int repl_len;
  975. if (isprint((int) (unsigned char) *p) || *p == '\r' || *p == '\n' || *p == '\t') {
  976. repl[0] = *p;
  977. repl_len = 1;
  978. } else {
  979. repl_len = Snprintf(repl, sizeof(repl), "\\%03o", (unsigned char) *p);
  980. }
  981. if (i + repl_len > n) {
  982. n = (i + repl_len) * 2;
  983. result = (char *) safe_realloc(result, n + 1);
  984. }
  985. memcpy(result + i, repl, repl_len);
  986. i += repl_len;
  987. }
  988. /* Trim to length. (Also does initial allocation when str is empty.) */
  989. result = (char *) safe_realloc(result, i + 1);
  990. result[i] = '\0';
  991. *nwritten = i;
  992. return result;
  993. }