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

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.236   ! stevesk    45: RCSID("$OpenBSD: sshd.c,v 1.235 2002/03/20 19:12:25 stevesk 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"
                     59: #include "mpaux.h"
1.155     markus     60: #include "log.h"
1.1       deraadt    61: #include "servconf.h"
                     62: #include "uidswap.h"
1.33      markus     63: #include "compat.h"
1.96      markus     64: #include "buffer.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.186     markus     76: #include "dispatch.h"
1.206     stevesk    77: #include "channels.h"
1.230     provos     78: #include "session.h"
1.231     provos     79: #include "monitor_mm.h"
                     80: #include "monitor.h"
                     81: #include "monitor_wrap.h"
                     82: #include "monitor_fdpass.h"
1.1       deraadt    83:
                     84: #ifdef LIBWRAP
                     85: #include <tcpd.h>
                     86: #include <syslog.h>
                     87: int allow_severity = LOG_INFO;
                     88: int deny_severity = LOG_WARNING;
                     89: #endif /* LIBWRAP */
                     90:
                     91: #ifndef O_NOCTTY
                     92: #define O_NOCTTY       0
                     93: #endif
                     94:
1.138     markus     95: extern char *__progname;
                     96:
1.1       deraadt    97: /* Server configuration options. */
                     98: ServerOptions options;
                     99:
                    100: /* Name of the server configuration file. */
1.154     markus    101: char *config_file_name = _PATH_SERVER_CONFIG_FILE;
1.1       deraadt   102:
1.105     markus    103: /*
1.75      markus    104:  * Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
                    105:  * Default value is AF_UNSPEC means both IPv4 and IPv6.
                    106:  */
                    107: int IPv4or6 = AF_UNSPEC;
                    108:
1.65      deraadt   109: /*
                    110:  * Debug mode flag.  This can be set on the command line.  If debug
                    111:  * mode is enabled, extra debugging output will be sent to the system
                    112:  * log, the daemon will not go to background, and will exit after processing
                    113:  * the first connection.
                    114:  */
1.1       deraadt   115: int debug_flag = 0;
                    116:
1.203     stevesk   117: /* Flag indicating that the daemon should only test the configuration and keys. */
                    118: int test_flag = 0;
                    119:
1.1       deraadt   120: /* Flag indicating that the daemon is being started from inetd. */
                    121: int inetd_flag = 0;
                    122:
1.135     markus    123: /* Flag indicating that sshd should not detach and become a daemon. */
                    124: int no_daemon_flag = 0;
                    125:
1.47      markus    126: /* debug goes to stderr unless inetd_flag is set */
                    127: int log_stderr = 0;
                    128:
1.1       deraadt   129: /* Saved arguments to main(). */
                    130: char **saved_argv;
                    131:
1.66      markus    132: /*
1.75      markus    133:  * The sockets that the server is listening; this is used in the SIGHUP
                    134:  * signal handler.
1.66      markus    135:  */
1.75      markus    136: #define        MAX_LISTEN_SOCKS        16
                    137: int listen_socks[MAX_LISTEN_SOCKS];
                    138: int num_listen_socks = 0;
1.1       deraadt   139:
1.66      markus    140: /*
                    141:  * the client's version string, passed by sshd2 in compat mode. if != NULL,
                    142:  * sshd will skip the version-number exchange
                    143:  */
1.61      markus    144: char *client_version_string = NULL;
1.96      markus    145: char *server_version_string = NULL;
1.1       deraadt   146:
1.189     markus    147: /* for rekeying XXX fixme */
                    148: Kex *xxx_kex;
                    149:
1.66      markus    150: /*
                    151:  * Any really sensitive data in the application is contained in this
                    152:  * structure. The idea is that this structure could be locked into memory so
                    153:  * that the pages do not get written into swap.  However, there are some
                    154:  * problems. The private key contains BIGNUMs, and we do not (in principle)
                    155:  * have access to the internals of them, and locking just the structure is
                    156:  * not very useful.  Currently, memory locking is not implemented.
                    157:  */
1.64      markus    158: struct {
1.174     deraadt   159:        Key     *server_key;            /* ephemeral server key */
1.134     markus    160:        Key     *ssh1_host_key;         /* ssh1 host key */
                    161:        Key     **host_keys;            /* all private host keys */
                    162:        int     have_ssh1_key;
                    163:        int     have_ssh2_key;
1.169     markus    164:        u_char  ssh1_cookie[SSH_SESSION_KEY_LENGTH];
1.1       deraadt   165: } sensitive_data;
                    166:
1.66      markus    167: /*
1.151     markus    168:  * Flag indicating whether the RSA server key needs to be regenerated.
                    169:  * Is set in the SIGALRM handler and cleared when the key is regenerated.
1.66      markus    170:  */
1.212     markus    171: static volatile sig_atomic_t key_do_regen = 0;
1.1       deraadt   172:
1.199     markus    173: /* This is set to true when a signal is received. */
1.212     markus    174: static volatile sig_atomic_t received_sighup = 0;
                    175: static volatile sig_atomic_t received_sigterm = 0;
1.1       deraadt   176:
1.96      markus    177: /* session identifier, used by RSA-auth */
1.140     markus    178: u_char session_id[16];
1.96      markus    179:
1.108     markus    180: /* same for ssh2 */
1.140     markus    181: u_char *session_id2 = NULL;
1.108     markus    182: int session_id2_len = 0;
                    183:
1.125     markus    184: /* record remote hostname or ip */
1.140     markus    185: u_int utmp_len = MAXHOSTNAMELEN;
1.125     markus    186:
1.211     markus    187: /* options.max_startup sized array of fd ints */
                    188: int *startup_pipes = NULL;
                    189: int startup_pipe;              /* in child */
                    190:
1.231     provos    191: /* variables used for privilege separation */
                    192: extern struct monitor *monitor;
                    193: extern int use_privsep;
                    194:
1.1       deraadt   195: /* Prototypes for various functions defined later in this file. */
1.200     itojun    196: void destroy_sensitive_data(void);
1.231     provos    197: void demote_sensitive_data(void);
1.87      markus    198:
1.200     itojun    199: static void do_ssh1_kex(void);
                    200: static void do_ssh2_kex(void);
1.129     provos    201:
1.87      markus    202: /*
1.75      markus    203:  * Close all listening sockets
                    204:  */
1.200     itojun    205: static void
1.75      markus    206: close_listen_socks(void)
                    207: {
                    208:        int i;
                    209:        for (i = 0; i < num_listen_socks; i++)
                    210:                close(listen_socks[i]);
                    211:        num_listen_socks = -1;
                    212: }
                    213:
1.211     markus    214: static void
                    215: close_startup_pipes(void)
                    216: {
                    217:        int i;
                    218:        if (startup_pipes)
                    219:                for (i = 0; i < options.max_startups; i++)
                    220:                        if (startup_pipes[i] != -1)
                    221:                                close(startup_pipes[i]);
                    222: }
                    223:
1.75      markus    224: /*
1.65      deraadt   225:  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
                    226:  * the effect is to reread the configuration file (and to regenerate
                    227:  * the server key).
                    228:  */
1.200     itojun    229: static void
1.64      markus    230: sighup_handler(int sig)
1.1       deraadt   231: {
1.210     deraadt   232:        int save_errno = errno;
                    233:
1.64      markus    234:        received_sighup = 1;
                    235:        signal(SIGHUP, sighup_handler);
1.210     deraadt   236:        errno = save_errno;
1.1       deraadt   237: }
                    238:
1.65      deraadt   239: /*
                    240:  * Called from the main program after receiving SIGHUP.
                    241:  * Restarts the server.
                    242:  */
1.200     itojun    243: static void
1.165     itojun    244: sighup_restart(void)
1.1       deraadt   245: {
1.64      markus    246:        log("Received SIGHUP; restarting.");
1.75      markus    247:        close_listen_socks();
1.211     markus    248:        close_startup_pipes();
1.64      markus    249:        execv(saved_argv[0], saved_argv);
1.138     markus    250:        log("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0], strerror(errno));
1.64      markus    251:        exit(1);
1.1       deraadt   252: }
                    253:
1.65      deraadt   254: /*
                    255:  * Generic signal handler for terminating signals in the master daemon.
                    256:  */
1.200     itojun    257: static void
1.64      markus    258: sigterm_handler(int sig)
1.1       deraadt   259: {
1.199     markus    260:        received_sigterm = sig;
1.1       deraadt   261: }
                    262:
1.65      deraadt   263: /*
                    264:  * SIGCHLD handler.  This is called whenever a child dies.  This will then
1.199     markus    265:  * reap any zombies left by exited children.
1.65      deraadt   266:  */
1.200     itojun    267: static void
1.64      markus    268: main_sigchld_handler(int sig)
1.1       deraadt   269: {
1.64      markus    270:        int save_errno = errno;
                    271:        int status;
1.60      deraadt   272:
1.64      markus    273:        while (waitpid(-1, &status, WNOHANG) > 0)
                    274:                ;
1.60      deraadt   275:
1.64      markus    276:        signal(SIGCHLD, main_sigchld_handler);
                    277:        errno = save_errno;
1.1       deraadt   278: }
                    279:
1.65      deraadt   280: /*
                    281:  * Signal handler for the alarm after the login grace period has expired.
                    282:  */
1.200     itojun    283: static void
1.64      markus    284: grace_alarm_handler(int sig)
1.1       deraadt   285: {
1.199     markus    286:        /* XXX no idea how fix this signal handler */
                    287:
1.64      markus    288:        /* Close the connection. */
                    289:        packet_close();
                    290:
                    291:        /* Log error and exit. */
                    292:        fatal("Timeout before authentication for %s.", get_remote_ipaddr());
1.62      markus    293: }
                    294:
1.65      deraadt   295: /*
                    296:  * Signal handler for the key regeneration alarm.  Note that this
                    297:  * alarm only occurs in the daemon waiting for connections, and it does not
                    298:  * do anything with the private key or random state before forking.
                    299:  * Thus there should be no concurrency control/asynchronous execution
                    300:  * problems.
                    301:  */
1.200     itojun    302: static void
1.174     deraadt   303: generate_ephemeral_server_key(void)
1.134     markus    304: {
1.169     markus    305:        u_int32_t rand = 0;
                    306:        int i;
                    307:
1.191     markus    308:        verbose("Generating %s%d bit RSA key.",
1.185     djm       309:            sensitive_data.server_key ? "new " : "", options.server_key_bits);
1.134     markus    310:        if (sensitive_data.server_key != NULL)
                    311:                key_free(sensitive_data.server_key);
1.191     markus    312:        sensitive_data.server_key = key_generate(KEY_RSA1,
1.185     djm       313:            options.server_key_bits);
                    314:        verbose("RSA key generation complete.");
1.169     markus    315:
                    316:        for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
                    317:                if (i % 4 == 0)
                    318:                        rand = arc4random();
                    319:                sensitive_data.ssh1_cookie[i] = rand & 0xff;
                    320:                rand >>= 8;
                    321:        }
1.134     markus    322:        arc4random_stir();
                    323: }
1.147     deraadt   324:
1.200     itojun    325: static void
1.64      markus    326: key_regeneration_alarm(int sig)
1.1       deraadt   327: {
1.64      markus    328:        int save_errno = errno;
1.151     markus    329:        signal(SIGALRM, SIG_DFL);
1.64      markus    330:        errno = save_errno;
1.151     markus    331:        key_do_regen = 1;
1.98      markus    332: }
                    333:
1.200     itojun    334: static void
1.96      markus    335: sshd_exchange_identification(int sock_in, int sock_out)
                    336: {
1.102     markus    337:        int i, mismatch;
1.96      markus    338:        int remote_major, remote_minor;
1.102     markus    339:        int major, minor;
1.96      markus    340:        char *s;
                    341:        char buf[256];                  /* Must not be larger than remote_version. */
                    342:        char remote_version[256];       /* Must be at least as big as buf. */
                    343:
1.103     markus    344:        if ((options.protocol & SSH_PROTO_1) &&
                    345:            (options.protocol & SSH_PROTO_2)) {
1.102     markus    346:                major = PROTOCOL_MAJOR_1;
                    347:                minor = 99;
                    348:        } else if (options.protocol & SSH_PROTO_2) {
                    349:                major = PROTOCOL_MAJOR_2;
                    350:                minor = PROTOCOL_MINOR_2;
                    351:        } else {
                    352:                major = PROTOCOL_MAJOR_1;
                    353:                minor = PROTOCOL_MINOR_1;
                    354:        }
                    355:        snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
1.96      markus    356:        server_version_string = xstrdup(buf);
                    357:
                    358:        if (client_version_string == NULL) {
                    359:                /* Send our protocol version identification. */
                    360:                if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
                    361:                    != strlen(server_version_string)) {
1.208     markus    362:                        log("Could not write ident string to %s", get_remote_ipaddr());
1.96      markus    363:                        fatal_cleanup();
                    364:                }
                    365:
1.167     markus    366:                /* Read other side's version identification. */
1.191     markus    367:                memset(buf, 0, sizeof(buf));
1.96      markus    368:                for (i = 0; i < sizeof(buf) - 1; i++) {
1.119     markus    369:                        if (atomicio(read, sock_in, &buf[i], 1) != 1) {
1.208     markus    370:                                log("Did not receive identification string from %s",
1.168     deraadt   371:                                    get_remote_ipaddr());
1.96      markus    372:                                fatal_cleanup();
                    373:                        }
                    374:                        if (buf[i] == '\r') {
1.176     deraadt   375:                                buf[i] = 0;
1.132     markus    376:                                /* Kludge for F-Secure Macintosh < 1.0.2 */
                    377:                                if (i == 12 &&
                    378:                                    strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
                    379:                                        break;
1.96      markus    380:                                continue;
                    381:                        }
                    382:                        if (buf[i] == '\n') {
1.176     deraadt   383:                                buf[i] = 0;
1.96      markus    384:                                break;
                    385:                        }
                    386:                }
                    387:                buf[sizeof(buf) - 1] = 0;
                    388:                client_version_string = xstrdup(buf);
                    389:        }
                    390:
                    391:        /*
                    392:         * Check that the versions match.  In future this might accept
                    393:         * several versions and set appropriate flags to handle them.
                    394:         */
                    395:        if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
                    396:            &remote_major, &remote_minor, remote_version) != 3) {
1.105     markus    397:                s = "Protocol mismatch.\n";
1.96      markus    398:                (void) atomicio(write, sock_out, s, strlen(s));
                    399:                close(sock_in);
                    400:                close(sock_out);
                    401:                log("Bad protocol version identification '%.100s' from %s",
                    402:                    client_version_string, get_remote_ipaddr());
                    403:                fatal_cleanup();
                    404:        }
                    405:        debug("Client protocol version %d.%d; client software version %.100s",
1.217     deraadt   406:            remote_major, remote_minor, remote_version);
1.96      markus    407:
1.98      markus    408:        compat_datafellows(remote_version);
1.175     deraadt   409:
                    410:        if (datafellows & SSH_BUG_SCANNER) {
                    411:                log("scanned from %s with %s.  Don't panic.",
                    412:                    get_remote_ipaddr(), client_version_string);
                    413:                fatal_cleanup();
                    414:        }
