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

1.479   ! dtucker     1: /* $OpenBSD: sshd.c,v 1.478 2016/11/30 00:28:31 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.333     stevesk    58: #include <pwd.h>
1.322     stevesk    59: #include <signal.h>
1.342     stevesk    60: #include <stdio.h>
1.341     stevesk    61: #include <stdlib.h>
1.339     stevesk    62: #include <string.h>
1.344     dtucker    63: #include <unistd.h>
1.438     deraadt    64: #include <limits.h>
1.1       deraadt    65:
1.426     markus     66: #ifdef WITH_OPENSSL
1.155     markus     67: #include <openssl/bn.h>
1.426     markus     68: #endif
1.155     markus     69:
1.343     deraadt    70: #include "xmalloc.h"
1.155     markus     71: #include "ssh.h"
                     72: #include "ssh2.h"
1.1       deraadt    73: #include "rsa.h"
1.171     djm        74: #include "sshpty.h"
1.1       deraadt    75: #include "packet.h"
1.155     markus     76: #include "log.h"
1.343     deraadt    77: #include "buffer.h"
1.428     millert    78: #include "misc.h"
1.454     markus     79: #include "match.h"
1.1       deraadt    80: #include "servconf.h"
                     81: #include "uidswap.h"
1.33      markus     82: #include "compat.h"
1.155     markus     83: #include "cipher.h"
1.415     markus     84: #include "digest.h"
1.343     deraadt    85: #include "key.h"
1.98      markus     86: #include "kex.h"
                     87: #include "myproposal.h"
1.108     markus     88: #include "authfile.h"
1.154     markus     89: #include "pathnames.h"
1.155     markus     90: #include "atomicio.h"
                     91: #include "canohost.h"
1.343     deraadt    92: #include "hostfile.h"
1.155     markus     93: #include "auth.h"
1.404     markus     94: #include "authfd.h"
1.294     djm        95: #include "msg.h"
1.186     markus     96: #include "dispatch.h"
1.206     stevesk    97: #include "channels.h"
1.230     provos     98: #include "session.h"
1.231     provos     99: #include "monitor.h"
1.343     deraadt   100: #ifdef GSSAPI
                    101: #include "ssh-gss.h"
                    102: #endif
1.231     provos    103: #include "monitor_wrap.h"
1.385     djm       104: #include "ssh-sandbox.h"
1.332     stevesk   105: #include "version.h"
1.432     djm       106: #include "ssherr.h"
1.1       deraadt   107:
1.296     djm       108: /* Re-exec fds */
                    109: #define REEXEC_DEVCRYPTO_RESERVED_FD   (STDERR_FILENO + 1)
                    110: #define REEXEC_STARTUP_PIPE_FD         (STDERR_FILENO + 2)
                    111: #define REEXEC_CONFIG_PASS_FD          (STDERR_FILENO + 3)
                    112: #define REEXEC_MIN_FREE_FD             (STDERR_FILENO + 4)
                    113:
1.138     markus    114: extern char *__progname;
                    115:
1.1       deraadt   116: /* Server configuration options. */
                    117: ServerOptions options;
                    118:
                    119: /* Name of the server configuration file. */
1.154     markus    120: char *config_file_name = _PATH_SERVER_CONFIG_FILE;
1.1       deraadt   121:
1.105     markus    122: /*
1.65      deraadt   123:  * Debug mode flag.  This can be set on the command line.  If debug
                    124:  * mode is enabled, extra debugging output will be sent to the system
                    125:  * log, the daemon will not go to background, and will exit after processing
                    126:  * the first connection.
                    127:  */
1.1       deraadt   128: int debug_flag = 0;
                    129:
1.203     stevesk   130: /* Flag indicating that the daemon should only test the configuration and keys. */
                    131: int test_flag = 0;
                    132:
1.1       deraadt   133: /* Flag indicating that the daemon is being started from inetd. */
                    134: int inetd_flag = 0;
                    135:
1.135     markus    136: /* Flag indicating that sshd should not detach and become a daemon. */
                    137: int no_daemon_flag = 0;
                    138:
1.47      markus    139: /* debug goes to stderr unless inetd_flag is set */
                    140: int log_stderr = 0;
                    141:
1.1       deraadt   142: /* Saved arguments to main(). */
                    143: char **saved_argv;
                    144:
1.294     djm       145: /* re-exec */
                    146: int rexeced_flag = 0;
                    147: int rexec_flag = 1;
                    148: int rexec_argc = 0;
                    149: char **rexec_argv;
                    150:
1.66      markus    151: /*
1.75      markus    152:  * The sockets that the server is listening; this is used in the SIGHUP
                    153:  * signal handler.
1.66      markus    154:  */
1.75      markus    155: #define        MAX_LISTEN_SOCKS        16
                    156: int listen_socks[MAX_LISTEN_SOCKS];
                    157: int num_listen_socks = 0;
1.1       deraadt   158:
1.66      markus    159: /*
                    160:  * the client's version string, passed by sshd2 in compat mode. if != NULL,
                    161:  * sshd will skip the version-number exchange
                    162:  */
1.61      markus    163: char *client_version_string = NULL;
1.96      markus    164: char *server_version_string = NULL;
1.1       deraadt   165:
1.404     markus    166: /* Daemon's agent connection */
1.432     djm       167: int auth_sock = -1;
1.404     markus    168: int have_agent = 0;
                    169:
1.66      markus    170: /*
                    171:  * Any really sensitive data in the application is contained in this
                    172:  * structure. The idea is that this structure could be locked into memory so
                    173:  * that the pages do not get written into swap.  However, there are some
                    174:  * problems. The private key contains BIGNUMs, and we do not (in principle)
                    175:  * have access to the internals of them, and locking just the structure is
                    176:  * not very useful.  Currently, memory locking is not implemented.
                    177:  */
1.64      markus    178: struct {
1.134     markus    179:        Key     **host_keys;            /* all private host keys */
1.404     markus    180:        Key     **host_pubkeys;         /* all public host keys */
1.373     djm       181:        Key     **host_certificates;    /* all public host certificates */
1.134     markus    182:        int     have_ssh2_key;
1.1       deraadt   183: } sensitive_data;
                    184:
1.199     markus    185: /* This is set to true when a signal is received. */
1.212     markus    186: static volatile sig_atomic_t received_sighup = 0;
                    187: static volatile sig_atomic_t received_sigterm = 0;
1.1       deraadt   188:
1.96      markus    189: /* session identifier, used by RSA-auth */
1.140     markus    190: u_char session_id[16];
1.96      markus    191:
1.108     markus    192: /* same for ssh2 */
1.140     markus    193: u_char *session_id2 = NULL;
1.269     markus    194: u_int session_id2_len = 0;
1.108     markus    195:
1.125     markus    196: /* record remote hostname or ip */
1.438     deraadt   197: u_int utmp_len = HOST_NAME_MAX+1;
1.125     markus    198:
1.211     markus    199: /* options.max_startup sized array of fd ints */
                    200: int *startup_pipes = NULL;
                    201: int startup_pipe;              /* in child */
                    202:
1.231     provos    203: /* variables used for privilege separation */
1.337     dtucker   204: int use_privsep = -1;
1.285     dtucker   205: struct monitor *pmonitor = NULL;
1.386     djm       206: int privsep_is_preauth = 1;
1.231     provos    207:
1.278     markus    208: /* global authentication context */
                    209: Authctxt *the_authctxt = NULL;
                    210:
1.337     dtucker   211: /* sshd_config buffer */
                    212: Buffer cfg;
                    213:
1.299     dtucker   214: /* message to be displayed after login */
                    215: Buffer loginmsg;
                    216:
1.1       deraadt   217: /* Prototypes for various functions defined later in this file. */
1.200     itojun    218: void destroy_sensitive_data(void);
1.231     provos    219: void demote_sensitive_data(void);
1.200     itojun    220: static void do_ssh2_kex(void);
1.129     provos    221:
1.87      markus    222: /*
1.75      markus    223:  * Close all listening sockets
                    224:  */
1.200     itojun    225: static void
1.75      markus    226: close_listen_socks(void)
                    227: {
                    228:        int i;
1.250     deraadt   229:
1.75      markus    230:        for (i = 0; i < num_listen_socks; i++)
                    231:                close(listen_socks[i]);
                    232:        num_listen_socks = -1;
                    233: }
                    234:
1.211     markus    235: static void
                    236: close_startup_pipes(void)
                    237: {
                    238:        int i;
1.250     deraadt   239:
1.211     markus    240:        if (startup_pipes)
                    241:                for (i = 0; i < options.max_startups; i++)
                    242:                        if (startup_pipes[i] != -1)
                    243:                                close(startup_pipes[i]);
                    244: }
                    245:
1.75      markus    246: /*
1.65      deraadt   247:  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
                    248:  * the effect is to reread the configuration file (and to regenerate
                    249:  * the server key).
                    250:  */
1.327     deraadt   251:
                    252: /*ARGSUSED*/
1.200     itojun    253: static void
1.64      markus    254: sighup_handler(int sig)
1.1       deraadt   255: {
1.210     deraadt   256:        int save_errno = errno;
                    257:
1.64      markus    258:        received_sighup = 1;
                    259:        signal(SIGHUP, sighup_handler);
1.210     deraadt   260:        errno = save_errno;
1.1       deraadt   261: }
                    262:
1.65      deraadt   263: /*
                    264:  * Called from the main program after receiving SIGHUP.
                    265:  * Restarts the server.
                    266:  */
1.200     itojun    267: static void
1.165     itojun    268: sighup_restart(void)
1.1       deraadt   269: {
1.264     itojun    270:        logit("Received SIGHUP; restarting.");
1.479   ! dtucker   271:        if (options.pid_file != NULL)
        !           272:                unlink(options.pid_file);
1.75      markus    273:        close_listen_socks();
1.211     markus    274:        close_startup_pipes();
1.349     dtucker   275:        alarm(0);  /* alarm timer persists across exec */
1.369     dtucker   276:        signal(SIGHUP, SIG_IGN); /* will be restored after exec */
1.64      markus    277:        execv(saved_argv[0], saved_argv);
1.264     itojun    278:        logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
1.250     deraadt   279:            strerror(errno));
1.64      markus    280:        exit(1);
1.1       deraadt   281: }
                    282:
1.65      deraadt   283: /*
                    284:  * Generic signal handler for terminating signals in the master daemon.
                    285:  */
1.327     deraadt   286: /*ARGSUSED*/
1.200     itojun    287: static void
1.64      markus    288: sigterm_handler(int sig)
1.1       deraadt   289: {
1.199     markus    290:        received_sigterm = sig;
1.1       deraadt   291: }
                    292:
1.65      deraadt   293: /*
                    294:  * SIGCHLD handler.  This is called whenever a child dies.  This will then
1.199     markus    295:  * reap any zombies left by exited children.
1.65      deraadt   296:  */
1.327     deraadt   297: /*ARGSUSED*/
1.200     itojun    298: static void
1.64      markus    299: main_sigchld_handler(int sig)
1.1       deraadt   300: {
1.250     deraadt   301:        int save_errno = errno;
1.239     markus    302:        pid_t pid;
1.64      markus    303:        int status;
1.60      deraadt   304:
1.239     markus    305:        while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
                    306:            (pid < 0 && errno == EINTR))
