svr-main.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. static void main_inetd(void);
  37. static void main_noinetd(int argc, char ** argv, const char* multipath);
  38. static void commonsetup(void);
  39. #if defined(DBMULTI_dropbear) || !DROPBEAR_MULTI
  40. #if defined(DBMULTI_dropbear) && DROPBEAR_MULTI
  41. int dropbear_main(int argc, char ** argv, const char* multipath)
  42. #else
  43. int main(int argc, char ** argv)
  44. #endif
  45. {
  46. #if !DROPBEAR_MULTI
  47. const char* multipath = NULL;
  48. #endif
  49. _dropbear_exit = svr_dropbear_exit;
  50. _dropbear_log = svr_dropbear_log;
  51. disallow_core();
  52. if (argc < 1) {
  53. dropbear_exit("Bad argc");
  54. }
  55. /* get commandline options */
  56. svr_getopts(argc, argv);
  57. #if INETD_MODE
  58. /* service program mode */
  59. if (svr_opts.inetdmode) {
  60. main_inetd();
  61. /* notreached */
  62. }
  63. #endif
  64. #if DROPBEAR_DO_REEXEC
  65. if (svr_opts.reexec_child) {
  66. #ifdef PR_SET_NAME
  67. /* Fix the "Name:" in /proc/pid/status, otherwise it's
  68. a FD number from fexecve.
  69. Failure doesn't really matter, it's mostly aesthetic */
  70. prctl(PR_SET_NAME, basename(argv[0]), 0, 0);
  71. #endif
  72. main_inetd();
  73. /* notreached */
  74. }
  75. #endif
  76. #if NON_INETD_MODE
  77. main_noinetd(argc, argv, multipath);
  78. /* notreached */
  79. #endif
  80. dropbear_exit("Compiled without normal mode, can't run without -i\n");
  81. return -1;
  82. }
  83. #endif
  84. #if INETD_MODE || DROPBEAR_DO_REEXEC
  85. static void main_inetd() {
  86. char *host, *port = NULL;
  87. /* Set up handlers, syslog */
  88. commonsetup();
  89. seedrandom();
  90. if (!svr_opts.reexec_child) {
  91. /* In case our inetd was lax in logging source addresses */
  92. get_socket_address(0, NULL, NULL, &host, &port, 0);
  93. dropbear_log(LOG_INFO, "Child connection from %s:%s", host, port);
  94. m_free(host);
  95. m_free(port);
  96. /* Don't check the return value - it may just fail since inetd has
  97. * already done setsid() after forking (xinetd on Darwin appears to do
  98. * this */
  99. setsid();
  100. }
  101. /* Start service program
  102. * -1 is a dummy childpipe, just something we can close() without
  103. * mattering. */
  104. svr_session(0, -1);
  105. /* notreached */
  106. }
  107. #endif /* INETD_MODE */
  108. #if NON_INETD_MODE
  109. static void main_noinetd(int argc, char ** argv, const char* multipath) {
  110. fd_set fds;
  111. unsigned int i, j;
  112. int val;
  113. int maxsock = -1;
  114. int listensocks[MAX_LISTEN_ADDR];
  115. size_t listensockcount = 0;
  116. FILE *pidfile = NULL;
  117. int execfd = -1;
  118. int childpipes[MAX_UNAUTH_CLIENTS];
  119. char * preauth_addrs[MAX_UNAUTH_CLIENTS];
  120. int childsock;
  121. int childpipe[2];
  122. (void)argc;
  123. (void)argv;
  124. (void)multipath;
  125. /* Note: commonsetup() must happen before we daemon()ise. Otherwise
  126. daemon() will chdir("/"), and we won't be able to find local-dir
  127. hostkeys. */
  128. commonsetup();
  129. /* sockets to identify pre-authenticated clients */
  130. for (i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
  131. childpipes[i] = -1;
  132. }
  133. memset(preauth_addrs, 0x0, sizeof(preauth_addrs));
  134. /* Set up the listening sockets */
  135. listensockcount = listensockets(listensocks, MAX_LISTEN_ADDR, &maxsock);
  136. if (listensockcount == 0)
  137. {
  138. dropbear_exit("No listening ports available.");
  139. }
  140. for (i = 0; i < listensockcount; i++) {
  141. FD_SET(listensocks[i], &fds);
  142. }
  143. #if DROPBEAR_DO_REEXEC
  144. if (multipath) {
  145. execfd = open(multipath, O_CLOEXEC|O_RDONLY);
  146. } else {
  147. execfd = open(argv[0], O_CLOEXEC|O_RDONLY);
  148. }
  149. if (execfd < 0) {
  150. /* Just fallback to straight fork */
  151. TRACE(("Couldn't open own binary %s, disabling re-exec: %s", argv[0], strerror(errno)))
  152. }
  153. #endif
  154. /* fork */
  155. if (svr_opts.forkbg) {
  156. int closefds = 0;
  157. #if !DEBUG_TRACE
  158. if (!opts.usingsyslog) {
  159. closefds = 1;
  160. }
  161. #endif
  162. if (daemon(0, closefds) < 0) {
  163. dropbear_exit("Failed to daemonize: %s", strerror(errno));
  164. }
  165. }
  166. /* should be done after syslog is working */
  167. if (svr_opts.forkbg) {
  168. dropbear_log(LOG_INFO, "Running in background");
  169. } else {
  170. dropbear_log(LOG_INFO, "Not backgrounding");
  171. }
  172. /* create a PID file so that we can be killed easily */
  173. pidfile = fopen(svr_opts.pidfile, "w");
  174. if (pidfile) {
  175. fprintf(pidfile, "%d\n", getpid());
  176. fclose(pidfile);
  177. }
  178. /* incoming connection select loop */
  179. for(;;) {
  180. DROPBEAR_FD_ZERO(&fds);
  181. /* listening sockets */
  182. for (i = 0; i < listensockcount; i++) {
  183. FD_SET(listensocks[i], &fds);
  184. }
  185. /* pre-authentication clients */
  186. for (i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
  187. if (childpipes[i] >= 0) {
  188. FD_SET(childpipes[i], &fds);
  189. maxsock = MAX(maxsock, childpipes[i]);
  190. }
  191. }
  192. val = select(maxsock+1, &fds, NULL, NULL, NULL);
  193. if (ses.exitflag) {
  194. unlink(svr_opts.pidfile);
  195. dropbear_exit("Terminated by signal");
  196. }
  197. if (val == 0) {
  198. /* timeout reached - shouldn't happen. eh */
  199. continue;
  200. }
  201. if (val < 0) {
  202. if (errno == EINTR) {
  203. continue;
  204. }
  205. dropbear_exit("Listening socket error");
  206. }
  207. /* close fds which have been authed or closed - svr-auth.c handles
  208. * closing the auth sockets on success */
  209. for (i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
  210. if (childpipes[i] >= 0 && FD_ISSET(childpipes[i], &fds)) {
  211. m_close(childpipes[i]);
  212. childpipes[i] = -1;
  213. m_free(preauth_addrs[i]);
  214. }
  215. }
  216. /* handle each socket which has something to say */
  217. for (i = 0; i < listensockcount; i++) {
  218. size_t num_unauthed_for_addr = 0;
  219. size_t num_unauthed_total = 0;
  220. char *remote_host = NULL, *remote_port = NULL;
  221. pid_t fork_ret = 0;
  222. size_t conn_idx = 0;
  223. struct sockaddr_storage remoteaddr;
  224. socklen_t remoteaddrlen;
  225. if (!FD_ISSET(listensocks[i], &fds))
  226. continue;
  227. remoteaddrlen = sizeof(remoteaddr);
  228. childsock = accept(listensocks[i],
  229. (struct sockaddr*)&remoteaddr, &remoteaddrlen);
  230. if (childsock < 0) {
  231. /* accept failed */
  232. continue;
  233. }
  234. /* Limit the number of unauthenticated connections per IP */
  235. getaddrstring(&remoteaddr, &remote_host, NULL, 0);
  236. num_unauthed_for_addr = 0;
  237. num_unauthed_total = 0;
  238. for (j = 0; j < MAX_UNAUTH_CLIENTS; j++) {
  239. if (childpipes[j] >= 0) {
  240. num_unauthed_total++;
  241. if (strcmp(remote_host, preauth_addrs[j]) == 0) {
  242. num_unauthed_for_addr++;
  243. }
  244. } else {
  245. /* a free slot */
  246. conn_idx = j;
  247. }
  248. }
  249. if (num_unauthed_total >= MAX_UNAUTH_CLIENTS
  250. || num_unauthed_for_addr >= MAX_UNAUTH_PER_IP) {
  251. goto out;
  252. }
  253. seedrandom();
  254. if (pipe(childpipe) < 0) {
  255. TRACE(("error creating child pipe"))
  256. goto out;
  257. }
  258. #if DEBUG_NOFORK
  259. fork_ret = 0;
  260. #else
  261. fork_ret = fork();
  262. #endif
  263. if (fork_ret < 0) {
  264. dropbear_log(LOG_WARNING, "Error forking: %s", strerror(errno));
  265. goto out;
  266. }
  267. addrandom((void*)&fork_ret, sizeof(fork_ret));
  268. if (fork_ret > 0) {
  269. /* parent */
  270. childpipes[conn_idx] = childpipe[0];
  271. m_close(childpipe[1]);
  272. preauth_addrs[conn_idx] = remote_host;
  273. remote_host = NULL;
  274. } else {
  275. /* child */
  276. getaddrstring(&remoteaddr, NULL, &remote_port, 0);
  277. dropbear_log(LOG_INFO, "Child connection from %s:%s", remote_host, remote_port);
  278. m_free(remote_host);
  279. m_free(remote_port);
  280. #ifndef DEBUG_NOFORK
  281. if (setsid() < 0) {
  282. dropbear_exit("setsid: %s", strerror(errno));
  283. }
  284. #endif
  285. /* make sure we close sockets */
  286. for (j = 0; j < listensockcount; j++) {
  287. m_close(listensocks[j]);
  288. }
  289. m_close(childpipe[0]);
  290. if (execfd >= 0) {
  291. #if DROPBEAR_DO_REEXEC
  292. /* Add "-2" to the args and re-execute ourself. */
  293. char **new_argv = m_malloc(sizeof(char*) * (argc+3));
  294. int pos0 = 0, new_argc = argc+1;
  295. /* We need to specially handle "dropbearmulti dropbear". */
  296. if (multipath) {
  297. new_argv[0] = (char*)multipath;
  298. pos0 = 1;
  299. new_argc++;
  300. }
  301. memcpy(&new_argv[pos0], argv, sizeof(char*) * argc);
  302. new_argv[new_argc-1] = "-2";
  303. new_argv[new_argc] = NULL;
  304. if ((dup2(childsock, STDIN_FILENO) < 0)) {
  305. dropbear_exit("dup2 failed: %s", strerror(errno));
  306. }
  307. if (fcntl(childsock, F_SETFD, FD_CLOEXEC) < 0) {
  308. TRACE(("cloexec for childsock %d failed: %s", childsock, strerror(errno)))
  309. }
  310. /* Re-execute ourself */
  311. fexecve(execfd, new_argv, environ);
  312. /* Not reached on success */
  313. /* Fall back on plain fork otherwise.
  314. * To be removed in future once re-exec has been well tested */
  315. dropbear_log(LOG_WARNING, "fexecve failed, disabling re-exec: %s", strerror(errno));
  316. m_close(STDIN_FILENO);
  317. m_free(new_argv);
  318. #endif /* DROPBEAR_DO_REEXEC */
  319. }
  320. /* start the session */
  321. svr_session(childsock, childpipe[1]);
  322. /* don't return */
  323. dropbear_assert(0);
  324. }
  325. out:
  326. /* This section is important for the parent too */
  327. m_close(childsock);
  328. if (remote_host) {
  329. m_free(remote_host);
  330. }
  331. }
  332. } /* for(;;) loop */
  333. /* don't reach here */
  334. }
  335. #endif /* NON_INETD_MODE */
  336. /* catch + reap zombie children */
  337. static void sigchld_handler(int UNUSED(unused)) {
  338. struct sigaction sa_chld;
  339. const int saved_errno = errno;
  340. while(waitpid(-1, NULL, WNOHANG) > 0) {}
  341. sa_chld.sa_handler = sigchld_handler;
  342. sa_chld.sa_flags = SA_NOCLDSTOP;
  343. sigemptyset(&sa_chld.sa_mask);
  344. if (sigaction(SIGCHLD, &sa_chld, NULL) < 0) {
  345. dropbear_exit("signal() error");
  346. }
  347. errno = saved_errno;
  348. }
  349. /* catch any segvs */
  350. static void sigsegv_handler(int UNUSED(unused)) {
  351. fprintf(stderr, "Aiee, segfault! You should probably report "
  352. "this as a bug to the developer\n");
  353. _exit(EXIT_FAILURE);
  354. }
  355. /* catch ctrl-c or sigterm */
  356. static void sigintterm_handler(int UNUSED(unused)) {
  357. ses.exitflag = 1;
  358. }
  359. /* Things used by inetd and non-inetd modes */
  360. static void commonsetup() {
  361. struct sigaction sa_chld;
  362. #ifndef DISABLE_SYSLOG
  363. if (opts.usingsyslog) {
  364. startsyslog(PROGNAME);
  365. }
  366. #endif
  367. /* set up cleanup handler */
  368. if (signal(SIGINT, sigintterm_handler) == SIG_ERR ||
  369. #ifndef DEBUG_VALGRIND
  370. signal(SIGTERM, sigintterm_handler) == SIG_ERR ||
  371. #endif
  372. signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
  373. dropbear_exit("signal() error");
  374. }
  375. /* catch and reap zombie children */
  376. sa_chld.sa_handler = sigchld_handler;
  377. sa_chld.sa_flags = SA_NOCLDSTOP;
  378. sigemptyset(&sa_chld.sa_mask);
  379. if (sigaction(SIGCHLD, &sa_chld, NULL) < 0) {
  380. dropbear_exit("signal() error");
  381. }
  382. if (signal(SIGSEGV, sigsegv_handler) == SIG_ERR) {
  383. dropbear_exit("signal() error");
  384. }
  385. crypto_init();
  386. /* Now we can setup the hostkeys - needs to be after logging is on,
  387. * otherwise we might end up blatting error messages to the socket */
  388. load_all_hostkeys();
  389. }
  390. /* Set up listening sockets for all the requested ports */
  391. static size_t listensockets(int *socks, size_t sockcount, int *maxfd) {
  392. unsigned int i, n;
  393. char* errstring = NULL;
  394. size_t sockpos = 0;
  395. int nsock;
  396. TRACE(("listensockets: %d to try", svr_opts.portcount))
  397. for (i = 0; i < svr_opts.portcount; i++) {
  398. TRACE(("listening on '%s:%s'", svr_opts.addresses[i], svr_opts.ports[i]))
  399. nsock = dropbear_listen(svr_opts.addresses[i], svr_opts.ports[i], &socks[sockpos],
  400. sockcount - sockpos,
  401. &errstring, maxfd);
  402. if (nsock < 0) {
  403. dropbear_log(LOG_WARNING, "Failed listening on '%s': %s",
  404. svr_opts.ports[i], errstring);
  405. m_free(errstring);
  406. continue;
  407. }
  408. for (n = 0; n < (unsigned int)nsock; n++) {
  409. int sock = socks[sockpos + n];
  410. set_sock_priority(sock, DROPBEAR_PRIO_LOWDELAY);
  411. #if DROPBEAR_SERVER_TCP_FAST_OPEN
  412. set_listen_fast_open(sock);
  413. #endif
  414. }
  415. sockpos += nsock;
  416. }
  417. return sockpos;
  418. }