1.98      markus    415:
1.102     markus    416:        mismatch = 0;
1.214     deraadt   417:        switch (remote_major) {
1.96      markus    418:        case 1:
1.108     markus    419:                if (remote_minor == 99) {
                    420:                        if (options.protocol & SSH_PROTO_2)
                    421:                                enable_compat20();
                    422:                        else
                    423:                                mismatch = 1;
                    424:                        break;
                    425:                }
1.102     markus    426:                if (!(options.protocol & SSH_PROTO_1)) {
                    427:                        mismatch = 1;
                    428:                        break;
                    429:                }
1.96      markus    430:                if (remote_minor < 3) {
1.121     provos    431:                        packet_disconnect("Your ssh version is too old and "
1.96      markus    432:                            "is no longer supported.  Please install a newer version.");
                    433:                } else if (remote_minor == 3) {
                    434:                        /* note that this disables agent-forwarding */
                    435:                        enable_compat13();
                    436:                }
1.102     markus    437:                break;
1.98      markus    438:        case 2:
1.102     markus    439:                if (options.protocol & SSH_PROTO_2) {
1.98      markus    440:                        enable_compat20();
                    441:                        break;
                    442:                }
1.99      markus    443:                /* FALLTHROUGH */
1.105     markus    444:        default:
1.102     markus    445:                mismatch = 1;
                    446:                break;
                    447:        }
                    448:        chop(server_version_string);
                    449:        debug("Local version string %.200s", server_version_string);
                    450:
                    451:        if (mismatch) {
1.96      markus    452:                s = "Protocol major versions differ.\n";
                    453:                (void) atomicio(write, sock_out, s, strlen(s));
                    454:                close(sock_in);
                    455:                close(sock_out);
1.102     markus    456:                log("Protocol major versions differ for %s: %.200s vs. %.200s",
                    457:                    get_remote_ipaddr(),
                    458:                    server_version_string, client_version_string);
1.96      markus    459:                fatal_cleanup();
                    460:        }
1.108     markus    461: }
                    462:
                    463:
1.134     markus    464: /* Destroy the host and server keys.  They will no longer be needed. */
1.108     markus    465: void
                    466: destroy_sensitive_data(void)
                    467: {
1.134     markus    468:        int i;
                    469:
                    470:        if (sensitive_data.server_key) {
                    471:                key_free(sensitive_data.server_key);
                    472:                sensitive_data.server_key = NULL;
                    473:        }
1.217     deraadt   474:        for (i = 0; i < options.num_host_key_files; i++) {
1.134     markus    475:                if (sensitive_data.host_keys[i]) {
                    476:                        key_free(sensitive_data.host_keys[i]);
                    477:                        sensitive_data.host_keys[i] = NULL;
                    478:                }
                    479:        }
                    480:        sensitive_data.ssh1_host_key = NULL;
1.169     markus    481:        memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
1.134     markus    482: }
                    483:
1.231     provos    484: /* Demote private to public keys for network child */
                    485: void
                    486: demote_sensitive_data(void)
                    487: {
                    488:        Key *tmp;
                    489:        int i;
                    490:
                    491:        if (sensitive_data.server_key) {
                    492:                tmp = key_demote(sensitive_data.server_key);
                    493:                key_free(sensitive_data.server_key);
                    494:                sensitive_data.server_key = tmp;
                    495:        }
                    496:
                    497:        for (i = 0; i < options.num_host_key_files; i++) {
                    498:                if (sensitive_data.host_keys[i]) {
                    499:                        tmp = key_demote(sensitive_data.host_keys[i]);
                    500:                        key_free(sensitive_data.host_keys[i]);
                    501:                        sensitive_data.host_keys[i] = tmp;
                    502:                        if (tmp->type == KEY_RSA1)
                    503:                                sensitive_data.ssh1_host_key = tmp;
                    504:                }
                    505:        }
                    506:
                    507:        /* We do not clear ssh1_host key and cookie.  XXX - Okay Niels? */
                    508: }
                    509:
1.233     markus    510: static void
1.231     provos    511: privsep_preauth_child(void)
                    512: {
                    513:        u_int32_t rand[256];
                    514:        int i;
1.235     stevesk   515:        struct passwd *pw;
1.231     provos    516:
                    517:        /* Enable challenge-response authentication for privilege separation */
                    518:        privsep_challenge_enable();
                    519:
                    520:        for (i = 0; i < 256; i++)
                    521:                rand[i] = arc4random();
                    522:        RAND_seed(rand, sizeof(rand));
                    523:
                    524:        /* Demote the private keys to public keys. */
                    525:        demote_sensitive_data();
                    526:
1.235     stevesk   527:        if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
                    528:                fatal("%s: no user", SSH_PRIVSEP_USER);
                    529:        memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
                    530:        endpwent();
                    531:
1.231     provos    532:        /* Change our root directory*/
1.232     stevesk   533:        if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
                    534:                fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
                    535:                    strerror(errno));
1.231     provos    536:        if (chdir("/") == -1)
1.236   ! stevesk   537:                fatal("chdir(\"/\"): %s", strerror(errno));
1.234     markus    538:
1.231     provos    539:        /* Drop our privileges */
1.235     stevesk   540:        debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
                    541:            (u_int)pw->pw_gid);
                    542:        do_setusercontext(pw);
1.231     provos    543: }
                    544:
1.233     markus    545: static void
1.231     provos    546: privsep_postauth(Authctxt *authctxt, pid_t pid)
                    547: {
                    548:        extern Authctxt *x_authctxt;
                    549:        int status;
                    550:
                    551:        /* Wait for the child's exit status */
                    552:        waitpid(pid, &status, 0);
                    553:
                    554:        /* XXX - Remote port forwarding */
                    555:        x_authctxt = authctxt;
                    556:
                    557:        if (authctxt->pw->pw_uid == 0 || options.use_login) {
                    558:                /* File descriptor passing is broken or root login */
                    559:                monitor_apply_keystate(monitor);
                    560:                use_privsep = 0;
                    561:                return;
                    562:        }
1.234     markus    563:
1.231     provos    564:        /* Authentication complete */
                    565:        alarm(0);
                    566:        if (startup_pipe != -1) {
                    567:                close(startup_pipe);
                    568:                startup_pipe = -1;
                    569:        }
                    570:
                    571:        /* New socket pair */
                    572:        monitor_reinit(monitor);
                    573:
                    574:        monitor->m_pid = fork();
                    575:        if (monitor->m_pid == -1)
                    576:                fatal("fork of unprivileged child failed");
                    577:        else if (monitor->m_pid != 0) {
                    578:                debug2("User child is on pid %d", pid);
                    579:                close(monitor->m_recvfd);
                    580:                monitor_child_postauth(monitor);
                    581:
                    582:                /* NEVERREACHED */
                    583:                exit(0);
                    584:        }
                    585:
                    586:        close(monitor->m_sendfd);
                    587:
                    588:        /* Demote the private keys to public keys. */
                    589:        demote_sensitive_data();
                    590:
                    591:        /* Drop privileges */
                    592:        do_setusercontext(authctxt->pw);
                    593:
                    594:        /* It is safe now to apply the key state */
                    595:        monitor_apply_keystate(monitor);
                    596: }
                    597:
                    598:
1.200     itojun    599: static char *
1.134     markus    600: list_hostkey_types(void)
                    601: {
1.223     markus    602:        Buffer b;
                    603:        char *p;
1.134     markus    604:        int i;
1.223     markus    605:
                    606:        buffer_init(&b);
1.217     deraadt   607:        for (i = 0; i < options.num_host_key_files; i++) {
1.134     markus    608:                Key *key = sensitive_data.host_keys[i];
                    609:                if (key == NULL)
                    610:                        continue;
1.214     deraadt   611:                switch (key->type) {
1.134     markus    612:                case KEY_RSA:
                    613:                case KEY_DSA:
1.223     markus    614:                        if (buffer_len(&b) > 0)
                    615:                                buffer_append(&b, ",", 1);
                    616:                        p = key_ssh_name(key);
                    617:                        buffer_append(&b, p, strlen(p));
1.134     markus    618:                        break;
                    619:                }
                    620:        }
1.223     markus    621:        buffer_append(&b, "\0", 1);
                    622:        p = xstrdup(buffer_ptr(&b));
                    623:        buffer_free(&b);
                    624:        debug("list_hostkey_types: %s", p);
                    625:        return p;
1.134     markus    626: }
                    627:
1.231     provos    628: Key *
1.134     markus    629: get_hostkey_by_type(int type)
                    630: {
                    631:        int i;
1.217     deraadt   632:        for (i = 0; i < options.num_host_key_files; i++) {
1.134     markus    633:                Key *key = sensitive_data.host_keys[i];
                    634:                if (key != NULL && key->type == type)
                    635:                        return key;
                    636:        }
                    637:        return NULL;
1.96      markus    638: }
                    639:
1.231     provos    640: Key *
                    641: get_hostkey_by_index(int ind)
                    642: {
                    643:        if (ind < 0 || ind >= options.num_host_key_files)
                    644:                return (NULL);
                    645:        return (sensitive_data.host_keys[ind]);
                    646: }
                    647:
                    648: int
                    649: get_hostkey_index(Key *key)
                    650: {
                    651:        int i;
                    652:        for (i = 0; i < options.num_host_key_files; i++) {
                    653:                if (key == sensitive_data.host_keys[i])
                    654:                        return (i);
                    655:        }
                    656:        return (-1);
                    657: }
                    658:
1.124     markus    659: /*
                    660:  * returns 1 if connection should be dropped, 0 otherwise.
                    661:  * dropping starts at connection #max_startups_begin with a probability
                    662:  * of (max_startups_rate/100). the probability increases linearly until
                    663:  * all connections are dropped for startups > max_startups
                    664:  */
1.200     itojun    665: static int
1.124     markus    666: drop_connection(int startups)
                    667: {
                    668:        double p, r;
                    669:
                    670:        if (startups < options.max_startups_begin)
                    671:                return 0;
                    672:        if (startups >= options.max_startups)
                    673:                return 1;
                    674:        if (options.max_startups_rate == 100)
                    675:                return 1;
                    676:
                    677:        p  = 100 - options.max_startups_rate;
                    678:        p *= startups - options.max_startups_begin;
                    679:        p /= (double) (options.max_startups - options.max_startups_begin);
                    680:        p += options.max_startups_rate;
                    681:        p /= 100.0;
                    682:        r = arc4random() / (double) UINT_MAX;
                    683:
                    684:        debug("drop_connection: p %g, r %g", p, r);
                    685:        return (r < p) ? 1 : 0;
                    686: }
                    687:
1.215     markus    688: static void
                    689: usage(void)
                    690: {
                    691:        fprintf(stderr, "sshd version %s\n", SSH_VERSION);
                    692:        fprintf(stderr, "Usage: %s [options]\n", __progname);
                    693:        fprintf(stderr, "Options:\n");
                    694:        fprintf(stderr, "  -f file    Configuration file (default %s)\n", _PATH_SERVER_CONFIG_FILE);
                    695:        fprintf(stderr, "  -d         Debugging mode (multiple -d means more debugging)\n");
                    696:        fprintf(stderr, "  -i         Started from inetd\n");
                    697:        fprintf(stderr, "  -D         Do not fork into daemon mode\n");
                    698:        fprintf(stderr, "  -t         Only test configuration file and keys\n");
                    699:        fprintf(stderr, "  -q         Quiet (no logging)\n");
                    700:        fprintf(stderr, "  -p port    Listen on the specified port (default: 22)\n");
                    701:        fprintf(stderr, "  -k seconds Regenerate server key every this many seconds (default: 3600)\n");
                    702:        fprintf(stderr, "  -g seconds Grace period for authentication (default: 600)\n");
                    703:        fprintf(stderr, "  -b bits    Size of server RSA key (default: 768 bits)\n");
                    704:        fprintf(stderr, "  -h file    File from which to read host key (default: %s)\n",
                    705:            _PATH_HOST_KEY_FILE);
                    706:        fprintf(stderr, "  -u len     Maximum hostname length for utmp recording\n");
                    707:        fprintf(stderr, "  -4         Use IPv4 only\n");
                    708:        fprintf(stderr, "  -6         Use IPv6 only\n");
                    709:        fprintf(stderr, "  -o option  Process the option as if it was read from a configuration file.\n");
                    710:        exit(1);
                    711: }
                    712:
1.65      deraadt   713: /*
                    714:  * Main program for the daemon.
                    715:  */
1.2       provos    716: int
                    717: main(int ac, char **av)
1.1       deraadt   718: {
1.64      markus    719:        extern char *optarg;
                    720:        extern int optind;
1.120     markus    721:        int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
1.107     deraadt   722:        pid_t pid;
1.75      markus    723:        socklen_t fromlen;
                    724:        fd_set *fdset;
                    725:        struct sockaddr_storage from;
1.64      markus    726:        const char *remote_ip;
                    727:        int remote_port;
                    728:        FILE *f;
                    729:        struct linger linger;
1.75      markus    730:        struct addrinfo *ai;
                    731:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
                    732:        int listen_sock, maxfd;
1.120     markus    733:        int startup_p[2];
                    734:        int startups = 0;
1.230     provos    735:        Authctxt *authctxt;
1.179     markus    736:        Key *key;
1.151     markus    737:        int ret, key_used = 0;
1.64      markus    738:
1.138     markus    739:        /* Save argv. */
1.64      markus    740:        saved_argv = av;
                    741:
                    742:        /* Initialize configuration options to their default values. */
                    743:        initialize_server_options(&options);
                    744:
                    745:        /* Parse command-line arguments. */
1.215     markus    746:        while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:o:dDeiqtQ46")) != -1) {
1.64      markus    747:                switch (opt) {
1.75      markus    748:                case '4':
                    749:                        IPv4or6 = AF_INET;
                    750:                        break;
                    751:                case '6':
                    752:                        IPv4or6 = AF_INET6;
                    753:                        break;
1.64      markus    754:                case 'f':
                    755:                        config_file_name = optarg;
                    756:                        break;
                    757:                case 'd':
1.127     markus    758:                        if (0 == debug_flag) {
                    759:                                debug_flag = 1;
                    760:                                options.log_level = SYSLOG_LEVEL_DEBUG1;
                    761:                        } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
                    762:                                options.log_level++;
                    763:                        } else {
                    764:                                fprintf(stderr, "Too high debugging level.\n");
                    765:                                exit(1);
                    766:                        }
1.64      markus    767:                        break;
1.135     markus    768:                case 'D':
                    769:                        no_daemon_flag = 1;
1.192     lebel     770:                        break;
                    771:                case 'e':
                    772:                        log_stderr = 1;
1.135     markus    773:                        break;
1.64      markus    774:                case 'i':
                    775:                        inetd_flag = 1;
                    776:                        break;
                    777:                case 'Q':
1.158     markus    778:                        /* ignored */
1.64      markus    779:                        break;
                    780:                case 'q':
                    781:                        options.log_level = SYSLOG_LEVEL_QUIET;
                    782:                        break;
                    783:                case 'b':
                    784:                        options.server_key_bits = atoi(optarg);
                    785:                        break;
                    786:                case 'p':
1.75      markus    787:                        options.ports_from_cmdline = 1;
1.127     markus    788:                        if (options.num_ports >= MAX_PORTS) {
                    789:                                fprintf(stderr, "too many ports.\n");
                    790:                                exit(1);
                    791:                        }
1.193     stevesk   792:                        options.ports[options.num_ports++] = a2port(optarg);
                    793:                        if (options.ports[options.num_ports-1] == 0) {
                    794:                                fprintf(stderr, "Bad port number.\n");
                    795:                                exit(1);
                    796:                        }
1.64      markus    797:                        break;
                    798:                case 'g':
1.197     stevesk   799:                        if ((options.login_grace_time = convtime(optarg)) == -1) {
                    800:                                fprintf(stderr, "Invalid login grace time.\n");
                    801:                                exit(1);
                    802:                        }
1.64      markus    803:                        break;
                    804:                case 'k':
1.197     stevesk   805:                        if ((options.key_regeneration_time = convtime(optarg)) == -1) {
                    806:                                fprintf(stderr, "Invalid key regeneration interval.\n");
                    807:                                exit(1);
                    808:                        }
1.64      markus    809:                        break;
                    810:                case 'h':
1.134     markus    811:                        if (options.num_host_key_files >= MAX_HOSTKEYS) {
                    812:                                fprintf(stderr, "too many host keys.\n");
                    813:                                exit(1);
                    814:                        }
                    815:                        options.host_key_files[options.num_host_key_files++] = optarg;
1.64      markus    816:                        break;
                    817:                case 'V':
                    818:                        client_version_string = optarg;
                    819:                        /* only makes sense with inetd_flag, i.e. no listen() */
                    820:                        inetd_flag = 1;
                    821:                        break;
1.203     stevesk   822:                case 't':
                    823:                        test_flag = 1;
                    824:                        break;
1.125     markus    825:                case 'u':
                    826:                        utmp_len = atoi(optarg);
                    827:                        break;
1.215     markus    828:                case 'o':
1.217     deraadt   829:                        if (process_server_config_line(&options, optarg,
1.215     markus    830:                            "command-line", 0) != 0)
1.217     deraadt   831:                                exit(1);
1.215     markus    832:                        break;
1.64      markus    833:                case '?':
                    834:                default:
1.215     markus    835:                        usage();
                    836:                        break;
1.64      markus    837:                }
                    838:        }
1.180     markus    839:        SSLeay_add_all_algorithms();
1.205     markus    840:        channel_set_af(IPv4or6);
1.64      markus    841:
1.75      markus    842:        /*
                    843:         * Force logging to stderr until we have loaded the private host
                    844:         * key (unless started from inetd)
                    845:         */
1.138     markus    846:        log_init(__progname,
1.224     markus    847:            options.log_level == SYSLOG_LEVEL_NOT_SET ?
                    848:            SYSLOG_LEVEL_INFO : options.log_level,
                    849:            options.log_facility == SYSLOG_FACILITY_NOT_SET ?
                    850:            SYSLOG_FACILITY_AUTH : options.log_facility,
1.158     markus    851:            !inetd_flag);
1.75      markus    852:
1.64      markus    853:        /* Read server configuration options from the configuration file. */
                    854:        read_server_config(&options, config_file_name);
                    855:
                    856:        /* Fill in default values for those options not explicitly set. */
                    857:        fill_default_server_options(&options);
                    858:
                    859:        /* Check that there are no remaining arguments. */
                    860:        if (optind < ac) {
                    861:                fprintf(stderr, "Extra argument %s.\n", av[optind]);
                    862:                exit(1);
                    863:        }
                    864:
                    865:        debug("sshd version %.100s", SSH_VERSION);
                    866:
1.134     markus    867:        /* load private host keys */
                    868:        sensitive_data.host_keys = xmalloc(options.num_host_key_files*sizeof(Key*));
1.217     deraadt   869:        for (i = 0; i < options.num_host_key_files; i++)
1.141     markus    870:                sensitive_data.host_keys[i] = NULL;
1.134     markus    871:        sensitive_data.server_key = NULL;
                    872:        sensitive_data.ssh1_host_key = NULL;
                    873:        sensitive_data.have_ssh1_key = 0;
                    874:        sensitive_data.have_ssh2_key = 0;
                    875:
1.217     deraadt   876:        for (i = 0; i < options.num_host_key_files; i++) {
1.179     markus    877:                key = key_load_private(options.host_key_files[i], "", NULL);
                    878:                sensitive_data.host_keys[i] = key;
1.134     markus    879:                if (key == NULL) {
1.195     markus    880:                        error("Could not load host key: %s",
                    881:                            options.host_key_files[i]);
1.179     markus    882:                        sensitive_data.host_keys[i] = NULL;
1.134     markus    883:                        continue;
                    884:                }
1.214     deraadt   885:                switch (key->type) {
1.134     markus    886:                case KEY_RSA1:
                    887:                        sensitive_data.ssh1_host_key = key;
                    888:                        sensitive_data.have_ssh1_key = 1;
                    889:                        break;
                    890:                case KEY_RSA:
                    891:                case KEY_DSA:
                    892:                        sensitive_data.have_ssh2_key = 1;
                    893:                        break;
                    894:                }
1.179     markus    895:                debug("private host key: #%d type %d %s", i, key->type,
                    896:                    key_type(key));
1.134     markus    897:        }
                    898:        if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
                    899:                log("Disabling protocol version 1. Could not load host key");
1.108     markus    900:                options.protocol &= ~SSH_PROTO_1;
                    901:        }
1.134     markus    902:        if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
                    903:                log("Disabling protocol version 2. Could not load host key");
                    904:                options.protocol &= ~SSH_PROTO_2;
1.108     markus    905:        }
1.162     stevesk   906:        if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1.172     millert   907:                log("sshd: no hostkeys available -- exiting.");
1.64      markus    908:                exit(1);
                    909:        }
                    910:
1.108     markus    911:        /* Check certain values for sanity. */
                    912:        if (options.protocol & SSH_PROTO_1) {
                    913:                if (options.server_key_bits < 512 ||
                    914:                    options.server_key_bits > 32768) {
                    915:                        fprintf(stderr, "Bad server key size.\n");
                    916:                        exit(1);
                    917:                }
                    918:                /*
                    919:                 * Check that server and host key lengths differ sufficiently. This
                    920:                 * is necessary to make double encryption work with rsaref. Oh, I
                    921:                 * hate software patents. I dont know if this can go? Niels
                    922:                 */
                    923:                if (options.server_key_bits >
1.134     markus    924:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) - SSH_KEY_BITS_RESERVED &&
1.108     markus    925:                    options.server_key_bits <
1.134     markus    926:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1.108     markus    927:                        options.server_key_bits =
1.134     markus    928:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED;
1.108     markus    929:                        debug("Forcing server key to %d bits to make it differ from host key.",
                    930:                            options.server_key_bits);
                    931:                }
                    932:        }
1.203     stevesk   933:
                    934:        /* Configuration looks good, so exit if in test mode. */
                    935:        if (test_flag)
                    936:                exit(0);
1.108     markus    937:
                    938:        /* Initialize the log (it is reinitialized below in case we forked). */
1.64      markus    939:        if (debug_flag && !inetd_flag)
                    940:                log_stderr = 1;
1.138     markus    941:        log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64      markus    942:
1.108     markus    943:        /*
                    944:         * If not in debugging mode, and not started from inetd, disconnect
                    945:         * from the controlling terminal, and fork.  The original process
                    946:         * exits.
                    947:         */
1.135     markus    948:        if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1.1       deraadt   949: #ifdef TIOCNOTTY
1.64      markus    950:                int fd;
1.1       deraadt   951: #endif /* TIOCNOTTY */
1.64      markus    952:                if (daemon(0, 0) < 0)
                    953:                        fatal("daemon() failed: %.200s", strerror(errno));
                    954:
                    955:                /* Disconnect from the controlling tty. */
1.1       deraadt   956: #ifdef TIOCNOTTY
1.165     itojun    957:                fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1.64      markus    958:                if (fd >= 0) {
                    959:                        (void) ioctl(fd, TIOCNOTTY, NULL);
                    960:                        close(fd);
                    961:                }
                    962: #endif /* TIOCNOTTY */
                    963:        }
                    964:        /* Reinitialize the log (because of the fork above). */
1.138     markus    965:        log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64      markus    966:
                    967:        /* Initialize the random number generator. */
                    968:        arc4random_stir();
                    969:
                    970:        /* Chdir to the root directory so that the current disk can be
                    971:           unmounted if desired. */
                    972:        chdir("/");
1.217     deraadt   973:
1.178     markus    974:        /* ignore SIGPIPE */
                    975:        signal(SIGPIPE, SIG_IGN);
1.64      markus    976:
                    977:        /* Start listening for a socket, unless started from inetd. */
                    978:        if (inetd_flag) {
1.194     markus    979:                int s1;
1.64      markus    980:                s1 = dup(0);    /* Make sure descriptors 0, 1, and 2 are in use. */
1.194     markus    981:                dup(s1);
1.64      markus    982:                sock_in = dup(0);
                    983:                sock_out = dup(1);
1.123     djm       984:                startup_pipe = -1;
1.108     markus    985:                /*
                    986:                 * We intentionally do not close the descriptors 0, 1, and 2
                    987:                 * as our code for setting the descriptors won\'t work if
                    988:                 * ttyfd happens to be one of those.
                    989:                 */
1.64      markus    990:                debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
1.134     markus    991:                if (options.protocol & SSH_PROTO_1)
1.174     deraadt   992:                        generate_ephemeral_server_key();
1.64      markus    993:        } else {
1.75      markus    994:                for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
                    995:                        if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                    996:                                continue;
                    997:                        if (num_listen_socks >= MAX_LISTEN_SOCKS)
                    998:                                fatal("Too many listen sockets. "
                    999:                                    "Enlarge MAX_LISTEN_SOCKS");
                   1000:                        if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
                   1001:                            ntop, sizeof(ntop), strport, sizeof(strport),
                   1002:                            NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
                   1003:                                error("getnameinfo failed");
                   1004:                                continue;
                   1005:                        }
                   1006:                        /* Create socket for listening. */
                   1007:                        listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
                   1008:                        if (listen_sock < 0) {
                   1009:                                /* kernel may not support ipv6 */
                   1010:                                verbose("socket: %.100s", strerror(errno));
                   1011:                                continue;
                   1012:                        }
                   1013:                        if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
                   1014:                                error("listen_sock O_NONBLOCK: %s", strerror(errno));
                   1015:                                close(listen_sock);
                   1016:                                continue;
                   1017:                        }
                   1018:                        /*
                   1019:                         * Set socket options.  We try to make the port
                   1020:                         * reusable and have it close as fast as possible
                   1021:                         * without waiting in unnecessary wait states on
                   1022:                         * close.
                   1023:                         */
                   1024:                        setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1.228     stevesk  1025:                            &on, sizeof(on));
1.75      markus   1026:                        linger.l_onoff = 1;
                   1027:                        linger.l_linger = 5;
                   1028:                        setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
1.228     stevesk  1029:                            &linger, sizeof(linger));
1.75      markus   1030:
                   1031:                        debug("Bind to port %s on %s.", strport, ntop);
                   1032:
                   1033:                        /* Bind the socket to the desired port. */
                   1034:                        if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   1035:                                error("Bind to port %s on %s failed: %.200s.",
                   1036:                                    strport, ntop, strerror(errno));
                   1037:                                close(listen_sock);
                   1038:                                continue;
                   1039:                        }
                   1040:                        listen_socks[num_listen_socks] = listen_sock;
                   1041:                        num_listen_socks++;
                   1042:
                   1043:                        /* Start listening on the port. */
                   1044:                        log("Server listening on %s port %s.", ntop, strport);
                   1045:                        if (listen(listen_sock, 5) < 0)
                   1046:                                fatal("listen: %.100s", strerror(errno));
                   1047:
1.64      markus   1048:                }
1.75      markus   1049:                freeaddrinfo(options.listen_addrs);
                   1050:
                   1051:                if (!num_listen_socks)
                   1052:                        fatal("Cannot bind any address.");
                   1053:
1.201     markus   1054:                if (options.protocol & SSH_PROTO_1)
                   1055:                        generate_ephemeral_server_key();
                   1056:
                   1057:                /*
                   1058:                 * Arrange to restart on SIGHUP.  The handler needs
                   1059:                 * listen_sock.
                   1060:                 */
                   1061:                signal(SIGHUP, sighup_handler);
                   1062:
                   1063:                signal(SIGTERM, sigterm_handler);
                   1064:                signal(SIGQUIT, sigterm_handler);
                   1065:
                   1066:                /* Arrange SIGCHLD to be caught. */
                   1067:                signal(SIGCHLD, main_sigchld_handler);
                   1068:
                   1069:                /* Write out the pid file after the sigterm handler is setup */
1.64      markus   1070:                if (!debug_flag) {
1.66      markus   1071:                        /*
1.136     todd     1072:                         * Record our pid in /var/run/sshd.pid to make it
                   1073:                         * easier to kill the correct sshd.  We don't want to
                   1074:                         * do this before the bind above because the bind will
1.66      markus   1075:                         * fail if there already is a daemon, and this will
                   1076:                         * overwrite any old pid in the file.
                   1077:                         */
1.112     markus   1078:                        f = fopen(options.pid_file, "w");
1.64      markus   1079:                        if (f) {
1.140     markus   1080:                                fprintf(f, "%u\n", (u_int) getpid());
1.64      markus   1081:                                fclose(f);
                   1082:                        }
                   1083:                }
                   1084:
1.75      markus   1085:                /* setup fd set for listen */
1.120     markus   1086:                fdset = NULL;
1.75      markus   1087:                maxfd = 0;
                   1088:                for (i = 0; i < num_listen_socks; i++)
                   1089:                        if (listen_socks[i] > maxfd)
                   1090:                                maxfd = listen_socks[i];
1.120     markus   1091:                /* pipes connected to unauthenticated childs */
                   1092:                startup_pipes = xmalloc(options.max_startups * sizeof(int));
                   1093:                for (i = 0; i < options.max_startups; i++)
                   1094:                        startup_pipes[i] = -1;
1.75      markus   1095:
1.66      markus   1096:                /*
                   1097:                 * Stay listening for connections until the system crashes or
                   1098:                 * the daemon is killed with a signal.
                   1099:                 */
