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

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