1.64      markus    307:                ;
1.60      deraadt   308:
1.64      markus    309:        signal(SIGCHLD, main_sigchld_handler);
                    310:        errno = save_errno;
1.1       deraadt   311: }
                    312:
1.65      deraadt   313: /*
                    314:  * Signal handler for the alarm after the login grace period has expired.
                    315:  */
1.327     deraadt   316: /*ARGSUSED*/
1.200     itojun    317: static void
1.64      markus    318: grace_alarm_handler(int sig)
1.1       deraadt   319: {
1.285     dtucker   320:        if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
                    321:                kill(pmonitor->m_pid, SIGALRM);
1.394     djm       322:
                    323:        /*
                    324:         * Try to kill any processes that we have spawned, E.g. authorized
                    325:         * keys command helpers.
                    326:         */
                    327:        if (getpgid(0) == getpid()) {
                    328:                signal(SIGTERM, SIG_IGN);
1.416     djm       329:                kill(0, SIGTERM);
1.394     djm       330:        }
1.285     dtucker   331:
1.64      markus    332:        /* Log error and exit. */
1.466     djm       333:        sigdie("Timeout before authentication for %s port %d",
                    334:            ssh_remote_ipaddr(active_state), ssh_remote_port(active_state));
1.62      markus    335: }
                    336:
1.200     itojun    337: static void
1.466     djm       338: sshd_exchange_identification(struct ssh *ssh, int sock_in, int sock_out)
1.96      markus    339: {
1.311     djm       340:        u_int i;
1.96      markus    341:        int remote_major, remote_minor;
1.363     dtucker   342:        char *s, *newline = "\n";
1.96      markus    343:        char buf[256];                  /* Must not be larger than remote_version. */
                    344:        char remote_version[256];       /* Must be at least as big as buf. */
                    345:
1.390     djm       346:        xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s%s",
1.473     naddy     347:            PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION,
1.390     djm       348:            *options.version_addendum == '\0' ? "" : " ",
                    349:            options.version_addendum, newline);
1.96      markus    350:
1.272     markus    351:        /* Send our protocol version identification. */
1.463     markus    352:        if (atomicio(vwrite, sock_out, server_version_string,
1.272     markus    353:            strlen(server_version_string))
                    354:            != strlen(server_version_string)) {
1.466     djm       355:                logit("Could not write ident string to %s port %d",
                    356:                    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1.278     markus    357:                cleanup_exit(255);
1.272     markus    358:        }
                    359:
                    360:        /* Read other sides version identification. */
                    361:        memset(buf, 0, sizeof(buf));
                    362:        for (i = 0; i < sizeof(buf) - 1; i++) {
1.463     markus    363:                if (atomicio(read, sock_in, &buf[i], 1) != 1) {
1.466     djm       364:                        logit("Did not receive identification string "
                    365:                            "from %s port %d",
                    366:                            ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1.278     markus    367:                        cleanup_exit(255);
1.96      markus    368:                }
1.272     markus    369:                if (buf[i] == '\r') {
                    370:                        buf[i] = 0;
                    371:                        /* Kludge for F-Secure Macintosh < 1.0.2 */
                    372:                        if (i == 12 &&
                    373:                            strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
1.96      markus    374:                                break;
1.272     markus    375:                        continue;
                    376:                }
                    377:                if (buf[i] == '\n') {
                    378:                        buf[i] = 0;
                    379:                        break;
1.96      markus    380:                }
                    381:        }
1.272     markus    382:        buf[sizeof(buf) - 1] = 0;
                    383:        client_version_string = xstrdup(buf);
1.96      markus    384:
                    385:        /*
                    386:         * Check that the versions match.  In future this might accept
                    387:         * several versions and set appropriate flags to handle them.
                    388:         */
                    389:        if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
                    390:            &remote_major, &remote_minor, remote_version) != 3) {
1.105     markus    391:                s = "Protocol mismatch.\n";
1.271     deraadt   392:                (void) atomicio(vwrite, sock_out, s, strlen(s));
1.408     djm       393:                logit("Bad protocol version identification '%.100s' "
                    394:                    "from %s port %d", client_version_string,
1.466     djm       395:                    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1.411     djm       396:                close(sock_in);
                    397:                close(sock_out);
1.278     markus    398:                cleanup_exit(255);
1.96      markus    399:        }
                    400:        debug("Client protocol version %d.%d; client software version %.100s",
1.217     deraadt   401:            remote_major, remote_minor, remote_version);
1.96      markus    402:
1.466     djm       403:        ssh->compat = compat_datafellows(remote_version);
1.260     mickey    404:
1.466     djm       405:        if ((ssh->compat & SSH_BUG_PROBE) != 0) {
                    406:                logit("probed from %s port %d with %s.  Don't panic.",
                    407:                    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
                    408:                    client_version_string);
1.278     markus    409:                cleanup_exit(255);
1.260     mickey    410:        }
1.466     djm       411:        if ((ssh->compat & SSH_BUG_SCANNER) != 0) {
                    412:                logit("scanned from %s port %d with %s.  Don't panic.",
                    413:                    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
                    414:                    client_version_string);
1.278     markus    415:                cleanup_exit(255);
1.175     deraadt   416:        }
1.466     djm       417:        if ((ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
1.413     djm       418:                logit("Client version \"%.100s\" uses unsafe RSA signature "
                    419:                    "scheme; disabling use of RSA keys", remote_version);
1.414     djm       420:        }
1.466     djm       421:        if ((ssh->compat & SSH_BUG_DERIVEKEY) != 0) {
1.414     djm       422:                fatal("Client version \"%.100s\" uses unsafe key agreement; "
                    423:                    "refusing connection", remote_version);
                    424:        }
1.98      markus    425:
1.102     markus    426:        chop(server_version_string);
                    427:        debug("Local version string %.200s", server_version_string);
                    428:
1.472     markus    429:        if (remote_major == 2 ||
                    430:            (remote_major == 1 && remote_minor == 99)) {
                    431:                enable_compat20();
                    432:        } else {
1.96      markus    433:                s = "Protocol major versions differ.\n";
1.271     deraadt   434:                (void) atomicio(vwrite, sock_out, s, strlen(s));
1.96      markus    435:                close(sock_in);
                    436:                close(sock_out);
1.466     djm       437:                logit("Protocol major versions differ for %s port %d: "
                    438:                    "%.200s vs. %.200s",
                    439:                    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1.102     markus    440:                    server_version_string, client_version_string);
1.278     markus    441:                cleanup_exit(255);
1.96      markus    442:        }
1.108     markus    443: }
                    444:
1.134     markus    445: /* Destroy the host and server keys.  They will no longer be needed. */
1.108     markus    446: void
                    447: destroy_sensitive_data(void)
                    448: {
1.134     markus    449:        int i;
                    450:
1.217     deraadt   451:        for (i = 0; i < options.num_host_key_files; i++) {
1.134     markus    452:                if (sensitive_data.host_keys[i]) {
                    453:                        key_free(sensitive_data.host_keys[i]);
                    454:                        sensitive_data.host_keys[i] = NULL;
                    455:                }
1.373     djm       456:                if (sensitive_data.host_certificates[i]) {
                    457:                        key_free(sensitive_data.host_certificates[i]);
                    458:                        sensitive_data.host_certificates[i] = NULL;
                    459:                }
1.134     markus    460:        }
                    461: }
                    462:
1.231     provos    463: /* Demote private to public keys for network child */
                    464: void
                    465: demote_sensitive_data(void)
                    466: {
                    467:        Key *tmp;
                    468:        int i;
                    469:
                    470:        for (i = 0; i < options.num_host_key_files; i++) {
                    471:                if (sensitive_data.host_keys[i]) {
                    472:                        tmp = key_demote(sensitive_data.host_keys[i]);
                    473:                        key_free(sensitive_data.host_keys[i]);
                    474:                        sensitive_data.host_keys[i] = tmp;
                    475:                }
1.373     djm       476:                /* Certs do not need demotion */
1.231     provos    477:        }
                    478: }
                    479:
1.233     markus    480: static void
1.231     provos    481: privsep_preauth_child(void)
                    482: {
1.253     deraadt   483:        gid_t gidset[1];
1.250     deraadt   484:        struct passwd *pw;
1.231     provos    485:
                    486:        /* Enable challenge-response authentication for privilege separation */
                    487:        privsep_challenge_enable();
1.419     djm       488:
1.420     markus    489: #ifdef GSSAPI
1.419     djm       490:        /* Cache supported mechanism OIDs for later use */
                    491:        if (options.gss_authentication)
                    492:                ssh_gssapi_prepare_supported_oids();
1.420     markus    493: #endif
1.231     provos    494:
                    495:        /* Demote the private keys to public keys. */
                    496:        demote_sensitive_data();
                    497:
1.460     djm       498:        /* Demote the child */
                    499:        if (getuid() == 0 || geteuid() == 0) {
                    500:                if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
                    501:                        fatal("Privilege separation user %s does not exist",
                    502:                            SSH_PRIVSEP_USER);
                    503:                explicit_bzero(pw->pw_passwd, strlen(pw->pw_passwd));
                    504:                endpwent();
                    505:
                    506:                /* Change our root directory */
                    507:                if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
                    508:                        fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
                    509:                            strerror(errno));
                    510:                if (chdir("/") == -1)
                    511:                        fatal("chdir(\"/\"): %s", strerror(errno));
                    512:
                    513:                /*
                    514:                 * Drop our privileges
                    515:                 * NB. Can't use setusercontext() after chroot.
                    516:                 */
                    517:                debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
                    518:                    (u_int)pw->pw_gid);
                    519:                gidset[0] = pw->pw_gid;
                    520:                if (setgroups(1, gidset) < 0)
                    521:                        fatal("setgroups: %.100s", strerror(errno));
                    522:                permanently_set_uid(pw);
                    523:        }
1.231     provos    524: }
                    525:
1.278     markus    526: static int
                    527: privsep_preauth(Authctxt *authctxt)