1.64      markus   1100:                for (;;) {
                   1101:                        if (received_sighup)
                   1102:                                sighup_restart();
1.120     markus   1103:                        if (fdset != NULL)
                   1104:                                xfree(fdset);
1.148     markus   1105:                        fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
1.120     markus   1106:                        fdset = (fd_set *)xmalloc(fdsetsz);
1.75      markus   1107:                        memset(fdset, 0, fdsetsz);
1.120     markus   1108:
1.75      markus   1109:                        for (i = 0; i < num_listen_socks; i++)
                   1110:                                FD_SET(listen_socks[i], fdset);
1.120     markus   1111:                        for (i = 0; i < options.max_startups; i++)
                   1112:                                if (startup_pipes[i] != -1)
                   1113:                                        FD_SET(startup_pipes[i], fdset);
                   1114:
                   1115:                        /* Wait in select until there is a connection. */
1.151     markus   1116:                        ret = select(maxfd+1, fdset, NULL, NULL, NULL);
                   1117:                        if (ret < 0 && errno != EINTR)
                   1118:                                error("select: %.100s", strerror(errno));
1.199     markus   1119:                        if (received_sigterm) {
                   1120:                                log("Received signal %d; terminating.",
1.213     itojun   1121:                                    (int) received_sigterm);
1.199     markus   1122:                                close_listen_socks();
                   1123:                                unlink(options.pid_file);
                   1124:                                exit(255);
                   1125:                        }
1.151     markus   1126:                        if (key_used && key_do_regen) {
1.174     deraadt  1127:                                generate_ephemeral_server_key();
1.151     markus   1128:                                key_used = 0;
                   1129:                                key_do_regen = 0;
                   1130:                        }
                   1131:                        if (ret < 0)
1.75      markus   1132:                                continue;
1.151     markus   1133:
1.120     markus   1134:                        for (i = 0; i < options.max_startups; i++)
                   1135:                                if (startup_pipes[i] != -1 &&
                   1136:                                    FD_ISSET(startup_pipes[i], fdset)) {
                   1137:                                        /*
                   1138:                                         * the read end of the pipe is ready
                   1139:                                         * if the child has closed the pipe
1.143     markus   1140:                                         * after successful authentication
1.120     markus   1141:                                         * or if the child has died
                   1142:                                         */
                   1143:                                        close(startup_pipes[i]);
                   1144:                                        startup_pipes[i] = -1;
                   1145:                                        startups--;
                   1146:                                }
1.75      markus   1147:                        for (i = 0; i < num_listen_socks; i++) {
                   1148:                                if (!FD_ISSET(listen_socks[i], fdset))
1.70      provos   1149:                                        continue;
1.120     markus   1150:                                fromlen = sizeof(from);
                   1151:                                newsock = accept(listen_socks[i], (struct sockaddr *)&from,
                   1152:                                    &fromlen);
                   1153:                                if (newsock < 0) {
                   1154:                                        if (errno != EINTR && errno != EWOULDBLOCK)
                   1155:                                                error("accept: %.100s", strerror(errno));
                   1156:                                        continue;
                   1157:                                }
                   1158:                                if (fcntl(newsock, F_SETFL, 0) < 0) {
                   1159:                                        error("newsock del O_NONBLOCK: %s", strerror(errno));
1.216     stevesk  1160:                                        close(newsock);
1.120     markus   1161:                                        continue;
                   1162:                                }
1.124     markus   1163:                                if (drop_connection(startups) == 1) {
                   1164:                                        debug("drop connection #%d", startups);
1.120     markus   1165:                                        close(newsock);
                   1166:                                        continue;
                   1167:                                }
                   1168:                                if (pipe(startup_p) == -1) {
                   1169:                                        close(newsock);
                   1170:                                        continue;
                   1171:                                }
                   1172:
                   1173:                                for (j = 0; j < options.max_startups; j++)
                   1174:                                        if (startup_pipes[j] == -1) {
                   1175:                                                startup_pipes[j] = startup_p[0];
                   1176:                                                if (maxfd < startup_p[0])
                   1177:                                                        maxfd = startup_p[0];
                   1178:                                                startups++;
                   1179:                                                break;
                   1180:                                        }
1.161     stevesk  1181:
1.66      markus   1182:                                /*
1.120     markus   1183:                                 * Got connection.  Fork a child to handle it, unless
                   1184:                                 * we are in debugging mode.
1.66      markus   1185:                                 */
1.120     markus   1186:                                if (debug_flag) {
1.66      markus   1187:                                        /*
1.120     markus   1188:                                         * In debugging mode.  Close the listening
                   1189:                                         * socket, and start processing the
                   1190:                                         * connection without forking.
1.66      markus   1191:                                         */
1.120     markus   1192:                                        debug("Server will not fork when running in debugging mode.");
1.75      markus   1193:                                        close_listen_socks();
1.64      markus   1194:                                        sock_in = newsock;
                   1195:                                        sock_out = newsock;
1.122     deraadt  1196:                                        startup_pipe = -1;
1.120     markus   1197:                                        pid = getpid();
1.64      markus   1198:                                        break;
1.120     markus   1199:                                } else {
                   1200:                                        /*
                   1201:                                         * Normal production daemon.  Fork, and have
                   1202:                                         * the child process the connection. The
                   1203:                                         * parent continues listening.
                   1204:                                         */
                   1205:                                        if ((pid = fork()) == 0) {
                   1206:                                                /*
                   1207:                                                 * Child.  Close the listening and max_startup
                   1208:                                                 * sockets.  Start using the accepted socket.
                   1209:                                                 * Reinitialize logging (since our pid has
                   1210:                                                 * changed).  We break out of the loop to handle
                   1211:                                                 * the connection.
                   1212:                                                 */
                   1213:                                                startup_pipe = startup_p[1];
1.211     markus   1214:                                                close_startup_pipes();
1.120     markus   1215:                                                close_listen_socks();
                   1216:                                                sock_in = newsock;
                   1217:                                                sock_out = newsock;
1.138     markus   1218:                                                log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.120     markus   1219:                                                break;
                   1220:                                        }
1.64      markus   1221:                                }
                   1222:
1.120     markus   1223:                                /* Parent.  Stay in the loop. */
                   1224:                                if (pid < 0)
                   1225:                                        error("fork: %.100s", strerror(errno));
                   1226:                                else
                   1227:                                        debug("Forked child %d.", pid);
                   1228:
                   1229:                                close(startup_p[1]);
1.1       deraadt  1230:
1.120     markus   1231:                                /* Mark that the key has been used (it was "given" to the child). */
1.151     markus   1232:                                if ((options.protocol & SSH_PROTO_1) &&
                   1233:                                    key_used == 0) {
                   1234:                                        /* Schedule server key regeneration alarm. */
                   1235:                                        signal(SIGALRM, key_regeneration_alarm);
                   1236:                                        alarm(options.key_regeneration_time);
                   1237:                                        key_used = 1;
                   1238:                                }
1.1       deraadt  1239:
1.120     markus   1240:                                arc4random_stir();
1.1       deraadt  1241:
1.120     markus   1242:                                /* Close the new socket (the child is now taking care of it). */
                   1243:                                close(newsock);
                   1244:                        }
1.75      markus   1245:                        /* child process check (or debug mode) */
                   1246:                        if (num_listen_socks < 0)
                   1247:                                break;
1.64      markus   1248:                }
1.1       deraadt  1249:        }
                   1250:
1.64      markus   1251:        /* This is the child processing a new connection. */
                   1252:
1.66      markus   1253:        /*
                   1254:         * Disable the key regeneration alarm.  We will not regenerate the
                   1255:         * key since we are no longer in a position to give it to anyone. We
                   1256:         * will not restart on SIGHUP since it no longer makes sense.
                   1257:         */
1.64      markus   1258:        alarm(0);
                   1259:        signal(SIGALRM, SIG_DFL);
                   1260:        signal(SIGHUP, SIG_DFL);
                   1261:        signal(SIGTERM, SIG_DFL);
                   1262:        signal(SIGQUIT, SIG_DFL);
                   1263:        signal(SIGCHLD, SIG_DFL);
                   1264:
1.66      markus   1265:        /*
                   1266:         * Set socket options for the connection.  We want the socket to
                   1267:         * close as fast as possible without waiting for anything.  If the
                   1268:         * connection is not a socket, these will do nothing.
                   1269:         */
                   1270:        /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1.64      markus   1271:        linger.l_onoff = 1;
                   1272:        linger.l_linger = 5;
1.228     stevesk  1273:        setsockopt(sock_in, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
1.150     markus   1274:
                   1275:        /* Set keepalives if requested. */
                   1276:        if (options.keepalives &&
1.228     stevesk  1277:            setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on,
1.150     markus   1278:            sizeof(on)) < 0)
                   1279:                error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1.64      markus   1280:
1.66      markus   1281:        /*
                   1282:         * Register our connection.  This turns encryption off because we do
                   1283:         * not have a key.
                   1284:         */
1.64      markus   1285:        packet_set_connection(sock_in, sock_out);
1.1       deraadt  1286:
1.64      markus   1287:        remote_port = get_remote_port();
                   1288:        remote_ip = get_remote_ipaddr();
1.52      markus   1289:
1.209     markus   1290: #ifdef LIBWRAP
1.64      markus   1291:        /* Check whether logins are denied from this host. */
                   1292:        {
                   1293:                struct request_info req;
1.37      dugsong  1294:
1.204     camield  1295:                request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1.64      markus   1296:                fromhost(&req);
1.37      dugsong  1297:
1.64      markus   1298:                if (!hosts_access(&req)) {
1.209     markus   1299:                        debug("Connection refused by tcp wrapper");
1.182     markus   1300:                        refuse(&req);
1.209     markus   1301:                        /* NOTREACHED */
                   1302:                        fatal("libwrap refuse returns");
1.64      markus   1303:                }
                   1304:        }
1.75      markus   1305: #endif /* LIBWRAP */
1.209     markus   1306:
1.64      markus   1307:        /* Log the connection. */
                   1308:        verbose("Connection from %.500s port %d", remote_ip, remote_port);
