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

1.414   ! djm         1: /* $OpenBSD: sshd.c,v 1.413 2013/12/30 23:52:28 djm Exp $ */
1.86      markus      2: /*
1.65      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
1.126     deraadt     6:  * This program is the ssh daemon.  It listens for connections from clients,
                      7:  * and performs authentication, executes use commands or shell, and forwards
1.65      deraadt     8:  * information to/from the application to the user client over an encrypted
1.126     deraadt     9:  * connection.  This can also handle forwarding of X11, TCP/IP, and
                     10:  * authentication agent connections.
1.98      markus     11:  *
1.126     deraadt    12:  * As far as I am concerned, the code I have written for this software
                     13:  * can be used freely for any purpose.  Any derived versions of this
                     14:  * software must be clearly marked as such, and if the derived work is
                     15:  * incompatible with the protocol description in the RFC file, it must be
                     16:  * called by a name other than "ssh" or "Secure Shell".
                     17:  *
                     18:  * SSH2 implementation:
1.231     provos     19:  * Privilege Separation:
1.126     deraadt    20:  *
1.231     provos     21:  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
                     22:  * Copyright (c) 2002 Niels Provos.  All rights reserved.
1.126     deraadt    23:  *
                     24:  * Redistribution and use in source and binary forms, with or without
                     25:  * modification, are permitted provided that the following conditions
                     26:  * are met:
                     27:  * 1. Redistributions of source code must retain the above copyright
                     28:  *    notice, this list of conditions and the following disclaimer.
                     29:  * 2. Redistributions in binary form must reproduce the above copyright
                     30:  *    notice, this list of conditions and the following disclaimer in the
                     31:  *    documentation and/or other materials provided with the distribution.
                     32:  *
                     33:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     34:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     35:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     36:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     37:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     38:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     39:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     40:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     41:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     42:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.65      deraadt    43:  */
1.1       deraadt    44:
1.343     deraadt    45: #include <sys/types.h>
1.320     stevesk    46: #include <sys/ioctl.h>
1.321     stevesk    47: #include <sys/wait.h>
1.343     deraadt    48: #include <sys/tree.h>
1.323     stevesk    49: #include <sys/stat.h>
1.334     stevesk    50: #include <sys/socket.h>
1.340     stevesk    51: #include <sys/time.h>
1.357     djm        52: #include <sys/queue.h>
1.319     stevesk    53:
1.336     stevesk    54: #include <errno.h>
1.335     stevesk    55: #include <fcntl.h>
1.338     stevesk    56: #include <netdb.h>
1.319     stevesk    57: #include <paths.h>
1.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.1       deraadt    64:
1.155     markus     65: #include <openssl/dh.h>
                     66: #include <openssl/bn.h>
1.226     markus     67: #include <openssl/md5.h>
1.231     provos     68: #include <openssl/rand.h>
1.155     markus     69:
1.343     deraadt    70: #include "xmalloc.h"
1.155     markus     71: #include "ssh.h"
                     72: #include "ssh1.h"
                     73: #include "ssh2.h"
1.1       deraadt    74: #include "rsa.h"
1.171     djm        75: #include "sshpty.h"
1.1       deraadt    76: #include "packet.h"
1.155     markus     77: #include "log.h"
1.343     deraadt    78: #include "buffer.h"
1.1       deraadt    79: #include "servconf.h"
                     80: #include "uidswap.h"
1.33      markus     81: #include "compat.h"
1.155     markus     82: #include "cipher.h"
1.343     deraadt    83: #include "key.h"
1.98      markus     84: #include "kex.h"
1.129     provos     85: #include "dh.h"
1.98      markus     86: #include "myproposal.h"
1.108     markus     87: #include "authfile.h"
1.154     markus     88: #include "pathnames.h"
1.155     markus     89: #include "atomicio.h"
                     90: #include "canohost.h"
1.343     deraadt    91: #include "hostfile.h"
1.155     markus     92: #include "auth.h"
1.404     markus     93: #include "authfd.h"
1.155     markus     94: #include "misc.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_mm.h"
                    100: #include "monitor.h"
1.343     deraadt   101: #ifdef GSSAPI
                    102: #include "ssh-gss.h"
                    103: #endif
1.231     provos    104: #include "monitor_wrap.h"
1.367     andreas   105: #include "roaming.h"
1.385     djm       106: #include "ssh-sandbox.h"
1.332     stevesk   107: #include "version.h"
1.1       deraadt   108:
                    109: #ifdef LIBWRAP
                    110: #include <tcpd.h>
                    111: #include <syslog.h>
                    112: int allow_severity = LOG_INFO;
                    113: int deny_severity = LOG_WARNING;
                    114: #endif /* LIBWRAP */
                    115:
                    116: #ifndef O_NOCTTY
                    117: #define O_NOCTTY       0
                    118: #endif
                    119:
1.296     djm       120: /* Re-exec fds */
                    121: #define REEXEC_DEVCRYPTO_RESERVED_FD   (STDERR_FILENO + 1)
                    122: #define REEXEC_STARTUP_PIPE_FD         (STDERR_FILENO + 2)
                    123: #define REEXEC_CONFIG_PASS_FD          (STDERR_FILENO + 3)
                    124: #define REEXEC_MIN_FREE_FD             (STDERR_FILENO + 4)
                    125:
1.138     markus    126: extern char *__progname;
                    127:
1.1       deraadt   128: /* Server configuration options. */
                    129: ServerOptions options;
                    130:
                    131: /* Name of the server configuration file. */
1.154     markus    132: char *config_file_name = _PATH_SERVER_CONFIG_FILE;
1.1       deraadt   133:
1.105     markus    134: /*
1.65      deraadt   135:  * Debug mode flag.  This can be set on the command line.  If debug
                    136:  * mode is enabled, extra debugging output will be sent to the system
                    137:  * log, the daemon will not go to background, and will exit after processing
                    138:  * the first connection.
                    139:  */
1.1       deraadt   140: int debug_flag = 0;
                    141:
1.203     stevesk   142: /* Flag indicating that the daemon should only test the configuration and keys. */
                    143: int test_flag = 0;
                    144:
1.1       deraadt   145: /* Flag indicating that the daemon is being started from inetd. */
                    146: int inetd_flag = 0;
                    147:
1.135     markus    148: /* Flag indicating that sshd should not detach and become a daemon. */
                    149: int no_daemon_flag = 0;
                    150:
1.47      markus    151: /* debug goes to stderr unless inetd_flag is set */
                    152: int log_stderr = 0;
                    153:
1.1       deraadt   154: /* Saved arguments to main(). */
                    155: char **saved_argv;
                    156:
1.294     djm       157: /* re-exec */
                    158: int rexeced_flag = 0;
                    159: int rexec_flag = 1;
                    160: int rexec_argc = 0;
                    161: char **rexec_argv;
                    162:
1.66      markus    163: /*
1.75      markus    164:  * The sockets that the server is listening; this is used in the SIGHUP
                    165:  * signal handler.
1.66      markus    166:  */
1.75      markus    167: #define        MAX_LISTEN_SOCKS        16
                    168: int listen_socks[MAX_LISTEN_SOCKS];
                    169: int num_listen_socks = 0;
1.1       deraadt   170:
1.66      markus    171: /*
                    172:  * the client's version string, passed by sshd2 in compat mode. if != NULL,
                    173:  * sshd will skip the version-number exchange
                    174:  */
1.61      markus    175: char *client_version_string = NULL;
1.96      markus    176: char *server_version_string = NULL;
1.1       deraadt   177:
1.189     markus    178: /* for rekeying XXX fixme */
                    179: Kex *xxx_kex;
                    180:
1.404     markus    181: /* Daemon's agent connection */
                    182: AuthenticationConnection *auth_conn = NULL;
                    183: int have_agent = 0;
                    184:
1.66      markus    185: /*
                    186:  * Any really sensitive data in the application is contained in this
                    187:  * structure. The idea is that this structure could be locked into memory so
                    188:  * that the pages do not get written into swap.  However, there are some
                    189:  * problems. The private key contains BIGNUMs, and we do not (in principle)
                    190:  * have access to the internals of them, and locking just the structure is
                    191:  * not very useful.  Currently, memory locking is not implemented.
                    192:  */
1.64      markus    193: struct {
1.174     deraadt   194:        Key     *server_key;            /* ephemeral server key */
1.134     markus    195:        Key     *ssh1_host_key;         /* ssh1 host key */
                    196:        Key     **host_keys;            /* all private host keys */
1.404     markus    197:        Key     **host_pubkeys;         /* all public host keys */
1.373     djm       198:        Key     **host_certificates;    /* all public host certificates */
1.134     markus    199:        int     have_ssh1_key;
                    200:        int     have_ssh2_key;
1.169     markus    201:        u_char  ssh1_cookie[SSH_SESSION_KEY_LENGTH];
1.1       deraadt   202: } sensitive_data;
                    203:
1.66      markus    204: /*
1.151     markus    205:  * Flag indicating whether the RSA server key needs to be regenerated.
                    206:  * Is set in the SIGALRM handler and cleared when the key is regenerated.
1.66      markus    207:  */
1.212     markus    208: static volatile sig_atomic_t key_do_regen = 0;
1.1       deraadt   209:
1.199     markus    210: /* This is set to true when a signal is received. */
1.212     markus    211: static volatile sig_atomic_t received_sighup = 0;
                    212: static volatile sig_atomic_t received_sigterm = 0;
1.1       deraadt   213:
1.96      markus    214: /* session identifier, used by RSA-auth */
1.140     markus    215: u_char session_id[16];
1.96      markus    216:
1.108     markus    217: /* same for ssh2 */
1.140     markus    218: u_char *session_id2 = NULL;
1.269     markus    219: u_int session_id2_len = 0;
1.108     markus    220:
1.125     markus    221: /* record remote hostname or ip */
1.140     markus    222: u_int utmp_len = MAXHOSTNAMELEN;
1.125     markus    223:
1.211     markus    224: /* options.max_startup sized array of fd ints */
                    225: int *startup_pipes = NULL;
                    226: int startup_pipe;              /* in child */
                    227:
1.231     provos    228: /* variables used for privilege separation */
1.337     dtucker   229: int use_privsep = -1;
1.285     dtucker   230: struct monitor *pmonitor = NULL;
1.386     djm       231: int privsep_is_preauth = 1;
1.231     provos    232:
1.278     markus    233: /* global authentication context */
                    234: Authctxt *the_authctxt = NULL;
                    235:
1.337     dtucker   236: /* sshd_config buffer */
                    237: Buffer cfg;
                    238:
1.299     dtucker   239: /* message to be displayed after login */
                    240: Buffer loginmsg;
                    241:
1.1       deraadt   242: /* Prototypes for various functions defined later in this file. */
1.200     itojun    243: void destroy_sensitive_data(void);
1.231     provos    244: void demote_sensitive_data(void);
1.87      markus    245:
1.200     itojun    246: static void do_ssh1_kex(void);
                    247: static void do_ssh2_kex(void);
1.129     provos    248:
1.87      markus    249: /*
1.75      markus    250:  * Close all listening sockets
                    251:  */
1.200     itojun    252: static void
1.75      markus    253: close_listen_socks(void)
                    254: {
                    255:        int i;
1.250     deraadt   256:
1.75      markus    257:        for (i = 0; i < num_listen_socks; i++)
                    258:                close(listen_socks[i]);
                    259:        num_listen_socks = -1;
                    260: }
                    261:
1.211     markus    262: static void
                    263: close_startup_pipes(void)
                    264: {
                    265:        int i;
1.250     deraadt   266:
1.211     markus    267:        if (startup_pipes)
                    268:                for (i = 0; i < options.max_startups; i++)
                    269:                        if (startup_pipes[i] != -1)
                    270:                                close(startup_pipes[i]);
                    271: }
                    272:
1.75      markus    273: /*
1.65      deraadt   274:  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
                    275:  * the effect is to reread the configuration file (and to regenerate
                    276:  * the server key).
                    277:  */
1.327     deraadt   278:
                    279: /*ARGSUSED*/
1.200     itojun    280: static void
1.64      markus    281: sighup_handler(int sig)
1.1       deraadt   282: {
1.210     deraadt   283:        int save_errno = errno;
                    284:
1.64      markus    285:        received_sighup = 1;
                    286:        signal(SIGHUP, sighup_handler);
1.210     deraadt   287:        errno = save_errno;
1.1       deraadt   288: }
                    289:
1.65      deraadt   290: /*
                    291:  * Called from the main program after receiving SIGHUP.
                    292:  * Restarts the server.
                    293:  */
1.200     itojun    294: static void
1.165     itojun    295: sighup_restart(void)
1.1       deraadt   296: {
1.264     itojun    297:        logit("Received SIGHUP; restarting.");
1.75      markus    298:        close_listen_socks();
1.211     markus    299:        close_startup_pipes();
1.349     dtucker   300:        alarm(0);  /* alarm timer persists across exec */
1.369     dtucker   301:        signal(SIGHUP, SIG_IGN); /* will be restored after exec */
1.64      markus    302:        execv(saved_argv[0], saved_argv);
1.264     itojun    303:        logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
1.250     deraadt   304:            strerror(errno));
1.64      markus    305:        exit(1);
1.1       deraadt   306: }
                    307:
1.65      deraadt   308: /*
                    309:  * Generic signal handler for terminating signals in the master daemon.
                    310:  */
