[BACK]Return to sshd.c CVS log [TXT][DIR] Up to [cvs.NetBSD.org] / src / crypto / external / bsd / openssh / dist

Annotation of src/crypto/external/bsd/openssh/dist/sshd.c, Revision 1.1.1.25

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

CVSweb <webmaster@jp.NetBSD.org>