1.237     markus    528: {
1.432     djm       529:        int status, r;
1.237     markus    530:        pid_t pid;
1.384     djm       531:        struct ssh_sandbox *box = NULL;
1.237     markus    532:
                    533:        /* Set up unprivileged child process to deal with network data */
1.242     mouring   534:        pmonitor = monitor_init();
1.237     markus    535:        /* Store a pointer to the kex for later rekeying */
1.434     markus    536:        pmonitor->m_pkex = &active_state->kex;
1.237     markus    537:
1.393     djm       538:        if (use_privsep == PRIVSEP_ON)
1.384     djm       539:                box = ssh_sandbox_init();
1.237     markus    540:        pid = fork();
                    541:        if (pid == -1) {
                    542:                fatal("fork of unprivileged child failed");
                    543:        } else if (pid != 0) {
1.245     mpech     544:                debug2("Network child is on pid %ld", (long)pid);
1.237     markus    545:
1.392     markus    546:                pmonitor->m_pid = pid;
1.432     djm       547:                if (have_agent) {
                    548:                        r = ssh_get_authentication_socket(&auth_sock);
                    549:                        if (r != 0) {
                    550:                                error("Could not get agent socket: %s",
                    551:                                    ssh_err(r));
                    552:                                have_agent = 0;
                    553:                        }
                    554:                }
1.384     djm       555:                if (box != NULL)
                    556:                        ssh_sandbox_parent_preauth(box, pid);
1.278     markus    557:                monitor_child_preauth(authctxt, pmonitor);
1.237     markus    558:
                    559:                /* Wait for the child's exit status */
1.384     djm       560:                while (waitpid(pid, &status, 0) < 0) {
1.386     djm       561:                        if (errno == EINTR)
                    562:                                continue;
                    563:                        pmonitor->m_pid = -1;
                    564:                        fatal("%s: waitpid: %s", __func__, strerror(errno));
1.384     djm       565:                }
1.386     djm       566:                privsep_is_preauth = 0;
                    567:                pmonitor->m_pid = -1;
1.384     djm       568:                if (WIFEXITED(status)) {
                    569:                        if (WEXITSTATUS(status) != 0)
                    570:                                fatal("%s: preauth child exited with status %d",
                    571:                                    __func__, WEXITSTATUS(status));
                    572:                } else if (WIFSIGNALED(status))
                    573:                        fatal("%s: preauth child terminated by signal %d",
                    574:                            __func__, WTERMSIG(status));
                    575:                if (box != NULL)
                    576:                        ssh_sandbox_parent_finish(box);
                    577:                return 1;
1.237     markus    578:        } else {
                    579:                /* child */
1.383     djm       580:                close(pmonitor->m_sendfd);
                    581:                close(pmonitor->m_log_recvfd);
1.237     markus    582:
1.383     djm       583:                /* Arrange for logging to be sent to the monitor */
                    584:                set_log_handler(mm_log_handler, pmonitor);
1.237     markus    585:
1.460     djm       586:                privsep_preauth_child();
1.238     stevesk   587:                setproctitle("%s", "[net]");
1.384     djm       588:                if (box != NULL)
                    589:                        ssh_sandbox_child(box);
                    590:
                    591:                return 0;
1.237     markus    592:        }
                    593: }
                    594:
1.233     markus    595: static void
1.237     markus    596: privsep_postauth(Authctxt *authctxt)
1.231     provos    597: {
1.474     djm       598:        if (authctxt->pw->pw_uid == 0) {
1.231     provos    599:                /* File descriptor passing is broken or root login */
                    600:                use_privsep = 0;
1.315     djm       601:                goto skip;
1.231     provos    602:        }
1.234     markus    603:
1.231     provos    604:        /* New socket pair */
1.242     mouring   605:        monitor_reinit(pmonitor);
1.231     provos    606:
1.242     mouring   607:        pmonitor->m_pid = fork();
                    608:        if (pmonitor->m_pid == -1)
1.231     provos    609:                fatal("fork of unprivileged child failed");
1.242     mouring   610:        else if (pmonitor->m_pid != 0) {
1.364     markus    611:                verbose("User child is on pid %ld", (long)pmonitor->m_pid);
1.307     otto      612:                buffer_clear(&loginmsg);
1.242     mouring   613:                monitor_child_postauth(pmonitor);
1.231     provos    614:
                    615:                /* NEVERREACHED */
                    616:                exit(0);
                    617:        }
                    618:
1.383     djm       619:        /* child */
                    620:
1.242     mouring   621:        close(pmonitor->m_sendfd);
1.383     djm       622:        pmonitor->m_sendfd = -1;
1.231     provos    623:
                    624:        /* Demote the private keys to public keys. */
                    625:        demote_sensitive_data();
1.354     djm       626:
1.231     provos    627:        /* Drop privileges */
                    628:        do_setusercontext(authctxt->pw);
                    629:
1.315     djm       630:  skip:
1.231     provos    631:        /* It is safe now to apply the key state */
1.242     mouring   632:        monitor_apply_keystate(pmonitor);
1.312     markus    633:
                    634:        /*
                    635:         * Tell the packet layer that authentication was successful, since
                    636:         * this information is not part of the key state.
                    637:         */
                    638:        packet_set_authenticated();
1.231     provos    639: }
                    640:
1.200     itojun    641: static char *
1.134     markus    642: list_hostkey_types(void)
                    643: {
1.223     markus    644:        Buffer b;
1.281     jakob     645:        const char *p;
                    646:        char *ret;
1.134     markus    647:        int i;
1.373     djm       648:        Key *key;
1.223     markus    649:
                    650:        buffer_init(&b);
1.217     deraadt   651:        for (i = 0; i < options.num_host_key_files; i++) {
1.373     djm       652:                key = sensitive_data.host_keys[i];
1.443     djm       653:                if (key == NULL)
1.404     markus    654:                        key = sensitive_data.host_pubkeys[i];
1.472     markus    655:                if (key == NULL)
1.134     markus    656:                        continue;
1.454     markus    657:                /* Check that the key is accepted in HostkeyAlgorithms */
                    658:                if (match_pattern_list(sshkey_ssh_name(key),
                    659:                    options.hostkeyalgorithms, 0) != 1) {
                    660:                        debug3("%s: %s key not permitted by HostkeyAlgorithms",
                    661:                            __func__, sshkey_ssh_name(key));
                    662:                        continue;
                    663:                }
1.214     deraadt   664:                switch (key->type) {
1.134     markus    665:                case KEY_RSA:
                    666:                case KEY_DSA:
1.378     djm       667:                case KEY_ECDSA:
1.412     markus    668:                case KEY_ED25519:
1.223     markus    669:                        if (buffer_len(&b) > 0)
                    670:                                buffer_append(&b, ",", 1);
                    671:                        p = key_ssh_name(key);
                    672:                        buffer_append(&b, p, strlen(p));
1.461     markus    673:
                    674:                        /* for RSA we also support SHA2 signatures */
                    675:                        if (key->type == KEY_RSA) {
                    676:                                p = ",rsa-sha2-512,rsa-sha2-256";
                    677:                                buffer_append(&b, p, strlen(p));
                    678:                        }
1.134     markus    679:                        break;
                    680:                }
1.373     djm       681:                /* If the private key has a cert peer, then list that too */
                    682:                key = sensitive_data.host_certificates[i];
                    683:                if (key == NULL)
                    684:                        continue;
                    685:                switch (key->type) {
                    686:                case KEY_RSA_CERT:
                    687:                case KEY_DSA_CERT:
1.378     djm       688:                case KEY_ECDSA_CERT:
1.412     markus    689:                case KEY_ED25519_CERT:
1.373     djm       690:                        if (buffer_len(&b) > 0)
                    691:                                buffer_append(&b, ",", 1);
                    692:                        p = key_ssh_name(key);
                    693:                        buffer_append(&b, p, strlen(p));
                    694:                        break;
                    695:                }
1.134     markus    696:        }
1.467     djm       697:        if ((ret = sshbuf_dup_string(&b)) == NULL)
                    698:                fatal("%s: sshbuf_dup_string failed", __func__);
1.223     markus    699:        buffer_free(&b);
1.281     jakob     700:        debug("list_hostkey_types: %s", ret);
                    701:        return ret;
1.134     markus    702: }
                    703:
1.373     djm       704: static Key *
1.440     djm       705: get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
1.134     markus    706: {
                    707:        int i;
1.373     djm       708:        Key *key;
1.250     deraadt   709:
1.217     deraadt   710:        for (i = 0; i < options.num_host_key_files; i++) {
1.375     djm       711:                switch (type) {
                    712:                case KEY_RSA_CERT:
                    713:                case KEY_DSA_CERT:
1.378     djm       714:                case KEY_ECDSA_CERT:
1.412     markus    715:                case KEY_ED25519_CERT:
1.373     djm       716:                        key = sensitive_data.host_certificates[i];
1.375     djm       717:                        break;
                    718:                default:
1.373     djm       719:                        key = sensitive_data.host_keys[i];
1.404     markus    720:                        if (key == NULL && !need_private)
                    721:                                key = sensitive_data.host_pubkeys[i];
1.375     djm       722:                        break;
                    723:                }
1.440     djm       724:                if (key != NULL && key->type == type &&
                    725:                    (key->type != KEY_ECDSA || key->ecdsa_nid == nid))
1.373     djm       726:                        return need_private ?
                    727:                            sensitive_data.host_keys[i] : key;
1.134     markus    728:        }
                    729:        return NULL;
1.96      markus    730: }
                    731:
1.231     provos    732: Key *
1.440     djm       733: get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
1.373     djm       734: {
1.440     djm       735:        return get_hostkey_by_type(type, nid, 0, ssh);
1.373     djm       736: }
                    737:
                    738: Key *
1.440     djm       739: get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
1.373     djm       740: {
1.440     djm       741:        return get_hostkey_by_type(type, nid, 1, ssh);
1.373     djm       742: }
                    743:
                    744: Key *
1.231     provos    745: get_hostkey_by_index(int ind)
                    746: {
                    747:        if (ind < 0 || ind >= options.num_host_key_files)
                    748:                return (NULL);
                    749:        return (sensitive_data.host_keys[ind]);
                    750: }
                    751:
1.404     markus    752: Key *
1.435     markus    753: get_hostkey_public_by_index(int ind, struct ssh *ssh)
1.404     markus    754: {
                    755:        if (ind < 0 || ind >= options.num_host_key_files)
                    756:                return (NULL);
                    757:        return (sensitive_data.host_pubkeys[ind]);
                    758: }
                    759:
1.231     provos    760: int
1.442     djm       761: get_hostkey_index(Key *key, int compare, struct ssh *ssh)
1.231     provos    762: {
                    763:        int i;
1.250     deraadt   764:
1.231     provos    765:        for (i = 0; i < options.num_host_key_files; i++) {
1.373     djm       766:                if (key_is_cert(key)) {
1.442     djm       767:                        if (key == sensitive_data.host_certificates[i] ||
                    768:                            (compare && sensitive_data.host_certificates[i] &&
                    769:                            sshkey_equal(key,
                    770:                            sensitive_data.host_certificates[i])))
1.373     djm       771:                                return (i);
                    772:                } else {
1.442     djm       773:                        if (key == sensitive_data.host_keys[i] ||
                    774:                            (compare && sensitive_data.host_keys[i] &&
                    775:                            sshkey_equal(key, sensitive_data.host_keys[i])))
1.373     djm       776:                                return (i);
1.442     djm       777:                        if (key == sensitive_data.host_pubkeys[i] ||
                    778:                            (compare && sensitive_data.host_pubkeys[i] &&
                    779:                            sshkey_equal(key, sensitive_data.host_pubkeys[i])))
1.404     markus    780:                                return (i);
1.373     djm       781:                }
1.231     provos    782:        }
                    783:        return (-1);
                    784: }
                    785:
1.439     djm       786: /* Inform the client of all hostkeys */
                    787: static void
                    788: notify_hostkeys(struct ssh *ssh)
                    789: {
                    790:        struct sshbuf *buf;
                    791:        struct sshkey *key;
                    792:        int i, nkeys, r;
                    793:        char *fp;
1.446     dtucker   794:
                    795:        /* Some clients cannot cope with the hostkeys message, skip those. */
                    796:        if (datafellows & SSH_BUG_HOSTKEYS)
                    797:                return;
1.439     djm       798:
                    799:        if ((buf = sshbuf_new()) == NULL)
                    800:                fatal("%s: sshbuf_new", __func__);
                    801:        for (i = nkeys = 0; i < options.num_host_key_files; i++) {
                    802:                key = get_hostkey_public_by_index(i, ssh);
                    803:                if (key == NULL || key->type == KEY_UNSPEC ||
1.472     markus    804:                    sshkey_is_cert(key))
1.439     djm       805:                        continue;
                    806:                fp = sshkey_fingerprint(key, options.fingerprint_hash,
                    807:                    SSH_FP_DEFAULT);
                    808:                debug3("%s: key %d: %s %s", __func__, i,
                    809:                    sshkey_ssh_name(key), fp);
                    810:                free(fp);
1.442     djm       811:                if (nkeys == 0) {
                    812:                        packet_start(SSH2_MSG_GLOBAL_REQUEST);
1.444     djm       813:                        packet_put_cstring("hostkeys-00@openssh.com");
1.442     djm       814:                        packet_put_char(0); /* want-reply */
                    815:                }
                    816:                sshbuf_reset(buf);
                    817:                if ((r = sshkey_putb(key, buf)) != 0)
1.439     djm       818:                        fatal("%s: couldn't put hostkey %d: %s",
                    819:                            __func__, i, ssh_err(r));
1.442     djm       820:                packet_put_string(sshbuf_ptr(buf), sshbuf_len(buf));
1.439     djm       821:                nkeys++;
                    822:        }
1.442     djm       823:        debug3("%s: sent %d hostkeys", __func__, nkeys);
1.439     djm       824:        if (nkeys == 0)
                    825:                fatal("%s: no hostkeys", __func__);
                    826:        packet_send();
1.442     djm       827:        sshbuf_free(buf);
1.439     djm       828: }
                    829:
1.124     markus    830: /*
                    831:  * returns 1 if connection should be dropped, 0 otherwise.
                    832:  * dropping starts at connection #max_startups_begin with a probability
                    833:  * of (max_startups_rate/100). the probability increases linearly until
                    834:  * all connections are dropped for startups > max_startups
                    835:  */
1.200     itojun    836: static int
1.124     markus    837: drop_connection(int startups)
                    838: {
1.303     mickey    839:        int p, r;
1.124     markus    840:
                    841:        if (startups < options.max_startups_begin)
                    842:                return 0;
                    843:        if (startups >= options.max_startups)
                    844:                return 1;
                    845:        if (options.max_startups_rate == 100)
                    846:                return 1;
                    847:
                    848:        p  = 100 - options.max_startups_rate;
                    849:        p *= startups - options.max_startups_begin;
1.303     mickey    850:        p /= options.max_startups - options.max_startups_begin;
1.124     markus    851:        p += options.max_startups_rate;
1.356     djm       852:        r = arc4random_uniform(100);
1.124     markus    853:
1.304     djm       854:        debug("drop_connection: p %d, r %d", p, r);
1.124     markus    855:        return (r < p) ? 1 : 0;
                    856: }
                    857:
1.215     markus    858: static void
                    859: usage(void)
                    860: {
1.290     markus    861:        fprintf(stderr, "%s, %s\n",
1.426     markus    862:            SSH_VERSION,
                    863: #ifdef WITH_OPENSSL
                    864:            SSLeay_version(SSLEAY_VERSION)
                    865: #else
                    866:            "without OpenSSL"
                    867: #endif
                    868:        );
1.289     markus    869:        fprintf(stderr,
1.473     naddy     870: "usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n"
1.399     dtucker   871: "            [-E log_file] [-f config_file] [-g login_grace_time]\n"
1.473     naddy     872: "            [-h host_key_file] [-o option] [-p port] [-u len]\n"
1.289     markus    873:        );
1.215     markus    874:        exit(1);
                    875: }
                    876:
1.294     djm       877: static void
1.467     djm       878: send_rexec_state(int fd, struct sshbuf *conf)
1.294     djm       879: {
1.467     djm       880:        struct sshbuf *m;
                    881:        int r;
1.294     djm       882:
1.467     djm       883:        debug3("%s: entering fd = %d config len %zu", __func__, fd,
                    884:            sshbuf_len(conf));
1.294     djm       885:
                    886:        /*
                    887:         * Protocol from reexec master to child:
                    888:         *      string  configuration
                    889:         */
1.467     djm       890:        if ((m = sshbuf_new()) == NULL)
                    891:                fatal("%s: sshbuf_new failed", __func__);
                    892:        if ((r = sshbuf_put_stringb(m, conf)) != 0)
                    893:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    894:        if (ssh_msg_send(fd, 0, m) == -1)
1.294     djm       895:                fatal("%s: ssh_msg_send failed", __func__);
                    896:
1.467     djm       897:        sshbuf_free(m);
1.294     djm       898:
                    899:        debug3("%s: done", __func__);
                    900: }
                    901:
                    902: static void
                    903: recv_rexec_state(int fd, Buffer *conf)
                    904: {
                    905:        Buffer m;
                    906:        char *cp;
                    907:        u_int len;
                    908:
                    909:        debug3("%s: entering fd = %d", __func__, fd);
                    910:
                    911:        buffer_init(&m);
                    912:
                    913:        if (ssh_msg_recv(fd, &m) == -1)
                    914:                fatal("%s: ssh_msg_recv failed", __func__);
                    915:        if (buffer_get_char(&m) != 0)
                    916:                fatal("%s: rexec version mismatch", __func__);
                    917:
                    918:        cp = buffer_get_string(&m, &len);
                    919:        if (conf != NULL)
1.469     djm       920:                buffer_append(conf, cp, len);
1.402     djm       921:        free(cp);
1.294     djm       922:
                    923:        buffer_free(&m);
                    924:
                    925:        debug3("%s: done", __func__);
                    926: }
                    927:
1.345     djm       928: /* Accept a connection from inetd */
                    929: static void
                    930: server_accept_inetd(int *sock_in, int *sock_out)
                    931: {
                    932:        int fd;
                    933:
                    934:        startup_pipe = -1;
                    935:        if (rexeced_flag) {
                    936:                close(REEXEC_CONFIG_PASS_FD);
                    937:                *sock_in = *sock_out = dup(STDIN_FILENO);
                    938:                if (!debug_flag) {
                    939:                        startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
                    940:                        close(REEXEC_STARTUP_PIPE_FD);
                    941:                }
                    942:        } else {
                    943:                *sock_in = dup(STDIN_FILENO);
                    944:                *sock_out = dup(STDOUT_FILENO);
                    945:        }
                    946:        /*
                    947:         * We intentionally do not close the descriptors 0, 1, and 2
                    948:         * as our code for setting the descriptors won't work if
                    949:         * ttyfd happens to be one of those.
                    950:         */
                    951:        if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
                    952:                dup2(fd, STDIN_FILENO);
                    953:                dup2(fd, STDOUT_FILENO);
1.403     dtucker   954:                if (!log_stderr)
                    955:                        dup2(fd, STDERR_FILENO);
                    956:                if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1.345     djm       957:                        close(fd);
                    958:        }
                    959:        debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
                    960: }
                    961:
                    962: /*
                    963:  * Listen for TCP connections
                    964:  */
                    965: static void
                    966: server_listen(void)
                    967: {
                    968:        int ret, listen_sock, on = 1;
                    969:        struct addrinfo *ai;
                    970:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
                    971:
                    972:        for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
                    973:                if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                    974:                        continue;
                    975:                if (num_listen_socks >= MAX_LISTEN_SOCKS)
                    976:                        fatal("Too many listen sockets. "
                    977:                            "Enlarge MAX_LISTEN_SOCKS");
                    978:                if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
                    979:                    ntop, sizeof(ntop), strport, sizeof(strport),
                    980:                    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
                    981:                        error("getnameinfo failed: %.100s",
1.352     dtucker   982:                            ssh_gai_strerror(ret));
1.345     djm       983:                        continue;
                    984:                }
                    985:                /* Create socket for listening. */
1.370     dtucker   986:                listen_sock = socket(ai->ai_family, ai->ai_socktype,
                    987:                    ai->ai_protocol);