1.327     deraadt   311: /*ARGSUSED*/
1.200     itojun    312: static void
1.64      markus    313: sigterm_handler(int sig)
1.1       deraadt   314: {
1.199     markus    315:        received_sigterm = sig;
1.1       deraadt   316: }
                    317:
1.65      deraadt   318: /*
                    319:  * SIGCHLD handler.  This is called whenever a child dies.  This will then
1.199     markus    320:  * reap any zombies left by exited children.
1.65      deraadt   321:  */
1.327     deraadt   322: /*ARGSUSED*/
1.200     itojun    323: static void
1.64      markus    324: main_sigchld_handler(int sig)
1.1       deraadt   325: {
1.250     deraadt   326:        int save_errno = errno;
1.239     markus    327:        pid_t pid;
1.64      markus    328:        int status;
1.60      deraadt   329:
1.239     markus    330:        while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
                    331:            (pid < 0 && errno == EINTR))
1.64      markus    332:                ;
1.60      deraadt   333:
1.64      markus    334:        signal(SIGCHLD, main_sigchld_handler);
                    335:        errno = save_errno;
1.1       deraadt   336: }
                    337:
1.65      deraadt   338: /*
                    339:  * Signal handler for the alarm after the login grace period has expired.
                    340:  */
1.327     deraadt   341: /*ARGSUSED*/
1.200     itojun    342: static void
1.64      markus    343: grace_alarm_handler(int sig)
1.1       deraadt   344: {
1.285     dtucker   345:        if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
                    346:                kill(pmonitor->m_pid, SIGALRM);
1.394     djm       347:
                    348:        /*
                    349:         * Try to kill any processes that we have spawned, E.g. authorized
                    350:         * keys command helpers.
                    351:         */
                    352:        if (getpgid(0) == getpid()) {
                    353:                signal(SIGTERM, SIG_IGN);
                    354:                killpg(0, SIGTERM);
                    355:        }
1.285     dtucker   356:
1.64      markus    357:        /* Log error and exit. */
1.346     deraadt   358:        sigdie("Timeout before authentication for %s", get_remote_ipaddr());
1.62      markus    359: }
                    360:
1.65      deraadt   361: /*
                    362:  * Signal handler for the key regeneration alarm.  Note that this
                    363:  * alarm only occurs in the daemon waiting for connections, and it does not
                    364:  * do anything with the private key or random state before forking.
                    365:  * Thus there should be no concurrency control/asynchronous execution
                    366:  * problems.
                    367:  */
1.200     itojun    368: static void
1.174     deraadt   369: generate_ephemeral_server_key(void)
1.134     markus    370: {
1.191     markus    371:        verbose("Generating %s%d bit RSA key.",
1.185     djm       372:            sensitive_data.server_key ? "new " : "", options.server_key_bits);
1.134     markus    373:        if (sensitive_data.server_key != NULL)
                    374:                key_free(sensitive_data.server_key);
1.191     markus    375:        sensitive_data.server_key = key_generate(KEY_RSA1,
1.185     djm       376:            options.server_key_bits);
                    377:        verbose("RSA key generation complete.");
1.169     markus    378:
1.356     djm       379:        arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1.134     markus    380: }
1.147     deraadt   381:
1.327     deraadt   382: /*ARGSUSED*/
1.200     itojun    383: static void
1.64      markus    384: key_regeneration_alarm(int sig)
1.1       deraadt   385: {
1.64      markus    386:        int save_errno = errno;
1.250     deraadt   387:
1.151     markus    388:        signal(SIGALRM, SIG_DFL);
1.64      markus    389:        errno = save_errno;
1.151     markus    390:        key_do_regen = 1;
1.98      markus    391: }
                    392:
1.200     itojun    393: static void
1.96      markus    394: sshd_exchange_identification(int sock_in, int sock_out)
                    395: {
1.311     djm       396:        u_int i;
                    397:        int mismatch;
1.96      markus    398:        int remote_major, remote_minor;
1.102     markus    399:        int major, minor;
1.363     dtucker   400:        char *s, *newline = "\n";
1.96      markus    401:        char buf[256];                  /* Must not be larger than remote_version. */
                    402:        char remote_version[256];       /* Must be at least as big as buf. */
                    403:
1.103     markus    404:        if ((options.protocol & SSH_PROTO_1) &&
                    405:            (options.protocol & SSH_PROTO_2)) {
1.102     markus    406:                major = PROTOCOL_MAJOR_1;
                    407:                minor = 99;
                    408:        } else if (options.protocol & SSH_PROTO_2) {
                    409:                major = PROTOCOL_MAJOR_2;
                    410:                minor = PROTOCOL_MINOR_2;
1.363     dtucker   411:                newline = "\r\n";
1.102     markus    412:        } else {
                    413:                major = PROTOCOL_MAJOR_1;
                    414:                minor = PROTOCOL_MINOR_1;
                    415:        }
1.390     djm       416:
                    417:        xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s%s",
                    418:            major, minor, SSH_VERSION,
                    419:            *options.version_addendum == '\0' ? "" : " ",
                    420:            options.version_addendum, newline);
1.96      markus    421:
1.272     markus    422:        /* Send our protocol version identification. */
1.367     andreas   423:        if (roaming_atomicio(vwrite, sock_out, server_version_string,
1.272     markus    424:            strlen(server_version_string))
                    425:            != strlen(server_version_string)) {
                    426:                logit("Could not write ident string to %s", get_remote_ipaddr());
1.278     markus    427:                cleanup_exit(255);
1.272     markus    428:        }
                    429:
                    430:        /* Read other sides version identification. */
                    431:        memset(buf, 0, sizeof(buf));
                    432:        for (i = 0; i < sizeof(buf) - 1; i++) {
1.367     andreas   433:                if (roaming_atomicio(read, sock_in, &buf[i], 1) != 1) {
1.272     markus    434:                        logit("Did not receive identification string from %s",
                    435:                            get_remote_ipaddr());
1.278     markus    436:                        cleanup_exit(255);
1.96      markus    437:                }
1.272     markus    438:                if (buf[i] == '\r') {
                    439:                        buf[i] = 0;
                    440:                        /* Kludge for F-Secure Macintosh < 1.0.2 */
                    441:                        if (i == 12 &&
                    442:                            strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
1.96      markus    443:                                break;
1.272     markus    444:                        continue;
                    445:                }
                    446:                if (buf[i] == '\n') {
                    447:                        buf[i] = 0;
                    448:                        break;
1.96      markus    449:                }
                    450:        }
1.272     markus    451:        buf[sizeof(buf) - 1] = 0;
                    452:        client_version_string = xstrdup(buf);
1.96      markus    453:
                    454:        /*
                    455:         * Check that the versions match.  In future this might accept
                    456:         * several versions and set appropriate flags to handle them.
                    457:         */
                    458:        if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
                    459:            &remote_major, &remote_minor, remote_version) != 3) {
1.105     markus    460:                s = "Protocol mismatch.\n";
1.271     deraadt   461:                (void) atomicio(vwrite, sock_out, s, strlen(s));
1.408     djm       462:                logit("Bad protocol version identification '%.100s' "
                    463:                    "from %s port %d", client_version_string,
                    464:                    get_remote_ipaddr(), get_remote_port());
1.411     djm       465:                close(sock_in);
                    466:                close(sock_out);
1.278     markus    467:                cleanup_exit(255);
1.96      markus    468:        }
                    469:        debug("Client protocol version %d.%d; client software version %.100s",
1.217     deraadt   470:            remote_major, remote_minor, remote_version);
1.96      markus    471:
1.98      markus    472:        compat_datafellows(remote_version);
1.260     mickey    473:
1.413     djm       474:        if ((datafellows & SSH_BUG_PROBE) != 0) {
1.264     itojun    475:                logit("probed from %s with %s.  Don't panic.",
1.260     mickey    476:                    get_remote_ipaddr(), client_version_string);
1.278     markus    477:                cleanup_exit(255);
1.260     mickey    478:        }
1.413     djm       479:        if ((datafellows & SSH_BUG_SCANNER) != 0) {
1.264     itojun    480:                logit("scanned from %s with %s.  Don't panic.",
1.175     deraadt   481:                    get_remote_ipaddr(), client_version_string);
1.278     markus    482:                cleanup_exit(255);
1.175     deraadt   483:        }
1.414   ! djm       484:        if ((datafellows & SSH_BUG_RSASIGMD5) != 0) {
1.413     djm       485:                logit("Client version \"%.100s\" uses unsafe RSA signature "
                    486:                    "scheme; disabling use of RSA keys", remote_version);
1.414   ! djm       487:        }
        !           488:        if ((datafellows & SSH_BUG_DERIVEKEY) != 0) {
        !           489:                fatal("Client version \"%.100s\" uses unsafe key agreement; "
        !           490:                    "refusing connection", remote_version);
        !           491:        }
1.98      markus    492:
1.102     markus    493:        mismatch = 0;
1.214     deraadt   494:        switch (remote_major) {
1.96      markus    495:        case 1:
1.108     markus    496:                if (remote_minor == 99) {
                    497:                        if (options.protocol & SSH_PROTO_2)
                    498:                                enable_compat20();
                    499:                        else
                    500:                                mismatch = 1;
                    501:                        break;
                    502:                }
1.102     markus    503:                if (!(options.protocol & SSH_PROTO_1)) {
                    504:                        mismatch = 1;
                    505:                        break;
                    506:                }
1.96      markus    507:                if (remote_minor < 3) {
1.121     provos    508:                        packet_disconnect("Your ssh version is too old and "
1.96      markus    509:                            "is no longer supported.  Please install a newer version.");
                    510:                } else if (remote_minor == 3) {
                    511:                        /* note that this disables agent-forwarding */
                    512:                        enable_compat13();
                    513:                }
1.102     markus    514:                break;
1.98      markus    515:        case 2:
1.102     markus    516:                if (options.protocol & SSH_PROTO_2) {
1.98      markus    517:                        enable_compat20();
                    518:                        break;
                    519:                }
1.99      markus    520:                /* FALLTHROUGH */
1.105     markus    521:        default:
1.102     markus    522:                mismatch = 1;
                    523:                break;
                    524:        }
                    525:        chop(server_version_string);
                    526:        debug("Local version string %.200s", server_version_string);
                    527:
                    528:        if (mismatch) {
1.96      markus    529:                s = "Protocol major versions differ.\n";
1.271     deraadt   530:                (void) atomicio(vwrite, sock_out, s, strlen(s));
1.96      markus    531:                close(sock_in);
                    532:                close(sock_out);
1.264     itojun    533:                logit("Protocol major versions differ for %s: %.200s vs. %.200s",
1.102     markus    534:                    get_remote_ipaddr(),
                    535:                    server_version_string, client_version_string);
1.278     markus    536:                cleanup_exit(255);
1.96      markus    537:        }
1.108     markus    538: }
                    539:
1.134     markus    540: /* Destroy the host and server keys.  They will no longer be needed. */
1.108     markus    541: void
                    542: destroy_sensitive_data(void)
                    543: {
1.134     markus    544:        int i;
                    545:
                    546:        if (sensitive_data.server_key) {
                    547:                key_free(sensitive_data.server_key);
                    548:                sensitive_data.server_key = NULL;
                    549:        }
1.217     deraadt   550:        for (i = 0; i < options.num_host_key_files; i++) {
1.134     markus    551:                if (sensitive_data.host_keys[i]) {
                    552:                        key_free(sensitive_data.host_keys[i]);
                    553:                        sensitive_data.host_keys[i] = NULL;
                    554:                }
1.373     djm       555:                if (sensitive_data.host_certificates[i]) {
                    556:                        key_free(sensitive_data.host_certificates[i]);
                    557:                        sensitive_data.host_certificates[i] = NULL;
                    558:                }
1.134     markus    559:        }
                    560:        sensitive_data.ssh1_host_key = NULL;
1.169     markus    561:        memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
1.134     markus    562: }
                    563:
1.231     provos    564: /* Demote private to public keys for network child */
                    565: void
                    566: demote_sensitive_data(void)
                    567: {
                    568:        Key *tmp;
                    569:        int i;
                    570:
                    571:        if (sensitive_data.server_key) {
                    572:                tmp = key_demote(sensitive_data.server_key);
                    573:                key_free(sensitive_data.server_key);
                    574:                sensitive_data.server_key = tmp;
                    575:        }
                    576:
                    577:        for (i = 0; i < options.num_host_key_files; i++) {
                    578:                if (sensitive_data.host_keys[i]) {
                    579:                        tmp = key_demote(sensitive_data.host_keys[i]);
                    580:                        key_free(sensitive_data.host_keys[i]);
                    581:                        sensitive_data.host_keys[i] = tmp;
                    582:                        if (tmp->type == KEY_RSA1)
                    583:                                sensitive_data.ssh1_host_key = tmp;
                    584:                }
1.373     djm       585:                /* Certs do not need demotion */
1.231     provos    586:        }
                    587:
                    588:        /* We do not clear ssh1_host key and cookie.  XXX - Okay Niels? */
                    589: }
                    590:
1.233     markus    591: static void
1.231     provos    592: privsep_preauth_child(void)
                    593: {
1.254     deraadt   594:        u_int32_t rnd[256];
1.253     deraadt   595:        gid_t gidset[1];
1.250     deraadt   596:        struct passwd *pw;
1.231     provos    597:
                    598:        /* Enable challenge-response authentication for privilege separation */
                    599:        privsep_challenge_enable();
                    600:
1.356     djm       601:        arc4random_buf(rnd, sizeof(rnd));
1.254     deraadt   602:        RAND_seed(rnd, sizeof(rnd));
1.405     djm       603:        bzero(rnd, sizeof(rnd));
1.231     provos    604:
                    605:        /* Demote the private keys to public keys. */
                    606:        demote_sensitive_data();
                    607:
1.235     stevesk   608:        if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
1.240     djm       609:                fatal("Privilege separation user %s does not exist",
                    610:                    SSH_PRIVSEP_USER);
1.235     stevesk   611:        memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
                    612:        endpwent();
                    613:
1.255     deraadt   614:        /* Change our root directory */
1.232     stevesk   615:        if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
                    616:                fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
                    617:                    strerror(errno));
1.231     provos    618:        if (chdir("/") == -1)
1.236     stevesk   619:                fatal("chdir(\"/\"): %s", strerror(errno));
1.234     markus    620:
1.231     provos    621:        /* Drop our privileges */
1.235     stevesk   622:        debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
                    623:            (u_int)pw->pw_gid);
1.251     markus    624: #if 0
1.287     djm       625:        /* XXX not ready, too heavy after chroot */
1.235     stevesk   626:        do_setusercontext(pw);
1.251     markus    627: #else
                    628:        gidset[0] = pw->pw_gid;
                    629:        if (setgroups(1, gidset) < 0)
                    630:                fatal("setgroups: %.100s", strerror(errno));
                    631:        permanently_set_uid(pw);
                    632: #endif
1.231     provos    633: }
                    634:
1.278     markus    635: static int
                    636: privsep_preauth(Authctxt *authctxt)
1.237     markus    637: {
                    638:        int status;
                    639:        pid_t pid;
1.384     djm       640:        struct ssh_sandbox *box = NULL;
1.237     markus    641:
                    642:        /* Set up unprivileged child process to deal with network data */
1.242     mouring   643:        pmonitor = monitor_init();
1.237     markus    644:        /* Store a pointer to the kex for later rekeying */
1.242     mouring   645:        pmonitor->m_pkex = &xxx_kex;
1.237     markus    646:
1.393     djm       647:        if (use_privsep == PRIVSEP_ON)
1.384     djm       648:                box = ssh_sandbox_init();
1.237     markus    649:        pid = fork();
                    650:        if (pid == -1) {
                    651:                fatal("fork of unprivileged child failed");
                    652:        } else if (pid != 0) {
1.245     mpech     653:                debug2("Network child is on pid %ld", (long)pid);
1.237     markus    654:
1.392     markus    655:                pmonitor->m_pid = pid;
1.404     markus    656:                if (have_agent)
                    657:                        auth_conn = ssh_get_authentication_connection();
1.384     djm       658:                if (box != NULL)
                    659:                        ssh_sandbox_parent_preauth(box, pid);
1.278     markus    660:                monitor_child_preauth(authctxt, pmonitor);
1.237     markus    661:
                    662:                /* Sync memory */
1.242     mouring   663:                monitor_sync(pmonitor);
1.237     markus    664:
                    665:                /* Wait for the child's exit status */
1.384     djm       666:                while (waitpid(pid, &status, 0) < 0) {
1.386     djm       667:                        if (errno == EINTR)
                    668:                                continue;
                    669:                        pmonitor->m_pid = -1;
                    670:                        fatal("%s: waitpid: %s", __func__, strerror(errno));
1.384     djm       671:                }
1.386     djm       672:                privsep_is_preauth = 0;
                    673:                pmonitor->m_pid = -1;
1.384     djm       674:                if (WIFEXITED(status)) {
                    675:                        if (WEXITSTATUS(status) != 0)
                    676:                                fatal("%s: preauth child exited with status %d",
                    677:                                    __func__, WEXITSTATUS(status));
                    678:                } else if (WIFSIGNALED(status))
                    679:                        fatal("%s: preauth child terminated by signal %d",
                    680:                            __func__, WTERMSIG(status));
                    681:                if (box != NULL)
                    682:                        ssh_sandbox_parent_finish(box);
                    683:                return 1;
1.237     markus    684:        } else {
                    685:                /* child */
1.383     djm       686:                close(pmonitor->m_sendfd);
                    687:                close(pmonitor->m_log_recvfd);
1.237     markus    688:
1.383     djm       689:                /* Arrange for logging to be sent to the monitor */
                    690:                set_log_handler(mm_log_handler, pmonitor);
1.237     markus    691:
                    692:                /* Demote the child */
                    693:                if (getuid() == 0 || geteuid() == 0)
                    694:                        privsep_preauth_child();
1.238     stevesk   695:                setproctitle("%s", "[net]");
1.384     djm       696:                if (box != NULL)
                    697:                        ssh_sandbox_child(box);
                    698:
                    699:                return 0;
1.237     markus    700:        }
                    701: }
                    702:
1.233     markus    703: static void
1.237     markus    704: privsep_postauth(Authctxt *authctxt)
1.231     provos    705: {
1.354     djm       706:        u_int32_t rnd[256];
                    707:
1.231     provos    708:        if (authctxt->pw->pw_uid == 0 || options.use_login) {
                    709:                /* File descriptor passing is broken or root login */
                    710:                use_privsep = 0;
1.315     djm       711:                goto skip;
1.231     provos    712:        }
1.234     markus    713:
1.231     provos    714:        /* New socket pair */
1.242     mouring   715:        monitor_reinit(pmonitor);
1.231     provos    716:
1.242     mouring   717:        pmonitor->m_pid = fork();
                    718:        if (pmonitor->m_pid == -1)
1.231     provos    719:                fatal("fork of unprivileged child failed");
1.242     mouring   720:        else if (pmonitor->m_pid != 0) {
1.364     markus    721:                verbose("User child is on pid %ld", (long)pmonitor->m_pid);
1.307     otto      722:                buffer_clear(&loginmsg);
1.242     mouring   723:                monitor_child_postauth(pmonitor);
1.231     provos    724:
                    725:                /* NEVERREACHED */
                    726:                exit(0);
                    727:        }
                    728:
1.383     djm       729:        /* child */
                    730:
1.242     mouring   731:        close(pmonitor->m_sendfd);
1.383     djm       732:        pmonitor->m_sendfd = -1;
1.231     provos    733:
                    734:        /* Demote the private keys to public keys. */
                    735:        demote_sensitive_data();
1.354     djm       736:
1.356     djm       737:        arc4random_buf(rnd, sizeof(rnd));
1.354     djm       738:        RAND_seed(rnd, sizeof(rnd));
1.405     djm       739:        bzero(rnd, sizeof(rnd));
1.231     provos    740:
                    741:        /* Drop privileges */
                    742:        do_setusercontext(authctxt->pw);
                    743:
1.315     djm       744:  skip:
1.231     provos    745:        /* It is safe now to apply the key state */
1.242     mouring   746:        monitor_apply_keystate(pmonitor);
1.312     markus    747:
                    748:        /*
                    749:         * Tell the packet layer that authentication was successful, since
                    750:         * this information is not part of the key state.
                    751:         */
                    752:        packet_set_authenticated();
1.231     provos    753: }
                    754:
1.200     itojun    755: static char *
1.134     markus    756: list_hostkey_types(void)
                    757: {
1.223     markus    758:        Buffer b;
1.281     jakob     759:        const char *p;
                    760:        char *ret;
1.134     markus    761:        int i;
1.373     djm       762:        Key *key;
1.223     markus    763:
                    764:        buffer_init(&b);
1.217     deraadt   765:        for (i = 0; i < options.num_host_key_files; i++) {
1.373     djm       766:                key = sensitive_data.host_keys[i];
1.134     markus    767:                if (key == NULL)
1.404     markus    768:                        key = sensitive_data.host_pubkeys[i];
                    769:                if (key == NULL)
1.134     markus    770:                        continue;
1.214     deraadt   771:                switch (key->type) {
1.134     markus    772:                case KEY_RSA:
                    773:                case KEY_DSA:
1.378     djm       774:                case KEY_ECDSA:
1.412     markus    775:                case KEY_ED25519:
1.223     markus    776:                        if (buffer_len(&b) > 0)
                    777:                                buffer_append(&b, ",", 1);
                    778:                        p = key_ssh_name(key);
                    779:                        buffer_append(&b, p, strlen(p));
1.134     markus    780:                        break;
                    781:                }
1.373     djm       782:                /* If the private key has a cert peer, then list that too */
                    783:                key = sensitive_data.host_certificates[i];
                    784:                if (key == NULL)
                    785:                        continue;
                    786:                switch (key->type) {
1.375     djm       787:                case KEY_RSA_CERT_V00:
                    788:                case KEY_DSA_CERT_V00:
1.373     djm       789:                case KEY_RSA_CERT:
                    790:                case KEY_DSA_CERT:
1.378     djm       791:                case KEY_ECDSA_CERT:
1.412     markus    792:                case KEY_ED25519_CERT:
1.373     djm       793:                        if (buffer_len(&b) > 0)
                    794:                                buffer_append(&b, ",", 1);
                    795:                        p = key_ssh_name(key);
                    796:                        buffer_append(&b, p, strlen(p));
                    797:                        break;
                    798:                }
1.134     markus    799:        }
1.223     markus    800:        buffer_append(&b, "\0", 1);
1.281     jakob     801:        ret = xstrdup(buffer_ptr(&b));
1.223     markus    802:        buffer_free(&b);
1.281     jakob     803:        debug("list_hostkey_types: %s", ret);
                    804:        return ret;
1.134     markus    805: }
                    806:
1.373     djm       807: static Key *
                    808: get_hostkey_by_type(int type, int need_private)
1.134     markus    809: {
                    810:        int i;
1.373     djm       811:        Key *key;
1.250     deraadt   812:
1.217     deraadt   813:        for (i = 0; i < options.num_host_key_files; i++) {
1.375     djm       814:                switch (type) {
                    815:                case KEY_RSA_CERT_V00:
                    816:                case KEY_DSA_CERT_V00:
                    817:                case KEY_RSA_CERT:
                    818:                case KEY_DSA_CERT:
1.378     djm       819:                case KEY_ECDSA_CERT:
1.412     markus    820:                case KEY_ED25519_CERT:
1.373     djm       821:                        key = sensitive_data.host_certificates[i];
1.375     djm       822:                        break;
                    823:                default:
1.373     djm       824:                        key = sensitive_data.host_keys[i];
1.404     markus    825:                        if (key == NULL && !need_private)
                    826:                                key = sensitive_data.host_pubkeys[i];
1.375     djm       827:                        break;
                    828:                }
1.134     markus    829:                if (key != NULL && key->type == type)
1.373     djm       830:                        return need_private ?
                    831:                            sensitive_data.host_keys[i] : key;
1.134     markus    832:        }
                    833:        return NULL;
1.96      markus    834: }
                    835:
1.231     provos    836: Key *
1.373     djm       837: get_hostkey_public_by_type(int type)
                    838: {
                    839:        return get_hostkey_by_type(type, 0);
                    840: }
                    841:
                    842: Key *
                    843: get_hostkey_private_by_type(int type)
                    844: {
                    845:        return get_hostkey_by_type(type, 1);
                    846: }
                    847:
                    848: Key *
1.231     provos    849: get_hostkey_by_index(int ind)
                    850: {
                    851:        if (ind < 0 || ind >= options.num_host_key_files)
                    852:                return (NULL);
                    853:        return (sensitive_data.host_keys[ind]);
                    854: }
                    855:
1.404     markus    856: Key *
                    857: get_hostkey_public_by_index(int ind)
                    858: {
                    859:        if (ind < 0 || ind >= options.num_host_key_files)
                    860:                return (NULL);
                    861:        return (sensitive_data.host_pubkeys[ind]);
                    862: }
                    863:
1.231     provos    864: int
                    865: get_hostkey_index(Key *key)
                    866: {
                    867:        int i;
1.250     deraadt   868:
1.231     provos    869:        for (i = 0; i < options.num_host_key_files; i++) {
1.373     djm       870:                if (key_is_cert(key)) {
                    871:                        if (key == sensitive_data.host_certificates[i])
                    872:                                return (i);
                    873:                } else {
                    874:                        if (key == sensitive_data.host_keys[i])
                    875:                                return (i);
1.404     markus    876:                        if (key == sensitive_data.host_pubkeys[i])
                    877:                                return (i);
1.373     djm       878:                }
1.231     provos    879:        }
                    880:        return (-1);
                    881: }
                    882:
1.124     markus    883: /*
                    884:  * returns 1 if connection should be dropped, 0 otherwise.
                    885:  * dropping starts at connection #max_startups_begin with a probability
                    886:  * of (max_startups_rate/100). the probability increases linearly until
                    887:  * all connections are dropped for startups > max_startups
                    888:  */
