[BACK]Return to sshd.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/sshd.c, Revision 1.545

1.545   ! djm         1: /* $OpenBSD: sshd.c,v 1.544 2020/01/23 07:10:22 dtucker Exp $ */
1.86      markus      2: /*
1.65      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
1.126     deraadt     6:  * This program is the ssh daemon.  It listens for connections from clients,
                      7:  * and performs authentication, executes use commands or shell, and forwards
1.65      deraadt     8:  * information to/from the application to the user client over an encrypted
1.126     deraadt     9:  * connection.  This can also handle forwarding of X11, TCP/IP, and
                     10:  * authentication agent connections.
1.98      markus     11:  *
1.126     deraadt    12:  * As far as I am concerned, the code I have written for this software
                     13:  * can be used freely for any purpose.  Any derived versions of this
                     14:  * software must be clearly marked as such, and if the derived work is
                     15:  * incompatible with the protocol description in the RFC file, it must be
                     16:  * called by a name other than "ssh" or "Secure Shell".
                     17:  *
                     18:  * SSH2 implementation:
1.231     provos     19:  * Privilege Separation:
1.126     deraadt    20:  *
1.231     provos     21:  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
                     22:  * Copyright (c) 2002 Niels Provos.  All rights reserved.
1.126     deraadt    23:  *
                     24:  * Redistribution and use in source and binary forms, with or without
                     25:  * modification, are permitted provided that the following conditions
                     26:  * are met:
                     27:  * 1. Redistributions of source code must retain the above copyright
                     28:  *    notice, this list of conditions and the following disclaimer.
                     29:  * 2. Redistributions in binary form must reproduce the above copyright
                     30:  *    notice, this list of conditions and the following disclaimer in the
                     31:  *    documentation and/or other materials provided with the distribution.
                     32:  *
                     33:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     34:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     35:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     36:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     37:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     38:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     39:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     40:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     41:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     42:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.65      deraadt    43:  */
1.1       deraadt    44:
1.343     deraadt    45: #include <sys/types.h>
1.320     stevesk    46: #include <sys/ioctl.h>
1.321     stevesk    47: #include <sys/wait.h>
1.343     deraadt    48: #include <sys/tree.h>
1.323     stevesk    49: #include <sys/stat.h>
1.334     stevesk    50: #include <sys/socket.h>
1.340     stevesk    51: #include <sys/time.h>
1.357     djm        52: #include <sys/queue.h>
1.319     stevesk    53:
1.336     stevesk    54: #include <errno.h>
1.335     stevesk    55: #include <fcntl.h>
1.338     stevesk    56: #include <netdb.h>
1.319     stevesk    57: #include <paths.h>
1.333     stevesk    58: #include <pwd.h>
1.322     stevesk    59: #include <signal.h>
1.342     stevesk    60: #include <stdio.h>
1.341     stevesk    61: #include <stdlib.h>
1.339     stevesk    62: #include <string.h>
1.541     naddy      63: #include <stdarg.h>
1.344     dtucker    64: #include <unistd.h>
1.438     deraadt    65: #include <limits.h>
1.1       deraadt    66:
1.426     markus     67: #ifdef WITH_OPENSSL
1.155     markus     68: #include <openssl/bn.h>
1.426     markus     69: #endif
1.155     markus     70:
1.343     deraadt    71: #include "xmalloc.h"
1.155     markus     72: #include "ssh.h"
                     73: #include "ssh2.h"
1.171     djm        74: #include "sshpty.h"
1.1       deraadt    75: #include "packet.h"
1.155     markus     76: #include "log.h"
1.511     markus     77: #include "sshbuf.h"
1.428     millert    78: #include "misc.h"
1.454     markus     79: #include "match.h"
1.1       deraadt    80: #include "servconf.h"
                     81: #include "uidswap.h"
1.33      markus     82: #include "compat.h"
1.155     markus     83: #include "cipher.h"
1.415     markus     84: #include "digest.h"
1.512     markus     85: #include "sshkey.h"
1.98      markus     86: #include "kex.h"
                     87: #include "myproposal.h"
1.108     markus     88: #include "authfile.h"
1.154     markus     89: #include "pathnames.h"
1.155     markus     90: #include "atomicio.h"
                     91: #include "canohost.h"
1.343     deraadt    92: #include "hostfile.h"
1.155     markus     93: #include "auth.h"
1.404     markus     94: #include "authfd.h"
1.294     djm        95: #include "msg.h"
1.186     markus     96: #include "dispatch.h"
1.206     stevesk    97: #include "channels.h"
1.230     provos     98: #include "session.h"
1.231     provos     99: #include "monitor.h"
1.343     deraadt   100: #ifdef GSSAPI
                    101: #include "ssh-gss.h"
                    102: #endif
1.231     provos    103: #include "monitor_wrap.h"
1.385     djm       104: #include "ssh-sandbox.h"
1.506     djm       105: #include "auth-options.h"
1.332     stevesk   106: #include "version.h"
1.432     djm       107: #include "ssherr.h"
1.542     djm       108: #include "sk-api.h"
1.522     djm       109:
1.296     djm       110: /* Re-exec fds */
                    111: #define REEXEC_DEVCRYPTO_RESERVED_FD   (STDERR_FILENO + 1)
                    112: #define REEXEC_STARTUP_PIPE_FD         (STDERR_FILENO + 2)
                    113: #define REEXEC_CONFIG_PASS_FD          (STDERR_FILENO + 3)
                    114: #define REEXEC_MIN_FREE_FD             (STDERR_FILENO + 4)
                    115:
1.138     markus    116: extern char *__progname;
                    117:
1.1       deraadt   118: /* Server configuration options. */
                    119: ServerOptions options;
                    120:
                    121: /* Name of the server configuration file. */
1.154     markus    122: char *config_file_name = _PATH_SERVER_CONFIG_FILE;
1.1       deraadt   123:
1.105     markus    124: /*
1.65      deraadt   125:  * Debug mode flag.  This can be set on the command line.  If debug
                    126:  * mode is enabled, extra debugging output will be sent to the system
                    127:  * log, the daemon will not go to background, and will exit after processing
                    128:  * the first connection.
                    129:  */
1.1       deraadt   130: int debug_flag = 0;
                    131:
1.499     djm       132: /*
                    133:  * Indicating that the daemon should only test the configuration and keys.
                    134:  * If test_flag > 1 ("-T" flag), then sshd will also dump the effective
                    135:  * configuration, optionally using connection information provided by the
                    136:  * "-C" flag.
                    137:  */
1.521     djm       138: static int test_flag = 0;
1.203     stevesk   139:
1.1       deraadt   140: /* Flag indicating that the daemon is being started from inetd. */
1.521     djm       141: static int inetd_flag = 0;
1.1       deraadt   142:
1.135     markus    143: /* Flag indicating that sshd should not detach and become a daemon. */
1.521     djm       144: static int no_daemon_flag = 0;
1.135     markus    145:
1.47      markus    146: /* debug goes to stderr unless inetd_flag is set */
1.521     djm       147: static int log_stderr = 0;
1.47      markus    148:
1.1       deraadt   149: /* Saved arguments to main(). */
1.521     djm       150: static char **saved_argv;
1.1       deraadt   151:
1.294     djm       152: /* re-exec */
1.521     djm       153: static int rexeced_flag = 0;
                    154: static int rexec_flag = 1;
                    155: static int rexec_argc = 0;
                    156: static char **rexec_argv;
1.294     djm       157:
1.66      markus    158: /*
1.75      markus    159:  * The sockets that the server is listening; this is used in the SIGHUP
                    160:  * signal handler.
1.66      markus    161:  */
1.75      markus    162: #define        MAX_LISTEN_SOCKS        16
1.521     djm       163: static int listen_socks[MAX_LISTEN_SOCKS];
                    164: static int num_listen_socks = 0;
1.1       deraadt   165:
1.404     markus    166: /* Daemon's agent connection */
1.432     djm       167: int auth_sock = -1;
1.521     djm       168: static int have_agent = 0;
1.404     markus    169:
1.66      markus    170: /*
                    171:  * Any really sensitive data in the application is contained in this
                    172:  * structure. The idea is that this structure could be locked into memory so
                    173:  * that the pages do not get written into swap.  However, there are some
                    174:  * problems. The private key contains BIGNUMs, and we do not (in principle)
                    175:  * have access to the internals of them, and locking just the structure is
                    176:  * not very useful.  Currently, memory locking is not implemented.
                    177:  */
1.64      markus    178: struct {
1.488     markus    179:        struct sshkey   **host_keys;            /* all private host keys */
                    180:        struct sshkey   **host_pubkeys;         /* all public host keys */
                    181:        struct sshkey   **host_certificates;    /* all public host certificates */
                    182:        int             have_ssh2_key;
1.1       deraadt   183: } sensitive_data;
                    184:
1.199     markus    185: /* This is set to true when a signal is received. */
1.212     markus    186: static volatile sig_atomic_t received_sighup = 0;
                    187: static volatile sig_atomic_t received_sigterm = 0;
1.1       deraadt   188:
1.96      markus    189: /* session identifier, used by RSA-auth */
1.140     markus    190: u_char session_id[16];
1.96      markus    191:
1.108     markus    192: /* same for ssh2 */
1.140     markus    193: u_char *session_id2 = NULL;
1.269     markus    194: u_int session_id2_len = 0;
1.108     markus    195:
1.125     markus    196: /* record remote hostname or ip */
1.438     deraadt   197: u_int utmp_len = HOST_NAME_MAX+1;
1.125     markus    198:
1.533     djm       199: /*
                    200:  * startup_pipes/flags are used for tracking children of the listening sshd
                    201:  * process early in their lifespans. This tracking is needed for three things:
                    202:  *
                    203:  * 1) Implementing the MaxStartups limit of concurrent unauthenticated
                    204:  *    connections.
                    205:  * 2) Avoiding a race condition for SIGHUP processing, where child processes
                    206:  *    may have listen_socks open that could collide with main listener process
                    207:  *    after it restarts.
                    208:  * 3) Ensuring that rexec'd sshd processes have received their initial state
                    209:  *    from the parent listen process before handling SIGHUP.
                    210:  *
                    211:  * Child processes signal that they have completed closure of the listen_socks
                    212:  * and (if applicable) received their rexec state by sending a char over their
                    213:  * sock. Child processes signal that authentication has completed by closing
                    214:  * the sock (or by exiting).
                    215:  */
1.521     djm       216: static int *startup_pipes = NULL;
1.533     djm       217: static int *startup_flags = NULL;      /* Indicates child closed listener */
                    218: static int startup_pipe = -1;          /* in child */
1.211     markus    219:
1.231     provos    220: /* variables used for privilege separation */
1.337     dtucker   221: int use_privsep = -1;
1.285     dtucker   222: struct monitor *pmonitor = NULL;
1.386     djm       223: int privsep_is_preauth = 1;
1.231     provos    224:
1.527     djm       225: /* global connection state and authentication contexts */
1.278     markus    226: Authctxt *the_authctxt = NULL;
1.527     djm       227: struct ssh *the_active_state;
1.278     markus    228:
1.506     djm       229: /* global key/cert auth options. XXX move to permanent ssh->authctxt? */
                    230: struct sshauthopt *auth_opts = NULL;
                    231:
1.337     dtucker   232: /* sshd_config buffer */
1.511     markus    233: struct sshbuf *cfg;
1.337     dtucker   234:
1.299     dtucker   235: /* message to be displayed after login */
1.510     markus    236: struct sshbuf *loginmsg;
1.299     dtucker   237:
1.1       deraadt   238: /* Prototypes for various functions defined later in this file. */
1.200     itojun    239: void destroy_sensitive_data(void);
1.231     provos    240: void demote_sensitive_data(void);
1.525     djm       241: static void do_ssh2_kex(struct ssh *);
1.129     provos    242:
1.545   ! djm       243: static char *listener_proctitle;
        !           244:
1.87      markus    245: /*
1.75      markus    246:  * Close all listening sockets
                    247:  */
1.200     itojun    248: static void
1.75      markus    249: close_listen_socks(void)
                    250: {
                    251:        int i;
1.250     deraadt   252:
1.75      markus    253:        for (i = 0; i < num_listen_socks; i++)
                    254:                close(listen_socks[i]);
                    255:        num_listen_socks = -1;
                    256: }
                    257:
1.211     markus    258: static void
                    259: close_startup_pipes(void)
                    260: {
                    261:        int i;
1.250     deraadt   262:
1.211     markus    263:        if (startup_pipes)
                    264:                for (i = 0; i < options.max_startups; i++)
                    265:                        if (startup_pipes[i] != -1)
                    266:                                close(startup_pipes[i]);
                    267: }
                    268:
1.75      markus    269: /*
1.65      deraadt   270:  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
                    271:  * the effect is to reread the configuration file (and to regenerate
                    272:  * the server key).
                    273:  */
1.327     deraadt   274:
                    275: /*ARGSUSED*/