1.345     djm       988:                if (listen_sock < 0) {
                    989:                        /* kernel may not support ipv6 */
                    990:                        verbose("socket: %.100s", strerror(errno));
                    991:                        continue;
                    992:                }
                    993:                if (set_nonblock(listen_sock) == -1) {
                    994:                        close(listen_sock);
                    995:                        continue;
                    996:                }
                    997:                /*
                    998:                 * Set socket options.
                    999:                 * Allow local port reuse in TIME_WAIT.
                   1000:                 */
                   1001:                if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
                   1002:                    &on, sizeof(on)) == -1)
                   1003:                        error("setsockopt SO_REUSEADDR: %s", strerror(errno));
                   1004:
                   1005:                debug("Bind to port %s on %s.", strport, ntop);
                   1006:
                   1007:                /* Bind the socket to the desired port. */
                   1008:                if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   1009:                        error("Bind to port %s on %s failed: %.200s.",
                   1010:                            strport, ntop, strerror(errno));
                   1011:                        close(listen_sock);
                   1012:                        continue;
                   1013:                }
                   1014:                listen_socks[num_listen_socks] = listen_sock;
                   1015:                num_listen_socks++;
                   1016:
                   1017:                /* Start listening on the port. */
                   1018:                if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
                   1019:                        fatal("listen on [%s]:%s: %.100s",
                   1020:                            ntop, strport, strerror(errno));
                   1021:                logit("Server listening on %s port %s.", ntop, strport);
                   1022:        }
                   1023:        freeaddrinfo(options.listen_addrs);
                   1024:
                   1025:        if (!num_listen_socks)
                   1026:                fatal("Cannot bind any address.");
                   1027: }
                   1028:
                   1029: /*
                   1030:  * The main TCP accept loop. Note that, for the non-debug case, returns
                   1031:  * from this function are in a forked subprocess.
                   1032:  */
                   1033: static void
                   1034: server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
                   1035: {
                   1036:        fd_set *fdset;
                   1037:        int i, j, ret, maxfd;
1.472     markus   1038:        int startups = 0;
1.345     djm      1039:        int startup_p[2] = { -1 , -1 };
                   1040:        struct sockaddr_storage from;
                   1041:        socklen_t fromlen;
                   1042:        pid_t pid;
                   1043:
                   1044:        /* setup fd set for accept */
                   1045:        fdset = NULL;
                   1046:        maxfd = 0;
                   1047:        for (i = 0; i < num_listen_socks; i++)
                   1048:                if (listen_socks[i] > maxfd)
                   1049:                        maxfd = listen_socks[i];
                   1050:        /* pipes connected to unauthenticated childs */
                   1051:        startup_pipes = xcalloc(options.max_startups, sizeof(int));
                   1052:        for (i = 0; i < options.max_startups; i++)
                   1053:                startup_pipes[i] = -1;
                   1054:
                   1055:        /*
                   1056:         * Stay listening for connections until the system crashes or
                   1057:         * the daemon is killed with a signal.
                   1058:         */
                   1059:        for (;;) {
                   1060:                if (received_sighup)
                   1061:                        sighup_restart();
1.462     mmcc     1062:                free(fdset);
1.458     deraadt  1063:                fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
1.345     djm      1064:                    sizeof(fd_mask));
                   1065:
                   1066:                for (i = 0; i < num_listen_socks; i++)
                   1067:                        FD_SET(listen_socks[i], fdset);
                   1068:                for (i = 0; i < options.max_startups; i++)
                   1069:                        if (startup_pipes[i] != -1)
                   1070:                                FD_SET(startup_pipes[i], fdset);
                   1071:
                   1072:                /* Wait in select until there is a connection. */
                   1073:                ret = select(maxfd+1, fdset, NULL, NULL, NULL);
                   1074:                if (ret < 0 && errno != EINTR)
                   1075:                        error("select: %.100s", strerror(errno));
                   1076:                if (received_sigterm) {
                   1077:                        logit("Received signal %d; terminating.",
                   1078:                            (int) received_sigterm);
                   1079:                        close_listen_socks();
1.430     djm      1080:                        if (options.pid_file != NULL)
                   1081:                                unlink(options.pid_file);
1.382     djm      1082:                        exit(received_sigterm == SIGTERM ? 0 : 255);
1.345     djm      1083:                }
                   1084:                if (ret < 0)
                   1085:                        continue;
                   1086:
                   1087:                for (i = 0; i < options.max_startups; i++)
                   1088:                        if (startup_pipes[i] != -1 &&
                   1089:                            FD_ISSET(startup_pipes[i], fdset)) {
                   1090:                                /*
                   1091:                                 * the read end of the pipe is ready
                   1092:                                 * if the child has closed the pipe
                   1093:                                 * after successful authentication
                   1094:                                 * or if the child has died
                   1095:                                 */
                   1096:                                close(startup_pipes[i]);
                   1097:                                startup_pipes[i] = -1;
                   1098:                                startups--;
                   1099:                        }
                   1100:                for (i = 0; i < num_listen_socks; i++) {
                   1101:                        if (!FD_ISSET(listen_socks[i], fdset))
                   1102:                                continue;
                   1103:                        fromlen = sizeof(from);
                   1104:                        *newsock = accept(listen_socks[i],
                   1105:                            (struct sockaddr *)&from, &fromlen);
                   1106:                        if (*newsock < 0) {
1.398     markus   1107:                                if (errno != EINTR && errno != EWOULDBLOCK &&
                   1108:                                    errno != ECONNABORTED)
1.389     djm      1109:                                        error("accept: %.100s",
                   1110:                                            strerror(errno));
                   1111:                                if (errno == EMFILE || errno == ENFILE)
                   1112:                                        usleep(100 * 1000);
1.345     djm      1113:                                continue;
                   1114:                        }
                   1115:                        if (unset_nonblock(*newsock) == -1) {
                   1116:                                close(*newsock);
                   1117:                                continue;
                   1118:                        }
                   1119:                        if (drop_connection(startups) == 1) {
                   1120:                                debug("drop connection #%d", startups);
                   1121:                                close(*newsock);
                   1122:                                continue;
                   1123:                        }
                   1124:                        if (pipe(startup_p) == -1) {
                   1125:                                close(*newsock);
                   1126:                                continue;
                   1127:                        }
                   1128:
                   1129:                        if (rexec_flag && socketpair(AF_UNIX,
                   1130:                            SOCK_STREAM, 0, config_s) == -1) {
                   1131:                                error("reexec socketpair: %s",
                   1132:                                    strerror(errno));
                   1133:                                close(*newsock);
                   1134:                                close(startup_p[0]);
                   1135:                                close(startup_p[1]);
                   1136:                                continue;
                   1137:                        }
                   1138:
                   1139:                        for (j = 0; j < options.max_startups; j++)
                   1140:                                if (startup_pipes[j] == -1) {
                   1141:                                        startup_pipes[j] = startup_p[0];
                   1142:                                        if (maxfd < startup_p[0])
                   1143:                                                maxfd = startup_p[0];
                   1144:                                        startups++;
                   1145:                                        break;
                   1146:                                }
                   1147:
                   1148:                        /*
                   1149:                         * Got connection.  Fork a child to handle it, unless
                   1150:                         * we are in debugging mode.
                   1151:                         */
                   1152:                        if (debug_flag) {
                   1153:                                /*
                   1154:                                 * In debugging mode.  Close the listening
                   1155:                                 * socket, and start processing the
                   1156:                                 * connection without forking.
                   1157:                                 */
                   1158:                                debug("Server will not fork when running in debugging mode.");
                   1159:                                close_listen_socks();
                   1160:                                *sock_in = *newsock;
                   1161:                                *sock_out = *newsock;
                   1162:                                close(startup_p[0]);
                   1163:                                close(startup_p[1]);
                   1164:                                startup_pipe = -1;
                   1165:                                pid = getpid();
                   1166:                                if (rexec_flag) {
                   1167:                                        send_rexec_state(config_s[0],
                   1168:                                            &cfg);
                   1169:                                        close(config_s[0]);
                   1170:                                }
                   1171:                                break;
                   1172:                        }
                   1173:
                   1174:                        /*
                   1175:                         * Normal production daemon.  Fork, and have
                   1176:                         * the child process the connection. The
                   1177:                         * parent continues listening.
                   1178:                         */
                   1179:                        if ((pid = fork()) == 0) {
                   1180:                                /*
                   1181:                                 * Child.  Close the listening and
                   1182:                                 * max_startup sockets.  Start using
                   1183:                                 * the accepted socket. Reinitialize
                   1184:                                 * logging (since our pid has changed).
                   1185:                                 * We break out of the loop to handle
                   1186:                                 * the connection.
                   1187:                                 */
                   1188:                                startup_pipe = startup_p[1];
                   1189:                                close_startup_pipes();
                   1190:                                close_listen_socks();
                   1191:                                *sock_in = *newsock;
                   1192:                                *sock_out = *newsock;
                   1193:                                log_init(__progname,
                   1194:                                    options.log_level,
                   1195:                                    options.log_facility,
                   1196:                                    log_stderr);
                   1197:                                if (rexec_flag)
                   1198:                                        close(config_s[0]);
                   1199:                                break;
                   1200:                        }
                   1201:
                   1202:                        /* Parent.  Stay in the loop. */
                   1203:                        if (pid < 0)
                   1204:                                error("fork: %.100s", strerror(errno));
                   1205:                        else
                   1206:                                debug("Forked child %ld.", (long)pid);
                   1207:
                   1208:                        close(startup_p[1]);
                   1209:
                   1210:                        if (rexec_flag) {
                   1211:                                send_rexec_state(config_s[0], &cfg);
                   1212:                                close(config_s[0]);
                   1213:                                close(config_s[1]);
                   1214:                        }
                   1215:                        close(*newsock);
                   1216:                }
                   1217:
                   1218:                /* child process check (or debug mode) */
                   1219:                if (num_listen_socks < 0)
                   1220:                        break;
                   1221:        }
                   1222: }
                   1223:
1.466     djm      1224: /*
                   1225:  * If IP options are supported, make sure there are none (log and
                   1226:  * return an error if any are found).  Basically we are worried about
                   1227:  * source routing; it can be used to pretend you are somebody
                   1228:  * (ip-address) you are not. That itself may be "almost acceptable"
                   1229:  * under certain circumstances, but rhosts autentication is useless
                   1230:  * if source routing is accepted. Notice also that if we just dropped
                   1231:  * source routing here, the other side could use IP spoofing to do
                   1232:  * rest of the interaction and could still bypass security.  So we
                   1233:  * exit here if we detect any IP options.
                   1234:  */
                   1235: static void
                   1236: check_ip_options(struct ssh *ssh)
                   1237: {
                   1238:        int sock_in = ssh_packet_get_connection_in(ssh);
                   1239:        struct sockaddr_storage from;
                   1240:        u_char opts[200];
1.475     djm      1241:        socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1.466     djm      1242:        char text[sizeof(opts) * 3 + 1];
                   1243:
                   1244:        memset(&from, 0, sizeof(from));
                   1245:        if (getpeername(sock_in, (struct sockaddr *)&from,
                   1246:            &fromlen) < 0)
                   1247:                return;
                   1248:        if (from.ss_family != AF_INET)
                   1249:                return;
                   1250:        /* XXX IPv6 options? */
                   1251:
                   1252:        if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
                   1253:            &option_size) >= 0 && option_size != 0) {
                   1254:                text[0] = '\0';
                   1255:                for (i = 0; i < option_size; i++)
                   1256:                        snprintf(text + i*3, sizeof(text) - i*3,
                   1257:                            " %2.2x", opts[i]);
                   1258:                fatal("Connection from %.100s port %d with IP opts: %.800s",
                   1259:                    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
                   1260:        }
                   1261:        return;
                   1262: }
1.345     djm      1263:
1.65      deraadt  1264: /*
                   1265:  * Main program for the daemon.
                   1266:  */
1.2       provos   1267: int
                   1268: main(int ac, char **av)
