dropbear 2016.73
[tomato.git] / release / src / router / dropbear / svr-main.c
blobb27455120141824d39d678610ea96477de54bc24
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:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
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. */
25 #include "includes.h"
26 #include "dbutil.h"
27 #include "session.h"
28 #include "buffer.h"
29 #include "signkey.h"
30 #include "runopts.h"
31 #include "dbrandom.h"
32 #include "crypto_desc.h"
34 static size_t listensockets(int *sock, size_t sockcount, int *maxfd);
35 static void sigchld_handler(int dummy);
36 static void sigsegv_handler(int);
37 static void sigintterm_handler(int fish);
38 #ifdef INETD_MODE
39 static void main_inetd(void);
40 #endif
41 #ifdef NON_INETD_MODE
42 static void main_noinetd(void);
43 #endif
44 static void commonsetup(void);
46 #if defined(DBMULTI_dropbear) || !defined(DROPBEAR_MULTI)
47 #if defined(DBMULTI_dropbear) && defined(DROPBEAR_MULTI)
48 int dropbear_main(int argc, char ** argv)
49 #else
50 int main(int argc, char ** argv)
51 #endif
53 _dropbear_exit = svr_dropbear_exit;
54 _dropbear_log = svr_dropbear_log;
56 disallow_core();
58 /* get commandline options */
59 svr_getopts(argc, argv);
61 #ifdef INETD_MODE
62 /* service program mode */
63 if (svr_opts.inetdmode) {
64 main_inetd();
65 /* notreached */
67 #endif
69 #ifdef NON_INETD_MODE
70 main_noinetd();
71 /* notreached */
72 #endif
74 dropbear_exit("Compiled without normal mode, can't run without -i\n");
75 return -1;
77 #endif
79 #ifdef INETD_MODE
80 static void main_inetd() {
81 char *host, *port = NULL;
83 /* Set up handlers, syslog, seed random */
84 commonsetup();
86 /* In case our inetd was lax in logging source addresses */
87 get_socket_address(0, NULL, NULL, &host, &port, 0);
88 dropbear_log(LOG_INFO, "Child connection from %s:%s", host, port);
89 m_free(host);
90 m_free(port);
92 /* Don't check the return value - it may just fail since inetd has
93 * already done setsid() after forking (xinetd on Darwin appears to do
94 * this */
95 setsid();
97 /* Start service program
98 * -1 is a dummy childpipe, just something we can close() without
99 * mattering. */
100 svr_session(0, -1);
102 /* notreached */
104 #endif /* INETD_MODE */
106 #ifdef NON_INETD_MODE
107 static void main_noinetd() {
108 fd_set fds;
109 unsigned int i, j;
110 int val;
111 int maxsock = -1;
112 int listensocks[MAX_LISTEN_ADDR];
113 size_t listensockcount = 0;
114 FILE *pidfile = NULL;
116 int childpipes[MAX_UNAUTH_CLIENTS];
117 char * preauth_addrs[MAX_UNAUTH_CLIENTS];
119 int childsock;
120 int childpipe[2];
122 /* Note: commonsetup() must happen before we daemon()ise. Otherwise
123 daemon() will chdir("/"), and we won't be able to find local-dir
124 hostkeys. */
125 commonsetup();
127 /* sockets to identify pre-authenticated clients */
128 for (i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
129 childpipes[i] = -1;
131 memset(preauth_addrs, 0x0, sizeof(preauth_addrs));
133 /* Set up the listening sockets */
134 listensockcount = listensockets(listensocks, MAX_LISTEN_ADDR, &maxsock);
135 if (listensockcount == 0)
137 dropbear_exit("No listening ports available.");
140 for (i = 0; i < listensockcount; i++) {
141 FD_SET(listensocks[i], &fds);
144 /* fork */
145 if (svr_opts.forkbg) {
146 int closefds = 0;
147 #ifndef DEBUG_TRACE
148 if (!opts.usingsyslog) {
149 closefds = 1;
151 #endif
152 if (daemon(0, closefds) < 0) {
153 dropbear_exit("Failed to daemonize: %s", strerror(errno));
157 /* should be done after syslog is working */
158 if (svr_opts.forkbg) {
159 dropbear_log(LOG_INFO, "Running in background");
160 } else {
161 dropbear_log(LOG_INFO, "Not backgrounding");
164 /* create a PID file so that we can be killed easily */
165 pidfile = fopen(svr_opts.pidfile, "w");
166 if (pidfile) {
167 fprintf(pidfile, "%d\n", getpid());
168 fclose(pidfile);
171 /* incoming connection select loop */
172 for(;;) {
174 FD_ZERO(&fds);
176 /* listening sockets */
177 for (i = 0; i < listensockcount; i++) {
178 FD_SET(listensocks[i], &fds);
181 /* pre-authentication clients */
182 for (i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
183 if (childpipes[i] >= 0) {
184 FD_SET(childpipes[i], &fds);
185 maxsock = MAX(maxsock, childpipes[i]);
189 val = select(maxsock+1, &fds, NULL, NULL, NULL);
191 if (exitflag) {
192 unlink(svr_opts.pidfile);
193 dropbear_exit("Terminated by signal");
196 if (val == 0) {
197 /* timeout reached - shouldn't happen. eh */
198 continue;
201 if (val < 0) {
202 if (errno == EINTR) {
203 continue;
205 dropbear_exit("Listening socket error");
208 /* close fds which have been authed or closed - svr-auth.c handles
209 * closing the auth sockets on success */
210 for (i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
211 if (childpipes[i] >= 0 && FD_ISSET(childpipes[i], &fds)) {
212 m_close(childpipes[i]);
213 childpipes[i] = -1;
214 m_free(preauth_addrs[i]);
218 /* handle each socket which has something to say */
219 for (i = 0; i < listensockcount; i++) {
220 size_t num_unauthed_for_addr = 0;
221 size_t num_unauthed_total = 0;
222 char *remote_host = NULL, *remote_port = NULL;
223 pid_t fork_ret = 0;
224 size_t conn_idx = 0;
225 struct sockaddr_storage remoteaddr;
226 socklen_t remoteaddrlen;
228 if (!FD_ISSET(listensocks[i], &fds))
229 continue;
231 remoteaddrlen = sizeof(remoteaddr);
232 childsock = accept(listensocks[i],
233 (struct sockaddr*)&remoteaddr, &remoteaddrlen);
235 if (childsock < 0) {
236 /* accept failed */
237 continue;
240 /* Limit the number of unauthenticated connections per IP */
241 getaddrstring(&remoteaddr, &remote_host, NULL, 0);
243 num_unauthed_for_addr = 0;
244 num_unauthed_total = 0;
245 for (j = 0; j < MAX_UNAUTH_CLIENTS; j++) {
246 if (childpipes[j] >= 0) {
247 num_unauthed_total++;
248 if (strcmp(remote_host, preauth_addrs[j]) == 0) {
249 num_unauthed_for_addr++;
251 } else {
252 /* a free slot */
253 conn_idx = j;
257 if (num_unauthed_total >= MAX_UNAUTH_CLIENTS
258 || num_unauthed_for_addr >= MAX_UNAUTH_PER_IP) {
259 goto out;
262 seedrandom();
264 if (pipe(childpipe) < 0) {
265 TRACE(("error creating child pipe"))
266 goto out;
269 #ifdef DEBUG_NOFORK
270 fork_ret = 0;
271 #else
272 fork_ret = fork();
273 #endif
274 if (fork_ret < 0) {
275 dropbear_log(LOG_WARNING, "Error forking: %s", strerror(errno));
276 goto out;
279 addrandom((void*)&fork_ret, sizeof(fork_ret));
281 if (fork_ret > 0) {
283 /* parent */
284 childpipes[conn_idx] = childpipe[0];
285 m_close(childpipe[1]);
286 preauth_addrs[conn_idx] = remote_host;
287 remote_host = NULL;
289 } else {
291 /* child */
292 #ifdef DEBUG_FORKGPROF
293 extern void _start(void), etext(void);
294 monstartup((u_long)&_start, (u_long)&etext);
295 #endif /* DEBUG_FORKGPROF */
297 getaddrstring(&remoteaddr, NULL, &remote_port, 0);
298 dropbear_log(LOG_INFO, "Child connection from %s:%s", remote_host, remote_port);
299 m_free(remote_host);
300 m_free(remote_port);
302 #ifndef DEBUG_NOFORK
303 if (setsid() < 0) {
304 dropbear_exit("setsid: %s", strerror(errno));
306 #endif
308 /* make sure we close sockets */
309 for (j = 0; j < listensockcount; j++) {
310 m_close(listensocks[j]);
313 m_close(childpipe[0]);
315 /* start the session */
316 svr_session(childsock, childpipe[1]);
317 /* don't return */
318 dropbear_assert(0);
321 out:
322 /* This section is important for the parent too */
323 m_close(childsock);
324 if (remote_host) {
325 m_free(remote_host);
328 } /* for(;;) loop */
330 /* don't reach here */
332 #endif /* NON_INETD_MODE */
335 /* catch + reap zombie children */
336 static void sigchld_handler(int UNUSED(unused)) {
337 struct sigaction sa_chld;
339 const int saved_errno = errno;
341 while(waitpid(-1, NULL, WNOHANG) > 0) {}
343 sa_chld.sa_handler = sigchld_handler;
344 sa_chld.sa_flags = SA_NOCLDSTOP;
345 sigemptyset(&sa_chld.sa_mask);
346 if (sigaction(SIGCHLD, &sa_chld, NULL) < 0) {
347 dropbear_exit("signal() error");
349 errno = saved_errno;
352 /* catch any segvs */
353 static void sigsegv_handler(int UNUSED(unused)) {
354 fprintf(stderr, "Aiee, segfault! You should probably report "
355 "this as a bug to the developer\n");
356 _exit(EXIT_FAILURE);
359 /* catch ctrl-c or sigterm */
360 static void sigintterm_handler(int UNUSED(unused)) {
362 exitflag = 1;
365 /* Things used by inetd and non-inetd modes */
366 static void commonsetup() {
368 struct sigaction sa_chld;
369 #ifndef DISABLE_SYSLOG
370 if (opts.usingsyslog) {
371 startsyslog(PROGNAME);
373 #endif
375 /* set up cleanup handler */
376 if (signal(SIGINT, sigintterm_handler) == SIG_ERR ||
377 #ifndef DEBUG_VALGRIND
378 signal(SIGTERM, sigintterm_handler) == SIG_ERR ||
379 #endif
380 signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
381 dropbear_exit("signal() error");
384 /* catch and reap zombie children */
385 sa_chld.sa_handler = sigchld_handler;
386 sa_chld.sa_flags = SA_NOCLDSTOP;
387 sigemptyset(&sa_chld.sa_mask);
388 if (sigaction(SIGCHLD, &sa_chld, NULL) < 0) {
389 dropbear_exit("signal() error");
391 if (signal(SIGSEGV, sigsegv_handler) == SIG_ERR) {
392 dropbear_exit("signal() error");
395 crypto_init();
397 /* Now we can setup the hostkeys - needs to be after logging is on,
398 * otherwise we might end up blatting error messages to the socket */
399 load_all_hostkeys();
401 seedrandom();
404 /* Set up listening sockets for all the requested ports */
405 static size_t listensockets(int *socks, size_t sockcount, int *maxfd) {
407 unsigned int i, n;
408 char* errstring = NULL;
409 size_t sockpos = 0;
410 int nsock;
412 TRACE(("listensockets: %d to try", svr_opts.portcount))
414 for (i = 0; i < svr_opts.portcount; i++) {
416 TRACE(("listening on '%s:%s'", svr_opts.addresses[i], svr_opts.ports[i]))
418 nsock = dropbear_listen(svr_opts.addresses[i], svr_opts.ports[i], &socks[sockpos],
419 sockcount - sockpos,
420 &errstring, maxfd);
422 if (nsock < 0) {
423 dropbear_log(LOG_WARNING, "Failed listening on '%s': %s",
424 svr_opts.ports[i], errstring);
425 m_free(errstring);
426 continue;
429 for (n = 0; n < (unsigned int)nsock; n++) {
430 int sock = socks[sockpos + n];
431 set_sock_priority(sock, DROPBEAR_PRIO_LOWDELAY);
432 #ifdef DROPBEAR_SERVER_TCP_FAST_OPEN
433 set_listen_fast_open(sock);
434 #endif
437 sockpos += nsock;
440 return sockpos;