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

1.86      markus      1: /*
1.65      deraadt     2:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      3:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      4:  *                    All rights reserved
1.126     deraadt     5:  * This program is the ssh daemon.  It listens for connections from clients,
                      6:  * and performs authentication, executes use commands or shell, and forwards
1.65      deraadt     7:  * information to/from the application to the user client over an encrypted
1.126     deraadt     8:  * connection.  This can also handle forwarding of X11, TCP/IP, and
                      9:  * authentication agent connections.
1.98      markus     10:  *
1.126     deraadt    11:  * As far as I am concerned, the code I have written for this software
                     12:  * can be used freely for any purpose.  Any derived versions of this
                     13:  * software must be clearly marked as such, and if the derived work is
                     14:  * incompatible with the protocol description in the RFC file, it must be
                     15:  * called by a name other than "ssh" or "Secure Shell".
                     16:  *
                     17:  * SSH2 implementation:
1.231     provos     18:  * Privilege Separation:
1.126     deraadt    19:  *
1.231     provos     20:  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
                     21:  * Copyright (c) 2002 Niels Provos.  All rights reserved.
1.126     deraadt    22:  *
                     23:  * Redistribution and use in source and binary forms, with or without
                     24:  * modification, are permitted provided that the following conditions
                     25:  * are met:
                     26:  * 1. Redistributions of source code must retain the above copyright
                     27:  *    notice, this list of conditions and the following disclaimer.
                     28:  * 2. Redistributions in binary form must reproduce the above copyright
                     29:  *    notice, this list of conditions and the following disclaimer in the
                     30:  *    documentation and/or other materials provided with the distribution.
                     31:  *
                     32:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     33:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     34:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     35:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     36:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     37:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     38:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     39:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     40:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     41:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.65      deraadt    42:  */
1.1       deraadt    43:
                     44: #include "includes.h"
1.294   ! djm        45: RCSID("$OpenBSD: sshd.c,v 1.293 2004/06/14 01:44:39 djm Exp $");
1.1       deraadt    46:
1.155     markus     47: #include <openssl/dh.h>
                     48: #include <openssl/bn.h>
1.226     markus     49: #include <openssl/md5.h>
1.231     provos     50: #include <openssl/rand.h>
1.155     markus     51:
                     52: #include "ssh.h"
                     53: #include "ssh1.h"
                     54: #include "ssh2.h"
1.1       deraadt    55: #include "xmalloc.h"
                     56: #include "rsa.h"
1.171     djm        57: #include "sshpty.h"
1.1       deraadt    58: #include "packet.h"
1.155     markus     59: #include "log.h"
1.1       deraadt    60: #include "servconf.h"
                     61: #include "uidswap.h"
1.33      markus     62: #include "compat.h"
1.96      markus     63: #include "buffer.h"
1.294   ! djm        64: #include "bufaux.h"
1.155     markus     65: #include "cipher.h"
1.98      markus     66: #include "kex.h"
1.96      markus     67: #include "key.h"
1.129     provos     68: #include "dh.h"
1.98      markus     69: #include "myproposal.h"
1.108     markus     70: #include "authfile.h"
1.154     markus     71: #include "pathnames.h"
1.155     markus     72: #include "atomicio.h"
                     73: #include "canohost.h"
                     74: #include "auth.h"
                     75: #include "misc.h"
1.294   ! djm        76: #include "msg.h"
1.186     markus     77: #include "dispatch.h"
1.206     stevesk    78: #include "channels.h"
1.230     provos     79: #include "session.h"
1.231     provos     80: #include "monitor_mm.h"
                     81: #include "monitor.h"
                     82: #include "monitor_wrap.h"
                     83: #include "monitor_fdpass.h"
1.1       deraadt    84:
                     85: #ifdef LIBWRAP
                     86: #include <tcpd.h>
                     87: #include <syslog.h>
                     88: int allow_severity = LOG_INFO;
                     89: int deny_severity = LOG_WARNING;
                     90: #endif /* LIBWRAP */
                     91:
                     92: #ifndef O_NOCTTY
                     93: #define O_NOCTTY       0
                     94: #endif
                     95:
1.138     markus     96: extern char *__progname;
                     97:
1.1       deraadt    98: /* Server configuration options. */
                     99: ServerOptions options;
                    100:
                    101: /* Name of the server configuration file. */
1.154     markus    102: char *config_file_name = _PATH_SERVER_CONFIG_FILE;
1.1       deraadt   103:
1.105     markus    104: /*
1.75      markus    105:  * Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
                    106:  * Default value is AF_UNSPEC means both IPv4 and IPv6.
                    107:  */
                    108: int IPv4or6 = AF_UNSPEC;
                    109:
1.65      deraadt   110: /*
                    111:  * Debug mode flag.  This can be set on the command line.  If debug
                    112:  * mode is enabled, extra debugging output will be sent to the system
                    113:  * log, the daemon will not go to background, and will exit after processing
                    114:  * the first connection.
                    115:  */
1.1       deraadt   116: int debug_flag = 0;
                    117:
1.203     stevesk   118: /* Flag indicating that the daemon should only test the configuration and keys. */
                    119: int test_flag = 0;
                    120:
1.1       deraadt   121: /* Flag indicating that the daemon is being started from inetd. */
                    122: int inetd_flag = 0;
                    123:
1.135     markus    124: /* Flag indicating that sshd should not detach and become a daemon. */
                    125: int no_daemon_flag = 0;
                    126:
1.47      markus    127: /* debug goes to stderr unless inetd_flag is set */
                    128: int log_stderr = 0;
                    129:
1.1       deraadt   130: /* Saved arguments to main(). */
                    131: char **saved_argv;
                    132:
1.294   ! djm       133: /* re-exec */
        !           134: int rexeced_flag = 0;
        !           135: int rexec_flag = 1;
        !           136: int rexec_argc = 0;
        !           137: char **rexec_argv;
        !           138:
1.66      markus    139: /*
1.75      markus    140:  * The sockets that the server is listening; this is used in the SIGHUP
                    141:  * signal handler.
1.66      markus    142:  */
1.75      markus    143: #define        MAX_LISTEN_SOCKS        16
                    144: int listen_socks[MAX_LISTEN_SOCKS];
                    145: int num_listen_socks = 0;
1.1       deraadt   146:
1.66      markus    147: /*
                    148:  * the client's version string, passed by sshd2 in compat mode. if != NULL,
                    149:  * sshd will skip the version-number exchange
                    150:  */
1.61      markus    151: char *client_version_string = NULL;
1.96      markus    152: char *server_version_string = NULL;
1.1       deraadt   153:
1.189     markus    154: /* for rekeying XXX fixme */
                    155: Kex *xxx_kex;
                    156:
1.66      markus    157: /*
                    158:  * Any really sensitive data in the application is contained in this
                    159:  * structure. The idea is that this structure could be locked into memory so
                    160:  * that the pages do not get written into swap.  However, there are some
                    161:  * problems. The private key contains BIGNUMs, and we do not (in principle)
                    162:  * have access to the internals of them, and locking just the structure is
                    163:  * not very useful.  Currently, memory locking is not implemented.
                    164:  */
1.64      markus    165: struct {
1.174     deraadt   166:        Key     *server_key;            /* ephemeral server key */
1.134     markus    167:        Key     *ssh1_host_key;         /* ssh1 host key */
                    168:        Key     **host_keys;            /* all private host keys */
                    169:        int     have_ssh1_key;
                    170:        int     have_ssh2_key;
1.169     markus    171:        u_char  ssh1_cookie[SSH_SESSION_KEY_LENGTH];
1.1       deraadt   172: } sensitive_data;
                    173:
1.66      markus    174: /*
1.151     markus    175:  * Flag indicating whether the RSA server key needs to be regenerated.
                    176:  * Is set in the SIGALRM handler and cleared when the key is regenerated.
1.66      markus    177:  */
1.212     markus    178: static volatile sig_atomic_t key_do_regen = 0;
1.1       deraadt   179:
1.199     markus    180: /* This is set to true when a signal is received. */
1.212     markus    181: static volatile sig_atomic_t received_sighup = 0;
                    182: static volatile sig_atomic_t received_sigterm = 0;
1.1       deraadt   183:
1.96      markus    184: /* session identifier, used by RSA-auth */
1.140     markus    185: u_char session_id[16];
1.96      markus    186:
1.108     markus    187: /* same for ssh2 */
1.140     markus    188: u_char *session_id2 = NULL;
1.269     markus    189: u_int session_id2_len = 0;
1.108     markus    190:
1.125     markus    191: /* record remote hostname or ip */
1.140     markus    192: u_int utmp_len = MAXHOSTNAMELEN;
1.125     markus    193:
1.211     markus    194: /* options.max_startup sized array of fd ints */
                    195: int *startup_pipes = NULL;
                    196: int startup_pipe;              /* in child */
                    197:
1.231     provos    198: /* variables used for privilege separation */
1.263     markus    199: int use_privsep;
1.285     dtucker   200: struct monitor *pmonitor = NULL;
1.231     provos    201:
1.278     markus    202: /* global authentication context */
                    203: Authctxt *the_authctxt = NULL;
                    204:
1.1       deraadt   205: /* Prototypes for various functions defined later in this file. */
1.200     itojun    206: void destroy_sensitive_data(void);
1.231     provos    207: void demote_sensitive_data(void);
1.87      markus    208:
1.200     itojun    209: static void do_ssh1_kex(void);
                    210: static void do_ssh2_kex(void);
1.129     provos    211:
1.87      markus    212: /*
1.75      markus    213:  * Close all listening sockets
                    214:  */
1.200     itojun    215: static void
1.75      markus    216: close_listen_socks(void)
                    217: {
                    218:        int i;
1.250     deraadt   219:
1.75      markus    220:        for (i = 0; i < num_listen_socks; i++)
                    221:                close(listen_socks[i]);
                    222:        num_listen_socks = -1;
                    223: }
                    224:
1.211     markus    225: static void
                    226: close_startup_pipes(void)
                    227: {
                    228:        int i;
1.250     deraadt   229:
1.211     markus    230:        if (startup_pipes)
                    231:                for (i = 0; i < options.max_startups; i++)
                    232:                        if (startup_pipes[i] != -1)
                    233:                                close(startup_pipes[i]);
                    234: }
                    235:
1.75      markus    236: /*
1.65      deraadt   237:  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
                    238:  * the effect is to reread the configuration file (and to regenerate
                    239:  * the server key).
                    240:  */
1.200     itojun    241: static void
1.64      markus    242: sighup_handler(int sig)
1.1       deraadt   243: {
1.210     deraadt   244:        int save_errno = errno;
                    245:
1.64      markus    246:        received_sighup = 1;
                    247:        signal(SIGHUP, sighup_handler);
1.210     deraadt   248:        errno = save_errno;
1.1       deraadt   249: }
                    250:
1.65      deraadt   251: /*
                    252:  * Called from the main program after receiving SIGHUP.
                    253:  * Restarts the server.
                    254:  */
1.200     itojun    255: static void
1.165     itojun    256: sighup_restart(void)
1.1       deraadt   257: {
1.264     itojun    258:        logit("Received SIGHUP; restarting.");
1.75      markus    259:        close_listen_socks();
1.211     markus    260:        close_startup_pipes();
1.64      markus    261:        execv(saved_argv[0], saved_argv);
1.264     itojun    262:        logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
1.250     deraadt   263:            strerror(errno));
1.64      markus    264:        exit(1);
1.1       deraadt   265: }
                    266:
1.65      deraadt   267: /*
                    268:  * Generic signal handler for terminating signals in the master daemon.
                    269:  */
1.200     itojun    270: static void
1.64      markus    271: sigterm_handler(int sig)
1.1       deraadt   272: {
1.199     markus    273:        received_sigterm = sig;
1.1       deraadt   274: }
                    275:
1.65      deraadt   276: /*
                    277:  * SIGCHLD handler.  This is called whenever a child dies.  This will then
1.199     markus    278:  * reap any zombies left by exited children.
1.65      deraadt   279:  */
1.200     itojun    280: static void
1.64      markus    281: main_sigchld_handler(int sig)
1.1       deraadt   282: {
1.250     deraadt   283:        int save_errno = errno;
1.239     markus    284:        pid_t pid;
1.64      markus    285:        int status;
1.60      deraadt   286:
1.239     markus    287:        while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
                    288:            (pid < 0 && errno == EINTR))
1.64      markus    289:                ;
1.60      deraadt   290:
1.64      markus    291:        signal(SIGCHLD, main_sigchld_handler);
                    292:        errno = save_errno;
1.1       deraadt   293: }
                    294:
1.65      deraadt   295: /*
                    296:  * Signal handler for the alarm after the login grace period has expired.
                    297:  */
1.200     itojun    298: static void
1.64      markus    299: grace_alarm_handler(int sig)
1.1       deraadt   300: {
1.199     markus    301:        /* XXX no idea how fix this signal handler */
                    302:
1.285     dtucker   303:        if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
                    304:                kill(pmonitor->m_pid, SIGALRM);
                    305:
1.64      markus    306:        /* Log error and exit. */
1.259     markus    307:        fatal("Timeout before authentication for %s", get_remote_ipaddr());
1.62      markus    308: }
                    309:
1.65      deraadt   310: /*
                    311:  * Signal handler for the key regeneration alarm.  Note that this
                    312:  * alarm only occurs in the daemon waiting for connections, and it does not
                    313:  * do anything with the private key or random state before forking.
                    314:  * Thus there should be no concurrency control/asynchronous execution
                    315:  * problems.
                    316:  */
1.200     itojun    317: static void
1.174     deraadt   318: generate_ephemeral_server_key(void)
1.134     markus    319: {
1.254     deraadt   320:        u_int32_t rnd = 0;
1.169     markus    321:        int i;
                    322:
1.191     markus    323:        verbose("Generating %s%d bit RSA key.",
1.185     djm       324:            sensitive_data.server_key ? "new " : "", options.server_key_bits);
1.134     markus    325:        if (sensitive_data.server_key != NULL)
                    326:                key_free(sensitive_data.server_key);
1.191     markus    327:        sensitive_data.server_key = key_generate(KEY_RSA1,
1.185     djm       328:            options.server_key_bits);
                    329:        verbose("RSA key generation complete.");
1.169     markus    330:
                    331:        for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
                    332:                if (i % 4 == 0)
1.254     deraadt   333:                        rnd = arc4random();
                    334:                sensitive_data.ssh1_cookie[i] = rnd & 0xff;
                    335:                rnd >>= 8;
1.169     markus    336:        }
1.134     markus    337:        arc4random_stir();
                    338: }
1.147     deraadt   339:
1.200     itojun    340: static void
1.64      markus    341: key_regeneration_alarm(int sig)
1.1       deraadt   342: {
1.64      markus    343:        int save_errno = errno;
1.250     deraadt   344:
1.151     markus    345:        signal(SIGALRM, SIG_DFL);
1.64      markus    346:        errno = save_errno;
1.151     markus    347:        key_do_regen = 1;
1.98      markus    348: }
                    349:
1.200     itojun    350: static void
1.96      markus    351: sshd_exchange_identification(int sock_in, int sock_out)
                    352: {
1.102     markus    353:        int i, mismatch;
1.96      markus    354:        int remote_major, remote_minor;
1.102     markus    355:        int major, minor;
1.96      markus    356:        char *s;
                    357:        char buf[256];                  /* Must not be larger than remote_version. */
                    358:        char remote_version[256];       /* Must be at least as big as buf. */
                    359:
1.103     markus    360:        if ((options.protocol & SSH_PROTO_1) &&
                    361:            (options.protocol & SSH_PROTO_2)) {
1.102     markus    362:                major = PROTOCOL_MAJOR_1;
                    363:                minor = 99;
                    364:        } else if (options.protocol & SSH_PROTO_2) {
                    365:                major = PROTOCOL_MAJOR_2;
                    366:                minor = PROTOCOL_MINOR_2;
                    367:        } else {
                    368:                major = PROTOCOL_MAJOR_1;
                    369:                minor = PROTOCOL_MINOR_1;
                    370:        }
                    371:        snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
1.96      markus    372:        server_version_string = xstrdup(buf);
                    373:
1.272     markus    374:        /* Send our protocol version identification. */
                    375:        if (atomicio(vwrite, sock_out, server_version_string,
                    376:            strlen(server_version_string))
                    377:            != strlen(server_version_string)) {
                    378:                logit("Could not write ident string to %s", get_remote_ipaddr());
1.278     markus    379:                cleanup_exit(255);
1.272     markus    380:        }
                    381:
                    382:        /* Read other sides version identification. */
                    383:        memset(buf, 0, sizeof(buf));
                    384:        for (i = 0; i < sizeof(buf) - 1; i++) {
                    385:                if (atomicio(read, sock_in, &buf[i], 1) != 1) {
                    386:                        logit("Did not receive identification string from %s",
                    387:                            get_remote_ipaddr());
1.278     markus    388:                        cleanup_exit(255);
1.96      markus    389:                }
1.272     markus    390:                if (buf[i] == '\r') {
                    391:                        buf[i] = 0;
                    392:                        /* Kludge for F-Secure Macintosh < 1.0.2 */
                    393:                        if (i == 12 &&
                    394:                            strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
1.96      markus    395:                                break;
1.272     markus    396:                        continue;
                    397:                }
                    398:                if (buf[i] == '\n') {
                    399:                        buf[i] = 0;
                    400:                        break;
1.96      markus    401:                }
                    402:        }
1.272     markus    403:        buf[sizeof(buf) - 1] = 0;
                    404:        client_version_string = xstrdup(buf);
1.96      markus    405:
                    406:        /*
                    407:         * Check that the versions match.  In future this might accept
                    408:         * several versions and set appropriate flags to handle them.
                    409:         */
                    410:        if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
                    411:            &remote_major, &remote_minor, remote_version) != 3) {
1.105     markus    412:                s = "Protocol mismatch.\n";
1.271     deraadt   413:                (void) atomicio(vwrite, sock_out, s, strlen(s));
1.96      markus    414:                close(sock_in);
                    415:                close(sock_out);
1.264     itojun    416:                logit("Bad protocol version identification '%.100s' from %s",
1.96      markus    417:                    client_version_string, get_remote_ipaddr());
1.278     markus    418:                cleanup_exit(255);
1.96      markus    419:        }
                    420:        debug("Client protocol version %d.%d; client software version %.100s",
1.217     deraadt   421:            remote_major, remote_minor, remote_version);
1.96      markus    422:
1.98      markus    423:        compat_datafellows(remote_version);
1.260     mickey    424:
                    425:        if (datafellows & SSH_BUG_PROBE) {
1.264     itojun    426:                logit("probed from %s with %s.  Don't panic.",
1.260     mickey    427:                    get_remote_ipaddr(), client_version_string);
1.278     markus    428:                cleanup_exit(255);
1.260     mickey    429:        }
1.175     deraadt   430:
                    431:        if (datafellows & SSH_BUG_SCANNER) {
1.264     itojun    432:                logit("scanned from %s with %s.  Don't panic.",
1.175     deraadt   433:                    get_remote_ipaddr(), client_version_string);
1.278     markus    434:                cleanup_exit(255);
1.175     deraadt   435:        }
1.98      markus    436:
1.102     markus    437:        mismatch = 0;
1.214     deraadt   438:        switch (remote_major) {
1.96      markus    439:        case 1:
1.108     markus    440:                if (remote_minor == 99) {
                    441:                        if (options.protocol & SSH_PROTO_2)
                    442:                                enable_compat20();
                    443:                        else
                    444:                                mismatch = 1;
                    445:                        break;
                    446:                }
1.102     markus    447:                if (!(options.protocol & SSH_PROTO_1)) {
                    448:                        mismatch = 1;
                    449:                        break;
                    450:                }
1.96      markus    451:                if (remote_minor < 3) {
1.121     provos    452:                        packet_disconnect("Your ssh version is too old and "
1.96      markus    453:                            "is no longer supported.  Please install a newer version.");
                    454:                } else if (remote_minor == 3) {
                    455:                        /* note that this disables agent-forwarding */
                    456:                        enable_compat13();
                    457:                }
1.102     markus    458:                break;
1.98      markus    459:        case 2:
1.102     markus    460:                if (options.protocol & SSH_PROTO_2) {
1.98      markus    461:                        enable_compat20();
                    462:                        break;
                    463:                }
1.99      markus    464:                /* FALLTHROUGH */
1.105     markus    465:        default:
1.102     markus    466:                mismatch = 1;
                    467:                break;
                    468:        }
                    469:        chop(server_version_string);
                    470:        debug("Local version string %.200s", server_version_string);
                    471:
                    472:        if (mismatch) {
1.96      markus    473:                s = "Protocol major versions differ.\n";
1.271     deraadt   474:                (void) atomicio(vwrite, sock_out, s, strlen(s));
1.96      markus    475:                close(sock_in);
                    476:                close(sock_out);
1.264     itojun    477:                logit("Protocol major versions differ for %s: %.200s vs. %.200s",
1.102     markus    478:                    get_remote_ipaddr(),
                    479:                    server_version_string, client_version_string);
1.278     markus    480:                cleanup_exit(255);
1.96      markus    481:        }
1.108     markus    482: }
                    483:
1.134     markus    484: /* Destroy the host and server keys.  They will no longer be needed. */
1.108     markus    485: void
                    486: destroy_sensitive_data(void)
                    487: {
1.134     markus    488:        int i;
                    489:
                    490:        if (sensitive_data.server_key) {
                    491:                key_free(sensitive_data.server_key);
                    492:                sensitive_data.server_key = NULL;
                    493:        }
1.217     deraadt   494:        for (i = 0; i < options.num_host_key_files; i++) {
1.134     markus    495:                if (sensitive_data.host_keys[i]) {
                    496:                        key_free(sensitive_data.host_keys[i]);
                    497:                        sensitive_data.host_keys[i] = NULL;
                    498:                }
                    499:        }
                    500:        sensitive_data.ssh1_host_key = NULL;
1.169     markus    501:        memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
1.134     markus    502: }
                    503:
1.231     provos    504: /* Demote private to public keys for network child */
                    505: void
                    506: demote_sensitive_data(void)
                    507: {
                    508:        Key *tmp;
                    509:        int i;
                    510:
                    511:        if (sensitive_data.server_key) {
                    512:                tmp = key_demote(sensitive_data.server_key);
                    513:                key_free(sensitive_data.server_key);
                    514:                sensitive_data.server_key = tmp;
                    515:        }
                    516:
                    517:        for (i = 0; i < options.num_host_key_files; i++) {
                    518:                if (sensitive_data.host_keys[i]) {
                    519:                        tmp = key_demote(sensitive_data.host_keys[i]);
                    520:                        key_free(sensitive_data.host_keys[i]);
                    521:                        sensitive_data.host_keys[i] = tmp;
                    522:                        if (tmp->type == KEY_RSA1)
                    523:                                sensitive_data.ssh1_host_key = tmp;
                    524:                }
                    525:        }
                    526:
                    527:        /* We do not clear ssh1_host key and cookie.  XXX - Okay Niels? */
                    528: }
                    529:
1.233     markus    530: static void
1.231     provos    531: privsep_preauth_child(void)
                    532: {
1.254     deraadt   533:        u_int32_t rnd[256];
1.253     deraadt   534:        gid_t gidset[1];
1.250     deraadt   535:        struct passwd *pw;
1.231     provos    536:        int i;
                    537:
                    538:        /* Enable challenge-response authentication for privilege separation */
                    539:        privsep_challenge_enable();
                    540:
                    541:        for (i = 0; i < 256; i++)
1.254     deraadt   542:                rnd[i] = arc4random();
                    543:        RAND_seed(rnd, sizeof(rnd));
1.231     provos    544:
                    545:        /* Demote the private keys to public keys. */
                    546:        demote_sensitive_data();
                    547:
1.235     stevesk   548:        if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
1.240     djm       549:                fatal("Privilege separation user %s does not exist",
                    550:                    SSH_PRIVSEP_USER);
1.235     stevesk   551:        memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
                    552:        endpwent();
                    553:
1.255     deraadt   554:        /* Change our root directory */
1.232     stevesk   555:        if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
                    556:                fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
                    557:                    strerror(errno));
1.231     provos    558:        if (chdir("/") == -1)
1.236     stevesk   559:                fatal("chdir(\"/\"): %s", strerror(errno));
1.234     markus    560:
1.231     provos    561:        /* Drop our privileges */
1.235     stevesk   562:        debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
                    563:            (u_int)pw->pw_gid);
1.251     markus    564: #if 0
1.287     djm       565:        /* XXX not ready, too heavy after chroot */
1.235     stevesk   566:        do_setusercontext(pw);
1.251     markus    567: #else
                    568:        gidset[0] = pw->pw_gid;
                    569:        if (setgroups(1, gidset) < 0)
                    570:                fatal("setgroups: %.100s", strerror(errno));
                    571:        permanently_set_uid(pw);
                    572: #endif
1.231     provos    573: }
                    574:
1.278     markus    575: static int
                    576: privsep_preauth(Authctxt *authctxt)
1.237     markus    577: {
                    578:        int status;
                    579:        pid_t pid;
                    580:
                    581:        /* Set up unprivileged child process to deal with network data */
1.242     mouring   582:        pmonitor = monitor_init();
1.237     markus    583:        /* Store a pointer to the kex for later rekeying */
1.242     mouring   584:        pmonitor->m_pkex = &xxx_kex;
1.237     markus    585:
                    586:        pid = fork();
                    587:        if (pid == -1) {
                    588:                fatal("fork of unprivileged child failed");
                    589:        } else if (pid != 0) {
1.245     mpech     590:                debug2("Network child is on pid %ld", (long)pid);
1.237     markus    591:
1.242     mouring   592:                close(pmonitor->m_recvfd);
1.285     dtucker   593:                pmonitor->m_pid = pid;
1.278     markus    594:                monitor_child_preauth(authctxt, pmonitor);
1.242     mouring   595:                close(pmonitor->m_sendfd);
1.237     markus    596:
                    597:                /* Sync memory */
1.242     mouring   598:                monitor_sync(pmonitor);
1.237     markus    599:
                    600:                /* Wait for the child's exit status */
1.239     markus    601:                while (waitpid(pid, &status, 0) < 0)
                    602:                        if (errno != EINTR)
                    603:                                break;
1.278     markus    604:                return (1);
1.237     markus    605:        } else {
                    606:                /* child */
                    607:
1.242     mouring   608:                close(pmonitor->m_sendfd);
1.237     markus    609:
                    610:                /* Demote the child */
                    611:                if (getuid() == 0 || geteuid() == 0)
                    612:                        privsep_preauth_child();
1.238     stevesk   613:                setproctitle("%s", "[net]");
1.237     markus    614:        }
1.278     markus    615:        return (0);
1.237     markus    616: }
                    617:
1.233     markus    618: static void
1.237     markus    619: privsep_postauth(Authctxt *authctxt)
1.231     provos    620: {
                    621:        if (authctxt->pw->pw_uid == 0 || options.use_login) {
                    622:                /* File descriptor passing is broken or root login */
1.242     mouring   623:                monitor_apply_keystate(pmonitor);
1.231     provos    624:                use_privsep = 0;
                    625:                return;
                    626:        }
1.234     markus    627:
1.231     provos    628:        /* Authentication complete */
                    629:        alarm(0);
                    630:        if (startup_pipe != -1) {
                    631:                close(startup_pipe);
                    632:                startup_pipe = -1;
                    633:        }
                    634:
                    635:        /* New socket pair */
1.242     mouring   636:        monitor_reinit(pmonitor);
1.231     provos    637:
1.242     mouring   638:        pmonitor->m_pid = fork();
                    639:        if (pmonitor->m_pid == -1)
1.231     provos    640:                fatal("fork of unprivileged child failed");
1.242     mouring   641:        else if (pmonitor->m_pid != 0) {
1.245     mpech     642:                debug2("User child is on pid %ld", (long)pmonitor->m_pid);
1.242     mouring   643:                close(pmonitor->m_recvfd);
                    644:                monitor_child_postauth(pmonitor);
1.231     provos    645:
                    646:                /* NEVERREACHED */
                    647:                exit(0);
                    648:        }
                    649:
1.242     mouring   650:        close(pmonitor->m_sendfd);
1.231     provos    651:
                    652:        /* Demote the private keys to public keys. */
                    653:        demote_sensitive_data();
                    654:
                    655:        /* Drop privileges */
                    656:        do_setusercontext(authctxt->pw);
                    657:
                    658:        /* It is safe now to apply the key state */
1.242     mouring   659:        monitor_apply_keystate(pmonitor);
1.231     provos    660: }
                    661:
1.200     itojun    662: static char *
1.134     markus    663: list_hostkey_types(void)
                    664: {
1.223     markus    665:        Buffer b;
1.281     jakob     666:        const char *p;
                    667:        char *ret;
1.134     markus    668:        int i;
1.223     markus    669:
                    670:        buffer_init(&b);
1.217     deraadt   671:        for (i = 0; i < options.num_host_key_files; i++) {
1.134     markus    672:                Key *key = sensitive_data.host_keys[i];
                    673:                if (key == NULL)
                    674:                        continue;
1.214     deraadt   675:                switch (key->type) {
1.134     markus    676:                case KEY_RSA:
                    677:                case KEY_DSA:
1.223     markus    678:                        if (buffer_len(&b) > 0)
                    679:                                buffer_append(&b, ",", 1);
                    680:                        p = key_ssh_name(key);
                    681:                        buffer_append(&b, p, strlen(p));
1.134     markus    682:                        break;
                    683:                }
                    684:        }
1.223     markus    685:        buffer_append(&b, "\0", 1);
1.281     jakob     686:        ret = xstrdup(buffer_ptr(&b));
1.223     markus    687:        buffer_free(&b);
1.281     jakob     688:        debug("list_hostkey_types: %s", ret);
                    689:        return ret;
1.134     markus    690: }
                    691:
1.231     provos    692: Key *
1.134     markus    693: get_hostkey_by_type(int type)
                    694: {
                    695:        int i;
1.250     deraadt   696:
1.217     deraadt   697:        for (i = 0; i < options.num_host_key_files; i++) {
1.134     markus    698:                Key *key = sensitive_data.host_keys[i];
                    699:                if (key != NULL && key->type == type)
                    700:                        return key;
                    701:        }
                    702:        return NULL;
1.96      markus    703: }
                    704:
1.231     provos    705: Key *
                    706: get_hostkey_by_index(int ind)
                    707: {
                    708:        if (ind < 0 || ind >= options.num_host_key_files)
                    709:                return (NULL);
                    710:        return (sensitive_data.host_keys[ind]);
                    711: }
                    712:
                    713: int
                    714: get_hostkey_index(Key *key)
                    715: {
                    716:        int i;
1.250     deraadt   717:
1.231     provos    718:        for (i = 0; i < options.num_host_key_files; i++) {
                    719:                if (key == sensitive_data.host_keys[i])
                    720:                        return (i);
                    721:        }
                    722:        return (-1);
                    723: }
                    724:
1.124     markus    725: /*
                    726:  * returns 1 if connection should be dropped, 0 otherwise.
                    727:  * dropping starts at connection #max_startups_begin with a probability
                    728:  * of (max_startups_rate/100). the probability increases linearly until
                    729:  * all connections are dropped for startups > max_startups
                    730:  */
1.200     itojun    731: static int
1.124     markus    732: drop_connection(int startups)
                    733: {
                    734:        double p, r;
                    735:
                    736:        if (startups < options.max_startups_begin)
                    737:                return 0;
                    738:        if (startups >= options.max_startups)
                    739:                return 1;
                    740:        if (options.max_startups_rate == 100)
                    741:                return 1;
                    742:
                    743:        p  = 100 - options.max_startups_rate;
                    744:        p *= startups - options.max_startups_begin;
                    745:        p /= (double) (options.max_startups - options.max_startups_begin);
                    746:        p += options.max_startups_rate;
                    747:        p /= 100.0;
                    748:        r = arc4random() / (double) UINT_MAX;
                    749:
                    750:        debug("drop_connection: p %g, r %g", p, r);
                    751:        return (r < p) ? 1 : 0;
                    752: }
                    753:
1.215     markus    754: static void
                    755: usage(void)
                    756: {
1.290     markus    757:        fprintf(stderr, "%s, %s\n",
1.280     markus    758:            SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
1.289     markus    759:        fprintf(stderr,
                    760: "usage: sshd [-46Ddeiqt] [-b bits] [-f config_file] [-g login_grace_time]\n"
                    761: "            [-h host_key_file] [-k key_gen_time] [-o option] [-p port] [-u len]\n"
                    762:        );
1.215     markus    763:        exit(1);
                    764: }
                    765:
1.294   ! djm       766: static void
        !           767: send_rexec_state(int fd, Buffer *conf)
        !           768: {
        !           769:        Buffer m;
        !           770:
        !           771:        debug3("%s: entering fd = %d config len %d", __func__, fd,
        !           772:            buffer_len(conf));
        !           773:
        !           774:        /*
        !           775:         * Protocol from reexec master to child:
        !           776:         *      string  configuration
        !           777:         *      u_int   ephemeral_key_follows
        !           778:         *      bignum  e               (only if ephemeral_key_follows == 1)
        !           779:         *      bignum  n                       "
        !           780:         *      bignum  d                       "
        !           781:         *      bignum  iqmp                    "
        !           782:         *      bignum  p                       "
        !           783:         *      bignum  q                       "
        !           784:         */
        !           785:        buffer_init(&m);
        !           786:        buffer_put_cstring(&m, buffer_ptr(conf));
        !           787:
        !           788:        if (sensitive_data.server_key != NULL &&
        !           789:            sensitive_data.server_key->type == KEY_RSA1) {
        !           790:                buffer_put_int(&m, 1);
        !           791:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
        !           792:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
        !           793:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
        !           794:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
        !           795:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
        !           796:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
        !           797:        } else
        !           798:                buffer_put_int(&m, 0);
        !           799:
        !           800:        if (ssh_msg_send(fd, 0, &m) == -1)
        !           801:                fatal("%s: ssh_msg_send failed", __func__);
        !           802:
        !           803:        buffer_free(&m);
        !           804:
        !           805:        debug3("%s: done", __func__);
        !           806: }
        !           807:
        !           808: static void
        !           809: recv_rexec_state(int fd, Buffer *conf)
        !           810: {
        !           811:        Buffer m;
        !           812:        char *cp;
        !           813:        u_int len;
        !           814:
        !           815:        debug3("%s: entering fd = %d", __func__, fd);
        !           816:
        !           817:        buffer_init(&m);
        !           818:
        !           819:        if (ssh_msg_recv(fd, &m) == -1)
        !           820:                fatal("%s: ssh_msg_recv failed", __func__);
        !           821:        if (buffer_get_char(&m) != 0)
        !           822:                fatal("%s: rexec version mismatch", __func__);
        !           823:
        !           824:        cp = buffer_get_string(&m, &len);
        !           825:        if (conf != NULL)
        !           826:                buffer_append(conf, cp, len + 1);
        !           827:        xfree(cp);
        !           828:
        !           829:        if (buffer_get_int(&m)) {
        !           830:                if (sensitive_data.server_key != NULL)
        !           831:                        key_free(sensitive_data.server_key);
        !           832:                sensitive_data.server_key = key_new_private(KEY_RSA1);
        !           833:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
        !           834:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
        !           835:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
        !           836:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
        !           837:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
        !           838:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
        !           839:                rsa_generate_additional_parameters(
        !           840:                    sensitive_data.server_key->rsa);
        !           841:        }
        !           842:        buffer_free(&m);
        !           843:
        !           844:        debug3("%s: done", __func__);
        !           845: }
        !           846:
1.65      deraadt   847: /*
                    848:  * Main program for the daemon.
                    849:  */
1.2       provos    850: int
                    851: main(int ac, char **av)
1.1       deraadt   852: {
1.64      markus    853:        extern char *optarg;
                    854:        extern int optind;
1.120     markus    855:        int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
1.107     deraadt   856:        pid_t pid;
1.75      markus    857:        socklen_t fromlen;
                    858:        fd_set *fdset;
                    859:        struct sockaddr_storage from;
1.64      markus    860:        const char *remote_ip;
                    861:        int remote_port;
                    862:        FILE *f;
1.75      markus    863:        struct addrinfo *ai;
                    864:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1.283     markus    865:        char *line;
1.75      markus    866:        int listen_sock, maxfd;
1.294   ! djm       867:        int startup_p[2], config_s[2];
1.120     markus    868:        int startups = 0;
1.278     markus    869:        Key *key;
1.230     provos    870:        Authctxt *authctxt;
1.151     markus    871:        int ret, key_used = 0;
1.294   ! djm       872:        Buffer cfg;
1.64      markus    873:
1.138     markus    874:        /* Save argv. */
1.64      markus    875:        saved_argv = av;
1.294   ! djm       876:        rexec_argc = ac;
1.64      markus    877:
                    878:        /* Initialize configuration options to their default values. */
                    879:        initialize_server_options(&options);
                    880:
                    881:        /* Parse command-line arguments. */
1.294   ! djm       882:        while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:dDeiqrtQR46")) != -1) {
1.64      markus    883:                switch (opt) {
1.75      markus    884:                case '4':
                    885:                        IPv4or6 = AF_INET;
                    886:                        break;
                    887:                case '6':
                    888:                        IPv4or6 = AF_INET6;
                    889:                        break;
1.64      markus    890:                case 'f':
                    891:                        config_file_name = optarg;
                    892:                        break;
                    893:                case 'd':
1.273     markus    894:                        if (debug_flag == 0) {
1.127     markus    895:                                debug_flag = 1;
                    896:                                options.log_level = SYSLOG_LEVEL_DEBUG1;
1.273     markus    897:                        } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1.127     markus    898:                                options.log_level++;
1.64      markus    899:                        break;
1.135     markus    900:                case 'D':
                    901:                        no_daemon_flag = 1;
1.192     lebel     902:                        break;
                    903:                case 'e':
                    904:                        log_stderr = 1;
1.135     markus    905:                        break;
1.64      markus    906:                case 'i':
                    907:                        inetd_flag = 1;
                    908:                        break;
1.294   ! djm       909:                case 'r':
        !           910:                        rexec_flag = 0;
        !           911:                        break;
        !           912:                case 'R':
        !           913:                        rexeced_flag = 1;
        !           914:                        inetd_flag = 1;
        !           915:                        break;
1.64      markus    916:                case 'Q':
1.158     markus    917:                        /* ignored */
1.64      markus    918:                        break;
                    919:                case 'q':
                    920:                        options.log_level = SYSLOG_LEVEL_QUIET;
                    921:                        break;
                    922:                case 'b':
                    923:                        options.server_key_bits = atoi(optarg);
                    924:                        break;
                    925:                case 'p':
1.75      markus    926:                        options.ports_from_cmdline = 1;
1.127     markus    927:                        if (options.num_ports >= MAX_PORTS) {
                    928:                                fprintf(stderr, "too many ports.\n");
                    929:                                exit(1);
                    930:                        }
1.193     stevesk   931:                        options.ports[options.num_ports++] = a2port(optarg);
                    932:                        if (options.ports[options.num_ports-1] == 0) {
                    933:                                fprintf(stderr, "Bad port number.\n");
                    934:                                exit(1);
                    935:                        }
1.64      markus    936:                        break;
                    937:                case 'g':
1.197     stevesk   938:                        if ((options.login_grace_time = convtime(optarg)) == -1) {
                    939:                                fprintf(stderr, "Invalid login grace time.\n");
                    940:                                exit(1);
                    941:                        }
1.64      markus    942:                        break;
                    943:                case 'k':
1.197     stevesk   944:                        if ((options.key_regeneration_time = convtime(optarg)) == -1) {
                    945:                                fprintf(stderr, "Invalid key regeneration interval.\n");
                    946:                                exit(1);
                    947:                        }
1.64      markus    948:                        break;
                    949:                case 'h':
1.134     markus    950:                        if (options.num_host_key_files >= MAX_HOSTKEYS) {
                    951:                                fprintf(stderr, "too many host keys.\n");
                    952:                                exit(1);
                    953:                        }
                    954:                        options.host_key_files[options.num_host_key_files++] = optarg;
1.64      markus    955:                        break;
1.203     stevesk   956:                case 't':
                    957:                        test_flag = 1;
                    958:                        break;
1.125     markus    959:                case 'u':
                    960:                        utmp_len = atoi(optarg);
1.257     stevesk   961:                        if (utmp_len > MAXHOSTNAMELEN) {
                    962:                                fprintf(stderr, "Invalid utmp length.\n");
                    963:                                exit(1);
                    964:                        }
1.125     markus    965:                        break;
1.215     markus    966:                case 'o':
1.283     markus    967:                        line = xstrdup(optarg);
                    968:                        if (process_server_config_line(&options, line,
1.215     markus    969:                            "command-line", 0) != 0)
1.217     deraadt   970:                                exit(1);
1.283     markus    971:                        xfree(line);
1.215     markus    972:                        break;
1.64      markus    973:                case '?':
                    974:                default:
1.215     markus    975:                        usage();
                    976:                        break;
1.64      markus    977:                }
                    978:        }
1.294   ! djm       979:        if (rexeced_flag || inetd_flag)
        !           980:                rexec_flag = 0;
        !           981:        if (rexec_flag && (av[0] == NULL || *av[0] != '/'))
        !           982:                fatal("sshd re-exec requires execution with an absolute path");
        !           983:        if (rexeced_flag)
        !           984:                closefrom(STDERR_FILENO + 3);
        !           985:
1.180     markus    986:        SSLeay_add_all_algorithms();
1.205     markus    987:        channel_set_af(IPv4or6);
1.64      markus    988:
1.75      markus    989:        /*
                    990:         * Force logging to stderr until we have loaded the private host
                    991:         * key (unless started from inetd)
                    992:         */
1.138     markus    993:        log_init(__progname,
1.224     markus    994:            options.log_level == SYSLOG_LEVEL_NOT_SET ?
                    995:            SYSLOG_LEVEL_INFO : options.log_level,
                    996:            options.log_facility == SYSLOG_FACILITY_NOT_SET ?
                    997:            SYSLOG_FACILITY_AUTH : options.log_facility,
1.261     markus    998:            log_stderr || !inetd_flag);
1.75      markus    999:
1.294   ! djm      1000:        sensitive_data.server_key = NULL;
        !          1001:        sensitive_data.ssh1_host_key = NULL;
        !          1002:        sensitive_data.have_ssh1_key = 0;
        !          1003:        sensitive_data.have_ssh2_key = 0;
        !          1004:
        !          1005:        /* Fetch our configuration */
        !          1006:        buffer_init(&cfg);
        !          1007:        if (rexeced_flag)
        !          1008:                recv_rexec_state(STDERR_FILENO + 2, &cfg);
        !          1009:        else
        !          1010:                load_server_config(config_file_name, &cfg);
        !          1011:
        !          1012:        parse_server_config(&options,
        !          1013:            rexeced_flag ? "rexec" : config_file_name, &cfg);
        !          1014:
        !          1015:        if (!rexec_flag)
        !          1016:                buffer_free(&cfg);
1.64      markus   1017:
                   1018:        /* Fill in default values for those options not explicitly set. */
                   1019:        fill_default_server_options(&options);
                   1020:
                   1021:        /* Check that there are no remaining arguments. */
                   1022:        if (optind < ac) {
                   1023:                fprintf(stderr, "Extra argument %s.\n", av[optind]);
                   1024:                exit(1);
                   1025:        }
                   1026:
                   1027:        debug("sshd version %.100s", SSH_VERSION);
                   1028:
1.134     markus   1029:        /* load private host keys */
1.255     deraadt  1030:        sensitive_data.host_keys = xmalloc(options.num_host_key_files *
                   1031:            sizeof(Key *));
1.217     deraadt  1032:        for (i = 0; i < options.num_host_key_files; i++)
1.141     markus   1033:                sensitive_data.host_keys[i] = NULL;
1.134     markus   1034:
1.217     deraadt  1035:        for (i = 0; i < options.num_host_key_files; i++) {
1.179     markus   1036:                key = key_load_private(options.host_key_files[i], "", NULL);
                   1037:                sensitive_data.host_keys[i] = key;
1.134     markus   1038:                if (key == NULL) {
1.195     markus   1039:                        error("Could not load host key: %s",
                   1040:                            options.host_key_files[i]);
1.179     markus   1041:                        sensitive_data.host_keys[i] = NULL;
1.134     markus   1042:                        continue;
                   1043:                }
1.214     deraadt  1044:                switch (key->type) {
1.134     markus   1045:                case KEY_RSA1:
                   1046:                        sensitive_data.ssh1_host_key = key;
                   1047:                        sensitive_data.have_ssh1_key = 1;
                   1048:                        break;
                   1049:                case KEY_RSA:
                   1050:                case KEY_DSA:
                   1051:                        sensitive_data.have_ssh2_key = 1;
                   1052:                        break;
                   1053:                }
1.179     markus   1054:                debug("private host key: #%d type %d %s", i, key->type,
                   1055:                    key_type(key));
1.134     markus   1056:        }
                   1057:        if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1.264     itojun   1058:                logit("Disabling protocol version 1. Could not load host key");
1.108     markus   1059:                options.protocol &= ~SSH_PROTO_1;
                   1060:        }