1.200     itojun    889: static int
1.124     markus    890: drop_connection(int startups)
                    891: {
1.303     mickey    892:        int p, r;
1.124     markus    893:
                    894:        if (startups < options.max_startups_begin)
                    895:                return 0;
                    896:        if (startups >= options.max_startups)
                    897:                return 1;
                    898:        if (options.max_startups_rate == 100)
                    899:                return 1;
                    900:
                    901:        p  = 100 - options.max_startups_rate;
                    902:        p *= startups - options.max_startups_begin;
1.303     mickey    903:        p /= options.max_startups - options.max_startups_begin;
1.124     markus    904:        p += options.max_startups_rate;
1.356     djm       905:        r = arc4random_uniform(100);
1.124     markus    906:
1.304     djm       907:        debug("drop_connection: p %d, r %d", p, r);
1.124     markus    908:        return (r < p) ? 1 : 0;
                    909: }
                    910:
1.215     markus    911: static void
                    912: usage(void)
                    913: {
1.290     markus    914:        fprintf(stderr, "%s, %s\n",
1.280     markus    915:            SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
1.289     markus    916:        fprintf(stderr,
1.373     djm       917: "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
1.399     dtucker   918: "            [-E log_file] [-f config_file] [-g login_grace_time]\n"
                    919: "            [-h host_key_file] [-k key_gen_time] [-o option] [-p port]\n"
                    920: "            [-u len]\n"
1.289     markus    921:        );
1.215     markus    922:        exit(1);
                    923: }
                    924:
1.294     djm       925: static void
                    926: send_rexec_state(int fd, Buffer *conf)
                    927: {
                    928:        Buffer m;
                    929:
                    930:        debug3("%s: entering fd = %d config len %d", __func__, fd,
                    931:            buffer_len(conf));
                    932:
                    933:        /*
                    934:         * Protocol from reexec master to child:
                    935:         *      string  configuration
                    936:         *      u_int   ephemeral_key_follows
                    937:         *      bignum  e               (only if ephemeral_key_follows == 1)
                    938:         *      bignum  n                       "
                    939:         *      bignum  d                       "
                    940:         *      bignum  iqmp                    "
                    941:         *      bignum  p                       "
                    942:         *      bignum  q                       "
                    943:         */
                    944:        buffer_init(&m);
                    945:        buffer_put_cstring(&m, buffer_ptr(conf));
                    946:
1.298     deraadt   947:        if (sensitive_data.server_key != NULL &&
1.294     djm       948:            sensitive_data.server_key->type == KEY_RSA1) {
                    949:                buffer_put_int(&m, 1);
                    950:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
                    951:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
                    952:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
                    953:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
                    954:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
                    955:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
                    956:        } else
                    957:                buffer_put_int(&m, 0);
                    958:
                    959:        if (ssh_msg_send(fd, 0, &m) == -1)
                    960:                fatal("%s: ssh_msg_send failed", __func__);
                    961:
                    962:        buffer_free(&m);
                    963:
                    964:        debug3("%s: done", __func__);
                    965: }
                    966:
                    967: static void
                    968: recv_rexec_state(int fd, Buffer *conf)
                    969: {
                    970:        Buffer m;
                    971:        char *cp;
                    972:        u_int len;
                    973:
                    974:        debug3("%s: entering fd = %d", __func__, fd);
                    975:
                    976:        buffer_init(&m);
                    977:
                    978:        if (ssh_msg_recv(fd, &m) == -1)
                    979:                fatal("%s: ssh_msg_recv failed", __func__);
                    980:        if (buffer_get_char(&m) != 0)
                    981:                fatal("%s: rexec version mismatch", __func__);
                    982:
                    983:        cp = buffer_get_string(&m, &len);
                    984:        if (conf != NULL)
                    985:                buffer_append(conf, cp, len + 1);
1.402     djm       986:        free(cp);
1.294     djm       987:
                    988:        if (buffer_get_int(&m)) {
                    989:                if (sensitive_data.server_key != NULL)
                    990:                        key_free(sensitive_data.server_key);
                    991:                sensitive_data.server_key = key_new_private(KEY_RSA1);
                    992:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
                    993:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
                    994:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
                    995:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
                    996:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
                    997:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
                    998:                rsa_generate_additional_parameters(
                    999:                    sensitive_data.server_key->rsa);
                   1000:        }
                   1001:        buffer_free(&m);
                   1002:
                   1003:        debug3("%s: done", __func__);
                   1004: }
                   1005:
1.345     djm      1006: /* Accept a connection from inetd */
                   1007: static void
                   1008: server_accept_inetd(int *sock_in, int *sock_out)
                   1009: {
                   1010:        int fd;
                   1011:
                   1012:        startup_pipe = -1;
                   1013:        if (rexeced_flag) {
                   1014:                close(REEXEC_CONFIG_PASS_FD);
                   1015:                *sock_in = *sock_out = dup(STDIN_FILENO);
                   1016:                if (!debug_flag) {
                   1017:                        startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
                   1018:                        close(REEXEC_STARTUP_PIPE_FD);
                   1019:                }
                   1020:        } else {
                   1021:                *sock_in = dup(STDIN_FILENO);
                   1022:                *sock_out = dup(STDOUT_FILENO);
                   1023:        }
                   1024:        /*
                   1025:         * We intentionally do not close the descriptors 0, 1, and 2
                   1026:         * as our code for setting the descriptors won't work if
                   1027:         * ttyfd happens to be one of those.
                   1028:         */
                   1029:        if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
                   1030:                dup2(fd, STDIN_FILENO);
                   1031:                dup2(fd, STDOUT_FILENO);
1.403     dtucker  1032:                if (!log_stderr)
                   1033:                        dup2(fd, STDERR_FILENO);
                   1034:                if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1.345     djm      1035:                        close(fd);
                   1036:        }
                   1037:        debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
                   1038: }
                   1039:
                   1040: /*
                   1041:  * Listen for TCP connections
                   1042:  */
                   1043: static void
                   1044: server_listen(void)
                   1045: {
                   1046:        int ret, listen_sock, on = 1;
                   1047:        struct addrinfo *ai;
                   1048:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
                   1049:
                   1050:        for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
                   1051:                if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   1052:                        continue;
                   1053:                if (num_listen_socks >= MAX_LISTEN_SOCKS)
                   1054:                        fatal("Too many listen sockets. "
                   1055:                            "Enlarge MAX_LISTEN_SOCKS");
                   1056:                if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
                   1057:                    ntop, sizeof(ntop), strport, sizeof(strport),
                   1058:                    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
                   1059:                        error("getnameinfo failed: %.100s",
1.352     dtucker  1060:                            ssh_gai_strerror(ret));
1.345     djm      1061:                        continue;
                   1062:                }
                   1063:                /* Create socket for listening. */
1.370     dtucker  1064:                listen_sock = socket(ai->ai_family, ai->ai_socktype,
                   1065:                    ai->ai_protocol);
1.345     djm      1066:                if (listen_sock < 0) {
                   1067:                        /* kernel may not support ipv6 */
                   1068:                        verbose("socket: %.100s", strerror(errno));
                   1069:                        continue;
                   1070:                }
                   1071:                if (set_nonblock(listen_sock) == -1) {
                   1072:                        close(listen_sock);
                   1073:                        continue;
                   1074:                }
                   1075:                /*
                   1076:                 * Set socket options.
                   1077:                 * Allow local port reuse in TIME_WAIT.
                   1078:                 */
                   1079:                if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
                   1080:                    &on, sizeof(on)) == -1)
                   1081:                        error("setsockopt SO_REUSEADDR: %s", strerror(errno));
                   1082:
                   1083:                debug("Bind to port %s on %s.", strport, ntop);
                   1084:
                   1085:                /* Bind the socket to the desired port. */
                   1086:                if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   1087:                        error("Bind to port %s on %s failed: %.200s.",
                   1088:                            strport, ntop, strerror(errno));
                   1089:                        close(listen_sock);
                   1090:                        continue;
                   1091:                }
                   1092:                listen_socks[num_listen_socks] = listen_sock;
                   1093:                num_listen_socks++;
                   1094:
                   1095:                /* Start listening on the port. */
                   1096:                if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
                   1097:                        fatal("listen on [%s]:%s: %.100s",
                   1098:                            ntop, strport, strerror(errno));
                   1099:                logit("Server listening on %s port %s.", ntop, strport);
                   1100:        }
                   1101:        freeaddrinfo(options.listen_addrs);
                   1102:
                   1103:        if (!num_listen_socks)
                   1104:                fatal("Cannot bind any address.");
                   1105: }
                   1106:
                   1107: /*
                   1108:  * The main TCP accept loop. Note that, for the non-debug case, returns
                   1109:  * from this function are in a forked subprocess.
                   1110:  */
                   1111: static void
                   1112: server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
                   1113: {
                   1114:        fd_set *fdset;
                   1115:        int i, j, ret, maxfd;
                   1116:        int key_used = 0, startups = 0;
                   1117:        int startup_p[2] = { -1 , -1 };
                   1118:        struct sockaddr_storage from;
                   1119:        socklen_t fromlen;
                   1120:        pid_t pid;
1.405     djm      1121:        u_char rnd[256];
1.345     djm      1122:
                   1123:        /* setup fd set for accept */
                   1124:        fdset = NULL;
                   1125:        maxfd = 0;
                   1126:        for (i = 0; i < num_listen_socks; i++)
                   1127:                if (listen_socks[i] > maxfd)
                   1128:                        maxfd = listen_socks[i];
                   1129:        /* pipes connected to unauthenticated childs */
                   1130:        startup_pipes = xcalloc(options.max_startups, sizeof(int));
                   1131:        for (i = 0; i < options.max_startups; i++)
                   1132:                startup_pipes[i] = -1;
                   1133:
                   1134:        /*
                   1135:         * Stay listening for connections until the system crashes or
                   1136:         * the daemon is killed with a signal.
                   1137:         */
                   1138:        for (;;) {
                   1139:                if (received_sighup)
                   1140:                        sighup_restart();
                   1141:                if (fdset != NULL)
1.402     djm      1142:                        free(fdset);
1.345     djm      1143:                fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
                   1144:                    sizeof(fd_mask));
                   1145:
                   1146:                for (i = 0; i < num_listen_socks; i++)
                   1147:                        FD_SET(listen_socks[i], fdset);
                   1148:                for (i = 0; i < options.max_startups; i++)
                   1149:                        if (startup_pipes[i] != -1)
                   1150:                                FD_SET(startup_pipes[i], fdset);
                   1151:
                   1152:                /* Wait in select until there is a connection. */
                   1153:                ret = select(maxfd+1, fdset, NULL, NULL, NULL);
                   1154:                if (ret < 0 && errno != EINTR)
                   1155:                        error("select: %.100s", strerror(errno));
                   1156:                if (received_sigterm) {
                   1157:                        logit("Received signal %d; terminating.",
                   1158:                            (int) received_sigterm);
                   1159:                        close_listen_socks();
                   1160:                        unlink(options.pid_file);
1.382     djm      1161:                        exit(received_sigterm == SIGTERM ? 0 : 255);
1.345     djm      1162:                }
                   1163:                if (key_used && key_do_regen) {
                   1164:                        generate_ephemeral_server_key();
                   1165:                        key_used = 0;
                   1166:                        key_do_regen = 0;
                   1167:                }
                   1168:                if (ret < 0)
                   1169:                        continue;
                   1170:
                   1171:                for (i = 0; i < options.max_startups; i++)
                   1172:                        if (startup_pipes[i] != -1 &&
                   1173:                            FD_ISSET(startup_pipes[i], fdset)) {
                   1174:                                /*
                   1175:                                 * the read end of the pipe is ready
                   1176:                                 * if the child has closed the pipe
                   1177:                                 * after successful authentication
                   1178:                                 * or if the child has died
                   1179:                                 */
                   1180:                                close(startup_pipes[i]);
                   1181:                                startup_pipes[i] = -1;
                   1182:                                startups--;
                   1183:                        }
                   1184:                for (i = 0; i < num_listen_socks; i++) {
                   1185:                        if (!FD_ISSET(listen_socks[i], fdset))
                   1186:                                continue;
                   1187:                        fromlen = sizeof(from);
                   1188:                        *newsock = accept(listen_socks[i],
                   1189:                            (struct sockaddr *)&from, &fromlen);
                   1190:                        if (*newsock < 0) {
1.398     markus   1191:                                if (errno != EINTR && errno != EWOULDBLOCK &&
                   1192:                                    errno != ECONNABORTED)
1.389     djm      1193:                                        error("accept: %.100s",
                   1194:                                            strerror(errno));
                   1195:                                if (errno == EMFILE || errno == ENFILE)
                   1196:                                        usleep(100 * 1000);
1.345     djm      1197:                                continue;
                   1198:                        }
                   1199:                        if (unset_nonblock(*newsock) == -1) {
                   1200:                                close(*newsock);
                   1201:                                continue;
                   1202:                        }
                   1203:                        if (drop_connection(startups) == 1) {
                   1204:                                debug("drop connection #%d", startups);
                   1205:                                close(*newsock);
                   1206:                                continue;
                   1207:                        }
                   1208:                        if (pipe(startup_p) == -1) {
                   1209:                                close(*newsock);
                   1210:                                continue;
                   1211:                        }
                   1212:
                   1213:                        if (rexec_flag && socketpair(AF_UNIX,
                   1214:                            SOCK_STREAM, 0, config_s) == -1) {
                   1215:                                error("reexec socketpair: %s",
                   1216:                                    strerror(errno));
                   1217:                                close(*newsock);
                   1218:                                close(startup_p[0]);
                   1219:                                close(startup_p[1]);
                   1220:                                continue;
                   1221:                        }
                   1222:
                   1223:                        for (j = 0; j < options.max_startups; j++)
                   1224:                                if (startup_pipes[j] == -1) {
                   1225:                                        startup_pipes[j] = startup_p[0];
                   1226:                                        if (maxfd < startup_p[0])
                   1227:                                                maxfd = startup_p[0];
                   1228:                                        startups++;
                   1229:                                        break;
                   1230:                                }
                   1231:
                   1232:                        /*
                   1233:                         * Got connection.  Fork a child to handle it, unless
                   1234:                         * we are in debugging mode.
                   1235:                         */
                   1236:                        if (debug_flag) {
                   1237:                                /*
                   1238:                                 * In debugging mode.  Close the listening
                   1239:                                 * socket, and start processing the
                   1240:                                 * connection without forking.
                   1241:                                 */
                   1242:                                debug("Server will not fork when running in debugging mode.");
                   1243:                                close_listen_socks();
                   1244:                                *sock_in = *newsock;
                   1245:                                *sock_out = *newsock;
                   1246:                                close(startup_p[0]);
                   1247:                                close(startup_p[1]);
                   1248:                                startup_pipe = -1;
                   1249:                                pid = getpid();
                   1250:                                if (rexec_flag) {
                   1251:                                        send_rexec_state(config_s[0],
                   1252:                                            &cfg);
                   1253:                                        close(config_s[0]);
                   1254:                                }
                   1255:                                break;
                   1256:                        }
                   1257:
                   1258:                        /*
                   1259:                         * Normal production daemon.  Fork, and have
                   1260:                         * the child process the connection. The
                   1261:                         * parent continues listening.
                   1262:                         */
                   1263:                        if ((pid = fork()) == 0) {
                   1264:                                /*
                   1265:                                 * Child.  Close the listening and
                   1266:                                 * max_startup sockets.  Start using
                   1267:                                 * the accepted socket. Reinitialize
                   1268:                                 * logging (since our pid has changed).
                   1269:                                 * We break out of the loop to handle
                   1270:                                 * the connection.
                   1271:                                 */
                   1272:                                startup_pipe = startup_p[1];
                   1273:                                close_startup_pipes();
                   1274:                                close_listen_socks();
                   1275:                                *sock_in = *newsock;
                   1276:                                *sock_out = *newsock;
                   1277:                                log_init(__progname,
                   1278:                                    options.log_level,
                   1279:                                    options.log_facility,
                   1280:                                    log_stderr);
                   1281:                                if (rexec_flag)
                   1282:                                        close(config_s[0]);
                   1283:                                break;
                   1284:                        }
                   1285:
                   1286:                        /* Parent.  Stay in the loop. */
                   1287:                        if (pid < 0)
                   1288:                                error("fork: %.100s", strerror(errno));
                   1289:                        else
                   1290:                                debug("Forked child %ld.", (long)pid);
                   1291:
                   1292:                        close(startup_p[1]);
                   1293:
                   1294:                        if (rexec_flag) {
                   1295:                                send_rexec_state(config_s[0], &cfg);
                   1296:                                close(config_s[0]);
                   1297:                                close(config_s[1]);
                   1298:                        }
                   1299:
                   1300:                        /*
                   1301:                         * Mark that the key has been used (it
                   1302:                         * was "given" to the child).
                   1303:                         */
                   1304:                        if ((options.protocol & SSH_PROTO_1) &&
                   1305:                            key_used == 0) {
                   1306:                                /* Schedule server key regeneration alarm. */
                   1307:                                signal(SIGALRM, key_regeneration_alarm);
                   1308:                                alarm(options.key_regeneration_time);
                   1309:                                key_used = 1;
                   1310:                        }
                   1311:
                   1312:                        close(*newsock);
                   1313:
                   1314:                        /*
                   1315:                         * Ensure that our random state differs
                   1316:                         * from that of the child
                   1317:                         */
1.405     djm      1318:                        arc4random_buf(rnd, sizeof(rnd));
                   1319:                        RAND_seed(rnd, sizeof(rnd));
                   1320:                        bzero(rnd, sizeof(rnd));
1.345     djm      1321:                }
                   1322:
                   1323:                /* child process check (or debug mode) */
                   1324:                if (num_listen_socks < 0)
                   1325:                        break;
                   1326:        }
                   1327: }
                   1328:
                   1329:
1.65      deraadt  1330: /*
                   1331:  * Main program for the daemon.
                   1332:  */
1.2       provos   1333: int
                   1334: main(int ac, char **av)
1.1       deraadt  1335: {
1.64      markus   1336:        extern char *optarg;
                   1337:        extern int optind;
1.373     djm      1338:        int opt, i, j, on = 1;
1.297     avsm     1339:        int sock_in = -1, sock_out = -1, newsock = -1;
1.64      markus   1340:        const char *remote_ip;
                   1341:        int remote_port;
1.399     dtucker  1342:        char *line, *logfile = NULL;
1.345     djm      1343:        int config_s[2] = { -1 , -1 };
1.396     djm      1344:        u_int n;
1.364     markus   1345:        u_int64_t ibytes, obytes;
1.362     dtucker  1346:        mode_t new_umask;
1.278     markus   1347:        Key *key;
1.404     markus   1348:        Key *pubkey;
                   1349:        int keytype;
1.230     provos   1350:        Authctxt *authctxt;
1.391     dtucker  1351:        struct connection_info *connection_info = get_connection_info(0, 0);
1.64      markus   1352:
1.138     markus   1353:        /* Save argv. */
1.64      markus   1354:        saved_argv = av;
1.294     djm      1355:        rexec_argc = ac;
1.313     djm      1356:
                   1357:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                   1358:        sanitise_stdfd();
1.64      markus   1359:
                   1360:        /* Initialize configuration options to their default values. */
                   1361:        initialize_server_options(&options);
                   1362:
                   1363:        /* Parse command-line arguments. */
1.399     dtucker  1364:        while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeE:iqrtQRT46")) != -1) {
1.64      markus   1365:                switch (opt) {
1.75      markus   1366:                case '4':
1.305     djm      1367:                        options.address_family = AF_INET;
1.75      markus   1368:                        break;
                   1369:                case '6':
1.305     djm      1370:                        options.address_family = AF_INET6;
1.75      markus   1371:                        break;
1.64      markus   1372:                case 'f':
                   1373:                        config_file_name = optarg;
                   1374:                        break;
1.373     djm      1375:                case 'c':
                   1376:                        if (options.num_host_cert_files >= MAX_HOSTCERTS) {
                   1377:                                fprintf(stderr, "too many host certificates.\n");
                   1378:                                exit(1);
                   1379:                        }
                   1380:                        options.host_cert_files[options.num_host_cert_files++] =
                   1381:                           derelativise_path(optarg);
                   1382:                        break;
1.64      markus   1383:                case 'd':
1.273     markus   1384:                        if (debug_flag == 0) {
1.127     markus   1385:                                debug_flag = 1;
                   1386:                                options.log_level = SYSLOG_LEVEL_DEBUG1;
1.273     markus   1387:                        } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1.127     markus   1388:                                options.log_level++;
1.64      markus   1389:                        break;
1.135     markus   1390:                case 'D':
                   1391:                        no_daemon_flag = 1;
1.192     lebel    1392:                        break;
1.399     dtucker  1393:                case 'E':
                   1394:                        logfile = xstrdup(optarg);
                   1395:                        /* FALLTHROUGH */
1.192     lebel    1396:                case 'e':
                   1397:                        log_stderr = 1;
1.135     markus   1398:                        break;
1.64      markus   1399:                case 'i':
                   1400:                        inetd_flag = 1;
                   1401:                        break;
1.294     djm      1402:                case 'r':
                   1403:                        rexec_flag = 0;
                   1404:                        break;
                   1405:                case 'R':
                   1406:                        rexeced_flag = 1;
                   1407:                        inetd_flag = 1;
                   1408:                        break;
1.64      markus   1409:                case 'Q':
1.158     markus   1410:                        /* ignored */
1.64      markus   1411:                        break;
                   1412:                case 'q':
                   1413:                        options.log_level = SYSLOG_LEVEL_QUIET;
                   1414:                        break;
                   1415:                case 'b':
1.327     deraadt  1416:                        options.server_key_bits = (int)strtonum(optarg, 256,
                   1417:                            32768, NULL);
1.64      markus   1418:                        break;
                   1419:                case 'p':
1.75      markus   1420:                        options.ports_from_cmdline = 1;
1.127     markus   1421:                        if (options.num_ports >= MAX_PORTS) {
                   1422:                                fprintf(stderr, "too many ports.\n");
                   1423:                                exit(1);
                   1424:                        }
1.193     stevesk  1425:                        options.ports[options.num_ports++] = a2port(optarg);
1.366     djm      1426:                        if (options.ports[options.num_ports-1] <= 0) {
1.193     stevesk  1427:                                fprintf(stderr, "Bad port number.\n");
                   1428:                                exit(1);
                   1429:                        }
1.64      markus   1430:                        break;
                   1431:                case 'g':
1.197     stevesk  1432:                        if ((options.login_grace_time = convtime(optarg)) == -1) {
                   1433:                                fprintf(stderr, "Invalid login grace time.\n");
                   1434:                                exit(1);
                   1435:                        }
1.64      markus   1436:                        break;
                   1437:                case 'k':
1.197     stevesk  1438:                        if ((options.key_regeneration_time = convtime(optarg)) == -1) {
                   1439:                                fprintf(stderr, "Invalid key regeneration interval.\n");
                   1440:                                exit(1);
                   1441:                        }
1.64      markus   1442:                        break;
                   1443:                case 'h':
1.134     markus   1444:                        if (options.num_host_key_files >= MAX_HOSTKEYS) {
                   1445:                                fprintf(stderr, "too many host keys.\n");
                   1446:                                exit(1);
                   1447:                        }
1.371     djm      1448:                        options.host_key_files[options.num_host_key_files++] =
                   1449:                           derelativise_path(optarg);
1.64      markus   1450:                        break;
1.203     stevesk  1451:                case 't':
                   1452:                        test_flag = 1;
                   1453:                        break;
1.358     dtucker  1454:                case 'T':
                   1455:                        test_flag = 2;
                   1456:                        break;
                   1457:                case 'C':
1.391     dtucker  1458:                        if (parse_server_match_testspec(connection_info,
                   1459:                            optarg) == -1)
                   1460:                                exit(1);
1.358     dtucker  1461:                        break;
1.125     markus   1462:                case 'u':
1.327     deraadt  1463:                        utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1.257     stevesk  1464:                        if (utmp_len > MAXHOSTNAMELEN) {
                   1465:                                fprintf(stderr, "Invalid utmp length.\n");
                   1466:                                exit(1);
                   1467:                        }
1.125     markus   1468:                        break;
1.215     markus   1469:                case 'o':
1.283     markus   1470:                        line = xstrdup(optarg);
                   1471:                        if (process_server_config_line(&options, line,
1.391     dtucker  1472:                            "command-line", 0, NULL, NULL) != 0)
1.217     deraadt  1473:                                exit(1);
1.402     djm      1474:                        free(line);
1.215     markus   1475:                        break;
1.64      markus   1476:                case '?':
                   1477:                default:
1.215     markus   1478:                        usage();
                   1479:                        break;
1.64      markus   1480:                }
                   1481:        }
1.294     djm      1482:        if (rexeced_flag || inetd_flag)
                   1483:                rexec_flag = 0;
1.355     mbalmer  1484:        if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1.294     djm      1485:                fatal("sshd re-exec requires execution with an absolute path");
                   1486:        if (rexeced_flag)
1.296     djm      1487:                closefrom(REEXEC_MIN_FREE_FD);
                   1488:        else
                   1489:                closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1.294     djm      1490:
1.379     djm      1491:        OpenSSL_add_all_algorithms();
1.64      markus   1492:
1.399     dtucker  1493:        /* If requested, redirect the logs to the specified logfile. */
                   1494:        if (logfile != NULL) {
                   1495:                log_redirect_stderr_to(logfile);
1.402     djm      1496:                free(logfile);
1.399     dtucker  1497:        }
1.75      markus   1498:        /*
                   1499:         * Force logging to stderr until we have loaded the private host
                   1500:         * key (unless started from inetd)
                   1501:         */
1.138     markus   1502:        log_init(__progname,
1.224     markus   1503:            options.log_level == SYSLOG_LEVEL_NOT_SET ?
                   1504:            SYSLOG_LEVEL_INFO : options.log_level,
                   1505:            options.log_facility == SYSLOG_FACILITY_NOT_SET ?
                   1506:            SYSLOG_FACILITY_AUTH : options.log_facility,
1.261     markus   1507:            log_stderr || !inetd_flag);
1.75      markus   1508:
1.294     djm      1509:        sensitive_data.server_key = NULL;
                   1510:        sensitive_data.ssh1_host_key = NULL;
                   1511:        sensitive_data.have_ssh1_key = 0;
                   1512:        sensitive_data.have_ssh2_key = 0;
                   1513:
1.358     dtucker  1514:        /*
                   1515:         * If we're doing an extended config test, make sure we have all of
                   1516:         * the parameters we need.  If we're not doing an extended test,
                   1517:         * do not silently ignore connection test params.
                   1518:         */
1.391     dtucker  1519:        if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1.358     dtucker  1520:                fatal("user, host and addr are all required when testing "
                   1521:                   "Match configs");
