]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - crypto/openssh/sshd.c
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / crypto / openssh / sshd.c
1 /* $OpenBSD: sshd.c,v 1.404 2013/07/19 07:37:48 markus Exp $ */
2 /* $FreeBSD$ */
3 /*
4  * Author: Tatu Ylonen <ylo@cs.hut.fi>
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  * This program is the ssh daemon.  It listens for connections from clients,
8  * and performs authentication, executes use commands or shell, and forwards
9  * information to/from the application to the user client over an encrypted
10  * connection.  This can also handle forwarding of X11, TCP/IP, and
11  * authentication agent connections.
12  *
13  * As far as I am concerned, the code I have written for this software
14  * can be used freely for any purpose.  Any derived versions of this
15  * software must be clearly marked as such, and if the derived work is
16  * incompatible with the protocol description in the RFC file, it must be
17  * called by a name other than "ssh" or "Secure Shell".
18  *
19  * SSH2 implementation:
20  * Privilege Separation:
21  *
22  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
23  * Copyright (c) 2002 Niels Provos.  All rights reserved.
24  *
25  * Redistribution and use in source and binary forms, with or without
26  * modification, are permitted provided that the following conditions
27  * are met:
28  * 1. Redistributions of source code must retain the above copyright
29  *    notice, this list of conditions and the following disclaimer.
30  * 2. Redistributions in binary form must reproduce the above copyright
31  *    notice, this list of conditions and the following disclaimer in the
32  *    documentation and/or other materials provided with the distribution.
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
35  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
36  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
37  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
38  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
39  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
40  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
41  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
42  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
43  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44  */
45
46 #include "includes.h"
47 __RCSID("$FreeBSD$");
48
49 #include <sys/types.h>
50 #include <sys/ioctl.h>
51 #include <sys/mman.h>
52 #include <sys/socket.h>
53 #ifdef HAVE_SYS_STAT_H
54 # include <sys/stat.h>
55 #endif
56 #ifdef HAVE_SYS_TIME_H
57 # include <sys/time.h>
58 #endif
59 #include "openbsd-compat/sys-tree.h"
60 #include "openbsd-compat/sys-queue.h"
61 #include <sys/wait.h>
62
63 #include <errno.h>
64 #include <fcntl.h>
65 #include <netdb.h>
66 #ifdef HAVE_PATHS_H
67 #include <paths.h>
68 #endif
69 #include <grp.h>
70 #include <pwd.h>
71 #include <signal.h>
72 #include <stdarg.h>
73 #include <stdio.h>
74 #include <stdlib.h>
75 #include <string.h>
76 #include <unistd.h>
77
78 #include <openssl/dh.h>
79 #include <openssl/bn.h>
80 #include <openssl/md5.h>
81 #include <openssl/rand.h>
82 #include "openbsd-compat/openssl-compat.h"
83
84 #ifdef HAVE_SECUREWARE
85 #include <sys/security.h>
86 #include <prot.h>
87 #endif
88
89 #ifdef __FreeBSD__
90 #include <resolv.h>
91 #if defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H)
92 #include <gssapi/gssapi.h>
93 #elif defined(GSSAPI) && defined(HAVE_GSSAPI_H)
94 #include <gssapi.h>
95 #endif
96 #endif
97
98 #include "xmalloc.h"
99 #include "ssh.h"
100 #include "ssh1.h"
101 #include "ssh2.h"
102 #include "rsa.h"
103 #include "sshpty.h"
104 #include "packet.h"
105 #include "log.h"
106 #include "buffer.h"
107 #include "servconf.h"
108 #include "uidswap.h"
109 #include "compat.h"
110 #include "cipher.h"
111 #include "key.h"
112 #include "kex.h"
113 #include "dh.h"
114 #include "myproposal.h"
115 #include "authfile.h"
116 #include "pathnames.h"
117 #include "atomicio.h"
118 #include "canohost.h"
119 #include "hostfile.h"
120 #include "auth.h"
121 #include "authfd.h"
122 #include "misc.h"
123 #include "msg.h"
124 #include "dispatch.h"
125 #include "channels.h"
126 #include "session.h"
127 #include "monitor_mm.h"
128 #include "monitor.h"
129 #ifdef GSSAPI
130 #include "ssh-gss.h"
131 #endif
132 #include "monitor_wrap.h"
133 #include "roaming.h"
134 #include "ssh-sandbox.h"
135 #include "version.h"
136
137 #ifdef LIBWRAP
138 #include <tcpd.h>
139 #include <syslog.h>
140 int allow_severity;
141 int deny_severity;
142 #endif /* LIBWRAP */
143
144 #ifndef O_NOCTTY
145 #define O_NOCTTY        0
146 #endif
147
148 /* Re-exec fds */
149 #define REEXEC_DEVCRYPTO_RESERVED_FD    (STDERR_FILENO + 1)
150 #define REEXEC_STARTUP_PIPE_FD          (STDERR_FILENO + 2)
151 #define REEXEC_CONFIG_PASS_FD           (STDERR_FILENO + 3)
152 #define REEXEC_MIN_FREE_FD              (STDERR_FILENO + 4)
153
154 extern char *__progname;
155
156 /* Server configuration options. */
157 ServerOptions options;
158
159 /* Name of the server configuration file. */
160 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
161
162 /*
163  * Debug mode flag.  This can be set on the command line.  If debug
164  * mode is enabled, extra debugging output will be sent to the system
165  * log, the daemon will not go to background, and will exit after processing
166  * the first connection.
167  */
168 int debug_flag = 0;
169
170 /* Flag indicating that the daemon should only test the configuration and keys. */
171 int test_flag = 0;
172
173 /* Flag indicating that the daemon is being started from inetd. */
174 int inetd_flag = 0;
175
176 /* Flag indicating that sshd should not detach and become a daemon. */
177 int no_daemon_flag = 0;
178
179 /* debug goes to stderr unless inetd_flag is set */
180 int log_stderr = 0;
181
182 /* Saved arguments to main(). */
183 char **saved_argv;
184 int saved_argc;
185
186 /* re-exec */
187 int rexeced_flag = 0;
188 int rexec_flag = 1;
189 int rexec_argc = 0;
190 char **rexec_argv;
191
192 /*
193  * The sockets that the server is listening; this is used in the SIGHUP
194  * signal handler.
195  */
196 #define MAX_LISTEN_SOCKS        16
197 int listen_socks[MAX_LISTEN_SOCKS];
198 int num_listen_socks = 0;
199
200 /*
201  * the client's version string, passed by sshd2 in compat mode. if != NULL,
202  * sshd will skip the version-number exchange
203  */
204 char *client_version_string = NULL;
205 char *server_version_string = NULL;
206
207 /* for rekeying XXX fixme */
208 Kex *xxx_kex;
209
210 /* Daemon's agent connection */
211 AuthenticationConnection *auth_conn = NULL;
212 int have_agent = 0;
213
214 /*
215  * Any really sensitive data in the application is contained in this
216  * structure. The idea is that this structure could be locked into memory so
217  * that the pages do not get written into swap.  However, there are some
218  * problems. The private key contains BIGNUMs, and we do not (in principle)
219  * have access to the internals of them, and locking just the structure is
220  * not very useful.  Currently, memory locking is not implemented.
221  */
222 struct {
223         Key     *server_key;            /* ephemeral server key */
224         Key     *ssh1_host_key;         /* ssh1 host key */
225         Key     **host_keys;            /* all private host keys */
226         Key     **host_pubkeys;         /* all public host keys */
227         Key     **host_certificates;    /* all public host certificates */
228         int     have_ssh1_key;
229         int     have_ssh2_key;
230         u_char  ssh1_cookie[SSH_SESSION_KEY_LENGTH];
231 } sensitive_data;
232
233 /*
234  * Flag indicating whether the RSA server key needs to be regenerated.
235  * Is set in the SIGALRM handler and cleared when the key is regenerated.
236  */
237 static volatile sig_atomic_t key_do_regen = 0;
238
239 /* This is set to true when a signal is received. */
240 static volatile sig_atomic_t received_sighup = 0;
241 static volatile sig_atomic_t received_sigterm = 0;
242
243 /* session identifier, used by RSA-auth */
244 u_char session_id[16];
245
246 /* same for ssh2 */
247 u_char *session_id2 = NULL;
248 u_int session_id2_len = 0;
249
250 /* record remote hostname or ip */
251 u_int utmp_len = MAXHOSTNAMELEN;
252
253 /* options.max_startup sized array of fd ints */
254 int *startup_pipes = NULL;
255 int startup_pipe;               /* in child */
256
257 /* variables used for privilege separation */
258 int use_privsep = -1;
259 struct monitor *pmonitor = NULL;
260 int privsep_is_preauth = 1;
261
262 /* global authentication context */
263 Authctxt *the_authctxt = NULL;
264
265 /* sshd_config buffer */
266 Buffer cfg;
267
268 /* message to be displayed after login */
269 Buffer loginmsg;
270
271 /* Unprivileged user */
272 struct passwd *privsep_pw = NULL;
273
274 /* Prototypes for various functions defined later in this file. */
275 void destroy_sensitive_data(void);
276 void demote_sensitive_data(void);
277
278 static void do_ssh1_kex(void);
279 static void do_ssh2_kex(void);
280
281 /*
282  * Close all listening sockets
283  */
284 static void
285 close_listen_socks(void)
286 {
287         int i;
288
289         for (i = 0; i < num_listen_socks; i++)
290                 close(listen_socks[i]);
291         num_listen_socks = -1;
292 }
293
294 static void
295 close_startup_pipes(void)
296 {
297         int i;
298
299         if (startup_pipes)
300                 for (i = 0; i < options.max_startups; i++)
301                         if (startup_pipes[i] != -1)
302                                 close(startup_pipes[i]);
303 }
304
305 /*
306  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
307  * the effect is to reread the configuration file (and to regenerate
308  * the server key).
309  */
310
311 /*ARGSUSED*/
312 static void
313 sighup_handler(int sig)
314 {
315         int save_errno = errno;
316
317         received_sighup = 1;
318         signal(SIGHUP, sighup_handler);
319         errno = save_errno;
320 }
321
322 /*
323  * Called from the main program after receiving SIGHUP.
324  * Restarts the server.
325  */
326 static void
327 sighup_restart(void)
328 {
329         logit("Received SIGHUP; restarting.");
330         close_listen_socks();
331         close_startup_pipes();
332         alarm(0);  /* alarm timer persists across exec */
333         signal(SIGHUP, SIG_IGN); /* will be restored after exec */
334         execv(saved_argv[0], saved_argv);
335         logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
336             strerror(errno));
337         exit(1);
338 }
339
340 /*
341  * Generic signal handler for terminating signals in the master daemon.
342  */
343 /*ARGSUSED*/
344 static void
345 sigterm_handler(int sig)
346 {
347         received_sigterm = sig;
348 }
349
350 /*
351  * SIGCHLD handler.  This is called whenever a child dies.  This will then
352  * reap any zombies left by exited children.
353  */
354 /*ARGSUSED*/
355 static void
356 main_sigchld_handler(int sig)
357 {
358         int save_errno = errno;
359         pid_t pid;
360         int status;
361
362         while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
363             (pid < 0 && errno == EINTR))
364                 ;
365
366         signal(SIGCHLD, main_sigchld_handler);
367         errno = save_errno;
368 }
369
370 /*
371  * Signal handler for the alarm after the login grace period has expired.
372  */
373 /*ARGSUSED*/
374 static void
375 grace_alarm_handler(int sig)
376 {
377         if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
378                 kill(pmonitor->m_pid, SIGALRM);
379
380         /*
381          * Try to kill any processes that we have spawned, E.g. authorized
382          * keys command helpers.
383          */
384         if (getpgid(0) == getpid()) {
385                 signal(SIGTERM, SIG_IGN);
386                 killpg(0, SIGTERM);
387         }
388
389         /* Log error and exit. */
390         sigdie("Timeout before authentication for %s", get_remote_ipaddr());
391 }
392
393 /*
394  * Signal handler for the key regeneration alarm.  Note that this
395  * alarm only occurs in the daemon waiting for connections, and it does not
396  * do anything with the private key or random state before forking.
397  * Thus there should be no concurrency control/asynchronous execution
398  * problems.
399  */
400 static void
401 generate_ephemeral_server_key(void)
402 {
403         verbose("Generating %s%d bit RSA key.",
404             sensitive_data.server_key ? "new " : "", options.server_key_bits);
405         if (sensitive_data.server_key != NULL)
406                 key_free(sensitive_data.server_key);
407         sensitive_data.server_key = key_generate(KEY_RSA1,
408             options.server_key_bits);
409         verbose("RSA key generation complete.");
410
411         arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
412         arc4random_stir();
413 }
414
415 /*ARGSUSED*/
416 static void
417 key_regeneration_alarm(int sig)
418 {
419         int save_errno = errno;
420
421         signal(SIGALRM, SIG_DFL);
422         errno = save_errno;
423         key_do_regen = 1;
424 }
425
426 static void
427 sshd_exchange_identification(int sock_in, int sock_out)
428 {
429         u_int i;
430         int mismatch;
431         int remote_major, remote_minor;
432         int major, minor;
433         char *s, *newline = "\n";
434         char buf[256];                  /* Must not be larger than remote_version. */
435         char remote_version[256];       /* Must be at least as big as buf. */
436
437         if ((options.protocol & SSH_PROTO_1) &&
438             (options.protocol & SSH_PROTO_2)) {
439                 major = PROTOCOL_MAJOR_1;
440                 minor = 99;
441         } else if (options.protocol & SSH_PROTO_2) {
442                 major = PROTOCOL_MAJOR_2;
443                 minor = PROTOCOL_MINOR_2;
444                 newline = "\r\n";
445         } else {
446                 major = PROTOCOL_MAJOR_1;
447                 minor = PROTOCOL_MINOR_1;
448         }
449
450         xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s%s%s",
451             major, minor, SSH_VERSION,
452             options.hpn_disabled ? "" : SSH_VERSION_HPN,
453             *options.version_addendum == '\0' ? "" : " ",
454             options.version_addendum, newline);
455
456         /* Send our protocol version identification. */
457         if (roaming_atomicio(vwrite, sock_out, server_version_string,
458             strlen(server_version_string))
459             != strlen(server_version_string)) {
460                 logit("Could not write ident string to %s", get_remote_ipaddr());
461                 cleanup_exit(255);
462         }
463
464         /* Read other sides version identification. */
465         memset(buf, 0, sizeof(buf));
466         for (i = 0; i < sizeof(buf) - 1; i++) {
467                 if (roaming_atomicio(read, sock_in, &buf[i], 1) != 1) {
468                         logit("Did not receive identification string from %s",
469                             get_remote_ipaddr());
470                         cleanup_exit(255);
471                 }
472                 if (buf[i] == '\r') {
473                         buf[i] = 0;
474                         /* Kludge for F-Secure Macintosh < 1.0.2 */
475                         if (i == 12 &&
476                             strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
477                                 break;
478                         continue;
479                 }
480                 if (buf[i] == '\n') {
481                         buf[i] = 0;
482                         break;
483                 }
484         }
485         buf[sizeof(buf) - 1] = 0;
486         client_version_string = xstrdup(buf);
487
488         /*
489          * Check that the versions match.  In future this might accept
490          * several versions and set appropriate flags to handle them.
491          */
492         if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
493             &remote_major, &remote_minor, remote_version) != 3) {
494                 s = "Protocol mismatch.\n";
495                 (void) atomicio(vwrite, sock_out, s, strlen(s));
496                 close(sock_in);
497                 close(sock_out);
498                 logit("Bad protocol version identification '%.100s' from %s",
499                     client_version_string, get_remote_ipaddr());
500                 cleanup_exit(255);
501         }
502         debug("Client protocol version %d.%d; client software version %.100s",
503             remote_major, remote_minor, remote_version);
504
505         compat_datafellows(remote_version);
506
507         if (datafellows & SSH_BUG_PROBE) {
508                 logit("probed from %s with %s.  Don't panic.",
509                     get_remote_ipaddr(), client_version_string);
510                 cleanup_exit(255);
511         }
512
513         if (datafellows & SSH_BUG_SCANNER) {
514                 logit("scanned from %s with %s.  Don't panic.",
515                     get_remote_ipaddr(), client_version_string);
516                 cleanup_exit(255);
517         }
518
519         mismatch = 0;
520         switch (remote_major) {
521         case 1:
522                 if (remote_minor == 99) {
523                         if (options.protocol & SSH_PROTO_2)
524                                 enable_compat20();
525                         else
526                                 mismatch = 1;
527                         break;
528                 }
529                 if (!(options.protocol & SSH_PROTO_1)) {
530                         mismatch = 1;
531                         break;
532                 }
533                 if (remote_minor < 3) {
534                         packet_disconnect("Your ssh version is too old and "
535                             "is no longer supported.  Please install a newer version.");
536                 } else if (remote_minor == 3) {
537                         /* note that this disables agent-forwarding */
538                         enable_compat13();
539                 }
540                 break;
541         case 2:
542                 if (options.protocol & SSH_PROTO_2) {
543                         enable_compat20();
544                         break;
545                 }
546                 /* FALLTHROUGH */
547         default:
548                 mismatch = 1;
549                 break;
550         }
551         chop(server_version_string);
552         debug("Local version string %.200s", server_version_string);
553
554         if (mismatch) {
555                 s = "Protocol major versions differ.\n";
556                 (void) atomicio(vwrite, sock_out, s, strlen(s));
557                 close(sock_in);
558                 close(sock_out);
559                 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
560                     get_remote_ipaddr(),
561                     server_version_string, client_version_string);
562                 cleanup_exit(255);
563         }
564 }
565
566 /* Destroy the host and server keys.  They will no longer be needed. */
567 void
568 destroy_sensitive_data(void)
569 {
570         int i;
571
572         if (sensitive_data.server_key) {
573                 key_free(sensitive_data.server_key);
574                 sensitive_data.server_key = NULL;
575         }
576         for (i = 0; i < options.num_host_key_files; i++) {
577                 if (sensitive_data.host_keys[i]) {
578                         key_free(sensitive_data.host_keys[i]);
579                         sensitive_data.host_keys[i] = NULL;
580                 }
581                 if (sensitive_data.host_certificates[i]) {
582                         key_free(sensitive_data.host_certificates[i]);
583                         sensitive_data.host_certificates[i] = NULL;
584                 }
585         }
586         sensitive_data.ssh1_host_key = NULL;
587         memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
588 }
589
590 /* Demote private to public keys for network child */
591 void
592 demote_sensitive_data(void)
593 {
594         Key *tmp;
595         int i;
596
597         if (sensitive_data.server_key) {
598                 tmp = key_demote(sensitive_data.server_key);
599                 key_free(sensitive_data.server_key);
600                 sensitive_data.server_key = tmp;
601         }
602
603         for (i = 0; i < options.num_host_key_files; i++) {
604                 if (sensitive_data.host_keys[i]) {
605                         tmp = key_demote(sensitive_data.host_keys[i]);
606                         key_free(sensitive_data.host_keys[i]);
607                         sensitive_data.host_keys[i] = tmp;
608                         if (tmp->type == KEY_RSA1)
609                                 sensitive_data.ssh1_host_key = tmp;
610                 }
611                 /* Certs do not need demotion */
612         }
613
614         /* We do not clear ssh1_host key and cookie.  XXX - Okay Niels? */
615 }
616
617 static void
618 privsep_preauth_child(void)
619 {
620         u_int32_t rnd[256];
621         gid_t gidset[1];
622
623         /* Enable challenge-response authentication for privilege separation */
624         privsep_challenge_enable();
625
626         arc4random_stir();
627         arc4random_buf(rnd, sizeof(rnd));
628         RAND_seed(rnd, sizeof(rnd));
629
630         /* Demote the private keys to public keys. */
631         demote_sensitive_data();
632
633         /* Change our root directory */
634         if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
635                 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
636                     strerror(errno));
637         if (chdir("/") == -1)
638                 fatal("chdir(\"/\"): %s", strerror(errno));
639
640         /* Drop our privileges */
641         debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
642             (u_int)privsep_pw->pw_gid);
643 #if 0
644         /* XXX not ready, too heavy after chroot */
645         do_setusercontext(privsep_pw);
646 #else
647         gidset[0] = privsep_pw->pw_gid;
648         if (setgroups(1, gidset) < 0)
649                 fatal("setgroups: %.100s", strerror(errno));
650         permanently_set_uid(privsep_pw);
651 #endif
652 }
653
654 static int
655 privsep_preauth(Authctxt *authctxt)
656 {
657         int status;
658         pid_t pid;
659         struct ssh_sandbox *box = NULL;
660
661         /* Set up unprivileged child process to deal with network data */
662         pmonitor = monitor_init();
663         /* Store a pointer to the kex for later rekeying */
664         pmonitor->m_pkex = &xxx_kex;
665
666         if (use_privsep == PRIVSEP_ON)
667                 box = ssh_sandbox_init();
668         pid = fork();
669         if (pid == -1) {
670                 fatal("fork of unprivileged child failed");
671         } else if (pid != 0) {
672                 debug2("Network child is on pid %ld", (long)pid);
673
674                 pmonitor->m_pid = pid;
675                 if (have_agent)
676                         auth_conn = ssh_get_authentication_connection();
677                 if (box != NULL)
678                         ssh_sandbox_parent_preauth(box, pid);
679                 monitor_child_preauth(authctxt, pmonitor);
680
681                 /* Sync memory */
682                 monitor_sync(pmonitor);
683
684                 /* Wait for the child's exit status */
685                 while (waitpid(pid, &status, 0) < 0) {
686                         if (errno == EINTR)
687                                 continue;
688                         pmonitor->m_pid = -1;
689                         fatal("%s: waitpid: %s", __func__, strerror(errno));
690                 }
691                 privsep_is_preauth = 0;
692                 pmonitor->m_pid = -1;
693                 if (WIFEXITED(status)) {
694                         if (WEXITSTATUS(status) != 0)
695                                 fatal("%s: preauth child exited with status %d",
696                                     __func__, WEXITSTATUS(status));
697                 } else if (WIFSIGNALED(status))
698                         fatal("%s: preauth child terminated by signal %d",
699                             __func__, WTERMSIG(status));
700                 if (box != NULL)
701                         ssh_sandbox_parent_finish(box);
702                 return 1;
703         } else {
704                 /* child */
705                 close(pmonitor->m_sendfd);
706                 close(pmonitor->m_log_recvfd);
707
708                 /* Arrange for logging to be sent to the monitor */
709                 set_log_handler(mm_log_handler, pmonitor);
710
711                 /* Demote the child */
712                 if (getuid() == 0 || geteuid() == 0)
713                         privsep_preauth_child();
714                 setproctitle("%s", "[net]");
715                 if (box != NULL)
716                         ssh_sandbox_child(box);
717
718                 return 0;
719         }
720 }
721
722 static void
723 privsep_postauth(Authctxt *authctxt)
724 {
725         u_int32_t rnd[256];
726
727 #ifdef DISABLE_FD_PASSING
728         if (1) {
729 #else
730         if (authctxt->pw->pw_uid == 0 || options.use_login) {
731 #endif
732                 /* File descriptor passing is broken or root login */
733                 use_privsep = 0;
734                 goto skip;
735         }
736
737         /* New socket pair */
738         monitor_reinit(pmonitor);
739
740         pmonitor->m_pid = fork();
741         if (pmonitor->m_pid == -1)
742                 fatal("fork of unprivileged child failed");
743         else if (pmonitor->m_pid != 0) {
744                 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
745                 buffer_clear(&loginmsg);
746                 monitor_child_postauth(pmonitor);
747
748                 /* NEVERREACHED */
749                 exit(0);
750         }
751
752         /* child */
753
754         close(pmonitor->m_sendfd);
755         pmonitor->m_sendfd = -1;
756
757         /* Demote the private keys to public keys. */
758         demote_sensitive_data();
759
760         arc4random_stir();
761         arc4random_buf(rnd, sizeof(rnd));
762         RAND_seed(rnd, sizeof(rnd));
763
764         /* Drop privileges */
765         do_setusercontext(authctxt->pw);
766
767  skip:
768         /* It is safe now to apply the key state */
769         monitor_apply_keystate(pmonitor);
770
771         /*
772          * Tell the packet layer that authentication was successful, since
773          * this information is not part of the key state.
774          */
775         packet_set_authenticated();
776 }
777
778 static char *
779 list_hostkey_types(void)
780 {
781         Buffer b;
782         const char *p;
783         char *ret;
784         int i;
785         Key *key;
786
787         buffer_init(&b);
788         for (i = 0; i < options.num_host_key_files; i++) {
789                 key = sensitive_data.host_keys[i];
790                 if (key == NULL)
791                         key = sensitive_data.host_pubkeys[i];
792                 if (key == NULL)
793                         continue;
794                 switch (key->type) {
795                 case KEY_RSA:
796                 case KEY_DSA:
797                 case KEY_ECDSA:
798                         if (buffer_len(&b) > 0)
799                                 buffer_append(&b, ",", 1);
800                         p = key_ssh_name(key);
801                         buffer_append(&b, p, strlen(p));
802                         break;
803                 }
804                 /* If the private key has a cert peer, then list that too */
805                 key = sensitive_data.host_certificates[i];
806                 if (key == NULL)
807                         continue;
808                 switch (key->type) {
809                 case KEY_RSA_CERT_V00:
810                 case KEY_DSA_CERT_V00:
811                 case KEY_RSA_CERT:
812                 case KEY_DSA_CERT:
813                 case KEY_ECDSA_CERT:
814                         if (buffer_len(&b) > 0)
815                                 buffer_append(&b, ",", 1);
816                         p = key_ssh_name(key);
817                         buffer_append(&b, p, strlen(p));
818                         break;
819                 }
820         }
821         buffer_append(&b, "\0", 1);
822         ret = xstrdup(buffer_ptr(&b));
823         buffer_free(&b);
824         debug("list_hostkey_types: %s", ret);
825         return ret;
826 }
827
828 static Key *
829 get_hostkey_by_type(int type, int need_private)
830 {
831         int i;
832         Key *key;
833
834         for (i = 0; i < options.num_host_key_files; i++) {
835                 switch (type) {
836                 case KEY_RSA_CERT_V00:
837                 case KEY_DSA_CERT_V00:
838                 case KEY_RSA_CERT:
839                 case KEY_DSA_CERT:
840                 case KEY_ECDSA_CERT:
841                         key = sensitive_data.host_certificates[i];
842                         break;
843                 default:
844                         key = sensitive_data.host_keys[i];
845                         if (key == NULL && !need_private)
846                                 key = sensitive_data.host_pubkeys[i];
847                         break;
848                 }
849                 if (key != NULL && key->type == type)
850                         return need_private ?
851                             sensitive_data.host_keys[i] : key;
852         }
853         return NULL;
854 }
855
856 Key *
857 get_hostkey_public_by_type(int type)
858 {
859         return get_hostkey_by_type(type, 0);
860 }
861
862 Key *
863 get_hostkey_private_by_type(int type)
864 {
865         return get_hostkey_by_type(type, 1);
866 }
867
868 Key *
869 get_hostkey_by_index(int ind)
870 {
871         if (ind < 0 || ind >= options.num_host_key_files)
872                 return (NULL);
873         return (sensitive_data.host_keys[ind]);
874 }
875
876 Key *
877 get_hostkey_public_by_index(int ind)
878 {
879         if (ind < 0 || ind >= options.num_host_key_files)
880                 return (NULL);
881         return (sensitive_data.host_pubkeys[ind]);
882 }
883
884 int
885 get_hostkey_index(Key *key)
886 {
887         int i;
888
889         for (i = 0; i < options.num_host_key_files; i++) {
890                 if (key_is_cert(key)) {
891                         if (key == sensitive_data.host_certificates[i])
892                                 return (i);
893                 } else {
894                         if (key == sensitive_data.host_keys[i])
895                                 return (i);
896                         if (key == sensitive_data.host_pubkeys[i])
897                                 return (i);
898                 }
899         }
900         return (-1);
901 }
902
903 /*
904  * returns 1 if connection should be dropped, 0 otherwise.
905  * dropping starts at connection #max_startups_begin with a probability
906  * of (max_startups_rate/100). the probability increases linearly until
907  * all connections are dropped for startups > max_startups
908  */
909 static int
910 drop_connection(int startups)
911 {
912         int p, r;
913
914         if (startups < options.max_startups_begin)
915                 return 0;
916         if (startups >= options.max_startups)
917                 return 1;
918         if (options.max_startups_rate == 100)
919                 return 1;
920
921         p  = 100 - options.max_startups_rate;
922         p *= startups - options.max_startups_begin;
923         p /= options.max_startups - options.max_startups_begin;
924         p += options.max_startups_rate;
925         r = arc4random_uniform(100);
926
927         debug("drop_connection: p %d, r %d", p, r);
928         return (r < p) ? 1 : 0;
929 }
930
931 static void
932 usage(void)
933 {
934         if (options.version_addendum && *options.version_addendum != '\0')
935                 fprintf(stderr, "%s%s %s, %s\n",
936                     SSH_RELEASE, options.hpn_disabled ? "" : SSH_VERSION_HPN,
937                     options.version_addendum, SSLeay_version(SSLEAY_VERSION));
938         else
939                 fprintf(stderr, "%s%s, %s\n",
940                     SSH_RELEASE, options.hpn_disabled ? "" : SSH_VERSION_HPN,
941                     SSLeay_version(SSLEAY_VERSION));
942         fprintf(stderr,
943 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
944 "            [-E log_file] [-f config_file] [-g login_grace_time]\n"
945 "            [-h host_key_file] [-k key_gen_time] [-o option] [-p port]\n"
946 "            [-u len]\n"
947         );
948         exit(1);
949 }
950
951 static void
952 send_rexec_state(int fd, Buffer *conf)
953 {
954         Buffer m;
955
956         debug3("%s: entering fd = %d config len %d", __func__, fd,
957             buffer_len(conf));
958
959         /*
960          * Protocol from reexec master to child:
961          *      string  configuration
962          *      u_int   ephemeral_key_follows
963          *      bignum  e               (only if ephemeral_key_follows == 1)
964          *      bignum  n                       "
965          *      bignum  d                       "
966          *      bignum  iqmp                    "
967          *      bignum  p                       "
968          *      bignum  q                       "
969          *      string rngseed          (only if OpenSSL is not self-seeded)
970          */
971         buffer_init(&m);
972         buffer_put_cstring(&m, buffer_ptr(conf));
973
974         if (sensitive_data.server_key != NULL &&
975             sensitive_data.server_key->type == KEY_RSA1) {
976                 buffer_put_int(&m, 1);
977                 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
978                 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
979                 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
980                 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
981                 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
982                 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
983         } else
984                 buffer_put_int(&m, 0);
985
986 #ifndef OPENSSL_PRNG_ONLY
987         rexec_send_rng_seed(&m);
988 #endif
989
990         if (ssh_msg_send(fd, 0, &m) == -1)
991                 fatal("%s: ssh_msg_send failed", __func__);
992
993         buffer_free(&m);
994
995         debug3("%s: done", __func__);
996 }
997
998 static void
999 recv_rexec_state(int fd, Buffer *conf)
1000 {
1001         Buffer m;
1002         char *cp;
1003         u_int len;
1004
1005         debug3("%s: entering fd = %d", __func__, fd);
1006
1007         buffer_init(&m);
1008
1009         if (ssh_msg_recv(fd, &m) == -1)
1010                 fatal("%s: ssh_msg_recv failed", __func__);
1011         if (buffer_get_char(&m) != 0)
1012                 fatal("%s: rexec version mismatch", __func__);
1013
1014         cp = buffer_get_string(&m, &len);
1015         if (conf != NULL)
1016                 buffer_append(conf, cp, len + 1);
1017         free(cp);
1018
1019         if (buffer_get_int(&m)) {
1020                 if (sensitive_data.server_key != NULL)
1021                         key_free(sensitive_data.server_key);
1022                 sensitive_data.server_key = key_new_private(KEY_RSA1);
1023                 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
1024                 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
1025                 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
1026                 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
1027                 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
1028                 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
1029                 rsa_generate_additional_parameters(
1030                     sensitive_data.server_key->rsa);
1031         }
1032
1033 #ifndef OPENSSL_PRNG_ONLY
1034         rexec_recv_rng_seed(&m);
1035 #endif
1036
1037         buffer_free(&m);
1038
1039         debug3("%s: done", __func__);
1040 }
1041
1042 /* Accept a connection from inetd */
1043 static void
1044 server_accept_inetd(int *sock_in, int *sock_out)
1045 {
1046         int fd;
1047
1048         startup_pipe = -1;
1049         if (rexeced_flag) {
1050                 close(REEXEC_CONFIG_PASS_FD);
1051                 *sock_in = *sock_out = dup(STDIN_FILENO);
1052                 if (!debug_flag) {
1053                         startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1054                         close(REEXEC_STARTUP_PIPE_FD);
1055                 }
1056         } else {
1057                 *sock_in = dup(STDIN_FILENO);
1058                 *sock_out = dup(STDOUT_FILENO);
1059         }
1060         /*
1061          * We intentionally do not close the descriptors 0, 1, and 2
1062          * as our code for setting the descriptors won't work if
1063          * ttyfd happens to be one of those.
1064          */
1065         if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1066                 dup2(fd, STDIN_FILENO);
1067                 dup2(fd, STDOUT_FILENO);
1068                 if (!log_stderr)
1069                         dup2(fd, STDERR_FILENO);
1070                 if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1071                         close(fd);
1072         }
1073         debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1074 }
1075
1076 /*
1077  * Listen for TCP connections
1078  */
1079 static void
1080 server_listen(void)
1081 {
1082         int ret, listen_sock, on = 1;
1083         struct addrinfo *ai;
1084         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1085         int socksize;
1086         socklen_t len;
1087
1088         for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1089                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1090                         continue;
1091                 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1092                         fatal("Too many listen sockets. "
1093                             "Enlarge MAX_LISTEN_SOCKS");
1094                 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1095                     ntop, sizeof(ntop), strport, sizeof(strport),
1096                     NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1097                         error("getnameinfo failed: %.100s",
1098                             ssh_gai_strerror(ret));
1099                         continue;
1100                 }
1101                 /* Create socket for listening. */
1102                 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1103                     ai->ai_protocol);
1104                 if (listen_sock < 0) {
1105                         /* kernel may not support ipv6 */
1106                         verbose("socket: %.100s", strerror(errno));
1107                         continue;
1108                 }
1109                 if (set_nonblock(listen_sock) == -1) {
1110                         close(listen_sock);
1111                         continue;
1112                 }
1113                 /*
1114                  * Set socket options.
1115                  * Allow local port reuse in TIME_WAIT.
1116                  */
1117                 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1118                     &on, sizeof(on)) == -1)
1119                         error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1120
1121                 /* Only communicate in IPv6 over AF_INET6 sockets. */
1122                 if (ai->ai_family == AF_INET6)
1123                         sock_set_v6only(listen_sock);
1124
1125                 debug("Bind to port %s on %s.", strport, ntop);
1126
1127                 len = sizeof(socksize);
1128                 getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF, &socksize, &len);
1129                 debug("Server TCP RWIN socket size: %d", socksize);
1130                 debug("HPN Buffer Size: %d", options.hpn_buffer_size);
1131
1132                 /* Bind the socket to the desired port. */
1133                 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1134                         error("Bind to port %s on %s failed: %.200s.",
1135                             strport, ntop, strerror(errno));
1136                         close(listen_sock);
1137                         continue;
1138                 }
1139                 listen_socks[num_listen_socks] = listen_sock;
1140                 num_listen_socks++;
1141
1142                 /* Start listening on the port. */
1143                 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1144                         fatal("listen on [%s]:%s: %.100s",
1145                             ntop, strport, strerror(errno));
1146                 logit("Server listening on %s port %s.", ntop, strport);
1147         }
1148         freeaddrinfo(options.listen_addrs);
1149
1150         if (!num_listen_socks)
1151                 fatal("Cannot bind any address.");
1152 }
1153
1154 /*
1155  * The main TCP accept loop. Note that, for the non-debug case, returns
1156  * from this function are in a forked subprocess.
1157  */
1158 static void
1159 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1160 {
1161         fd_set *fdset;
1162         int i, j, ret, maxfd;
1163         int key_used = 0, startups = 0;
1164         int startup_p[2] = { -1 , -1 };
1165         struct sockaddr_storage from;
1166         socklen_t fromlen;
1167         pid_t pid;
1168
1169         /* setup fd set for accept */
1170         fdset = NULL;
1171         maxfd = 0;
1172         for (i = 0; i < num_listen_socks; i++)
1173                 if (listen_socks[i] > maxfd)
1174                         maxfd = listen_socks[i];
1175         /* pipes connected to unauthenticated childs */
1176         startup_pipes = xcalloc(options.max_startups, sizeof(int));
1177         for (i = 0; i < options.max_startups; i++)
1178                 startup_pipes[i] = -1;
1179
1180         /*
1181          * Stay listening for connections until the system crashes or
1182          * the daemon is killed with a signal.
1183          */
1184         for (;;) {
1185                 if (received_sighup)
1186                         sighup_restart();
1187                 if (fdset != NULL)
1188                         free(fdset);
1189                 fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1190                     sizeof(fd_mask));
1191
1192                 for (i = 0; i < num_listen_socks; i++)
1193                         FD_SET(listen_socks[i], fdset);
1194                 for (i = 0; i < options.max_startups; i++)
1195                         if (startup_pipes[i] != -1)
1196                                 FD_SET(startup_pipes[i], fdset);
1197
1198                 /* Wait in select until there is a connection. */
1199                 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1200                 if (ret < 0 && errno != EINTR)
1201                         error("select: %.100s", strerror(errno));
1202                 if (received_sigterm) {
1203                         logit("Received signal %d; terminating.",
1204                             (int) received_sigterm);
1205                         close_listen_socks();
1206                         unlink(options.pid_file);
1207                         exit(received_sigterm == SIGTERM ? 0 : 255);
1208                 }
1209                 if (key_used && key_do_regen) {
1210                         generate_ephemeral_server_key();
1211                         key_used = 0;
1212                         key_do_regen = 0;
1213                 }
1214                 if (ret < 0)
1215                         continue;
1216
1217                 for (i = 0; i < options.max_startups; i++)
1218                         if (startup_pipes[i] != -1 &&
1219                             FD_ISSET(startup_pipes[i], fdset)) {
1220                                 /*
1221                                  * the read end of the pipe is ready
1222                                  * if the child has closed the pipe
1223                                  * after successful authentication
1224                                  * or if the child has died
1225                                  */
1226                                 close(startup_pipes[i]);
1227                                 startup_pipes[i] = -1;
1228                                 startups--;
1229                         }
1230                 for (i = 0; i < num_listen_socks; i++) {
1231                         if (!FD_ISSET(listen_socks[i], fdset))
1232                                 continue;
1233                         fromlen = sizeof(from);
1234                         *newsock = accept(listen_socks[i],
1235                             (struct sockaddr *)&from, &fromlen);
1236                         if (*newsock < 0) {
1237                                 if (errno != EINTR && errno != EWOULDBLOCK &&
1238                                     errno != ECONNABORTED && errno != EAGAIN)
1239                                         error("accept: %.100s",
1240                                             strerror(errno));
1241                                 if (errno == EMFILE || errno == ENFILE)
1242                                         usleep(100 * 1000);
1243                                 continue;
1244                         }
1245                         if (unset_nonblock(*newsock) == -1) {
1246                                 close(*newsock);
1247                                 continue;
1248                         }
1249                         if (drop_connection(startups) == 1) {
1250                                 debug("drop connection #%d", startups);
1251                                 close(*newsock);
1252                                 continue;
1253                         }
1254                         if (pipe(startup_p) == -1) {
1255                                 close(*newsock);
1256                                 continue;
1257                         }
1258
1259                         if (rexec_flag && socketpair(AF_UNIX,
1260                             SOCK_STREAM, 0, config_s) == -1) {
1261                                 error("reexec socketpair: %s",
1262                                     strerror(errno));
1263                                 close(*newsock);
1264                                 close(startup_p[0]);
1265                                 close(startup_p[1]);
1266                                 continue;
1267                         }
1268
1269                         for (j = 0; j < options.max_startups; j++)
1270                                 if (startup_pipes[j] == -1) {
1271                                         startup_pipes[j] = startup_p[0];
1272                                         if (maxfd < startup_p[0])
1273                                                 maxfd = startup_p[0];
1274                                         startups++;
1275                                         break;
1276                                 }
1277
1278                         /*
1279                          * Got connection.  Fork a child to handle it, unless
1280                          * we are in debugging mode.
1281                          */
1282                         if (debug_flag) {
1283                                 /*
1284                                  * In debugging mode.  Close the listening
1285                                  * socket, and start processing the
1286                                  * connection without forking.
1287                                  */
1288                                 debug("Server will not fork when running in debugging mode.");
1289                                 close_listen_socks();
1290                                 *sock_in = *newsock;
1291                                 *sock_out = *newsock;
1292                                 close(startup_p[0]);
1293                                 close(startup_p[1]);
1294                                 startup_pipe = -1;
1295                                 pid = getpid();
1296                                 if (rexec_flag) {
1297                                         send_rexec_state(config_s[0],
1298                                             &cfg);
1299                                         close(config_s[0]);
1300                                 }
1301                                 break;
1302                         }
1303
1304                         /*
1305                          * Normal production daemon.  Fork, and have
1306                          * the child process the connection. The
1307                          * parent continues listening.
1308                          */
1309                         platform_pre_fork();
1310                         if ((pid = fork()) == 0) {
1311                                 /*
1312                                  * Child.  Close the listening and
1313                                  * max_startup sockets.  Start using
1314                                  * the accepted socket. Reinitialize
1315                                  * logging (since our pid has changed).
1316                                  * We break out of the loop to handle
1317                                  * the connection.
1318                                  */
1319                                 platform_post_fork_child();
1320                                 startup_pipe = startup_p[1];
1321                                 close_startup_pipes();
1322                                 close_listen_socks();
1323                                 *sock_in = *newsock;
1324                                 *sock_out = *newsock;
1325                                 log_init(__progname,
1326                                     options.log_level,
1327                                     options.log_facility,
1328                                     log_stderr);
1329                                 if (rexec_flag)
1330                                         close(config_s[0]);
1331                                 break;
1332                         }
1333
1334                         /* Parent.  Stay in the loop. */
1335                         platform_post_fork_parent(pid);
1336                         if (pid < 0)
1337                                 error("fork: %.100s", strerror(errno));
1338                         else
1339                                 debug("Forked child %ld.", (long)pid);
1340
1341                         close(startup_p[1]);
1342
1343                         if (rexec_flag) {
1344                                 send_rexec_state(config_s[0], &cfg);
1345                                 close(config_s[0]);
1346                                 close(config_s[1]);
1347                         }
1348
1349                         /*
1350                          * Mark that the key has been used (it
1351                          * was "given" to the child).
1352                          */
1353                         if ((options.protocol & SSH_PROTO_1) &&
1354                             key_used == 0) {
1355                                 /* Schedule server key regeneration alarm. */
1356                                 signal(SIGALRM, key_regeneration_alarm);
1357                                 alarm(options.key_regeneration_time);
1358                                 key_used = 1;
1359                         }
1360
1361                         close(*newsock);
1362
1363                         /*
1364                          * Ensure that our random state differs
1365                          * from that of the child
1366                          */
1367                         arc4random_stir();
1368                 }
1369
1370                 /* child process check (or debug mode) */
1371                 if (num_listen_socks < 0)
1372                         break;
1373         }
1374 }
1375
1376
1377 /*
1378  * Main program for the daemon.
1379  */
1380 int
1381 main(int ac, char **av)
1382 {
1383         extern char *optarg;
1384         extern int optind;
1385         int opt, i, j, on = 1;
1386         int sock_in = -1, sock_out = -1, newsock = -1;
1387         const char *remote_ip;
1388         int remote_port;
1389         char *line, *logfile = NULL;
1390         int config_s[2] = { -1 , -1 };
1391         u_int n;
1392         u_int64_t ibytes, obytes;
1393         mode_t new_umask;
1394         Key *key;
1395         Key *pubkey;
1396         int keytype;
1397         Authctxt *authctxt;
1398         struct connection_info *connection_info = get_connection_info(0, 0);
1399
1400 #ifdef HAVE_SECUREWARE
1401         (void)set_auth_parameters(ac, av);
1402 #endif
1403         __progname = ssh_get_progname(av[0]);
1404
1405         /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1406         saved_argc = ac;
1407         rexec_argc = ac;
1408         saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1409         for (i = 0; i < ac; i++)
1410                 saved_argv[i] = xstrdup(av[i]);
1411         saved_argv[i] = NULL;
1412
1413 #ifndef HAVE_SETPROCTITLE
1414         /* Prepare for later setproctitle emulation */
1415         compat_init_setproctitle(ac, av);
1416         av = saved_argv;
1417 #endif
1418
1419         if (geteuid() == 0 && setgroups(0, NULL) == -1)
1420                 debug("setgroups(): %.200s", strerror(errno));
1421
1422         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1423         sanitise_stdfd();
1424
1425         /* Initialize configuration options to their default values. */
1426         initialize_server_options(&options);
1427
1428         /* Parse command-line arguments. */
1429         while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeE:iqrtQRT46")) != -1) {
1430                 switch (opt) {
1431                 case '4':
1432                         options.address_family = AF_INET;
1433                         break;
1434                 case '6':
1435                         options.address_family = AF_INET6;
1436                         break;
1437                 case 'f':
1438                         config_file_name = optarg;
1439                         break;
1440                 case 'c':
1441                         if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1442                                 fprintf(stderr, "too many host certificates.\n");
1443                                 exit(1);
1444                         }
1445                         options.host_cert_files[options.num_host_cert_files++] =
1446                            derelativise_path(optarg);
1447                         break;
1448                 case 'd':
1449                         if (debug_flag == 0) {
1450                                 debug_flag = 1;
1451                                 options.log_level = SYSLOG_LEVEL_DEBUG1;
1452                         } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1453                                 options.log_level++;
1454                         break;
1455                 case 'D':
1456                         no_daemon_flag = 1;
1457                         break;
1458                 case 'E':
1459                         logfile = xstrdup(optarg);
1460                         /* FALLTHROUGH */
1461                 case 'e':
1462                         log_stderr = 1;
1463                         break;
1464                 case 'i':
1465                         inetd_flag = 1;
1466                         break;
1467                 case 'r':
1468                         rexec_flag = 0;
1469                         break;
1470                 case 'R':
1471                         rexeced_flag = 1;
1472                         inetd_flag = 1;
1473                         break;
1474                 case 'Q':
1475                         /* ignored */
1476                         break;
1477                 case 'q':
1478                         options.log_level = SYSLOG_LEVEL_QUIET;
1479                         break;
1480                 case 'b':
1481                         options.server_key_bits = (int)strtonum(optarg, 256,
1482                             32768, NULL);
1483                         break;
1484                 case 'p':
1485                         options.ports_from_cmdline = 1;
1486                         if (options.num_ports >= MAX_PORTS) {
1487                                 fprintf(stderr, "too many ports.\n");
1488                                 exit(1);
1489                         }
1490                         options.ports[options.num_ports++] = a2port(optarg);
1491                         if (options.ports[options.num_ports-1] <= 0) {
1492                                 fprintf(stderr, "Bad port number.\n");
1493                                 exit(1);
1494                         }
1495                         break;
1496                 case 'g':
1497                         if ((options.login_grace_time = convtime(optarg)) == -1) {
1498                                 fprintf(stderr, "Invalid login grace time.\n");
1499                                 exit(1);
1500                         }
1501                         break;
1502                 case 'k':
1503                         if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1504                                 fprintf(stderr, "Invalid key regeneration interval.\n");
1505                                 exit(1);
1506                         }
1507                         break;
1508                 case 'h':
1509                         if (options.num_host_key_files >= MAX_HOSTKEYS) {
1510                                 fprintf(stderr, "too many host keys.\n");
1511                                 exit(1);
1512                         }
1513                         options.host_key_files[options.num_host_key_files++] = 
1514                            derelativise_path(optarg);
1515                         break;
1516                 case 't':
1517                         test_flag = 1;
1518                         break;
1519                 case 'T':
1520                         test_flag = 2;
1521                         break;
1522                 case 'C':
1523                         if (parse_server_match_testspec(connection_info,
1524                             optarg) == -1)
1525                                 exit(1);
1526                         break;
1527                 case 'u':
1528                         utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1529                         if (utmp_len > MAXHOSTNAMELEN) {
1530                                 fprintf(stderr, "Invalid utmp length.\n");
1531                                 exit(1);
1532                         }
1533                         break;
1534                 case 'o':
1535                         line = xstrdup(optarg);
1536                         if (process_server_config_line(&options, line,
1537                             "command-line", 0, NULL, NULL) != 0)
1538                                 exit(1);
1539                         free(line);
1540                         break;
1541                 case '?':
1542                 default:
1543                         usage();
1544                         break;
1545                 }
1546         }
1547         if (rexeced_flag || inetd_flag)
1548                 rexec_flag = 0;
1549         if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1550                 fatal("sshd re-exec requires execution with an absolute path");
1551         if (rexeced_flag)
1552                 closefrom(REEXEC_MIN_FREE_FD);
1553         else
1554                 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1555
1556         OpenSSL_add_all_algorithms();
1557
1558         /* If requested, redirect the logs to the specified logfile. */
1559         if (logfile != NULL) {
1560                 log_redirect_stderr_to(logfile);
1561                 free(logfile);
1562         }
1563         /*
1564          * Force logging to stderr until we have loaded the private host
1565          * key (unless started from inetd)
1566          */
1567         log_init(__progname,
1568             options.log_level == SYSLOG_LEVEL_NOT_SET ?
1569             SYSLOG_LEVEL_INFO : options.log_level,
1570             options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1571             SYSLOG_FACILITY_AUTH : options.log_facility,
1572             log_stderr || !inetd_flag);
1573
1574         /*
1575          * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1576          * root's environment
1577          */
1578         if (getenv("KRB5CCNAME") != NULL)
1579                 (void) unsetenv("KRB5CCNAME");
1580
1581 #ifdef _UNICOS
1582         /* Cray can define user privs drop all privs now!
1583          * Not needed on PRIV_SU systems!
1584          */
1585         drop_cray_privs();
1586 #endif
1587
1588         sensitive_data.server_key = NULL;
1589         sensitive_data.ssh1_host_key = NULL;
1590         sensitive_data.have_ssh1_key = 0;
1591         sensitive_data.have_ssh2_key = 0;
1592
1593         /*
1594          * If we're doing an extended config test, make sure we have all of
1595          * the parameters we need.  If we're not doing an extended test,
1596          * do not silently ignore connection test params.
1597          */
1598         if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1599                 fatal("user, host and addr are all required when testing "
1600                    "Match configs");
1601         if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1602                 fatal("Config test connection parameter (-C) provided without "
1603                    "test mode (-T)");
1604
1605         /* Fetch our configuration */
1606         buffer_init(&cfg);
1607         if (rexeced_flag)
1608                 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1609         else
1610                 load_server_config(config_file_name, &cfg);
1611
1612         parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1613             &cfg, NULL);
1614
1615         seed_rng();
1616
1617         /* Fill in default values for those options not explicitly set. */
1618         fill_default_server_options(&options);
1619
1620         /* challenge-response is implemented via keyboard interactive */
1621         if (options.challenge_response_authentication)
1622                 options.kbd_interactive_authentication = 1;
1623
1624         /* Check that options are sensible */
1625         if (options.authorized_keys_command_user == NULL &&
1626             (options.authorized_keys_command != NULL &&
1627             strcasecmp(options.authorized_keys_command, "none") != 0))
1628                 fatal("AuthorizedKeysCommand set without "
1629                     "AuthorizedKeysCommandUser");
1630
1631         /*
1632          * Check whether there is any path through configured auth methods.
1633          * Unfortunately it is not possible to verify this generally before
1634          * daemonisation in the presence of Match block, but this catches
1635          * and warns for trivial misconfigurations that could break login.
1636          */
1637         if (options.num_auth_methods != 0) {
1638                 if ((options.protocol & SSH_PROTO_1))
1639                         fatal("AuthenticationMethods is not supported with "
1640                             "SSH protocol 1");
1641                 for (n = 0; n < options.num_auth_methods; n++) {
1642                         if (auth2_methods_valid(options.auth_methods[n],
1643                             1) == 0)
1644                                 break;
1645                 }
1646                 if (n >= options.num_auth_methods)
1647                         fatal("AuthenticationMethods cannot be satisfied by "
1648                             "enabled authentication methods");
1649         }
1650
1651         /* set default channel AF */
1652         channel_set_af(options.address_family);
1653
1654         /* Check that there are no remaining arguments. */
1655         if (optind < ac) {
1656                 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1657                 exit(1);
1658         }
1659
1660         debug("sshd version %.100s%.100s%s%.100s, %.100s",
1661             SSH_RELEASE,
1662             options.hpn_disabled ? "" : SSH_VERSION_HPN,
1663             *options.version_addendum == '\0' ? "" : " ",
1664             options.version_addendum,
1665             SSLeay_version(SSLEAY_VERSION));
1666
1667         /* Store privilege separation user for later use if required. */
1668         if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1669                 if (use_privsep || options.kerberos_authentication)
1670                         fatal("Privilege separation user %s does not exist",
1671                             SSH_PRIVSEP_USER);
1672         } else {
1673                 memset(privsep_pw->pw_passwd, 0, strlen(privsep_pw->pw_passwd));
1674                 privsep_pw = pwcopy(privsep_pw);
1675                 free(privsep_pw->pw_passwd);
1676                 privsep_pw->pw_passwd = xstrdup("*");
1677         }
1678         endpwent();
1679
1680         /* load host keys */
1681         sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1682             sizeof(Key *));
1683         sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1684             sizeof(Key *));
1685         for (i = 0; i < options.num_host_key_files; i++) {
1686                 sensitive_data.host_keys[i] = NULL;
1687                 sensitive_data.host_pubkeys[i] = NULL;
1688         }
1689
1690         if (options.host_key_agent) {
1691                 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1692                         setenv(SSH_AUTHSOCKET_ENV_NAME,
1693                             options.host_key_agent, 1);
1694                 have_agent = ssh_agent_present();
1695         }
1696
1697         for (i = 0; i < options.num_host_key_files; i++) {
1698                 key = key_load_private(options.host_key_files[i], "", NULL);
1699                 pubkey = key_load_public(options.host_key_files[i], NULL);
1700                 sensitive_data.host_keys[i] = key;
1701                 sensitive_data.host_pubkeys[i] = pubkey;
1702
1703                 if (key == NULL && pubkey != NULL && pubkey->type != KEY_RSA1 &&
1704                     have_agent) {
1705                         debug("will rely on agent for hostkey %s",
1706                             options.host_key_files[i]);
1707                         keytype = pubkey->type;
1708                 } else if (key != NULL) {
1709                         keytype = key->type;
1710                 } else {
1711                         error("Could not load host key: %s",
1712                             options.host_key_files[i]);
1713                         sensitive_data.host_keys[i] = NULL;
1714                         sensitive_data.host_pubkeys[i] = NULL;
1715                         continue;
1716                 }
1717
1718                 switch (keytype) {
1719                 case KEY_RSA1:
1720                         sensitive_data.ssh1_host_key = key;
1721                         sensitive_data.have_ssh1_key = 1;
1722                         break;
1723                 case KEY_RSA:
1724                 case KEY_DSA:
1725                 case KEY_ECDSA:
1726                         sensitive_data.have_ssh2_key = 1;
1727                         break;
1728                 }
1729                 debug("private host key: #%d type %d %s", i, keytype,
1730                     key_type(key ? key : pubkey));
1731         }
1732         if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1733                 logit("Disabling protocol version 1. Could not load host key");
1734                 options.protocol &= ~SSH_PROTO_1;
1735         }
1736         if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1737                 logit("Disabling protocol version 2. Could not load host key");
1738                 options.protocol &= ~SSH_PROTO_2;
1739         }
1740         if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1741                 logit("sshd: no hostkeys available -- exiting.");
1742                 exit(1);
1743         }
1744
1745         /*
1746          * Load certificates. They are stored in an array at identical
1747          * indices to the public keys that they relate to.
1748          */
1749         sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1750             sizeof(Key *));
1751         for (i = 0; i < options.num_host_key_files; i++)
1752                 sensitive_data.host_certificates[i] = NULL;
1753
1754         for (i = 0; i < options.num_host_cert_files; i++) {
1755                 key = key_load_public(options.host_cert_files[i], NULL);
1756                 if (key == NULL) {
1757                         error("Could not load host certificate: %s",
1758                             options.host_cert_files[i]);
1759                         continue;
1760                 }
1761                 if (!key_is_cert(key)) {
1762                         error("Certificate file is not a certificate: %s",
1763                             options.host_cert_files[i]);
1764                         key_free(key);
1765                         continue;
1766                 }
1767                 /* Find matching private key */
1768                 for (j = 0; j < options.num_host_key_files; j++) {
1769                         if (key_equal_public(key,
1770                             sensitive_data.host_keys[j])) {
1771                                 sensitive_data.host_certificates[j] = key;
1772                                 break;
1773                         }
1774                 }
1775                 if (j >= options.num_host_key_files) {
1776                         error("No matching private key for certificate: %s",
1777                             options.host_cert_files[i]);
1778                         key_free(key);
1779                         continue;
1780                 }
1781                 sensitive_data.host_certificates[j] = key;
1782                 debug("host certificate: #%d type %d %s", j, key->type,
1783                     key_type(key));
1784         }
1785         /* Check certain values for sanity. */
1786         if (options.protocol & SSH_PROTO_1) {
1787                 if (options.server_key_bits < 512 ||
1788                     options.server_key_bits > 32768) {
1789                         fprintf(stderr, "Bad server key size.\n");
1790                         exit(1);
1791                 }
1792                 /*
1793                  * Check that server and host key lengths differ sufficiently. This
1794                  * is necessary to make double encryption work with rsaref. Oh, I
1795                  * hate software patents. I dont know if this can go? Niels
1796                  */
1797                 if (options.server_key_bits >
1798                     BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1799                     SSH_KEY_BITS_RESERVED && options.server_key_bits <
1800                     BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1801                     SSH_KEY_BITS_RESERVED) {
1802                         options.server_key_bits =
1803                             BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1804                             SSH_KEY_BITS_RESERVED;
1805                         debug("Forcing server key to %d bits to make it differ from host key.",
1806                             options.server_key_bits);
1807                 }
1808         }
1809
1810         if (use_privsep) {
1811                 struct stat st;
1812
1813                 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1814                     (S_ISDIR(st.st_mode) == 0))
1815                         fatal("Missing privilege separation directory: %s",
1816                             _PATH_PRIVSEP_CHROOT_DIR);
1817
1818 #ifdef HAVE_CYGWIN
1819                 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1820                     (st.st_uid != getuid () ||
1821                     (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1822 #else
1823                 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1824 #endif
1825                         fatal("%s must be owned by root and not group or "
1826                             "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1827         }
1828
1829         if (test_flag > 1) {
1830                 if (server_match_spec_complete(connection_info) == 1)
1831                         parse_server_match_config(&options, connection_info);
1832                 dump_config(&options);
1833         }
1834
1835         /* Configuration looks good, so exit if in test mode. */
1836         if (test_flag)
1837                 exit(0);
1838
1839         /*
1840          * Clear out any supplemental groups we may have inherited.  This
1841          * prevents inadvertent creation of files with bad modes (in the
1842          * portable version at least, it's certainly possible for PAM
1843          * to create a file, and we can't control the code in every
1844          * module which might be used).
1845          */
1846         if (setgroups(0, NULL) < 0)
1847                 debug("setgroups() failed: %.200s", strerror(errno));
1848
1849         if (rexec_flag) {
1850                 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1851                 for (i = 0; i < rexec_argc; i++) {
1852                         debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1853                         rexec_argv[i] = saved_argv[i];
1854                 }
1855                 rexec_argv[rexec_argc] = "-R";
1856                 rexec_argv[rexec_argc + 1] = NULL;
1857         }
1858
1859         /* Ensure that umask disallows at least group and world write */
1860         new_umask = umask(0077) | 0022;
1861         (void) umask(new_umask);
1862
1863         /* Initialize the log (it is reinitialized below in case we forked). */
1864         if (debug_flag && (!inetd_flag || rexeced_flag))
1865                 log_stderr = 1;
1866         log_init(__progname, options.log_level, options.log_facility, log_stderr);
1867
1868         /*
1869          * If not in debugging mode, and not started from inetd, disconnect
1870          * from the controlling terminal, and fork.  The original process
1871          * exits.
1872          */
1873         if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1874 #ifdef TIOCNOTTY
1875                 int fd;
1876 #endif /* TIOCNOTTY */
1877                 if (daemon(0, 0) < 0)
1878                         fatal("daemon() failed: %.200s", strerror(errno));
1879
1880                 /* Disconnect from the controlling tty. */
1881 #ifdef TIOCNOTTY
1882                 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1883                 if (fd >= 0) {
1884                         (void) ioctl(fd, TIOCNOTTY, NULL);
1885                         close(fd);
1886                 }
1887 #endif /* TIOCNOTTY */
1888         }
1889         /* Reinitialize the log (because of the fork above). */
1890         log_init(__progname, options.log_level, options.log_facility, log_stderr);
1891
1892         /* Avoid killing the process in high-pressure swapping environments. */
1893         if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
1894                 debug("madvise(): %.200s", strerror(errno));
1895
1896         /* Initialize the random number generator. */
1897         arc4random_stir();
1898
1899         /* Chdir to the root directory so that the current disk can be
1900            unmounted if desired. */
1901         if (chdir("/") == -1)
1902                 error("chdir(\"/\"): %s", strerror(errno));
1903
1904         /* ignore SIGPIPE */
1905         signal(SIGPIPE, SIG_IGN);
1906
1907         /* Get a connection, either from inetd or a listening TCP socket */
1908         if (inetd_flag) {
1909                 server_accept_inetd(&sock_in, &sock_out);
1910         } else {
1911                 platform_pre_listen();
1912                 server_listen();
1913
1914                 if (options.protocol & SSH_PROTO_1)
1915                         generate_ephemeral_server_key();
1916
1917                 signal(SIGHUP, sighup_handler);
1918                 signal(SIGCHLD, main_sigchld_handler);
1919                 signal(SIGTERM, sigterm_handler);
1920                 signal(SIGQUIT, sigterm_handler);
1921
1922                 /*
1923                  * Write out the pid file after the sigterm handler
1924                  * is setup and the listen sockets are bound
1925                  */
1926                 if (!debug_flag) {
1927                         FILE *f = fopen(options.pid_file, "w");
1928
1929                         if (f == NULL) {
1930                                 error("Couldn't create pid file \"%s\": %s",
1931                                     options.pid_file, strerror(errno));
1932                         } else {
1933                                 fprintf(f, "%ld\n", (long) getpid());
1934                                 fclose(f);
1935                         }
1936                 }
1937
1938                 /* Accept a connection and return in a forked child */
1939                 server_accept_loop(&sock_in, &sock_out,
1940                     &newsock, config_s);
1941         }
1942
1943         /* This is the child processing a new connection. */
1944         setproctitle("%s", "[accepted]");
1945
1946         /*
1947          * Create a new session and process group since the 4.4BSD
1948          * setlogin() affects the entire process group.  We don't
1949          * want the child to be able to affect the parent.
1950          */
1951 #if !defined(SSHD_ACQUIRES_CTTY)
1952         /*
1953          * If setsid is called, on some platforms sshd will later acquire a
1954          * controlling terminal which will result in "could not set
1955          * controlling tty" errors.
1956          */
1957         if (!debug_flag && !inetd_flag && setsid() < 0)
1958                 error("setsid: %.100s", strerror(errno));
1959 #endif
1960
1961         if (rexec_flag) {
1962                 int fd;
1963
1964                 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1965                     sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1966                 dup2(newsock, STDIN_FILENO);
1967                 dup2(STDIN_FILENO, STDOUT_FILENO);
1968                 if (startup_pipe == -1)
1969                         close(REEXEC_STARTUP_PIPE_FD);
1970                 else
1971                         dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1972
1973                 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1974                 close(config_s[1]);
1975                 if (startup_pipe != -1)
1976                         close(startup_pipe);
1977
1978                 execv(rexec_argv[0], rexec_argv);
1979
1980                 /* Reexec has failed, fall back and continue */
1981                 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1982                 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1983                 log_init(__progname, options.log_level,
1984                     options.log_facility, log_stderr);
1985
1986                 /* Clean up fds */
1987                 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1988                 close(config_s[1]);
1989                 close(REEXEC_CONFIG_PASS_FD);
1990                 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1991                 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1992                         dup2(fd, STDIN_FILENO);
1993                         dup2(fd, STDOUT_FILENO);
1994                         if (fd > STDERR_FILENO)
1995                                 close(fd);
1996                 }
1997                 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1998                     sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1999         }
2000
2001         /* Executed child processes don't need these. */
2002         fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2003         fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2004
2005         /*
2006          * Disable the key regeneration alarm.  We will not regenerate the
2007          * key since we are no longer in a position to give it to anyone. We
2008          * will not restart on SIGHUP since it no longer makes sense.
2009          */
2010         alarm(0);
2011         signal(SIGALRM, SIG_DFL);
2012         signal(SIGHUP, SIG_DFL);
2013         signal(SIGTERM, SIG_DFL);
2014         signal(SIGQUIT, SIG_DFL);
2015         signal(SIGCHLD, SIG_DFL);
2016         signal(SIGINT, SIG_DFL);
2017
2018 #ifdef __FreeBSD__
2019         /*
2020          * Initialize the resolver.  This may not happen automatically
2021          * before privsep chroot().
2022          */
2023         if ((_res.options & RES_INIT) == 0) {
2024                 debug("res_init()");
2025                 res_init();
2026         }
2027 #ifdef GSSAPI
2028         /*
2029          * Force GSS-API to parse its configuration and load any
2030          * mechanism plugins.
2031          */
2032         {
2033                 gss_OID_set mechs;
2034                 OM_uint32 minor_status;
2035                 gss_indicate_mechs(&minor_status, &mechs);
2036                 gss_release_oid_set(&minor_status, &mechs);
2037         }
2038 #endif
2039 #endif
2040
2041         /*
2042          * Register our connection.  This turns encryption off because we do
2043          * not have a key.
2044          */
2045         packet_set_connection(sock_in, sock_out);
2046         packet_set_server();
2047
2048         /* Set SO_KEEPALIVE if requested. */
2049         if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
2050             setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
2051                 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2052
2053         if ((remote_port = get_remote_port()) < 0) {
2054                 debug("get_remote_port failed");
2055                 cleanup_exit(255);
2056         }
2057
2058         /*
2059          * We use get_canonical_hostname with usedns = 0 instead of
2060          * get_remote_ipaddr here so IP options will be checked.
2061          */
2062         (void) get_canonical_hostname(0);
2063         /*
2064          * The rest of the code depends on the fact that
2065          * get_remote_ipaddr() caches the remote ip, even if
2066          * the socket goes away.
2067          */
2068         remote_ip = get_remote_ipaddr();
2069
2070 #ifdef SSH_AUDIT_EVENTS
2071         audit_connection_from(remote_ip, remote_port);
2072 #endif
2073 #ifdef LIBWRAP
2074         allow_severity = options.log_facility|LOG_INFO;
2075         deny_severity = options.log_facility|LOG_WARNING;
2076         /* Check whether logins are denied from this host. */
2077         if (packet_connection_is_on_socket()) {
2078                 struct request_info req;
2079
2080                 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
2081                 fromhost(&req);
2082
2083                 if (!hosts_access(&req)) {
2084                         debug("Connection refused by tcp wrapper");
2085                         refuse(&req);
2086                         /* NOTREACHED */
2087                         fatal("libwrap refuse returns");
2088                 }
2089         }
2090 #endif /* LIBWRAP */
2091
2092         /* Log the connection. */
2093         verbose("Connection from %.500s port %d", remote_ip, remote_port);
2094
2095         /* Set HPN options for the child. */
2096         channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
2097
2098         /*
2099          * We don't want to listen forever unless the other side
2100          * successfully authenticates itself.  So we set up an alarm which is
2101          * cleared after successful authentication.  A limit of zero
2102          * indicates no limit. Note that we don't set the alarm in debugging
2103          * mode; it is just annoying to have the server exit just when you
2104          * are about to discover the bug.
2105          */
2106         signal(SIGALRM, grace_alarm_handler);
2107         if (!debug_flag)
2108                 alarm(options.login_grace_time);
2109
2110         sshd_exchange_identification(sock_in, sock_out);
2111
2112         /* In inetd mode, generate ephemeral key only for proto 1 connections */
2113         if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
2114                 generate_ephemeral_server_key();
2115
2116         packet_set_nonblocking();
2117
2118         /* allocate authentication context */
2119         authctxt = xcalloc(1, sizeof(*authctxt));
2120
2121         authctxt->loginmsg = &loginmsg;
2122
2123         /* XXX global for cleanup, access from other modules */
2124         the_authctxt = authctxt;
2125
2126         /* prepare buffer to collect messages to display to user after login */
2127         buffer_init(&loginmsg);
2128         auth_debug_reset();
2129
2130         if (use_privsep) {
2131                 if (privsep_preauth(authctxt) == 1)
2132                         goto authenticated;
2133         } else if (compat20 && have_agent)
2134                 auth_conn = ssh_get_authentication_connection();
2135
2136         /* perform the key exchange */
2137         /* authenticate user and start session */
2138         if (compat20) {
2139                 do_ssh2_kex();
2140                 do_authentication2(authctxt);
2141         } else {
2142                 do_ssh1_kex();
2143                 do_authentication(authctxt);
2144         }
2145         /*
2146          * If we use privilege separation, the unprivileged child transfers
2147          * the current keystate and exits
2148          */
2149         if (use_privsep) {
2150                 mm_send_keystate(pmonitor);
2151                 exit(0);
2152         }
2153
2154  authenticated:
2155         /*
2156          * Cancel the alarm we set to limit the time taken for
2157          * authentication.
2158          */
2159         alarm(0);
2160         signal(SIGALRM, SIG_DFL);
2161         authctxt->authenticated = 1;
2162         if (startup_pipe != -1) {
2163                 close(startup_pipe);
2164                 startup_pipe = -1;
2165         }
2166
2167 #ifdef SSH_AUDIT_EVENTS
2168         audit_event(SSH_AUTH_SUCCESS);
2169 #endif
2170
2171 #ifdef GSSAPI
2172         if (options.gss_authentication) {
2173                 temporarily_use_uid(authctxt->pw);
2174                 ssh_gssapi_storecreds();
2175                 restore_uid();
2176         }
2177 #endif
2178 #ifdef USE_PAM
2179         if (options.use_pam) {
2180                 do_pam_setcred(1);
2181                 do_pam_session();
2182         }
2183 #endif
2184
2185         /*
2186          * In privilege separation, we fork another child and prepare
2187          * file descriptor passing.
2188          */
2189         if (use_privsep) {
2190                 privsep_postauth(authctxt);
2191                 /* the monitor process [priv] will not return */
2192                 if (!compat20)
2193                         destroy_sensitive_data();
2194         }
2195
2196         packet_set_timeout(options.client_alive_interval,
2197             options.client_alive_count_max);
2198
2199         /* Start session. */
2200         do_authenticated(authctxt);
2201
2202         /* The connection has been terminated. */
2203         packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
2204         packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
2205         verbose("Transferred: sent %llu, received %llu bytes",
2206             (unsigned long long)obytes, (unsigned long long)ibytes);
2207
2208         verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2209
2210 #ifdef USE_PAM
2211         if (options.use_pam)
2212                 finish_pam();
2213 #endif /* USE_PAM */
2214
2215 #ifdef SSH_AUDIT_EVENTS
2216         PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2217 #endif
2218
2219         packet_close();
2220
2221         if (use_privsep)
2222                 mm_terminate();
2223
2224         exit(0);
2225 }
2226
2227 /*
2228  * Decrypt session_key_int using our private server key and private host key
2229  * (key with larger modulus first).
2230  */
2231 int
2232 ssh1_session_key(BIGNUM *session_key_int)
2233 {
2234         int rsafail = 0;
2235
2236         if (BN_cmp(sensitive_data.server_key->rsa->n,
2237             sensitive_data.ssh1_host_key->rsa->n) > 0) {
2238                 /* Server key has bigger modulus. */
2239                 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
2240                     BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
2241                     SSH_KEY_BITS_RESERVED) {
2242                         fatal("do_connection: %s: "
2243                             "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2244                             get_remote_ipaddr(),
2245                             BN_num_bits(sensitive_data.server_key->rsa->n),
2246                             BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2247                             SSH_KEY_BITS_RESERVED);
2248                 }
2249                 if (rsa_private_decrypt(session_key_int, session_key_int,
2250                     sensitive_data.server_key->rsa) <= 0)
2251                         rsafail++;
2252                 if (rsa_private_decrypt(session_key_int, session_key_int,
2253                     sensitive_data.ssh1_host_key->rsa) <= 0)
2254                         rsafail++;
2255         } else {
2256                 /* Host key has bigger modulus (or they are equal). */
2257                 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2258                     BN_num_bits(sensitive_data.server_key->rsa->n) +
2259                     SSH_KEY_BITS_RESERVED) {
2260                         fatal("do_connection: %s: "
2261                             "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2262                             get_remote_ipaddr(),
2263                             BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2264                             BN_num_bits(sensitive_data.server_key->rsa->n),
2265                             SSH_KEY_BITS_RESERVED);
2266                 }
2267                 if (rsa_private_decrypt(session_key_int, session_key_int,
2268                     sensitive_data.ssh1_host_key->rsa) < 0)
2269                         rsafail++;
2270                 if (rsa_private_decrypt(session_key_int, session_key_int,
2271                     sensitive_data.server_key->rsa) < 0)
2272                         rsafail++;
2273         }
2274         return (rsafail);
2275 }
2276 /*
2277  * SSH1 key exchange
2278  */
2279 static void
2280 do_ssh1_kex(void)
2281 {
2282         int i, len;
2283         int rsafail = 0;
2284         BIGNUM *session_key_int;
2285         u_char session_key[SSH_SESSION_KEY_LENGTH];
2286         u_char cookie[8];
2287         u_int cipher_type, auth_mask, protocol_flags;
2288
2289         /*
2290          * Generate check bytes that the client must send back in the user
2291          * packet in order for it to be accepted; this is used to defy ip
2292          * spoofing attacks.  Note that this only works against somebody
2293          * doing IP spoofing from a remote machine; any machine on the local
2294          * network can still see outgoing packets and catch the random
2295          * cookie.  This only affects rhosts authentication, and this is one
2296          * of the reasons why it is inherently insecure.
2297          */
2298         arc4random_buf(cookie, sizeof(cookie));
2299
2300         /*
2301          * Send our public key.  We include in the packet 64 bits of random
2302          * data that must be matched in the reply in order to prevent IP
2303          * spoofing.
2304          */
2305         packet_start(SSH_SMSG_PUBLIC_KEY);
2306         for (i = 0; i < 8; i++)
2307                 packet_put_char(cookie[i]);
2308
2309         /* Store our public server RSA key. */
2310         packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2311         packet_put_bignum(sensitive_data.server_key->rsa->e);
2312         packet_put_bignum(sensitive_data.server_key->rsa->n);
2313
2314         /* Store our public host RSA key. */
2315         packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2316         packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2317         packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2318
2319         /* Put protocol flags. */
2320         packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2321
2322         /* Declare which ciphers we support. */
2323         packet_put_int(cipher_mask_ssh1(0));
2324
2325         /* Declare supported authentication types. */
2326         auth_mask = 0;
2327         if (options.rhosts_rsa_authentication)
2328                 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2329         if (options.rsa_authentication)
2330                 auth_mask |= 1 << SSH_AUTH_RSA;
2331         if (options.challenge_response_authentication == 1)
2332                 auth_mask |= 1 << SSH_AUTH_TIS;
2333         if (options.password_authentication)
2334                 auth_mask |= 1 << SSH_AUTH_PASSWORD;
2335         packet_put_int(auth_mask);
2336
2337         /* Send the packet and wait for it to be sent. */
2338         packet_send();
2339         packet_write_wait();
2340
2341         debug("Sent %d bit server key and %d bit host key.",
2342             BN_num_bits(sensitive_data.server_key->rsa->n),
2343             BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2344
2345         /* Read clients reply (cipher type and session key). */
2346         packet_read_expect(SSH_CMSG_SESSION_KEY);
2347
2348         /* Get cipher type and check whether we accept this. */
2349         cipher_type = packet_get_char();
2350
2351         if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2352                 packet_disconnect("Warning: client selects unsupported cipher.");
2353
2354         /* Get check bytes from the packet.  These must match those we
2355            sent earlier with the public key packet. */
2356         for (i = 0; i < 8; i++)
2357                 if (cookie[i] != packet_get_char())
2358                         packet_disconnect("IP Spoofing check bytes do not match.");
2359
2360         debug("Encryption type: %.200s", cipher_name(cipher_type));
2361
2362         /* Get the encrypted integer. */
2363         if ((session_key_int = BN_new()) == NULL)
2364                 fatal("do_ssh1_kex: BN_new failed");
2365         packet_get_bignum(session_key_int);
2366
2367         protocol_flags = packet_get_int();
2368         packet_set_protocol_flags(protocol_flags);
2369         packet_check_eom();
2370
2371         /* Decrypt session_key_int using host/server keys */
2372         rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2373
2374         /*
2375          * Extract session key from the decrypted integer.  The key is in the
2376          * least significant 256 bits of the integer; the first byte of the
2377          * key is in the highest bits.
2378          */
2379         if (!rsafail) {
2380                 (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2381                 len = BN_num_bytes(session_key_int);
2382                 if (len < 0 || (u_int)len > sizeof(session_key)) {
2383                         error("do_ssh1_kex: bad session key len from %s: "
2384                             "session_key_int %d > sizeof(session_key) %lu",
2385                             get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2386                         rsafail++;
2387                 } else {
2388                         memset(session_key, 0, sizeof(session_key));
2389                         BN_bn2bin(session_key_int,
2390                             session_key + sizeof(session_key) - len);
2391
2392                         derive_ssh1_session_id(
2393                             sensitive_data.ssh1_host_key->rsa->n,
2394                             sensitive_data.server_key->rsa->n,
2395                             cookie, session_id);
2396                         /*
2397                          * Xor the first 16 bytes of the session key with the
2398                          * session id.
2399                          */
2400                         for (i = 0; i < 16; i++)
2401                                 session_key[i] ^= session_id[i];
2402                 }
2403         }
2404         if (rsafail) {
2405                 int bytes = BN_num_bytes(session_key_int);
2406                 u_char *buf = xmalloc(bytes);
2407                 MD5_CTX md;
2408
2409                 logit("do_connection: generating a fake encryption key");
2410                 BN_bn2bin(session_key_int, buf);
2411                 MD5_Init(&md);
2412                 MD5_Update(&md, buf, bytes);
2413                 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2414                 MD5_Final(session_key, &md);
2415                 MD5_Init(&md);
2416                 MD5_Update(&md, session_key, 16);
2417                 MD5_Update(&md, buf, bytes);
2418                 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2419                 MD5_Final(session_key + 16, &md);
2420                 memset(buf, 0, bytes);
2421                 free(buf);
2422                 for (i = 0; i < 16; i++)
2423                         session_id[i] = session_key[i] ^ session_key[i + 16];
2424         }
2425         /* Destroy the private and public keys. No longer. */
2426         destroy_sensitive_data();
2427
2428         if (use_privsep)
2429                 mm_ssh1_session_id(session_id);
2430
2431         /* Destroy the decrypted integer.  It is no longer needed. */
2432         BN_clear_free(session_key_int);
2433
2434         /* Set the session key.  From this on all communications will be encrypted. */
2435         packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2436
2437         /* Destroy our copy of the session key.  It is no longer needed. */
2438         memset(session_key, 0, sizeof(session_key));
2439
2440         debug("Received session key; encryption turned on.");
2441
2442         /* Send an acknowledgment packet.  Note that this packet is sent encrypted. */
2443         packet_start(SSH_SMSG_SUCCESS);
2444         packet_send();
2445         packet_write_wait();
2446 }
2447
2448 void
2449 sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, u_int *slen,
2450     u_char *data, u_int dlen)
2451 {
2452         if (privkey) {
2453                 if (PRIVSEP(key_sign(privkey, signature, slen, data, dlen) < 0))
2454                         fatal("%s: key_sign failed", __func__);
2455         } else if (use_privsep) {
2456                 if (mm_key_sign(pubkey, signature, slen, data, dlen) < 0)
2457                         fatal("%s: pubkey_sign failed", __func__);
2458         } else {
2459                 if (ssh_agent_sign(auth_conn, pubkey, signature, slen, data,
2460                     dlen))
2461                         fatal("%s: ssh_agent_sign failed", __func__);
2462         }
2463 }
2464
2465 /*
2466  * SSH2 key exchange: diffie-hellman-group1-sha1
2467  */
2468 static void
2469 do_ssh2_kex(void)
2470 {
2471         Kex *kex;
2472
2473         if (options.ciphers != NULL) {
2474                 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2475                 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2476 #ifdef  NONE_CIPHER_ENABLED
2477         } else if (options.none_enabled == 1) {
2478                 debug ("WARNING: None cipher enabled");
2479                 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2480                 myproposal[PROPOSAL_ENC_ALGS_STOC] = KEX_ENCRYPT_INCLUDE_NONE;
2481 #endif
2482         }
2483         myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2484             compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2485         myproposal[PROPOSAL_ENC_ALGS_STOC] =
2486             compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2487
2488         if (options.macs != NULL) {
2489                 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2490                 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2491         }
2492         if (options.compression == COMP_NONE) {
2493                 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2494                 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2495         } else if (options.compression == COMP_DELAYED) {
2496                 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2497                 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2498         }
2499         if (options.kex_algorithms != NULL)
2500                 myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
2501
2502         if (options.rekey_limit || options.rekey_interval)
2503                 packet_set_rekey_limits((u_int32_t)options.rekey_limit,
2504                     (time_t)options.rekey_interval);
2505
2506         myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2507
2508         /* start key exchange */
2509         kex = kex_setup(myproposal);
2510         kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2511         kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2512         kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2513         kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2514         kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2515         kex->server = 1;
2516         kex->client_version_string=client_version_string;
2517         kex->server_version_string=server_version_string;
2518         kex->load_host_public_key=&get_hostkey_public_by_type;
2519         kex->load_host_private_key=&get_hostkey_private_by_type;
2520         kex->host_key_index=&get_hostkey_index;
2521         kex->sign = sshd_hostkey_sign;
2522
2523         xxx_kex = kex;
2524
2525         dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2526
2527         session_id2 = kex->session_id;
2528         session_id2_len = kex->session_id_len;
2529
2530 #ifdef DEBUG_KEXDH
2531         /* send 1st encrypted/maced/compressed message */
2532         packet_start(SSH2_MSG_IGNORE);
2533         packet_put_cstring("markus");
2534         packet_send();
2535         packet_write_wait();
2536 #endif
2537         debug("KEX done");
2538 }
2539
2540 /* server specific fatal cleanup */
2541 void
2542 cleanup_exit(int i)
2543 {
2544         if (the_authctxt) {
2545                 do_cleanup(the_authctxt);
2546                 if (use_privsep && privsep_is_preauth && pmonitor->m_pid > 1) {
2547                         debug("Killing privsep child %d", pmonitor->m_pid);
2548                         if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2549                             errno != ESRCH)
2550                                 error("%s: kill(%d): %s", __func__,
2551                                     pmonitor->m_pid, strerror(errno));
2552                 }
2553         }
2554 #ifdef SSH_AUDIT_EVENTS
2555         /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2556         if (!use_privsep || mm_is_monitor())
2557                 audit_event(SSH_CONNECTION_ABANDON);
2558 #endif
2559         _exit(i);
2560 }