1.134     markus   1061:        if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1.264     itojun   1062:                logit("Disabling protocol version 2. Could not load host key");
1.134     markus   1063:                options.protocol &= ~SSH_PROTO_2;
1.108     markus   1064:        }
1.162     stevesk  1065:        if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1.264     itojun   1066:                logit("sshd: no hostkeys available -- exiting.");
1.64      markus   1067:                exit(1);
                   1068:        }
                   1069:
1.108     markus   1070:        /* Check certain values for sanity. */
                   1071:        if (options.protocol & SSH_PROTO_1) {
                   1072:                if (options.server_key_bits < 512 ||
                   1073:                    options.server_key_bits > 32768) {
                   1074:                        fprintf(stderr, "Bad server key size.\n");
                   1075:                        exit(1);
                   1076:                }
                   1077:                /*
                   1078:                 * Check that server and host key lengths differ sufficiently. This
                   1079:                 * is necessary to make double encryption work with rsaref. Oh, I
                   1080:                 * hate software patents. I dont know if this can go? Niels
                   1081:                 */
                   1082:                if (options.server_key_bits >
1.250     deraadt  1083:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
                   1084:                    SSH_KEY_BITS_RESERVED && options.server_key_bits <
                   1085:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
                   1086:                    SSH_KEY_BITS_RESERVED) {
1.108     markus   1087:                        options.server_key_bits =
1.250     deraadt  1088:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
                   1089:                            SSH_KEY_BITS_RESERVED;
1.108     markus   1090:                        debug("Forcing server key to %d bits to make it differ from host key.",
                   1091:                            options.server_key_bits);
                   1092:                }
1.244     markus   1093:        }
                   1094:
                   1095:        if (use_privsep) {
                   1096:                struct passwd *pw;
                   1097:                struct stat st;
                   1098:
                   1099:                if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
                   1100:                        fatal("Privilege separation user %s does not exist",
                   1101:                            SSH_PRIVSEP_USER);
                   1102:                if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
                   1103:                    (S_ISDIR(st.st_mode) == 0))
                   1104:                        fatal("Missing privilege separation directory: %s",
1.247     stevesk  1105:                            _PATH_PRIVSEP_CHROOT_DIR);
                   1106:                if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1.262     markus   1107:                        fatal("%s must be owned by root and not group or "
                   1108:                            "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1.108     markus   1109:        }
1.203     stevesk  1110:
                   1111:        /* Configuration looks good, so exit if in test mode. */
                   1112:        if (test_flag)
                   1113:                exit(0);
1.108     markus   1114:
1.294   ! djm      1115:        if (rexec_flag) {
        !          1116:                rexec_argv = xmalloc(sizeof(char *) * (rexec_argc + 2));
        !          1117:                for (i = 0; i < rexec_argc; i++) {
        !          1118:                        debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
        !          1119:                        rexec_argv[i] = saved_argv[i];
        !          1120:                }
        !          1121:                rexec_argv[rexec_argc] = "-R";
        !          1122:                rexec_argv[rexec_argc + 1] = NULL;
        !          1123:        }
        !          1124:
1.108     markus   1125:        /* Initialize the log (it is reinitialized below in case we forked). */
1.64      markus   1126:        if (debug_flag && !inetd_flag)
                   1127:                log_stderr = 1;
1.138     markus   1128:        log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64      markus   1129:
1.108     markus   1130:        /*
                   1131:         * If not in debugging mode, and not started from inetd, disconnect
                   1132:         * from the controlling terminal, and fork.  The original process
                   1133:         * exits.
                   1134:         */
1.135     markus   1135:        if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1.1       deraadt  1136: #ifdef TIOCNOTTY
1.64      markus   1137:                int fd;
1.1       deraadt  1138: #endif /* TIOCNOTTY */
1.64      markus   1139:                if (daemon(0, 0) < 0)
                   1140:                        fatal("daemon() failed: %.200s", strerror(errno));
                   1141:
                   1142:                /* Disconnect from the controlling tty. */
1.1       deraadt  1143: #ifdef TIOCNOTTY
1.165     itojun   1144:                fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1.64      markus   1145:                if (fd >= 0) {
                   1146:                        (void) ioctl(fd, TIOCNOTTY, NULL);
                   1147:                        close(fd);
                   1148:                }
                   1149: #endif /* TIOCNOTTY */
                   1150:        }
                   1151:        /* Reinitialize the log (because of the fork above). */
1.138     markus   1152:        log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64      markus   1153:
                   1154:        /* Initialize the random number generator. */
                   1155:        arc4random_stir();
                   1156:
                   1157:        /* Chdir to the root directory so that the current disk can be
                   1158:           unmounted if desired. */
                   1159:        chdir("/");
1.217     deraadt  1160:
1.178     markus   1161:        /* ignore SIGPIPE */
                   1162:        signal(SIGPIPE, SIG_IGN);
1.64      markus   1163:
                   1164:        /* Start listening for a socket, unless started from inetd. */
                   1165:        if (inetd_flag) {
1.294   ! djm      1166:                int fd;
        !          1167:
1.123     djm      1168:                startup_pipe = -1;
1.294   ! djm      1169:                if (rexeced_flag) {
        !          1170:                        close(STDERR_FILENO + 2);
        !          1171:                        sock_in = sock_out = dup(STDIN_FILENO);
        !          1172:                        if (!debug_flag) {
        !          1173:                                startup_pipe = dup(STDERR_FILENO + 1);
        !          1174:                                close(STDERR_FILENO + 1);
        !          1175:                        }
        !          1176:                } else {
        !          1177:                        sock_in = dup(STDIN_FILENO);
        !          1178:                        sock_out = dup(STDOUT_FILENO);
        !          1179:                }
1.108     markus   1180:                /*
                   1181:                 * We intentionally do not close the descriptors 0, 1, and 2
1.294   ! djm      1182:                 * as our code for setting the descriptors won't work if
1.108     markus   1183:                 * ttyfd happens to be one of those.
                   1184:                 */
1.294   ! djm      1185:                if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
        !          1186:                        dup2(fd, STDIN_FILENO);
        !          1187:                        dup2(fd, STDOUT_FILENO);
        !          1188:                        if (fd > STDOUT_FILENO)
        !          1189:                                close(fd);
        !          1190:                }
1.64      markus   1191:                debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
1.294   ! djm      1192:                if ((options.protocol & SSH_PROTO_1) &&
        !          1193:                    sensitive_data.server_key == NULL)
1.174     deraadt  1194:                        generate_ephemeral_server_key();
1.64      markus   1195:        } else {
1.75      markus   1196:                for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
                   1197:                        if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   1198:                                continue;
                   1199:                        if (num_listen_socks >= MAX_LISTEN_SOCKS)
                   1200:                                fatal("Too many listen sockets. "
                   1201:                                    "Enlarge MAX_LISTEN_SOCKS");
                   1202:                        if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
                   1203:                            ntop, sizeof(ntop), strport, sizeof(strport),
                   1204:                            NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
                   1205:                                error("getnameinfo failed");
                   1206:                                continue;
                   1207:                        }
                   1208:                        /* Create socket for listening. */
1.265     markus   1209:                        listen_sock = socket(ai->ai_family, ai->ai_socktype,
                   1210:                            ai->ai_protocol);
1.75      markus   1211:                        if (listen_sock < 0) {
                   1212:                                /* kernel may not support ipv6 */
                   1213:                                verbose("socket: %.100s", strerror(errno));
                   1214:                                continue;
                   1215:                        }
1.293     djm      1216:                        if (set_nonblock(listen_sock) == -1) {
1.286     markus   1217:                                close(listen_sock);
                   1218:                                continue;
                   1219:                        }
1.75      markus   1220:                        /*
1.258     stevesk  1221:                         * Set socket options.
                   1222:                         * Allow local port reuse in TIME_WAIT.
1.75      markus   1223:                         */
1.258     stevesk  1224:                        if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
                   1225:                            &on, sizeof(on)) == -1)
                   1226:                                error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1.75      markus   1227:
                   1228:                        debug("Bind to port %s on %s.", strport, ntop);
                   1229:
                   1230:                        /* Bind the socket to the desired port. */
                   1231:                        if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   1232:                                error("Bind to port %s on %s failed: %.200s.",
                   1233:                                    strport, ntop, strerror(errno));
                   1234:                                close(listen_sock);
                   1235:                                continue;
                   1236:                        }
                   1237:                        listen_socks[num_listen_socks] = listen_sock;
                   1238:                        num_listen_socks++;
                   1239:
                   1240:                        /* Start listening on the port. */