1.391     dtucker  1522:        if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1.358     dtucker  1523:                fatal("Config test connection parameter (-C) provided without "
                   1524:                   "test mode (-T)");
                   1525:
1.294     djm      1526:        /* Fetch our configuration */
                   1527:        buffer_init(&cfg);
                   1528:        if (rexeced_flag)
1.296     djm      1529:                recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1.294     djm      1530:        else
                   1531:                load_server_config(config_file_name, &cfg);
                   1532:
1.337     dtucker  1533:        parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1.391     dtucker  1534:            &cfg, NULL);
1.64      markus   1535:
                   1536:        /* Fill in default values for those options not explicitly set. */
                   1537:        fill_default_server_options(&options);
1.350     dtucker  1538:
                   1539:        /* challenge-response is implemented via keyboard interactive */
                   1540:        if (options.challenge_response_authentication)
                   1541:                options.kbd_interactive_authentication = 1;
1.395     djm      1542:
                   1543:        /* Check that options are sensible */
                   1544:        if (options.authorized_keys_command_user == NULL &&
                   1545:            (options.authorized_keys_command != NULL &&
                   1546:            strcasecmp(options.authorized_keys_command, "none") != 0))
                   1547:                fatal("AuthorizedKeysCommand set without "
                   1548:                    "AuthorizedKeysCommandUser");
1.396     djm      1549:
                   1550:        /*
                   1551:         * Check whether there is any path through configured auth methods.
                   1552:         * Unfortunately it is not possible to verify this generally before
                   1553:         * daemonisation in the presence of Match block, but this catches
                   1554:         * and warns for trivial misconfigurations that could break login.
                   1555:         */
                   1556:        if (options.num_auth_methods != 0) {
                   1557:                if ((options.protocol & SSH_PROTO_1))
                   1558:                        fatal("AuthenticationMethods is not supported with "
                   1559:                            "SSH protocol 1");
                   1560:                for (n = 0; n < options.num_auth_methods; n++) {
                   1561:                        if (auth2_methods_valid(options.auth_methods[n],
                   1562:                            1) == 0)
                   1563:                                break;
                   1564:                }
                   1565:                if (n >= options.num_auth_methods)
                   1566:                        fatal("AuthenticationMethods cannot be satisfied by "
                   1567:                            "enabled authentication methods");
                   1568:        }
1.305     djm      1569:
1.370     dtucker  1570:        /* set default channel AF */
1.305     djm      1571:        channel_set_af(options.address_family);
1.64      markus   1572:
                   1573:        /* Check that there are no remaining arguments. */
                   1574:        if (optind < ac) {
                   1575:                fprintf(stderr, "Extra argument %s.\n", av[optind]);
                   1576:                exit(1);
                   1577:        }
                   1578:
1.397     dtucker  1579:        debug("sshd version %s, %s", SSH_VERSION,
                   1580:            SSLeay_version(SSLEAY_VERSION));
1.64      markus   1581:
1.404     markus   1582:        /* load host keys */
1.329     djm      1583:        sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1.255     deraadt  1584:            sizeof(Key *));
1.404     markus   1585:        sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
                   1586:            sizeof(Key *));
                   1587:        for (i = 0; i < options.num_host_key_files; i++) {
1.141     markus   1588:                sensitive_data.host_keys[i] = NULL;
1.404     markus   1589:                sensitive_data.host_pubkeys[i] = NULL;
                   1590:        }
                   1591:
                   1592:        if (options.host_key_agent) {
                   1593:                if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
                   1594:                        setenv(SSH_AUTHSOCKET_ENV_NAME,
                   1595:                            options.host_key_agent, 1);
                   1596:                have_agent = ssh_agent_present();
                   1597:        }
1.134     markus   1598:
1.217     deraadt  1599:        for (i = 0; i < options.num_host_key_files; i++) {
1.179     markus   1600:                key = key_load_private(options.host_key_files[i], "", NULL);
1.404     markus   1601:                pubkey = key_load_public(options.host_key_files[i], NULL);
1.179     markus   1602:                sensitive_data.host_keys[i] = key;
1.404     markus   1603:                sensitive_data.host_pubkeys[i] = pubkey;
                   1604:
                   1605:                if (key == NULL && pubkey != NULL && pubkey->type != KEY_RSA1 &&
                   1606:                    have_agent) {
                   1607:                        debug("will rely on agent for hostkey %s",
                   1608:                            options.host_key_files[i]);
                   1609:                        keytype = pubkey->type;
                   1610:                } else if (key != NULL) {
                   1611:                        keytype = key->type;
                   1612:                } else {
1.195     markus   1613:                        error("Could not load host key: %s",
                   1614:                            options.host_key_files[i]);
1.179     markus   1615:                        sensitive_data.host_keys[i] = NULL;
1.404     markus   1616:                        sensitive_data.host_pubkeys[i] = NULL;
1.134     markus   1617:                        continue;
                   1618:                }
1.404     markus   1619:
                   1620:                switch (keytype) {
1.134     markus   1621:                case KEY_RSA1:
                   1622:                        sensitive_data.ssh1_host_key = key;
                   1623:                        sensitive_data.have_ssh1_key = 1;
                   1624:                        break;
                   1625:                case KEY_RSA:
                   1626:                case KEY_DSA:
1.378     djm      1627:                case KEY_ECDSA:
1.412     markus   1628:                case KEY_ED25519:
1.134     markus   1629:                        sensitive_data.have_ssh2_key = 1;
                   1630:                        break;
                   1631:                }
1.404     markus   1632:                debug("private host key: #%d type %d %s", i, keytype,
                   1633:                    key_type(key ? key : pubkey));
1.134     markus   1634:        }
                   1635:        if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1.264     itojun   1636:                logit("Disabling protocol version 1. Could not load host key");
1.108     markus   1637:                options.protocol &= ~SSH_PROTO_1;
                   1638:        }
1.134     markus   1639:        if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1.264     itojun   1640:                logit("Disabling protocol version 2. Could not load host key");
1.134     markus   1641:                options.protocol &= ~SSH_PROTO_2;
1.108     markus   1642:        }
1.162     stevesk  1643:        if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1.264     itojun   1644:                logit("sshd: no hostkeys available -- exiting.");
1.64      markus   1645:                exit(1);
                   1646:        }
                   1647:
1.373     djm      1648:        /*
                   1649:         * Load certificates. They are stored in an array at identical
                   1650:         * indices to the public keys that they relate to.
                   1651:         */
                   1652:        sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
                   1653:            sizeof(Key *));
                   1654:        for (i = 0; i < options.num_host_key_files; i++)
                   1655:                sensitive_data.host_certificates[i] = NULL;
                   1656:
                   1657:        for (i = 0; i < options.num_host_cert_files; i++) {
                   1658:                key = key_load_public(options.host_cert_files[i], NULL);
                   1659:                if (key == NULL) {
                   1660:                        error("Could not load host certificate: %s",
                   1661:                            options.host_cert_files[i]);
                   1662:                        continue;
                   1663:                }
                   1664:                if (!key_is_cert(key)) {
                   1665:                        error("Certificate file is not a certificate: %s",
                   1666:                            options.host_cert_files[i]);
                   1667:                        key_free(key);
                   1668:                        continue;
                   1669:                }
                   1670:                /* Find matching private key */
                   1671:                for (j = 0; j < options.num_host_key_files; j++) {
                   1672:                        if (key_equal_public(key,
                   1673:                            sensitive_data.host_keys[j])) {
                   1674:                                sensitive_data.host_certificates[j] = key;
                   1675:                                break;
                   1676:                        }
                   1677:                }
                   1678:                if (j >= options.num_host_key_files) {
                   1679:                        error("No matching private key for certificate: %s",
                   1680:                            options.host_cert_files[i]);
                   1681:                        key_free(key);
                   1682:                        continue;
                   1683:                }
                   1684:                sensitive_data.host_certificates[j] = key;
                   1685:                debug("host certificate: #%d type %d %s", j, key->type,
                   1686:                    key_type(key));
                   1687:        }
1.108     markus   1688:        /* Check certain values for sanity. */
                   1689:        if (options.protocol & SSH_PROTO_1) {
                   1690:                if (options.server_key_bits < 512 ||
                   1691:                    options.server_key_bits > 32768) {
                   1692:                        fprintf(stderr, "Bad server key size.\n");
                   1693:                        exit(1);
                   1694:                }
                   1695:                /*
                   1696:                 * Check that server and host key lengths differ sufficiently. This
                   1697:                 * is necessary to make double encryption work with rsaref. Oh, I
                   1698:                 * hate software patents. I dont know if this can go? Niels
                   1699:                 */
                   1700:                if (options.server_key_bits >
1.250     deraadt  1701:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
                   1702:                    SSH_KEY_BITS_RESERVED && options.server_key_bits <
                   1703:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
                   1704:                    SSH_KEY_BITS_RESERVED) {
1.108     markus   1705:                        options.server_key_bits =
1.250     deraadt  1706:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
                   1707:                            SSH_KEY_BITS_RESERVED;
1.108     markus   1708:                        debug("Forcing server key to %d bits to make it differ from host key.",
                   1709:                            options.server_key_bits);
                   1710:                }
1.244     markus   1711:        }
                   1712:
                   1713:        if (use_privsep) {
                   1714:                struct stat st;
                   1715:
1.327     deraadt  1716:                if (getpwnam(SSH_PRIVSEP_USER) == NULL)
1.244     markus   1717:                        fatal("Privilege separation user %s does not exist",
                   1718:                            SSH_PRIVSEP_USER);
                   1719:                if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
                   1720:                    (S_ISDIR(st.st_mode) == 0))
                   1721:                        fatal("Missing privilege separation directory: %s",
1.247     stevesk  1722:                            _PATH_PRIVSEP_CHROOT_DIR);
                   1723:                if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1.262     markus   1724:                        fatal("%s must be owned by root and not group or "
                   1725:                            "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1.358     dtucker  1726:        }
                   1727:
                   1728:        if (test_flag > 1) {
1.391     dtucker  1729:                if (server_match_spec_complete(connection_info) == 1)
                   1730:                        parse_server_match_config(&options, connection_info);
1.358     dtucker  1731:                dump_config(&options);
1.108     markus   1732:        }
1.203     stevesk  1733:
                   1734:        /* Configuration looks good, so exit if in test mode. */
                   1735:        if (test_flag)
                   1736:                exit(0);
1.108     markus   1737:
1.294     djm      1738:        if (rexec_flag) {
1.329     djm      1739:                rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1.294     djm      1740:                for (i = 0; i < rexec_argc; i++) {
                   1741:                        debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
                   1742:                        rexec_argv[i] = saved_argv[i];
                   1743:                }
                   1744:                rexec_argv[rexec_argc] = "-R";
                   1745:                rexec_argv[rexec_argc + 1] = NULL;
                   1746:        }
1.362     dtucker  1747:
                   1748:        /* Ensure that umask disallows at least group and world write */
                   1749:        new_umask = umask(0077) | 0022;
                   1750:        (void) umask(new_umask);
1.294     djm      1751:
1.108     markus   1752:        /* Initialize the log (it is reinitialized below in case we forked). */
1.306     dtucker  1753:        if (debug_flag && (!inetd_flag || rexeced_flag))
1.64      markus   1754:                log_stderr = 1;
1.138     markus   1755:        log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64      markus   1756:
1.108     markus   1757:        /*
                   1758:         * If not in debugging mode, and not started from inetd, disconnect
                   1759:         * from the controlling terminal, and fork.  The original process
                   1760:         * exits.
                   1761:         */
1.135     markus   1762:        if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1.64      markus   1763:                int fd;
1.345     djm      1764:
1.64      markus   1765:                if (daemon(0, 0) < 0)
                   1766:                        fatal("daemon() failed: %.200s", strerror(errno));
                   1767:
                   1768:                /* Disconnect from the controlling tty. */
1.165     itojun   1769:                fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1.64      markus   1770:                if (fd >= 0) {
                   1771:                        (void) ioctl(fd, TIOCNOTTY, NULL);
                   1772:                        close(fd);
                   1773:                }
                   1774:        }
                   1775:        /* Reinitialize the log (because of the fork above). */
1.138     markus   1776:        log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64      markus   1777:
                   1778:        /* Chdir to the root directory so that the current disk can be
                   1779:           unmounted if desired. */
1.401     dtucker  1780:        if (chdir("/") == -1)
                   1781:                error("chdir(\"/\"): %s", strerror(errno));
1.217     deraadt  1782:
1.178     markus   1783:        /* ignore SIGPIPE */
                   1784:        signal(SIGPIPE, SIG_IGN);