1.1       deraadt  1269: {
1.466     djm      1270:        struct ssh *ssh = NULL;
1.64      markus   1271:        extern char *optarg;
                   1272:        extern int optind;
1.478     dtucker  1273:        int r, opt, i, j, on = 1, already_daemon;
1.297     avsm     1274:        int sock_in = -1, sock_out = -1, newsock = -1;
1.64      markus   1275:        const char *remote_ip;
                   1276:        int remote_port;
1.447     dtucker  1277:        char *fp, *line, *laddr, *logfile = NULL;
1.345     djm      1278:        int config_s[2] = { -1 , -1 };
1.396     djm      1279:        u_int n;
1.364     markus   1280:        u_int64_t ibytes, obytes;
1.362     dtucker  1281:        mode_t new_umask;
1.278     markus   1282:        Key *key;
1.404     markus   1283:        Key *pubkey;
                   1284:        int keytype;
1.230     provos   1285:        Authctxt *authctxt;
1.391     dtucker  1286:        struct connection_info *connection_info = get_connection_info(0, 0);
1.64      markus   1287:
1.465     dtucker  1288:        ssh_malloc_init();      /* must be called before any mallocs */
1.138     markus   1289:        /* Save argv. */
1.64      markus   1290:        saved_argv = av;
1.294     djm      1291:        rexec_argc = ac;
1.313     djm      1292:
                   1293:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                   1294:        sanitise_stdfd();
1.64      markus   1295:
                   1296:        /* Initialize configuration options to their default values. */
                   1297:        initialize_server_options(&options);
                   1298:
                   1299:        /* Parse command-line arguments. */
1.450     djm      1300:        while ((opt = getopt(ac, av,
                   1301:            "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1.64      markus   1302:                switch (opt) {
1.75      markus   1303:                case '4':
1.305     djm      1304:                        options.address_family = AF_INET;
1.75      markus   1305:                        break;
                   1306:                case '6':
1.305     djm      1307:                        options.address_family = AF_INET6;
1.75      markus   1308:                        break;
1.64      markus   1309:                case 'f':
                   1310:                        config_file_name = optarg;
                   1311:                        break;
1.373     djm      1312:                case 'c':
                   1313:                        if (options.num_host_cert_files >= MAX_HOSTCERTS) {
                   1314:                                fprintf(stderr, "too many host certificates.\n");
                   1315:                                exit(1);
                   1316:                        }
                   1317:                        options.host_cert_files[options.num_host_cert_files++] =
                   1318:                           derelativise_path(optarg);
                   1319:                        break;
1.64      markus   1320:                case 'd':
1.273     markus   1321:                        if (debug_flag == 0) {
1.127     markus   1322:                                debug_flag = 1;
                   1323:                                options.log_level = SYSLOG_LEVEL_DEBUG1;
1.273     markus   1324:                        } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1.127     markus   1325:                                options.log_level++;
1.64      markus   1326:                        break;
1.135     markus   1327:                case 'D':
                   1328:                        no_daemon_flag = 1;
1.192     lebel    1329:                        break;
1.399     dtucker  1330:                case 'E':
1.459     dtucker  1331:                        logfile = optarg;
1.399     dtucker  1332:                        /* FALLTHROUGH */
1.192     lebel    1333:                case 'e':
                   1334:                        log_stderr = 1;
1.135     markus   1335:                        break;
1.64      markus   1336:                case 'i':
                   1337:                        inetd_flag = 1;
                   1338:                        break;
1.294     djm      1339:                case 'r':
                   1340:                        rexec_flag = 0;
                   1341:                        break;
                   1342:                case 'R':
                   1343:                        rexeced_flag = 1;
                   1344:                        inetd_flag = 1;
                   1345:                        break;
1.64      markus   1346:                case 'Q':
1.158     markus   1347:                        /* ignored */
1.64      markus   1348:                        break;
                   1349:                case 'q':
                   1350:                        options.log_level = SYSLOG_LEVEL_QUIET;
                   1351:                        break;
                   1352:                case 'b':
1.473     naddy    1353:                        /* protocol 1, ignored */
1.64      markus   1354:                        break;
                   1355:                case 'p':
1.75      markus   1356:                        options.ports_from_cmdline = 1;
1.127     markus   1357:                        if (options.num_ports >= MAX_PORTS) {
                   1358:                                fprintf(stderr, "too many ports.\n");
                   1359:                                exit(1);
                   1360:                        }
1.193     stevesk  1361:                        options.ports[options.num_ports++] = a2port(optarg);
1.366     djm      1362:                        if (options.ports[options.num_ports-1] <= 0) {
1.193     stevesk  1363:                                fprintf(stderr, "Bad port number.\n");
                   1364:                                exit(1);
                   1365:                        }
1.64      markus   1366:                        break;
                   1367:                case 'g':
1.197     stevesk  1368:                        if ((options.login_grace_time = convtime(optarg)) == -1) {
                   1369:                                fprintf(stderr, "Invalid login grace time.\n");
                   1370:                                exit(1);
                   1371:                        }
1.64      markus   1372:                        break;
                   1373:                case 'k':
1.473     naddy    1374:                        /* protocol 1, ignored */
1.64      markus   1375:                        break;
                   1376:                case 'h':
1.134     markus   1377:                        if (options.num_host_key_files >= MAX_HOSTKEYS) {
                   1378:                                fprintf(stderr, "too many host keys.\n");
                   1379:                                exit(1);
                   1380:                        }
1.371     djm      1381:                        options.host_key_files[options.num_host_key_files++] =
                   1382:                           derelativise_path(optarg);
1.64      markus   1383:                        break;
1.203     stevesk  1384:                case 't':
                   1385:                        test_flag = 1;
                   1386:                        break;
1.358     dtucker  1387:                case 'T':
                   1388:                        test_flag = 2;
                   1389:                        break;
                   1390:                case 'C':
1.391     dtucker  1391:                        if (parse_server_match_testspec(connection_info,
                   1392:                            optarg) == -1)
                   1393:                                exit(1);
1.358     dtucker  1394:                        break;
1.125     markus   1395:                case 'u':
1.438     deraadt  1396:                        utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
                   1397:                        if (utmp_len > HOST_NAME_MAX+1) {
1.257     stevesk  1398:                                fprintf(stderr, "Invalid utmp length.\n");
                   1399:                                exit(1);
                   1400:                        }
1.125     markus   1401:                        break;
1.215     markus   1402:                case 'o':
1.283     markus   1403:                        line = xstrdup(optarg);
                   1404:                        if (process_server_config_line(&options, line,
1.391     dtucker  1405:                            "command-line", 0, NULL, NULL) != 0)
1.217     deraadt  1406:                                exit(1);
1.402     djm      1407:                        free(line);
1.215     markus   1408:                        break;
1.64      markus   1409:                case '?':
                   1410:                default:
1.215     markus   1411:                        usage();
                   1412:                        break;
1.64      markus   1413:                }
                   1414:        }
1.294     djm      1415:        if (rexeced_flag || inetd_flag)
                   1416:                rexec_flag = 0;
1.355     mbalmer  1417:        if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1.294     djm      1418:                fatal("sshd re-exec requires execution with an absolute path");
                   1419:        if (rexeced_flag)
1.296     djm      1420:                closefrom(REEXEC_MIN_FREE_FD);
                   1421:        else
                   1422:                closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1.294     djm      1423:
1.426     markus   1424: #ifdef WITH_OPENSSL
1.379     djm      1425:        OpenSSL_add_all_algorithms();
1.426     markus   1426: #endif
1.64      markus   1427:
1.399     dtucker  1428:        /* If requested, redirect the logs to the specified logfile. */
1.459     dtucker  1429:        if (logfile != NULL)
1.399     dtucker  1430:                log_redirect_stderr_to(logfile);
1.75      markus   1431:        /*
                   1432:         * Force logging to stderr until we have loaded the private host
                   1433:         * key (unless started from inetd)
                   1434:         */
1.138     markus   1435:        log_init(__progname,
1.224     markus   1436:            options.log_level == SYSLOG_LEVEL_NOT_SET ?
                   1437:            SYSLOG_LEVEL_INFO : options.log_level,
                   1438:            options.log_facility == SYSLOG_FACILITY_NOT_SET ?
                   1439:            SYSLOG_FACILITY_AUTH : options.log_facility,
1.261     markus   1440:            log_stderr || !inetd_flag);
1.75      markus   1441:
1.294     djm      1442:        sensitive_data.have_ssh2_key = 0;
                   1443:
1.358     dtucker  1444:        /*
                   1445:         * If we're doing an extended config test, make sure we have all of
                   1446:         * the parameters we need.  If we're not doing an extended test,
                   1447:         * do not silently ignore connection test params.
                   1448:         */
1.391     dtucker  1449:        if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1.358     dtucker  1450:                fatal("user, host and addr are all required when testing "
                   1451:                   "Match configs");
1.391     dtucker  1452:        if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1.358     dtucker  1453:                fatal("Config test connection parameter (-C) provided without "
                   1454:                   "test mode (-T)");
                   1455:
1.294     djm      1456:        /* Fetch our configuration */
                   1457:        buffer_init(&cfg);
                   1458:        if (rexeced_flag)
1.296     djm      1459:                recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1.448     djm      1460:        else if (strcasecmp(config_file_name, "none") != 0)
1.294     djm      1461:                load_server_config(config_file_name, &cfg);
                   1462:
1.337     dtucker  1463:        parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1.391     dtucker  1464:            &cfg, NULL);
1.64      markus   1465:
                   1466:        /* Fill in default values for those options not explicitly set. */
                   1467:        fill_default_server_options(&options);
1.350     dtucker  1468:
                   1469:        /* challenge-response is implemented via keyboard interactive */
                   1470:        if (options.challenge_response_authentication)
                   1471:                options.kbd_interactive_authentication = 1;
1.395     djm      1472:
                   1473:        /* Check that options are sensible */
                   1474:        if (options.authorized_keys_command_user == NULL &&
                   1475:            (options.authorized_keys_command != NULL &&
                   1476:            strcasecmp(options.authorized_keys_command, "none") != 0))
                   1477:                fatal("AuthorizedKeysCommand set without "
                   1478:                    "AuthorizedKeysCommandUser");
1.449     djm      1479:        if (options.authorized_principals_command_user == NULL &&
                   1480:            (options.authorized_principals_command != NULL &&
                   1481:            strcasecmp(options.authorized_principals_command, "none") != 0))
                   1482:                fatal("AuthorizedPrincipalsCommand set without "
                   1483:                    "AuthorizedPrincipalsCommandUser");
1.396     djm      1484:
                   1485:        /*
                   1486:         * Check whether there is any path through configured auth methods.
                   1487:         * Unfortunately it is not possible to verify this generally before
                   1488:         * daemonisation in the presence of Match block, but this catches
                   1489:         * and warns for trivial misconfigurations that could break login.
                   1490:         */
                   1491:        if (options.num_auth_methods != 0) {
                   1492:                for (n = 0; n < options.num_auth_methods; n++) {
                   1493:                        if (auth2_methods_valid(options.auth_methods[n],
                   1494:                            1) == 0)
                   1495:                                break;
                   1496:                }
                   1497:                if (n >= options.num_auth_methods)
                   1498:                        fatal("AuthenticationMethods cannot be satisfied by "
                   1499:                            "enabled authentication methods");
                   1500:        }
1.305     djm      1501:
1.370     dtucker  1502:        /* set default channel AF */
1.305     djm      1503:        channel_set_af(options.address_family);
1.64      markus   1504:
                   1505:        /* Check that there are no remaining arguments. */
                   1506:        if (optind < ac) {
                   1507:                fprintf(stderr, "Extra argument %s.\n", av[optind]);
                   1508:                exit(1);
                   1509:        }
                   1510:
1.397     dtucker  1511:        debug("sshd version %s, %s", SSH_VERSION,
1.426     markus   1512: #ifdef WITH_OPENSSL
                   1513:            SSLeay_version(SSLEAY_VERSION)
                   1514: #else
                   1515:            "without OpenSSL"
                   1516: #endif
                   1517:        );
1.64      markus   1518:
1.404     markus   1519:        /* load host keys */
1.329     djm      1520:        sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1.255     deraadt  1521:            sizeof(Key *));
1.404     markus   1522:        sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
                   1523:            sizeof(Key *));
                   1524:
                   1525:        if (options.host_key_agent) {
                   1526:                if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
                   1527:                        setenv(SSH_AUTHSOCKET_ENV_NAME,
                   1528:                            options.host_key_agent, 1);
1.433     djm      1529:                if ((r = ssh_get_authentication_socket(NULL)) == 0)
                   1530:                        have_agent = 1;
                   1531:                else
                   1532:                        error("Could not connect to agent \"%s\": %s",
                   1533:                            options.host_key_agent, ssh_err(r));
1.404     markus   1534:        }
1.134     markus   1535:
1.217     deraadt  1536:        for (i = 0; i < options.num_host_key_files; i++) {
1.430     djm      1537:                if (options.host_key_files[i] == NULL)
                   1538:                        continue;
1.179     markus   1539:                key = key_load_private(options.host_key_files[i], "", NULL);
1.404     markus   1540:                pubkey = key_load_public(options.host_key_files[i], NULL);
1.439     djm      1541:                if (pubkey == NULL && key != NULL)
                   1542:                        pubkey = key_demote(key);
1.179     markus   1543:                sensitive_data.host_keys[i] = key;
1.404     markus   1544:                sensitive_data.host_pubkeys[i] = pubkey;
                   1545:
1.472     markus   1546:                if (key == NULL && pubkey != NULL && have_agent) {
1.443     djm      1547:                        debug("will rely on agent for hostkey %s",
                   1548:                            options.host_key_files[i]);
1.404     markus   1549:                        keytype = pubkey->type;
                   1550:                } else if (key != NULL) {
                   1551:                        keytype = key->type;
                   1552:                } else {
1.195     markus   1553:                        error("Could not load host key: %s",
                   1554:                            options.host_key_files[i]);
1.179     markus   1555:                        sensitive_data.host_keys[i] = NULL;
1.404     markus   1556:                        sensitive_data.host_pubkeys[i] = NULL;
1.134     markus   1557:                        continue;
                   1558:                }
1.404     markus   1559:
                   1560:                switch (keytype) {
1.134     markus   1561:                case KEY_RSA:
                   1562:                case KEY_DSA:
1.378     djm      1563:                case KEY_ECDSA:
1.412     markus   1564:                case KEY_ED25519:
1.441     djm      1565:                        if (have_agent || key != NULL)
                   1566:                                sensitive_data.have_ssh2_key = 1;
1.134     markus   1567:                        break;
                   1568:                }
1.441     djm      1569:                if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
                   1570:                    SSH_FP_DEFAULT)) == NULL)
                   1571:                        fatal("sshkey_fingerprint failed");
                   1572:                debug("%s host key #%d: %s %s",
1.472     markus   1573:                    key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1.441     djm      1574:                free(fp);
1.134     markus   1575:        }
1.472     markus   1576:        if (!sensitive_data.have_ssh2_key) {
1.264     itojun   1577:                logit("sshd: no hostkeys available -- exiting.");
1.64      markus   1578:                exit(1);
                   1579:        }
                   1580:
