[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.565

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