1.264     itojun   1241:                        logit("Server listening on %s port %s.", ntop, strport);
1.282     markus   1242:                        if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1.75      markus   1243:                                fatal("listen: %.100s", strerror(errno));
                   1244:
1.64      markus   1245:                }
1.75      markus   1246:                freeaddrinfo(options.listen_addrs);
                   1247:
                   1248:                if (!num_listen_socks)
                   1249:                        fatal("Cannot bind any address.");
                   1250:
1.201     markus   1251:                if (options.protocol & SSH_PROTO_1)
                   1252:                        generate_ephemeral_server_key();
                   1253:
                   1254:                /*
                   1255:                 * Arrange to restart on SIGHUP.  The handler needs
                   1256:                 * listen_sock.
                   1257:                 */
                   1258:                signal(SIGHUP, sighup_handler);
                   1259:
                   1260:                signal(SIGTERM, sigterm_handler);
                   1261:                signal(SIGQUIT, sigterm_handler);
                   1262:
                   1263:                /* Arrange SIGCHLD to be caught. */
                   1264:                signal(SIGCHLD, main_sigchld_handler);
                   1265:
                   1266:                /* Write out the pid file after the sigterm handler is setup */
1.64      markus   1267:                if (!debug_flag) {
1.66      markus   1268:                        /*
1.136     todd     1269:                         * Record our pid in /var/run/sshd.pid to make it
                   1270:                         * easier to kill the correct sshd.  We don't want to
                   1271:                         * do this before the bind above because the bind will
1.66      markus   1272:                         * fail if there already is a daemon, and this will
                   1273:                         * overwrite any old pid in the file.
                   1274:                         */
1.112     markus   1275:                        f = fopen(options.pid_file, "w");
1.270     djm      1276:                        if (f == NULL) {
                   1277:                                error("Couldn't create pid file \"%s\": %s",
                   1278:                                    options.pid_file, strerror(errno));
                   1279:                        } else {
1.245     mpech    1280:                                fprintf(f, "%ld\n", (long) getpid());
1.64      markus   1281:                                fclose(f);
                   1282:                        }
                   1283:                }
                   1284:
1.75      markus   1285:                /* setup fd set for listen */
1.120     markus   1286:                fdset = NULL;
1.75      markus   1287:                maxfd = 0;
                   1288:                for (i = 0; i < num_listen_socks; i++)
                   1289:                        if (listen_socks[i] > maxfd)
                   1290:                                maxfd = listen_socks[i];
1.120     markus   1291:                /* pipes connected to unauthenticated childs */
                   1292:                startup_pipes = xmalloc(options.max_startups * sizeof(int));
                   1293:                for (i = 0; i < options.max_startups; i++)
                   1294:                        startup_pipes[i] = -1;
1.75      markus   1295:
1.66      markus   1296:                /*
                   1297:                 * Stay listening for connections until the system crashes or
                   1298:                 * the daemon is killed with a signal.
                   1299:                 */
1.64      markus   1300:                for (;;) {
                   1301:                        if (received_sighup)
                   1302:                                sighup_restart();
1.120     markus   1303:                        if (fdset != NULL)
                   1304:                                xfree(fdset);
1.148     markus   1305:                        fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
1.120     markus   1306:                        fdset = (fd_set *)xmalloc(fdsetsz);
1.75      markus   1307:                        memset(fdset, 0, fdsetsz);
1.120     markus   1308:
1.75      markus   1309:                        for (i = 0; i < num_listen_socks; i++)
                   1310:                                FD_SET(listen_socks[i], fdset);
1.120     markus   1311:                        for (i = 0; i < options.max_startups; i++)
                   1312:                                if (startup_pipes[i] != -1)
                   1313:                                        FD_SET(startup_pipes[i], fdset);
                   1314:
                   1315:                        /* Wait in select until there is a connection. */
1.151     markus   1316:                        ret = select(maxfd+1, fdset, NULL, NULL, NULL);
                   1317:                        if (ret < 0 && errno != EINTR)
                   1318:                                error("select: %.100s", strerror(errno));
1.199     markus   1319:                        if (received_sigterm) {
1.264     itojun   1320:                                logit("Received signal %d; terminating.",
1.213     itojun   1321:                                    (int) received_sigterm);
1.199     markus   1322:                                close_listen_socks();
                   1323:                                unlink(options.pid_file);
                   1324:                                exit(255);
                   1325:                        }
1.151     markus   1326:                        if (key_used && key_do_regen) {
1.174     deraadt  1327:                                generate_ephemeral_server_key();
1.151     markus   1328:                                key_used = 0;
                   1329:                                key_do_regen = 0;
                   1330:                        }
                   1331:                        if (ret < 0)
1.75      markus   1332:                                continue;
1.151     markus   1333:
1.120     markus   1334:                        for (i = 0; i < options.max_startups; i++)
                   1335:                                if (startup_pipes[i] != -1 &&
                   1336:                                    FD_ISSET(startup_pipes[i], fdset)) {
                   1337:                                        /*
                   1338:                                         * the read end of the pipe is ready
                   1339:                                         * if the child has closed the pipe
1.143     markus   1340:                                         * after successful authentication
1.120     markus   1341:                                         * or if the child has died
                   1342:                                         */
                   1343:                                        close(startup_pipes[i]);
                   1344:                                        startup_pipes[i] = -1;
                   1345:                                        startups--;
                   1346:                                }
1.75      markus   1347:                        for (i = 0; i < num_listen_socks; i++) {
                   1348:                                if (!FD_ISSET(listen_socks[i], fdset))
1.70      provos   1349:                                        continue;
1.120     markus   1350:                                fromlen = sizeof(from);
                   1351:                                newsock = accept(listen_socks[i], (struct sockaddr *)&from,
                   1352:                                    &fromlen);
                   1353:                                if (newsock < 0) {
                   1354:                                        if (errno != EINTR && errno != EWOULDBLOCK)
                   1355:                                                error("accept: %.100s", strerror(errno));
1.286     markus   1356:                                        continue;
                   1357:                                }
1.293     djm      1358:                                if (unset_nonblock(newsock) == -1) {
1.286     markus   1359:                                        close(newsock);
1.120     markus   1360:                                        continue;
                   1361:                                }
1.124     markus   1362:                                if (drop_connection(startups) == 1) {
                   1363:                                        debug("drop connection #%d", startups);
1.120     markus   1364:                                        close(newsock);
                   1365:                                        continue;
                   1366:                                }
                   1367:                                if (pipe(startup_p) == -1) {
                   1368:                                        close(newsock);
                   1369:                                        continue;
                   1370:                                }
                   1371:
1.294   ! djm      1372:                                if (rexec_flag && socketpair(AF_UNIX,
        !          1373:                                    SOCK_STREAM, 0, config_s) == -1) {
        !          1374:                                        error("reexec socketpair: %s",
        !          1375:                                            strerror(errno));
        !          1376:                                        close(newsock);
        !          1377:                                        close(startup_p[0]);
        !          1378:                                        close(startup_p[1]);
        !          1379:                                        continue;
        !          1380:                                }
        !          1381:
1.120     markus   1382:                                for (j = 0; j < options.max_startups; j++)
                   1383:                                        if (startup_pipes[j] == -1) {
                   1384:                                                startup_pipes[j] = startup_p[0];
                   1385:                                                if (maxfd < startup_p[0])
                   1386:                                                        maxfd = startup_p[0];
                   1387:                                                startups++;
                   1388:                                                break;
                   1389:                                        }
1.161     stevesk  1390:
1.66      markus   1391:                                /*
1.120     markus   1392:                                 * Got connection.  Fork a child to handle it, unless
                   1393:                                 * we are in debugging mode.
1.66      markus   1394:                                 */
1.120     markus   1395:                                if (debug_flag) {
1.66      markus   1396:                                        /*
1.120     markus   1397:                                         * In debugging mode.  Close the listening
                   1398:                                         * socket, and start processing the
                   1399:                                         * connection without forking.
1.66      markus   1400:                                         */
1.120     markus   1401:                                        debug("Server will not fork when running in debugging mode.");
1.75      markus   1402:                                        close_listen_socks();
1.64      markus   1403:                                        sock_in = newsock;
                   1404:                                        sock_out = newsock;
1.294   ! djm      1405:                                        close(startup_p[0]);
        !          1406:                                        close(startup_p[1]);
1.122     deraadt  1407:                                        startup_pipe = -1;
1.120     markus   1408:                                        pid = getpid();
1.294   ! djm      1409:                                        if (rexec_flag) {
        !          1410:                                                send_rexec_state(config_s[0],
        !          1411:                                                    &cfg);
        !          1412:                                                close(config_s[0]);
        !          1413:                                        }
1.64      markus   1414:                                        break;
1.120     markus   1415:                                } else {
                   1416:                                        /*
                   1417:                                         * Normal production daemon.  Fork, and have
                   1418:                                         * the child process the connection. The
                   1419:                                         * parent continues listening.
                   1420:                                         */
                   1421:                                        if ((pid = fork()) == 0) {
                   1422:                                                /*
                   1423:                                                 * Child.  Close the listening and max_startup
                   1424:                                                 * sockets.  Start using the accepted socket.
                   1425:                                                 * Reinitialize logging (since our pid has
                   1426:                                                 * changed).  We break out of the loop to handle
                   1427:                                                 * the connection.
                   1428:                                                 */
                   1429:                                                startup_pipe = startup_p[1];
1.211     markus   1430:                                                close_startup_pipes();
1.120     markus   1431:                                                close_listen_socks();
                   1432:                                                sock_in = newsock;
                   1433:                                                sock_out = newsock;
1.138     markus   1434:                                                log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.120     markus   1435:                                                break;
                   1436:                                        }
1.64      markus   1437:                                }
                   1438:
1.120     markus   1439:                                /* Parent.  Stay in the loop. */
                   1440:                                if (pid < 0)
                   1441:                                        error("fork: %.100s", strerror(errno));
                   1442:                                else
1.245     mpech    1443:                                        debug("Forked child %ld.", (long)pid);
1.120     markus   1444:
                   1445:                                close(startup_p[1]);
1.1       deraadt  1446:
1.294   ! djm      1447:                                if (rexec_flag) {
        !          1448:                                        send_rexec_state(config_s[0], &cfg);
        !          1449:                                        close(config_s[0]);
        !          1450:                                        close(config_s[1]);
        !          1451:                                }
        !          1452:
1.120     markus   1453:                                /* Mark that the key has been used (it was "given" to the child). */
1.151     markus   1454:                                if ((options.protocol & SSH_PROTO_1) &&
                   1455:                                    key_used == 0) {
                   1456:                                        /* Schedule server key regeneration alarm. */
                   1457:                                        signal(SIGALRM, key_regeneration_alarm);
                   1458:                                        alarm(options.key_regeneration_time);
                   1459:                                        key_used = 1;
                   1460:                                }
1.1       deraadt  1461:
1.120     markus   1462:                                arc4random_stir();
1.1       deraadt  1463:
1.120     markus   1464:                                /* Close the new socket (the child is now taking care of it). */
                   1465:                                close(newsock);
                   1466:                        }
1.75      markus   1467:                        /* child process check (or debug mode) */
                   1468:                        if (num_listen_socks < 0)
                   1469:                                break;
1.64      markus   1470:                }
1.1       deraadt  1471:        }
                   1472:
1.64      markus   1473:        /* This is the child processing a new connection. */
1.288     markus   1474:        setproctitle("%s", "[accepted]");
1.294   ! djm      1475:
        !          1476:        if (rexec_flag) {
        !          1477:                int fd;
        !          1478:
        !          1479:                debug("rexec newsock %d pipe %d sock %d", newsock,
        !          1480:                    startup_pipe, config_s[0]);
        !          1481:                dup2(newsock, STDIN_FILENO);
        !          1482:                dup2(STDIN_FILENO, STDOUT_FILENO);
        !          1483:                if (startup_pipe == -1)
        !          1484:                        close(STDERR_FILENO + 1);
        !          1485:                else
        !          1486:                        dup2(startup_pipe, STDERR_FILENO + 1);
        !          1487:
        !          1488:                dup2(config_s[1], STDERR_FILENO + 2);
        !          1489:                close(config_s[1]);
        !          1490:                execv(rexec_argv[0], rexec_argv);
        !          1491:
        !          1492:                /* Reexec has failed, fall back and continue */
        !          1493:                error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
        !          1494:                recv_rexec_state(STDERR_FILENO + 2, NULL);
        !          1495:                log_init(__progname, options.log_level,
        !          1496:                    options.log_facility, log_stderr);
        !          1497:
        !          1498:                /* Clean up fds */
        !          1499:                close(config_s[1]);
        !          1500:                close(STDERR_FILENO + 1);
        !          1501:                close(STDERR_FILENO + 2);
        !          1502:                if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
        !          1503:                        dup2(fd, STDIN_FILENO);
        !          1504:                        dup2(fd, STDOUT_FILENO);
        !          1505:                        if (fd > STDERR_FILENO)
        !          1506:                                close(fd);
        !          1507:                }
        !          1508:        }
1.241     millert  1509:
                   1510:        /*
                   1511:         * Create a new session and process group since the 4.4BSD
                   1512:         * setlogin() affects the entire process group.  We don't
                   1513:         * want the child to be able to affect the parent.
                   1514:         */
1.248     stevesk  1515:        if (!debug_flag && !inetd_flag && setsid() < 0)
1.241     millert  1516:                error("setsid: %.100s", strerror(errno));
1.64      markus   1517:
1.66      markus   1518:        /*
                   1519:         * Disable the key regeneration alarm.  We will not regenerate the
                   1520:         * key since we are no longer in a position to give it to anyone. We
                   1521:         * will not restart on SIGHUP since it no longer makes sense.
                   1522:         */
1.64      markus   1523:        alarm(0);
                   1524:        signal(SIGALRM, SIG_DFL);
                   1525:        signal(SIGHUP, SIG_DFL);
                   1526:        signal(SIGTERM, SIG_DFL);
                   1527:        signal(SIGQUIT, SIG_DFL);
                   1528:        signal(SIGCHLD, SIG_DFL);
1.150     markus   1529:
1.284     markus   1530:        /* Set SO_KEEPALIVE if requested. */
                   1531:        if (options.tcp_keep_alive &&
1.228     stevesk  1532:            setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on,
1.150     markus   1533:            sizeof(on)) < 0)
                   1534:                error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1.64      markus   1535:
1.66      markus   1536:        /*
                   1537:         * Register our connection.  This turns encryption off because we do
                   1538:         * not have a key.
                   1539:         */
1.64      markus   1540:        packet_set_connection(sock_in, sock_out);
1.1       deraadt  1541:
1.64      markus   1542:        remote_port = get_remote_port();
                   1543:        remote_ip = get_remote_ipaddr();
1.52      markus   1544:
1.209     markus   1545: #ifdef LIBWRAP
1.64      markus   1546:        /* Check whether logins are denied from this host. */
                   1547:        {
                   1548:                struct request_info req;
1.37      dugsong  1549:
1.204     camield  1550:                request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1.64      markus   1551:                fromhost(&req);
1.37      dugsong  1552:
1.64      markus   1553:                if (!hosts_access(&req)) {
1.209     markus   1554:                        debug("Connection refused by tcp wrapper");
1.182     markus   1555:                        refuse(&req);
1.209     markus   1556:                        /* NOTREACHED */
                   1557:                        fatal("libwrap refuse returns");
1.64      markus   1558:                }
                   1559:        }
1.75      markus   1560: #endif /* LIBWRAP */
1.209     markus   1561:
1.64      markus   1562:        /* Log the connection. */
                   1563:        verbose("Connection from %.500s port %d", remote_ip, remote_port);
1.1       deraadt  1564:
1.66      markus   1565:        /*
                   1566:         * We don\'t want to listen forever unless the other side
                   1567:         * successfully authenticates itself.  So we set up an alarm which is
                   1568:         * cleared after successful authentication.  A limit of zero
                   1569:         * indicates no limit. Note that we don\'t set the alarm in debugging
                   1570:         * mode; it is just annoying to have the server exit just when you
                   1571:         * are about to discover the bug.
                   1572:         */
1.64      markus   1573:        signal(SIGALRM, grace_alarm_handler);
                   1574:        if (!debug_flag)
                   1575:                alarm(options.login_grace_time);
                   1576:
1.96      markus   1577:        sshd_exchange_identification(sock_in, sock_out);
1.275     markus   1578:
1.64      markus   1579:        packet_set_nonblocking();
1.1       deraadt  1580:
1.278     markus   1581:        /* allocate authentication context */
                   1582:        authctxt = xmalloc(sizeof(*authctxt));
                   1583:        memset(authctxt, 0, sizeof(*authctxt));
                   1584:
                   1585:        /* XXX global for cleanup, access from other modules */
                   1586:        the_authctxt = authctxt;
                   1587:
1.237     markus   1588:        if (use_privsep)
1.278     markus   1589:                if (privsep_preauth(authctxt) == 1)
1.237     markus   1590:                        goto authenticated;
1.231     provos   1591:
1.77      markus   1592:        /* perform the key exchange */
                   1593:        /* authenticate user and start session */
1.98      markus   1594:        if (compat20) {
                   1595:                do_ssh2_kex();
1.278     markus   1596:                do_authentication2(authctxt);
1.98      markus   1597:        } else {
                   1598:                do_ssh1_kex();
1.278     markus   1599:                do_authentication(authctxt);
1.98      markus   1600:        }
1.237     markus   1601:        /*
                   1602:         * If we use privilege separation, the unprivileged child transfers
                   1603:         * the current keystate and exits
                   1604:         */
                   1605:        if (use_privsep) {
1.242     mouring  1606:                mm_send_keystate(pmonitor);
1.231     provos   1607:                exit(0);
1.237     markus   1608:        }
1.231     provos   1609:
                   1610:  authenticated:
1.234     markus   1611:        /*
1.231     provos   1612:         * In privilege separation, we fork another child and prepare
                   1613:         * file descriptor passing.
                   1614:         */
                   1615:        if (use_privsep) {
1.237     markus   1616:                privsep_postauth(authctxt);
                   1617:                /* the monitor process [priv] will not return */
1.231     provos   1618:                if (!compat20)
                   1619:                        destroy_sensitive_data();
                   1620:        }
1.230     provos   1621:
1.278     markus   1622:        /* Start session. */
1.230     provos   1623:        do_authenticated(authctxt);
                   1624:
1.64      markus   1625:        /* The connection has been terminated. */
                   1626:        verbose("Closing connection to %.100s", remote_ip);
                   1627:        packet_close();
1.231     provos   1628:
                   1629:        if (use_privsep)
                   1630:                mm_terminate();
                   1631:
1.64      markus   1632:        exit(0);
1.1       deraadt  1633: }
                   1634:
1.65      deraadt  1635: /*
1.229     markus   1636:  * Decrypt session_key_int using our private server key and private host key
                   1637:  * (key with larger modulus first).
                   1638:  */