1.200     itojun    276: static void
1.64      markus    277: sighup_handler(int sig)
1.1       deraadt   278: {
1.64      markus    279:        received_sighup = 1;
1.1       deraadt   280: }
                    281:
1.65      deraadt   282: /*
                    283:  * Called from the main program after receiving SIGHUP.
                    284:  * Restarts the server.
                    285:  */
1.200     itojun    286: static void
1.165     itojun    287: sighup_restart(void)
1.1       deraadt   288: {
1.264     itojun    289:        logit("Received SIGHUP; restarting.");
1.479     dtucker   290:        if (options.pid_file != NULL)
                    291:                unlink(options.pid_file);
1.75      markus    292:        close_listen_socks();
1.211     markus    293:        close_startup_pipes();
1.349     dtucker   294:        alarm(0);  /* alarm timer persists across exec */
1.544     dtucker   295:        ssh_signal(SIGHUP, SIG_IGN); /* will be restored after exec */
1.64      markus    296:        execv(saved_argv[0], saved_argv);
1.264     itojun    297:        logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
1.250     deraadt   298:            strerror(errno));
1.64      markus    299:        exit(1);
1.1       deraadt   300: }
                    301:
1.65      deraadt   302: /*
                    303:  * Generic signal handler for terminating signals in the master daemon.
                    304:  */
1.327     deraadt   305: /*ARGSUSED*/
1.200     itojun    306: static void
1.64      markus    307: sigterm_handler(int sig)
1.1       deraadt   308: {
1.199     markus    309:        received_sigterm = sig;
1.1       deraadt   310: }
                    311:
1.65      deraadt   312: /*
                    313:  * SIGCHLD handler.  This is called whenever a child dies.  This will then
1.199     markus    314:  * reap any zombies left by exited children.
1.65      deraadt   315:  */
1.327     deraadt   316: /*ARGSUSED*/
1.200     itojun    317: static void
1.64      markus    318: main_sigchld_handler(int sig)
1.1       deraadt   319: {
1.250     deraadt   320:        int save_errno = errno;
1.239     markus    321:        pid_t pid;
1.64      markus    322:        int status;
1.60      deraadt   323:
1.544     dtucker   324:        debug("main_sigchld_handler: %s", strsignal(sig));
                    325:
1.239     markus    326:        while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
1.537     deraadt   327:            (pid == -1 && errno == EINTR))
1.64      markus    328:                ;
                    329:        errno = save_errno;
1.1       deraadt   330: }
                    331:
1.65      deraadt   332: /*
                    333:  * Signal handler for the alarm after the login grace period has expired.
                    334:  */
1.327     deraadt   335: /*ARGSUSED*/
1.200     itojun    336: static void
1.64      markus    337: grace_alarm_handler(int sig)
1.1       deraadt   338: {
1.285     dtucker   339:        if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
                    340:                kill(pmonitor->m_pid, SIGALRM);
1.394     djm       341:
                    342:        /*
                    343:         * Try to kill any processes that we have spawned, E.g. authorized
                    344:         * keys command helpers.
                    345:         */
                    346:        if (getpgid(0) == getpid()) {
1.544     dtucker   347:                ssh_signal(SIGTERM, SIG_IGN);
1.416     djm       348:                kill(0, SIGTERM);
1.394     djm       349:        }
1.285     dtucker   350:
1.527     djm       351:        /* XXX pre-format ipaddr/port so we don't need to access active_state */
1.64      markus    352:        /* Log error and exit. */
1.466     djm       353:        sigdie("Timeout before authentication for %s port %d",
1.527     djm       354:            ssh_remote_ipaddr(the_active_state),
                    355:            ssh_remote_port(the_active_state));
1.62      markus    356: }
                    357:
1.134     markus    358: /* Destroy the host and server keys.  They will no longer be needed. */
1.108     markus    359: void
                    360: destroy_sensitive_data(void)
                    361: {
1.493     djm       362:        u_int i;
1.134     markus    363:
1.217     deraadt   364:        for (i = 0; i < options.num_host_key_files; i++) {
1.134     markus    365:                if (sensitive_data.host_keys[i]) {
1.512     markus    366:                        sshkey_free(sensitive_data.host_keys[i]);
1.134     markus    367:                        sensitive_data.host_keys[i] = NULL;
                    368:                }
1.373     djm       369:                if (sensitive_data.host_certificates[i]) {
1.512     markus    370:                        sshkey_free(sensitive_data.host_certificates[i]);
1.373     djm       371:                        sensitive_data.host_certificates[i] = NULL;
                    372:                }
1.134     markus    373:        }
                    374: }
                    375:
1.231     provos    376: /* Demote private to public keys for network child */
                    377: void
                    378: demote_sensitive_data(void)
                    379: {
1.488     markus    380:        struct sshkey *tmp;
1.493     djm       381:        u_int i;
1.512     markus    382:        int r;
1.231     provos    383:
                    384:        for (i = 0; i < options.num_host_key_files; i++) {
                    385:                if (sensitive_data.host_keys[i]) {
1.515     djm       386:                        if ((r = sshkey_from_private(
                    387:                            sensitive_data.host_keys[i], &tmp)) != 0)
1.512     markus    388:                                fatal("could not demote host %s key: %s",
                    389:                                    sshkey_type(sensitive_data.host_keys[i]),
                    390:                                    ssh_err(r));
                    391:                        sshkey_free(sensitive_data.host_keys[i]);
1.231     provos    392:                        sensitive_data.host_keys[i] = tmp;
                    393:                }
1.373     djm       394:                /* Certs do not need demotion */
1.231     provos    395:        }
                    396: }
                    397:
1.233     markus    398: static void
1.231     provos    399: privsep_preauth_child(void)
                    400: {
1.253     deraadt   401:        gid_t gidset[1];
1.250     deraadt   402:        struct passwd *pw;
1.231     provos    403:
                    404:        /* Enable challenge-response authentication for privilege separation */
                    405:        privsep_challenge_enable();
1.419     djm       406:
1.420     markus    407: #ifdef GSSAPI
1.419     djm       408:        /* Cache supported mechanism OIDs for later use */
1.516     djm       409:        ssh_gssapi_prepare_supported_oids();
1.420     markus    410: #endif
1.231     provos    411:
                    412:        /* Demote the private keys to public keys. */
                    413:        demote_sensitive_data();
                    414:
1.460     djm       415:        /* Demote the child */
                    416:        if (getuid() == 0 || geteuid() == 0) {
                    417:                if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
                    418:                        fatal("Privilege separation user %s does not exist",
                    419:                            SSH_PRIVSEP_USER);
1.500     djm       420:                pw = pwcopy(pw); /* Ensure mutable */
1.460     djm       421:                endpwent();
1.500     djm       422:                freezero(pw->pw_passwd, strlen(pw->pw_passwd));
1.460     djm       423:
                    424:                /* Change our root directory */
                    425:                if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
                    426:                        fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
                    427:                            strerror(errno));
                    428:                if (chdir("/") == -1)
                    429:                        fatal("chdir(\"/\"): %s", strerror(errno));
                    430:
                    431:                /*
                    432:                 * Drop our privileges
                    433:                 * NB. Can't use setusercontext() after chroot.
                    434:                 */
                    435:                debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
                    436:                    (u_int)pw->pw_gid);
                    437:                gidset[0] = pw->pw_gid;
1.537     deraadt   438:                if (setgroups(1, gidset) == -1)
1.460     djm       439:                        fatal("setgroups: %.100s", strerror(errno));
                    440:                permanently_set_uid(pw);
                    441:        }
1.231     provos    442: }
                    443:
1.278     markus    444: static int
1.525     djm       445: privsep_preauth(struct ssh *ssh)
1.237     markus    446: {
1.432     djm       447:        int status, r;
1.237     markus    448:        pid_t pid;
1.384     djm       449:        struct ssh_sandbox *box = NULL;
1.237     markus    450:
                    451:        /* Set up unprivileged child process to deal with network data */
1.242     mouring   452:        pmonitor = monitor_init();
1.237     markus    453:        /* Store a pointer to the kex for later rekeying */
1.525     djm       454:        pmonitor->m_pkex = &ssh->kex;
1.237     markus    455:
1.393     djm       456:        if (use_privsep == PRIVSEP_ON)
1.384     djm       457:                box = ssh_sandbox_init();
1.237     markus    458:        pid = fork();
                    459:        if (pid == -1) {
                    460:                fatal("fork of unprivileged child failed");
                    461:        } else if (pid != 0) {
1.245     mpech     462:                debug2("Network child is on pid %ld", (long)pid);
1.237     markus    463:
1.392     markus    464:                pmonitor->m_pid = pid;
1.432     djm       465:                if (have_agent) {
                    466:                        r = ssh_get_authentication_socket(&auth_sock);
                    467:                        if (r != 0) {
                    468:                                error("Could not get agent socket: %s",
                    469:                                    ssh_err(r));
                    470:                                have_agent = 0;
                    471:                        }
                    472:                }
1.384     djm       473:                if (box != NULL)
                    474:                        ssh_sandbox_parent_preauth(box, pid);
1.526     djm       475:                monitor_child_preauth(ssh, pmonitor);
1.237     markus    476:
                    477:                /* Wait for the child's exit status */
1.537     deraadt   478:                while (waitpid(pid, &status, 0) == -1) {
1.386     djm       479:                        if (errno == EINTR)
                    480:                                continue;
                    481:                        pmonitor->m_pid = -1;
                    482:                        fatal("%s: waitpid: %s", __func__, strerror(errno));
1.384     djm       483:                }
1.386     djm       484:                privsep_is_preauth = 0;
                    485:                pmonitor->m_pid = -1;
1.384     djm       486:                if (WIFEXITED(status)) {
                    487:                        if (WEXITSTATUS(status) != 0)
                    488:                                fatal("%s: preauth child exited with status %d",
                    489:                                    __func__, WEXITSTATUS(status));
                    490:                } else if (WIFSIGNALED(status))
                    491:                        fatal("%s: preauth child terminated by signal %d",
                    492:                            __func__, WTERMSIG(status));
                    493:                if (box != NULL)
                    494:                        ssh_sandbox_parent_finish(box);
                    495:                return 1;
1.237     markus    496:        } else {
                    497:                /* child */
1.383     djm       498:                close(pmonitor->m_sendfd);
                    499:                close(pmonitor->m_log_recvfd);
1.237     markus    500:
1.383     djm       501:                /* Arrange for logging to be sent to the monitor */
                    502:                set_log_handler(mm_log_handler, pmonitor);
1.237     markus    503:
1.460     djm       504:                privsep_preauth_child();
1.238     stevesk   505:                setproctitle("%s", "[net]");
1.384     djm       506:                if (box != NULL)
                    507:                        ssh_sandbox_child(box);
                    508:
                    509:                return 0;
1.237     markus    510:        }
                    511: }
                    512:
1.233     markus    513: static void
1.525     djm       514: privsep_postauth(struct ssh *ssh, Authctxt *authctxt)
1.231     provos    515: {
1.474     djm       516:        if (authctxt->pw->pw_uid == 0) {
1.231     provos    517:                /* File descriptor passing is broken or root login */
                    518:                use_privsep = 0;
1.315     djm       519:                goto skip;
1.231     provos    520:        }
1.234     markus    521:
1.231     provos    522:        /* New socket pair */
1.242     mouring   523:        monitor_reinit(pmonitor);
1.231     provos    524:
1.242     mouring   525:        pmonitor->m_pid = fork();
                    526:        if (pmonitor->m_pid == -1)
1.231     provos    527:                fatal("fork of unprivileged child failed");
1.242     mouring   528:        else if (pmonitor->m_pid != 0) {
1.364     markus    529:                verbose("User child is on pid %ld", (long)pmonitor->m_pid);
1.510     markus    530:                sshbuf_reset(loginmsg);
1.526     djm       531:                monitor_clear_keystate(ssh, pmonitor);
                    532:                monitor_child_postauth(ssh, pmonitor);
1.231     provos    533:
                    534:                /* NEVERREACHED */
                    535:                exit(0);
                    536:        }
                    537:
1.383     djm       538:        /* child */
                    539:
1.242     mouring   540:        close(pmonitor->m_sendfd);
1.383     djm       541:        pmonitor->m_sendfd = -1;
1.231     provos    542:
                    543:        /* Demote the private keys to public keys. */
                    544:        demote_sensitive_data();
1.354     djm       545:
1.231     provos    546:        /* Drop privileges */
                    547:        do_setusercontext(authctxt->pw);
                    548:
1.315     djm       549:  skip:
1.231     provos    550:        /* It is safe now to apply the key state */
1.526     djm       551:        monitor_apply_keystate(ssh, pmonitor);
1.312     markus    552:
                    553:        /*
                    554:         * Tell the packet layer that authentication was successful, since
                    555:         * this information is not part of the key state.
                    556:         */
1.525     djm       557:        ssh_packet_set_authenticated(ssh);
1.231     provos    558: }
                    559:
1.509     djm       560: static void
                    561: append_hostkey_type(struct sshbuf *b, const char *s)
                    562: {
                    563:        int r;
                    564:
                    565:        if (match_pattern_list(s, options.hostkeyalgorithms, 0) != 1) {
                    566:                debug3("%s: %s key not permitted by HostkeyAlgorithms",
                    567:                    __func__, s);
                    568:                return;
                    569:        }
                    570:        if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) > 0 ? "," : "", s)) != 0)
                    571:                fatal("%s: sshbuf_putf: %s", __func__, ssh_err(r));
                    572: }
                    573:
1.200     itojun    574: static char *
1.134     markus    575: list_hostkey_types(void)
                    576: {
1.509     djm       577:        struct sshbuf *b;
                    578:        struct sshkey *key;
1.281     jakob     579:        char *ret;
1.493     djm       580:        u_int i;
1.223     markus    581:
1.509     djm       582:        if ((b = sshbuf_new()) == NULL)
                    583:                fatal("%s: sshbuf_new failed", __func__);
1.217     deraadt   584:        for (i = 0; i < options.num_host_key_files; i++) {
1.373     djm       585:                key = sensitive_data.host_keys[i];
1.443     djm       586:                if (key == NULL)
1.404     markus    587:                        key = sensitive_data.host_pubkeys[i];
1.472     markus    588:                if (key == NULL)
1.134     markus    589:                        continue;
1.214     deraadt   590:                switch (key->type) {
1.134     markus    591:                case KEY_RSA:
1.509     djm       592:                        /* for RSA we also support SHA2 signatures */
                    593:                        append_hostkey_type(b, "rsa-sha2-512");
                    594:                        append_hostkey_type(b, "rsa-sha2-256");
                    595:                        /* FALLTHROUGH */
1.134     markus    596:                case KEY_DSA:
1.378     djm       597:                case KEY_ECDSA:
1.412     markus    598:                case KEY_ED25519:
1.542     djm       599:                case KEY_ECDSA_SK:
                    600:                case KEY_ED25519_SK:
1.505     markus    601:                case KEY_XMSS:
1.509     djm       602:                        append_hostkey_type(b, sshkey_ssh_name(key));
1.134     markus    603:                        break;
                    604:                }
1.373     djm       605:                /* If the private key has a cert peer, then list that too */
                    606:                key = sensitive_data.host_certificates[i];
                    607:                if (key == NULL)
                    608:                        continue;
                    609:                switch (key->type) {
                    610:                case KEY_RSA_CERT:
1.509     djm       611:                        /* for RSA we also support SHA2 signatures */
                    612:                        append_hostkey_type(b,
                    613:                            "rsa-sha2-512-cert-v01@openssh.com");
                    614:                        append_hostkey_type(b,
                    615:                            "rsa-sha2-256-cert-v01@openssh.com");
                    616:                        /* FALLTHROUGH */
1.373     djm       617:                case KEY_DSA_CERT:
1.378     djm       618:                case KEY_ECDSA_CERT:
1.412     markus    619:                case KEY_ED25519_CERT:
1.542     djm       620:                case KEY_ECDSA_SK_CERT:
                    621:                case KEY_ED25519_SK_CERT:
1.505     markus    622:                case KEY_XMSS_CERT:
1.509     djm       623:                        append_hostkey_type(b, sshkey_ssh_name(key));
1.373     djm       624:                        break;
                    625:                }
1.134     markus    626:        }
1.509     djm       627:        if ((ret = sshbuf_dup_string(b)) == NULL)
1.467     djm       628:                fatal("%s: sshbuf_dup_string failed", __func__);
1.509     djm       629:        sshbuf_free(b);
                    630:        debug("%s: %s", __func__, ret);
1.281     jakob     631:        return ret;
1.134     markus    632: }
                    633:
1.488     markus    634: static struct sshkey *
1.440     djm       635: get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
1.134     markus    636: {
1.493     djm       637:        u_int i;
1.488     markus    638:        struct sshkey *key;
1.250     deraadt   639:
1.217     deraadt   640:        for (i = 0; i < options.num_host_key_files; i++) {
1.375     djm       641:                switch (type) {
                    642:                case KEY_RSA_CERT:
                    643:                case KEY_DSA_CERT:
1.378     djm       644:                case KEY_ECDSA_CERT:
1.412     markus    645:                case KEY_ED25519_CERT:
1.542     djm       646:                case KEY_ECDSA_SK_CERT:
                    647:                case KEY_ED25519_SK_CERT:
1.505     markus    648:                case KEY_XMSS_CERT:
1.373     djm       649:                        key = sensitive_data.host_certificates[i];
1.375     djm       650:                        break;
                    651:                default:
1.373     djm       652:                        key = sensitive_data.host_keys[i];
1.404     markus    653:                        if (key == NULL && !need_private)
                    654:                                key = sensitive_data.host_pubkeys[i];
1.375     djm       655:                        break;
                    656:                }
1.542     djm       657:                if (key == NULL || key->type != type)
                    658:                        continue;
                    659:                switch (type) {
                    660:                case KEY_ECDSA:
                    661:                case KEY_ECDSA_SK:
                    662:                case KEY_ECDSA_CERT:
                    663:                case KEY_ECDSA_SK_CERT:
                    664:                        if (key->ecdsa_nid != nid)
                    665:                                continue;
                    666:                        /* FALLTHROUGH */
                    667:                default:
1.373     djm       668:                        return need_private ?
                    669:                            sensitive_data.host_keys[i] : key;
1.542     djm       670:                }
1.134     markus    671:        }
                    672:        return NULL;
1.96      markus    673: }
                    674:
1.488     markus    675: struct sshkey *
1.440     djm       676: get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
1.373     djm       677: {
1.440     djm       678:        return get_hostkey_by_type(type, nid, 0, ssh);
1.373     djm       679: }
                    680:
1.488     markus    681: struct sshkey *
1.440     djm       682: get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
1.373     djm       683: {
1.440     djm       684:        return get_hostkey_by_type(type, nid, 1, ssh);
1.373     djm       685: }
                    686:
1.488     markus    687: struct sshkey *
1.231     provos    688: get_hostkey_by_index(int ind)
                    689: {
1.493     djm       690:        if (ind < 0 || (u_int)ind >= options.num_host_key_files)
1.231     provos    691:                return (NULL);
                    692:        return (sensitive_data.host_keys[ind]);
                    693: }
                    694:
1.488     markus    695: struct sshkey *
1.435     markus    696: get_hostkey_public_by_index(int ind, struct ssh *ssh)
1.404     markus    697: {
1.493     djm       698:        if (ind < 0 || (u_int)ind >= options.num_host_key_files)
1.404     markus    699:                return (NULL);
                    700:        return (sensitive_data.host_pubkeys[ind]);
                    701: }
                    702:
1.231     provos    703: int
1.488     markus    704: get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh)
1.231     provos    705: {
1.493     djm       706:        u_int i;
1.250     deraadt   707:
1.231     provos    708:        for (i = 0; i < options.num_host_key_files; i++) {
1.512     markus    709:                if (sshkey_is_cert(key)) {
1.442     djm       710:                        if (key == sensitive_data.host_certificates[i] ||
                    711:                            (compare && sensitive_data.host_certificates[i] &&
                    712:                            sshkey_equal(key,
                    713:                            sensitive_data.host_certificates[i])))
1.373     djm       714:                                return (i);
                    715:                } else {
1.442     djm       716:                        if (key == sensitive_data.host_keys[i] ||
                    717:                            (compare && sensitive_data.host_keys[i] &&
                    718:                            sshkey_equal(key, sensitive_data.host_keys[i])))
1.373     djm       719:                                return (i);
1.442     djm       720:                        if (key == sensitive_data.host_pubkeys[i] ||
                    721:                            (compare && sensitive_data.host_pubkeys[i] &&
                    722:                            sshkey_equal(key, sensitive_data.host_pubkeys[i])))
1.404     markus    723:                                return (i);
1.373     djm       724:                }
1.231     provos    725:        }
                    726:        return (-1);
                    727: }
                    728:
1.439     djm       729: /* Inform the client of all hostkeys */
                    730: static void
                    731: notify_hostkeys(struct ssh *ssh)
                    732: {
                    733:        struct sshbuf *buf;
                    734:        struct sshkey *key;
1.493     djm       735:        u_int i, nkeys;
                    736:        int r;
1.439     djm       737:        char *fp;
1.446     dtucker   738:
                    739:        /* Some clients cannot cope with the hostkeys message, skip those. */
1.527     djm       740:        if (ssh->compat & SSH_BUG_HOSTKEYS)
1.446     dtucker   741:                return;
1.439     djm       742:
                    743:        if ((buf = sshbuf_new()) == NULL)
                    744:                fatal("%s: sshbuf_new", __func__);
                    745:        for (i = nkeys = 0; i < options.num_host_key_files; i++) {
                    746:                key = get_hostkey_public_by_index(i, ssh);
                    747:                if (key == NULL || key->type == KEY_UNSPEC ||
1.472     markus    748:                    sshkey_is_cert(key))
1.439     djm       749:                        continue;
                    750:                fp = sshkey_fingerprint(key, options.fingerprint_hash,
                    751:                    SSH_FP_DEFAULT);
                    752:                debug3("%s: key %d: %s %s", __func__, i,
                    753:                    sshkey_ssh_name(key), fp);
                    754:                free(fp);
1.442     djm       755:                if (nkeys == 0) {
1.525     djm       756:                        /*
                    757:                         * Start building the request when we find the
                    758:                         * first usable key.
                    759:                         */
                    760:                        if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
                    761:                            (r = sshpkt_put_cstring(ssh, "hostkeys-00@openssh.com")) != 0 ||
                    762:                            (r = sshpkt_put_u8(ssh, 0)) != 0) /* want reply */
                    763:                                sshpkt_fatal(ssh, r, "%s: start request", __func__);
1.442     djm       764:                }
1.525     djm       765:                /* Append the key to the request */
1.442     djm       766:                sshbuf_reset(buf);
                    767:                if ((r = sshkey_putb(key, buf)) != 0)
1.439     djm       768:                        fatal("%s: couldn't put hostkey %d: %s",
                    769:                            __func__, i, ssh_err(r));
1.525     djm       770:                if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
                    771:                        sshpkt_fatal(ssh, r, "%s: append key", __func__);
1.439     djm       772:                nkeys++;
                    773:        }
1.493     djm       774:        debug3("%s: sent %u hostkeys", __func__, nkeys);
1.439     djm       775:        if (nkeys == 0)
                    776:                fatal("%s: no hostkeys", __func__);
1.525     djm       777:        if ((r = sshpkt_send(ssh)) != 0)
                    778:                sshpkt_fatal(ssh, r, "%s: send", __func__);
1.442     djm       779:        sshbuf_free(buf);
1.439     djm       780: }
                    781:
1.124     markus    782: /*
                    783:  * returns 1 if connection should be dropped, 0 otherwise.
                    784:  * dropping starts at connection #max_startups_begin with a probability
                    785:  * of (max_startups_rate/100). the probability increases linearly until
                    786:  * all connections are dropped for startups > max_startups
                    787:  */
1.200     itojun    788: static int
1.124     markus    789: drop_connection(int startups)
                    790: {
1.303     mickey    791:        int p, r;
1.124     markus    792:
                    793:        if (startups < options.max_startups_begin)
                    794:                return 0;
                    795:        if (startups >= options.max_startups)
                    796:                return 1;
                    797:        if (options.max_startups_rate == 100)
                    798:                return 1;
                    799:
                    800:        p  = 100 - options.max_startups_rate;
                    801:        p *= startups - options.max_startups_begin;
1.303     mickey    802:        p /= options.max_startups - options.max_startups_begin;
1.124     markus    803:        p += options.max_startups_rate;
1.356     djm       804:        r = arc4random_uniform(100);
1.124     markus    805:
1.304     djm       806:        debug("drop_connection: p %d, r %d", p, r);
1.124     markus    807:        return (r < p) ? 1 : 0;
                    808: }
                    809:
1.215     markus    810: static void
                    811: usage(void)
                    812: {
1.290     markus    813:        fprintf(stderr, "%s, %s\n",
1.426     markus    814:            SSH_VERSION,
                    815: #ifdef WITH_OPENSSL
1.517     djm       816:            OpenSSL_version(OPENSSL_VERSION)
1.426     markus    817: #else
                    818:            "without OpenSSL"
                    819: #endif
                    820:        );
1.289     markus    821:        fprintf(stderr,
1.473     naddy     822: "usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n"
1.399     dtucker   823: "            [-E log_file] [-f config_file] [-g login_grace_time]\n"
1.473     naddy     824: "            [-h host_key_file] [-o option] [-p port] [-u len]\n"
1.289     markus    825:        );
1.215     markus    826:        exit(1);
                    827: }
                    828:
