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

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