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

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

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