1.294     djm       829: static void
1.467     djm       830: send_rexec_state(int fd, struct sshbuf *conf)
1.294     djm       831: {
1.467     djm       832:        struct sshbuf *m;
                    833:        int r;
1.294     djm       834:
1.467     djm       835:        debug3("%s: entering fd = %d config len %zu", __func__, fd,
                    836:            sshbuf_len(conf));
1.294     djm       837:
                    838:        /*
                    839:         * Protocol from reexec master to child:
                    840:         *      string  configuration
                    841:         */
1.467     djm       842:        if ((m = sshbuf_new()) == NULL)
                    843:                fatal("%s: sshbuf_new failed", __func__);
                    844:        if ((r = sshbuf_put_stringb(m, conf)) != 0)
                    845:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    846:        if (ssh_msg_send(fd, 0, m) == -1)
1.294     djm       847:                fatal("%s: ssh_msg_send failed", __func__);
                    848:
1.467     djm       849:        sshbuf_free(m);
1.294     djm       850:
                    851:        debug3("%s: done", __func__);
                    852: }
                    853:
                    854: static void
1.511     markus    855: recv_rexec_state(int fd, struct sshbuf *conf)
1.294     djm       856: {
1.511     markus    857:        struct sshbuf *m;
                    858:        u_char *cp, ver;
                    859:        size_t len;
                    860:        int r;
1.294     djm       861:
                    862:        debug3("%s: entering fd = %d", __func__, fd);
                    863:
1.511     markus    864:        if ((m = sshbuf_new()) == NULL)
                    865:                fatal("%s: sshbuf_new failed", __func__);
                    866:        if (ssh_msg_recv(fd, m) == -1)
1.294     djm       867:                fatal("%s: ssh_msg_recv failed", __func__);
1.511     markus    868:        if ((r = sshbuf_get_u8(m, &ver)) != 0)
                    869:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    870:        if (ver != 0)
1.294     djm       871:                fatal("%s: rexec version mismatch", __func__);
1.511     markus    872:        if ((r = sshbuf_get_string(m, &cp, &len)) != 0)
                    873:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    874:        if (conf != NULL && (r = sshbuf_put(conf, cp, len)))
                    875:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.294     djm       876:
1.402     djm       877:        free(cp);
1.511     markus    878:        sshbuf_free(m);
1.294     djm       879:
                    880:        debug3("%s: done", __func__);
                    881: }
                    882:
1.345     djm       883: /* Accept a connection from inetd */
                    884: static void
                    885: server_accept_inetd(int *sock_in, int *sock_out)
                    886: {
                    887:        int fd;
                    888:
                    889:        if (rexeced_flag) {
                    890:                close(REEXEC_CONFIG_PASS_FD);
                    891:                *sock_in = *sock_out = dup(STDIN_FILENO);
                    892:        } else {
                    893:                *sock_in = dup(STDIN_FILENO);
                    894:                *sock_out = dup(STDOUT_FILENO);
                    895:        }
                    896:        /*
                    897:         * We intentionally do not close the descriptors 0, 1, and 2
                    898:         * as our code for setting the descriptors won't work if
                    899:         * ttyfd happens to be one of those.
                    900:         */
                    901:        if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
                    902:                dup2(fd, STDIN_FILENO);
                    903:                dup2(fd, STDOUT_FILENO);
1.403     dtucker   904:                if (!log_stderr)
                    905:                        dup2(fd, STDERR_FILENO);
                    906:                if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1.345     djm       907:                        close(fd);
                    908:        }
                    909:        debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
                    910: }
                    911:
                    912: /*
                    913:  * Listen for TCP connections
                    914:  */
                    915: static void
1.494     djm       916: listen_on_addrs(struct listenaddr *la)
1.345     djm       917: {
1.494     djm       918:        int ret, listen_sock;
1.345     djm       919:        struct addrinfo *ai;
                    920:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
                    921:
1.494     djm       922:        for (ai = la->addrs; ai; ai = ai->ai_next) {
1.345     djm       923:                if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                    924:                        continue;
                    925:                if (num_listen_socks >= MAX_LISTEN_SOCKS)
                    926:                        fatal("Too many listen sockets. "
                    927:                            "Enlarge MAX_LISTEN_SOCKS");
                    928:                if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
                    929:                    ntop, sizeof(ntop), strport, sizeof(strport),
                    930:                    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
                    931:                        error("getnameinfo failed: %.100s",
1.352     dtucker   932:                            ssh_gai_strerror(ret));
1.345     djm       933:                        continue;
                    934:                }
                    935:                /* Create socket for listening. */
1.370     dtucker   936:                listen_sock = socket(ai->ai_family, ai->ai_socktype,
                    937:                    ai->ai_protocol);
1.537     deraadt   938:                if (listen_sock == -1) {
1.345     djm       939:                        /* kernel may not support ipv6 */
                    940:                        verbose("socket: %.100s", strerror(errno));
                    941:                        continue;
                    942:                }
                    943:                if (set_nonblock(listen_sock) == -1) {
1.483     djm       944:                        close(listen_sock);
                    945:                        continue;
                    946:                }
                    947:                if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
                    948:                        verbose("socket: CLOEXEC: %s", strerror(errno));
1.345     djm       949:                        close(listen_sock);
                    950:                        continue;
                    951:                }
1.494     djm       952:                /* Socket options */
                    953:                set_reuseaddr(listen_sock);
                    954:                if (la->rdomain != NULL &&
                    955:                    set_rdomain(listen_sock, la->rdomain) == -1) {
                    956:                        close(listen_sock);
                    957:                        continue;
                    958:                }
1.345     djm       959:
                    960:                debug("Bind to port %s on %s.", strport, ntop);
                    961:
                    962:                /* Bind the socket to the desired port. */
1.537     deraadt   963:                if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) == -1) {
1.345     djm       964:                        error("Bind to port %s on %s failed: %.200s.",
                    965:                            strport, ntop, strerror(errno));
                    966:                        close(listen_sock);
                    967:                        continue;
                    968:                }
                    969:                listen_socks[num_listen_socks] = listen_sock;
                    970:                num_listen_socks++;
                    971:
                    972:                /* Start listening on the port. */
1.537     deraadt   973:                if (listen(listen_sock, SSH_LISTEN_BACKLOG) == -1)
1.345     djm       974:                        fatal("listen on [%s]:%s: %.100s",
                    975:                            ntop, strport, strerror(errno));
1.494     djm       976:                logit("Server listening on %s port %s%s%s.",
                    977:                    ntop, strport,
                    978:                    la->rdomain == NULL ? "" : " rdomain ",
                    979:                    la->rdomain == NULL ? "" : la->rdomain);
1.345     djm       980:        }
1.494     djm       981: }
                    982:
                    983: static void
                    984: server_listen(void)
                    985: {
                    986:        u_int i;
                    987:
                    988:        for (i = 0; i < options.num_listen_addrs; i++) {
                    989:                listen_on_addrs(&options.listen_addrs[i]);
                    990:                freeaddrinfo(options.listen_addrs[i].addrs);
                    991:                free(options.listen_addrs[i].rdomain);
                    992:                memset(&options.listen_addrs[i], 0,
                    993:                    sizeof(options.listen_addrs[i]));
                    994:        }
                    995:        free(options.listen_addrs);
                    996:        options.listen_addrs = NULL;
                    997:        options.num_listen_addrs = 0;
1.345     djm       998:
                    999:        if (!num_listen_socks)
                   1000:                fatal("Cannot bind any address.");
                   1001: }
                   1002:
                   1003: /*
                   1004:  * The main TCP accept loop. Note that, for the non-debug case, returns
                   1005:  * from this function are in a forked subprocess.
                   1006:  */
                   1007: static void
                   1008: server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
                   1009: {
                   1010:        fd_set *fdset;
                   1011:        int i, j, ret, maxfd;
1.543     djm      1012:        int ostartups = -1, startups = 0, listening = 0, lameduck = 0;
1.345     djm      1013:        int startup_p[2] = { -1 , -1 };
1.533     djm      1014:        char c = 0;
1.345     djm      1015:        struct sockaddr_storage from;
                   1016:        socklen_t fromlen;
                   1017:        pid_t pid;
                   1018:
                   1019:        /* setup fd set for accept */
                   1020:        fdset = NULL;
                   1021:        maxfd = 0;
                   1022:        for (i = 0; i < num_listen_socks; i++)
                   1023:                if (listen_socks[i] > maxfd)
                   1024:                        maxfd = listen_socks[i];
                   1025:        /* pipes connected to unauthenticated childs */
                   1026:        startup_pipes = xcalloc(options.max_startups, sizeof(int));
1.533     djm      1027:        startup_flags = xcalloc(options.max_startups, sizeof(int));
1.345     djm      1028:        for (i = 0; i < options.max_startups; i++)
                   1029:                startup_pipes[i] = -1;
                   1030:
                   1031:        /*
                   1032:         * Stay listening for connections until the system crashes or
                   1033:         * the daemon is killed with a signal.
                   1034:         */
                   1035:        for (;;) {
1.543     djm      1036:                if (ostartups != startups) {
1.545   ! djm      1037:                        setproctitle("%s [listener] %d of %d-%d startups",
        !          1038:                            listener_proctitle, startups,
        !          1039:                            options.max_startups_begin, options.max_startups);
1.543     djm      1040:                        ostartups = startups;
                   1041:                }
1.533     djm      1042:                if (received_sighup) {
                   1043:                        if (!lameduck) {
                   1044:                                debug("Received SIGHUP; waiting for children");
                   1045:                                close_listen_socks();
                   1046:                                lameduck = 1;
                   1047:                        }
                   1048:                        if (listening <= 0)
                   1049:                                sighup_restart();
                   1050:                }
1.462     mmcc     1051:                free(fdset);
1.458     deraadt  1052:                fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
1.345     djm      1053:                    sizeof(fd_mask));
                   1054:
                   1055:                for (i = 0; i < num_listen_socks; i++)
                   1056:                        FD_SET(listen_socks[i], fdset);
                   1057:                for (i = 0; i < options.max_startups; i++)
                   1058:                        if (startup_pipes[i] != -1)
                   1059:                                FD_SET(startup_pipes[i], fdset);
                   1060:
                   1061:                /* Wait in select until there is a connection. */
                   1062:                ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1.537     deraadt  1063:                if (ret == -1 && errno != EINTR)
1.345     djm      1064:                        error("select: %.100s", strerror(errno));
                   1065:                if (received_sigterm) {
                   1066:                        logit("Received signal %d; terminating.",
                   1067:                            (int) received_sigterm);
                   1068:                        close_listen_socks();
1.430     djm      1069:                        if (options.pid_file != NULL)
                   1070:                                unlink(options.pid_file);
1.382     djm      1071:                        exit(received_sigterm == SIGTERM ? 0 : 255);
1.345     djm      1072:                }
1.537     deraadt  1073:                if (ret == -1)
1.345     djm      1074:                        continue;
                   1075:
1.533     djm      1076:                for (i = 0; i < options.max_startups; i++) {
                   1077:                        if (startup_pipes[i] == -1 ||
                   1078:                            !FD_ISSET(startup_pipes[i], fdset))
                   1079:                                continue;
                   1080:                        switch (read(startup_pipes[i], &c, sizeof(c))) {
                   1081:                        case -1:
                   1082:                                if (errno == EINTR || errno == EAGAIN)
                   1083:                                        continue;
                   1084:                                if (errno != EPIPE) {
                   1085:                                        error("%s: startup pipe %d (fd=%d): "
                   1086:                                            "read %s", __func__, i,
                   1087:                                            startup_pipes[i], strerror(errno));
                   1088:                                }
                   1089:                                /* FALLTHROUGH */
                   1090:                        case 0:
                   1091:                                /* child exited or completed auth */
1.345     djm      1092:                                close(startup_pipes[i]);
                   1093:                                startup_pipes[i] = -1;
                   1094:                                startups--;
1.533     djm      1095:                                if (startup_flags[i])
                   1096:                                        listening--;
                   1097:                                break;
                   1098:                        case 1:
                   1099:                                /* child has finished preliminaries */
                   1100:                                if (startup_flags[i]) {
                   1101:                                        listening--;
                   1102:                                        startup_flags[i] = 0;
                   1103:                                }
                   1104:                                break;
1.345     djm      1105:                        }
1.533     djm      1106:                }
1.345     djm      1107:                for (i = 0; i < num_listen_socks; i++) {
                   1108:                        if (!FD_ISSET(listen_socks[i], fdset))
                   1109:                                continue;
                   1110:                        fromlen = sizeof(from);
                   1111:                        *newsock = accept(listen_socks[i],
                   1112:                            (struct sockaddr *)&from, &fromlen);
1.537     deraadt  1113:                        if (*newsock == -1) {
1.398     markus   1114:                                if (errno != EINTR && errno != EWOULDBLOCK &&
                   1115:                                    errno != ECONNABORTED)
1.389     djm      1116:                                        error("accept: %.100s",
                   1117:                                            strerror(errno));
                   1118:                                if (errno == EMFILE || errno == ENFILE)
                   1119:                                        usleep(100 * 1000);
1.345     djm      1120:                                continue;
                   1121:                        }
                   1122:                        if (unset_nonblock(*newsock) == -1) {
                   1123:                                close(*newsock);
                   1124:                                continue;
                   1125:                        }
                   1126:                        if (drop_connection(startups) == 1) {
1.480     djm      1127:                                char *laddr = get_local_ipaddr(*newsock);
                   1128:                                char *raddr = get_peer_ipaddr(*newsock);
1.540     dtucker  1129:                                char msg[] = "Exceeded MaxStartups\r\n";
1.480     djm      1130:
                   1131:                                verbose("drop connection #%d from [%s]:%d "
                   1132:                                    "on [%s]:%d past MaxStartups", startups,
                   1133:                                    raddr, get_peer_port(*newsock),
                   1134:                                    laddr, get_local_port(*newsock));
                   1135:                                free(laddr);
                   1136:                                free(raddr);
1.540     dtucker  1137:                                /* best-effort notification to client */
                   1138:                                (void)write(*newsock, msg, strlen(msg));
1.345     djm      1139:                                close(*newsock);
                   1140:                                continue;
                   1141:                        }
                   1142:                        if (pipe(startup_p) == -1) {
                   1143:                                close(*newsock);
                   1144:                                continue;
                   1145:                        }
                   1146:
                   1147:                        if (rexec_flag && socketpair(AF_UNIX,
                   1148:                            SOCK_STREAM, 0, config_s) == -1) {
                   1149:                                error("reexec socketpair: %s",
                   1150:                                    strerror(errno));
                   1151:                                close(*newsock);
                   1152:                                close(startup_p[0]);
                   1153:                                close(startup_p[1]);
                   1154:                                continue;
                   1155:                        }
                   1156:
                   1157:                        for (j = 0; j < options.max_startups; j++)
                   1158:                                if (startup_pipes[j] == -1) {
                   1159:                                        startup_pipes[j] = startup_p[0];
                   1160:                                        if (maxfd < startup_p[0])
                   1161:                                                maxfd = startup_p[0];
                   1162:                                        startups++;
1.533     djm      1163:                                        startup_flags[j] = 1;
1.345     djm      1164:                                        break;
                   1165:                                }
                   1166:
                   1167:                        /*
                   1168:                         * Got connection.  Fork a child to handle it, unless
                   1169:                         * we are in debugging mode.
                   1170:                         */
                   1171:                        if (debug_flag) {
                   1172:                                /*
                   1173:                                 * In debugging mode.  Close the listening
                   1174:                                 * socket, and start processing the
                   1175:                                 * connection without forking.
                   1176:                                 */
                   1177:                                debug("Server will not fork when running in debugging mode.");
                   1178:                                close_listen_socks();
                   1179:                                *sock_in = *newsock;
                   1180:                                *sock_out = *newsock;
                   1181:                                close(startup_p[0]);
                   1182:                                close(startup_p[1]);
                   1183:                                startup_pipe = -1;
                   1184:                                pid = getpid();
                   1185:                                if (rexec_flag) {
1.511     markus   1186:                                        send_rexec_state(config_s[0], cfg);
1.345     djm      1187:                                        close(config_s[0]);
                   1188:                                }
1.533     djm      1189:                                return;
1.345     djm      1190:                        }
                   1191:
                   1192:                        /*
                   1193:                         * Normal production daemon.  Fork, and have
                   1194:                         * the child process the connection. The
                   1195:                         * parent continues listening.
                   1196:                         */
1.533     djm      1197:                        listening++;
1.345     djm      1198:                        if ((pid = fork()) == 0) {
                   1199:                                /*
                   1200:                                 * Child.  Close the listening and
                   1201:                                 * max_startup sockets.  Start using
                   1202:                                 * the accepted socket. Reinitialize
                   1203:                                 * logging (since our pid has changed).
1.533     djm      1204:                                 * We return from this function to handle
1.345     djm      1205:                                 * the connection.
                   1206:                                 */
                   1207:                                startup_pipe = startup_p[1];
                   1208:                                close_startup_pipes();
                   1209:                                close_listen_socks();
                   1210:                                *sock_in = *newsock;
                   1211:                                *sock_out = *newsock;
                   1212:                                log_init(__progname,
                   1213:                                    options.log_level,
                   1214:                                    options.log_facility,
                   1215:                                    log_stderr);
                   1216:                                if (rexec_flag)
                   1217:                                        close(config_s[0]);
1.533     djm      1218:                                else {
                   1219:                                        /*
                   1220:                                         * Signal parent that the preliminaries
                   1221:                                         * for this child are complete. For the
                   1222:                                         * re-exec case, this happens after the
                   1223:                                         * child has received the rexec state
                   1224:                                         * from the server.
                   1225:                                         */
                   1226:                                        (void)atomicio(vwrite, startup_pipe,
                   1227:                                            "\0", 1);
                   1228:                                }
                   1229:                                return;
1.345     djm      1230:                        }
                   1231:
                   1232:                        /* Parent.  Stay in the loop. */
1.537     deraadt  1233:                        if (pid == -1)
1.345     djm      1234:                                error("fork: %.100s", strerror(errno));
                   1235:                        else
                   1236:                                debug("Forked child %ld.", (long)pid);
                   1237:
                   1238:                        close(startup_p[1]);
                   1239:
                   1240:                        if (rexec_flag) {
1.511     markus   1241:                                send_rexec_state(config_s[0], cfg);
1.345     djm      1242:                                close(config_s[0]);
                   1243:                                close(config_s[1]);
                   1244:                        }
                   1245:                        close(*newsock);
                   1246:                }
                   1247:        }
                   1248: }
                   1249:
1.466     djm      1250: /*
                   1251:  * If IP options are supported, make sure there are none (log and
                   1252:  * return an error if any are found).  Basically we are worried about
                   1253:  * source routing; it can be used to pretend you are somebody
                   1254:  * (ip-address) you are not. That itself may be "almost acceptable"
1.507     djm      1255:  * under certain circumstances, but rhosts authentication is useless
1.466     djm      1256:  * if source routing is accepted. Notice also that if we just dropped
                   1257:  * source routing here, the other side could use IP spoofing to do
                   1258:  * rest of the interaction and could still bypass security.  So we
                   1259:  * exit here if we detect any IP options.
                   1260:  */
                   1261: static void
                   1262: check_ip_options(struct ssh *ssh)
                   1263: {
                   1264:        int sock_in = ssh_packet_get_connection_in(ssh);
                   1265:        struct sockaddr_storage from;
                   1266:        u_char opts[200];
1.475     djm      1267:        socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1.466     djm      1268:        char text[sizeof(opts) * 3 + 1];
                   1269:
                   1270:        memset(&from, 0, sizeof(from));
                   1271:        if (getpeername(sock_in, (struct sockaddr *)&from,
1.537     deraadt  1272:            &fromlen) == -1)
1.466     djm      1273:                return;
                   1274:        if (from.ss_family != AF_INET)
                   1275:                return;
                   1276:        /* XXX IPv6 options? */
                   1277:
                   1278:        if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
                   1279:            &option_size) >= 0 && option_size != 0) {
                   1280:                text[0] = '\0';
                   1281:                for (i = 0; i < option_size; i++)
                   1282:                        snprintf(text + i*3, sizeof(text) - i*3,
                   1283:                            " %2.2x", opts[i]);
                   1284:                fatal("Connection from %.100s port %d with IP opts: %.800s",
                   1285:                    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
                   1286:        }
                   1287:        return;
                   1288: }
1.345     djm      1289:
1.495     djm      1290: /* Set the routing domain for this process */
                   1291: static void
                   1292: set_process_rdomain(struct ssh *ssh, const char *name)
                   1293: {
                   1294:        int rtable, ortable = getrtable();
                   1295:        const char *errstr;
                   1296:
                   1297:        if (name == NULL)
                   1298:                return; /* default */
                   1299:
                   1300:        if (strcmp(name, "%D") == 0) {
                   1301:                /* "expands" to routing domain of connection */
                   1302:                if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
                   1303:                        return;
                   1304:        }
                   1305:
                   1306:        rtable = (int)strtonum(name, 0, 255, &errstr);
                   1307:        if (errstr != NULL) /* Shouldn't happen */
                   1308:                fatal("Invalid routing domain \"%s\": %s", name, errstr);
                   1309:        if (rtable != ortable && setrtable(rtable) != 0)
                   1310:                fatal("Unable to set routing domain %d: %s",
                   1311:                    rtable, strerror(errno));
                   1312:        debug("%s: set routing domain %d (was %d)", __func__, rtable, ortable);
                   1313: }
                   1314:
1.508     dtucker  1315: static void
                   1316: accumulate_host_timing_secret(struct sshbuf *server_cfg,
1.536     djm      1317:     struct sshkey *key)
1.508     dtucker  1318: {
                   1319:        static struct ssh_digest_ctx *ctx;
                   1320:        u_char *hash;
                   1321:        size_t len;
                   1322:        struct sshbuf *buf;
                   1323:        int r;
                   1324:
                   1325:        if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL)
                   1326:                fatal("%s: ssh_digest_start", __func__);
                   1327:        if (key == NULL) { /* finalize */
                   1328:                /* add server config in case we are using agent for host keys */
                   1329:                if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg),
                   1330:                    sshbuf_len(server_cfg)) != 0)
                   1331:                        fatal("%s: ssh_digest_update", __func__);
                   1332:                len = ssh_digest_bytes(SSH_DIGEST_SHA512);
                   1333:                hash = xmalloc(len);
                   1334:                if (ssh_digest_final(ctx, hash, len) != 0)
                   1335:                        fatal("%s: ssh_digest_final", __func__);
                   1336:                options.timing_secret = PEEK_U64(hash);
                   1337:                freezero(hash, len);
                   1338:                ssh_digest_free(ctx);
                   1339:                ctx = NULL;
                   1340:                return;
                   1341:        }
                   1342:        if ((buf = sshbuf_new()) == NULL)
                   1343:                fatal("%s could not allocate buffer", __func__);
                   1344:        if ((r = sshkey_private_serialize(key, buf)) != 0)
                   1345:                fatal("sshkey_private_serialize: %s", ssh_err(r));
                   1346:        if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0)
                   1347:                fatal("%s: ssh_digest_update", __func__);
                   1348:        sshbuf_reset(buf);
                   1349:        sshbuf_free(buf);
                   1350: }
                   1351:
1.545   ! djm      1352: static char *
        !          1353: prepare_proctitle(int ac, char **av)
        !          1354: {
        !          1355:        char *ret = NULL;
        !          1356:        int i;
        !          1357:
        !          1358:        for (i = 0; i < ac; i++)
        !          1359:                xextendf(&ret, " ", "%s", av[i]);
        !          1360:        return ret;
        !          1361: }
        !          1362:
1.65      deraadt  1363: /*
                   1364:  * Main program for the daemon.
                   1365:  */
1.2       provos   1366: int
                   1367: main(int ac, char **av)