1.373     djm      1581:        /*
                   1582:         * Load certificates. They are stored in an array at identical
                   1583:         * indices to the public keys that they relate to.
                   1584:         */
                   1585:        sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
                   1586:            sizeof(Key *));
                   1587:        for (i = 0; i < options.num_host_key_files; i++)
                   1588:                sensitive_data.host_certificates[i] = NULL;
                   1589:
                   1590:        for (i = 0; i < options.num_host_cert_files; i++) {
1.430     djm      1591:                if (options.host_cert_files[i] == NULL)
                   1592:                        continue;
1.373     djm      1593:                key = key_load_public(options.host_cert_files[i], NULL);
                   1594:                if (key == NULL) {
                   1595:                        error("Could not load host certificate: %s",
                   1596:                            options.host_cert_files[i]);
                   1597:                        continue;
                   1598:                }
                   1599:                if (!key_is_cert(key)) {
                   1600:                        error("Certificate file is not a certificate: %s",
                   1601:                            options.host_cert_files[i]);
                   1602:                        key_free(key);
                   1603:                        continue;
                   1604:                }
                   1605:                /* Find matching private key */
                   1606:                for (j = 0; j < options.num_host_key_files; j++) {
                   1607:                        if (key_equal_public(key,
                   1608:                            sensitive_data.host_keys[j])) {
                   1609:                                sensitive_data.host_certificates[j] = key;
                   1610:                                break;
                   1611:                        }
                   1612:                }
                   1613:                if (j >= options.num_host_key_files) {
                   1614:                        error("No matching private key for certificate: %s",
                   1615:                            options.host_cert_files[i]);
                   1616:                        key_free(key);
                   1617:                        continue;
                   1618:                }
                   1619:                sensitive_data.host_certificates[j] = key;
                   1620:                debug("host certificate: #%d type %d %s", j, key->type,
                   1621:                    key_type(key));
                   1622:        }
1.426     markus   1623:
1.244     markus   1624:        if (use_privsep) {
                   1625:                struct stat st;
                   1626:
1.327     deraadt  1627:                if (getpwnam(SSH_PRIVSEP_USER) == NULL)
1.244     markus   1628:                        fatal("Privilege separation user %s does not exist",
                   1629:                            SSH_PRIVSEP_USER);
                   1630:                if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
                   1631:                    (S_ISDIR(st.st_mode) == 0))
                   1632:                        fatal("Missing privilege separation directory: %s",
1.247     stevesk  1633:                            _PATH_PRIVSEP_CHROOT_DIR);
                   1634:                if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1.262     markus   1635:                        fatal("%s must be owned by root and not group or "
                   1636:                            "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1.358     dtucker  1637:        }
                   1638:
                   1639:        if (test_flag > 1) {
1.391     dtucker  1640:                if (server_match_spec_complete(connection_info) == 1)
                   1641:                        parse_server_match_config(&options, connection_info);
1.358     dtucker  1642:                dump_config(&options);
1.108     markus   1643:        }
1.203     stevesk  1644:
                   1645:        /* Configuration looks good, so exit if in test mode. */
                   1646:        if (test_flag)
                   1647:                exit(0);
1.108     markus   1648:
1.294     djm      1649:        if (rexec_flag) {
1.329     djm      1650:                rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1.294     djm      1651:                for (i = 0; i < rexec_argc; i++) {
                   1652:                        debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
                   1653:                        rexec_argv[i] = saved_argv[i];
                   1654:                }
                   1655:                rexec_argv[rexec_argc] = "-R";
                   1656:                rexec_argv[rexec_argc + 1] = NULL;
                   1657:        }
1.362     dtucker  1658:
                   1659:        /* Ensure that umask disallows at least group and world write */
                   1660:        new_umask = umask(0077) | 0022;
                   1661:        (void) umask(new_umask);
1.294     djm      1662:
1.108     markus   1663:        /* Initialize the log (it is reinitialized below in case we forked). */
1.306     dtucker  1664:        if (debug_flag && (!inetd_flag || rexeced_flag))
1.64      markus   1665:                log_stderr = 1;
1.138     markus   1666:        log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64      markus   1667:
1.108     markus   1668:        /*
1.478     dtucker  1669:         * If not in debugging mode, not started from inetd and not already
                   1670:         * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
                   1671:         * terminal, and fork.  The original process exits.
1.108     markus   1672:         */
1.478     dtucker  1673:        already_daemon = daemonized();
                   1674:        if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
1.345     djm      1675:
1.64      markus   1676:                if (daemon(0, 0) < 0)
                   1677:                        fatal("daemon() failed: %.200s", strerror(errno));
                   1678:
1.477     dtucker  1679:                disconnect_controlling_tty();
1.64      markus   1680:        }
                   1681:        /* Reinitialize the log (because of the fork above). */
1.138     markus   1682:        log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64      markus   1683:
                   1684:        /* Chdir to the root directory so that the current disk can be
                   1685:           unmounted if desired. */
1.401     dtucker  1686:        if (chdir("/") == -1)
                   1687:                error("chdir(\"/\"): %s", strerror(errno));
1.217     deraadt  1688:
1.178     markus   1689:        /* ignore SIGPIPE */
                   1690:        signal(SIGPIPE, SIG_IGN);
1.64      markus   1691:
1.345     djm      1692:        /* Get a connection, either from inetd or a listening TCP socket */
1.64      markus   1693:        if (inetd_flag) {
1.345     djm      1694:                server_accept_inetd(&sock_in, &sock_out);
1.64      markus   1695:        } else {
1.345     djm      1696:                server_listen();
1.75      markus   1697:
1.201     markus   1698:                signal(SIGHUP, sighup_handler);
1.345     djm      1699:                signal(SIGCHLD, main_sigchld_handler);
1.201     markus   1700:                signal(SIGTERM, sigterm_handler);
                   1701:                signal(SIGQUIT, sigterm_handler);
                   1702:
1.345     djm      1703:                /*
                   1704:                 * Write out the pid file after the sigterm handler
                   1705:                 * is setup and the listen sockets are bound
                   1706:                 */
1.479   ! dtucker  1707:                if (options.pid_file != NULL && !debug_flag) {
1.345     djm      1708:                        FILE *f = fopen(options.pid_file, "w");
1.201     markus   1709:
1.270     djm      1710:                        if (f == NULL) {
                   1711:                                error("Couldn't create pid file \"%s\": %s",
                   1712:                                    options.pid_file, strerror(errno));
                   1713:                        } else {
1.245     mpech    1714:                                fprintf(f, "%ld\n", (long) getpid());
1.64      markus   1715:                                fclose(f);
                   1716:                        }
                   1717:                }
                   1718:
1.345     djm      1719:                /* Accept a connection and return in a forked child */
                   1720:                server_accept_loop(&sock_in, &sock_out,
                   1721:                    &newsock, config_s);
1.1       deraadt  1722:        }
                   1723:
1.64      markus   1724:        /* This is the child processing a new connection. */
1.288     markus   1725:        setproctitle("%s", "[accepted]");
1.294     djm      1726:
1.300     markus   1727:        /*
                   1728:         * Create a new session and process group since the 4.4BSD
                   1729:         * setlogin() affects the entire process group.  We don't
                   1730:         * want the child to be able to affect the parent.
                   1731:         */
                   1732:        if (!debug_flag && !inetd_flag && setsid() < 0)
                   1733:                error("setsid: %.100s", strerror(errno));
                   1734:
1.294     djm      1735:        if (rexec_flag) {
                   1736:                int fd;
                   1737:
1.296     djm      1738:                debug("rexec start in %d out %d newsock %d pipe %d sock %d",
                   1739:                    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1.294     djm      1740:                dup2(newsock, STDIN_FILENO);
                   1741:                dup2(STDIN_FILENO, STDOUT_FILENO);
                   1742:                if (startup_pipe == -1)
1.296     djm      1743:                        close(REEXEC_STARTUP_PIPE_FD);
1.407     djm      1744:                else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
1.296     djm      1745:                        dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1.407     djm      1746:                        close(startup_pipe);
                   1747:                        startup_pipe = REEXEC_STARTUP_PIPE_FD;
                   1748:                }
1.294     djm      1749:
1.296     djm      1750:                dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1.294     djm      1751:                close(config_s[1]);
1.296     djm      1752:
1.294     djm      1753:                execv(rexec_argv[0], rexec_argv);
                   1754:
                   1755:                /* Reexec has failed, fall back and continue */
                   1756:                error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1.296     djm      1757:                recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1.294     djm      1758:                log_init(__progname, options.log_level,
                   1759:                    options.log_facility, log_stderr);
                   1760:
                   1761:                /* Clean up fds */
1.296     djm      1762:                close(REEXEC_CONFIG_PASS_FD);
                   1763:                newsock = sock_out = sock_in = dup(STDIN_FILENO);
1.294     djm      1764:                if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
                   1765:                        dup2(fd, STDIN_FILENO);
                   1766:                        dup2(fd, STDOUT_FILENO);
                   1767:                        if (fd > STDERR_FILENO)
                   1768:                                close(fd);
                   1769:                }
1.296     djm      1770:                debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
                   1771:                    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1.294     djm      1772:        }
1.372     djm      1773:
                   1774:        /* Executed child processes don't need these. */
                   1775:        fcntl(sock_out, F_SETFD, FD_CLOEXEC);
                   1776:        fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1.64      markus   1777:
1.66      markus   1778:        /*
                   1779:         * Disable the key regeneration alarm.  We will not regenerate the
                   1780:         * key since we are no longer in a position to give it to anyone. We
                   1781:         * will not restart on SIGHUP since it no longer makes sense.
                   1782:         */
1.64      markus   1783:        alarm(0);
                   1784:        signal(SIGALRM, SIG_DFL);
                   1785:        signal(SIGHUP, SIG_DFL);
                   1786:        signal(SIGTERM, SIG_DFL);
                   1787:        signal(SIGQUIT, SIG_DFL);
                   1788:        signal(SIGCHLD, SIG_DFL);
1.150     markus   1789:
1.66      markus   1790:        /*
                   1791:         * Register our connection.  This turns encryption off because we do
                   1792:         * not have a key.
                   1793:         */