1.1       deraadt  1309:
1.66      markus   1310:        /*
                   1311:         * We don\'t want to listen forever unless the other side
                   1312:         * successfully authenticates itself.  So we set up an alarm which is
                   1313:         * cleared after successful authentication.  A limit of zero
                   1314:         * indicates no limit. Note that we don\'t set the alarm in debugging
                   1315:         * mode; it is just annoying to have the server exit just when you
                   1316:         * are about to discover the bug.
                   1317:         */
1.64      markus   1318:        signal(SIGALRM, grace_alarm_handler);
                   1319:        if (!debug_flag)
                   1320:                alarm(options.login_grace_time);
                   1321:
1.96      markus   1322:        sshd_exchange_identification(sock_in, sock_out);
1.66      markus   1323:        /*
1.137     markus   1324:         * Check that the connection comes from a privileged port.
                   1325:         * Rhosts-Authentication only makes sense from priviledged
1.66      markus   1326:         * programs.  Of course, if the intruder has root access on his local
                   1327:         * machine, he can connect from any port.  So do not use these
                   1328:         * authentication methods from machines that you do not trust.
                   1329:         */
1.225     markus   1330:        if (options.rhosts_authentication &&
                   1331:            (remote_port >= IPPORT_RESERVED ||
                   1332:            remote_port < IPPORT_RESERVED / 2)) {
1.137     markus   1333:                debug("Rhosts Authentication disabled, "
1.207     markus   1334:                    "originating port %d not trusted.", remote_port);
1.64      markus   1335:                options.rhosts_authentication = 0;
                   1336:        }
1.202     dugsong  1337: #if defined(KRB4) && !defined(KRB5)
1.76      markus   1338:        if (!packet_connection_is_ipv4() &&
                   1339:            options.kerberos_authentication) {
                   1340:                debug("Kerberos Authentication disabled, only available for IPv4.");
                   1341:                options.kerberos_authentication = 0;
                   1342:        }
1.202     dugsong  1343: #endif /* KRB4 && !KRB5 */
1.164     markus   1344: #ifdef AFS
                   1345:        /* If machine has AFS, set process authentication group. */
                   1346:        if (k_hasafs()) {
                   1347:                k_setpag();
                   1348:                k_unlog();
                   1349:        }
                   1350: #endif /* AFS */
1.76      markus   1351:
1.64      markus   1352:        packet_set_nonblocking();
1.1       deraadt  1353:
1.231     provos   1354:        if (!use_privsep)
                   1355:                goto skip_privilegeseparation;
1.234     markus   1356:
1.231     provos   1357:        /* Set up unprivileged child process to deal with network data */
                   1358:        monitor = monitor_init();
                   1359:        /* Store a pointer to the kex for later rekeying */
                   1360:        monitor->m_pkex = &xxx_kex;
                   1361:
                   1362:        pid = fork();
                   1363:        if (pid == -1)
                   1364:                fatal("fork of unprivileged child failed");
                   1365:        else if (pid != 0) {
                   1366:                debug2("Network child is on pid %d", pid);
                   1367:
                   1368:                close(monitor->m_recvfd);
                   1369:                authctxt = monitor_child_preauth(monitor);
                   1370:                close(monitor->m_sendfd);
                   1371:
                   1372:                /* Sync memory */
                   1373:                monitor_sync(monitor);
                   1374:                goto authenticated;
                   1375:        } else {
                   1376:                close(monitor->m_sendfd);
                   1377:
                   1378:                /* Demote the child */
                   1379:                if (getuid() == 0 || geteuid() == 0)
                   1380:                        privsep_preauth_child();
                   1381:        }
                   1382:
                   1383:  skip_privilegeseparation:
                   1384:
1.77      markus   1385:        /* perform the key exchange */
                   1386:        /* authenticate user and start session */
1.98      markus   1387:        if (compat20) {
                   1388:                do_ssh2_kex();
1.230     provos   1389:                authctxt = do_authentication2();
1.98      markus   1390:        } else {
                   1391:                do_ssh1_kex();
1.230     provos   1392:                authctxt = do_authentication();
1.98      markus   1393:        }
1.231     provos   1394:        if (use_privsep)
                   1395:                mm_send_keystate(monitor);
                   1396:
                   1397:        /* If we use privilege separation, the unprivileged child exits */
                   1398:        if (use_privsep)
                   1399:                exit(0);
                   1400:
                   1401:  authenticated:
1.234     markus   1402:        /*
1.231     provos   1403:         * In privilege separation, we fork another child and prepare
                   1404:         * file descriptor passing.
                   1405:         */
                   1406:        if (use_privsep) {
                   1407:                privsep_postauth(authctxt, pid);
                   1408:                if (!compat20)
                   1409:                        destroy_sensitive_data();
                   1410:        }
1.230     provos   1411:
                   1412:        /* Perform session preparation. */
                   1413:        do_authenticated(authctxt);
                   1414:
1.64      markus   1415:        /* The connection has been terminated. */
                   1416:        verbose("Closing connection to %.100s", remote_ip);
                   1417:        packet_close();
1.231     provos   1418:
                   1419:        if (use_privsep)
                   1420:                mm_terminate();
                   1421:
1.64      markus   1422:        exit(0);
1.1       deraadt  1423: }
                   1424:
1.65      deraadt  1425: /*
1.229     markus   1426:  * Decrypt session_key_int using our private server key and private host key
                   1427:  * (key with larger modulus first).
                   1428:  */