1.1       deraadt  1368: {
1.466     djm      1369:        struct ssh *ssh = NULL;
1.64      markus   1370:        extern char *optarg;
                   1371:        extern int optind;
1.493     djm      1372:        int r, opt, on = 1, already_daemon, remote_port;
1.297     avsm     1373:        int sock_in = -1, sock_out = -1, newsock = -1;
1.496     djm      1374:        const char *remote_ip, *rdomain;
1.447     dtucker  1375:        char *fp, *line, *laddr, *logfile = NULL;
1.345     djm      1376:        int config_s[2] = { -1 , -1 };
1.493     djm      1377:        u_int i, j;
1.364     markus   1378:        u_int64_t ibytes, obytes;
1.362     dtucker  1379:        mode_t new_umask;
1.488     markus   1380:        struct sshkey *key;
                   1381:        struct sshkey *pubkey;
1.404     markus   1382:        int keytype;
1.230     provos   1383:        Authctxt *authctxt;
1.498     dtucker  1384:        struct connection_info *connection_info = NULL;
1.64      markus   1385:
1.138     markus   1386:        /* Save argv. */
1.64      markus   1387:        saved_argv = av;
1.294     djm      1388:        rexec_argc = ac;
1.313     djm      1389:
                   1390:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                   1391:        sanitise_stdfd();
1.64      markus   1392:
                   1393:        /* Initialize configuration options to their default values. */
                   1394:        initialize_server_options(&options);
                   1395:
                   1396:        /* Parse command-line arguments. */
1.450     djm      1397:        while ((opt = getopt(ac, av,
                   1398:            "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1.64      markus   1399:                switch (opt) {
1.75      markus   1400:                case '4':
1.305     djm      1401:                        options.address_family = AF_INET;
1.75      markus   1402:                        break;
                   1403:                case '6':
1.305     djm      1404:                        options.address_family = AF_INET6;
1.75      markus   1405:                        break;
1.64      markus   1406:                case 'f':
                   1407:                        config_file_name = optarg;
                   1408:                        break;
1.373     djm      1409:                case 'c':
1.493     djm      1410:                        servconf_add_hostcert("[command-line]", 0,
                   1411:                            &options, optarg);
1.373     djm      1412:                        break;
1.64      markus   1413:                case 'd':
1.273     markus   1414:                        if (debug_flag == 0) {
1.127     markus   1415:                                debug_flag = 1;
                   1416:                                options.log_level = SYSLOG_LEVEL_DEBUG1;
1.273     markus   1417:                        } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1.127     markus   1418:                                options.log_level++;
1.64      markus   1419:                        break;
1.135     markus   1420:                case 'D':
                   1421:                        no_daemon_flag = 1;
1.192     lebel    1422:                        break;
1.399     dtucker  1423:                case 'E':
1.459     dtucker  1424:                        logfile = optarg;
1.399     dtucker  1425:                        /* FALLTHROUGH */
1.192     lebel    1426:                case 'e':
                   1427:                        log_stderr = 1;
1.135     markus   1428:                        break;
1.64      markus   1429:                case 'i':
                   1430:                        inetd_flag = 1;
                   1431:                        break;
1.294     djm      1432:                case 'r':
                   1433:                        rexec_flag = 0;
                   1434:                        break;
                   1435:                case 'R':
                   1436:                        rexeced_flag = 1;
                   1437:                        inetd_flag = 1;
                   1438:                        break;
1.64      markus   1439:                case 'Q':
1.158     markus   1440:                        /* ignored */
1.64      markus   1441:                        break;
                   1442:                case 'q':
                   1443:                        options.log_level = SYSLOG_LEVEL_QUIET;
                   1444:                        break;
                   1445:                case 'b':
1.473     naddy    1446:                        /* protocol 1, ignored */
1.64      markus   1447:                        break;
                   1448:                case 'p':
1.75      markus   1449:                        options.ports_from_cmdline = 1;
1.127     markus   1450:                        if (options.num_ports >= MAX_PORTS) {
                   1451:                                fprintf(stderr, "too many ports.\n");
                   1452:                                exit(1);
                   1453:                        }
1.193     stevesk  1454:                        options.ports[options.num_ports++] = a2port(optarg);
1.366     djm      1455:                        if (options.ports[options.num_ports-1] <= 0) {
1.193     stevesk  1456:                                fprintf(stderr, "Bad port number.\n");
                   1457:                                exit(1);
                   1458:                        }
1.64      markus   1459:                        break;
                   1460:                case 'g':
1.197     stevesk  1461:                        if ((options.login_grace_time = convtime(optarg)) == -1) {
                   1462:                                fprintf(stderr, "Invalid login grace time.\n");
                   1463:                                exit(1);
                   1464:                        }
1.64      markus   1465:                        break;
                   1466:                case 'k':
1.473     naddy    1467:                        /* protocol 1, ignored */
1.64      markus   1468:                        break;
                   1469:                case 'h':
1.493     djm      1470:                        servconf_add_hostkey("[command-line]", 0,
1.519     djm      1471:                            &options, optarg, 1);
1.64      markus   1472:                        break;
1.203     stevesk  1473:                case 't':
                   1474:                        test_flag = 1;
                   1475:                        break;
1.358     dtucker  1476:                case 'T':
                   1477:                        test_flag = 2;
                   1478:                        break;
                   1479:                case 'C':
1.523     djm      1480:                        connection_info = get_connection_info(ssh, 0, 0);
1.391     dtucker  1481:                        if (parse_server_match_testspec(connection_info,
                   1482:                            optarg) == -1)
                   1483:                                exit(1);
1.358     dtucker  1484:                        break;
1.125     markus   1485:                case 'u':
1.438     deraadt  1486:                        utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
                   1487:                        if (utmp_len > HOST_NAME_MAX+1) {
1.257     stevesk  1488:                                fprintf(stderr, "Invalid utmp length.\n");
                   1489:                                exit(1);
                   1490:                        }
1.125     markus   1491:                        break;
1.215     markus   1492:                case 'o':
1.283     markus   1493:                        line = xstrdup(optarg);
                   1494:                        if (process_server_config_line(&options, line,
1.391     dtucker  1495:                            "command-line", 0, NULL, NULL) != 0)
1.217     deraadt  1496:                                exit(1);
1.402     djm      1497:                        free(line);
1.215     markus   1498:                        break;
1.64      markus   1499:                case '?':
                   1500:                default:
1.215     markus   1501:                        usage();
                   1502:                        break;
1.64      markus   1503:                }
                   1504:        }
1.294     djm      1505:        if (rexeced_flag || inetd_flag)
                   1506:                rexec_flag = 0;
1.518     djm      1507:        if (!test_flag && rexec_flag && !path_absolute(av[0]))
1.294     djm      1508:                fatal("sshd re-exec requires execution with an absolute path");
                   1509:        if (rexeced_flag)
1.296     djm      1510:                closefrom(REEXEC_MIN_FREE_FD);
                   1511:        else
                   1512:                closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1.294     djm      1513:
1.426     markus   1514: #ifdef WITH_OPENSSL
1.379     djm      1515:        OpenSSL_add_all_algorithms();
1.426     markus   1516: #endif
1.64      markus   1517:
1.399     dtucker  1518:        /* If requested, redirect the logs to the specified logfile. */
1.459     dtucker  1519:        if (logfile != NULL)
1.399     dtucker  1520:                log_redirect_stderr_to(logfile);
1.75      markus   1521:        /*
                   1522:         * Force logging to stderr until we have loaded the private host
                   1523:         * key (unless started from inetd)
                   1524:         */
1.138     markus   1525:        log_init(__progname,
1.224     markus   1526:            options.log_level == SYSLOG_LEVEL_NOT_SET ?
                   1527:            SYSLOG_LEVEL_INFO : options.log_level,
                   1528:            options.log_facility == SYSLOG_FACILITY_NOT_SET ?
                   1529:            SYSLOG_FACILITY_AUTH : options.log_facility,
1.261     markus   1530:            log_stderr || !inetd_flag);
1.75      markus   1531:
1.294     djm      1532:        sensitive_data.have_ssh2_key = 0;
                   1533:
1.358     dtucker  1534:        /*
1.498     dtucker  1535:         * If we're not doing an extended test do not silently ignore connection
                   1536:         * test params.
1.358     dtucker  1537:         */
1.498     dtucker  1538:        if (test_flag < 2 && connection_info != NULL)
1.358     dtucker  1539:                fatal("Config test connection parameter (-C) provided without "
                   1540:                   "test mode (-T)");
                   1541:
1.294     djm      1542:        /* Fetch our configuration */
1.511     markus   1543:        if ((cfg = sshbuf_new()) == NULL)
                   1544:                fatal("%s: sshbuf_new failed", __func__);
1.533     djm      1545:        if (rexeced_flag) {
1.511     markus   1546:                recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg);
1.533     djm      1547:                if (!debug_flag) {
                   1548:                        startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
                   1549:                        close(REEXEC_STARTUP_PIPE_FD);
                   1550:                        /*
                   1551:                         * Signal parent that this child is at a point where
                   1552:                         * they can go away if they have a SIGHUP pending.
                   1553:                         */
                   1554:                        (void)atomicio(vwrite, startup_pipe, "\0", 1);
                   1555:                }
                   1556:        }
1.448     djm      1557:        else if (strcasecmp(config_file_name, "none") != 0)
1.511     markus   1558:                load_server_config(config_file_name, cfg);
1.294     djm      1559:
1.337     dtucker  1560:        parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1.511     markus   1561:            cfg, NULL);
1.64      markus   1562:
                   1563:        /* Fill in default values for those options not explicitly set. */
                   1564:        fill_default_server_options(&options);
1.350     dtucker  1565:
                   1566:        /* challenge-response is implemented via keyboard interactive */
                   1567:        if (options.challenge_response_authentication)
                   1568:                options.kbd_interactive_authentication = 1;
1.395     djm      1569:
                   1570:        /* Check that options are sensible */
                   1571:        if (options.authorized_keys_command_user == NULL &&
                   1572:            (options.authorized_keys_command != NULL &&
                   1573:            strcasecmp(options.authorized_keys_command, "none") != 0))
                   1574:                fatal("AuthorizedKeysCommand set without "
                   1575:                    "AuthorizedKeysCommandUser");
1.449     djm      1576:        if (options.authorized_principals_command_user == NULL &&
                   1577:            (options.authorized_principals_command != NULL &&
                   1578:            strcasecmp(options.authorized_principals_command, "none") != 0))
                   1579:                fatal("AuthorizedPrincipalsCommand set without "
                   1580:                    "AuthorizedPrincipalsCommandUser");
1.396     djm      1581:
                   1582:        /*
                   1583:         * Check whether there is any path through configured auth methods.
                   1584:         * Unfortunately it is not possible to verify this generally before
                   1585:         * daemonisation in the presence of Match block, but this catches
                   1586:         * and warns for trivial misconfigurations that could break login.
                   1587:         */
                   1588:        if (options.num_auth_methods != 0) {
1.493     djm      1589:                for (i = 0; i < options.num_auth_methods; i++) {
                   1590:                        if (auth2_methods_valid(options.auth_methods[i],
1.396     djm      1591:                            1) == 0)
                   1592:                                break;
                   1593:                }
1.493     djm      1594:                if (i >= options.num_auth_methods)
1.396     djm      1595:                        fatal("AuthenticationMethods cannot be satisfied by "
                   1596:                            "enabled authentication methods");
                   1597:        }
1.305     djm      1598:
1.64      markus   1599:        /* Check that there are no remaining arguments. */
                   1600:        if (optind < ac) {
                   1601:                fprintf(stderr, "Extra argument %s.\n", av[optind]);
                   1602:                exit(1);
                   1603:        }
                   1604:
1.397     dtucker  1605:        debug("sshd version %s, %s", SSH_VERSION,
1.426     markus   1606: #ifdef WITH_OPENSSL
1.517     djm      1607:            OpenSSL_version(OPENSSL_VERSION)
1.426     markus   1608: #else
                   1609:            "without OpenSSL"
                   1610: #endif
                   1611:        );
