svr-main.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. /*
  2. * Dropbear - a SSH2 server
  3. *
  4. * Copyright (c) 2002-2006 Matt Johnston
  5. * All rights reserved.
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in
  15. * all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. * SOFTWARE. */
  24. #include "includes.h"
  25. #include "dbutil.h"
  26. #include "session.h"
  27. #include "buffer.h"
  28. #include "signkey.h"
  29. #include "runopts.h"
  30. #include "dbrandom.h"
  31. #include "crypto_desc.h"
  32. static size_t listensockets(int *sock, size_t sockcount, int *maxfd);
  33. static void sigchld_handler(int dummy);
  34. static void sigsegv_handler(int);
  35. static void sigintterm_handler(int fish);
  36. #ifdef INETD_MODE
  37. static void main_inetd(void);
  38. #endif
  39. #ifdef NON_INETD_MODE
  40. static void main_noinetd(void);
  41. #endif
  42. static void commonsetup(void);
  43. #if defined(DBMULTI_dropbear) || !defined(DROPBEAR_MULTI)
  44. #if defined(DBMULTI_dropbear) && defined(DROPBEAR_MULTI)
  45. int dropbear_main(int argc, char ** argv)
  46. #else
  47. int main(int argc, char ** argv)
  48. #endif
  49. {
  50. _dropbear_exit = svr_dropbear_exit;
  51. _dropbear_log = svr_dropbear_log;
  52. disallow_core();
  53. /* get commandline options */
  54. svr_getopts(argc, argv);
  55. #ifdef INETD_MODE
  56. /* service program mode */
  57. if (svr_opts.inetdmode) {
  58. main_inetd();
  59. /* notreached */
  60. }
  61. #endif
  62. #ifdef NON_INETD_MODE
  63. main_noinetd();
  64. /* notreached */
  65. #endif
  66. dropbear_exit("Compiled without normal mode, can't run without -i\n");
  67. return -1;
  68. }
  69. #endif
  70. #ifdef INETD_MODE
  71. static void main_inetd() {
  72. char *host, *port = NULL;
  73. /* Set up handlers, syslog, seed random */
  74. commonsetup();
  75. /* In case our inetd was lax in logging source addresses */
  76. get_socket_address(0, NULL, NULL, &host, &port, 0);
  77. dropbear_log(LOG_INFO, "Child connection from %s:%s", host, port);
  78. m_free(host);
  79. m_free(port);
  80. /* Don't check the return value - it may just fail since inetd has
  81. * already done setsid() after forking (xinetd on Darwin appears to do
  82. * this */
  83. setsid();
  84. /* Start service program
  85. * -1 is a dummy childpipe, just something we can close() without
  86. * mattering. */
  87. svr_session(0, -1);
  88. /* notreached */
  89. }
  90. #endif /* INETD_MODE */
  91. #ifdef NON_INETD_MODE
  92. static void main_noinetd() {
  93. fd_set fds;
  94. unsigned int i, j;
  95. int val;
  96. int maxsock = -1;
  97. int listensocks[MAX_LISTEN_ADDR];
  98. size_t listensockcount = 0;
  99. FILE *pidfile = NULL;
  100. int childpipes[MAX_UNAUTH_CLIENTS];
  101. char * preauth_addrs[MAX_UNAUTH_CLIENTS];
  102. int childsock;
  103. int childpipe[2];
  104. /* Note: commonsetup() must happen before we daemon()ise. Otherwise
  105. daemon() will chdir("/"), and we won't be able to find local-dir
  106. hostkeys. */
  107. commonsetup();
  108. /* sockets to identify pre-authenticated clients */
  109. for (i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
  110. childpipes[i] = -1;
  111. }
  112. memset(preauth_addrs, 0x0, sizeof(preauth_addrs));
  113. /* Set up the listening sockets */
  114. listensockcount = listensockets(listensocks, MAX_LISTEN_ADDR, &maxsock);
  115. if (listensockcount == 0)
  116. {
  117. dropbear_exit("No listening ports available.");
  118. }
  119. for (i = 0; i < listensockcount; i++) {
  120. FD_SET(listensocks[i], &fds);
  121. }
  122. /* fork */
  123. if (svr_opts.forkbg) {
  124. int closefds = 0;
  125. #ifndef DEBUG_TRACE
  126. if (!opts.usingsyslog) {
  127. closefds = 1;
  128. }
  129. #endif
  130. if (daemon(0, closefds) < 0) {
  131. dropbear_exit("Failed to daemonize: %s", strerror(errno));
  132. }
  133. }
  134. /* should be done after syslog is working */
  135. if (svr_opts.forkbg) {
  136. dropbear_log(LOG_INFO, "Running in background");
  137. } else {
  138. dropbear_log(LOG_INFO, "Not backgrounding");
  139. }
  140. /* create a PID file so that we can be killed easily */
  141. pidfile = fopen(svr_opts.pidfile, "w");
  142. if (pidfile) {
  143. fprintf(pidfile, "%d\n", getpid());
  144. fclose(pidfile);
  145. }
  146. /* incoming connection select loop */
  147. for(;;) {
  148. FD_ZERO(&fds);
  149. /* listening sockets */
  150. for (i = 0; i < listensockcount; i++) {
  151. FD_SET(listensocks[i], &fds);
  152. }
  153. /* pre-authentication clients */
  154. for (i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
  155. if (childpipes[i] >= 0) {
  156. FD_SET(childpipes[i], &fds);
  157. maxsock = MAX(maxsock, childpipes[i]);
  158. }
  159. }
  160. val = select(maxsock+1, &fds, NULL, NULL, NULL);
  161. if (exitflag) {
  162. unlink(svr_opts.pidfile);
  163. dropbear_exit("Terminated by signal");
  164. }
  165. if (val == 0) {
  166. /* timeout reached - shouldn't happen. eh */
  167. continue;
  168. }
  169. if (val < 0) {
  170. if (errno == EINTR) {
  171. continue;
  172. }
  173. dropbear_exit("Listening socket error");
  174. }
  175. /* close fds which have been authed or closed - svr-auth.c handles
  176. * closing the auth sockets on success */
  177. for (i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
  178. if (childpipes[i] >= 0 && FD_ISSET(childpipes[i], &fds)) {
  179. m_close(childpipes[i]);
  180. childpipes[i] = -1;
  181. m_free(preauth_addrs[i]);
  182. }
  183. }
  184. /* handle each socket which has something to say */
  185. for (i = 0; i < listensockcount; i++) {
  186. size_t num_unauthed_for_addr = 0;
  187. size_t num_unauthed_total = 0;
  188. char *remote_host = NULL, *remote_port = NULL;
  189. pid_t fork_ret = 0;
  190. size_t conn_idx = 0;
  191. struct sockaddr_storage remoteaddr;
  192. socklen_t remoteaddrlen;
  193. if (!FD_ISSET(listensocks[i], &fds))
  194. continue;
  195. remoteaddrlen = sizeof(remoteaddr);
  196. childsock = accept(listensocks[i],
  197. (struct sockaddr*)&remoteaddr, &remoteaddrlen);
  198. if (childsock < 0) {
  199. /* accept failed */
  200. continue;
  201. }
  202. /* Limit the number of unauthenticated connections per IP */
  203. getaddrstring(&remoteaddr, &remote_host, NULL, 0);
  204. num_unauthed_for_addr = 0;
  205. num_unauthed_total = 0;
  206. for (j = 0; j < MAX_UNAUTH_CLIENTS; j++) {
  207. if (childpipes[j] >= 0) {
  208. num_unauthed_total++;
  209. if (strcmp(remote_host, preauth_addrs[j]) == 0) {
  210. num_unauthed_for_addr++;
  211. }
  212. } else {
  213. /* a free slot */
  214. conn_idx = j;
  215. }
  216. }
  217. if (num_unauthed_total >= MAX_UNAUTH_CLIENTS
  218. || num_unauthed_for_addr >= MAX_UNAUTH_PER_IP) {
  219. goto out;
  220. }
  221. seedrandom();
  222. if (pipe(childpipe) < 0) {
  223. TRACE(("error creating child pipe"))
  224. goto out;
  225. }
  226. #ifdef DEBUG_NOFORK
  227. fork_ret = 0;
  228. #else
  229. fork_ret = fork();
  230. #endif
  231. if (fork_ret < 0) {
  232. dropbear_log(LOG_WARNING, "Error forking: %s", strerror(errno));
  233. goto out;
  234. }
  235. addrandom((void*)&fork_ret, sizeof(fork_ret));
  236. if (fork_ret > 0) {
  237. /* parent */
  238. childpipes[conn_idx] = childpipe[0];
  239. m_close(childpipe[1]);
  240. preauth_addrs[conn_idx] = remote_host;
  241. remote_host = NULL;
  242. } else {
  243. /* child */
  244. #ifdef DEBUG_FORKGPROF
  245. extern void _start(void), etext(void);
  246. monstartup((u_long)&_start, (u_long)&etext);
  247. #endif /* DEBUG_FORKGPROF */
  248. getaddrstring(&remoteaddr, NULL, &remote_port, 0);
  249. dropbear_log(LOG_INFO, "Child connection from %s:%s", remote_host, remote_port);
  250. m_free(remote_host);
  251. m_free(remote_port);
  252. #ifndef DEBUG_NOFORK
  253. if (setsid() < 0) {
  254. dropbear_exit("setsid: %s", strerror(errno));
  255. }
  256. #endif
  257. /* make sure we close sockets */
  258. for (j = 0; j < listensockcount; j++) {
  259. m_close(listensocks[j]);
  260. }
  261. m_close(childpipe[0]);
  262. /* start the session */
  263. svr_session(childsock, childpipe[1]);
  264. /* don't return */
  265. dropbear_assert(0);
  266. }
  267. out:
  268. /* This section is important for the parent too */
  269. m_close(childsock);
  270. if (remote_host) {
  271. m_free(remote_host);
  272. }
  273. }
  274. } /* for(;;) loop */
  275. /* don't reach here */
  276. }
  277. #endif /* NON_INETD_MODE */
  278. /* catch + reap zombie children */
  279. static void sigchld_handler(int UNUSED(unused)) {
  280. struct sigaction sa_chld;
  281. const int saved_errno = errno;
  282. while(waitpid(-1, NULL, WNOHANG) > 0) {}
  283. sa_chld.sa_handler = sigchld_handler;
  284. sa_chld.sa_flags = SA_NOCLDSTOP;
  285. sigemptyset(&sa_chld.sa_mask);
  286. if (sigaction(SIGCHLD, &sa_chld, NULL) < 0) {
  287. dropbear_exit("signal() error");
  288. }
  289. errno = saved_errno;
  290. }
  291. /* catch any segvs */
  292. static void sigsegv_handler(int UNUSED(unused)) {
  293. fprintf(stderr, "Aiee, segfault! You should probably report "
  294. "this as a bug to the developer\n");
  295. _exit(EXIT_FAILURE);
  296. }
  297. /* catch ctrl-c or sigterm */
  298. static void sigintterm_handler(int UNUSED(unused)) {
  299. exitflag = 1;
  300. }
  301. /* Things used by inetd and non-inetd modes */
  302. static void commonsetup() {
  303. struct sigaction sa_chld;
  304. #ifndef DISABLE_SYSLOG
  305. if (opts.usingsyslog) {
  306. startsyslog(PROGNAME);
  307. }
  308. #endif
  309. /* set up cleanup handler */
  310. if (signal(SIGINT, sigintterm_handler) == SIG_ERR ||
  311. #ifndef DEBUG_VALGRIND
  312. signal(SIGTERM, sigintterm_handler) == SIG_ERR ||
  313. #endif
  314. signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
  315. dropbear_exit("signal() error");
  316. }
  317. /* catch and reap zombie children */
  318. sa_chld.sa_handler = sigchld_handler;
  319. sa_chld.sa_flags = SA_NOCLDSTOP;
  320. sigemptyset(&sa_chld.sa_mask);
  321. if (sigaction(SIGCHLD, &sa_chld, NULL) < 0) {
  322. dropbear_exit("signal() error");
  323. }
  324. if (signal(SIGSEGV, sigsegv_handler) == SIG_ERR) {
  325. dropbear_exit("signal() error");
  326. }
  327. crypto_init();
  328. /* Now we can setup the hostkeys - needs to be after logging is on,
  329. * otherwise we might end up blatting error messages to the socket */
  330. load_all_hostkeys();
  331. seedrandom();
  332. }
  333. /* Set up listening sockets for all the requested ports */
  334. static size_t listensockets(int *socks, size_t sockcount, int *maxfd) {
  335. unsigned int i, n;
  336. char* errstring = NULL;
  337. size_t sockpos = 0;
  338. int nsock;
  339. TRACE(("listensockets: %d to try", svr_opts.portcount))
  340. for (i = 0; i < svr_opts.portcount; i++) {
  341. TRACE(("listening on '%s:%s'", svr_opts.addresses[i], svr_opts.ports[i]))
  342. nsock = dropbear_listen(svr_opts.addresses[i], svr_opts.ports[i], &socks[sockpos],
  343. sockcount - sockpos,
  344. &errstring, maxfd);
  345. if (nsock < 0) {
  346. dropbear_log(LOG_WARNING, "Failed listening on '%s': %s",
  347. svr_opts.ports[i], errstring);
  348. m_free(errstring);
  349. continue;
  350. }
  351. for (n = 0; n < (unsigned int)nsock; n++) {
  352. int sock = socks[sockpos + n];
  353. set_sock_priority(sock, DROPBEAR_PRIO_LOWDELAY);
  354. #ifdef DROPBEAR_SERVER_TCP_FAST_OPEN
  355. set_listen_fast_open(sock);
  356. #endif
  357. }
  358. sockpos += nsock;
  359. }
  360. return sockpos;
  361. }