1.64      markus   1785:
1.345     djm      1786:        /* Get a connection, either from inetd or a listening TCP socket */
1.64      markus   1787:        if (inetd_flag) {
1.345     djm      1788:                server_accept_inetd(&sock_in, &sock_out);
1.64      markus   1789:        } else {
1.345     djm      1790:                server_listen();
1.75      markus   1791:
1.201     markus   1792:                if (options.protocol & SSH_PROTO_1)
                   1793:                        generate_ephemeral_server_key();
                   1794:
                   1795:                signal(SIGHUP, sighup_handler);
1.345     djm      1796:                signal(SIGCHLD, main_sigchld_handler);
1.201     markus   1797:                signal(SIGTERM, sigterm_handler);
                   1798:                signal(SIGQUIT, sigterm_handler);
                   1799:
1.345     djm      1800:                /*
                   1801:                 * Write out the pid file after the sigterm handler
                   1802:                 * is setup and the listen sockets are bound
                   1803:                 */
                   1804:                if (!debug_flag) {
                   1805:                        FILE *f = fopen(options.pid_file, "w");
1.201     markus   1806:
1.270     djm      1807:                        if (f == NULL) {
                   1808:                                error("Couldn't create pid file \"%s\": %s",
                   1809:                                    options.pid_file, strerror(errno));
                   1810:                        } else {
1.245     mpech    1811:                                fprintf(f, "%ld\n", (long) getpid());
1.64      markus   1812:                                fclose(f);
                   1813:                        }
                   1814:                }
                   1815:
1.345     djm      1816:                /* Accept a connection and return in a forked child */
                   1817:                server_accept_loop(&sock_in, &sock_out,
                   1818:                    &newsock, config_s);
1.1       deraadt  1819:        }
                   1820:
1.64      markus   1821:        /* This is the child processing a new connection. */
1.288     markus   1822:        setproctitle("%s", "[accepted]");
1.294     djm      1823:
1.300     markus   1824:        /*
                   1825:         * Create a new session and process group since the 4.4BSD
                   1826:         * setlogin() affects the entire process group.  We don't
                   1827:         * want the child to be able to affect the parent.
                   1828:         */
                   1829:        if (!debug_flag && !inetd_flag && setsid() < 0)
                   1830:                error("setsid: %.100s", strerror(errno));
                   1831:
1.294     djm      1832:        if (rexec_flag) {
                   1833:                int fd;
                   1834:
1.296     djm      1835:                debug("rexec start in %d out %d newsock %d pipe %d sock %d",
                   1836:                    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1.294     djm      1837:                dup2(newsock, STDIN_FILENO);
                   1838:                dup2(STDIN_FILENO, STDOUT_FILENO);
                   1839:                if (startup_pipe == -1)
1.296     djm      1840:                        close(REEXEC_STARTUP_PIPE_FD);
1.407     djm      1841:                else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
1.296     djm      1842:                        dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1.407     djm      1843:                        close(startup_pipe);
                   1844:                        startup_pipe = REEXEC_STARTUP_PIPE_FD;
                   1845:                }
1.294     djm      1846:
1.296     djm      1847:                dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1.294     djm      1848:                close(config_s[1]);
1.296     djm      1849:
1.294     djm      1850:                execv(rexec_argv[0], rexec_argv);
                   1851:
                   1852:                /* Reexec has failed, fall back and continue */
                   1853:                error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1.296     djm      1854:                recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1.294     djm      1855:                log_init(__progname, options.log_level,
                   1856:                    options.log_facility, log_stderr);
                   1857:
                   1858:                /* Clean up fds */
1.296     djm      1859:                close(REEXEC_CONFIG_PASS_FD);
                   1860:                newsock = sock_out = sock_in = dup(STDIN_FILENO);
1.294     djm      1861:                if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
                   1862:                        dup2(fd, STDIN_FILENO);
                   1863:                        dup2(fd, STDOUT_FILENO);
                   1864:                        if (fd > STDERR_FILENO)
                   1865:                                close(fd);
                   1866:                }
1.296     djm      1867:                debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
                   1868:                    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1.294     djm      1869:        }
1.372     djm      1870:
                   1871:        /* Executed child processes don't need these. */
                   1872:        fcntl(sock_out, F_SETFD, FD_CLOEXEC);
                   1873:        fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1.64      markus   1874:
1.66      markus   1875:        /*
                   1876:         * Disable the key regeneration alarm.  We will not regenerate the
                   1877:         * key since we are no longer in a position to give it to anyone. We
                   1878:         * will not restart on SIGHUP since it no longer makes sense.
                   1879:         */
1.64      markus   1880:        alarm(0);
                   1881:        signal(SIGALRM, SIG_DFL);
                   1882:        signal(SIGHUP, SIG_DFL);
                   1883:        signal(SIGTERM, SIG_DFL);
                   1884:        signal(SIGQUIT, SIG_DFL);
                   1885:        signal(SIGCHLD, SIG_DFL);
1.150     markus   1886:
1.66      markus   1887:        /*
                   1888:         * Register our connection.  This turns encryption off because we do
                   1889:         * not have a key.
                   1890:         */
1.64      markus   1891:        packet_set_connection(sock_in, sock_out);
1.312     markus   1892:        packet_set_server();
1.309     djm      1893:
                   1894:        /* Set SO_KEEPALIVE if requested. */
                   1895:        if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
                   1896:            setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
                   1897:                error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1.1       deraadt  1898:
1.310     markus   1899:        if ((remote_port = get_remote_port()) < 0) {
                   1900:                debug("get_remote_port failed");
                   1901:                cleanup_exit(255);
                   1902:        }
1.316     dtucker  1903:
                   1904:        /*
                   1905:         * We use get_canonical_hostname with usedns = 0 instead of
                   1906:         * get_remote_ipaddr here so IP options will be checked.
                   1907:         */
1.331     markus   1908:        (void) get_canonical_hostname(0);
                   1909:        /*
                   1910:         * The rest of the code depends on the fact that
                   1911:         * get_remote_ipaddr() caches the remote ip, even if
                   1912:         * the socket goes away.
                   1913:         */
                   1914:        remote_ip = get_remote_ipaddr();
1.52      markus   1915:
1.209     markus   1916: #ifdef LIBWRAP
1.64      markus   1917:        /* Check whether logins are denied from this host. */
1.295     djm      1918:        if (packet_connection_is_on_socket()) {
1.64      markus   1919:                struct request_info req;
1.37      dugsong  1920:
1.204     camield  1921:                request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1.64      markus   1922:                fromhost(&req);
1.37      dugsong  1923:
1.64      markus   1924:                if (!hosts_access(&req)) {
1.209     markus   1925:                        debug("Connection refused by tcp wrapper");
1.182     markus   1926:                        refuse(&req);
1.209     markus   1927:                        /* NOTREACHED */
                   1928:                        fatal("libwrap refuse returns");
1.64      markus   1929:                }
                   1930:        }
1.75      markus   1931: #endif /* LIBWRAP */
1.209     markus   1932:
1.64      markus   1933:        /* Log the connection. */
1.409     djm      1934:        verbose("Connection from %s port %d on %s port %d",
                   1935:            remote_ip, remote_port,
                   1936:            get_local_ipaddr(sock_in), get_local_port());
1.1       deraadt  1937:
1.66      markus   1938:        /*
1.317     djm      1939:         * We don't want to listen forever unless the other side
1.66      markus   1940:         * successfully authenticates itself.  So we set up an alarm which is
                   1941:         * cleared after successful authentication.  A limit of zero
1.317     djm      1942:         * indicates no limit. Note that we don't set the alarm in debugging
1.66      markus   1943:         * mode; it is just annoying to have the server exit just when you
                   1944:         * are about to discover the bug.
                   1945:         */
1.64      markus   1946:        signal(SIGALRM, grace_alarm_handler);
                   1947:        if (!debug_flag)
                   1948:                alarm(options.login_grace_time);
                   1949:
1.96      markus   1950:        sshd_exchange_identification(sock_in, sock_out);
1.353     dtucker  1951:
                   1952:        /* In inetd mode, generate ephemeral key only for proto 1 connections */
                   1953:        if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
                   1954:                generate_ephemeral_server_key();
1.275     markus   1955:
1.64      markus   1956:        packet_set_nonblocking();
1.1       deraadt  1957:
1.278     markus   1958:        /* allocate authentication context */
1.329     djm      1959:        authctxt = xcalloc(1, sizeof(*authctxt));
1.278     markus   1960:
                   1961:        /* XXX global for cleanup, access from other modules */
                   1962:        the_authctxt = authctxt;
                   1963:
1.307     otto     1964:        /* prepare buffer to collect messages to display to user after login */
                   1965:        buffer_init(&loginmsg);
1.374     dtucker  1966:        auth_debug_reset();
1.307     otto     1967:
1.404     markus   1968:        if (use_privsep) {
1.278     markus   1969:                if (privsep_preauth(authctxt) == 1)
1.237     markus   1970:                        goto authenticated;
1.404     markus   1971:        } else if (compat20 && have_agent)
                   1972:                auth_conn = ssh_get_authentication_connection();
1.231     provos   1973:
1.77      markus   1974:        /* perform the key exchange */
                   1975:        /* authenticate user and start session */
1.98      markus   1976:        if (compat20) {
                   1977:                do_ssh2_kex();
1.278     markus   1978:                do_authentication2(authctxt);
1.98      markus   1979:        } else {
                   1980:                do_ssh1_kex();
1.278     markus   1981:                do_authentication(authctxt);
1.98      markus   1982:        }
1.237     markus   1983:        /*
                   1984:         * If we use privilege separation, the unprivileged child transfers
                   1985:         * the current keystate and exits
                   1986:         */
                   1987:        if (use_privsep) {
1.242     mouring  1988:                mm_send_keystate(pmonitor);
1.231     provos   1989:                exit(0);
1.237     markus   1990:        }
1.231     provos   1991:
                   1992:  authenticated:
1.318     djm      1993:        /*
                   1994:         * Cancel the alarm we set to limit the time taken for
                   1995:         * authentication.
                   1996:         */
                   1997:        alarm(0);
                   1998:        signal(SIGALRM, SIG_DFL);
1.347     markus   1999:        authctxt->authenticated = 1;
1.318     djm      2000:        if (startup_pipe != -1) {
                   2001:                close(startup_pipe);
                   2002:                startup_pipe = -1;
                   2003:        }
                   2004:
1.234     markus   2005:        /*
1.231     provos   2006:         * In privilege separation, we fork another child and prepare
                   2007:         * file descriptor passing.
                   2008:         */
                   2009:        if (use_privsep) {
1.237     markus   2010:                privsep_postauth(authctxt);
                   2011:                /* the monitor process [priv] will not return */
1.231     provos   2012:                if (!compat20)
                   2013:                        destroy_sensitive_data();
                   2014:        }
1.360     dtucker  2015:
                   2016:        packet_set_timeout(options.client_alive_interval,
                   2017:            options.client_alive_count_max);
1.230     provos   2018:
1.278     markus   2019:        /* Start session. */
1.230     provos   2020:        do_authenticated(authctxt);
                   2021:
1.64      markus   2022:        /* The connection has been terminated. */
1.364     markus   2023:        packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
                   2024:        packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1.381     djm      2025:        verbose("Transferred: sent %llu, received %llu bytes",
                   2026:            (unsigned long long)obytes, (unsigned long long)ibytes);
1.364     markus   2027:
                   2028:        verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
1.64      markus   2029:        packet_close();
1.231     provos   2030:
                   2031:        if (use_privsep)
                   2032:                mm_terminate();
                   2033:
1.64      markus   2034:        exit(0);
1.1       deraadt  2035: }
                   2036:
1.65      deraadt  2037: /*
1.229     markus   2038:  * Decrypt session_key_int using our private server key and private host key
                   2039:  * (key with larger modulus first).
                   2040:  */