1.231     provos   1639: int
1.229     markus   1640: ssh1_session_key(BIGNUM *session_key_int)
                   1641: {
                   1642:        int rsafail = 0;
                   1643:
                   1644:        if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
                   1645:                /* Server key has bigger modulus. */
                   1646:                if (BN_num_bits(sensitive_data.server_key->rsa->n) <
                   1647:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
                   1648:                        fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
                   1649:                            get_remote_ipaddr(),
                   1650:                            BN_num_bits(sensitive_data.server_key->rsa->n),
                   1651:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
                   1652:                            SSH_KEY_BITS_RESERVED);
                   1653:                }
                   1654:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   1655:                    sensitive_data.server_key->rsa) <= 0)
                   1656:                        rsafail++;
                   1657:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   1658:                    sensitive_data.ssh1_host_key->rsa) <= 0)
                   1659:                        rsafail++;
                   1660:        } else {
                   1661:                /* Host key has bigger modulus (or they are equal). */
                   1662:                if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
                   1663:                    BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
                   1664:                        fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
                   1665:                            get_remote_ipaddr(),
                   1666:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
                   1667:                            BN_num_bits(sensitive_data.server_key->rsa->n),
                   1668:                            SSH_KEY_BITS_RESERVED);
                   1669:                }
                   1670:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   1671:                    sensitive_data.ssh1_host_key->rsa) < 0)
                   1672:                        rsafail++;
                   1673:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   1674:                    sensitive_data.server_key->rsa) < 0)
                   1675:                        rsafail++;
                   1676:        }
                   1677:        return (rsafail);
                   1678: }
                   1679: /*
1.77      markus   1680:  * SSH1 key exchange
1.65      deraadt  1681:  */
1.200     itojun   1682: static void
1.142     markus   1683: do_ssh1_kex(void)
1.1       deraadt  1684: {
1.64      markus   1685:        int i, len;
1.159     markus   1686:        int rsafail = 0;
1.64      markus   1687:        BIGNUM *session_key_int;
1.140     markus   1688:        u_char session_key[SSH_SESSION_KEY_LENGTH];
                   1689:        u_char cookie[8];
                   1690:        u_int cipher_type, auth_mask, protocol_flags;
1.254     deraadt  1691:        u_int32_t rnd = 0;
1.64      markus   1692:
1.66      markus   1693:        /*
                   1694:         * Generate check bytes that the client must send back in the user
                   1695:         * packet in order for it to be accepted; this is used to defy ip
                   1696:         * spoofing attacks.  Note that this only works against somebody
                   1697:         * doing IP spoofing from a remote machine; any machine on the local
                   1698:         * network can still see outgoing packets and catch the random
                   1699:         * cookie.  This only affects rhosts authentication, and this is one
                   1700:         * of the reasons why it is inherently insecure.
                   1701:         */
1.64      markus   1702:        for (i = 0; i < 8; i++) {
                   1703:                if (i % 4 == 0)
1.254     deraadt  1704:                        rnd = arc4random();
                   1705:                cookie[i] = rnd & 0xff;
                   1706:                rnd >>= 8;
1.64      markus   1707:        }
                   1708:
1.66      markus   1709:        /*
                   1710:         * Send our public key.  We include in the packet 64 bits of random
                   1711:         * data that must be matched in the reply in order to prevent IP
                   1712:         * spoofing.
                   1713:         */
1.64      markus   1714:        packet_start(SSH_SMSG_PUBLIC_KEY);
                   1715:        for (i = 0; i < 8; i++)
1.77      markus   1716:                packet_put_char(cookie[i]);
1.64      markus   1717:
                   1718:        /* Store our public server RSA key. */
1.134     markus   1719:        packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
                   1720:        packet_put_bignum(sensitive_data.server_key->rsa->e);
                   1721:        packet_put_bignum(sensitive_data.server_key->rsa->n);
1.64      markus   1722:
                   1723:        /* Store our public host RSA key. */
1.134     markus   1724:        packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
                   1725:        packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
                   1726:        packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1.64      markus   1727:
                   1728:        /* Put protocol flags. */
                   1729:        packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
                   1730:
                   1731:        /* Declare which ciphers we support. */
1.131     markus   1732:        packet_put_int(cipher_mask_ssh1(0));
1.64      markus   1733:
                   1734:        /* Declare supported authentication types. */
                   1735:        auth_mask = 0;
                   1736:        if (options.rhosts_rsa_authentication)
                   1737:                auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
                   1738:        if (options.rsa_authentication)
                   1739:                auth_mask |= 1 << SSH_AUTH_RSA;
1.196     markus   1740:        if (options.challenge_response_authentication == 1)
1.64      markus   1741:                auth_mask |= 1 << SSH_AUTH_TIS;
                   1742:        if (options.password_authentication)
                   1743:                auth_mask |= 1 << SSH_AUTH_PASSWORD;
                   1744:        packet_put_int(auth_mask);
                   1745:
                   1746:        /* Send the packet and wait for it to be sent. */
                   1747:        packet_send();
                   1748:        packet_write_wait();
                   1749:
1.134     markus   1750:        debug("Sent %d bit server key and %d bit host key.",
                   1751:            BN_num_bits(sensitive_data.server_key->rsa->n),
                   1752:            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1.64      markus   1753:
                   1754:        /* Read clients reply (cipher type and session key). */
1.222     markus   1755:        packet_read_expect(SSH_CMSG_SESSION_KEY);
1.64      markus   1756:
1.69      markus   1757:        /* Get cipher type and check whether we accept this. */
1.64      markus   1758:        cipher_type = packet_get_char();
1.69      markus   1759:
1.131     markus   1760:        if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1.69      markus   1761:                packet_disconnect("Warning: client selects unsupported cipher.");
1.64      markus   1762:
                   1763:        /* Get check bytes from the packet.  These must match those we
                   1764:           sent earlier with the public key packet. */
                   1765:        for (i = 0; i < 8; i++)
1.77      markus   1766:                if (cookie[i] != packet_get_char())
1.64      markus   1767:                        packet_disconnect("IP Spoofing check bytes do not match.");
                   1768:
                   1769:        debug("Encryption type: %.200s", cipher_name(cipher_type));
                   1770:
                   1771:        /* Get the encrypted integer. */
1.218     markus   1772:        if ((session_key_int = BN_new()) == NULL)
                   1773:                fatal("do_ssh1_kex: BN_new failed");
1.221     markus   1774:        packet_get_bignum(session_key_int);
1.64      markus   1775:
                   1776:        protocol_flags = packet_get_int();
                   1777:        packet_set_protocol_flags(protocol_flags);
1.220     markus   1778:        packet_check_eom();
1.64      markus   1779:
1.229     markus   1780:        /* Decrypt session_key_int using host/server keys */
1.231     provos   1781:        rsafail = PRIVSEP(ssh1_session_key(session_key_int));
                   1782:
1.66      markus   1783:        /*
                   1784:         * Extract session key from the decrypted integer.  The key is in the
                   1785:         * least significant 256 bits of the integer; the first byte of the
                   1786:         * key is in the highest bits.
                   1787:         */
1.159     markus   1788:        if (!rsafail) {
                   1789:                BN_mask_bits(session_key_int, sizeof(session_key) * 8);
                   1790:                len = BN_num_bytes(session_key_int);
                   1791:                if (len < 0 || len > sizeof(session_key)) {
                   1792:                        error("do_connection: bad session key len from %s: "
1.165     itojun   1793:                            "session_key_int %d > sizeof(session_key) %lu",
                   1794:                            get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1.159     markus   1795:                        rsafail++;
                   1796:                } else {
                   1797:                        memset(session_key, 0, sizeof(session_key));
                   1798:                        BN_bn2bin(session_key_int,
                   1799:                            session_key + sizeof(session_key) - len);
1.169     markus   1800:
1.291     djm      1801:                        derive_ssh1_session_id(
                   1802:                            sensitive_data.ssh1_host_key->rsa->n,
                   1803:                            sensitive_data.server_key->rsa->n,
                   1804:                            cookie, session_id);
1.169     markus   1805:                        /*
                   1806:                         * Xor the first 16 bytes of the session key with the
                   1807:                         * session id.
                   1808:                         */
                   1809:                        for (i = 0; i < 16; i++)
                   1810:                                session_key[i] ^= session_id[i];
1.159     markus   1811:                }
                   1812:        }
                   1813:        if (rsafail) {
1.169     markus   1814:                int bytes = BN_num_bytes(session_key_int);
1.227     stevesk  1815:                u_char *buf = xmalloc(bytes);
1.169     markus   1816:                MD5_CTX md;
                   1817:
1.264     itojun   1818:                logit("do_connection: generating a fake encryption key");
1.169     markus   1819:                BN_bn2bin(session_key_int, buf);
                   1820:                MD5_Init(&md);
                   1821:                MD5_Update(&md, buf, bytes);
                   1822:                MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
                   1823:                MD5_Final(session_key, &md);
                   1824:                MD5_Init(&md);
                   1825:                MD5_Update(&md, session_key, 16);
                   1826:                MD5_Update(&md, buf, bytes);
                   1827:                MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
                   1828:                MD5_Final(session_key + 16, &md);
                   1829:                memset(buf, 0, bytes);
                   1830:                xfree(buf);
1.170     markus   1831:                for (i = 0; i < 16; i++)
                   1832:                        session_id[i] = session_key[i] ^ session_key[i + 16];
1.159     markus   1833:        }
1.231     provos   1834:        /* Destroy the private and public keys. No longer. */
1.169     markus   1835:        destroy_sensitive_data();
                   1836:
1.231     provos   1837:        if (use_privsep)
                   1838:                mm_ssh1_session_id(session_id);
                   1839:
1.77      markus   1840:        /* Destroy the decrypted integer.  It is no longer needed. */
                   1841:        BN_clear_free(session_key_int);
1.64      markus   1842:
                   1843:        /* Set the session key.  From this on all communications will be encrypted. */
                   1844:        packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
                   1845:
                   1846:        /* Destroy our copy of the session key.  It is no longer needed. */
                   1847:        memset(session_key, 0, sizeof(session_key));
                   1848:
                   1849:        debug("Received session key; encryption turned on.");
                   1850:
1.243     deraadt  1851:        /* Send an acknowledgment packet.  Note that this packet is sent encrypted. */
1.64      markus   1852:        packet_start(SSH_SMSG_SUCCESS);
                   1853:        packet_send();
                   1854:        packet_write_wait();
1.98      markus   1855: }
                   1856:
                   1857: /*
                   1858:  * SSH2 key exchange: diffie-hellman-group1-sha1
                   1859:  */
1.200     itojun   1860: static void
1.142     markus   1861: do_ssh2_kex(void)
1.98      markus   1862: {
                   1863:        Kex *kex;
1.102     markus   1864:
                   1865:        if (options.ciphers != NULL) {
1.105     markus   1866:                myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1.102     markus   1867:                myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1.166     markus   1868:        }
1.184     stevesk  1869:        myproposal[PROPOSAL_ENC_ALGS_CTOS] =
                   1870:            compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
                   1871:        myproposal[PROPOSAL_ENC_ALGS_STOC] =
                   1872:            compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
                   1873:
1.166     markus   1874:        if (options.macs != NULL) {
                   1875:                myproposal[PROPOSAL_MAC_ALGS_CTOS] =
                   1876:                myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1.246     markus   1877:        }
                   1878:        if (!options.compression) {
                   1879:                myproposal[PROPOSAL_COMP_ALGS_CTOS] =
                   1880:                myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
1.102     markus   1881:        }
1.134     markus   1882:        myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
                   1883:
1.189     markus   1884:        /* start key exchange */
1.188     markus   1885:        kex = kex_setup(myproposal);
1.263     markus   1886:        kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1.292     djm      1887:        kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1.263     markus   1888:        kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1.186     markus   1889:        kex->server = 1;
                   1890:        kex->client_version_string=client_version_string;
                   1891:        kex->server_version_string=server_version_string;
                   1892:        kex->load_host_key=&get_hostkey_by_type;
1.231     provos   1893:        kex->host_key_index=&get_hostkey_index;
1.129     provos   1894:
1.189     markus   1895:        xxx_kex = kex;
                   1896:
1.190     markus   1897:        dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1.187     markus   1898:
                   1899:        session_id2 = kex->session_id;
                   1900:        session_id2_len = kex->session_id_len;
1.129     provos   1901:
                   1902: #ifdef DEBUG_KEXDH
                   1903:        /* send 1st encrypted/maced/compressed message */
                   1904:        packet_start(SSH2_MSG_IGNORE);
                   1905:        packet_put_cstring("markus");
                   1906:        packet_send();
                   1907:        packet_write_wait();
                   1908: #endif
1.186     markus   1909:        debug("KEX done");
1.278     markus   1910: }
                   1911:
                   1912: /* server specific fatal cleanup */
                   1913: void
                   1914: cleanup_exit(int i)
                   1915: {
                   1916:        if (the_authctxt)
                   1917:                do_cleanup(the_authctxt);
                   1918:        _exit(i);
1.1       deraadt  1919: }