1.64      markus   1794:        packet_set_connection(sock_in, sock_out);
1.312     markus   1795:        packet_set_server();
1.466     djm      1796:        ssh = active_state; /* XXX */
                   1797:        check_ip_options(ssh);
1.309     djm      1798:
                   1799:        /* Set SO_KEEPALIVE if requested. */
                   1800:        if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
                   1801:            setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
                   1802:                error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1.1       deraadt  1803:
1.466     djm      1804:        if ((remote_port = ssh_remote_port(ssh)) < 0) {
                   1805:                debug("ssh_remote_port failed");
1.310     markus   1806:                cleanup_exit(255);
                   1807:        }
1.316     dtucker  1808:
                   1809:        /*
1.331     markus   1810:         * The rest of the code depends on the fact that
1.466     djm      1811:         * ssh_remote_ipaddr() caches the remote ip, even if
1.331     markus   1812:         * the socket goes away.
                   1813:         */
1.466     djm      1814:        remote_ip = ssh_remote_ipaddr(ssh);
1.209     markus   1815:
1.64      markus   1816:        /* Log the connection. */
1.447     dtucker  1817:        laddr = get_local_ipaddr(sock_in);
1.409     djm      1818:        verbose("Connection from %s port %d on %s port %d",
1.466     djm      1819:            remote_ip, remote_port, laddr,  ssh_local_port(ssh));
1.447     dtucker  1820:        free(laddr);
1.1       deraadt  1821:
1.66      markus   1822:        /*
1.317     djm      1823:         * We don't want to listen forever unless the other side
1.66      markus   1824:         * successfully authenticates itself.  So we set up an alarm which is
                   1825:         * cleared after successful authentication.  A limit of zero
1.317     djm      1826:         * indicates no limit. Note that we don't set the alarm in debugging
1.66      markus   1827:         * mode; it is just annoying to have the server exit just when you
                   1828:         * are about to discover the bug.
                   1829:         */
1.64      markus   1830:        signal(SIGALRM, grace_alarm_handler);
                   1831:        if (!debug_flag)
                   1832:                alarm(options.login_grace_time);
                   1833:
1.466     djm      1834:        sshd_exchange_identification(ssh, sock_in, sock_out);
1.64      markus   1835:        packet_set_nonblocking();
1.1       deraadt  1836:
1.278     markus   1837:        /* allocate authentication context */
1.329     djm      1838:        authctxt = xcalloc(1, sizeof(*authctxt));
1.278     markus   1839:
                   1840:        /* XXX global for cleanup, access from other modules */
                   1841:        the_authctxt = authctxt;
                   1842:
1.307     otto     1843:        /* prepare buffer to collect messages to display to user after login */
                   1844:        buffer_init(&loginmsg);
1.374     dtucker  1845:        auth_debug_reset();
1.307     otto     1846:
1.404     markus   1847:        if (use_privsep) {
1.278     markus   1848:                if (privsep_preauth(authctxt) == 1)
1.237     markus   1849:                        goto authenticated;
1.472     markus   1850:        } else if (have_agent) {
1.432     djm      1851:                if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
                   1852:                        error("Unable to get agent socket: %s", ssh_err(r));
1.433     djm      1853:                        have_agent = 0;
1.432     djm      1854:                }
                   1855:        }
1.231     provos   1856:
1.77      markus   1857:        /* perform the key exchange */
                   1858:        /* authenticate user and start session */
1.472     markus   1859:        do_ssh2_kex();
                   1860:        do_authentication2(authctxt);
                   1861:
1.237     markus   1862:        /*
                   1863:         * If we use privilege separation, the unprivileged child transfers
                   1864:         * the current keystate and exits
                   1865:         */
                   1866:        if (use_privsep) {
1.242     mouring  1867:                mm_send_keystate(pmonitor);
1.231     provos   1868:                exit(0);
1.237     markus   1869:        }
1.231     provos   1870:
                   1871:  authenticated:
1.318     djm      1872:        /*
                   1873:         * Cancel the alarm we set to limit the time taken for
                   1874:         * authentication.
                   1875:         */
                   1876:        alarm(0);
                   1877:        signal(SIGALRM, SIG_DFL);
1.347     markus   1878:        authctxt->authenticated = 1;
1.318     djm      1879:        if (startup_pipe != -1) {
                   1880:                close(startup_pipe);
                   1881:                startup_pipe = -1;
                   1882:        }
                   1883:
1.234     markus   1884:        /*
1.231     provos   1885:         * In privilege separation, we fork another child and prepare
                   1886:         * file descriptor passing.
                   1887:         */
                   1888:        if (use_privsep) {
1.237     markus   1889:                privsep_postauth(authctxt);
                   1890:                /* the monitor process [priv] will not return */
1.231     provos   1891:        }
1.360     dtucker  1892:
                   1893:        packet_set_timeout(options.client_alive_interval,
                   1894:            options.client_alive_count_max);
1.439     djm      1895:
                   1896:        /* Try to send all our hostkeys to the client */
1.472     markus   1897:        notify_hostkeys(active_state);
1.230     provos   1898:
1.278     markus   1899:        /* Start session. */
1.230     provos   1900:        do_authenticated(authctxt);
                   1901:
1.64      markus   1902:        /* The connection has been terminated. */
1.434     markus   1903:        packet_get_bytes(&ibytes, &obytes);
1.381     djm      1904:        verbose("Transferred: sent %llu, received %llu bytes",
                   1905:            (unsigned long long)obytes, (unsigned long long)ibytes);
1.364     markus   1906:
                   1907:        verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
1.64      markus   1908:        packet_close();
1.231     provos   1909:
                   1910:        if (use_privsep)
                   1911:                mm_terminate();
                   1912:
1.64      markus   1913:        exit(0);
1.1       deraadt  1914: }
1.98      markus   1915:
1.435     markus   1916: int
                   1917: sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, size_t *slen,
1.461     markus   1918:     const u_char *data, size_t dlen, const char *alg, u_int flag)
1.404     markus   1919: {
1.432     djm      1920:        int r;
1.435     markus   1921:        u_int xxx_slen, xxx_dlen = dlen;
1.432     djm      1922:
1.404     markus   1923:        if (privkey) {
1.461     markus   1924:                if (PRIVSEP(key_sign(privkey, signature, &xxx_slen, data, xxx_dlen,
                   1925:                    alg) < 0))
1.404     markus   1926:                        fatal("%s: key_sign failed", __func__);
1.435     markus   1927:                if (slen)
                   1928:                        *slen = xxx_slen;
1.404     markus   1929:        } else if (use_privsep) {
1.461     markus   1930:                if (mm_key_sign(pubkey, signature, &xxx_slen, data, xxx_dlen,
                   1931:                    alg) < 0)
1.404     markus   1932:                        fatal("%s: pubkey_sign failed", __func__);
1.435     markus   1933:                if (slen)
                   1934:                        *slen = xxx_slen;
1.404     markus   1935:        } else {
1.435     markus   1936:                if ((r = ssh_agent_sign(auth_sock, pubkey, signature, slen,
1.461     markus   1937:                    data, dlen, alg, datafellows)) != 0)
1.432     djm      1938:                        fatal("%s: ssh_agent_sign failed: %s",
                   1939:                            __func__, ssh_err(r));
1.404     markus   1940:        }
1.435     markus   1941:        return 0;
1.404     markus   1942: }
                   1943:
1.452     djm      1944: /* SSH2 key exchange */
1.200     itojun   1945: static void
1.142     markus   1946: do_ssh2_kex(void)
1.98      markus   1947: {
1.422     markus   1948:        char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
1.435     markus   1949:        struct kex *kex;
1.437     markus   1950:        int r;
1.102     markus   1951:
1.457     djm      1952:        myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
                   1953:            options.kex_algorithms);
                   1954:        myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(
                   1955:            options.ciphers);
                   1956:        myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(
                   1957:            options.ciphers);
                   1958:        myproposal[PROPOSAL_MAC_ALGS_CTOS] =
                   1959:            myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
                   1960:
1.312     markus   1961:        if (options.compression == COMP_NONE) {
1.246     markus   1962:                myproposal[PROPOSAL_COMP_ALGS_CTOS] =
1.470     dtucker  1963:                    myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
1.102     markus   1964:        }
1.400     dtucker  1965:
                   1966:        if (options.rekey_limit || options.rekey_interval)
1.464     dtucker  1967:                packet_set_rekey_limits(options.rekey_limit,
1.400     dtucker  1968:                    (time_t)options.rekey_interval);
1.327     deraadt  1969:
1.413     djm      1970:        myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
                   1971:            list_hostkey_types());
1.134     markus   1972:
1.189     markus   1973:        /* start key exchange */
1.437     markus   1974:        if ((r = kex_setup(active_state, myproposal)) != 0)
                   1975:                fatal("kex_setup: %s", ssh_err(r));
1.435     markus   1976:        kex = active_state->kex;
1.426     markus   1977: #ifdef WITH_OPENSSL
1.263     markus   1978:        kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1.292     djm      1979:        kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1.468     djm      1980:        kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
                   1981:        kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
                   1982:        kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
1.263     markus   1983:        kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1.324     djm      1984:        kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1.378     djm      1985:        kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
1.426     markus   1986: #endif
1.410     markus   1987:        kex->kex[KEX_C25519_SHA256] = kexc25519_server;
1.186     markus   1988:        kex->server = 1;
                   1989:        kex->client_version_string=client_version_string;
                   1990:        kex->server_version_string=server_version_string;
1.373     djm      1991:        kex->load_host_public_key=&get_hostkey_public_by_type;
                   1992:        kex->load_host_private_key=&get_hostkey_private_by_type;
1.231     provos   1993:        kex->host_key_index=&get_hostkey_index;
1.404     markus   1994:        kex->sign = sshd_hostkey_sign;
1.189     markus   1995:
1.435     markus   1996:        dispatch_run(DISPATCH_BLOCK, &kex->done, active_state);
1.187     markus   1997:
                   1998:        session_id2 = kex->session_id;
                   1999:        session_id2_len = kex->session_id_len;
1.129     provos   2000:
                   2001: #ifdef DEBUG_KEXDH
                   2002:        /* send 1st encrypted/maced/compressed message */
                   2003:        packet_start(SSH2_MSG_IGNORE);
                   2004:        packet_put_cstring("markus");
                   2005:        packet_send();
                   2006:        packet_write_wait();
                   2007: #endif
1.186     markus   2008:        debug("KEX done");
1.278     markus   2009: }
                   2010:
                   2011: /* server specific fatal cleanup */
                   2012: void
                   2013: cleanup_exit(int i)
                   2014: {
1.386     djm      2015:        if (the_authctxt) {
1.278     markus   2016:                do_cleanup(the_authctxt);
1.423     djm      2017:                if (use_privsep && privsep_is_preauth &&
                   2018:                    pmonitor != NULL && pmonitor->m_pid > 1) {
1.386     djm      2019:                        debug("Killing privsep child %d", pmonitor->m_pid);
                   2020:                        if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
1.388     djm      2021:                            errno != ESRCH)
1.386     djm      2022:                                error("%s: kill(%d): %s", __func__,
                   2023:                                    pmonitor->m_pid, strerror(errno));
                   2024:                }
                   2025:        }
1.278     markus   2026:        _exit(i);
1.1       deraadt  2027: }