1.231     provos   2041: int
1.229     markus   2042: ssh1_session_key(BIGNUM *session_key_int)
                   2043: {
                   2044:        int rsafail = 0;
                   2045:
1.327     deraadt  2046:        if (BN_cmp(sensitive_data.server_key->rsa->n,
                   2047:            sensitive_data.ssh1_host_key->rsa->n) > 0) {
1.229     markus   2048:                /* Server key has bigger modulus. */
                   2049:                if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1.327     deraadt  2050:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
                   2051:                    SSH_KEY_BITS_RESERVED) {
                   2052:                        fatal("do_connection: %s: "
                   2053:                            "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1.229     markus   2054:                            get_remote_ipaddr(),
                   2055:                            BN_num_bits(sensitive_data.server_key->rsa->n),
                   2056:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
                   2057:                            SSH_KEY_BITS_RESERVED);
                   2058:                }
                   2059:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   2060:                    sensitive_data.server_key->rsa) <= 0)
                   2061:                        rsafail++;
                   2062:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   2063:                    sensitive_data.ssh1_host_key->rsa) <= 0)
                   2064:                        rsafail++;
                   2065:        } else {
                   2066:                /* Host key has bigger modulus (or they are equal). */
                   2067:                if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1.327     deraadt  2068:                    BN_num_bits(sensitive_data.server_key->rsa->n) +
                   2069:                    SSH_KEY_BITS_RESERVED) {
                   2070:                        fatal("do_connection: %s: "
                   2071:                            "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1.229     markus   2072:                            get_remote_ipaddr(),
                   2073:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
                   2074:                            BN_num_bits(sensitive_data.server_key->rsa->n),
                   2075:                            SSH_KEY_BITS_RESERVED);
                   2076:                }
                   2077:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   2078:                    sensitive_data.ssh1_host_key->rsa) < 0)
                   2079:                        rsafail++;
                   2080:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   2081:                    sensitive_data.server_key->rsa) < 0)
                   2082:                        rsafail++;
                   2083:        }
                   2084:        return (rsafail);
                   2085: }
                   2086: /*
1.77      markus   2087:  * SSH1 key exchange
1.65      deraadt  2088:  */
1.200     itojun   2089: static void
1.142     markus   2090: do_ssh1_kex(void)
1.1       deraadt  2091: {
1.64      markus   2092:        int i, len;
1.159     markus   2093:        int rsafail = 0;
1.64      markus   2094:        BIGNUM *session_key_int;
1.140     markus   2095:        u_char session_key[SSH_SESSION_KEY_LENGTH];
                   2096:        u_char cookie[8];
                   2097:        u_int cipher_type, auth_mask, protocol_flags;
1.64      markus   2098:
1.66      markus   2099:        /*
                   2100:         * Generate check bytes that the client must send back in the user
                   2101:         * packet in order for it to be accepted; this is used to defy ip
                   2102:         * spoofing attacks.  Note that this only works against somebody
                   2103:         * doing IP spoofing from a remote machine; any machine on the local
                   2104:         * network can still see outgoing packets and catch the random
                   2105:         * cookie.  This only affects rhosts authentication, and this is one
                   2106:         * of the reasons why it is inherently insecure.
                   2107:         */
1.356     djm      2108:        arc4random_buf(cookie, sizeof(cookie));
1.64      markus   2109:
1.66      markus   2110:        /*
                   2111:         * Send our public key.  We include in the packet 64 bits of random
                   2112:         * data that must be matched in the reply in order to prevent IP
                   2113:         * spoofing.
                   2114:         */
1.64      markus   2115:        packet_start(SSH_SMSG_PUBLIC_KEY);
                   2116:        for (i = 0; i < 8; i++)
1.77      markus   2117:                packet_put_char(cookie[i]);
1.64      markus   2118:
                   2119:        /* Store our public server RSA key. */
1.134     markus   2120:        packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
                   2121:        packet_put_bignum(sensitive_data.server_key->rsa->e);
                   2122:        packet_put_bignum(sensitive_data.server_key->rsa->n);
1.64      markus   2123:
                   2124:        /* Store our public host RSA key. */
1.134     markus   2125:        packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
                   2126:        packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
                   2127:        packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1.64      markus   2128:
                   2129:        /* Put protocol flags. */
                   2130:        packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
                   2131:
                   2132:        /* Declare which ciphers we support. */
1.131     markus   2133:        packet_put_int(cipher_mask_ssh1(0));
1.64      markus   2134:
                   2135:        /* Declare supported authentication types. */
                   2136:        auth_mask = 0;
                   2137:        if (options.rhosts_rsa_authentication)
                   2138:                auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
                   2139:        if (options.rsa_authentication)
                   2140:                auth_mask |= 1 << SSH_AUTH_RSA;
1.196     markus   2141:        if (options.challenge_response_authentication == 1)
1.64      markus   2142:                auth_mask |= 1 << SSH_AUTH_TIS;
                   2143:        if (options.password_authentication)
                   2144:                auth_mask |= 1 << SSH_AUTH_PASSWORD;
                   2145:        packet_put_int(auth_mask);
                   2146:
                   2147:        /* Send the packet and wait for it to be sent. */
                   2148:        packet_send();
                   2149:        packet_write_wait();
                   2150:
1.134     markus   2151:        debug("Sent %d bit server key and %d bit host key.",
                   2152:            BN_num_bits(sensitive_data.server_key->rsa->n),
                   2153:            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1.64      markus   2154:
                   2155:        /* Read clients reply (cipher type and session key). */
1.222     markus   2156:        packet_read_expect(SSH_CMSG_SESSION_KEY);
1.64      markus   2157:
1.69      markus   2158:        /* Get cipher type and check whether we accept this. */
1.64      markus   2159:        cipher_type = packet_get_char();
1.69      markus   2160:
1.131     markus   2161:        if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1.69      markus   2162:                packet_disconnect("Warning: client selects unsupported cipher.");
1.64      markus   2163:
                   2164:        /* Get check bytes from the packet.  These must match those we
                   2165:           sent earlier with the public key packet. */
                   2166:        for (i = 0; i < 8; i++)
1.77      markus   2167:                if (cookie[i] != packet_get_char())
1.64      markus   2168:                        packet_disconnect("IP Spoofing check bytes do not match.");
                   2169:
                   2170:        debug("Encryption type: %.200s", cipher_name(cipher_type));
                   2171:
                   2172:        /* Get the encrypted integer. */
1.218     markus   2173:        if ((session_key_int = BN_new()) == NULL)
                   2174:                fatal("do_ssh1_kex: BN_new failed");
1.221     markus   2175:        packet_get_bignum(session_key_int);
1.64      markus   2176:
                   2177:        protocol_flags = packet_get_int();
                   2178:        packet_set_protocol_flags(protocol_flags);
1.220     markus   2179:        packet_check_eom();
1.64      markus   2180:
1.229     markus   2181:        /* Decrypt session_key_int using host/server keys */
1.231     provos   2182:        rsafail = PRIVSEP(ssh1_session_key(session_key_int));
                   2183:
1.66      markus   2184:        /*
                   2185:         * Extract session key from the decrypted integer.  The key is in the
                   2186:         * least significant 256 bits of the integer; the first byte of the
                   2187:         * key is in the highest bits.
                   2188:         */
1.159     markus   2189:        if (!rsafail) {
1.348     markus   2190:                (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1.159     markus   2191:                len = BN_num_bytes(session_key_int);
1.311     djm      2192:                if (len < 0 || (u_int)len > sizeof(session_key)) {
1.348     markus   2193:                        error("do_ssh1_kex: bad session key len from %s: "
1.165     itojun   2194:                            "session_key_int %d > sizeof(session_key) %lu",
                   2195:                            get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1.159     markus   2196:                        rsafail++;
                   2197:                } else {
                   2198:                        memset(session_key, 0, sizeof(session_key));
                   2199:                        BN_bn2bin(session_key_int,
                   2200:                            session_key + sizeof(session_key) - len);
1.169     markus   2201:
1.291     djm      2202:                        derive_ssh1_session_id(
1.298     deraadt  2203:                            sensitive_data.ssh1_host_key->rsa->n,
1.291     djm      2204:                            sensitive_data.server_key->rsa->n,
                   2205:                            cookie, session_id);
1.169     markus   2206:                        /*
                   2207:                         * Xor the first 16 bytes of the session key with the
                   2208:                         * session id.
                   2209:                         */
                   2210:                        for (i = 0; i < 16; i++)
                   2211:                                session_key[i] ^= session_id[i];
1.159     markus   2212:                }
                   2213:        }
                   2214:        if (rsafail) {
1.169     markus   2215:                int bytes = BN_num_bytes(session_key_int);
1.227     stevesk  2216:                u_char *buf = xmalloc(bytes);
1.169     markus   2217:                MD5_CTX md;
                   2218:
1.264     itojun   2219:                logit("do_connection: generating a fake encryption key");
1.169     markus   2220:                BN_bn2bin(session_key_int, buf);
                   2221:                MD5_Init(&md);
                   2222:                MD5_Update(&md, buf, bytes);
                   2223:                MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
                   2224:                MD5_Final(session_key, &md);
                   2225:                MD5_Init(&md);
                   2226:                MD5_Update(&md, session_key, 16);
                   2227:                MD5_Update(&md, buf, bytes);
                   2228:                MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
                   2229:                MD5_Final(session_key + 16, &md);
                   2230:                memset(buf, 0, bytes);
1.402     djm      2231:                free(buf);
1.170     markus   2232:                for (i = 0; i < 16; i++)
                   2233:                        session_id[i] = session_key[i] ^ session_key[i + 16];
1.159     markus   2234:        }
1.231     provos   2235:        /* Destroy the private and public keys. No longer. */
1.169     markus   2236:        destroy_sensitive_data();
                   2237:
1.231     provos   2238:        if (use_privsep)
                   2239:                mm_ssh1_session_id(session_id);
                   2240:
1.77      markus   2241:        /* Destroy the decrypted integer.  It is no longer needed. */
                   2242:        BN_clear_free(session_key_int);
1.64      markus   2243:
                   2244:        /* Set the session key.  From this on all communications will be encrypted. */
                   2245:        packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
                   2246:
                   2247:        /* Destroy our copy of the session key.  It is no longer needed. */
                   2248:        memset(session_key, 0, sizeof(session_key));
                   2249:
                   2250:        debug("Received session key; encryption turned on.");
                   2251:
1.243     deraadt  2252:        /* Send an acknowledgment packet.  Note that this packet is sent encrypted. */
1.64      markus   2253:        packet_start(SSH_SMSG_SUCCESS);
                   2254:        packet_send();
                   2255:        packet_write_wait();
1.98      markus   2256: }
                   2257:
1.404     markus   2258: void
                   2259: sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, u_int *slen,
                   2260:     u_char *data, u_int dlen)
                   2261: {
                   2262:        if (privkey) {
                   2263:                if (PRIVSEP(key_sign(privkey, signature, slen, data, dlen) < 0))
                   2264:                        fatal("%s: key_sign failed", __func__);
                   2265:        } else if (use_privsep) {
                   2266:                if (mm_key_sign(pubkey, signature, slen, data, dlen) < 0)
                   2267:                        fatal("%s: pubkey_sign failed", __func__);
                   2268:        } else {
                   2269:                if (ssh_agent_sign(auth_conn, pubkey, signature, slen, data,
                   2270:                    dlen))
                   2271:                        fatal("%s: ssh_agent_sign failed", __func__);
                   2272:        }
                   2273: }
                   2274:
1.98      markus   2275: /*
                   2276:  * SSH2 key exchange: diffie-hellman-group1-sha1
                   2277:  */
1.200     itojun   2278: static void
1.142     markus   2279: do_ssh2_kex(void)
1.98      markus   2280: {
                   2281:        Kex *kex;
1.102     markus   2282:
                   2283:        if (options.ciphers != NULL) {
1.105     markus   2284:                myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1.102     markus   2285:                myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1.166     markus   2286:        }
1.184     stevesk  2287:        myproposal[PROPOSAL_ENC_ALGS_CTOS] =
                   2288:            compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
                   2289:        myproposal[PROPOSAL_ENC_ALGS_STOC] =
                   2290:            compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
                   2291:
1.166     markus   2292:        if (options.macs != NULL) {
                   2293:                myproposal[PROPOSAL_MAC_ALGS_CTOS] =
                   2294:                myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1.246     markus   2295:        }
1.312     markus   2296:        if (options.compression == COMP_NONE) {
1.246     markus   2297:                myproposal[PROPOSAL_COMP_ALGS_CTOS] =
                   2298:                myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
1.312     markus   2299:        } else if (options.compression == COMP_DELAYED) {
                   2300:                myproposal[PROPOSAL_COMP_ALGS_CTOS] =
                   2301:                myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
1.102     markus   2302:        }
1.380     djm      2303:        if (options.kex_algorithms != NULL)
                   2304:                myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
1.400     dtucker  2305:
                   2306:        if (options.rekey_limit || options.rekey_interval)
                   2307:                packet_set_rekey_limits((u_int32_t)options.rekey_limit,
                   2308:                    (time_t)options.rekey_interval);
1.327     deraadt  2309:
1.413     djm      2310:        myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
                   2311:            list_hostkey_types());
1.134     markus   2312:
1.189     markus   2313:        /* start key exchange */
1.188     markus   2314:        kex = kex_setup(myproposal);
1.263     markus   2315:        kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1.292     djm      2316:        kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1.263     markus   2317:        kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1.324     djm      2318:        kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1.378     djm      2319:        kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
1.410     markus   2320:        kex->kex[KEX_C25519_SHA256] = kexc25519_server;
1.186     markus   2321:        kex->server = 1;
                   2322:        kex->client_version_string=client_version_string;
                   2323:        kex->server_version_string=server_version_string;
1.373     djm      2324:        kex->load_host_public_key=&get_hostkey_public_by_type;
                   2325:        kex->load_host_private_key=&get_hostkey_private_by_type;
1.231     provos   2326:        kex->host_key_index=&get_hostkey_index;
1.404     markus   2327:        kex->sign = sshd_hostkey_sign;
1.129     provos   2328:
1.189     markus   2329:        xxx_kex = kex;
                   2330:
1.190     markus   2331:        dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1.187     markus   2332:
                   2333:        session_id2 = kex->session_id;
                   2334:        session_id2_len = kex->session_id_len;
1.129     provos   2335:
                   2336: #ifdef DEBUG_KEXDH
                   2337:        /* send 1st encrypted/maced/compressed message */
                   2338:        packet_start(SSH2_MSG_IGNORE);
                   2339:        packet_put_cstring("markus");
                   2340:        packet_send();
                   2341:        packet_write_wait();
                   2342: #endif
1.186     markus   2343:        debug("KEX done");
1.278     markus   2344: }
                   2345:
                   2346: /* server specific fatal cleanup */
                   2347: void
                   2348: cleanup_exit(int i)
                   2349: {
1.386     djm      2350:        if (the_authctxt) {
1.278     markus   2351:                do_cleanup(the_authctxt);
1.387     dtucker  2352:                if (use_privsep && privsep_is_preauth && pmonitor->m_pid > 1) {
1.386     djm      2353:                        debug("Killing privsep child %d", pmonitor->m_pid);
                   2354:                        if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
1.388     djm      2355:                            errno != ESRCH)
1.386     djm      2356:                                error("%s: kill(%d): %s", __func__,
                   2357:                                    pmonitor->m_pid, strerror(errno));
                   2358:                }
                   2359:        }
1.278     markus   2360:        _exit(i);
1.1       deraadt  2361: }