Home | History | Annotate | Download | only in sshd
      1      0     stevel /*
      2      0     stevel  * Author: Tatu Ylonen <ylo (at) cs.hut.fi>
      3      0     stevel  * Copyright (c) 1995 Tatu Ylonen <ylo (at) cs.hut.fi>, Espoo, Finland
      4      0     stevel  *                    All rights reserved
      5      0     stevel  * This program is the ssh daemon.  It listens for connections from clients,
      6      0     stevel  * and performs authentication, executes use commands or shell, and forwards
      7      0     stevel  * information to/from the application to the user client over an encrypted
      8      0     stevel  * connection.  This can also handle forwarding of X11, TCP/IP, and
      9      0     stevel  * authentication agent connections.
     10      0     stevel  *
     11      0     stevel  * As far as I am concerned, the code I have written for this software
     12      0     stevel  * can be used freely for any purpose.  Any derived versions of this
     13      0     stevel  * software must be clearly marked as such, and if the derived work is
     14      0     stevel  * incompatible with the protocol description in the RFC file, it must be
     15      0     stevel  * called by a name other than "ssh" or "Secure Shell".
     16      0     stevel  *
     17      0     stevel  * SSH2 implementation:
     18      0     stevel  * Privilege Separation:
     19      0     stevel  *
     20      0     stevel  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
     21      0     stevel  * Copyright (c) 2002 Niels Provos.  All rights reserved.
     22      0     stevel  *
     23      0     stevel  * Redistribution and use in source and binary forms, with or without
     24      0     stevel  * modification, are permitted provided that the following conditions
     25      0     stevel  * are met:
     26      0     stevel  * 1. Redistributions of source code must retain the above copyright
     27      0     stevel  *    notice, this list of conditions and the following disclaimer.
     28      0     stevel  * 2. Redistributions in binary form must reproduce the above copyright
     29      0     stevel  *    notice, this list of conditions and the following disclaimer in the
     30      0     stevel  *    documentation and/or other materials provided with the distribution.
     31      0     stevel  *
     32      0     stevel  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     33      0     stevel  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     34      0     stevel  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     35      0     stevel  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     36      0     stevel  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     37      0     stevel  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     38      0     stevel  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     39      0     stevel  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     40      0     stevel  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     41      0     stevel  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     42      0     stevel  */
     43      0     stevel /*
     44   8658        Jan  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
     45      0     stevel  * Use is subject to license terms.
     46      0     stevel  */
     47      0     stevel 
     48      0     stevel #include "includes.h"
     49      0     stevel RCSID("$OpenBSD: sshd.c,v 1.260 2002/09/27 10:42:09 mickey Exp $");
     50      0     stevel 
     51      0     stevel #include <openssl/dh.h>
     52      0     stevel #include <openssl/bn.h>
     53      0     stevel #include <openssl/md5.h>
     54      0     stevel 
     55      0     stevel #include <openssl/rand.h>
     56      0     stevel 
     57      0     stevel #include "ssh.h"
     58      0     stevel #include "ssh1.h"
     59      0     stevel #include "ssh2.h"
     60      0     stevel #include "xmalloc.h"
     61      0     stevel #include "rsa.h"
     62      0     stevel #include "sshpty.h"
     63      0     stevel #include "packet.h"
     64      0     stevel #include "mpaux.h"
     65      0     stevel #include "log.h"
     66      0     stevel #include "servconf.h"
     67      0     stevel #include "uidswap.h"
     68      0     stevel #include "compat.h"
     69      0     stevel #include "buffer.h"
     70      0     stevel #include "cipher.h"
     71      0     stevel #include "kex.h"
     72      0     stevel #include "key.h"
     73      0     stevel #include "dh.h"
     74      0     stevel #include "myproposal.h"
     75      0     stevel #include "authfile.h"
     76      0     stevel #include "pathnames.h"
     77      0     stevel #include "atomicio.h"
     78      0     stevel #include "canohost.h"
     79      0     stevel #include "auth.h"
     80      0     stevel #include "misc.h"
     81      0     stevel #include "dispatch.h"
     82      0     stevel #include "channels.h"
     83      0     stevel #include "session.h"
     84      0     stevel #include "g11n.h"
     85      0     stevel #include "sshlogin.h"
     86      0     stevel #include "xlist.h"
     87   7574        Jan #include "engine.h"
     88      0     stevel 
     89      0     stevel #ifdef HAVE_BSM
     90      0     stevel #include "bsmaudit.h"
     91      0     stevel #endif /* HAVE_BSM */
     92      0     stevel 
     93      0     stevel #ifdef ALTPRIVSEP
     94      0     stevel #include "altprivsep.h"
     95      0     stevel #endif /* ALTPRIVSEP */
     96      0     stevel 
     97      0     stevel #ifdef HAVE_SOLARIS_CONTRACTS
     98      0     stevel #include <sys/ctfs.h>
     99      0     stevel #include <sys/contract.h>
    100      0     stevel #include <sys/contract/process.h>
    101      0     stevel #include <libcontract.h>
    102      0     stevel #endif /* HAVE_SOLARIS_CONTRACTS */
    103      0     stevel 
    104      0     stevel #ifdef GSSAPI
    105      0     stevel #include "ssh-gss.h"
    106      0     stevel #endif /* GSSAPI */
    107      0     stevel 
    108      0     stevel #ifdef LIBWRAP
    109      0     stevel #include <tcpd.h>
    110      0     stevel #include <syslog.h>
    111      0     stevel #ifndef lint
    112      0     stevel int allow_severity = LOG_INFO;
    113      0     stevel int deny_severity = LOG_WARNING;
    114      0     stevel #endif /* lint */
    115      0     stevel #endif /* LIBWRAP */
    116      0     stevel 
    117      0     stevel #ifndef O_NOCTTY
    118      0     stevel #define O_NOCTTY	0
    119      0     stevel #endif
    120      0     stevel 
    121      0     stevel #ifdef HAVE___PROGNAME
    122      0     stevel extern char *__progname;
    123      0     stevel #else
    124      0     stevel char *__progname;
    125      0     stevel #endif
    126      0     stevel 
    127      0     stevel /* Server configuration options. */
    128      0     stevel ServerOptions options;
    129      0     stevel 
    130      0     stevel /* Name of the server configuration file. */
    131      0     stevel static char *config_file_name = _PATH_SERVER_CONFIG_FILE;
    132      0     stevel 
    133      0     stevel /*
    134      0     stevel  * Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
    135      0     stevel  * Default value is AF_UNSPEC means both IPv4 and IPv6.
    136      0     stevel  */
    137      0     stevel #ifdef IPV4_DEFAULT
    138      0     stevel int IPv4or6 = AF_INET;
    139      0     stevel #else
    140      0     stevel int IPv4or6 = AF_UNSPEC;
    141      0     stevel #endif
    142      0     stevel 
    143      0     stevel /*
    144      0     stevel  * Debug mode flag.  This can be set on the command line.  If debug
    145      0     stevel  * mode is enabled, extra debugging output will be sent to the system
    146      0     stevel  * log, the daemon will not go to background, and will exit after processing
    147      0     stevel  * the first connection.
    148      0     stevel  */
    149      0     stevel int debug_flag = 0;
    150      0     stevel 
    151      0     stevel /* Flag indicating that the daemon should only test the configuration and keys. */
    152      0     stevel static int test_flag = 0;
    153      0     stevel 
    154      0     stevel /* Flag indicating that the daemon is being started from inetd. */
    155      0     stevel static int inetd_flag = 0;
    156      0     stevel 
    157      0     stevel /* Flag indicating that sshd should not detach and become a daemon. */
    158      0     stevel static int no_daemon_flag = 0;
    159      0     stevel 
    160      0     stevel /* debug goes to stderr unless inetd_flag is set */
    161      0     stevel int log_stderr = 0;
    162      0     stevel 
    163      0     stevel /* Saved arguments to main(). */
    164      0     stevel static char **saved_argv;
    165      0     stevel static int saved_argc;
    166      0     stevel 
    167      0     stevel /*
    168      0     stevel  * The sockets that the server is listening; this is used in the SIGHUP
    169      0     stevel  * signal handler.
    170      0     stevel  */
    171      0     stevel #define	MAX_LISTEN_SOCKS	16
    172      0     stevel static int listen_socks[MAX_LISTEN_SOCKS];
    173      0     stevel static int num_listen_socks = 0;
    174      0     stevel 
    175      0     stevel /*
    176      0     stevel  * the client's version string, passed by sshd2 in compat mode. if != NULL,
    177      0     stevel  * sshd will skip the version-number exchange
    178      0     stevel  */
    179      0     stevel static char *client_version_string = NULL;
    180      0     stevel static char *server_version_string = NULL;
    181      0     stevel 
    182      0     stevel /* for rekeying XXX fixme */
    183      0     stevel Kex *xxx_kex;
    184      0     stevel 
    185      0     stevel /*
    186      0     stevel  * Any really sensitive data in the application is contained in this
    187      0     stevel  * structure. The idea is that this structure could be locked into memory so
    188      0     stevel  * that the pages do not get written into swap.  However, there are some
    189      0     stevel  * problems. The private key contains BIGNUMs, and we do not (in principle)
    190      0     stevel  * have access to the internals of them, and locking just the structure is
    191      0     stevel  * not very useful.  Currently, memory locking is not implemented.
    192      0     stevel  */
    193      0     stevel static struct {
    194      0     stevel 	Key	*server_key;		/* ephemeral server key */
    195      0     stevel 	Key	*ssh1_host_key;		/* ssh1 host key */
    196      0     stevel 	Key	**host_keys;		/* all private host keys */
    197      0     stevel 	int	have_ssh1_key;
    198      0     stevel 	int	have_ssh2_key;
    199      0     stevel 	u_char	ssh1_cookie[SSH_SESSION_KEY_LENGTH];
    200      0     stevel } sensitive_data;
    201      0     stevel 
    202      0     stevel /*
    203      0     stevel  * Flag indicating whether the RSA server key needs to be regenerated.
    204      0     stevel  * Is set in the SIGALRM handler and cleared when the key is regenerated.
    205      0     stevel  */
    206      0     stevel static volatile sig_atomic_t key_do_regen = 0;
    207      0     stevel 
    208      0     stevel /* This is set to true when a signal is received. */
    209      0     stevel static volatile sig_atomic_t received_sighup = 0;
    210      0     stevel static volatile sig_atomic_t received_sigterm = 0;
    211      0     stevel 
    212      0     stevel /* session identifier, used by RSA-auth */
    213      0     stevel u_char session_id[16];
    214      0     stevel 
    215      0     stevel /* same for ssh2 */
    216      0     stevel u_char *session_id2 = NULL;
    217      0     stevel int session_id2_len = 0;
    218      0     stevel 
    219      0     stevel /* record remote hostname or ip */
    220      0     stevel u_int utmp_len = MAXHOSTNAMELEN;
    221      0     stevel 
    222      0     stevel /* options.max_startup sized array of fd ints */
    223      0     stevel static int *startup_pipes = NULL;
    224      0     stevel static int startup_pipe = -1;	/* in child */
    225  11044  Huie-Ying 
    226  11044  Huie-Ying /* sshd_config buffer */
    227  11044  Huie-Ying Buffer cfg;
    228      0     stevel 
    229      0     stevel #ifdef GSSAPI
    230      0     stevel static gss_OID_set mechs = GSS_C_NULL_OID_SET;
    231      0     stevel #endif /* GSSAPI */
    232      0     stevel 
    233      0     stevel /* Prototypes for various functions defined later in this file. */
    234      0     stevel void destroy_sensitive_data(void);
    235      0     stevel static void demote_sensitive_data(void);
    236      0     stevel 
    237      0     stevel static void do_ssh1_kex(void);
    238      0     stevel static void do_ssh2_kex(void);
    239      0     stevel 
    240      0     stevel /*
    241      0     stevel  * Close all listening sockets
    242      0     stevel  */
    243      0     stevel static void
    244      0     stevel close_listen_socks(void)
    245      0     stevel {
    246      0     stevel 	int i;
    247      0     stevel 
    248      0     stevel 	for (i = 0; i < num_listen_socks; i++)
    249      0     stevel 		(void) close(listen_socks[i]);
    250      0     stevel 	num_listen_socks = -1;
    251      0     stevel }
    252      0     stevel 
    253      0     stevel static void
    254      0     stevel close_startup_pipes(void)
    255      0     stevel {
    256      0     stevel 	int i;
    257      0     stevel 
    258      0     stevel 	if (startup_pipes)
    259      0     stevel 		for (i = 0; i < options.max_startups; i++)
    260      0     stevel 			if (startup_pipes[i] != -1)
    261      0     stevel 				(void) close(startup_pipes[i]);
    262      0     stevel }
    263      0     stevel 
    264      0     stevel /*
    265      0     stevel  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
    266      0     stevel  * the effect is to reread the configuration file (and to regenerate
    267      0     stevel  * the server key).
    268      0     stevel  */
    269      0     stevel static void
    270      0     stevel sighup_handler(int sig)
    271      0     stevel {
    272      0     stevel 	int save_errno = errno;
    273      0     stevel 
    274      0     stevel 	received_sighup = 1;
    275      0     stevel 	(void) signal(SIGHUP, sighup_handler);
    276      0     stevel 	errno = save_errno;
    277      0     stevel }
    278      0     stevel 
    279      0     stevel /*
    280      0     stevel  * Called from the main program after receiving SIGHUP.
    281      0     stevel  * Restarts the server.
    282      0     stevel  */
    283      0     stevel static void
    284      0     stevel sighup_restart(void)
    285      0     stevel {
    286      0     stevel 	log("Received SIGHUP; restarting.");
    287      0     stevel 	close_listen_socks();
    288      0     stevel 	close_startup_pipes();
    289      0     stevel 	(void) execv(saved_argv[0], saved_argv);
    290      0     stevel 	log("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
    291      0     stevel 	    strerror(errno));
    292      0     stevel 	exit(1);
    293      0     stevel }
    294      0     stevel 
    295      0     stevel /*
    296      0     stevel  * Generic signal handler for terminating signals in the master daemon.
    297      0     stevel  */
    298      0     stevel static void
    299      0     stevel sigterm_handler(int sig)
    300      0     stevel {
    301      0     stevel 	received_sigterm = sig;
    302      0     stevel }
    303      0     stevel 
    304      0     stevel /*
    305      0     stevel  * SIGCHLD handler.  This is called whenever a child dies.  This will then
    306      0     stevel  * reap any zombies left by exited children.
    307      0     stevel  */
    308      0     stevel static void
    309      0     stevel main_sigchld_handler(int sig)
    310      0     stevel {
    311      0     stevel 	int save_errno = errno;
    312      0     stevel 	pid_t pid;
    313      0     stevel 	int status;
    314      0     stevel 
    315      0     stevel 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
    316      0     stevel 	    (pid < 0 && errno == EINTR))
    317      0     stevel 		;
    318      0     stevel 
    319      0     stevel 	(void) signal(SIGCHLD, main_sigchld_handler);
    320      0     stevel 	errno = save_errno;
    321      0     stevel }
    322      0     stevel 
    323      0     stevel /*
    324  10515        Jan  * Signal handler for the alarm after the login grace period has expired. This
    325  10515        Jan  * is for the (soon-to-be) unprivileged child only. The monitor gets an event on
    326  10515        Jan  * the communication pipe and exits as well.
    327      0     stevel  */
    328      0     stevel static void
    329      0     stevel grace_alarm_handler(int sig)
    330      0     stevel {
    331      0     stevel 	/* Log error and exit. */
    332  10515        Jan 	fatal("Timeout before authentication for %.200s", get_remote_ipaddr());
    333      0     stevel }
    334      0     stevel 
    335      0     stevel #ifdef HAVE_SOLARIS_CONTRACTS
    336      0     stevel static int contracts_fd = -1;
    337      0     stevel void
    338      0     stevel contracts_pre_fork()
    339      0     stevel {
    340      0     stevel 	const char *during = "opening process contract template";
    341      0     stevel 
    342      0     stevel 	/*
    343      0     stevel 	 * Failure should not be treated as fatal on the theory that
    344      0     stevel 	 * it's better to start with children in the same contract as
    345      0     stevel 	 * the master listener than not at all.
    346      0     stevel 	 */
    347      0     stevel 
    348      0     stevel 	if (contracts_fd == -1) {
    349      0     stevel 		if ((contracts_fd = open64(CTFS_ROOT "/process/template",
    350      0     stevel 				O_RDWR)) == -1)
    351      0     stevel 			goto cleanup;
    352      0     stevel 
    353      0     stevel 		during = "setting sundry contract terms";
    354      0     stevel 		if ((errno = ct_pr_tmpl_set_param(contracts_fd, CT_PR_PGRPONLY)))
    355      0     stevel 			goto cleanup;
    356      0     stevel 
    357      0     stevel 		if ((errno = ct_tmpl_set_informative(contracts_fd, CT_PR_EV_HWERR)))
    358      0     stevel 			goto cleanup;
    359      0     stevel 
    360      0     stevel 		if ((errno = ct_pr_tmpl_set_fatal(contracts_fd, CT_PR_EV_HWERR)))
    361      0     stevel 			goto cleanup;
    362      0     stevel 
    363      0     stevel 		if ((errno = ct_tmpl_set_critical(contracts_fd, 0)))
    364      0     stevel 			goto cleanup;
    365      0     stevel 	}
    366      0     stevel 
    367      0     stevel 	during = "setting active template";
    368      0     stevel 	if ((errno = ct_tmpl_activate(contracts_fd)))
    369      0     stevel 		goto cleanup;
    370      0     stevel 
    371      0     stevel 	debug3("Set active contract");
    372      0     stevel 	return;
    373      0     stevel 
    374      0     stevel cleanup:
    375      0     stevel 	if (contracts_fd != -1)
    376      0     stevel 		(void) close(contracts_fd);
    377      0     stevel 
    378      0     stevel 	contracts_fd = -1;
    379      0     stevel 
    380      0     stevel 	if (errno)
    381      0     stevel 		debug2("Error while trying to set up active contract"
    382      0     stevel 			" template: %s while %s", strerror(errno), during);
    383      0     stevel }
    384      0     stevel 
    385      0     stevel void
    386      0     stevel contracts_post_fork_child()
    387      0     stevel {
    388      0     stevel 	/* Clear active template so fork() creates no new contracts. */
    389      0     stevel 
    390      0     stevel 	if (contracts_fd == -1)
    391      0     stevel 		return;
    392      0     stevel 
    393      0     stevel 	if ((errno = (ct_tmpl_clear(contracts_fd))))
    394      0     stevel 		debug2("Error while trying to clear active contract template"
    395      0     stevel 			" (child): %s", strerror(errno));
    396      0     stevel 	else
    397      0     stevel 		debug3("Cleared active contract template (child)");
    398      0     stevel 
    399      0     stevel 	(void) close(contracts_fd);
    400      0     stevel 
    401      0     stevel 	contracts_fd = -1;
    402      0     stevel }
    403      0     stevel 
    404      0     stevel void
    405      0     stevel contracts_post_fork_parent(int fork_succeeded)
    406      0     stevel {
    407      0     stevel 	char path[PATH_MAX];
    408      0     stevel 	int cfd, n;
    409      0     stevel 	ct_stathdl_t st;
    410      0     stevel 	ctid_t latest;
    411      0     stevel 
    412      0     stevel 	/* Clear active template, abandon latest contract. */
    413      0     stevel 	if (contracts_fd == -1)
    414      0     stevel 		return;
    415      0     stevel 
    416      0     stevel 	if ((errno = ct_tmpl_clear(contracts_fd)))
    417      0     stevel 		debug2("Error while clearing active contract template: %s",
    418      0     stevel 			strerror(errno));
    419      0     stevel 	else
    420      0     stevel 		debug3("Cleared active contract template (parent)");
    421      0     stevel 
    422      0     stevel 	if (!fork_succeeded)
    423      0     stevel 		return;
    424      0     stevel 
    425      0     stevel 	if ((cfd = open64(CTFS_ROOT "/process/latest", O_RDONLY)) == -1) {
    426      0     stevel 		debug2("Error while getting latest contract: %s",
    427      0     stevel 			strerror(errno));
    428      0     stevel 		return;
    429      0     stevel 	}
    430      0     stevel 
    431      0     stevel 	if ((errno = ct_status_read(cfd, CTD_COMMON, &st)) != 0) {
    432      0     stevel 		debug2("Error while getting latest contract ID: %s",
    433      0     stevel 			strerror(errno));
    434      0     stevel 		(void) close(cfd);
    435      0     stevel 		return;
    436      0     stevel 	}
    437      0     stevel 
    438      0     stevel 	latest = ct_status_get_id(st);
    439      0     stevel 	ct_status_free(st);
    440      0     stevel 	(void) close(cfd);
    441      0     stevel 
    442      0     stevel 	n = snprintf(path, PATH_MAX, CTFS_ROOT "/all/%ld/ctl", latest);
    443      0     stevel 
    444      0     stevel 	if (n >= PATH_MAX) {
    445      0     stevel 		debug2("Error while opening the latest contract ctl file: %s",
    446      0     stevel 			strerror(ENAMETOOLONG));
    447      0     stevel 		return;
    448      0     stevel 	}
    449      0     stevel 
    450      0     stevel 	if ((cfd = open64(path, O_WRONLY)) == -1) {
    451      0     stevel 		debug2("Error while opening the latest contract ctl file: %s",
    452      0     stevel 			strerror(errno));
    453      0     stevel 		return;
    454      0     stevel 	}
    455      0     stevel 
    456      0     stevel 	if ((errno = ct_ctl_abandon(cfd)))
    457      0     stevel 		debug2("Error while abandoning latest contract: %s",
    458      0     stevel 			strerror(errno));
    459      0     stevel 	else
    460      0     stevel 		debug3("Abandoned latest contract");
    461      0     stevel 
    462      0     stevel 	(void) close(cfd);
    463      0     stevel }
    464      0     stevel #endif /* HAVE_SOLARIS_CONTRACTS */
    465      0     stevel 
    466      0     stevel /*
    467      0     stevel  * Signal handler for the key regeneration alarm.  Note that this
    468      0     stevel  * alarm only occurs in the daemon waiting for connections, and it does not
    469      0     stevel  * do anything with the private key or random state before forking.
    470      0     stevel  * Thus there should be no concurrency control/asynchronous execution
    471      0     stevel  * problems.
    472      0     stevel  */
    473      0     stevel static void
    474      0     stevel generate_ephemeral_server_key(void)
    475      0     stevel {
    476      0     stevel 	u_int32_t rnd = 0;
    477      0     stevel 	int i;
    478      0     stevel 
    479      0     stevel 	verbose("Generating %s%d bit RSA key.",
    480      0     stevel 	    sensitive_data.server_key ? "new " : "", options.server_key_bits);
    481      0     stevel 	if (sensitive_data.server_key != NULL)
    482      0     stevel 		key_free(sensitive_data.server_key);
    483      0     stevel 	sensitive_data.server_key = key_generate(KEY_RSA1,
    484      0     stevel 	    options.server_key_bits);
    485      0     stevel 	verbose("RSA key generation complete.");
    486      0     stevel 
    487      0     stevel 	for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
    488      0     stevel 		if (i % 4 == 0)
    489      0     stevel 			rnd = arc4random();
    490      0     stevel 		sensitive_data.ssh1_cookie[i] = rnd & 0xff;
    491      0     stevel 		rnd >>= 8;
    492      0     stevel 	}
    493      0     stevel 	arc4random_stir();
    494      0     stevel }
    495      0     stevel 
    496      0     stevel static void
    497      0     stevel key_regeneration_alarm(int sig)
    498      0     stevel {
    499      0     stevel 	int save_errno = errno;
    500      0     stevel 
    501      0     stevel 	(void) signal(SIGALRM, SIG_DFL);
    502      0     stevel 	errno = save_errno;
    503      0     stevel 	key_do_regen = 1;
    504      0     stevel }
    505      0     stevel 
    506      0     stevel static void
    507      0     stevel sshd_exchange_identification(int sock_in, int sock_out)
    508      0     stevel {
    509      0     stevel 	int i, mismatch;
    510      0     stevel 	int remote_major, remote_minor;
    511      0     stevel 	int major, minor;
    512      0     stevel 	char *s;
    513      0     stevel 	char buf[256];			/* Must not be larger than remote_version. */
    514      0     stevel 	char remote_version[256];	/* Must be at least as big as buf. */
    515      0     stevel 
    516      0     stevel 	if ((options.protocol & SSH_PROTO_1) &&
    517      0     stevel 	    (options.protocol & SSH_PROTO_2)) {
    518      0     stevel 		major = PROTOCOL_MAJOR_1;
    519      0     stevel 		minor = 99;
    520      0     stevel 	} else if (options.protocol & SSH_PROTO_2) {
    521      0     stevel 		major = PROTOCOL_MAJOR_2;
    522      0     stevel 		minor = PROTOCOL_MINOR_2;
    523      0     stevel 	} else {
    524      0     stevel 		major = PROTOCOL_MAJOR_1;
    525      0     stevel 		minor = PROTOCOL_MINOR_1;
    526      0     stevel 	}
    527      0     stevel 	(void) snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
    528      0     stevel 	server_version_string = xstrdup(buf);
    529      0     stevel 
    530      0     stevel 	if (client_version_string == NULL) {
    531      0     stevel 		/* Send our protocol version identification. */
    532      0     stevel 		if (atomicio(write, sock_out, server_version_string,
    533      0     stevel 		    strlen(server_version_string))
    534      0     stevel 		    != strlen(server_version_string)) {
    535      0     stevel 			log("Could not write ident string to %s", get_remote_ipaddr());
    536      0     stevel 			fatal_cleanup();
    537      0     stevel 		}
    538      0     stevel 
    539      0     stevel 		/* Read other sides version identification. */
    540      0     stevel 		(void) memset(buf, 0, sizeof(buf));
    541      0     stevel 		for (i = 0; i < sizeof(buf) - 1; i++) {
    542      0     stevel 			if (atomicio(read, sock_in, &buf[i], 1) != 1) {
    543      0     stevel 				log("Did not receive identification string from %s",
    544      0     stevel 				    get_remote_ipaddr());
    545      0     stevel 				fatal_cleanup();
    546      0     stevel 			}
    547      0     stevel 			if (buf[i] == '\r') {
    548      0     stevel 				buf[i] = 0;
    549      0     stevel 				/* Kludge for F-Secure Macintosh < 1.0.2 */
    550      0     stevel 				if (i == 12 &&
    551      0     stevel 				    strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
    552      0     stevel 					break;
    553      0     stevel 				continue;
    554      0     stevel 			}
    555      0     stevel 			if (buf[i] == '\n') {
    556      0     stevel 				buf[i] = 0;
    557      0     stevel 				break;
    558      0     stevel 			}
    559      0     stevel 		}
    560      0     stevel 		buf[sizeof(buf) - 1] = 0;
    561      0     stevel 		client_version_string = xstrdup(buf);
    562      0     stevel 	}
    563      0     stevel 
    564      0     stevel 	/*
    565      0     stevel 	 * Check that the versions match.  In future this might accept
    566      0     stevel 	 * several versions and set appropriate flags to handle them.
    567      0     stevel 	 */
    568      0     stevel 	if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
    569      0     stevel 	    &remote_major, &remote_minor, remote_version) != 3) {
    570      0     stevel 		s = "Protocol mismatch.\n";
    571      0     stevel 		(void) atomicio(write, sock_out, s, strlen(s));
    572      0     stevel 		(void) close(sock_in);
    573      0     stevel 		(void) close(sock_out);
    574      0     stevel 		log("Bad protocol version identification '%.100s' from %s",
    575      0     stevel 		    client_version_string, get_remote_ipaddr());
    576      0     stevel 		fatal_cleanup();
    577      0     stevel 	}
    578      0     stevel 	debug("Client protocol version %d.%d; client software version %.100s",
    579      0     stevel 	    remote_major, remote_minor, remote_version);
    580      0     stevel 
    581      0     stevel 	compat_datafellows(remote_version);
    582      0     stevel 
    583      0     stevel 	if (datafellows & SSH_BUG_PROBE) {
    584      0     stevel 		log("probed from %s with %s.  Don't panic.",
    585      0     stevel 		    get_remote_ipaddr(), client_version_string);
    586      0     stevel 		fatal_cleanup();
    587      0     stevel 	}
    588      0     stevel 
    589      0     stevel 	if (datafellows & SSH_BUG_SCANNER) {
    590      0     stevel 		log("scanned from %s with %s.  Don't panic.",
    591      0     stevel 		    get_remote_ipaddr(), client_version_string);
    592      0     stevel 		fatal_cleanup();
    593      0     stevel 	}
    594      0     stevel 
    595      0     stevel 	mismatch = 0;
    596      0     stevel 	switch (remote_major) {
    597      0     stevel 	case 1:
    598      0     stevel 		if (remote_minor == 99) {
    599      0     stevel 			if (options.protocol & SSH_PROTO_2)
    600      0     stevel 				enable_compat20();
    601      0     stevel 			else
    602      0     stevel 				mismatch = 1;
    603      0     stevel 			break;
    604      0     stevel 		}
    605      0     stevel 		if (!(options.protocol & SSH_PROTO_1)) {
    606      0     stevel 			mismatch = 1;
    607      0     stevel 			break;
    608      0     stevel 		}
    609      0     stevel 		if (remote_minor < 3) {
    610      0     stevel 			packet_disconnect("Your ssh version is too old and "
    611      0     stevel 			    "is no longer supported.  Please install a newer version.");
    612      0     stevel 		} else if (remote_minor == 3) {
    613      0     stevel 			/* note that this disables agent-forwarding */
    614      0     stevel 			enable_compat13();
    615      0     stevel 		}
    616      0     stevel 		break;
    617      0     stevel 	case 2:
    618      0     stevel 		if (options.protocol & SSH_PROTO_2) {
    619      0     stevel 			enable_compat20();
    620      0     stevel 			break;
    621      0     stevel 		}
    622      0     stevel 		/* FALLTHROUGH */
    623      0     stevel 	default:
    624      0     stevel 		mismatch = 1;
    625      0     stevel 		break;
    626      0     stevel 	}
    627      0     stevel 	chop(server_version_string);
    628      0     stevel 	debug("Local version string %.200s", server_version_string);
    629      0     stevel 
    630      0     stevel 	if (mismatch) {
    631      0     stevel 		s = "Protocol major versions differ.\n";
    632      0     stevel 		(void) atomicio(write, sock_out, s, strlen(s));
    633      0     stevel 		(void) close(sock_in);
    634      0     stevel 		(void) close(sock_out);
    635      0     stevel 		log("Protocol major versions differ for %s: %.200s vs. %.200s",
    636      0     stevel 		    get_remote_ipaddr(),
    637      0     stevel 		    server_version_string, client_version_string);
    638      0     stevel 		fatal_cleanup();
    639      0     stevel 	}
    640      0     stevel }
    641      0     stevel 
    642      0     stevel /* Destroy the host and server keys.  They will no longer be needed. */
    643      0     stevel void
    644      0     stevel destroy_sensitive_data(void)
    645      0     stevel {
    646      0     stevel 	int i;
    647      0     stevel 
    648      0     stevel 	if (sensitive_data.server_key) {
    649      0     stevel 		key_free(sensitive_data.server_key);
    650      0     stevel 		sensitive_data.server_key = NULL;
    651      0     stevel 	}
    652      0     stevel 	for (i = 0; i < options.num_host_key_files; i++) {
    653      0     stevel 		if (sensitive_data.host_keys[i]) {
    654      0     stevel 			key_free(sensitive_data.host_keys[i]);
    655      0     stevel 			sensitive_data.host_keys[i] = NULL;
    656      0     stevel 		}
    657      0     stevel 	}
    658      0     stevel 	sensitive_data.ssh1_host_key = NULL;
    659      0     stevel 	(void) memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
    660      0     stevel }
    661      0     stevel 
    662      0     stevel /* Demote private to public keys for network child */
    663      0     stevel static void
    664      0     stevel demote_sensitive_data(void)
    665      0     stevel {
    666      0     stevel 	Key *tmp;
    667      0     stevel 	int i;
    668      0     stevel 
    669      0     stevel 	if (sensitive_data.server_key) {
    670      0     stevel 		tmp = key_demote(sensitive_data.server_key);
    671      0     stevel 		key_free(sensitive_data.server_key);
    672      0     stevel 		sensitive_data.server_key = tmp;
    673      0     stevel 	}
    674      0     stevel 
    675      0     stevel 	for (i = 0; i < options.num_host_key_files; i++) {
    676      0     stevel 		if (sensitive_data.host_keys[i]) {
    677      0     stevel 			tmp = key_demote(sensitive_data.host_keys[i]);
    678      0     stevel 			key_free(sensitive_data.host_keys[i]);
    679      0     stevel 			sensitive_data.host_keys[i] = tmp;
    680      0     stevel 			if (tmp->type == KEY_RSA1)
    681      0     stevel 				sensitive_data.ssh1_host_key = tmp;
    682      0     stevel 		}
    683      0     stevel 	}
    684      0     stevel 
    685      0     stevel 	/* We do not clear ssh1_host key and cookie.  XXX - Okay Niels? */
    686      0     stevel }
    687      0     stevel 
    688      0     stevel static char *
    689      0     stevel list_hostkey_types(void)
    690      0     stevel {
    691      0     stevel 	Buffer b;
    692      0     stevel 	char *p;
    693      0     stevel 	int i;
    694      0     stevel 
    695      0     stevel 	buffer_init(&b);
    696      0     stevel 	for (i = 0; i < options.num_host_key_files; i++) {
    697      0     stevel 		Key *key = sensitive_data.host_keys[i];
    698      0     stevel 		if (key == NULL)
    699      0     stevel 			continue;
    700      0     stevel 		switch (key->type) {
    701      0     stevel 		case KEY_RSA:
    702      0     stevel 		case KEY_DSA:
    703      0     stevel 			if (buffer_len(&b) > 0)
    704      0     stevel 				buffer_append(&b, ",", 1);
    705      0     stevel 			p = key_ssh_name(key);
    706      0     stevel 			buffer_append(&b, p, strlen(p));
    707      0     stevel 			break;
    708      0     stevel 		}
    709      0     stevel 	}
    710      0     stevel 	buffer_append(&b, "\0", 1);
    711      0     stevel 	p = xstrdup(buffer_ptr(&b));
    712      0     stevel 	buffer_free(&b);
    713      0     stevel 	debug("list_hostkey_types: %s", p);
    714      0     stevel 	return p;
    715      0     stevel }
    716      0     stevel 
    717      0     stevel #ifdef lint
    718      0     stevel static
    719      0     stevel #endif /* lint */
    720      0     stevel Key *
    721      0     stevel get_hostkey_by_type(int type)
    722      0     stevel {
    723      0     stevel 	int i;
    724      0     stevel 
    725      0     stevel 	for (i = 0; i < options.num_host_key_files; i++) {
    726      0     stevel 		Key *key = sensitive_data.host_keys[i];
    727      0     stevel 		if (key != NULL && key->type == type)
    728      0     stevel 			return key;
    729      0     stevel 	}
    730      0     stevel 	return NULL;
    731      0     stevel }
    732      0     stevel 
    733      0     stevel #ifdef lint
    734      0     stevel static
    735      0     stevel #endif /* lint */
    736      0     stevel Key *
    737      0     stevel get_hostkey_by_index(int ind)
    738      0     stevel {
    739      0     stevel 	if (ind < 0 || ind >= options.num_host_key_files)
    740      0     stevel 		return (NULL);
    741      0     stevel 	return (sensitive_data.host_keys[ind]);
    742      0     stevel }
    743      0     stevel 
    744      0     stevel #ifdef lint
    745      0     stevel static
    746      0     stevel #endif /* lint */
    747      0     stevel int
    748      0     stevel get_hostkey_index(Key *key)
    749      0     stevel {
    750      0     stevel 	int i;
    751      0     stevel 
    752      0     stevel 	for (i = 0; i < options.num_host_key_files; i++) {
    753      0     stevel 		if (key == sensitive_data.host_keys[i])
    754      0     stevel 			return (i);
    755      0     stevel 	}
    756      0     stevel 	return (-1);
    757      0     stevel }
    758      0     stevel 
    759      0     stevel /*
    760      0     stevel  * returns 1 if connection should be dropped, 0 otherwise.
    761      0     stevel  * dropping starts at connection #max_startups_begin with a probability
    762      0     stevel  * of (max_startups_rate/100). the probability increases linearly until
    763      0     stevel  * all connections are dropped for startups > max_startups
    764      0     stevel  */
    765      0     stevel static int
    766      0     stevel drop_connection(int startups)
    767      0     stevel {
    768      0     stevel 	double p, r;
    769      0     stevel 
    770      0     stevel 	if (startups < options.max_startups_begin)
    771      0     stevel 		return 0;
    772      0     stevel 	if (startups >= options.max_startups)
    773      0     stevel 		return 1;
    774      0     stevel 	if (options.max_startups_rate == 100)
    775      0     stevel 		return 1;
    776      0     stevel 
    777      0     stevel 	p  = 100 - options.max_startups_rate;
    778      0     stevel 	p *= startups - options.max_startups_begin;
    779      0     stevel 	p /= (double) (options.max_startups - options.max_startups_begin);
    780      0     stevel 	p += options.max_startups_rate;
    781      0     stevel 	p /= 100.0;
    782      0     stevel 	r = arc4random() / (double) UINT_MAX;
    783      0     stevel 
    784      0     stevel 	debug("drop_connection: p %g, r %g", p, r);
    785      0     stevel 	return (r < p) ? 1 : 0;
    786      0     stevel }
    787      0     stevel 
    788      0     stevel static void
    789      0     stevel usage(void)
    790      0     stevel {
    791      0     stevel 	(void) fprintf(stderr, gettext("sshd version %s\n"), SSH_VERSION);
    792      0     stevel 	(void) fprintf(stderr,
    793      0     stevel 	    gettext("Usage: %s [options]\n"
    794      0     stevel 		"Options:\n"
    795      0     stevel 		"  -f file    Configuration file (default %s)\n"
    796      0     stevel 		"  -d         Debugging mode (multiple -d means more "
    797      0     stevel 		"debugging)\n"
    798      0     stevel 		"  -i         Started from inetd\n"
    799      0     stevel 		"  -D         Do not fork into daemon mode\n"
    800      0     stevel 		"  -t         Only test configuration file and keys\n"
    801      0     stevel 		"  -q         Quiet (no logging)\n"
    802      0     stevel 		"  -p port    Listen on the specified port (default: 22)\n"
    803      0     stevel 		"  -k seconds Regenerate server key every this many seconds "
    804      0     stevel 		"(default: 3600)\n"
    805      0     stevel 		"  -g seconds Grace period for authentication (default: 600)\n"
    806      0     stevel 		"  -b bits    Size of server RSA key (default: 768 bits)\n"
    807      0     stevel 		"  -h file    File from which to read host key (default: %s)\n"
    808      0     stevel 		"  -4         Use IPv4 only\n"
    809      0     stevel 		"  -6         Use IPv6 only\n"
    810      0     stevel 		"  -o option  Process the option as if it was read from "
    811      0     stevel 		"a configuration file.\n"),
    812      0     stevel 	    __progname, _PATH_SERVER_CONFIG_FILE, _PATH_HOST_KEY_FILE);
    813      0     stevel 	exit(1);
    814      0     stevel }
    815      0     stevel 
    816      0     stevel /*
    817      0     stevel  * Main program for the daemon.
    818      0     stevel  */
    819      0     stevel int
    820      0     stevel main(int ac, char **av)
    821      0     stevel {
    822      0     stevel 	extern char *optarg;
    823      0     stevel 	extern int optind;
    824   7574        Jan 	int opt, j, i, fdsetsz, sock_in = 0, sock_out = 0, newsock = -1, on = 1;
    825      0     stevel 	pid_t pid;
    826      0     stevel 	socklen_t fromlen;
    827      0     stevel 	fd_set *fdset;
    828      0     stevel 	struct sockaddr_storage from;
    829      0     stevel 	const char *remote_ip;
    830      0     stevel 	int remote_port;
    831      0     stevel 	FILE *f;
    832      0     stevel 	struct addrinfo *ai;
    833      0     stevel 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
    834      0     stevel 	int listen_sock, maxfd;
    835      0     stevel 	int startup_p[2];
    836      0     stevel 	int startups = 0;
    837   7574        Jan 	Authctxt *authctxt = NULL;
    838      0     stevel 	Key *key;
    839      0     stevel 	int ret, key_used = 0;
    840      0     stevel #ifdef HAVE_BSM
    841      0     stevel 	au_id_t	    auid = AU_NOAUDITID;
    842      0     stevel #endif /* HAVE_BSM */
    843   7574        Jan 	int mpipe;
    844      0     stevel 
    845      0     stevel 	__progname = get_progname(av[0]);
    846      0     stevel 
    847      0     stevel 	(void) g11n_setlocale(LC_ALL, "");
    848      0     stevel 
    849      0     stevel 	init_rng();
    850      0     stevel 
    851      0     stevel 	/* Save argv. */
    852      0     stevel 	saved_argc = ac;
    853      0     stevel 	saved_argv = av;
    854      0     stevel 
    855      0     stevel 	/* Initialize configuration options to their default values. */
    856      0     stevel 	initialize_server_options(&options);
    857      0     stevel 
    858      0     stevel 	/* Parse command-line arguments. */
    859      0     stevel 	while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:o:dDeiqtQ46")) != -1) {
    860      0     stevel 		switch (opt) {
    861      0     stevel 		case '4':
    862      0     stevel 			IPv4or6 = AF_INET;
    863      0     stevel 			break;
    864      0     stevel 		case '6':
    865      0     stevel 			IPv4or6 = AF_INET6;
    866      0     stevel 			break;
    867      0     stevel 		case 'f':
    868      0     stevel 			config_file_name = optarg;
    869      0     stevel 			break;
    870      0     stevel 		case 'd':
    871      0     stevel 			if (0 == debug_flag) {
    872      0     stevel 				debug_flag = 1;
    873      0     stevel 				options.log_level = SYSLOG_LEVEL_DEBUG1;
    874      0     stevel 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
    875      0     stevel 				options.log_level++;
    876      0     stevel 			} else {
    877      0     stevel 				(void) fprintf(stderr,
    878      0     stevel 					gettext("Debug level too high.\n"));
    879      0     stevel 				exit(1);
    880      0     stevel 			}
    881      0     stevel 			break;
    882      0     stevel 		case 'D':
    883      0     stevel 			no_daemon_flag = 1;
    884      0     stevel 			break;
    885      0     stevel 		case 'e':
    886      0     stevel 			log_stderr = 1;
    887      0     stevel 			break;
    888      0     stevel 		case 'i':
    889      0     stevel 			inetd_flag = 1;
    890      0     stevel 			break;
    891      0     stevel 		case 'Q':
    892      0     stevel 			/* ignored */
    893      0     stevel 			break;
    894      0     stevel 		case 'q':
    895      0     stevel 			options.log_level = SYSLOG_LEVEL_QUIET;
    896      0     stevel 			break;
    897      0     stevel 		case 'b':
    898      0     stevel 			options.server_key_bits = atoi(optarg);
    899      0     stevel 			break;
    900      0     stevel 		case 'p':
    901      0     stevel 			options.ports_from_cmdline = 1;
    902      0     stevel 			if (options.num_ports >= MAX_PORTS) {
    903      0     stevel 				(void) fprintf(stderr, gettext("too many ports.\n"));
    904      0     stevel 				exit(1);
    905      0     stevel 			}
    906      0     stevel 			options.ports[options.num_ports++] = a2port(optarg);
    907      0     stevel 			if (options.ports[options.num_ports-1] == 0) {
    908      0     stevel 				(void) fprintf(stderr, gettext("Bad port number.\n"));
    909      0     stevel 				exit(1);
    910      0     stevel 			}
    911      0     stevel 			break;
    912      0     stevel 		case 'g':
    913      0     stevel 			if ((options.login_grace_time = convtime(optarg)) == -1) {
    914      0     stevel 				(void) fprintf(stderr,
    915      0     stevel 					gettext("Invalid login grace time.\n"));
    916      0     stevel 				exit(1);
    917      0     stevel 			}
    918      0     stevel 			break;
    919      0     stevel 		case 'k':
    920      0     stevel 			if ((options.key_regeneration_time = convtime(optarg)) == -1) {
    921      0     stevel 				(void) fprintf(stderr,
    922      0     stevel 					gettext("Invalid key regeneration "
    923      0     stevel 						"interval.\n"));
    924      0     stevel 				exit(1);
    925      0     stevel 			}
    926      0     stevel 			break;
    927      0     stevel 		case 'h':
    928      0     stevel 			if (options.num_host_key_files >= MAX_HOSTKEYS) {
    929      0     stevel 				(void) fprintf(stderr,
    930      0     stevel 					gettext("too many host keys.\n"));
    931      0     stevel 				exit(1);
    932      0     stevel 			}
    933      0     stevel 			options.host_key_files[options.num_host_key_files++] = optarg;
    934      0     stevel 			break;
    935      0     stevel 		case 'V':
    936      0     stevel 			client_version_string = optarg;
    937      0     stevel 			/* only makes sense with inetd_flag, i.e. no listen() */
    938      0     stevel 			inetd_flag = 1;
    939      0     stevel 			break;
    940      0     stevel 		case 't':
    941      0     stevel 			test_flag = 1;
    942      0     stevel 			break;
    943      0     stevel 		case 'o':
    944      0     stevel 			if (process_server_config_line(&options, optarg,
    945  11044  Huie-Ying 			    "command-line", 0, NULL, NULL, NULL, NULL) != 0)
    946      0     stevel 				exit(1);
    947      0     stevel 			break;
    948      0     stevel 		case '?':
    949      0     stevel 		default:
    950      0     stevel 			usage();
    951      0     stevel 			break;
    952      0     stevel 		}
    953      0     stevel 	}
    954   7574        Jan 
    955   7574        Jan 	/*
    956   7574        Jan 	 * There is no need to use the PKCS#11 engine in the master SSH process.
    957   7574        Jan 	 */
    958      0     stevel 	SSLeay_add_all_algorithms();
    959   7574        Jan 	seed_rng();
    960      0     stevel 	channel_set_af(IPv4or6);
    961      0     stevel 
    962      0     stevel 	/*
    963      0     stevel 	 * Force logging to stderr until we have loaded the private host
    964      0     stevel 	 * key (unless started from inetd)
    965      0     stevel 	 */
    966      0     stevel 	log_init(__progname,
    967      0     stevel 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
    968      0     stevel 	    SYSLOG_LEVEL_INFO : options.log_level,
    969      0     stevel 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
    970      0     stevel 	    SYSLOG_FACILITY_AUTH : options.log_facility,
    971      0     stevel 	    !inetd_flag);
    972      0     stevel 
    973      0     stevel #ifdef _UNICOS
    974      0     stevel 	/* Cray can define user privs drop all prives now!
    975      0     stevel 	 * Not needed on PRIV_SU systems!
    976      0     stevel 	 */
    977      0     stevel 	drop_cray_privs();
    978      0     stevel #endif
    979      0     stevel 
    980  11044  Huie-Ying 	/* Fetch our configuration */
    981  11044  Huie-Ying 	buffer_init(&cfg);
    982  11044  Huie-Ying 	load_server_config(config_file_name, &cfg);
    983  11044  Huie-Ying 	parse_server_config(&options, config_file_name, &cfg, NULL, NULL, NULL);
    984      0     stevel 
    985      0     stevel 	/* Fill in default values for those options not explicitly set. */
    986      0     stevel 	fill_default_server_options(&options);
    987      0     stevel 
    988      0     stevel 	utmp_len = options.lookup_client_hostnames ? utmp_len : 0;
    989      0     stevel 
    990      0     stevel 	/* Check that there are no remaining arguments. */
    991      0     stevel 	if (optind < ac) {
    992      0     stevel 		(void) fprintf(stderr, gettext("Extra argument %s.\n"), av[optind]);
    993      0     stevel 		exit(1);
    994      0     stevel 	}
    995      0     stevel 
    996      0     stevel 	debug("sshd version %.100s", SSH_VERSION);
    997      0     stevel 
    998      0     stevel 	/* load private host keys */
    999      0     stevel 	if (options.num_host_key_files > 0)
   1000      0     stevel 		sensitive_data.host_keys =
   1001      0     stevel 		    xmalloc(options.num_host_key_files * sizeof(Key *));
   1002      0     stevel 	for (i = 0; i < options.num_host_key_files; i++)
   1003      0     stevel 		sensitive_data.host_keys[i] = NULL;
   1004      0     stevel 	sensitive_data.server_key = NULL;
   1005      0     stevel 	sensitive_data.ssh1_host_key = NULL;
   1006      0     stevel 	sensitive_data.have_ssh1_key = 0;
   1007      0     stevel 	sensitive_data.have_ssh2_key = 0;
   1008      0     stevel 
   1009      0     stevel 	for (i = 0; i < options.num_host_key_files; i++) {
   1010      0     stevel 		key = key_load_private(options.host_key_files[i], "", NULL);
   1011      0     stevel 		sensitive_data.host_keys[i] = key;
   1012      0     stevel 		if (key == NULL) {
   1013      0     stevel 			error("Could not load host key: %s",
   1014      0     stevel 			    options.host_key_files[i]);
   1015      0     stevel 			sensitive_data.host_keys[i] = NULL;
   1016      0     stevel 			continue;
   1017      0     stevel 		}
   1018      0     stevel 		switch (key->type) {
   1019      0     stevel 		case KEY_RSA1:
   1020      0     stevel 			sensitive_data.ssh1_host_key = key;
   1021      0     stevel 			sensitive_data.have_ssh1_key = 1;
   1022      0     stevel 			break;
   1023      0     stevel 		case KEY_RSA:
   1024      0     stevel 		case KEY_DSA:
   1025      0     stevel 			sensitive_data.have_ssh2_key = 1;
   1026      0     stevel 			break;
   1027      0     stevel 		}
   1028      0     stevel 		debug("private host key: #%d type %d %s", i, key->type,
   1029      0     stevel 		    key_type(key));
   1030      0     stevel 	}
   1031      0     stevel 	if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
   1032      0     stevel 		log("Disabling protocol version 1. Could not load host key");
   1033      0     stevel 		options.protocol &= ~SSH_PROTO_1;
   1034      0     stevel 	}
   1035      0     stevel 	if ((options.protocol & SSH_PROTO_2) &&
   1036      0     stevel 	    !sensitive_data.have_ssh2_key) {
   1037      0     stevel #ifdef GSSAPI
   1038      0     stevel 		if (options.gss_keyex)
   1039      0     stevel 			ssh_gssapi_server_mechs(&mechs);
   1040      0     stevel 
   1041      0     stevel 		if (mechs == GSS_C_NULL_OID_SET) {
   1042      0     stevel 			log("Disabling protocol version 2. Could not load host"
   1043      0     stevel 			    "key or GSS-API mechanisms");
   1044      0     stevel 			options.protocol &= ~SSH_PROTO_2;
   1045      0     stevel 		}
   1046      0     stevel #else
   1047      0     stevel 		log("Disabling protocol version 2. Could not load host key");
   1048      0     stevel 		options.protocol &= ~SSH_PROTO_2;
   1049      0     stevel #endif /* GSSAPI */
   1050      0     stevel 	}
   1051      0     stevel 	if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
   1052      0     stevel 		log("sshd: no hostkeys available -- exiting.");
   1053      0     stevel 		exit(1);
   1054      0     stevel 	}
   1055      0     stevel 
   1056      0     stevel 	/* Check certain values for sanity. */
   1057      0     stevel 	if (options.protocol & SSH_PROTO_1) {
   1058      0     stevel 		if (options.server_key_bits < 512 ||
   1059      0     stevel 		    options.server_key_bits > 32768) {
   1060      0     stevel 			(void) fprintf(stderr, gettext("Bad server key size.\n"));
   1061      0     stevel 			exit(1);
   1062      0     stevel 		}
   1063      0     stevel 		/*
   1064      0     stevel 		 * Check that server and host key lengths differ sufficiently. This
   1065      0     stevel 		 * is necessary to make double encryption work with rsaref. Oh, I
   1066      0     stevel 		 * hate software patents. I dont know if this can go? Niels
   1067      0     stevel 		 */
   1068      0     stevel 		if (options.server_key_bits >
   1069      0     stevel 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
   1070      0     stevel 		    SSH_KEY_BITS_RESERVED && options.server_key_bits <
   1071      0     stevel 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
   1072      0     stevel 		    SSH_KEY_BITS_RESERVED) {
   1073      0     stevel 			options.server_key_bits =
   1074      0     stevel 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
   1075      0     stevel 			    SSH_KEY_BITS_RESERVED;
   1076      0     stevel 			debug("Forcing server key to %d bits to make it differ from host key.",
   1077      0     stevel 			    options.server_key_bits);
   1078      0     stevel 		}
   1079      0     stevel 	}
   1080      0     stevel 
   1081      0     stevel 	/* Configuration looks good, so exit if in test mode. */
   1082      0     stevel 	if (test_flag)
   1083      0     stevel 		exit(0);
   1084      0     stevel 
   1085      0     stevel 	/*
   1086      0     stevel 	 * Clear out any supplemental groups we may have inherited.  This
   1087      0     stevel 	 * prevents inadvertent creation of files with bad modes (in the
   1088      0     stevel 	 * portable version at least, it's certainly possible for PAM
   1089      0     stevel 	 * to create a file, and we can't control the code in every
   1090      0     stevel 	 * module which might be used).
   1091      0     stevel 	 */
   1092      0     stevel 	if (setgroups(0, NULL) < 0)
   1093      0     stevel 		debug("setgroups() failed: %.200s", strerror(errno));
   1094      0     stevel 
   1095      0     stevel 	/* Initialize the log (it is reinitialized below in case we forked). */
   1096      0     stevel 	if (debug_flag && !inetd_flag)
   1097      0     stevel 		log_stderr = 1;
   1098      0     stevel 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
   1099      0     stevel 
   1100   8658        Jan 	/*
   1101   8658        Jan 	 * Solaris 9 and systems upgraded from it may have the Ciphers option
   1102   8658        Jan 	 * explicitly set to "aes128-cbc,blowfish-cbc,3des-cbc" in the
   1103   8658        Jan 	 * sshd_config. Since the default server cipher list completely changed
   1104   8658        Jan 	 * since then we rather notify the administator on startup. We do this
   1105   8658        Jan 	 * check after log_init() so that the message goes to syslogd and not to
   1106   8658        Jan 	 * stderr (unless the server is in the debug mode). Note that since
   1107   8658        Jan 	 * Solaris 10 we no longer ship sshd_config with explicit settings for
   1108   8658        Jan 	 * Ciphers or MACs. Do not try to augment the cipher list here since
   1109   8658        Jan 	 * that might end up in a very confusing situation.
   1110   8658        Jan 	 */
   1111   8658        Jan #define	OLD_DEFAULT_CIPHERS_LIST "aes128-cbc,blowfish-cbc,3des-cbc"
   1112   8658        Jan 	if (options.ciphers != NULL &&
   1113   8658        Jan 	    strcmp(options.ciphers, OLD_DEFAULT_CIPHERS_LIST) == 0) {
   1114   8658        Jan 		notice("Old default value \"%s\" for the \"Ciphers\" "
   1115   8658        Jan 		    "option found in use. In general it is prudent to let "
   1116   8658        Jan 		    "the server choose the defaults unless your environment "
   1117   8658        Jan 		    "specifically needs an explicit setting. See "
   1118   8658        Jan 		    "sshd_config(4) for more information.",
   1119   8658        Jan 		    OLD_DEFAULT_CIPHERS_LIST);
   1120   8658        Jan 	}
   1121   8658        Jan 
   1122      0     stevel #ifdef HAVE_BSM
   1123      0     stevel 	(void) setauid(&auid);
   1124      0     stevel #endif /* HAVE_BSM */
   1125      0     stevel 
   1126      0     stevel 	/*
   1127      0     stevel 	 * If not in debugging mode, and not started from inetd, disconnect
   1128      0     stevel 	 * from the controlling terminal, and fork.  The original process
   1129      0     stevel 	 * exits.
   1130      0     stevel 	 */
   1131      0     stevel 	if (!(debug_flag || inetd_flag || no_daemon_flag)) {
   1132      0     stevel #ifdef TIOCNOTTY
   1133      0     stevel 		int fd;
   1134      0     stevel #endif /* TIOCNOTTY */
   1135      0     stevel 		if (daemon(0, 0) < 0)
   1136      0     stevel 			fatal("daemon() failed: %.200s", strerror(errno));
   1137      0     stevel 
   1138      0     stevel 		/* Disconnect from the controlling tty. */
   1139      0     stevel #ifdef TIOCNOTTY
   1140      0     stevel 		fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
   1141      0     stevel 		if (fd >= 0) {
   1142      0     stevel 			(void) ioctl(fd, TIOCNOTTY, NULL);
   1143      0     stevel 			(void) close(fd);
   1144      0     stevel 		}
   1145      0     stevel #endif /* TIOCNOTTY */
   1146      0     stevel 	}
   1147      0     stevel 	/* Reinitialize the log (because of the fork above). */
   1148      0     stevel 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
   1149      0     stevel 
   1150      0     stevel 	/* Initialize the random number generator. */
   1151      0     stevel 	arc4random_stir();
   1152      0     stevel 
   1153      0     stevel 	/* Chdir to the root directory so that the current disk can be
   1154      0     stevel 	   unmounted if desired. */
   1155      0     stevel 	(void) chdir("/");
   1156      0     stevel 
   1157      0     stevel 	/* ignore SIGPIPE */
   1158      0     stevel 	(void) signal(SIGPIPE, SIG_IGN);
   1159      0     stevel 
   1160      0     stevel 	/* Start listening for a socket, unless started from inetd. */
   1161      0     stevel 	if (inetd_flag) {
   1162      0     stevel 		int s1;
   1163      0     stevel 		s1 = dup(0);	/* Make sure descriptors 0, 1, and 2 are in use. */
   1164      0     stevel 		(void) dup(s1);
   1165      0     stevel 		sock_in = dup(0);
   1166      0     stevel 		sock_out = dup(1);
   1167      0     stevel 		startup_pipe = -1;
   1168   7574        Jan 		/* we need this later for setting audit context */
   1169   6481    paulson 		newsock = sock_in;
   1170      0     stevel 		/*
   1171      0     stevel 		 * We intentionally do not close the descriptors 0, 1, and 2
   1172      0     stevel 		 * as our code for setting the descriptors won\'t work if
   1173      0     stevel 		 * ttyfd happens to be one of those.
   1174      0     stevel 		 */
   1175      0     stevel 		debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
   1176      0     stevel 		if (options.protocol & SSH_PROTO_1)
   1177      0     stevel 			generate_ephemeral_server_key();
   1178      0     stevel 	} else {
   1179      0     stevel 		for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
   1180      0     stevel 			if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
   1181      0     stevel 				continue;
   1182      0     stevel 			if (num_listen_socks >= MAX_LISTEN_SOCKS)
   1183      0     stevel 				fatal("Too many listen sockets. "
   1184      0     stevel 				    "Enlarge MAX_LISTEN_SOCKS");
   1185      0     stevel 			if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
   1186      0     stevel 			    ntop, sizeof(ntop), strport, sizeof(strport),
   1187      0     stevel 			    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
   1188      0     stevel 				error("getnameinfo failed");
   1189      0     stevel 				continue;
   1190      0     stevel 			}
   1191      0     stevel 			/* Create socket for listening. */
   1192      0     stevel 			listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
   1193      0     stevel 			if (listen_sock < 0) {
   1194      0     stevel 				/* kernel may not support ipv6 */
   1195      0     stevel 				verbose("socket: %.100s", strerror(errno));
   1196      0     stevel 				continue;
   1197      0     stevel 			}
   1198      0     stevel 			if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
   1199      0     stevel 				error("listen_sock O_NONBLOCK: %s", strerror(errno));
   1200      0     stevel 				(void) close(listen_sock);
   1201      0     stevel 				continue;
   1202      0     stevel 			}
   1203      0     stevel 			/*
   1204      0     stevel 			 * Set socket options.
   1205      0     stevel 			 * Allow local port reuse in TIME_WAIT.
   1206      0     stevel 			 */
   1207      0     stevel 			if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
   1208      0     stevel 			    &on, sizeof(on)) == -1)
   1209      0     stevel 				error("setsockopt SO_REUSEADDR: %s", strerror(errno));
   1210      0     stevel 
   1211      0     stevel 			debug("Bind to port %s on %s.", strport, ntop);
   1212      0     stevel 
   1213      0     stevel 			/* Bind the socket to the desired port. */
   1214      0     stevel 			if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
   1215      0     stevel 				if (!ai->ai_next)
   1216      0     stevel 				    error("Bind to port %s on %s failed: %.200s.",
   1217      0     stevel 					    strport, ntop, strerror(errno));
   1218      0     stevel 				(void) close(listen_sock);
   1219      0     stevel 				continue;
   1220      0     stevel 			}
   1221      0     stevel 			listen_socks[num_listen_socks] = listen_sock;
   1222      0     stevel 			num_listen_socks++;
   1223      0     stevel 
   1224      0     stevel 			/* Start listening on the port. */
   1225      0     stevel 			log("Server listening on %s port %s.", ntop, strport);
   1226      0     stevel 			if (listen(listen_sock, 5) < 0)
   1227      0     stevel 				fatal("listen: %.100s", strerror(errno));
   1228      0     stevel 
   1229      0     stevel 		}
   1230      0     stevel 		freeaddrinfo(options.listen_addrs);
   1231      0     stevel 
   1232      0     stevel 		if (!num_listen_socks)
   1233      0     stevel 			fatal("Cannot bind any address.");
   1234      0     stevel 
   1235      0     stevel 		if (options.protocol & SSH_PROTO_1)
   1236      0     stevel 			generate_ephemeral_server_key();
   1237      0     stevel 
   1238      0     stevel 		/*
   1239      0     stevel 		 * Arrange to restart on SIGHUP.  The handler needs
   1240      0     stevel 		 * listen_sock.
   1241      0     stevel 		 */
   1242      0     stevel 		(void) signal(SIGHUP, sighup_handler);
   1243      0     stevel 
   1244      0     stevel 		(void) signal(SIGTERM, sigterm_handler);
   1245      0     stevel 		(void) signal(SIGQUIT, sigterm_handler);
   1246      0     stevel 
   1247      0     stevel 		/* Arrange SIGCHLD to be caught. */
   1248      0     stevel 		(void) signal(SIGCHLD, main_sigchld_handler);
   1249      0     stevel 
   1250      0     stevel 		/* Write out the pid file after the sigterm handler is setup */
   1251      0     stevel 		if (!debug_flag) {
   1252      0     stevel 			/*
   1253      0     stevel 			 * Record our pid in /var/run/sshd.pid to make it
   1254      0     stevel 			 * easier to kill the correct sshd.  We don't want to
   1255      0     stevel 			 * do this before the bind above because the bind will
   1256      0     stevel 			 * fail if there already is a daemon, and this will
   1257      0     stevel 			 * overwrite any old pid in the file.
   1258      0     stevel 			 */
   1259      0     stevel 			f = fopen(options.pid_file, "wb");
   1260      0     stevel 			if (f) {
   1261      0     stevel 				(void) fprintf(f, "%ld\n", (long) getpid());
   1262      0     stevel 				(void) fclose(f);
   1263      0     stevel 			}
   1264      0     stevel 		}
   1265      0     stevel 
   1266      0     stevel 		/* setup fd set for listen */
   1267      0     stevel 		fdset = NULL;
   1268      0     stevel 		maxfd = 0;
   1269      0     stevel 		for (i = 0; i < num_listen_socks; i++)
   1270      0     stevel 			if (listen_socks[i] > maxfd)
   1271      0     stevel 				maxfd = listen_socks[i];
   1272      0     stevel 		/* pipes connected to unauthenticated childs */
   1273      0     stevel 		startup_pipes = xmalloc(options.max_startups * sizeof(int));
   1274      0     stevel 		for (i = 0; i < options.max_startups; i++)
   1275      0     stevel 			startup_pipes[i] = -1;
   1276      0     stevel 
   1277      0     stevel 		/*
   1278      0     stevel 		 * Stay listening for connections until the system crashes or
   1279      0     stevel 		 * the daemon is killed with a signal.
   1280      0     stevel 		 */
   1281      0     stevel 		for (;;) {
   1282      0     stevel 			if (received_sighup)
   1283      0     stevel 				sighup_restart();
   1284      0     stevel 			if (fdset != NULL)
   1285      0     stevel 				xfree(fdset);
   1286      0     stevel 			fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
   1287      0     stevel 			fdset = (fd_set *)xmalloc(fdsetsz);
   1288      0     stevel 			(void) memset(fdset, 0, fdsetsz);
   1289      0     stevel 
   1290      0     stevel 			for (i = 0; i < num_listen_socks; i++)
   1291      0     stevel 				FD_SET(listen_socks[i], fdset);
   1292      0     stevel 			for (i = 0; i < options.max_startups; i++)
   1293      0     stevel 				if (startup_pipes[i] != -1)
   1294      0     stevel 					FD_SET(startup_pipes[i], fdset);
   1295      0     stevel 
   1296      0     stevel 			/* Wait in select until there is a connection. */
   1297      0     stevel 			ret = select(maxfd+1, fdset, NULL, NULL, NULL);
   1298      0     stevel 			if (ret < 0 && errno != EINTR)
   1299      0     stevel 				error("select: %.100s", strerror(errno));
   1300      0     stevel 			if (received_sigterm) {
   1301      0     stevel 				log("Received signal %d; terminating.",
   1302      0     stevel 				    (int) received_sigterm);
   1303      0     stevel 				close_listen_socks();
   1304      0     stevel 				(void) unlink(options.pid_file);
   1305      0     stevel 				exit(255);
   1306      0     stevel 			}
   1307      0     stevel 			if (key_used && key_do_regen) {
   1308      0     stevel 				generate_ephemeral_server_key();
   1309      0     stevel 				key_used = 0;
   1310      0     stevel 				key_do_regen = 0;
   1311      0     stevel 			}
   1312      0     stevel 			if (ret < 0)
   1313      0     stevel 				continue;
   1314      0     stevel 
   1315      0     stevel 			for (i = 0; i < options.max_startups; i++)
   1316      0     stevel 				if (startup_pipes[i] != -1 &&
   1317      0     stevel 				    FD_ISSET(startup_pipes[i], fdset)) {
   1318      0     stevel 					/*
   1319      0     stevel 					 * the read end of the pipe is ready
   1320      0     stevel 					 * if the child has closed the pipe
   1321      0     stevel 					 * after successful authentication
   1322      0     stevel 					 * or if the child has died
   1323      0     stevel 					 */
   1324      0     stevel 					(void) close(startup_pipes[i]);
   1325      0     stevel 					startup_pipes[i] = -1;
   1326      0     stevel 					startups--;
   1327      0     stevel 				}
   1328      0     stevel 			for (i = 0; i < num_listen_socks; i++) {
   1329      0     stevel 				if (!FD_ISSET(listen_socks[i], fdset))
   1330      0     stevel 					continue;
   1331      0     stevel 				fromlen = sizeof(from);
   1332      0     stevel 				newsock = accept(listen_socks[i], (struct sockaddr *)&from,
   1333      0     stevel 				    &fromlen);
   1334      0     stevel 				if (newsock < 0) {
   1335      0     stevel 					if (errno != EINTR && errno != EWOULDBLOCK)
   1336      0     stevel 						error("accept: %.100s", strerror(errno));
   1337      0     stevel 					continue;
   1338      0     stevel 				}
   1339      0     stevel 				if (fcntl(newsock, F_SETFL, 0) < 0) {
   1340      0     stevel 					error("newsock del O_NONBLOCK: %s", strerror(errno));
   1341      0     stevel 					(void) close(newsock);
   1342      0     stevel 					continue;
   1343      0     stevel 				}
   1344      0     stevel 				if (drop_connection(startups) == 1) {
   1345      0     stevel 					debug("drop connection #%d", startups);
   1346      0     stevel 					(void) close(newsock);
   1347      0     stevel 					continue;
   1348      0     stevel 				}
   1349      0     stevel 				if (pipe(startup_p) == -1) {
   1350      0     stevel 					(void) close(newsock);
   1351      0     stevel 					continue;
   1352      0     stevel 				}
   1353      0     stevel 
   1354      0     stevel 				for (j = 0; j < options.max_startups; j++)
   1355      0     stevel 					if (startup_pipes[j] == -1) {
   1356      0     stevel 						startup_pipes[j] = startup_p[0];
   1357      0     stevel 						if (maxfd < startup_p[0])
   1358      0     stevel 							maxfd = startup_p[0];
   1359      0     stevel 						startups++;
   1360      0     stevel 						break;
   1361      0     stevel 					}
   1362      0     stevel 
   1363      0     stevel 				/*
   1364      0     stevel 				 * Got connection.  Fork a child to handle it, unless
   1365      0     stevel 				 * we are in debugging mode.
   1366      0     stevel 				 */
   1367      0     stevel 				if (debug_flag) {
   1368      0     stevel 					/*
   1369      0     stevel 					 * In debugging mode.  Close the listening
   1370      0     stevel 					 * socket, and start processing the
   1371      0     stevel 					 * connection without forking.
   1372      0     stevel 					 */
   1373      0     stevel 					debug("Server will not fork when running in debugging mode.");
   1374      0     stevel 					close_listen_socks();
   1375      0     stevel 					sock_in = newsock;
   1376      0     stevel 					sock_out = newsock;
   1377      0     stevel 					startup_pipe = -1;
   1378      0     stevel 					pid = getpid();
   1379      0     stevel 					break;
   1380      0     stevel 				} else {
   1381      0     stevel 					/*
   1382      0     stevel 					 * Normal production daemon.  Fork, and have
   1383      0     stevel 					 * the child process the connection. The
   1384      0     stevel 					 * parent continues listening.
   1385      0     stevel 					 */
   1386      0     stevel #ifdef HAVE_SOLARIS_CONTRACTS
   1387      0     stevel 					/*
   1388      0     stevel 					 * Setup Solaris contract template so
   1389      0     stevel 					 * the child process is in a different
   1390      0     stevel 					 * process contract than the parent;
   1391      0     stevel 					 * prevents established connections from
   1392      0     stevel 					 * being killed when the sshd master
   1393      0     stevel 					 * listener service is stopped.
   1394      0     stevel 					 */
   1395      0     stevel 					contracts_pre_fork();
   1396      0     stevel #endif /* HAVE_SOLARIS_CONTRACTS */
   1397      0     stevel 					if ((pid = fork()) == 0) {
   1398      0     stevel 						/*
   1399      0     stevel 						 * Child.  Close the listening and max_startup
   1400      0     stevel 						 * sockets.  Start using the accepted socket.
   1401      0     stevel 						 * Reinitialize logging (since our pid has
   1402      0     stevel 						 * changed).  We break out of the loop to handle
   1403      0     stevel 						 * the connection.
   1404      0     stevel 						 */
   1405      0     stevel #ifdef HAVE_SOLARIS_CONTRACTS
   1406      0     stevel 						contracts_post_fork_child();
   1407      0     stevel #endif /* HAVE_SOLARIS_CONTRACTS */
   1408   5562   jp161948 						xfree(fdset);
   1409      0     stevel 						startup_pipe = startup_p[1];
   1410      0     stevel 						close_startup_pipes();
   1411      0     stevel 						close_listen_socks();
   1412      0     stevel 						sock_in = newsock;
   1413      0     stevel 						sock_out = newsock;
   1414      0     stevel 						log_init(__progname, options.log_level, options.log_facility, log_stderr);
   1415      0     stevel 						break;
   1416      0     stevel 					}
   1417      0     stevel 
   1418      0     stevel #ifdef HAVE_SOLARIS_CONTRACTS
   1419      0     stevel 					contracts_post_fork_parent((pid > 0));
   1420      0     stevel #endif /* HAVE_SOLARIS_CONTRACTS */
   1421      0     stevel 				}
   1422      0     stevel 
   1423      0     stevel 				/* Parent.  Stay in the loop. */
   1424      0     stevel 				if (pid < 0)
   1425      0     stevel 					error("fork: %.100s", strerror(errno));
   1426      0     stevel 				else
   1427      0     stevel 					debug("Forked child %ld.", (long)pid);
   1428      0     stevel 
   1429      0     stevel 				(void) close(startup_p[1]);
   1430      0     stevel 
   1431      0     stevel 				/* Mark that the key has been used (it was "given" to the child). */
   1432      0     stevel 				if ((options.protocol & SSH_PROTO_1) &&
   1433      0     stevel 				    key_used == 0) {
   1434      0     stevel 					/* Schedule server key regeneration alarm. */
   1435      0     stevel 					(void) signal(SIGALRM, key_regeneration_alarm);
   1436      0     stevel 					(void) alarm(options.key_regeneration_time);
   1437      0     stevel 					key_used = 1;
   1438      0     stevel 				}
   1439      0     stevel 
   1440      0     stevel 				arc4random_stir();
   1441      0     stevel 
   1442   7574        Jan 				/*
   1443   7574        Jan 				 * Close the accepted socket since the child
   1444   7574        Jan 				 * will now take care of the new connection.
   1445   7574        Jan 				 */
   1446      0     stevel 				(void) close(newsock);
   1447      0     stevel 			}
   1448      0     stevel 			/* child process check (or debug mode) */
   1449      0     stevel 			if (num_listen_socks < 0)
   1450      0     stevel 				break;
   1451      0     stevel 		}
   1452      0     stevel 	}
   1453      0     stevel 
   1454   7574        Jan 	/*
   1455   7574        Jan 	 * This is the child processing a new connection, the SSH master process
   1456   7574        Jan 	 * stays in the ( ; ; ) loop above.
   1457   7574        Jan 	 */
   1458      0     stevel #ifdef HAVE_BSM
   1459      0     stevel 	audit_sshd_settid(newsock);
   1460      0     stevel #endif
   1461      0     stevel 	/*
   1462      0     stevel 	 * Create a new session and process group since the 4.4BSD
   1463      0     stevel 	 * setlogin() affects the entire process group.  We don't
   1464      0     stevel 	 * want the child to be able to affect the parent.
   1465      0     stevel 	 */
   1466      0     stevel #if 0
   1467      0     stevel 	/* XXX: this breaks Solaris */
   1468      0     stevel 	if (!debug_flag && !inetd_flag && setsid() < 0)
   1469      0     stevel 		error("setsid: %.100s", strerror(errno));
   1470      0     stevel #endif
   1471      0     stevel 
   1472      0     stevel 	/*
   1473      0     stevel 	 * Disable the key regeneration alarm.  We will not regenerate the
   1474      0     stevel 	 * key since we are no longer in a position to give it to anyone. We
   1475      0     stevel 	 * will not restart on SIGHUP since it no longer makes sense.
   1476      0     stevel 	 */
   1477      0     stevel 	(void) alarm(0);
   1478      0     stevel 	(void) signal(SIGALRM, SIG_DFL);
   1479      0     stevel 	(void) signal(SIGHUP, SIG_DFL);
   1480      0     stevel 	(void) signal(SIGTERM, SIG_DFL);
   1481      0     stevel 	(void) signal(SIGQUIT, SIG_DFL);
   1482      0     stevel 	(void) signal(SIGCHLD, SIG_DFL);
   1483      0     stevel 	(void) signal(SIGINT, SIG_DFL);
   1484      0     stevel 
   1485      0     stevel 	/* Set keepalives if requested. */
   1486      0     stevel 	if (options.keepalives &&
   1487      0     stevel 	    setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on,
   1488      0     stevel 	    sizeof(on)) < 0)
   1489      0     stevel 		debug2("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
   1490      0     stevel 
   1491      0     stevel 	/*
   1492      0     stevel 	 * Register our connection.  This turns encryption off because we do
   1493      0     stevel 	 * not have a key.
   1494      0     stevel 	 */
   1495      0     stevel 	packet_set_connection(sock_in, sock_out);
   1496      0     stevel 
   1497      0     stevel 	remote_port = get_remote_port();
   1498      0     stevel 	remote_ip = get_remote_ipaddr();
   1499      0     stevel 
   1500      0     stevel #ifdef LIBWRAP
   1501      0     stevel 	/* Check whether logins are denied from this host. */
   1502      0     stevel 	{
   1503      0     stevel 		struct request_info req;
   1504      0     stevel 
   1505      0     stevel 		(void) request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
   1506      0     stevel 		fromhost(&req);
   1507      0     stevel 
   1508      0     stevel 		if (!hosts_access(&req)) {
   1509      0     stevel 			debug("Connection refused by tcp wrapper");
   1510      0     stevel 			refuse(&req);
   1511      0     stevel 			/* NOTREACHED */
   1512      0     stevel 			fatal("libwrap refuse returns");
   1513      0     stevel 		}
   1514      0     stevel 	}
   1515      0     stevel #endif /* LIBWRAP */
   1516      0     stevel 
   1517      0     stevel 	/* Log the connection. */
   1518      0     stevel 	verbose("Connection from %.500s port %d", remote_ip, remote_port);
   1519      0     stevel 
   1520      0     stevel 	sshd_exchange_identification(sock_in, sock_out);
   1521      0     stevel 	/*
   1522      0     stevel 	 * Check that the connection comes from a privileged port.
   1523      0     stevel 	 * Rhosts-Authentication only makes sense from privileged
   1524      0     stevel 	 * programs.  Of course, if the intruder has root access on his local
   1525      0     stevel 	 * machine, he can connect from any port.  So do not use these
   1526      0     stevel 	 * authentication methods from machines that you do not trust.
   1527      0     stevel 	 */
   1528      0     stevel 	if (options.rhosts_authentication &&
   1529      0     stevel 	    (remote_port >= IPPORT_RESERVED ||
   1530      0     stevel 	    remote_port < IPPORT_RESERVED / 2)) {
   1531      0     stevel 		debug("Rhosts Authentication disabled, "
   1532      0     stevel 		    "originating port %d not trusted.", remote_port);
   1533      0     stevel 		options.rhosts_authentication = 0;
   1534      0     stevel 	}
   1535      0     stevel #if defined(KRB4) && !defined(KRB5)
   1536      0     stevel 	if (!packet_connection_is_ipv4() &&
   1537      0     stevel 	    options.kerberos_authentication) {
   1538      0     stevel 		debug("Kerberos Authentication disabled, only available for IPv4.");
   1539      0     stevel 		options.kerberos_authentication = 0;
   1540      0     stevel 	}
   1541      0     stevel #endif /* KRB4 && !KRB5 */
   1542      0     stevel #ifdef AFS
   1543      0     stevel 	/* If machine has AFS, set process authentication group. */
   1544      0     stevel 	if (k_hasafs()) {
   1545      0     stevel 		k_setpag();
   1546      0     stevel 		k_unlog();
   1547      0     stevel 	}
   1548      0     stevel #endif /* AFS */
   1549      0     stevel 
   1550      0     stevel 	packet_set_nonblocking();
   1551      0     stevel 
   1552   7574        Jan 	/*
   1553   7574        Jan 	 * Start the monitor. That way both processes will have their own
   1554   7574        Jan 	 * PKCS#11 sessions. See the PKCS#11 standard for more information on
   1555   7574        Jan 	 * fork safety and packet.c for information about forking with the
   1556   7574        Jan 	 * engine.
   1557  10515        Jan 	 *
   1558  10515        Jan 	 * Note that the monitor stays in the function while the child is the
   1559  10515        Jan 	 * only one that returns.
   1560   7574        Jan 	 */
   1561   7574        Jan 	altprivsep_start_and_do_monitor(options.use_openssl_engine,
   1562   7574        Jan 	    inetd_flag, newsock, startup_pipe);
   1563  10515        Jan 
   1564  10515        Jan 	/*
   1565  10515        Jan 	 * We don't want to listen forever unless the other side successfully
   1566  10515        Jan 	 * authenticates itself. So we set up an alarm which is cleared after
   1567  10515        Jan 	 * successful authentication. A limit of zero indicates no limit. Note
   1568  10515        Jan 	 * that we don't set the alarm in debugging mode; it is just annoying to
   1569  10515        Jan 	 * have the server exit just when you are about to discover the bug.
   1570  10515        Jan 	 */
   1571  10515        Jan 	(void) signal(SIGALRM, grace_alarm_handler);
   1572  10515        Jan 	if (!debug_flag)
   1573  10515        Jan 		(void) alarm(options.login_grace_time);
   1574   7574        Jan 
   1575   7574        Jan 	/*
   1576   7574        Jan 	 * The child is about to start the first key exchange while the monitor
   1577   7574        Jan 	 * stays in altprivsep_start_and_do_monitor() function.
   1578   7574        Jan 	 */
   1579   7574        Jan 	(void) pkcs11_engine_load(options.use_openssl_engine);
   1580   7574        Jan 
   1581      0     stevel 	/* perform the key exchange */
   1582      0     stevel 	/* authenticate user and start session */
   1583      0     stevel 	if (compat20) {
   1584      0     stevel 		do_ssh2_kex();
   1585      0     stevel 		authctxt = do_authentication2();
   1586      0     stevel 	} else {
   1587      0     stevel 		do_ssh1_kex();
   1588      0     stevel 		authctxt = do_authentication();
   1589      0     stevel 	}
   1590      0     stevel 
   1591      0     stevel 	/* Authentication complete */
   1592      0     stevel 	(void) alarm(0);
   1593   7574        Jan 	/* we no longer need an alarm handler */
   1594   7574        Jan 	(void) signal(SIGALRM, SIG_DFL);
   1595      0     stevel 
   1596      0     stevel 	if (startup_pipe != -1) {
   1597      0     stevel 		(void) close(startup_pipe);
   1598      0     stevel 		startup_pipe = -1;
   1599      0     stevel 	}
   1600      0     stevel 
   1601   7574        Jan 	/* ALTPRIVSEP Child */
   1602      0     stevel 
   1603   7574        Jan 	/*
   1604   7574        Jan 	 * Drop privileges, access to privileged resources.
   1605   7574        Jan 	 *
   1606   7574        Jan 	 * Destroy private host keys, if any.
   1607   7574        Jan 	 *
   1608   7574        Jan 	 * No need to release any GSS credentials -- sshd only acquires
   1609   7574        Jan 	 * creds to determine what mechs it can negotiate then releases
   1610   7574        Jan 	 * them right away and uses GSS_C_NO_CREDENTIAL to accept
   1611   7574        Jan 	 * contexts.
   1612   7574        Jan 	 */
   1613   7574        Jan 	debug2("Unprivileged server process dropping privileges");
   1614   9139        Jan 	permanently_set_uid(authctxt->pw, options.chroot_directory);
   1615   7574        Jan 	destroy_sensitive_data();
   1616   9139        Jan 
   1617   9139        Jan 	/* Just another safety check. */
   1618   9139        Jan 	if (getuid() != authctxt->pw->pw_uid ||
   1619   9139        Jan 	    geteuid() != authctxt->pw->pw_uid) {
   1620   9139        Jan 		fatal("Failed to set uids to %u.", (u_int)authctxt->pw->pw_uid);
   1621   9139        Jan 	}
   1622   9139        Jan 
   1623   7574        Jan 	ssh_gssapi_server_mechs(NULL); /* release cached mechs list */
   1624   7574        Jan 	packet_set_server();
   1625      0     stevel 
   1626   7574        Jan 	/* now send the authentication context to the monitor */
   1627   7574        Jan 	altprivsep_send_auth_context(authctxt);
   1628      0     stevel 
   1629   7574        Jan 	mpipe = altprivsep_get_pipe_fd();
   1630   7574        Jan 	if (fcntl(mpipe, F_SETFL, O_NONBLOCK) < 0)
   1631   7574        Jan 		error("fcntl O_NONBLOCK: %.100s", strerror(errno));
   1632      0     stevel 
   1633      0     stevel #ifdef HAVE_BSM
   1634   7574        Jan 	fatal_remove_cleanup(
   1635   7574        Jan 		(void (*)(void *))audit_failed_login_cleanup,
   1636   7574        Jan 		(void *)authctxt);
   1637      0     stevel #endif /* HAVE_BSM */
   1638      0     stevel 
   1639   7574        Jan 	if (compat20) {
   1640   7574        Jan 		debug3("setting handler to forward re-key packets to the monitor");
   1641   7574        Jan 		dispatch_range(SSH2_MSG_KEXINIT, SSH2_MSG_TRANSPORT_MAX,
   1642   7574        Jan 			&altprivsep_rekey);
   1643   7574        Jan 	}
   1644      0     stevel 
   1645   7574        Jan 	/* Logged-in session. */
   1646   7574        Jan 	do_authenticated(authctxt);
   1647      0     stevel 
   1648   7574        Jan 	/* The connection has been terminated. */
   1649   7574        Jan 	verbose("Closing connection to %.100s", remote_ip);
   1650      0     stevel 
   1651   7574        Jan 	packet_close();
   1652      0     stevel 
   1653      0     stevel #ifdef USE_PAM
   1654   7574        Jan 	finish_pam(authctxt);
   1655      0     stevel #endif /* USE_PAM */
   1656      0     stevel 
   1657   7574        Jan 	return (0);
   1658      0     stevel }
   1659      0     stevel 
   1660      0     stevel /*
   1661      0     stevel  * Decrypt session_key_int using our private server key and private host key
   1662      0     stevel  * (key with larger modulus first).
   1663      0     stevel  */
   1664      0     stevel int
   1665      0     stevel ssh1_session_key(BIGNUM *session_key_int)
   1666      0     stevel {
   1667      0     stevel 	int rsafail = 0;
   1668      0     stevel 
   1669      0     stevel 	if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
   1670      0     stevel 		/* Server key has bigger modulus. */
   1671      0     stevel 		if (BN_num_bits(sensitive_data.server_key->rsa->n) <
   1672      0     stevel 		    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
   1673      0     stevel 			fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
   1674      0     stevel 			    get_remote_ipaddr(),
   1675      0     stevel 			    BN_num_bits(sensitive_data.server_key->rsa->n),
   1676      0     stevel 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
   1677      0     stevel 			    SSH_KEY_BITS_RESERVED);
   1678      0     stevel 		}
   1679      0     stevel 		if (rsa_private_decrypt(session_key_int, session_key_int,
   1680      0     stevel 		    sensitive_data.server_key->rsa) <= 0)
   1681      0     stevel 			rsafail++;
   1682      0     stevel 		if (rsa_private_decrypt(session_key_int, session_key_int,
   1683      0     stevel 		    sensitive_data.ssh1_host_key->rsa) <= 0)
   1684      0     stevel 			rsafail++;
   1685      0     stevel 	} else {
   1686      0     stevel 		/* Host key has bigger modulus (or they are equal). */
   1687      0     stevel 		if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
   1688      0     stevel 		    BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
   1689      0     stevel 			fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
   1690      0     stevel 			    get_remote_ipaddr(),
   1691      0     stevel 			    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
   1692      0     stevel 			    BN_num_bits(sensitive_data.server_key->rsa->n),
   1693      0     stevel 			    SSH_KEY_BITS_RESERVED);
   1694      0     stevel 		}
   1695      0     stevel 		if (rsa_private_decrypt(session_key_int, session_key_int,
   1696      0     stevel 		    sensitive_data.ssh1_host_key->rsa) < 0)
   1697      0     stevel 			rsafail++;
   1698      0     stevel 		if (rsa_private_decrypt(session_key_int, session_key_int,
   1699      0     stevel 		    sensitive_data.server_key->rsa) < 0)
   1700      0     stevel 			rsafail++;
   1701      0     stevel 	}
   1702      0     stevel 	return (rsafail);
   1703      0     stevel }
   1704      0     stevel /*
   1705      0     stevel  * SSH1 key exchange
   1706      0     stevel  */
   1707      0     stevel static void
   1708      0     stevel do_ssh1_kex(void)
   1709      0     stevel {
   1710      0     stevel 	int i, len;
   1711      0     stevel 	int rsafail = 0;
   1712      0     stevel 	BIGNUM *session_key_int;
   1713      0     stevel 	u_char session_key[SSH_SESSION_KEY_LENGTH];
   1714      0     stevel 	u_char cookie[8];
   1715      0     stevel 	u_int cipher_type, auth_mask, protocol_flags;
   1716      0     stevel 	u_int32_t rnd = 0;
   1717      0     stevel 
   1718      0     stevel 	/*
   1719      0     stevel 	 * Generate check bytes that the client must send back in the user
   1720      0     stevel 	 * packet in order for it to be accepted; this is used to defy ip
   1721      0     stevel 	 * spoofing attacks.  Note that this only works against somebody
   1722      0     stevel 	 * doing IP spoofing from a remote machine; any machine on the local
   1723      0     stevel 	 * network can still see outgoing packets and catch the random
   1724      0     stevel 	 * cookie.  This only affects rhosts authentication, and this is one
   1725      0     stevel 	 * of the reasons why it is inherently insecure.
   1726      0     stevel 	 */
   1727      0     stevel 	for (i = 0; i < 8; i++) {
   1728      0     stevel 		if (i % 4 == 0)
   1729      0     stevel 			rnd = arc4random();
   1730      0     stevel 		cookie[i] = rnd & 0xff;
   1731      0     stevel 		rnd >>= 8;
   1732      0     stevel 	}
   1733      0     stevel 
   1734      0     stevel 	/*
   1735      0     stevel 	 * Send our public key.  We include in the packet 64 bits of random
   1736      0     stevel 	 * data that must be matched in the reply in order to prevent IP
   1737      0     stevel 	 * spoofing.
   1738      0     stevel 	 */
   1739      0     stevel 	packet_start(SSH_SMSG_PUBLIC_KEY);
   1740      0     stevel 	for (i = 0; i < 8; i++)
   1741      0     stevel 		packet_put_char(cookie[i]);
   1742      0     stevel 
   1743      0     stevel 	/* Store our public server RSA key. */
   1744      0     stevel 	packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
   1745      0     stevel 	packet_put_bignum(sensitive_data.server_key->rsa->e);
   1746      0     stevel 	packet_put_bignum(sensitive_data.server_key->rsa->n);
   1747      0     stevel 
   1748      0     stevel 	/* Store our public host RSA key. */
   1749      0     stevel 	packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
   1750      0     stevel 	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
   1751      0     stevel 	packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
   1752      0     stevel 
   1753      0     stevel 	/* Put protocol flags. */
   1754      0     stevel 	packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
   1755      0     stevel 
   1756      0     stevel 	/* Declare which ciphers we support. */
   1757      0     stevel 	packet_put_int(cipher_mask_ssh1(0));
   1758      0     stevel 
   1759      0     stevel 	/* Declare supported authentication types. */
   1760      0     stevel 	auth_mask = 0;
   1761      0     stevel 	if (options.rhosts_authentication)
   1762      0     stevel 		auth_mask |= 1 << SSH_AUTH_RHOSTS;
   1763      0     stevel 	if (options.rhosts_rsa_authentication)
   1764      0     stevel 		auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
   1765      0     stevel 	if (options.rsa_authentication)
   1766      0     stevel 		auth_mask |= 1 << SSH_AUTH_RSA;
   1767      0     stevel #if defined(KRB4) || defined(KRB5)
   1768      0     stevel 	if (options.kerberos_authentication)
   1769      0     stevel 		auth_mask |= 1 << SSH_AUTH_KERBEROS;
   1770      0     stevel #endif
   1771      0     stevel #if defined(AFS) || defined(KRB5)
   1772      0     stevel 	if (options.kerberos_tgt_passing)
   1773      0     stevel 		auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
   1774      0     stevel #endif
   1775      0     stevel #ifdef AFS
   1776      0     stevel 	if (options.afs_token_passing)
   1777      0     stevel 		auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
   1778      0     stevel #endif
   1779      0     stevel 	if (options.challenge_response_authentication == 1)
   1780      0     stevel 		auth_mask |= 1 << SSH_AUTH_TIS;
   1781      0     stevel 	if (options.password_authentication)
   1782      0     stevel 		auth_mask |= 1 << SSH_AUTH_PASSWORD;
   1783      0     stevel 	packet_put_int(auth_mask);
   1784      0     stevel 
   1785      0     stevel 	/* Send the packet and wait for it to be sent. */
   1786      0     stevel 	packet_send();
   1787      0     stevel 	packet_write_wait();
   1788      0     stevel 
   1789      0     stevel 	debug("Sent %d bit server key and %d bit host key.",
   1790      0     stevel 	    BN_num_bits(sensitive_data.server_key->rsa->n),
   1791      0     stevel 	    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
   1792      0     stevel 
   1793      0     stevel 	/* Read clients reply (cipher type and session key). */
   1794      0     stevel 	packet_read_expect(SSH_CMSG_SESSION_KEY);
   1795      0     stevel 
   1796      0     stevel 	/* Get cipher type and check whether we accept this. */
   1797      0     stevel 	cipher_type = packet_get_char();
   1798      0     stevel 
   1799      0     stevel 	if (!(cipher_mask_ssh1(0) & (1 << cipher_type))) {
   1800      0     stevel 		packet_disconnect("Warning: client selects unsupported cipher.");
   1801      0     stevel 	}
   1802      0     stevel 
   1803      0     stevel 	/* Get check bytes from the packet.  These must match those we
   1804      0     stevel 	   sent earlier with the public key packet. */
   1805      0     stevel 	for (i = 0; i < 8; i++) {
   1806      0     stevel 		if (cookie[i] != packet_get_char()) {
   1807      0     stevel 			packet_disconnect("IP Spoofing check bytes do not match.");
   1808      0     stevel 		}
   1809      0     stevel 	}
   1810      0     stevel 
   1811      0     stevel 	debug("Encryption type: %.200s", cipher_name(cipher_type));
   1812      0     stevel 
   1813      0     stevel 	/* Get the encrypted integer. */
   1814      0     stevel 	if ((session_key_int = BN_new()) == NULL)
   1815      0     stevel 		fatal("do_ssh1_kex: BN_new failed");
   1816      0     stevel 	packet_get_bignum(session_key_int);
   1817      0     stevel 
   1818      0     stevel 	protocol_flags = packet_get_int();
   1819      0     stevel 	packet_set_protocol_flags(protocol_flags);
   1820      0     stevel 	packet_check_eom();
   1821      0     stevel 
   1822      0     stevel 	/* Decrypt session_key_int using host/server keys */
   1823   5562   jp161948 	rsafail = ssh1_session_key(session_key_int);
   1824      0     stevel 
   1825      0     stevel 	/*
   1826      0     stevel 	 * Extract session key from the decrypted integer.  The key is in the
   1827      0     stevel 	 * least significant 256 bits of the integer; the first byte of the
   1828      0     stevel 	 * key is in the highest bits.
   1829      0     stevel 	 */
   1830      0     stevel 	if (!rsafail) {
   1831      0     stevel 		(void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
   1832      0     stevel 		len = BN_num_bytes(session_key_int);
   1833      0     stevel 		if (len < 0 || len > sizeof(session_key)) {
   1834      0     stevel 			error("do_connection: bad session key len from %s: "
   1835      0     stevel 			    "session_key_int %d > sizeof(session_key) %lu",
   1836      0     stevel 			    get_remote_ipaddr(), len, (u_long)sizeof(session_key));
   1837      0     stevel 			rsafail++;
   1838      0     stevel 		} else {
   1839      0     stevel 			(void) memset(session_key, 0, sizeof(session_key));
   1840      0     stevel 			(void) BN_bn2bin(session_key_int,
   1841      0     stevel 			    session_key + sizeof(session_key) - len);
   1842      0     stevel 
   1843      0     stevel 			compute_session_id(session_id, cookie,
   1844      0     stevel 			    sensitive_data.ssh1_host_key->rsa->n,
   1845      0     stevel 			    sensitive_data.server_key->rsa->n);
   1846      0     stevel 			/*
   1847      0     stevel 			 * Xor the first 16 bytes of the session key with the
   1848      0     stevel 			 * session id.
   1849      0     stevel 			 */
   1850      0     stevel 			for (i = 0; i < 16; i++)
   1851      0     stevel 				session_key[i] ^= session_id[i];
   1852      0     stevel 		}
   1853      0     stevel 	}
   1854      0     stevel 	if (rsafail) {
   1855      0     stevel 		int bytes = BN_num_bytes(session_key_int);
   1856      0     stevel 		u_char *buf = xmalloc(bytes);
   1857      0     stevel 		MD5_CTX md;
   1858      0     stevel 
   1859      0     stevel 		log("do_connection: generating a fake encryption key");
   1860      0     stevel 		(void) BN_bn2bin(session_key_int, buf);
   1861      0     stevel 		MD5_Init(&md);
   1862      0     stevel 		MD5_Update(&md, buf, bytes);
   1863      0     stevel 		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
   1864      0     stevel 		MD5_Final(session_key, &md);
   1865      0     stevel 		MD5_Init(&md);
   1866      0     stevel 		MD5_Update(&md, session_key, 16);
   1867      0     stevel 		MD5_Update(&md, buf, bytes);
   1868      0     stevel 		MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
   1869      0     stevel 		MD5_Final(session_key + 16, &md);
   1870      0     stevel 		(void) memset(buf, 0, bytes);
   1871      0     stevel 		xfree(buf);
   1872      0     stevel 		for (i = 0; i < 16; i++)
   1873      0     stevel 			session_id[i] = session_key[i] ^ session_key[i + 16];
   1874      0     stevel 	}
   1875      0     stevel 	/* Destroy the private and public keys. No longer. */
   1876      0     stevel 	destroy_sensitive_data();
   1877      0     stevel 
   1878      0     stevel 	/* Destroy the decrypted integer.  It is no longer needed. */
   1879      0     stevel 	BN_clear_free(session_key_int);
   1880      0     stevel 
   1881      0     stevel 	/* Set the session key.  From this on all communications will be encrypted. */
   1882      0     stevel 	packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
   1883      0     stevel 
   1884      0     stevel 	/* Destroy our copy of the session key.  It is no longer needed. */
   1885      0     stevel 	(void) memset(session_key, 0, sizeof(session_key));
   1886      0     stevel 
   1887      0     stevel 	debug("Received session key; encryption turned on.");
   1888      0     stevel 
   1889      0     stevel 	/* Send an acknowledgment packet.  Note that this packet is sent encrypted. */
   1890      0     stevel 	packet_start(SSH_SMSG_SUCCESS);
   1891      0     stevel 	packet_send();
   1892      0     stevel 	packet_write_wait();
   1893      0     stevel }
   1894      0     stevel 
   1895      0     stevel /*
   1896   7574        Jan  * Prepare for SSH2 key exchange.
   1897      0     stevel  */
   1898   7574        Jan Kex *
   1899   7574        Jan prepare_for_ssh2_kex(void)
   1900      0     stevel {
   1901      0     stevel 	Kex *kex;
   1902      0     stevel 	Kex_hook_func kex_hook = NULL;
   1903      0     stevel 	char **locales;
   1904   8658        Jan 	static char **myproposal;
   1905   8658        Jan 
   1906   8658        Jan 	myproposal = my_srv_proposal;
   1907      0     stevel 
   1908      0     stevel 	if (options.ciphers != NULL) {
   1909      0     stevel 		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
   1910      0     stevel 		myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
   1911      0     stevel 	}
   1912      0     stevel 	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
   1913      0     stevel 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
   1914      0     stevel 	myproposal[PROPOSAL_ENC_ALGS_STOC] =
   1915      0     stevel 	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
   1916      0     stevel 
   1917      0     stevel 	if (options.macs != NULL) {
   1918      0     stevel 		myproposal[PROPOSAL_MAC_ALGS_CTOS] =
   1919      0     stevel 		myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
   1920      0     stevel 	}
   1921      0     stevel 	if (!options.compression) {
   1922      0     stevel 		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
   1923      0     stevel 		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
   1924      0     stevel 	}
   1925      0     stevel 
   1926      0     stevel 	/*
   1927      0     stevel 	 * Prepare kex algs / hostkey algs (excluding GSS, which is
   1928      0     stevel 	 * handled in the kex hook.
   1929      0     stevel 	 *
   1930      0     stevel 	 * XXX This should probably move to the kex hook as well, where
   1931      0     stevel 	 * all non-constant kex offer material belongs.
   1932      0     stevel 	 */
   1933      0     stevel 	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
   1934      0     stevel 
   1935      0     stevel 	/* If we have no host key algs we can't offer KEXDH/KEX_DH_GEX */
   1936      0     stevel 	if (myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] == NULL ||
   1937      0     stevel 	    *myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] == '\0')
   1938      0     stevel 		myproposal[PROPOSAL_KEX_ALGS] = "";
   1939      0     stevel 
   1940      0     stevel 	if ((locales = g11n_getlocales()) != NULL) {
   1941      0     stevel 		/* Solaris 9 SSH expects a list of locales */
   1942      0     stevel 		if (datafellows & SSH_BUG_LOCALES_NOT_LANGTAGS)
   1943      0     stevel 			myproposal[PROPOSAL_LANG_STOC] = xjoin(locales, ',');
   1944      0     stevel 		else
   1945      0     stevel 			myproposal[PROPOSAL_LANG_STOC] =
   1946      0     stevel 				g11n_locales2langs(locales);
   1947      0     stevel 	}
   1948      0     stevel 
   1949   5562   jp161948 	if (locales != NULL)
   1950   5562   jp161948 		g11n_freelist(locales);
   1951   5562   jp161948 
   1952   9845        Jan 	if ((myproposal[PROPOSAL_LANG_STOC] != NULL) &&
   1953      0     stevel 	    (strcmp(myproposal[PROPOSAL_LANG_STOC], "")) != 0)
   1954      0     stevel 		myproposal[PROPOSAL_LANG_CTOS] =
   1955      0     stevel 			xstrdup(myproposal[PROPOSAL_LANG_STOC]);
   1956      0     stevel 
   1957      0     stevel #ifdef GSSAPI
   1958      0     stevel 	if (options.gss_keyex)
   1959      0     stevel 		kex_hook = ssh_gssapi_server_kex_hook;
   1960      0     stevel #endif /* GSSAPI */
   1961      0     stevel 
   1962      0     stevel 	kex = kex_setup(NULL, myproposal, kex_hook);
   1963   5562   jp161948 
   1964   9845        Jan 	/*
   1965   9845        Jan 	 * Note that the my_srv_proposal variable (ie., myproposal) is staticly
   1966   9845        Jan 	 * initialized with "" for the language fields; we must not xfree such
   1967   9845        Jan 	 * strings.
   1968   9845        Jan 	 */
   1969   9845        Jan 	if (myproposal[PROPOSAL_LANG_STOC] != NULL &&
   1970   9845        Jan 	    strcmp(myproposal[PROPOSAL_LANG_STOC], "") != 0)
   1971   5562   jp161948 		xfree(myproposal[PROPOSAL_LANG_STOC]);
   1972   9845        Jan 	if (myproposal[PROPOSAL_LANG_CTOS] != NULL &&
   1973   9845        Jan 	    strcmp(myproposal[PROPOSAL_LANG_STOC], "") != 0)
   1974   5562   jp161948 		xfree(myproposal[PROPOSAL_LANG_CTOS]);
   1975   5562   jp161948 
   1976      0     stevel 	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
   1977      0     stevel 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
   1978      0     stevel #ifdef GSSAPI
   1979      0     stevel 	kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
   1980      0     stevel #endif /* GSSAPI */
   1981      0     stevel 	kex->server = 1;
   1982   7574        Jan 	kex->client_version_string = client_version_string;
   1983   7574        Jan 	kex->server_version_string = server_version_string;
   1984   7574        Jan 	kex->load_host_key = &get_hostkey_by_type;
   1985   7574        Jan 	kex->host_key_index = &get_hostkey_index;
   1986      0     stevel 
   1987      0     stevel 	xxx_kex = kex;
   1988   7574        Jan 	return (kex);
   1989   7574        Jan }
   1990   7574        Jan 
   1991   7574        Jan /*
   1992   7574        Jan  * Do SSH2 key exchange.
   1993   7574        Jan  */
   1994   7574        Jan static void
   1995   7574        Jan do_ssh2_kex(void)
   1996   7574        Jan {
   1997   7574        Jan 	Kex *kex;
   1998   7574        Jan 
   1999   7574        Jan 	kex = prepare_for_ssh2_kex();
   2000   7574        Jan 	kex_start(kex);
   2001      0     stevel 
   2002      0     stevel 	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
   2003      0     stevel 
   2004      0     stevel 	if (kex->name) {
   2005      0     stevel 		xfree(kex->name);
   2006      0     stevel 		kex->name = NULL;
   2007      0     stevel 	}
   2008      0     stevel 	session_id2 = kex->session_id;
   2009      0     stevel 	session_id2_len = kex->session_id_len;
   2010      0     stevel 
   2011      0     stevel #ifdef DEBUG_KEXDH
   2012      0     stevel 	/* send 1st encrypted/maced/compressed message */
   2013      0     stevel 	packet_start(SSH2_MSG_IGNORE);
   2014      0     stevel 	packet_put_cstring("markus");
   2015      0     stevel 	packet_send();
   2016      0     stevel 	packet_write_wait();
   2017      0     stevel #endif
   2018      0     stevel 	debug("KEX done");
   2019      0     stevel }
   2020