1.231     provos   1429: int
1.229     markus   1430: ssh1_session_key(BIGNUM *session_key_int)
                   1431: {
                   1432:        int rsafail = 0;
                   1433:
                   1434:        if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
                   1435:                /* Server key has bigger modulus. */
                   1436:                if (BN_num_bits(sensitive_data.server_key->rsa->n) <
                   1437:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
                   1438:                        fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
                   1439:                            get_remote_ipaddr(),
                   1440:                            BN_num_bits(sensitive_data.server_key->rsa->n),
                   1441:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
                   1442:                            SSH_KEY_BITS_RESERVED);
                   1443:                }
                   1444:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   1445:                    sensitive_data.server_key->rsa) <= 0)
                   1446:                        rsafail++;
                   1447:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   1448:                    sensitive_data.ssh1_host_key->rsa) <= 0)
                   1449:                        rsafail++;
                   1450:        } else {
                   1451:                /* Host key has bigger modulus (or they are equal). */
                   1452:                if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
                   1453:                    BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
                   1454:                        fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
                   1455:                            get_remote_ipaddr(),
                   1456:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
                   1457:                            BN_num_bits(sensitive_data.server_key->rsa->n),
                   1458:                            SSH_KEY_BITS_RESERVED);
                   1459:                }
                   1460:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   1461:                    sensitive_data.ssh1_host_key->rsa) < 0)
                   1462:                        rsafail++;
                   1463:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   1464:                    sensitive_data.server_key->rsa) < 0)
                   1465:                        rsafail++;
                   1466:        }
                   1467:        return (rsafail);
                   1468: }
                   1469: /*
1.77      markus   1470:  * SSH1 key exchange
1.65      deraadt  1471:  */
1.200     itojun   1472: static void
1.142     markus   1473: do_ssh1_kex(void)
1.1       deraadt  1474: {
1.64      markus   1475:        int i, len;
1.159     markus   1476:        int rsafail = 0;
1.64      markus   1477:        BIGNUM *session_key_int;
1.140     markus   1478:        u_char session_key[SSH_SESSION_KEY_LENGTH];
                   1479:        u_char cookie[8];
                   1480:        u_int cipher_type, auth_mask, protocol_flags;
1.64      markus   1481:        u_int32_t rand = 0;
                   1482:
1.66      markus   1483:        /*
                   1484:         * Generate check bytes that the client must send back in the user
                   1485:         * packet in order for it to be accepted; this is used to defy ip
                   1486:         * spoofing attacks.  Note that this only works against somebody
                   1487:         * doing IP spoofing from a remote machine; any machine on the local
                   1488:         * network can still see outgoing packets and catch the random
                   1489:         * cookie.  This only affects rhosts authentication, and this is one
                   1490:         * of the reasons why it is inherently insecure.
                   1491:         */
1.64      markus   1492:        for (i = 0; i < 8; i++) {
                   1493:                if (i % 4 == 0)
                   1494:                        rand = arc4random();
1.77      markus   1495:                cookie[i] = rand & 0xff;
1.64      markus   1496:                rand >>= 8;
                   1497:        }
                   1498:
1.66      markus   1499:        /*
                   1500:         * Send our public key.  We include in the packet 64 bits of random
                   1501:         * data that must be matched in the reply in order to prevent IP
                   1502:         * spoofing.
                   1503:         */
1.64      markus   1504:        packet_start(SSH_SMSG_PUBLIC_KEY);
                   1505:        for (i = 0; i < 8; i++)
1.77      markus   1506:                packet_put_char(cookie[i]);
1.64      markus   1507:
                   1508:        /* Store our public server RSA key. */
1.134     markus   1509:        packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
                   1510:        packet_put_bignum(sensitive_data.server_key->rsa->e);
                   1511:        packet_put_bignum(sensitive_data.server_key->rsa->n);
1.64      markus   1512:
                   1513:        /* Store our public host RSA key. */
1.134     markus   1514:        packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
                   1515:        packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
                   1516:        packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1.64      markus   1517:
                   1518:        /* Put protocol flags. */
                   1519:        packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
                   1520:
                   1521:        /* Declare which ciphers we support. */
1.131     markus   1522:        packet_put_int(cipher_mask_ssh1(0));
1.64      markus   1523:
                   1524:        /* Declare supported authentication types. */
                   1525:        auth_mask = 0;
                   1526:        if (options.rhosts_authentication)
                   1527:                auth_mask |= 1 << SSH_AUTH_RHOSTS;
                   1528:        if (options.rhosts_rsa_authentication)
                   1529:                auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
                   1530:        if (options.rsa_authentication)
                   1531:                auth_mask |= 1 << SSH_AUTH_RSA;
1.202     dugsong  1532: #if defined(KRB4) || defined(KRB5)
1.64      markus   1533:        if (options.kerberos_authentication)
                   1534:                auth_mask |= 1 << SSH_AUTH_KERBEROS;
1.1       deraadt  1535: #endif
1.202     dugsong  1536: #if defined(AFS) || defined(KRB5)
1.64      markus   1537:        if (options.kerberos_tgt_passing)
                   1538:                auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1.202     dugsong  1539: #endif
                   1540: #ifdef AFS
1.64      markus   1541:        if (options.afs_token_passing)
                   1542:                auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1.1       deraadt  1543: #endif
1.196     markus   1544:        if (options.challenge_response_authentication == 1)
1.64      markus   1545:                auth_mask |= 1 << SSH_AUTH_TIS;
                   1546:        if (options.password_authentication)
                   1547:                auth_mask |= 1 << SSH_AUTH_PASSWORD;
                   1548:        packet_put_int(auth_mask);
                   1549:
                   1550:        /* Send the packet and wait for it to be sent. */
                   1551:        packet_send();
                   1552:        packet_write_wait();
                   1553:
1.134     markus   1554:        debug("Sent %d bit server key and %d bit host key.",
                   1555:            BN_num_bits(sensitive_data.server_key->rsa->n),
                   1556:            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1.64      markus   1557:
                   1558:        /* Read clients reply (cipher type and session key). */
1.222     markus   1559:        packet_read_expect(SSH_CMSG_SESSION_KEY);
1.64      markus   1560:
1.69      markus   1561:        /* Get cipher type and check whether we accept this. */
1.64      markus   1562:        cipher_type = packet_get_char();
1.69      markus   1563:
1.131     markus   1564:        if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1.69      markus   1565:                packet_disconnect("Warning: client selects unsupported cipher.");
1.64      markus   1566:
                   1567:        /* Get check bytes from the packet.  These must match those we
                   1568:           sent earlier with the public key packet. */
                   1569:        for (i = 0; i < 8; i++)
1.77      markus   1570:                if (cookie[i] != packet_get_char())
1.64      markus   1571:                        packet_disconnect("IP Spoofing check bytes do not match.");
                   1572:
                   1573:        debug("Encryption type: %.200s", cipher_name(cipher_type));
                   1574:
                   1575:        /* Get the encrypted integer. */
1.218     markus   1576:        if ((session_key_int = BN_new()) == NULL)
                   1577:                fatal("do_ssh1_kex: BN_new failed");
1.221     markus   1578:        packet_get_bignum(session_key_int);
1.64      markus   1579:
                   1580:        protocol_flags = packet_get_int();
                   1581:        packet_set_protocol_flags(protocol_flags);
1.220     markus   1582:        packet_check_eom();
1.64      markus   1583:
1.229     markus   1584:        /* Decrypt session_key_int using host/server keys */
1.231     provos   1585:        rsafail = PRIVSEP(ssh1_session_key(session_key_int));
                   1586:
1.66      markus   1587:        /*
                   1588:         * Extract session key from the decrypted integer.  The key is in the
                   1589:         * least significant 256 bits of the integer; the first byte of the
                   1590:         * key is in the highest bits.
                   1591:         */
1.159     markus   1592:        if (!rsafail) {
                   1593:                BN_mask_bits(session_key_int, sizeof(session_key) * 8);
                   1594:                len = BN_num_bytes(session_key_int);
                   1595:                if (len < 0 || len > sizeof(session_key)) {
                   1596:                        error("do_connection: bad session key len from %s: "
1.165     itojun   1597:                            "session_key_int %d > sizeof(session_key) %lu",
                   1598:                            get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1.159     markus   1599:                        rsafail++;
                   1600:                } else {
                   1601:                        memset(session_key, 0, sizeof(session_key));
                   1602:                        BN_bn2bin(session_key_int,
                   1603:                            session_key + sizeof(session_key) - len);
1.169     markus   1604:
                   1605:                        compute_session_id(session_id, cookie,
                   1606:                            sensitive_data.ssh1_host_key->rsa->n,
                   1607:                            sensitive_data.server_key->rsa->n);
                   1608:                        /*
                   1609:                         * Xor the first 16 bytes of the session key with the
                   1610:                         * session id.
                   1611:                         */
                   1612:                        for (i = 0; i < 16; i++)
                   1613:                                session_key[i] ^= session_id[i];
1.159     markus   1614:                }
                   1615:        }
                   1616:        if (rsafail) {
1.169     markus   1617:                int bytes = BN_num_bytes(session_key_int);
1.227     stevesk  1618:                u_char *buf = xmalloc(bytes);
1.169     markus   1619:                MD5_CTX md;
                   1620:
1.159     markus   1621:                log("do_connection: generating a fake encryption key");
1.169     markus   1622:                BN_bn2bin(session_key_int, buf);
                   1623:                MD5_Init(&md);
                   1624:                MD5_Update(&md, buf, bytes);
                   1625:                MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
                   1626:                MD5_Final(session_key, &md);
                   1627:                MD5_Init(&md);
                   1628:                MD5_Update(&md, session_key, 16);
                   1629:                MD5_Update(&md, buf, bytes);
                   1630:                MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
                   1631:                MD5_Final(session_key + 16, &md);
                   1632:                memset(buf, 0, bytes);
                   1633:                xfree(buf);
1.170     markus   1634:                for (i = 0; i < 16; i++)
                   1635:                        session_id[i] = session_key[i] ^ session_key[i + 16];
1.159     markus   1636:        }
1.231     provos   1637:        /* Destroy the private and public keys. No longer. */
1.169     markus   1638:        destroy_sensitive_data();
                   1639:
1.231     provos   1640:        if (use_privsep)
                   1641:                mm_ssh1_session_id(session_id);
                   1642:
1.77      markus   1643:        /* Destroy the decrypted integer.  It is no longer needed. */
                   1644:        BN_clear_free(session_key_int);
1.64      markus   1645:
                   1646:        /* Set the session key.  From this on all communications will be encrypted. */
                   1647:        packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
                   1648:
                   1649:        /* Destroy our copy of the session key.  It is no longer needed. */
                   1650:        memset(session_key, 0, sizeof(session_key));
                   1651:
                   1652:        debug("Received session key; encryption turned on.");
                   1653:
                   1654:        /* Send an acknowledgement packet.  Note that this packet is sent encrypted. */
                   1655:        packet_start(SSH_SMSG_SUCCESS);
                   1656:        packet_send();
                   1657:        packet_write_wait();
1.98      markus   1658: }
                   1659:
                   1660: /*
                   1661:  * SSH2 key exchange: diffie-hellman-group1-sha1
                   1662:  */
1.200     itojun   1663: static void
1.142     markus   1664: do_ssh2_kex(void)
1.98      markus   1665: {
                   1666:        Kex *kex;
1.102     markus   1667:
                   1668:        if (options.ciphers != NULL) {
1.105     markus   1669:                myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1.102     markus   1670:                myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1.166     markus   1671:        }
1.184     stevesk  1672:        myproposal[PROPOSAL_ENC_ALGS_CTOS] =
                   1673:            compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
                   1674:        myproposal[PROPOSAL_ENC_ALGS_STOC] =
                   1675:            compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
                   1676:
1.166     markus   1677:        if (options.macs != NULL) {
                   1678:                myproposal[PROPOSAL_MAC_ALGS_CTOS] =
                   1679:                myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1.102     markus   1680:        }
1.134     markus   1681:        myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
                   1682:
1.189     markus   1683:        /* start key exchange */
1.188     markus   1684:        kex = kex_setup(myproposal);
1.186     markus   1685:        kex->server = 1;
                   1686:        kex->client_version_string=client_version_string;
                   1687:        kex->server_version_string=server_version_string;
                   1688:        kex->load_host_key=&get_hostkey_by_type;
1.231     provos   1689:        kex->host_key_index=&get_hostkey_index;
1.129     provos   1690:
1.189     markus   1691:        xxx_kex = kex;
                   1692:
1.190     markus   1693:        dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1.187     markus   1694:
                   1695:        session_id2 = kex->session_id;
                   1696:        session_id2_len = kex->session_id_len;
1.129     provos   1697:
                   1698: #ifdef DEBUG_KEXDH
                   1699:        /* send 1st encrypted/maced/compressed message */
                   1700:        packet_start(SSH2_MSG_IGNORE);
                   1701:        packet_put_cstring("markus");
                   1702:        packet_send();
                   1703:        packet_write_wait();
                   1704: #endif
1.186     markus   1705:        debug("KEX done");
1.1       deraadt  1706: }