1.64      markus   1612:
1.404     markus   1613:        /* load host keys */
1.329     djm      1614:        sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1.488     markus   1615:            sizeof(struct sshkey *));
1.404     markus   1616:        sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1.488     markus   1617:            sizeof(struct sshkey *));
1.404     markus   1618:
                   1619:        if (options.host_key_agent) {
                   1620:                if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
                   1621:                        setenv(SSH_AUTHSOCKET_ENV_NAME,
                   1622:                            options.host_key_agent, 1);
1.433     djm      1623:                if ((r = ssh_get_authentication_socket(NULL)) == 0)
                   1624:                        have_agent = 1;
                   1625:                else
                   1626:                        error("Could not connect to agent \"%s\": %s",
                   1627:                            options.host_key_agent, ssh_err(r));
1.404     markus   1628:        }
1.134     markus   1629:
1.217     deraadt  1630:        for (i = 0; i < options.num_host_key_files; i++) {
1.519     djm      1631:                int ll = options.host_key_file_userprovided[i] ?
                   1632:                    SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_DEBUG1;
                   1633:
1.430     djm      1634:                if (options.host_key_files[i] == NULL)
                   1635:                        continue;
1.512     markus   1636:                if ((r = sshkey_load_private(options.host_key_files[i], "",
                   1637:                    &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1.519     djm      1638:                        do_log2(ll, "Unable to load host key \"%s\": %s",
1.512     markus   1639:                            options.host_key_files[i], ssh_err(r));
1.542     djm      1640:                if (sshkey_is_sk(key) &&
                   1641:                    key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
                   1642:                        debug("host key %s requires user presence, ignoring",
                   1643:                            options.host_key_files[i]);
                   1644:                        key->sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
                   1645:                }
                   1646:                if (r == 0 && key != NULL &&
                   1647:                    (r = sshkey_shield_private(key)) != 0) {
1.536     djm      1648:                        do_log2(ll, "Unable to shield host key \"%s\": %s",
                   1649:                            options.host_key_files[i], ssh_err(r));
                   1650:                        sshkey_free(key);
                   1651:                        key = NULL;
                   1652:                }
1.512     markus   1653:                if ((r = sshkey_load_public(options.host_key_files[i],
                   1654:                    &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1.519     djm      1655:                        do_log2(ll, "Unable to load host key \"%s\": %s",
1.512     markus   1656:                            options.host_key_files[i], ssh_err(r));
1.439     djm      1657:                if (pubkey == NULL && key != NULL)
1.515     djm      1658:                        if ((r = sshkey_from_private(key, &pubkey)) != 0)
1.512     markus   1659:                                fatal("Could not demote key: \"%s\": %s",
                   1660:                                    options.host_key_files[i], ssh_err(r));
1.179     markus   1661:                sensitive_data.host_keys[i] = key;
1.404     markus   1662:                sensitive_data.host_pubkeys[i] = pubkey;
                   1663:
1.472     markus   1664:                if (key == NULL && pubkey != NULL && have_agent) {
1.443     djm      1665:                        debug("will rely on agent for hostkey %s",
                   1666:                            options.host_key_files[i]);
1.404     markus   1667:                        keytype = pubkey->type;
                   1668:                } else if (key != NULL) {
                   1669:                        keytype = key->type;
1.511     markus   1670:                        accumulate_host_timing_secret(cfg, key);
1.404     markus   1671:                } else {
1.519     djm      1672:                        do_log2(ll, "Unable to load host key: %s",
1.195     markus   1673:                            options.host_key_files[i]);
1.179     markus   1674:                        sensitive_data.host_keys[i] = NULL;
1.404     markus   1675:                        sensitive_data.host_pubkeys[i] = NULL;
1.134     markus   1676:                        continue;
                   1677:                }
1.404     markus   1678:
                   1679:                switch (keytype) {
1.134     markus   1680:                case KEY_RSA:
                   1681:                case KEY_DSA:
1.378     djm      1682:                case KEY_ECDSA:
1.412     markus   1683:                case KEY_ED25519:
1.542     djm      1684:                case KEY_ECDSA_SK:
                   1685:                case KEY_ED25519_SK:
1.505     markus   1686:                case KEY_XMSS:
1.441     djm      1687:                        if (have_agent || key != NULL)
                   1688:                                sensitive_data.have_ssh2_key = 1;
1.134     markus   1689:                        break;
                   1690:                }
1.441     djm      1691:                if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
                   1692:                    SSH_FP_DEFAULT)) == NULL)
                   1693:                        fatal("sshkey_fingerprint failed");
                   1694:                debug("%s host key #%d: %s %s",
1.472     markus   1695:                    key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1.441     djm      1696:                free(fp);
1.134     markus   1697:        }
1.511     markus   1698:        accumulate_host_timing_secret(cfg, NULL);
1.472     markus   1699:        if (!sensitive_data.have_ssh2_key) {
1.264     itojun   1700:                logit("sshd: no hostkeys available -- exiting.");
1.64      markus   1701:                exit(1);
                   1702:        }
                   1703:
1.373     djm      1704:        /*
                   1705:         * Load certificates. They are stored in an array at identical
                   1706:         * indices to the public keys that they relate to.
                   1707:         */
                   1708:        sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1.488     markus   1709:            sizeof(struct sshkey *));
1.373     djm      1710:        for (i = 0; i < options.num_host_key_files; i++)
                   1711:                sensitive_data.host_certificates[i] = NULL;
                   1712:
                   1713:        for (i = 0; i < options.num_host_cert_files; i++) {
1.430     djm      1714:                if (options.host_cert_files[i] == NULL)
                   1715:                        continue;
1.512     markus   1716:                if ((r = sshkey_load_public(options.host_cert_files[i],
                   1717:                    &key, NULL)) != 0) {
                   1718:                        error("Could not load host certificate \"%s\": %s",
                   1719:                            options.host_cert_files[i], ssh_err(r));
1.373     djm      1720:                        continue;
                   1721:                }
1.512     markus   1722:                if (!sshkey_is_cert(key)) {
1.373     djm      1723:                        error("Certificate file is not a certificate: %s",
                   1724:                            options.host_cert_files[i]);
1.512     markus   1725:                        sshkey_free(key);
1.373     djm      1726:                        continue;
                   1727:                }
                   1728:                /* Find matching private key */
                   1729:                for (j = 0; j < options.num_host_key_files; j++) {
1.512     markus   1730:                        if (sshkey_equal_public(key,
1.373     djm      1731:                            sensitive_data.host_keys[j])) {
                   1732:                                sensitive_data.host_certificates[j] = key;
                   1733:                                break;
                   1734:                        }
                   1735:                }
                   1736:                if (j >= options.num_host_key_files) {
                   1737:                        error("No matching private key for certificate: %s",
                   1738:                            options.host_cert_files[i]);
1.512     markus   1739:                        sshkey_free(key);
1.373     djm      1740:                        continue;
                   1741:                }
                   1742:                sensitive_data.host_certificates[j] = key;
1.493     djm      1743:                debug("host certificate: #%u type %d %s", j, key->type,
1.512     markus   1744:                    sshkey_type(key));
1.373     djm      1745:        }
1.426     markus   1746:
1.244     markus   1747:        if (use_privsep) {
                   1748:                struct stat st;
                   1749:
1.327     deraadt  1750:                if (getpwnam(SSH_PRIVSEP_USER) == NULL)
1.244     markus   1751:                        fatal("Privilege separation user %s does not exist",
                   1752:                            SSH_PRIVSEP_USER);
1.500     djm      1753:                endpwent();
1.244     markus   1754:                if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
                   1755:                    (S_ISDIR(st.st_mode) == 0))
                   1756:                        fatal("Missing privilege separation directory: %s",
1.247     stevesk  1757:                            _PATH_PRIVSEP_CHROOT_DIR);
                   1758:                if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1.262     markus   1759:                        fatal("%s must be owned by root and not group or "
                   1760:                            "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1.358     dtucker  1761:        }
                   1762:
                   1763:        if (test_flag > 1) {
1.499     djm      1764:                /*
                   1765:                 * If no connection info was provided by -C then use
                   1766:                 * use a blank one that will cause no predicate to match.
                   1767:                 */
                   1768:                if (connection_info == NULL)
1.523     djm      1769:                        connection_info = get_connection_info(ssh, 0, 0);
1.534     dtucker  1770:                connection_info->test = 1;
1.498     dtucker  1771:                parse_server_match_config(&options, connection_info);
1.358     dtucker  1772:                dump_config(&options);
1.108     markus   1773:        }
1.203     stevesk  1774:
                   1775:        /* Configuration looks good, so exit if in test mode. */
                   1776:        if (test_flag)
                   1777:                exit(0);
1.108     markus   1778:
1.294     djm      1779:        if (rexec_flag) {
1.493     djm      1780:                if (rexec_argc < 0)
                   1781:                        fatal("rexec_argc %d < 0", rexec_argc);
1.329     djm      1782:                rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1.493     djm      1783:                for (i = 0; i < (u_int)rexec_argc; i++) {
1.294     djm      1784:                        debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
                   1785:                        rexec_argv[i] = saved_argv[i];
                   1786:                }
                   1787:                rexec_argv[rexec_argc] = "-R";
                   1788:                rexec_argv[rexec_argc + 1] = NULL;
                   1789:        }
1.545   ! djm      1790:        listener_proctitle = prepare_proctitle(ac, av);
1.362     dtucker  1791:
                   1792:        /* Ensure that umask disallows at least group and world write */
                   1793:        new_umask = umask(0077) | 0022;
                   1794:        (void) umask(new_umask);
1.294     djm      1795:
1.108     markus   1796:        /* Initialize the log (it is reinitialized below in case we forked). */
1.306     dtucker  1797:        if (debug_flag && (!inetd_flag || rexeced_flag))
1.64      markus   1798:                log_stderr = 1;
1.138     markus   1799:        log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64      markus   1800:
1.108     markus   1801:        /*
1.478     dtucker  1802:         * If not in debugging mode, not started from inetd and not already
                   1803:         * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
                   1804:         * terminal, and fork.  The original process exits.
1.108     markus   1805:         */
1.478     dtucker  1806:        already_daemon = daemonized();
                   1807:        if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
1.345     djm      1808:
1.537     deraadt  1809:                if (daemon(0, 0) == -1)
1.64      markus   1810:                        fatal("daemon() failed: %.200s", strerror(errno));
                   1811:
1.477     dtucker  1812:                disconnect_controlling_tty();
1.64      markus   1813:        }
                   1814:        /* Reinitialize the log (because of the fork above). */
1.138     markus   1815:        log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64      markus   1816:
                   1817:        /* Chdir to the root directory so that the current disk can be
                   1818:           unmounted if desired. */
1.401     dtucker  1819:        if (chdir("/") == -1)
                   1820:                error("chdir(\"/\"): %s", strerror(errno));
1.217     deraadt  1821:
1.178     markus   1822:        /* ignore SIGPIPE */
1.544     dtucker  1823:        ssh_signal(SIGPIPE, SIG_IGN);
1.64      markus   1824:
1.345     djm      1825:        /* Get a connection, either from inetd or a listening TCP socket */
1.64      markus   1826:        if (inetd_flag) {
1.345     djm      1827:                server_accept_inetd(&sock_in, &sock_out);
1.64      markus   1828:        } else {
1.345     djm      1829:                server_listen();
1.75      markus   1830:
1.544     dtucker  1831:                ssh_signal(SIGHUP, sighup_handler);
                   1832:                ssh_signal(SIGCHLD, main_sigchld_handler);
                   1833:                ssh_signal(SIGTERM, sigterm_handler);
                   1834:                ssh_signal(SIGQUIT, sigterm_handler);
1.201     markus   1835:
1.345     djm      1836:                /*
                   1837:                 * Write out the pid file after the sigterm handler
                   1838:                 * is setup and the listen sockets are bound
                   1839:                 */
1.479     dtucker  1840:                if (options.pid_file != NULL && !debug_flag) {
1.345     djm      1841:                        FILE *f = fopen(options.pid_file, "w");
1.201     markus   1842:
1.270     djm      1843:                        if (f == NULL) {
                   1844:                                error("Couldn't create pid file \"%s\": %s",
                   1845:                                    options.pid_file, strerror(errno));
                   1846:                        } else {
1.245     mpech    1847:                                fprintf(f, "%ld\n", (long) getpid());
1.64      markus   1848:                                fclose(f);
                   1849:                        }
                   1850:                }
                   1851:
1.345     djm      1852:                /* Accept a connection and return in a forked child */
                   1853:                server_accept_loop(&sock_in, &sock_out,
                   1854:                    &newsock, config_s);
1.1       deraadt  1855:        }
                   1856:
1.64      markus   1857:        /* This is the child processing a new connection. */
1.288     markus   1858:        setproctitle("%s", "[accepted]");
1.294     djm      1859:
1.300     markus   1860:        /*
                   1861:         * Create a new session and process group since the 4.4BSD
                   1862:         * setlogin() affects the entire process group.  We don't
                   1863:         * want the child to be able to affect the parent.
                   1864:         */
1.537     deraadt  1865:        if (!debug_flag && !inetd_flag && setsid() == -1)
1.300     markus   1866:                error("setsid: %.100s", strerror(errno));
                   1867:
1.294     djm      1868:        if (rexec_flag) {
                   1869:                int fd;
                   1870:
1.296     djm      1871:                debug("rexec start in %d out %d newsock %d pipe %d sock %d",
                   1872:                    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1.294     djm      1873:                dup2(newsock, STDIN_FILENO);
                   1874:                dup2(STDIN_FILENO, STDOUT_FILENO);
                   1875:                if (startup_pipe == -1)
1.296     djm      1876:                        close(REEXEC_STARTUP_PIPE_FD);
1.407     djm      1877:                else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
1.296     djm      1878:                        dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1.407     djm      1879:                        close(startup_pipe);
                   1880:                        startup_pipe = REEXEC_STARTUP_PIPE_FD;
                   1881:                }
1.294     djm      1882:
1.296     djm      1883:                dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1.294     djm      1884:                close(config_s[1]);
1.296     djm      1885:
1.294     djm      1886:                execv(rexec_argv[0], rexec_argv);
                   1887:
                   1888:                /* Reexec has failed, fall back and continue */
                   1889:                error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1.296     djm      1890:                recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1.294     djm      1891:                log_init(__progname, options.log_level,
                   1892:                    options.log_facility, log_stderr);
                   1893:
                   1894:                /* Clean up fds */
1.296     djm      1895:                close(REEXEC_CONFIG_PASS_FD);
                   1896:                newsock = sock_out = sock_in = dup(STDIN_FILENO);
1.294     djm      1897:                if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
                   1898:                        dup2(fd, STDIN_FILENO);
                   1899:                        dup2(fd, STDOUT_FILENO);
                   1900:                        if (fd > STDERR_FILENO)
                   1901:                                close(fd);
                   1902:                }
1.296     djm      1903:                debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
                   1904:                    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1.294     djm      1905:        }
1.372     djm      1906:
                   1907:        /* Executed child processes don't need these. */
                   1908:        fcntl(sock_out, F_SETFD, FD_CLOEXEC);
                   1909:        fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1.64      markus   1910:
1.66      markus   1911:        /*
                   1912:         * Disable the key regeneration alarm.  We will not regenerate the
                   1913:         * key since we are no longer in a position to give it to anyone. We
                   1914:         * will not restart on SIGHUP since it no longer makes sense.
                   1915:         */
1.64      markus   1916:        alarm(0);
1.544     dtucker  1917:        ssh_signal(SIGALRM, SIG_DFL);
                   1918:        ssh_signal(SIGHUP, SIG_DFL);
                   1919:        ssh_signal(SIGTERM, SIG_DFL);
                   1920:        ssh_signal(SIGQUIT, SIG_DFL);
                   1921:        ssh_signal(SIGCHLD, SIG_DFL);
1.150     markus   1922:
1.66      markus   1923:        /*
                   1924:         * Register our connection.  This turns encryption off because we do
                   1925:         * not have a key.
                   1926:         */
1.525     djm      1927:        if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL)
                   1928:                fatal("Unable to create connection");
1.527     djm      1929:        the_active_state = ssh;
1.525     djm      1930:        ssh_packet_set_server(ssh);
1.492     djm      1931:
1.466     djm      1932:        check_ip_options(ssh);
1.309     djm      1933:
1.492     djm      1934:        /* Prepare the channels layer */
                   1935:        channel_init_channels(ssh);
                   1936:        channel_set_af(ssh, options.address_family);
                   1937:        process_permitopen(ssh, &options);
                   1938:
1.309     djm      1939:        /* Set SO_KEEPALIVE if requested. */
1.525     djm      1940:        if (options.tcp_keep_alive && ssh_packet_connection_is_on_socket(ssh) &&
1.537     deraadt  1941:            setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) == -1)
1.309     djm      1942:                error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1.1       deraadt  1943:
1.466     djm      1944:        if ((remote_port = ssh_remote_port(ssh)) < 0) {
                   1945:                debug("ssh_remote_port failed");
1.310     markus   1946:                cleanup_exit(255);
                   1947:        }
