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

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