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

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