1.316     dtucker  1948:
                   1949:        /*
1.331     markus   1950:         * The rest of the code depends on the fact that
1.466     djm      1951:         * ssh_remote_ipaddr() caches the remote ip, even if
1.331     markus   1952:         * the socket goes away.
                   1953:         */
1.466     djm      1954:        remote_ip = ssh_remote_ipaddr(ssh);
1.209     markus   1955:
1.496     djm      1956:        rdomain = ssh_packet_rdomain_in(ssh);
                   1957:
1.64      markus   1958:        /* Log the connection. */
1.447     dtucker  1959:        laddr = get_local_ipaddr(sock_in);
1.497     djm      1960:        verbose("Connection from %s port %d on %s port %d%s%s%s",
1.496     djm      1961:            remote_ip, remote_port, laddr,  ssh_local_port(ssh),
1.497     djm      1962:            rdomain == NULL ? "" : " rdomain \"",
                   1963:            rdomain == NULL ? "" : rdomain,
                   1964:            rdomain == NULL ? "" : "\"");
1.447     dtucker  1965:        free(laddr);
1.1       deraadt  1966:
1.66      markus   1967:        /*
1.317     djm      1968:         * We don't want to listen forever unless the other side
1.66      markus   1969:         * successfully authenticates itself.  So we set up an alarm which is
                   1970:         * cleared after successful authentication.  A limit of zero
1.317     djm      1971:         * indicates no limit. Note that we don't set the alarm in debugging
1.66      markus   1972:         * mode; it is just annoying to have the server exit just when you
                   1973:         * are about to discover the bug.
                   1974:         */
1.544     dtucker  1975:        ssh_signal(SIGALRM, grace_alarm_handler);
1.64      markus   1976:        if (!debug_flag)
                   1977:                alarm(options.login_grace_time);
                   1978:
1.520     djm      1979:        if (kex_exchange_identification(ssh, -1, options.version_addendum) != 0)
                   1980:                cleanup_exit(255); /* error already logged */
                   1981:
1.525     djm      1982:        ssh_packet_set_nonblocking(ssh);
1.1       deraadt  1983:
1.278     markus   1984:        /* allocate authentication context */
1.329     djm      1985:        authctxt = xcalloc(1, sizeof(*authctxt));
1.525     djm      1986:        ssh->authctxt = authctxt;
1.278     markus   1987:
                   1988:        /* XXX global for cleanup, access from other modules */
                   1989:        the_authctxt = authctxt;
1.506     djm      1990:
                   1991:        /* Set default key authentication options */
                   1992:        if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
                   1993:                fatal("allocation failed");
1.278     markus   1994:
1.307     otto     1995:        /* prepare buffer to collect messages to display to user after login */
1.510     markus   1996:        if ((loginmsg = sshbuf_new()) == NULL)
                   1997:                fatal("%s: sshbuf_new failed", __func__);
1.374     dtucker  1998:        auth_debug_reset();
1.307     otto     1999:
1.404     markus   2000:        if (use_privsep) {
1.525     djm      2001:                if (privsep_preauth(ssh) == 1)
1.237     markus   2002:                        goto authenticated;
1.472     markus   2003:        } else if (have_agent) {
1.432     djm      2004:                if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
                   2005:                        error("Unable to get agent socket: %s", ssh_err(r));
1.433     djm      2006:                        have_agent = 0;
1.432     djm      2007:                }
                   2008:        }
1.231     provos   2009:
1.77      markus   2010:        /* perform the key exchange */
                   2011:        /* authenticate user and start session */
1.525     djm      2012:        do_ssh2_kex(ssh);
1.524     djm      2013:        do_authentication2(ssh);
1.472     markus   2014:
1.237     markus   2015:        /*
                   2016:         * If we use privilege separation, the unprivileged child transfers
                   2017:         * the current keystate and exits
                   2018:         */
                   2019:        if (use_privsep) {
1.527     djm      2020:                mm_send_keystate(ssh, pmonitor);
1.525     djm      2021:                ssh_packet_clear_keys(ssh);
1.231     provos   2022:                exit(0);
1.237     markus   2023:        }
1.231     provos   2024:
                   2025:  authenticated:
1.318     djm      2026:        /*
                   2027:         * Cancel the alarm we set to limit the time taken for
                   2028:         * authentication.
                   2029:         */
                   2030:        alarm(0);
1.544     dtucker  2031:        ssh_signal(SIGALRM, SIG_DFL);
1.347     markus   2032:        authctxt->authenticated = 1;
1.318     djm      2033:        if (startup_pipe != -1) {
                   2034:                close(startup_pipe);
                   2035:                startup_pipe = -1;
                   2036:        }
1.495     djm      2037:
                   2038:        if (options.routing_domain != NULL)
                   2039:                set_process_rdomain(ssh, options.routing_domain);
1.318     djm      2040:
1.234     markus   2041:        /*
1.231     provos   2042:         * In privilege separation, we fork another child and prepare
                   2043:         * file descriptor passing.
                   2044:         */
                   2045:        if (use_privsep) {
1.525     djm      2046:                privsep_postauth(ssh, authctxt);
1.237     markus   2047:                /* the monitor process [priv] will not return */
1.231     provos   2048:        }
1.360     dtucker  2049:
1.525     djm      2050:        ssh_packet_set_timeout(ssh, options.client_alive_interval,
1.360     dtucker  2051:            options.client_alive_count_max);
1.439     djm      2052:
                   2053:        /* Try to send all our hostkeys to the client */
1.492     djm      2054:        notify_hostkeys(ssh);
1.230     provos   2055:
1.278     markus   2056:        /* Start session. */
1.492     djm      2057:        do_authenticated(ssh, authctxt);
1.230     provos   2058:
1.64      markus   2059:        /* The connection has been terminated. */
1.525     djm      2060:        ssh_packet_get_bytes(ssh, &ibytes, &obytes);
1.381     djm      2061:        verbose("Transferred: sent %llu, received %llu bytes",
                   2062:            (unsigned long long)obytes, (unsigned long long)ibytes);
1.364     markus   2063:
                   2064:        verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
1.525     djm      2065:        ssh_packet_close(ssh);
1.231     provos   2066:
                   2067:        if (use_privsep)
                   2068:                mm_terminate();
                   2069:
1.64      markus   2070:        exit(0);
1.1       deraadt  2071: }
1.98      markus   2072:
1.435     markus   2073: int
1.527     djm      2074: sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey,
                   2075:     struct sshkey *pubkey, u_char **signature, size_t *slenp,
                   2076:     const u_char *data, size_t dlen, const char *alg)
1.404     markus   2077: {
1.432     djm      2078:        int r;
                   2079:
1.527     djm      2080:        if (use_privsep) {
                   2081:                if (privkey) {
                   2082:                        if (mm_sshkey_sign(ssh, privkey, signature, slenp,
1.542     djm      2083:                            data, dlen, alg, options.sk_provider,
                   2084:                            ssh->compat) < 0)
1.527     djm      2085:                                fatal("%s: privkey sign failed", __func__);
                   2086:                } else {
                   2087:                        if (mm_sshkey_sign(ssh, pubkey, signature, slenp,
1.542     djm      2088:                            data, dlen, alg, options.sk_provider,
                   2089:                            ssh->compat) < 0)
1.527     djm      2090:                                fatal("%s: pubkey sign failed", __func__);
                   2091:                }
1.404     markus   2092:        } else {
1.527     djm      2093:                if (privkey) {
                   2094:                        if (sshkey_sign(privkey, signature, slenp, data, dlen,
1.542     djm      2095:                            alg, options.sk_provider, ssh->compat) < 0)
1.527     djm      2096:                                fatal("%s: privkey sign failed", __func__);
                   2097:                } else {
                   2098:                        if ((r = ssh_agent_sign(auth_sock, pubkey,
                   2099:                            signature, slenp, data, dlen, alg,
                   2100:                            ssh->compat)) != 0) {
                   2101:                                fatal("%s: agent sign failed: %s",
                   2102:                                    __func__, ssh_err(r));
                   2103:                        }
                   2104:                }
1.404     markus   2105:        }
1.435     markus   2106:        return 0;
1.404     markus   2107: }
                   2108:
1.452     djm      2109: /* SSH2 key exchange */
1.200     itojun   2110: static void
1.525     djm      2111: do_ssh2_kex(struct ssh *ssh)
1.98      markus   2112: {
1.422     markus   2113:        char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
1.435     markus   2114:        struct kex *kex;
1.437     markus   2115:        int r;
1.102     markus   2116:
1.457     djm      2117:        myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
1.514     djm      2118:            options.kex_algorithms);
1.457     djm      2119:        myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(
1.514     djm      2120:            options.ciphers);
1.457     djm      2121:        myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(
1.514     djm      2122:            options.ciphers);
1.457     djm      2123:        myproposal[PROPOSAL_MAC_ALGS_CTOS] =
                   2124:            myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
                   2125:
1.312     markus   2126:        if (options.compression == COMP_NONE) {
1.246     markus   2127:                myproposal[PROPOSAL_COMP_ALGS_CTOS] =
1.470     dtucker  2128:                    myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
1.102     markus   2129:        }
1.400     dtucker  2130:
                   2131:        if (options.rekey_limit || options.rekey_interval)
1.525     djm      2132:                ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
1.481     dtucker  2133:                    options.rekey_interval);
1.327     deraadt  2134:
1.413     djm      2135:        myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
1.514     djm      2136:            list_hostkey_types());
1.134     markus   2137:
1.189     markus   2138:        /* start key exchange */
1.525     djm      2139:        if ((r = kex_setup(ssh, myproposal)) != 0)
1.437     markus   2140:                fatal("kex_setup: %s", ssh_err(r));
1.525     djm      2141:        kex = ssh->kex;
1.426     markus   2142: #ifdef WITH_OPENSSL
1.532     djm      2143:        kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
                   2144:        kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
                   2145:        kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
                   2146:        kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
                   2147:        kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
1.263     markus   2148:        kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1.324     djm      2149:        kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1.532     djm      2150:        kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
1.426     markus   2151: #endif
1.532     djm      2152:        kex->kex[KEX_C25519_SHA256] = kex_gen_server;
                   2153:        kex->kex[KEX_KEM_SNTRUP4591761X25519_SHA512] = kex_gen_server;
1.373     djm      2154:        kex->load_host_public_key=&get_hostkey_public_by_type;
                   2155:        kex->load_host_private_key=&get_hostkey_private_by_type;
1.231     provos   2156:        kex->host_key_index=&get_hostkey_index;
1.404     markus   2157:        kex->sign = sshd_hostkey_sign;
1.189     markus   2158:
1.525     djm      2159:        ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done);
1.187     markus   2160:
                   2161:        session_id2 = kex->session_id;
                   2162:        session_id2_len = kex->session_id_len;
1.129     provos   2163:
                   2164: #ifdef DEBUG_KEXDH
                   2165:        /* send 1st encrypted/maced/compressed message */
                   2166:        packet_start(SSH2_MSG_IGNORE);
                   2167:        packet_put_cstring("markus");
                   2168:        packet_send();
                   2169:        packet_write_wait();
                   2170: #endif
1.186     markus   2171:        debug("KEX done");
1.278     markus   2172: }
                   2173:
                   2174: /* server specific fatal cleanup */
                   2175: void
                   2176: cleanup_exit(int i)
                   2177: {
1.527     djm      2178:        if (the_active_state != NULL && the_authctxt != NULL) {
                   2179:                do_cleanup(the_active_state, the_authctxt);
1.423     djm      2180:                if (use_privsep && privsep_is_preauth &&
                   2181:                    pmonitor != NULL && pmonitor->m_pid > 1) {
1.386     djm      2182:                        debug("Killing privsep child %d", pmonitor->m_pid);
                   2183:                        if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
1.388     djm      2184:                            errno != ESRCH)
1.386     djm      2185:                                error("%s: kill(%d): %s", __func__,
                   2186:                                    pmonitor->m_pid, strerror(errno));
                   2187:                }
                   2188:        }
1.278     markus   2189:        _exit(i);
1.1       deraadt  2190: }